Skip to content

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

Go

MUL-7695: fix(desktop): stop daemon before Windows update install (#9582)

Multica Eve984d9db74b57
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.ts
index 4b645baf59..ac70e044d9 100644
--- a/apps/desktop/src/main/daemon-manager.ts
+++ b/apps/desktop/src/main/daemon-manager.ts
@@ -24,6 +24,10 @@ import type {
import { daemonStatusAlive } from "../shared/daemon-types";
import { ensureManagedCli, managedCliPath } from "./cli-bootstrap";
import { decideVersionAction } from "./version-decision";
+import {
+ prepareDaemonForInstall,
+ type DaemonInstallPrep,
+} from "./update-install-gate";
import {
deriveProfileName,
profileArgs,
@@ -99,6 +103,9 @@ let activeProfile: ActiveProfile | null = null;
// Recovery is intentionally process-local: it keeps a daemon alive while the
// Desktop main process is running, but is not an OS service/watchdog.
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." };
// 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;
@@ -311,6 +318,7 @@ function invalidateActiveProfile(): void {
}
function setDesiredDaemonRunning(desired: boolean, explicit = false): void {
+ if (desired && desiredRunningBeforeUpdateStop !== null) return;
if (desiredDaemonRunning === desired && !explicit) return;
desiredDaemonRunning = desired;
recoveryPolicy.reset();
@@ -620,6 +628,10 @@ async function ensureRunningDaemonVersionMatches(): Promise<
}
const bundled = await getCliBinaryVersion();
+ if (desiredRunningBeforeUpdateStop !== null) {
+ pendingVersionRestart = true;
+ return "deferred";
+ }
const action = decideVersionAction(bundled, running);
switch (action) {
@@ -951,6 +963,7 @@ function scheduleStatusRefresh(): void {
async function startDaemon(
recoveryProfile?: ActiveProfile,
): Promise<{ success: boolean; error?: string }> {
+ if (desiredRunningBeforeUpdateStop !== null) return UPDATE_IN_PROGRESS;
const bin = await resolveCliBinary();
if (!bin) return { success: false, error: "multica CLI is not installed" };
@@ -993,6 +1006,7 @@ async function startDaemon(
return { success: false, error: "Daemon recovery was superseded" };
}
+ if (desiredRunningBeforeUpdateStop !== null) return UPDATE_IN_PROGRESS;
if (recoveryProfile) recoveryPolicy.recordRecoveryAttempt(Date.now());
currentState = "starting";
// Begin a fresh auth-probe window for this attempt.
@@ -1042,7 +1056,10 @@ async function lifecycleBlockedByForeignDaemon(): Promise<boolean> {
);
}
-async function stopDaemon(): Promise<{ success: boolean; error?: string }> {
+async function stopDaemon(
+ signal?: AbortSignal,
+): Promise<{ success: boolean; error?: string }> {
+ 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
// native CLI — it would act on the host process namespace and no-op, while
@@ -1057,6 +1074,8 @@ async function stopDaemon(): Promise<{ success: boolean; error?: string }> {
const active = await ensureActiveProfile();
if (!active) return { success: true };
+ // A queued update stop can expire while resolving the CLI/profile/preflight.
+ if (signal?.aborted) return { success: true };
currentState = "stopping";
// An explicit stop is a clean reset — drop any pending auth-failure verdict.
authExpired = false;
@@ -1079,6 +1098,7 @@ async function stopDaemon(): Promise<{ success: boolean; error?: string }> {
}
async function restartDaemon(): Promise<{ success: boolean; error?: string }> {
+ if (desiredRunningBeforeUpdateStop !== null) return UPDATE_IN_PROGRESS;
// 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).
@@ -1225,7 +1245,7 @@ async function pollOnce(): Promise<void> {
}
function startPolling(): void {
- if (statusPollTimer) return;
+ if (statusPollTimer || desiredRunningBeforeUpdateStop !== null) return;
void pollOnce();
statusPollTimer = setInterval(() => void pollOnce(), POLL_INTERVAL_MS);
}
@@ -1351,6 +1371,41 @@ function stopLogTail(): void {
}
}
+export function prepareDaemonForUpdateInstall(options: {
+ interruptActiveTasks: boolean;
+}): Promise<DaemonInstallPrep> {
+ desiredRunningBeforeUpdateStop ??= desiredDaemonRunning;
+ setDesiredDaemonRunning(false);
+ stopPolling();
+ return prepareDaemonForInstall({
+ probe: async () => {
+ const active = await ensureActiveProfile();
+ if (!active) return null;
+ const health = await fetchProfileHealth(active);
+ return {
+ alive: daemonStatusAlive(health?.status),
+ pid: health?.pid,
+ activeTasks: health?.active_task_count ?? 0,
+ externallyManaged: isDaemonExternallyManaged(health?.os, normalizeHostOS(process.platform)),
+ };
+ },
+ stop: async (signal) => {
+ const result = await lifecycleOperations.runForeground(() => stopDaemon(signal));
+ if (!result.success) throw new Error(result.error ?? "daemon stop failed");
+ },
+ processExists: daemonProcessExists,
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
+ }, options);
+}
+
+export function resumeDaemonAfterAbortedUpdateInstall(): void {
+ if (desiredRunningBeforeUpdateStop === null) return;
+ const desired = desiredRunningBeforeUpdateStop;
+ desiredRunningBeforeUpdateStop = null;
+ setDesiredDaemonRunning(desired, true);
+ startPolling();
+}
+
export function setupDaemonManager(
windowGetter: () => BrowserWindow | null,
): void {
@@ -1367,15 +1422,21 @@ export function setupDaemonManager(
}
});
ipcMain.handle("daemon:start", () => {
+ if (desiredRunningBeforeUpdateStop !== null) return UPDATE_IN_PROGRESS;
externalDaemonObserved = false;
setDesiredDaemonRunning(true, true);
return lifecycleOperations.runForeground(() => startDaemon());
});
ipcMain.handle("daemon:stop", () => {
+ if (desiredRunningBeforeUpdateStop !== null) {
+ desiredRunningBeforeUpdateStop = false;
+ return { success: true };
+ }
setDesiredDaemonRunning(false, true);
return lifecycleOperations.runForeground(() => stopDaemon());
});
ipcMain.handle("daemon:restart", () => {
+ if (desiredRunningBeforeUpdateStop !== null) return UPDATE_IN_PROGRESS;
externalDaemonObserved = false;
setDesiredDaemonRunning(true, true);
return lifecycleOperations.runForeground(() => restartDaemon());
@@ -1485,11 +1546,17 @@ export function setupDaemonManager(
let isQuitting = false;
app.on("before-quit", (event) => {
- if (isQuitting) return;
+ // 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;
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 4e4d535588..c549608dda 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -4,8 +4,12 @@ import { join } from "path";
import { pathToFileURL } from "url";
import { electronApp, optimizer, is } from "@electron-toolkit/utils";
import fixPath from "fix-path";
-import { setupAutoUpdater } from "./updater";
-import { setupDaemonManager } from "./daemon-manager";
+import { createElectronBusyInstallPrompt, setupAutoUpdater } from "./updater";
+import {
+ prepareDaemonForUpdateInstall,
+ resumeDaemonAfterAbortedUpdateInstall,
+ setupDaemonManager,
+} from "./daemon-manager";
import { setupLocalDirectory } from "./local-directory";
import { configureLinuxFileDialogs } from "./linux-file-dialog";
import { openExternalSafely, downloadURLSafely } from "./external-url";
@@ -842,7 +846,20 @@ if (!gotTheLock) {
desktopInitialized = true;
createWindow();
- setupAutoUpdater(() => mainWindow);
+ // Register first so the update quit gate can block daemon autoStop.
+ setupAutoUpdater(() => mainWindow, {
+ // Windows only (the updater ignores it elsewhere): stop the bundled
+ // daemon before the installer runs so multica.exe is replaced. #8823
+ daemonGate: {
+ prepare: prepareDaemonForUpdateInstall,
+ resumeAfterAbortedInstall: resumeDaemonAfterAbortedUpdateInstall,
+ confirmInstallWhileBusy: createElectronBusyInstallPrompt((options) =>
+ mainWindow && !mainWindow.isDestroyed()
+ ? dialog.showMessageBox(mainWindow, options)
+ : dialog.showMessageBox(options),
+ ),
+ },
+ });
setupDaemonManager(() => mainWindow);
setupLocalDirectory(() => mainWindow);
diff --git a/apps/desktop/src/main/update-install-gate.test.ts b/apps/desktop/src/main/update-install-gate.test.ts
new file mode 100644
index 0000000000..46f84140c8
--- /dev/null
+++ b/apps/desktop/src/main/update-install-gate.test.ts
@@ -0,0 +1,74 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { prepareDaemonForInstall, type DaemonInstallGateDeps } from "./update-install-gate";
+
+const running = { alive: true, pid: 4242, activeTasks: 0, externallyManaged: false };
+function makeDeps(): DaemonInstallGateDeps {
+ return {
+ probe: vi.fn().mockResolvedValue(running),
+ stop: vi.fn(async () => {}),
+ processExists: vi.fn(() => true),
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
+ };
+}
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
+
+describe("prepareDaemonForInstall", () => {
+ it.each([null, { ...running, alive: false }, { ...running, externallyManaged: true }])(
+ "leaves absent, stopped and external daemons alone (%j)", async (probe) => {
+ const deps = makeDeps();
+ vi.mocked(deps.probe).mockResolvedValue(probe);
+ await expect(prepareDaemonForInstall(deps, { interruptActiveTasks: false })).resolves.toEqual({ kind: "ready" });
+ expect(deps.stop).not.toHaveBeenCalled();
+ },
+ );
+
+ it("requires permission before stopping active tasks", async () => {
+ const deps = makeDeps();
+ vi.mocked(deps.probe).mockResolvedValue({ ...running, activeTasks: 2 });
+ await expect(prepareDaemonForInstall(deps, { interruptActiveTasks: false })).resolves.toEqual({ kind: "busy", activeTasks: 2 });
+ expect(deps.stop).not.toHaveBeenCalled();
+ vi.mocked(deps.probe).mockResolvedValueOnce({ ...running, activeTasks: 2 }).mockResolvedValue(null);
+ vi.mocked(deps.processExists).mockReturnValue(false);
+ await expect(prepareDaemonForInstall(deps, { interruptActiveTasks: true })).resolves.toEqual({ kind: "ready" });
+ expect(deps.stop).toHaveBeenCalledTimes(1);
+ });
+
+ it("waits for both health and the original PID after a graceful stop", async () => {
+ const deps = makeDeps();
+ vi.mocked(deps.probe).mockResolvedValueOnce(running).mockResolvedValue(null);
+ const completed = vi.fn();
+ const prep = prepareDaemonForInstall(deps, { interruptActiveTasks: false }).then(completed);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(completed).not.toHaveBeenCalled();
+ expect(deps.processExists).toHaveBeenCalledWith(4242);
+ vi.mocked(deps.processExists).mockReturnValue(false);
+ await vi.advanceTimersByTimeAsync(250);
+ await prep;
+ expect(completed).toHaveBeenCalledWith({ kind: "ready" });
+ });
+
+ it.each(["probe", "stop", "exit"])("bounds a stalled %s to 15 seconds", async (stage) => {
+ const deps = makeDeps();
+ if (stage === "probe") vi.mocked(deps.probe).mockImplementation(() => new Promise(() => {}));
+ if (stage === "stop") vi.mocked(deps.stop).mockImplementation(() => new Promise(() => {}));
+ const completed = vi.fn();
+ const prep = prepareDaemonForInstall(deps, { interruptActiveTasks: false }).then(completed);
+ await vi.advanceTimersByTimeAsync(14_999);
+ expect(completed).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ await prep;
+ expect(completed).toHaveBeenCalledWith({ kind: "timeout" });
+ const stopSignal = vi.mocked(deps.stop).mock.calls[0]?.[0];
+ if (stopSignal) expect(stopSignal.aborted).toBe(true);
+ });
+
+ it("still checks exit after the stop command fails", async () => {
+ const deps = makeDeps();
+ vi.mocked(deps.probe).mockResolvedValueOnce(running).mockResolvedValue(null);
+ vi.mocked(deps.stop).mockRejectedValue(new Error("stop failed"));
+ vi.mocked(deps.processExists).mockReturnValue(false);
+ await expect(prepareDaemonForInstall(deps, { interruptActiveTasks: false })).resolves.toEqual({ kind: "ready" });
+ });
+});
diff --git a/apps/desktop/src/main/update-install-gate.ts b/apps/desktop/src/main/update-install-gate.ts
new file mode 100644
index 0000000000..76ae669cda
--- /dev/null
+++ b/apps/desktop/src/main/update-install-gate.ts
@@ -0,0 +1,69 @@
+export type DaemonInstallPrep =
+ | { kind: "ready" }
+ | { kind: "busy"; activeTasks: number }
+ | { kind: "timeout" };
+
+export interface DaemonInstallProbe {
+ alive: boolean;
+ pid?: number;
+ activeTasks: number;
+ externallyManaged: boolean;
+}
+
+export interface DaemonInstallGateDeps {
+ probe: () => Promise<DaemonInstallProbe | null>;
+ // Check this signal before issuing a stop that was queued behind other work.
+ stop: (signal: AbortSignal) => Promise<void>;
+ processExists: (pid: number) => boolean;
+ sleep: (ms: number) => Promise<void>;
+}
+
+export interface DaemonInstallGateOptions {
+ interruptActiveTasks: boolean;
+ timeoutMs?: number;
+}
+
+// Bound the whole preparation, including health probes and lifecycle queuing.
+export async function prepareDaemonForInstall(
+ deps: DaemonInstallGateDeps,
+ options: DaemonInstallGateOptions,
+): Promise<DaemonInstallPrep> {
+ const controller = new AbortController();
+ const { signal } = controller;
+ const prepare = async (): Promise<DaemonInstallPrep> => {
+ const initial = await deps.probe();
+ if (signal.aborted) return { kind: "timeout" };
+ if (!initial?.alive || initial.externallyManaged) return { kind: "ready" };
+ if (!options.interruptActiveTasks && initial.activeTasks > 0) {
+ return { kind: "busy", activeTasks: initial.activeTasks };
+ }
+ try {
+ await deps.stop(signal);
+ } catch (err) {
+ console.warn("[updater] daemon stop failed:", err);
+ }
+ while (!signal.aborted) {
+ const current = await deps.probe();
+ if (signal.aborted) break;
+ // The CLI can report success and close /health while the process still
+ // drains. Windows releases the executable lock only when that PID exits.
+ if (!current?.alive && (initial.pid === undefined || !deps.processExists(initial.pid))) {
+ return { kind: "ready" };
+ }
+ await deps.sleep(250);
+ }
+ return { kind: "timeout" };
+ };
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ prepare(),
+ new Promise<DaemonInstallPrep>((resolve) => {
+ timer = setTimeout(() => resolve({ kind: "timeout" }), options.timeoutMs ?? 15_000);
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ controller.abort();
+ }
+}
diff --git a/apps/desktop/src/main/update-install-lifecycle.test.ts b/apps/desktop/src/main/update-install-lifecycle.test.ts
new file mode 100644
index 0000000000..280d3a964d
--- /dev/null
+++ b/apps/desktop/src/main/update-install-lifecycle.test.ts
@@ -0,0 +1,248 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+type Health = {
+ status: string;
+ pid: number;
+ active_task_count: number;
+ cli_version: string;
+};
+type Handler = (...args: unknown[]) => void;
+type IpcHandler = (...args: unknown[]) => unknown;
+
+const ctx = vi.hoisted(() => ({
+ listeners: new Map<string, Handler[]>(),
+ updaterListeners: new Map<string, Handler[]>(),
+ ipc: new Map<string, IpcHandler>(),
+ health: null as Health | null,
+ processAlive: true,
+ autoStop: false,
+ quits: 0,
+ stops: 0,
+ starts: 0,
+ holdStart: false,
+ finishStart: null as null | (() => void),
+ quit: vi.fn(),
+ install: vi.fn(),
+}));
+
+vi.mock("electron", () => ({
+ app: {
+ on: (name: string, listener: Handler) => {
+ ctx.listeners.set(name, [...(ctx.listeners.get(name) ?? []), listener]);
+ },
+ quit: ctx.quit,
+ getPath: () => "/review-only/user-data",
+ getAppPath: () => "/review-only/app",
+ getVersion: () => "0.7.0",
+ },
+ BrowserWindow: class {},
+ ipcMain: {
+ handle: (name: string, fn: IpcHandler) => ctx.ipc.set(name, fn),
+ on: vi.fn(),
+ },
+ shell: { openPath: vi.fn() },
+}));
+
+vi.mock("electron-updater", () => ({
+ autoUpdater: {
+ autoInstallOnAppQuit: true,
+ quitAndInstall: ctx.install,
+ checkForUpdates: vi.fn(async () => null),
+ downloadUpdate: vi.fn(),
+ on: (name: string, fn: Handler) => {
+ ctx.updaterListeners.set(name, [...(ctx.updaterListeners.get(name) ?? []), fn]);
+ },
+ },
+}));
+
+vi.mock("./updater-preferences", () => ({
+ DEFAULT_UPDATER_PREFERENCES: { automaticUpdates: false },
+ updaterPreferencesPath: () => "/review-only/updater-preferences.json",
+ loadUpdaterPreferences: async () => ({ automaticUpdates: false }),
+ saveUpdaterPreferences: vi.fn(),
+}));
+
+vi.mock("./cli-bootstrap", () => ({
+ managedCliPath: () => "/review-only/managed-cli",
+ ensureManagedCli: vi.fn(async () => "/review-only/managed-cli"),
+}));
+
+vi.mock("fs", () => ({
+ existsSync: () => true,
+ watchFile: vi.fn(),
+ unwatchFile: vi.fn(),
+}));
+vi.mock("fs/promises", () => ({
+ readFile: vi.fn(async (path: string) => {
+ if (path.endsWith("desktop_prefs.json")) {
+ return JSON.stringify({ autoStart: true, autoStop: ctx.autoStop });
+ }
+ if (path.endsWith("daemon.pid")) return "4242";
+ return JSON.stringify({ server_url: "https://review.invalid" });
+ }),
+ writeFile: vi.fn(),
+ mkdir: vi.fn(),
+ rm: vi.fn(),
+ open: vi.fn(),
+ stat: vi.fn(),
+}));
+vi.mock("./daemon-port", () => ({
+ probeProfileHealth: vi.fn(async () => ctx.health),
+}));
+vi.mock("child_process", () => ({
+ execFile: vi.fn((_file: string, args: string[], _opts: unknown, cb: (err: Error | null, stdout: string) => void) => {
+ if (args[0] === "version") cb(null, '{"version":"0.7.0"}');
+ else if (args[0] === "daemon" && args[1] === "stop") {
+ ctx.stops++;
+ ctx.health = null;
+ // CLI success and /health disappearing do not prove that PID 4242 exited.
+ cb(null, "");
+ } else if (args[0] === "daemon" && args[1] === "start") {
+ ctx.starts++;
+ ctx.health = { status: "starting", pid: 4343, active_task_count: 0, cli_version: "0.7.0" };
+ if (ctx.holdStart) ctx.finishStart = () => cb(null, "");
+ else cb(null, "");
+ } else cb(null, "");
+ }),
+}));
+
+function emitQuit() {
+ const event = {
+ defaultPrevented: false,
+ preventDefault() { this.defaultPrevented = true; },
+ };
+ for (const listener of ctx.listeners.get("before-quit") ?? []) listener(event);
+ if (!event.defaultPrevented) {
+ ctx.quits++;
+ for (const listener of ctx.listeners.get("will-quit") ?? []) listener(event);
+ }
+ return event;
+}
+
+function downloaded() {
+ for (const fn of ctx.updaterListeners.get("update-downloaded") ?? []) fn({ version: "0.7.1" });
+}
+
+async function ipc(name: string) {
+ return ctx.ipc.get(name)!({});
+}
+
+async function setupRealGate() {
+ const manager = await import("./daemon-manager");
+ const { setupAutoUpdater } = await import("./updater");
+ setupAutoUpdater(() => null, {
+ platform: "win32",
+ daemonGate: {
+ prepare: manager.prepareDaemonForUpdateInstall,
+ resumeAfterAbortedInstall: manager.resumeDaemonAfterAbortedUpdateInstall,
+ confirmInstallWhileBusy: async () => false,
+ },
+ });
+ manager.setupDaemonManager(() => null);
+ await ctx.ipc.get("daemon:set-target-api-url")!({}, "https://review.invalid");
+ await ipc("daemon:auto-start");
+ await vi.advanceTimersByTimeAsync(0);
+ return manager;
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ ctx.listeners.clear();
+ ctx.updaterListeners.clear();
+ ctx.ipc.clear();
+ ctx.autoStop = false;
+ ctx.quits = 0;
+ ctx.stops = 0;
+ ctx.starts = 0;
+ ctx.processAlive = true;
+ ctx.holdStart = false;
+ ctx.finishStart = null;
+ ctx.health = { status: "running", pid: 4242, active_task_count: 0, cli_version: "0.7.0" };
+ ctx.quit.mockReset().mockImplementation(emitQuit);
+ ctx.install.mockReset();
+ // Never probe or signal a real process.
+ vi.spyOn(process, "kill").mockImplementation(() => {
+ if (ctx.processAlive) return true;
+ throw Object.assign(new Error("No such process"), { code: "ESRCH" });
+ });
+});
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe("Windows update and daemon lifecycle coordination", () => {
+ it("blocks repeated quits and legacy autoStop until the original PID exits", async () => {
+ ctx.autoStop = true;
+ await setupRealGate();
+ downloaded();
+ expect(emitQuit().defaultPrevented).toBe(true);
+ expect(emitQuit().defaultPrevented).toBe(true);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(ctx.stops).toBe(1);
+ expect(ctx.quits).toBe(0);
+ ctx.processAlive = false;
+ await vi.advanceTimersByTimeAsync(250);
+ expect(ctx.quits).toBe(1);
+ expect(ctx.stops).toBe(1);
+ });
+
+ it("shares an ongoing stop across update clicks and quit, and blocks daemon starts", async () => {
+ await setupRealGate();
+ downloaded();
+ ctx.install.mockImplementation(emitQuit);
+ const first = ipc("updater:install");
+ await vi.advanceTimersByTimeAsync(1_000);
+ const second = ipc("updater:install");
+ expect(emitQuit().defaultPrevented).toBe(true);
+ await expect(ipc("daemon:start")).resolves.toMatchObject({ success: false });
+ await expect(ipc("daemon:restart")).resolves.toMatchObject({ success: false });
+ await ipc("daemon:stop");
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(ctx.starts).toBe(0);
+ expect(ctx.stops).toBe(1);
+ expect(ctx.install).not.toHaveBeenCalled();
+ expect(ctx.quits).toBe(0);
+ ctx.processAlive = false;
+ await vi.advanceTimersByTimeAsync(250);
+ await Promise.all([first, second]);
+ expect(ctx.stops).toBe(1);
+ expect(ctx.install).toHaveBeenCalledTimes(1);
+ expect(ctx.quits).toBe(1);
+ });
+
+ it("restores daemon control if installation never quits the app", async () => {
+ await setupRealGate();
+ const install = ipc("updater:install");
+ await vi.advanceTimersByTimeAsync(0);
+ ctx.processAlive = false;
+ await vi.advanceTimersByTimeAsync(250);
+ await install;
+ await expect(ipc("daemon:start")).resolves.toMatchObject({ success: false });
+ await vi.advanceTimersByTimeAsync(10_000);
+ await expect(ipc("daemon:start")).resolves.toMatchObject({ success: true });
+ expect(ctx.starts).toBe(1);
+ });
+
+ it("invalidates a timed-out stop queued behind an earlier start", async () => {
+ await setupRealGate();
+ ctx.holdStart = true;
+ const restart = ipc("daemon:restart");
+ await vi.advanceTimersByTimeAsync(0);
+ const stopsBeforeInstall = ctx.stops;
+ const install = ipc("updater:install");
+ await vi.advanceTimersByTimeAsync(15_000);
+ await install;
+ expect(ctx.install).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(10_000);
+ ctx.health!.status = "running";
+ ctx.health!.active_task_count = 1;
+ ctx.finishStart!();
+ await restart;
+ await vi.advanceTimersByTimeAsync(0);
+ expect(ctx.stops).toBe(stopsBeforeInstall);
+ });
+});
diff --git a/apps/desktop/src/main/updater.test.ts b/apps/desktop/src/main/updater.test.ts
index 6d6b29e2df..4297d17538 100644
--- a/apps/desktop/src/main/updater.test.ts
+++ b/apps/desktop/src/main/updater.test.ts
@@ -19,6 +19,8 @@ const ctx = vi.hoisted(() => ({
downloadUpdate: vi.fn(),
quitAndInstall: vi.fn(),
getVersion: vi.fn(() => "0.3.17"),
+ appHandlers: new Map<string, Handler[]>(),
+ appQuit: vi.fn(),
userDataPath: "",
}));
@@ -45,6 +47,12 @@ vi.mock("electron", () => ({
app: {
getVersion: ctx.getVersion,
getPath: vi.fn(() => ctx.userDataPath),
+ on: vi.fn((event: string, handler: Handler) => {
+ const handlers = ctx.appHandlers.get(event) ?? [];
+ handlers.push(handler);
+ ctx.appHandlers.set(event, handlers);
+ }),
+ quit: ctx.appQuit,
},
BrowserWindow: class BrowserWindow {},
ipcMain: {
@@ -52,9 +60,12 @@ vi.mock("electron", () => ({
},
}));
+import { autoUpdater } from "electron-updater";
import {
configureMacX64UpdateChannel,
+ createElectronBusyInstallPrompt,
setupAutoUpdater,
+ type UpdaterDaemonGate,
} from "./updater";
import { updaterPreferencesPath } from "./updater-preferences";
@@ -280,3 +291,136 @@ describe("setupAutoUpdater", () => {
);
});
});
+
+describe("Windows update installation", () => {
+ function makeGate() {
+ return {
+ prepare: vi.fn<UpdaterDaemonGate["prepare"]>().mockResolvedValue({ kind: "ready" }),
+ resumeAfterAbortedInstall: vi.fn(),
+ confirmInstallWhileBusy: vi.fn(async () => false),
+ } satisfies UpdaterDaemonGate;
+ }
+
+ function emitApp(eventName: string) {
+ const event = { preventDefault: vi.fn() };
+ for (const handler of ctx.appHandlers.get(eventName) ?? []) handler(event);
+ return event;
+ }
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ ctx.userDataPath = mkdtempSync(join(tmpdir(), "multica-updater-gate-"));
+ ctx.handlers.clear();
+ ctx.ipcHandlers.clear();
+ ctx.appHandlers.clear();
+ ctx.appQuit.mockClear();
+ ctx.quitAndInstall.mockClear();
+ ctx.ipcHandle.mockImplementation((channel: string, handler: IpcHandler) => {
+ ctx.ipcHandlers.set(channel, handler);
+ });
+ autoUpdater.autoInstallOnAppQuit = true;
+ });
+
+ afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ rmSync(ctx.userDataPath, { recursive: true, force: true });
+ });
+
+ it("keeps macOS and Linux on the existing install path", async () => {
+ for (const platform of ["darwin", "linux"] as const) {
+ const gate = makeGate();
+ setupAutoUpdater(() => null, { daemonGate: gate, platform });
+ await invokeIpc("updater:install");
+ expect(gate.prepare).not.toHaveBeenCalled();
+ }
+ expect(ctx.quitAndInstall).toHaveBeenCalledTimes(2);
+ expect(ctx.appHandlers.get("before-quit")).toBeUndefined();
+ });
+
+ it.each(["ready", "timeout", "error"])("installs after preparation returns %s", async (result) => {
+ const gate = makeGate();
+ if (result === "error") gate.prepare.mockRejectedValue(new Error("probe failed"));
+ else gate.prepare.mockResolvedValue({ kind: result as "ready" | "timeout" });
+ setupAutoUpdater(() => null, { daemonGate: gate, platform: "win32" });
+ await invokeIpc("updater:install");
+ expect(ctx.quitAndInstall).toHaveBeenCalledExactlyOnceWith(false, true);
+ });
+
+ it.each([false, true])("asks before interrupting busy tasks (confirmed=%s)", async (confirmed) => {
+ const gate = makeGate();
+ gate.prepare.mockResolvedValueOnce({ kind: "busy", activeTasks: 2 });
+ gate.confirmInstallWhileBusy.mockResolvedValue(confirmed);
+ setupAutoUpdater(() => null, { daemonGate: gate, platform: "win32" });
+ await invokeIpc("updater:install");
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(gate.confirmInstallWhileBusy).toHaveBeenCalledWith(2);
+ expect(gate.prepare).toHaveBeenCalledTimes(confirmed ? 2 : 1);
+ expect(ctx.quitAndInstall).toHaveBeenCalledTimes(confirmed ? 1 : 0);
+ if (confirmed) {
+ expect(gate.prepare).toHaveBeenLastCalledWith({ interruptActiveTasks: true });
+ } else {
+ expect(gate.resumeAfterAbortedInstall).toHaveBeenCalledTimes(1);
+ }
+ });
+
+ it("lets quit wait for a manual confirmation without opening another preparation", async () => {
+ const gate = makeGate();
+ gate.prepare.mockResolvedValueOnce({ kind: "busy", activeTasks: 1 });
+ let confirm!: (choice: boolean) => void;
+ gate.confirmInstallWhileBusy.mockImplementation(() => new Promise((resolve) => { confirm = resolve; }));
+ setupAutoUpdater(() => null, { daemonGate: gate, platform: "win32" });
+ emitUpdater("update-downloaded", { version: "0.7.1" });
+ const manual = invokeIpc("updater:install");
+ await vi.advanceTimersByTimeAsync(0);
+ expect(emitApp("before-quit").preventDefault).toHaveBeenCalled();
+ confirm(false);
+ await manual;
+ expect(gate.prepare).toHaveBeenCalledTimes(1);
+ expect(autoUpdater.autoInstallOnAppQuit).toBe(false);
+ expect(ctx.appQuit).toHaveBeenCalledTimes(1);
+ expect(ctx.quitAndInstall).not.toHaveBeenCalled();
+ });
+
+ it.each(["ready", "busy", "timeout", "error"] as const)("handles ordinary quit with a %s daemon", async (kind) => {
+ const gate = makeGate();
+ if (kind === "error") gate.prepare.mockRejectedValue(new Error("probe failed"));
+ else gate.prepare.mockResolvedValue(kind === "busy" ? { kind, activeTasks: 1 } : { kind });
+ setupAutoUpdater(() => null, { daemonGate: gate, platform: "win32" });
+ expect(emitApp("before-quit").preventDefault).not.toHaveBeenCalled();
+ emitUpdater("update-downloaded", { version: "0.7.1" });
+ expect(emitApp("before-quit").preventDefault).toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(gate.confirmInstallWhileBusy).not.toHaveBeenCalled();
+ expect(autoUpdater.autoInstallOnAppQuit).toBe(kind !== "busy");
+ expect(ctx.appQuit).toHaveBeenCalledTimes(1);
+ expect(ctx.quitAndInstall).not.toHaveBeenCalled();
+ expect(emitApp("before-quit").preventDefault).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])("recovers a failed install unless the app has reached will-quit (%s)", async (quitting) => {
+ const gate = makeGate();
+ setupAutoUpdater(() => null, { daemonGate: gate, platform: "win32" });
+ await invokeIpc("updater:install");
+ if (quitting) emitApp("will-quit");
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(gate.resumeAfterAbortedInstall).toHaveBeenCalledTimes(quitting ? 0 : 1);
+ if (!quitting) {
+ await invokeIpc("updater:install");
+ expect(ctx.quitAndInstall).toHaveBeenCalledTimes(2);
+ }
+ });
+});
+
+describe("createElectronBusyInstallPrompt", () => {
+ it.each([0, 1, 2])("offers only immediate installation or cancellation (response=%s)", async (response) => {
+ const showMessageBox = vi.fn(async () => ({ response }));
+ await expect(createElectronBusyInstallPrompt(showMessageBox)(2)).resolves.toBe(response === 0);
+ expect(showMessageBox).toHaveBeenCalledWith(expect.objectContaining({
+ buttons: ["Install now", "Cancel"],
+ defaultId: 1,
+ cancelId: 1,
+ message: "2 agent tasks are running on this computer.",
+ }));
+ });
+});
diff --git a/apps/desktop/src/main/updater.ts b/apps/desktop/src/main/updater.ts
index 7097fb39be..407de03387 100644
--- a/apps/desktop/src/main/updater.ts
+++ b/apps/desktop/src/main/updater.ts
@@ -1,5 +1,5 @@
import { autoUpdater, type UpdateDownloadedEvent } from "electron-updater";
-import { app, type BrowserWindow, ipcMain } from "electron";
+import { app, type BrowserWindow, type MessageBoxOptions, ipcMain } from "electron";
import type {
ManualUpdateCheckResult,
UpdaterPreferences,
@@ -10,6 +10,7 @@ import {
saveUpdaterPreferences,
updaterPreferencesPath,
} from "./updater-preferences";
+import type { DaemonInstallPrep } from "./update-install-gate";
// Silent background updates: electron-updater downloads on its own as soon
// as `update-available` fires; we only surface UI when the package is fully
@@ -53,6 +54,44 @@ configureMacX64UpdateChannel(autoUpdater);
const STARTUP_CHECK_DELAY_MS = 5_000;
const PERIODIC_CHECK_INTERVAL_MS = 60 * 60 * 1000; // 1 hour
+// quitAndInstall only quits once the installer has been spawned. If the app is
+// still running this long afterwards, the install bailed and the daemon we
+// stopped for it must be brought back.
+const INSTALL_QUIT_WATCHDOG_MS = 10_000;
+
+// Injected so the updater does not own the daemon manager's state.
+export interface UpdaterDaemonGate {
+ prepare: (options: {
+ interruptActiveTasks: boolean;
+ }) => Promise<DaemonInstallPrep>;
+ resumeAfterAbortedInstall: () => void;
+ confirmInstallWhileBusy: (activeTasks: number) => Promise<boolean>;
+}
+
+export interface SetupAutoUpdaterOptions {
+ daemonGate?: UpdaterDaemonGate;
+ platform?: NodeJS.Platform;
+}
+
+export function createElectronBusyInstallPrompt(
+ showMessageBox: (
+ options: MessageBoxOptions,
+ ) => Promise<{ response: number }>,
+): (activeTasks: number) => Promise<boolean> {
+ return async (activeTasks) => {
+ const tasks = activeTasks === 1 ? "1 agent task is" : `${activeTasks} agent tasks are`;
+ const { response } = await showMessageBox({
+ type: "question",
+ buttons: ["Install now", "Cancel"],
+ defaultId: 1,
+ cancelId: 1,
+ title: "Install update",
+ message: `${tasks} running on this computer.`,
+ detail: "Installing now stops the local runtime and interrupts these tasks.",
+ });
+ return response === 0;
+ };
+}
type RendererChannel =
| "updater:update-available"
@@ -109,7 +148,14 @@ function checkForUpdatesOnce(): Promise<unknown> {
return p;
}
-export function setupAutoUpdater(getMainWindow: () => BrowserWindow | null): void {
+export function setupAutoUpdater(
+ getMainWindow: () => BrowserWindow | null,
+ options: SetupAutoUpdaterOptions = {},
+): void {
+ const platform = options.platform ?? process.platform;
+ // Only Windows locks a running executable against replacement; macOS and
+ // Linux keep their existing update path untouched.
+ const daemonGate = platform === "win32" ? (options.daemonGate ?? null) : null;
const preferencesFilePath = updaterPreferencesPath(app.getPath("userData"));
let automaticUpdatesEnabled =
DEFAULT_UPDATER_PREFERENCES.automaticUpdates;
@@ -169,6 +215,65 @@ export function setupAutoUpdater(getMainWindow: () => BrowserWindow | null): voi
}
};
+ let updateReadyToInstall = false;
+ let installFlow: Promise<void> | null = null;
+ let quitRequested = false;
+ let finishing = false;
+ let appQuitting = false;
+
+ const finish = (install: boolean, manual: boolean): void => {
+ finishing = true;
+ const previousAutoInstall = autoUpdater.autoInstallOnAppQuit;
+ if (!install) autoUpdater.autoInstallOnAppQuit = false;
+ setTimeout(() => {
+ if (appQuitting) return;
+ finishing = false;
+ quitRequested = false;
+ autoUpdater.autoInstallOnAppQuit = previousAutoInstall;
+ daemonGate?.resumeAfterAbortedInstall();
+ }, INSTALL_QUIT_WATCHDOG_MS);
+ if (install && manual) autoUpdater.quitAndInstall(false, true);
+ else app.quit();
+ };
+
+ // All entry points join this promise. Once stopping starts, nobody cancels
+ // or replaces its PID wait, and no other flow can resume the daemon.
+ const installWithDaemonGate = (manual: boolean): Promise<void> => {
+ if (installFlow) return installFlow;
+ if (finishing || !daemonGate) return Promise.resolve();
+ installFlow = (async () => {
+ let install = true;
+ try {
+ const prep = await daemonGate.prepare({ interruptActiveTasks: false });
+ if (prep.kind === "busy") {
+ install = manual && await daemonGate.confirmInstallWhileBusy(prep.activeTasks);
+ if (install) await daemonGate.prepare({ interruptActiveTasks: true });
+ }
+ } catch (err) {
+ // Preserve the existing installer fallback if preparation fails.
+ console.error("[updater] daemon preparation failed; installing anyway:", err);
+ }
+ if (install) finish(true, manual);
+ else {
+ daemonGate.resumeAfterAbortedInstall();
+ if (quitRequested) finish(false, false);
+ }
+ })().finally(() => { installFlow = null; });
+ return installFlow;
+ };
+
+ if (daemonGate) {
+ app.on("will-quit", () => { appQuitting = true; });
+ app.on("before-quit", (event) => {
+ if (finishing || !updateReadyToInstall || !autoUpdater.autoInstallOnAppQuit) return;
+ event.preventDefault();
+ quitRequested = true;
+ void installWithDaemonGate(false).catch((err) => {
+ console.error("[updater] quit-time installation failed:", err);
+ });
+ });
+ }
+
autoUpdater.on("update-available", (info) => {
// Forwarded for renderer-side state tracking only; the notification UI
// does not render an "available" affordance with autoDownload=true.
@@ -185,6 +290,7 @@ export function setupAutoUpdater(getMainWindow: () => BrowserWindow | null): voi
});
autoUpdater.on("update-downloaded", (info: UpdateDownloadedEvent) => {
+ updateReadyToInstall = true;
sendToLiveRenderer(getMainWindow(), "updater:update-downloaded", {
version: info.version,
releaseNotes: info.releaseNotes,
@@ -201,8 +307,12 @@ export function setupAutoUpdater(getMainWindow: () => BrowserWindow | null): voi
return autoUpdater.downloadUpdate();
});
- ipcMain.handle("updater:install", () => {
- autoUpdater.quitAndInstall(false, true);
+ ipcMain.handle("updater:install", async () => {
+ if (!daemonGate) {
+ autoUpdater.quitAndInstall(false, true);
+ return;
+ }
+ await installWithDaemonGate(true);
});
ipcMain.handle(