Skip to content

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

Go

MUL-6874 fix(desktop): recover unexpectedly stopped daemon (#7808)

Multica Evef93855470ff3
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.ts
index edaa3aba9d..365eb55665 100644
--- a/apps/desktop/src/main/daemon-manager.ts
+++ b/apps/desktop/src/main/daemon-manager.ts
@@ -31,8 +31,17 @@ import {
profileConfigPath,
profileDir,
profileLogPath,
+ profilePidPath,
profileUserIdPath,
} from "./daemon-profile";
+import {
+ DaemonOperationGate,
+ DaemonRecoveryPolicy,
+ daemonProcessExists,
+ parseDaemonPid,
+ recoveryStartAllowed,
+ runDaemonRecoveryAttempt,
+} from "./daemon-recovery";
import {
daemonLifecycleUnreachable,
isDaemonExternallyManaged,
@@ -60,6 +69,10 @@ const AUTH_PROBE_GRACE_MS = 10_000;
// healthy-but-slow start is misreported as a failure (the detached daemon child
// keeps running, so the UI flashes "stopped" then "running").
const DAEMON_START_EXEC_TIMEOUT_MS = 60_000;
+const HEALTH_PROBE_TIMEOUT_MS = 2_000;
+// Five times the UI probe and equal to the auth-probe grace: a daemon that
+// misses this second independent window is no longer treated as merely busy.
+const RECOVERY_HEALTH_PROBE_TIMEOUT_MS = 10_000;
const DEFAULT_PREFS: DaemonPrefs = { autoStart: true, autoStop: false };
@@ -74,7 +87,7 @@ let statusPollTimer: ReturnType<typeof setInterval> | null = null;
let logTailWatcher: { path: string; listener: StatsListener } | null = null;
let currentState: DaemonStatus["state"] = "installing_cli";
let getMainWindow: () => BrowserWindow | null = () => null;
-let operationInProgress = false;
+let statusPollInProgress = false;
let cachedCliBinary: string | null | undefined = undefined;
let cliResolvePromise: Promise<string | null> | null = null;
let cachedCliBinaryVersion: string | null | undefined = undefined;
@@ -84,6 +97,14 @@ let cachedCliBinaryVersion: string | null | undefined = undefined;
let pendingVersionRestart = false;
let targetApiBaseUrl: string | null = null;
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;
+// 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;
+const recoveryPolicy = new DaemonRecoveryPolicy();
+const lifecycleOperations = new DaemonOperationGate();
// Auth-probe state for the current start attempt. When a start fails to reach
// "running", we probe the daemon's token once (after AUTH_PROBE_GRACE_MS) to
@@ -164,18 +185,20 @@ interface HealthPayload {
async function fetchHealthAtPort(
port: number,
+ timeoutMs = HEALTH_PROBE_TIMEOUT_MS,
): Promise<HealthPayload | null> {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2_000);
const res = await fetch(`http://127.0.0.1:${port}/health`, {
signal: controller.signal,
});
- clearTimeout(timeout);
if (!res.ok) return null;
return (await res.json()) as HealthPayload;
} catch {
return null;
+ } finally {
+ clearTimeout(timeout);
}
}
@@ -274,6 +297,22 @@ async function ensureActiveProfile(): Promise<ActiveProfile | null> {
function invalidateActiveProfile(): void {
activeProfile = null;
+ externalDaemonObserved = false;
+ recoveryPolicy.reset();
+}
+
+function setDesiredDaemonRunning(desired: boolean, explicit = false): void {
+ if (desiredDaemonRunning === desired && !explicit) return;
+ desiredDaemonRunning = desired;
+ recoveryPolicy.reset();
+}
+
+function observeDaemonBoundary(status: DaemonStatus): void {
+ if (status.state !== "running") return;
+ externalDaemonObserved = status.externallyManaged === true;
+ if (externalDaemonObserved) {
+ recoveryPolicy.reset();
+ }
}
async function fetchHealth(): Promise<DaemonStatus> {
@@ -320,10 +359,18 @@ async function fetchHealth(): Promise<DaemonStatus> {
// daemon booting on its own — or started via the CLI — surfaces as
// "starting" instead of "stopped".
if (data?.status === "starting") {
- return { state: "starting", profile: active.name };
+ return {
+ state: "starting",
+ profile: active.name,
+ };
}
return {
- state: currentState === "starting" ? "starting" : "stopped",
+ state:
+ currentState === "starting"
+ ? "starting"
+ : recoveryPolicy.isPaused
+ ? "recovery_paused"
+ : "stopped",
profile: active.name,
};
}
@@ -641,13 +688,13 @@ async function mintPat(jwt: string): Promise<string> {
* mint a fresh PAT, overwriting any stale cached PAT. This is the critical
* path: without it, a previous user's PAT would be used by a new session.
* - If the caller happens to pass a PAT directly, write it through.
- * - When we mint fresh and a daemon is already running, restart it so the
- * new credentials take effect (the Go daemon reads config at startup).
+ * - Reports a user mismatch to the caller; the IPC boundary owns the gated
+ * restart so internal callers such as reauthenticate never re-enter it.
*/
async function syncToken(
tokenFromRenderer: string,
userId: string,
-): Promise<void> {
+): Promise<{ active: ActiveProfile; userChanged: boolean }> {
const active = await ensureActiveProfile();
if (!active) {
// Writing here would land the token and server_url in the user's default
@@ -686,22 +733,31 @@ async function syncToken(
await writeProfileConfig(active.name, config);
await writeProfileUserId(active.name, userId);
+ return { active, userChanged };
+}
+
+async function restartDaemonAfterUserSwitch(
+ active: ActiveProfile,
+): Promise<void> {
// If we just rotated credentials onto a running daemon, restart it so the
// in-memory token in the Go process matches the new config.
- if (userChanged) {
- try {
- const existing = await fetchHealthAtPort(active.port);
- if (daemonStatusAlive(existing?.status)) {
- // Restart whether it's "running" or still "starting" — a booting daemon
- // already loaded the old token at startup, so it must be restarted to
- // pick up the rotated credentials.
- console.log(
- "[daemon] user switched — restarting daemon with new credentials",
- );
- void restartDaemon();
- }
- } catch (err) {
- console.warn("[daemon] restart-on-user-switch failed:", err);
+ const existing = await fetchHealthAtPort(active.port);
+ if (daemonStatusAlive(existing?.status)) {
+ // Restart whether it's "running" or still "starting" — a booting daemon
+ // already loaded the old token at startup, so it must be restarted to
+ // pick up the rotated credentials.
+ console.log(
+ "[daemon] user switched — restarting daemon with new credentials",
+ );
+ // Credential rotation is a one-shot login intent, not poll-driven
+ // maintenance: wait for bootstrap/recovery instead of dropping it.
+ const restarted = await lifecycleOperations.runForeground(() =>
+ restartDaemon(),
+ );
+ if (!restarted.success) {
+ console.warn(
+ `[daemon] restart-on-user-switch failed: ${restarted.error ?? "unknown error"}`,
+ );
}
}
}
@@ -783,18 +839,6 @@ async function reauthenticate(
return { ok: true };
}
-async function withGuard<T>(fn: () => Promise<T>): Promise<T | { success: false; error: string }> {
- if (operationInProgress) {
- return { success: false, error: "Another daemon operation is in progress" };
- }
- operationInProgress = true;
- try {
- return await fn();
- } finally {
- operationInProgress = false;
- }
-}
-
function successfulRuntimeProbe(
providers: string[],
daemonRunning: boolean,
@@ -891,7 +935,13 @@ function desktopSpawnEnv(): NodeJS.ProcessEnv {
return { ...process.env, MULTICA_LAUNCHED_BY: "desktop" };
}
-async function startDaemon(): Promise<{ success: boolean; error?: string }> {
+function scheduleStatusRefresh(): void {
+ setTimeout(() => void pollOnce(), 0);
+}
+
+async function startDaemon(
+ recoveryProfile?: ActiveProfile,
+): Promise<{ success: boolean; error?: string }> {
const bin = await resolveCliBinary();
if (!bin) return { success: false, error: "multica CLI is not installed" };
@@ -899,15 +949,42 @@ async function startDaemon(): Promise<{ success: boolean; error?: string }> {
if (!active) {
return { success: false, error: "Waiting for the service address" };
}
+ if (
+ recoveryProfile &&
+ !recoveryStartAllowed({
+ desiredRunning: desiredDaemonRunning,
+ externalDaemonObserved,
+ expected: recoveryProfile,
+ current: active,
+ })
+ ) {
+ return { success: false, error: "Daemon recovery was superseded" };
+ }
const existing = await fetchHealthAtPort(active.port);
if (daemonStatusAlive(existing?.status)) {
// A daemon is already up ("running") or booting ("starting") on this port —
// don't spawn a second one (the CLI rejects that as "already running").
// Let polling track it through to "running".
- pollOnce();
+ externalDaemonObserved = isDaemonExternallyManaged(
+ existing?.os,
+ normalizeHostOS(process.platform),
+ );
+ scheduleStatusRefresh();
return { success: true };
}
+ if (
+ recoveryProfile &&
+ !recoveryStartAllowed({
+ desiredRunning: desiredDaemonRunning,
+ externalDaemonObserved,
+ expected: recoveryProfile,
+ current: active,
+ })
+ ) {
+ return { success: false, error: "Daemon recovery was superseded" };
+ }
+ if (recoveryProfile) recoveryPolicy.recordRecoveryAttempt(Date.now());
currentState = "starting";
// Begin a fresh auth-probe window for this attempt.
startingSince = Date.now();
@@ -932,7 +1009,7 @@ async function startDaemon(): Promise<{ success: boolean; error?: string }> {
// Stay in "starting" until pollOnce confirms /health — the CLI
// returning 0 only means the supervisor was spawned, not that the
// daemon process is already listening.
- pollOnce();
+ scheduleStatusRefresh();
resolve({ success: true });
},
);
@@ -1003,20 +1080,148 @@ async function restartDaemon(): Promise<{ success: boolean; error?: string }> {
return startDaemon();
}
+async function daemonPidIsConfirmedAbsent(profile: string): Promise<boolean> {
+ try {
+ const raw = await readFile(profilePidPath(profile), "utf-8");
+ const pid = parseDaemonPid(raw);
+ if (pid === null) {
+ console.warn(
+ `[daemon] recovery deferred: ${profilePidPath(profile)} is invalid`,
+ );
+ return false;
+ }
+ return !daemonProcessExists(pid);
+ } catch (err) {
+ if (
+ err &&
+ typeof err === "object" &&
+ "code" in err &&
+ err.code === "ENOENT"
+ ) {
+ return true;
+ }
+ console.warn("[daemon] recovery deferred: unable to read daemon PID:", err);
+ return false;
+ }
+}
+
+async function attemptDaemonRecovery(active: ActiveProfile): Promise<void> {
+ const startAllowed = () =>
+ recoveryStartAllowed({
+ desiredRunning: desiredDaemonRunning,
+ externalDaemonObserved,
+ expected: active,
+ current: activeProfile,
+ });
+ const outcome = await runDaemonRecoveryAttempt({
+ startAllowed,
+ // A normal UI poll intentionally gives up after 2s. Before treating that
+ // as process death, use an independent longer probe so a busy daemon is
+ // not restarted merely because one health request was slow.
+ confirmAlive: async () => {
+ const health = await fetchHealthAtPort(
+ active.port,
+ RECOVERY_HEALTH_PROBE_TIMEOUT_MS,
+ );
+ if (!daemonStatusAlive(health?.status)) return false;
+ externalDaemonObserved = isDaemonExternallyManaged(
+ health?.os,
+ normalizeHostOS(process.platform),
+ );
+ recoveryPolicy.observe({
+ desiredRunning: desiredDaemonRunning,
+ externalDaemonObserved,
+ lifecycleBusy: lifecycleOperations.inProgress,
+ state: health?.status === "running" ? "running" : "starting",
+ now: Date.now(),
+ });
+ scheduleStatusRefresh();
+ return true;
+ },
+ pidConfirmedAbsent: () => daemonPidIsConfirmedAbsent(active.name),
+ recordPidDeferral: () => recoveryPolicy.recordPidDeferral(Date.now()),
+ recordPidAbsent: () => recoveryPolicy.recordPidAbsent(),
+ // Force-kill leaves daemon.pid behind, and Windows can reuse the number
+ // for another process. After three spaced deferrals, let the CLI recheck
+ // health and attempt the start; an occupied port then fails safely into
+ // the normal retry backoff and absolute budget.
+ onPidFallback: () =>
+ console.warn(
+ "[daemon] daemon PID stayed unverifiable; proceeding through CLI safety checks",
+ ),
+ start: () => {
+ console.warn("[daemon] managed daemon disappeared; attempting recovery");
+ return startDaemon(active);
+ },
+ desiredRunning: () => desiredDaemonRunning,
+ stop: () => stopDaemon(),
+ });
+
+ if (outcome.kind === "alive") {
+ console.log("[daemon] recovery cancelled: longer health probe succeeded");
+ } else if (outcome.kind === "pid_deferred") {
+ console.warn(
+ "[daemon] recovery deferred: daemon PID is still alive or could not be verified",
+ );
+ } else if (outcome.kind === "start_failed") {
+ console.warn(
+ `[daemon] recovery failed: ${outcome.error ?? "unknown error"}`,
+ );
+ }
+}
+
+function recoveryDecision(status: DaemonStatus) {
+ return recoveryPolicy.observe({
+ desiredRunning: desiredDaemonRunning,
+ externalDaemonObserved,
+ lifecycleBusy: lifecycleOperations.inProgress,
+ state: status.state,
+ now: Date.now(),
+ });
+}
+
async function pollOnce(): Promise<void> {
- const status = await fetchHealth();
- currentState = status.state;
- sendStatus(status);
- // Retry a deferred version-mismatch restart once the daemon drains.
- if (pendingVersionRestart && status.state === "running") {
- void ensureRunningDaemonVersionMatches();
+ if (statusPollInProgress) return;
+ statusPollInProgress = true;
+ try {
+ const status = await fetchHealth();
+ currentState = status.state;
+ observeDaemonBoundary(status);
+ const decision = recoveryDecision(status);
+ sendStatus(
+ decision === "pause" ? { ...status, state: "recovery_paused" } : status,
+ );
+ if (decision === "confirm") {
+ const active = await ensureActiveProfile();
+ if (active) {
+ // Recovery can spend 10s confirming health plus 60s in the CLI start.
+ // Do not hold the poll lock across it: startDaemon publishes
+ // "starting" immediately, and subsequent polls keep that visible.
+ void lifecycleOperations
+ .runBackground(() => attemptDaemonRecovery(active))
+ .catch((err) => {
+ console.warn("[daemon] background recovery failed:", err);
+ });
+ }
+ }
+ // Retry a deferred version-mismatch restart once the daemon drains. Route
+ // it through the same singleflight guard as user and recovery operations.
+ if (pendingVersionRestart && status.state === "running") {
+ void lifecycleOperations
+ .runBackground(() => ensureRunningDaemonVersionMatches())
+ .catch((err) => {
+ console.warn("[daemon] deferred version restart failed:", err);
+ });
+ }
+ } finally {
+ statusPollInProgress = false;
}
}
function startPolling(): void {
if (statusPollTimer) return;
- pollOnce();
- statusPollTimer = setInterval(pollOnce, POLL_INTERVAL_MS);
+ void pollOnce();
+ statusPollTimer = setInterval(() => void pollOnce(), POLL_INTERVAL_MS);
}
/**
@@ -1149,14 +1354,26 @@ export function setupDaemonManager(
const normalized = url || null;
if (targetApiBaseUrl !== normalized) {
console.log(`[daemon] target API URL set to ${normalized ?? "(none)"}`);
+ setDesiredDaemonRunning(false);
targetApiBaseUrl = normalized;
invalidateActiveProfile();
await pollOnce();
}
});
- ipcMain.handle("daemon:start", () => withGuard(() => startDaemon()));
- ipcMain.handle("daemon:stop", () => withGuard(() => stopDaemon()));
- ipcMain.handle("daemon:restart", () => withGuard(() => restartDaemon()));
+ ipcMain.handle("daemon:start", () => {
+ externalDaemonObserved = false;
+ setDesiredDaemonRunning(true, true);
+ return lifecycleOperations.runForeground(() => startDaemon());
+ });
+ ipcMain.handle("daemon:stop", () => {
+ setDesiredDaemonRunning(false, true);
+ return lifecycleOperations.runForeground(() => stopDaemon());
+ });
+ ipcMain.handle("daemon:restart", () => {
+ externalDaemonObserved = false;
+ setDesiredDaemonRunning(true, true);
+ return lifecycleOperations.runForeground(() => restartDaemon());
+ });
ipcMain.handle("daemon:get-status", () => fetchHealth());
ipcMain.handle("daemon:probe-runtimes", () => probeLocalRuntimes());
// The host's OS name, available regardless of daemon state. The Runtimes
@@ -1166,12 +1383,25 @@ export function setupDaemonManager(
ipcMain.handle("daemon:get-host-name", () => hostname());
ipcMain.handle(
"daemon:sync-token",
- (_event, token: string, userId: string) => syncToken(token, userId),
+ async (_event, token: string, userId: string) => {
+ const result = await syncToken(token, userId);
+ if (result.userChanged) {
+ await restartDaemonAfterUserSwitch(result.active);
+ }
+ },
);
- ipcMain.handle("daemon:clear-token", () => clearToken());
+ ipcMain.handle("daemon:clear-token", () => {
+ setDesiredDaemonRunning(false, true);
+ return clearToken();
+ });
ipcMain.handle(
"daemon:reauthenticate",
- (_event, token: string, userId: string) => reauthenticate(token, userId),
+ async (_event, token: string, userId: string): Promise<ReauthResult> => {
+ setDesiredDaemonRunning(true, true);
+ return lifecycleOperations.runForeground(() =>
+ reauthenticate(token, userId),
+ );
+ },
);
ipcMain.handle("daemon:is-cli-installed", async () => {
const bin = await resolveCliBinary();
@@ -1183,7 +1413,7 @@ export function setupDaemonManager(
// A retry-install may land a new CLI at a different version; drop the
// cached version string so the next check re-reads the binary.
cachedCliBinaryVersion = undefined;
- await bootstrapCli();
+ await lifecycleOperations.runForeground(() => bootstrapCli());
});
ipcMain.handle("daemon:get-prefs", () => loadPrefs());
ipcMain.handle(
@@ -1191,22 +1421,31 @@ export function setupDaemonManager(
(_event, prefs: Partial<DaemonPrefs>) =>
loadPrefs().then((cur) => {
const merged = { ...cur, ...prefs };
+ // Changing the preference still affects the next logged-in launch; it
+ // does not start/stop the current session. The Settings copy explicitly
+ // states that a launched daemon is supervised while Desktop stays open.
return savePrefs(merged).then(() => merged);
}),
);
ipcMain.handle("daemon:auto-start", async () => {
const prefs = await loadPrefs();
+ setDesiredDaemonRunning(prefs.autoStart);
if (!prefs.autoStart) return;
- const bin = await resolveCliBinary();
- if (!bin) return;
- const health = await fetchHealth();
- if (health.state === "running") {
- // Daemon is up but may be running an older CLI than the one we just
- // bundled. Restart it so the new binary actually takes effect.
- await ensureRunningDaemonVersionMatches();
- return;
- }
- await startDaemon();
+ // 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 () => {
+ const bin = await resolveCliBinary();
+ if (!bin) return;
+ const health = await fetchHealth();
+ observeDaemonBoundary(health);
+ if (health.state === "running") {
+ // Daemon is up but may be running an older CLI than the one we just
+ // bundled. Restart it so the new binary actually takes effect.
+ await ensureRunningDaemonVersionMatches();
+ return;
+ }
+ await startDaemon();
+ });
});
ipcMain.on("daemon:start-log-stream", () => {
@@ -1236,11 +1475,12 @@ export function setupDaemonManager(
// until the managed binary is on disk (instant on subsequent launches).
currentState = "installing_cli";
sendStatus({ state: "installing_cli" });
- void bootstrapCli();
+ void lifecycleOperations.runBackground(() => bootstrapCli());
let isQuitting = false;
app.on("before-quit", (event) => {
if (isQuitting) return;
+ setDesiredDaemonRunning(false);
stopPolling();
stopLogTail();
diff --git a/apps/desktop/src/main/daemon-profile.test.ts b/apps/desktop/src/main/daemon-profile.test.ts
index 15b1250b05..7d69f5c543 100644
--- a/apps/desktop/src/main/daemon-profile.test.ts
+++ b/apps/desktop/src/main/daemon-profile.test.ts
@@ -11,6 +11,7 @@ import {
profileConfigPath,
profileDir,
profileLogPath,
+ profilePidPath,
profileUserIdPath,
} from "./daemon-profile";
@@ -45,6 +46,9 @@ describe("profile paths", () => {
expect(profileLogPath("desktop-api.multica.ai")).toBe(
join(dir, "daemon.log"),
);
+ expect(profilePidPath("desktop-api.multica.ai")).toBe(
+ join(dir, "daemon.pid"),
+ );
expect(profileUserIdPath("desktop-api.multica.ai")).toBe(
join(dir, ".desktop-user-id"),
);
@@ -56,6 +60,7 @@ describe("profile paths", () => {
expect(() => profileDir("")).toThrow(/unresolved/);
expect(() => profileConfigPath("")).toThrow(/unresolved/);
expect(() => profileLogPath("")).toThrow(/unresolved/);
+ expect(() => profilePidPath("")).toThrow(/unresolved/);
expect(() => profileUserIdPath("")).toThrow(/unresolved/);
});
diff --git a/apps/desktop/src/main/daemon-profile.ts b/apps/desktop/src/main/daemon-profile.ts
index a52b13efc8..00b2fc729c 100644
--- a/apps/desktop/src/main/daemon-profile.ts
+++ b/apps/desktop/src/main/daemon-profile.ts
@@ -60,6 +60,10 @@ export function profileLogPath(profile: string): string {
return join(profileDir(profile), "daemon.log");
}
+export function profilePidPath(profile: string): string {
+ return join(profileDir(profile), "daemon.pid");
+}
+
// Sidecar file that records which Multica user the cached PAT in config.json
// was minted for. The Go CLI/daemon never read or write this file, so it
// survives Go-side config rewrites. Used to detect user switches and mint a
diff --git a/apps/desktop/src/main/daemon-recovery.test.ts b/apps/desktop/src/main/daemon-recovery.test.ts
new file mode 100644
index 0000000000..9e6517fe6e
--- /dev/null
+++ b/apps/desktop/src/main/daemon-recovery.test.ts
@@ -0,0 +1,439 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ DaemonOperationGate,
+ DaemonRecoveryPolicy,
+ RECOVERY_ATTEMPT_BUDGET,
+ RECOVERY_ATTEMPT_WINDOW_MS,
+ RECOVERY_BACKOFF_MS,
+ RECOVERY_PID_DEFERRAL_LIMIT,
+ RECOVERY_PID_RECHECK_MS,
+ RECOVERY_STABLE_RUNNING_MS,
+ daemonProcessExists,
+ parseDaemonPid,
+ recoveryStartAllowed,
+ runDaemonRecoveryAttempt,
+} from "./daemon-recovery";
+
+const eligible = {
+ desiredRunning: true,
+ externalDaemonObserved: false,
+ lifecycleBusy: false,
+ state: "stopped" as const,
+ now: 1_000,
+};
+
+function reachDecision(
+ policy: DaemonRecoveryPolicy,
+ now: number,
+): ReturnType<DaemonRecoveryPolicy["observe"]> {
+ policy.observe({ ...eligible, now });
+ policy.observe({ ...eligible, now });
+ return policy.observe({ ...eligible, now });
+}
+
+describe("DaemonRecoveryPolicy", () => {
+ it("requires three consecutive stopped polls before confirmation", () => {
+ const policy = new DaemonRecoveryPolicy();
+ expect(policy.observe(eligible)).toBe("none");
+ expect(policy.observe(eligible)).toBe("none");
+ expect(policy.observe(eligible)).toBe("confirm");
+ });
+
+ it.each([
+ { desiredRunning: false },
+ { externalDaemonObserved: true },
+ { lifecycleBusy: true },
+ { state: "running" as const },
+ { state: "starting" as const },
+ { state: "stopping" as const },
+ { state: "installing_cli" as const },
+ { state: "cli_not_found" as const },
+ { state: "auth_expired" as const },
+ { state: "recovery_paused" as const },
+ ])("does not recover when ineligible: %o", (override) => {
+ const policy = new DaemonRecoveryPolicy();
+ for (let i = 0; i < 5; i += 1) {
+ expect(policy.observe({ ...eligible, ...override })).toBe("none");
+ }
+ });
+
+ it("keeps escalating backoff through a short-lived running crash loop", () => {
+ const policy = new DaemonRecoveryPolicy();
+ expect(reachDecision(policy, 1_000)).toBe("confirm");
+ policy.recordRecoveryAttempt(1_000);
+
+ policy.observe({ ...eligible, state: "starting", now: 2_000 });
+ policy.observe({ ...eligible, state: "running", now: 5_000 });
+ expect(reachDecision(policy, 20_000)).toBe("confirm");
+ policy.recordRecoveryAttempt(20_000);
+
+ policy.observe({ ...eligible, state: "running", now: 25_000 });
+ expect(reachDecision(policy, 20_000 + RECOVERY_BACKOFF_MS[1] - 1)).toBe(
+ "none",
+ );
+ expect(reachDecision(policy, 20_000 + RECOVERY_BACKOFF_MS[1])).toBe(
+ "confirm",
+ );
+ });
+
+ it("forgives the backoff only after sustained running", () => {
+ const policy = new DaemonRecoveryPolicy();
+ policy.recordRecoveryAttempt(1_000);
+ policy.recordRecoveryAttempt(2_000);
+ policy.observe({ ...eligible, state: "running", now: 3_000 });
+ policy.observe({
+ ...eligible,
+ state: "running",
+ now: 3_000 + RECOVERY_STABLE_RUNNING_MS,
+ });
+
+ expect(reachDecision(policy, 64_000)).toBe("confirm");
+ policy.recordRecoveryAttempt(64_000);
+ expect(reachDecision(policy, 64_000 + RECOVERY_BACKOFF_MS[0] - 1)).toBe(
+ "none",
+ );
+ expect(reachDecision(policy, 64_000 + RECOVERY_BACKOFF_MS[0])).toBe(
+ "confirm",
+ );
+ });
+
+ it("pauses visibly after the absolute attempt budget", () => {
+ const policy = new DaemonRecoveryPolicy();
+ for (let i = 0; i < RECOVERY_ATTEMPT_BUDGET; i += 1) {
+ policy.recordRecoveryAttempt(1_000 + i);
+ }
+ expect(
+ reachDecision(
+ policy,
+ 1_000 + RECOVERY_ATTEMPT_BUDGET + RECOVERY_BACKOFF_MS.at(-1)!,
+ ),
+ ).toBe("pause");
+ expect(policy.isPaused).toBe(true);
+ expect(policy.observe(eligible)).toBe("pause");
+
+ policy.reset();
+ expect(policy.isPaused).toBe(false);
+ expect(reachDecision(policy, 2_000)).toBe("confirm");
+ });
+
+ it("expires old attempts from the rolling budget", () => {
+ const policy = new DaemonRecoveryPolicy();
+ for (let i = 0; i < RECOVERY_ATTEMPT_BUDGET; i += 1) {
+ policy.recordRecoveryAttempt(1_000 + i);
+ }
+ expect(
+ reachDecision(policy, 1_000 + RECOVERY_ATTEMPT_WINDOW_MS + 1),
+ ).toBe("confirm");
+ });
+
+ it("bounds a live or unverifiable PID to three deferrals", () => {
+ const policy = new DaemonRecoveryPolicy();
+ expect(policy.recordPidDeferral(1_000)).toBe(false);
+ expect(reachDecision(policy, 1_000 + RECOVERY_PID_RECHECK_MS - 1)).toBe(
+ "none",
+ );
+ expect(reachDecision(policy, 1_000 + RECOVERY_PID_RECHECK_MS)).toBe(
+ "confirm",
+ );
+
+ policy.reset();
+ for (let i = 1; i < RECOVERY_PID_DEFERRAL_LIMIT; i += 1) {
+ expect(policy.recordPidDeferral(i * RECOVERY_PID_RECHECK_MS)).toBe(false);
+ }
+ expect(
+ policy.recordPidDeferral(
+ RECOVERY_PID_DEFERRAL_LIMIT * RECOVERY_PID_RECHECK_MS,
+ ),
+ ).toBe(true);
+ });
+});
+
+describe("recovery orchestration guards", () => {
+ const profile = { name: "desktop-api.multica.ai", port: 19_999 };
+
+ it("allows first-start recovery for a Desktop-owned profile", () => {
+ expect(
+ recoveryStartAllowed({
+ desiredRunning: true,
+ externalDaemonObserved: false,
+ expected: profile,
+ current: profile,
+ }),
+ ).toBe(true);
+ });
+
+ it("recovers an initial timed-out start without prior healthy ownership", async () => {
+ const start = vi.fn(async () => ({ success: true }));
+ const outcome = await runDaemonRecoveryAttempt({
+ startAllowed: () =>
+ recoveryStartAllowed({
+ desiredRunning: true,
+ externalDaemonObserved: false,
+ expected: profile,
+ current: profile,
+ }),
+ confirmAlive: async () => false,
+ pidConfirmedAbsent: async () => true,
+ recordPidDeferral: () => false,
+ recordPidAbsent: vi.fn(),
+ onPidFallback: vi.fn(),
+ start,
+ desiredRunning: () => true,
+ stop: vi.fn(async () => ({ success: true })),
+ });
+
+ expect(outcome).toEqual({ kind: "started" });
+ expect(start).toHaveBeenCalledOnce();
+ });
+
+ it("does not start after the profile changes during confirmation", async () => {
+ let current = profile;
+ let finishConfirmation: (alive: boolean) => void = () => {};
+ const confirmation = new Promise<boolean>((resolve) => {
+ finishConfirmation = resolve;
+ });
+ const start = vi.fn(async () => ({ success: true }));
+ const attempt = runDaemonRecoveryAttempt({
+ startAllowed: () =>
+ recoveryStartAllowed({
+ desiredRunning: true,
+ externalDaemonObserved: false,
+ expected: profile,
+ current,
+ }),
+ confirmAlive: () => confirmation,
+ pidConfirmedAbsent: vi.fn(async () => true),
+ recordPidDeferral: () => false,
+ recordPidAbsent: vi.fn(),
+ onPidFallback: vi.fn(),
+ start,
+ desiredRunning: () => true,
+ stop: vi.fn(async () => ({ success: true })),
+ });
+
+ current = { ...profile, name: "desktop-other" };
+ finishConfirmation(false);
+ await expect(attempt).resolves.toEqual({ kind: "superseded" });
+ expect(start).not.toHaveBeenCalled();
+ });
+
+ it("rolls back a successful start when Stop arrives in flight", async () => {
+ let desiredRunning = true;
+ let finishStart: (result: { success: boolean }) => void = () => {};
+ let markStartEntered: () => void = () => {};
+ const startResult = new Promise<{ success: boolean }>((resolve) => {
+ finishStart = resolve;
+ });
+ const startEntered = new Promise<void>((resolve) => {
+ markStartEntered = resolve;
+ });
+ const stop = vi.fn(async () => ({ success: true }));
+ const attempt = runDaemonRecoveryAttempt({
+ startAllowed: () => desiredRunning,
+ confirmAlive: async () => false,
+ pidConfirmedAbsent: async () => true,
+ recordPidDeferral: () => false,
+ recordPidAbsent: vi.fn(),
+ onPidFallback: vi.fn(),
+ start: () => {
+ markStartEntered();
+ return startResult;
+ },
+ desiredRunning: () => desiredRunning,
+ stop,
+ });
+
+ await startEntered;
+ desiredRunning = false;
+ finishStart({ success: true });
+ await expect(attempt).resolves.toEqual({ kind: "cancelled" });
+ expect(stop).toHaveBeenCalledOnce();
+ });
+
+ it("defers on an unverifiable PID, then uses the bounded fallback", async () => {
+ const start = vi.fn(async () => ({ success: true }));
+ let fallbackAllowed = false;
+ const dependencies = {
+ startAllowed: () => true,
+ confirmAlive: async () => false,
+ pidConfirmedAbsent: async () => false,
+ recordPidDeferral: () => fallbackAllowed,
+ recordPidAbsent: vi.fn(),
+ onPidFallback: vi.fn(),
+ start,
+ desiredRunning: () => true,
+ stop: vi.fn(async () => ({ success: true })),
+ };
+
+ await expect(runDaemonRecoveryAttempt(dependencies)).resolves.toEqual({
+ kind: "pid_deferred",
+ });
+ expect(start).not.toHaveBeenCalled();
+
+ fallbackAllowed = true;
+ await expect(runDaemonRecoveryAttempt(dependencies)).resolves.toEqual({
+ kind: "started",
+ });
+ expect(dependencies.onPidFallback).toHaveBeenCalledOnce();
+ expect(start).toHaveBeenCalledOnce();
+ });
+
+ it.each([
+ { desiredRunning: false },
+ { externalDaemonObserved: true },
+ { current: null },
+ { current: { ...profile, name: "desktop-other" } },
+ { current: { ...profile, port: profile.port + 1 } },
+ ])("rejects a superseded recovery: %o", (override) => {
+ expect(
+ recoveryStartAllowed({
+ desiredRunning: true,
+ externalDaemonObserved: false,
+ expected: profile,
+ current: profile,
+ ...override,
+ }),
+ ).toBe(false);
+ });
+
+ it("queues a one-shot login intent behind bootstrap", async () => {
+ const gate = new DaemonOperationGate();
+ let releaseBackground: () => void = () => {};
+ const background = gate.runBackground(
+ () =>
+ new Promise<string>((resolve) => {
+ releaseBackground = () => resolve("recovered");
+ }),
+ );
+ const foregroundFn = vi.fn(async () => "stopped");
+ const foreground = gate.runForeground(foregroundFn);
+ const retryablePollFn = vi.fn(async () => "polled");
+
+ await Promise.resolve();
+ expect(foregroundFn).not.toHaveBeenCalled();
+ await expect(
+ gate.runBackground(retryablePollFn),
+ ).resolves.toMatchObject({ operationBusy: true });
+ expect(retryablePollFn).not.toHaveBeenCalled();
+ releaseBackground();
+ await expect(background).resolves.toBe("recovered");
+ await expect(foreground).resolves.toBe("stopped");
+ expect(foregroundFn).toHaveBeenCalledOnce();
+ });
+
+ it("queues one-shot foreground intents in invocation order", async () => {
+ const gate = new DaemonOperationGate();
+ let releaseFirst: () => void = () => {};
+ const first = gate.runForeground(
+ () =>
+ new Promise<string>((resolve) => {
+ releaseFirst = () => resolve("first");
+ }),
+ );
+ const secondFn = vi.fn(async () => "second");
+ const second = gate.runForeground(secondFn);
+
+ await Promise.resolve();
+ expect(secondFn).not.toHaveBeenCalled();
+ releaseFirst();
+ await expect(first).resolves.toBe("first");
+ await expect(second).resolves.toBe("second");
+ expect(secondFn).toHaveBeenCalledOnce();
+ });
+
+ it("rejects foreground reentrancy instead of waiting on itself", async () => {
+ const gate = new DaemonOperationGate();
+ const nested = vi.fn(async () => "nested");
+
+ await expect(
+ gate.runForeground(() => gate.runForeground(nested)),
+ ).rejects.toThrow("cannot be called from inside a gated operation");
+ expect(nested).not.toHaveBeenCalled();
+ expect(gate.inProgress).toBe(false);
+ await expect(gate.runForeground(async () => "recovered")).resolves.toBe(
+ "recovered",
+ );
+ });
+
+ it("lets a queued member stop revoke recovery intent immediately", async () => {
+ const gate = new DaemonOperationGate();
+ let desiredRunning = true;
+ let releaseProbe: () => void = () => {};
+ const start = vi.fn(async () => ({ success: true }));
+ const recovery = gate.runBackground(() =>
+ runDaemonRecoveryAttempt({
+ startAllowed: () => desiredRunning,
+ confirmAlive: async () => {
+ await new Promise<void>((resolve) => {
+ releaseProbe = resolve;
+ });
+ return false;
+ },
+ pidConfirmedAbsent: async () => true,
+ recordPidDeferral: () => false,
+ recordPidAbsent: vi.fn(),
+ onPidFallback: vi.fn(),
+ start,
+ desiredRunning: () => desiredRunning,
+ stop: vi.fn(async () => ({ success: true })),
+ }),
+ );
+
+ desiredRunning = false;
+ const stop = gate.runForeground(async () => "stopped");
+ releaseProbe();
+ await expect(recovery).resolves.toEqual({ kind: "superseded" });
+ await expect(stop).resolves.toBe("stopped");
+ expect(start).not.toHaveBeenCalled();
+ });
+
+ it("does not queue new background work behind a member operation", async () => {
+ const gate = new DaemonOperationGate();
+ let releaseForeground: () => void = () => {};
+ const foreground = gate.runForeground(
+ () =>
+ new Promise<string>((resolve) => {
+ releaseForeground = () => resolve("started");
+ }),
+ );
+ await Promise.resolve();
+
+ await expect(
+ gate.runBackground(async () => "background"),
+ ).resolves.toMatchObject({ operationBusy: true });
+ releaseForeground();
+ await expect(foreground).resolves.toBe("started");
+ });
+});
+
+describe("daemon PID checks", () => {
+ it.each([
+ ["42", 42],
+ ["42\n", 42],
+ ["", null],
+ ["0", null],
+ ["-1", null],
+ ["12x", null],
+ ])("parses %j as %j", (raw, expected) => {
+ expect(parseDaemonPid(raw)).toBe(expected);
+ });
+
+ it("treats only ESRCH as proof that a PID is absent", () => {
+ const alive = vi.fn();
+ expect(daemonProcessExists(42, alive)).toBe(true);
+ expect(alive).toHaveBeenCalledWith(42, 0);
+
+ expect(
+ daemonProcessExists(42, () => {
+ throw Object.assign(new Error("gone"), { code: "ESRCH" });
+ }),
+ ).toBe(false);
+ expect(
+ daemonProcessExists(42, () => {
+ throw Object.assign(new Error("denied"), { code: "EPERM" });
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/daemon-recovery.ts b/apps/desktop/src/main/daemon-recovery.ts
new file mode 100644
index 0000000000..e86bc84fd3
--- /dev/null
+++ b/apps/desktop/src/main/daemon-recovery.ts
@@ -0,0 +1,331 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+
+import type { DaemonState } from "../shared/daemon-types";
+
+// The normal poll runs every 5s. Requiring three misses gives a transient slow
+// response two chances to recover before Desktop spends 10s confirming death.
+export const RECOVERY_STOPPED_THRESHOLD = 3;
+// A daemon reports "running" only after its startup preflight completes. Keep
+// it there for another minute before forgiving failures, so a 20s crash loop
+// cannot reset the retry ladder on every cycle.
+export const RECOVERY_STABLE_RUNNING_MS = 60_000;
+// Fast retries cover one-off process kills; repeated failures step up to two
+// minutes and then cap at ten minutes so broken preflight cannot create a
+// restart storm while still allowing unattended recovery.
+export const RECOVERY_BACKOFF_MS = [15_000, 30_000, 120_000, 600_000] as const;
+// Even a daemon that survives the stable-running threshold may crash again.
+// Five starts in thirty minutes is the absolute automatic budget; the sixth
+// pauses visibly until a member explicitly starts/restarts the daemon.
+export const RECOVERY_ATTEMPT_BUDGET = 5;
+export const RECOVERY_ATTEMPT_WINDOW_MS = 30 * 60_000;
+// A force-killed daemon leaves daemon.pid behind and Windows may later reuse
+// that PID. Three 30s-spaced deferrals provide a conservative process check,
+// then allow the CLI's fresh health check and the OS port bind to decide: an
+// unresponsive old listener makes the replacement fail into normal backoff.
+export const RECOVERY_PID_DEFERRAL_LIMIT = 3;
+export const RECOVERY_PID_RECHECK_MS = 30_000;
+
+export type RecoveryDecision = "none" | "confirm" | "pause";
+
+interface RecoveryObservation {
+ desiredRunning: boolean;
+ externalDaemonObserved: boolean;
+ lifecycleBusy: boolean;
+ state: DaemonState;
+ now: number;
+}
+
+/**
+ * Pure policy for deciding when the Desktop should confirm and recover a lost
+ * daemon. Side effects stay in daemon-manager; this class owns consecutive
+ * misses, sustained-health forgiveness, PID deferrals, backoff, and budget.
+ */
+export class DaemonRecoveryPolicy {
+ private consecutiveStopped = 0;
+ private runningSince: number | null = null;
+ private failureCount = 0;
+ private nextAttemptAt = 0;
+ private pidDeferrals = 0;
+ private attemptTimestamps: number[] = [];
+ private paused = false;
+
+ get isPaused(): boolean {
+ return this.paused;
+ }
+
+ observe(observation: RecoveryObservation): RecoveryDecision {
+ this.pruneAttemptBudget(observation.now);
+
+ if (observation.state === "running") {
+ this.consecutiveStopped = 0;
+ if (this.runningSince === null) this.runningSince = observation.now;
+ if (
+ observation.now - this.runningSince >=
+ RECOVERY_STABLE_RUNNING_MS
+ ) {
+ this.failureCount = 0;
+ this.nextAttemptAt = 0;
+ this.pidDeferrals = 0;
+ this.paused = false;
+ }
+ return "none";
+ }
+
+ this.runningSince = null;
+ const eligible =
+ observation.desiredRunning &&
+ !observation.externalDaemonObserved &&
+ !observation.lifecycleBusy &&
+ observation.state === "stopped";
+ if (!eligible) {
+ this.consecutiveStopped = 0;
+ return "none";
+ }
+ if (this.paused) return "pause";
+
+ this.consecutiveStopped += 1;
+ if (this.consecutiveStopped < RECOVERY_STOPPED_THRESHOLD) return "none";
+
+ this.consecutiveStopped = 0;
+ if (observation.now < this.nextAttemptAt) return "none";
+ if (this.attemptTimestamps.length >= RECOVERY_ATTEMPT_BUDGET) {
+ this.paused = true;
+ return "pause";
+ }
+ return "confirm";
+ }
+
+ recordRecoveryAttempt(now: number): void {
+ this.pruneAttemptBudget(now);
+ this.attemptTimestamps.push(now);
+ const delay =
+ RECOVERY_BACKOFF_MS[
+ Math.min(this.failureCount, RECOVERY_BACKOFF_MS.length - 1)
+ ];
+ this.failureCount += 1;
+ this.nextAttemptAt = now + delay;
+ this.pidDeferrals = 0;
+ }
+
+ /** Returns true once a stale/reused PID must stop blocking recovery. */
+ recordPidDeferral(now: number): boolean {
+ this.pidDeferrals += 1;
+ this.nextAttemptAt = now + RECOVERY_PID_RECHECK_MS;
+ if (this.pidDeferrals < RECOVERY_PID_DEFERRAL_LIMIT) return false;
+ this.pidDeferrals = 0;
+ return true;
+ }
+
+ recordPidAbsent(): void {
+ this.pidDeferrals = 0;
+ }
+
+ reset(): void {
+ this.consecutiveStopped = 0;
+ this.runningSince = null;
+ this.failureCount = 0;
+ this.nextAttemptAt = 0;
+ this.pidDeferrals = 0;
+ this.attemptTimestamps = [];
+ this.paused = false;
+ }
+
+ private pruneAttemptBudget(now: number): void {
+ const cutoff = now - RECOVERY_ATTEMPT_WINDOW_MS;
+ this.attemptTimestamps = this.attemptTimestamps.filter(
+ (attemptedAt) => attemptedAt > cutoff,
+ );
+ }
+}
+
+export interface RecoveryProfile {
+ name: string;
+ port: number;
+}
+
+export interface DaemonLifecycleResult {
+ success: boolean;
+ error?: string;
+}
+
+export type RecoveryAttemptOutcome =
+ | { kind: "superseded" }
+ | { kind: "alive" }
+ | { kind: "pid_deferred" }
+ | { kind: "started" }
+ | { kind: "start_failed"; error?: string }
+ | { kind: "cancelled" };
+
+interface RecoveryAttemptDependencies {
+ startAllowed: () => boolean;
+ confirmAlive: () => Promise<boolean>;
+ pidConfirmedAbsent: () => Promise<boolean>;
+ recordPidDeferral: () => boolean;
+ recordPidAbsent: () => void;
+ onPidFallback: () => void;
+ start: () => Promise<DaemonLifecycleResult>;
+ desiredRunning: () => boolean;
+ stop: () => Promise<DaemonLifecycleResult>;
+}
+
+/**
+ * Runs one recovery attempt with a fresh intent check after every await. This
+ * is the race-sensitive orchestration boundary: profile switches and member
+ * Stop actions can supersede background work while its health/PID/start calls
+ * are in flight, and a successful late start is rolled back before release.
+ */
+export async function runDaemonRecoveryAttempt(
+ dependencies: RecoveryAttemptDependencies,
+): Promise<RecoveryAttemptOutcome> {
+ if (!dependencies.startAllowed()) return { kind: "superseded" };
+ if (await dependencies.confirmAlive()) return { kind: "alive" };
+ if (!dependencies.startAllowed()) return { kind: "superseded" };
+
+ if (!(await dependencies.pidConfirmedAbsent())) {
+ if (!dependencies.recordPidDeferral()) return { kind: "pid_deferred" };
+ dependencies.onPidFallback();
+ } else {
+ dependencies.recordPidAbsent();
+ }
+ if (!dependencies.startAllowed()) return { kind: "superseded" };
+
+ const result = await dependencies.start();
+ if (!dependencies.desiredRunning()) {
+ if (result.success) await dependencies.stop();
+ return { kind: "cancelled" };
+ }
+ return result.success
+ ? { kind: "started" }
+ : { kind: "start_failed", error: result.error };
+}
+
+/**
+ * Named Desktop profiles and their derived ports are the ownership boundary;
+ * recovery does not require a prior successful health observation. A known
+ * foreign-OS daemon and profile/target changes remain explicit exclusions.
+ */
+export function recoveryStartAllowed(input: {
+ desiredRunning: boolean;
+ externalDaemonObserved: boolean;
+ expected: RecoveryProfile;
+ current: RecoveryProfile | null;
+}): boolean {
+ return Boolean(
+ input.desiredRunning &&
+ !input.externalDaemonObserved &&
+ input.current &&
+ input.current.name === input.expected.name &&
+ input.current.port === input.expected.port,
+ );
+}
+
+export interface OperationBusyResult {
+ success: false;
+ error: string;
+ operationBusy: true;
+}
+
+const OPERATION_BUSY: OperationBusyResult = {
+ success: false,
+ error: "Another daemon operation is in progress",
+ operationBusy: true,
+};
+
+/**
+ * Serializes lifecycle work. One-shot member/login intents use runForeground:
+ * they wait for already-running background maintenance instead of disappearing.
+ * Only work driven by a recurring poll uses runBackground, whose busy result is
+ * intentionally dropped because the next poll safely retries it. Calling
+ * runForeground from inside either gated mode throws before it can self-wait.
+ */
+export class DaemonOperationGate {
+ private busy = false;
+ private foregroundQueued = 0;
+ private completion: Promise<void> = Promise.resolve();
+ private activeOperation: symbol | null = null;
+ private readonly operationContext = new AsyncLocalStorage<symbol>();
+
+ get inProgress(): boolean {
+ return this.busy || this.foregroundQueued > 0;
+ }
+
+ async runForeground<T>(fn: () => Promise<T>): Promise<T> {
+ const currentOperation = this.operationContext.getStore();
+ if (
+ currentOperation !== undefined &&
+ currentOperation === this.activeOperation
+ ) {
+ throw new Error(
+ "DaemonOperationGate.runForeground cannot be called from inside a gated operation",
+ );
+ }
+ const previous = this.completion;
+ let release: () => void = () => {};
+ const current = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ this.foregroundQueued += 1;
+ this.completion = previous.then(
+ () => current,
+ () => current,
+ );
+
+ await previous;
+ this.foregroundQueued -= 1;
+ try {
+ return await this.execute(fn);
+ } finally {
+ release();
+ }
+ }
+
+ runBackground<T>(
+ fn: () => Promise<T>,
+ ): Promise<T | OperationBusyResult> {
+ if (this.inProgress) return Promise.resolve(OPERATION_BUSY);
+ const operation = this.execute(fn);
+ const completion = operation.then(
+ () => undefined,
+ () => undefined,
+ );
+ this.completion = completion;
+ return operation;
+ }
+
+ private async execute<T>(fn: () => Promise<T>): Promise<T> {
+ const operation = Symbol("daemon-operation");
+ this.busy = true;
+ this.activeOperation = operation;
+ try {
+ return await this.operationContext.run(operation, fn);
+ } finally {
+ this.busy = false;
+ if (this.activeOperation === operation) this.activeOperation = null;
+ }
+ }
+}
+
+export function parseDaemonPid(raw: string): number | null {
+ const trimmed = raw.trim();
+ if (!/^\d+$/.test(trimmed)) return null;
+ const pid = Number(trimmed);
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
+}
+
+/** Conservative process-liveness check: only ESRCH proves the PID is absent. */
+export function daemonProcessExists(
+ pid: number,
+ signalProbe: (pid: number, signal: 0) => void = process.kill,
+): boolean {
+ try {
+ signalProbe(pid, 0);
+ return true;
+ } catch (err) {
+ return !(
+ err &&
+ typeof err === "object" &&
+ "code" in err &&
+ err.code === "ESRCH"
+ );
+ }
+}
diff --git a/apps/desktop/src/renderer/src/components/daemon-runtime-card.test.tsx b/apps/desktop/src/renderer/src/components/daemon-runtime-card.test.tsx
index 69656dce88..0c3873d77c 100644
--- a/apps/desktop/src/renderer/src/components/daemon-runtime-card.test.tsx
+++ b/apps/desktop/src/renderer/src/components/daemon-runtime-card.test.tsx
@@ -64,3 +64,12 @@ describe("DaemonRuntimeActions — externally managed daemon (#3916)", () => {
).not.toBeInTheDocument();
});
});
+
+describe("DaemonRuntimeActions — recovery budget", () => {
+ it("offers a manual Start when automatic recovery is paused", async () => {
+ stubDaemonAPI({ state: "recovery_paused" });
+ render(<DaemonRuntimeActions />);
+
+ expect(await screen.findByText("Start")).toBeInTheDocument();
+ });
+});
diff --git a/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx b/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx
index a3d5f11041..45111f418e 100644
--- a/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx
+++ b/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx
@@ -133,7 +133,8 @@ export function DaemonRuntimeActions() {
// real guard is in the main process (stopDaemon/restartDaemon); this is the
// matching UX. See #3916.
const externallyManaged = status.externallyManaged === true;
- const isStopped = status.state === "stopped";
+ const isStopped =
+ status.state === "stopped" || status.state === "recovery_paused";
const isCliMissing = status.state === "cli_not_found";
const isAuthExpired = status.state === "auth_expired";
const isTransitioning =
diff --git a/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx b/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx
index f14639e2d2..f3c5ba44c0 100644
--- a/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx
+++ b/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx
@@ -135,7 +135,7 @@ export function DaemonSettingsTab() {
<SettingsCard>
<SettingsRow
label="Auto-start on launch"
- description="Automatically start the daemon when the app opens and you are logged in."
+ description="Start the daemon when you log in. While the app is open, it supervises both auto-started and manually started daemons."
>
<Switch
checked={prefs.autoStart}
diff --git a/apps/desktop/src/renderer/src/platform/client-usage-reporter.tsx b/apps/desktop/src/renderer/src/platform/client-usage-reporter.tsx
index 4dc4ce857d..c959a86ed3 100644
--- a/apps/desktop/src/renderer/src/platform/client-usage-reporter.tsx
+++ b/apps/desktop/src/renderer/src/platform/client-usage-reporter.tsx
@@ -83,7 +83,8 @@ export function DesktopClientUsageReporter({ apiUrl }: { apiUrl: string }) {
status.state === "running" ||
status.state === "stopped" ||
status.state === "auth_expired" ||
- status.state === "cli_not_found"
+ status.state === "cli_not_found" ||
+ status.state === "recovery_paused"
) {
const signal = `${status.state}:${[...(status.agents ?? [])].sort().join(",")}`;
if (lastStatusSignal.current === signal) return;
diff --git a/apps/desktop/src/renderer/src/platform/daemon-ipc-bridge.ts b/apps/desktop/src/renderer/src/platform/daemon-ipc-bridge.ts
index 6442b9c933..4e98c73f97 100644
--- a/apps/desktop/src/renderer/src/platform/daemon-ipc-bridge.ts
+++ b/apps/desktop/src/renderer/src/platform/daemon-ipc-bridge.ts
@@ -18,6 +18,7 @@ interface DaemonStatusLike {
| "stopping"
| "installing_cli"
| "cli_not_found"
+ | "recovery_paused"
| "auth_expired";
daemonId?: string;
}
@@ -35,6 +36,7 @@ function mergeDaemonStatus(rt: AgentRuntime, status: DaemonStatusLike): AgentRun
if (
status.state === "stopped" ||
status.state === "stopping" ||
+ status.state === "recovery_paused" ||
status.state === "auth_expired"
) {
return { ...rt, status: "offline" };
diff --git a/apps/desktop/src/shared/daemon-types.test.ts b/apps/desktop/src/shared/daemon-types.test.ts
index 54675678bf..8a68e82044 100644
--- a/apps/desktop/src/shared/daemon-types.test.ts
+++ b/apps/desktop/src/shared/daemon-types.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { describe, it, expect } from "vitest";
-import { daemonStatusAlive } from "./daemon-types";
+import { daemonStateDescription, daemonStatusAlive } from "./daemon-types";
describe("daemonStatusAlive", () => {
it("treats a ready daemon as alive", () => {
@@ -21,3 +21,11 @@ describe("daemonStatusAlive", () => {
expect(daemonStatusAlive(undefined)).toBe(false);
});
});
+
+describe("daemonStateDescription", () => {
+ it("makes an exhausted recovery budget actionable", () => {
+ expect(daemonStateDescription("recovery_paused", 0)).toMatch(
+ /start manually/i,
+ );
+ });
+});
diff --git a/apps/desktop/src/shared/daemon-types.ts b/apps/desktop/src/shared/daemon-types.ts
index d8a86cf475..37ea0f26b9 100644
--- a/apps/desktop/src/shared/daemon-types.ts
+++ b/apps/desktop/src/shared/daemon-types.ts
@@ -5,6 +5,9 @@ export type DaemonState =
| "stopping"
| "installing_cli"
| "cli_not_found"
+ // Automatic starts hit the rolling safety budget. The daemon is offline and
+ // a member must explicitly Start/Restart before recovery resumes.
+ | "recovery_paused"
// The daemon can't start because the server rejected its credentials (the
// cached PAT expired / was revoked, or the session token is dead). Without
// this, an auth failure silently sticks at "starting" forever — see #3512.
@@ -56,6 +59,7 @@ export const DAEMON_STATE_COLORS: Record<DaemonState, string> = {
stopping: "bg-amber-500 animate-pulse",
installing_cli: "bg-sky-500 animate-pulse",
cli_not_found: "bg-red-500",
+ recovery_paused: "bg-amber-500",
auth_expired: "bg-red-500",
};
@@ -66,6 +70,7 @@ export const DAEMON_STATE_LABELS: Record<DaemonState, string> = {
stopping: "Stopping…",
installing_cli: "Setting up…",
cli_not_found: "Setup Failed",
+ recovery_paused: "Recovery paused",
auth_expired: "Sign-in required",
};
@@ -120,6 +125,8 @@ export function daemonStateDescription(state: DaemonState, runtimeCount: number)
return "Setting up the runtime for the first time. Only happens once.";
case "cli_not_found":
return "Setup failed · couldn't download the runtime. Check your network.";
+ case "recovery_paused":
+ return "Automatic recovery paused after repeated failures · start manually to retry.";
case "auth_expired":
return "Sign-in expired · sign in again to bring this device back online.";
}
diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.go
index 2fd27539f9..13086ca5cd 100644
--- a/server/internal/daemon/execenv/execenv_test.go
+++ b/server/internal/daemon/execenv/execenv_test.go
@@ -1417,6 +1417,10 @@ func TestInjectRuntimeConfigBackgroundTaskSafetyProviderAgnostic(t *testing.T) {
"verify readiness",
"URL, logs, and stop instructions",
"survival as best-effort, not guaranteed",
+ "Never terminate `multica` or `multica.exe` by executable name",
+ "exact child PID you started",
+ "`multica daemon status --output json`",
+ "never kill it if it is the reported daemon PID",
} {
if !strings.Contains(s, want) {
t.Errorf("%s missing background task safety text %q\n---\n%s", tc.file, want, s)
diff --git a/server/internal/daemon/execenv/runtime_config_kind_test.go b/server/internal/daemon/execenv/runtime_config_kind_test.go
index 7eeefbebd2..4cc74bc79c 100644
--- a/server/internal/daemon/execenv/runtime_config_kind_test.go
+++ b/server/internal/daemon/execenv/runtime_config_kind_test.go
@@ -299,6 +299,10 @@ func TestBackgroundTaskSafetySlimHardPins(t *testing.T) {
"verify readiness",
"URL, logs, and stop instructions",
"survival as best-effort, not guaranteed",
+ "Never terminate `multica` or `multica.exe` by executable name",
+ "exact child PID you started",
+ "`multica daemon status --output json`",
+ "never kill it if it is the reported daemon PID",
} {
if !strings.Contains(out, want) {
t.Errorf("slim Background Task Safety missing hardened pin %q\n---\n%s", want, out)
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 57b5746192..21a0932820 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -45,7 +45,7 @@ func writeHeader(b *strings.Builder) {
}
// writeBackgroundTaskSafetySlim emits the Background Task Safety section
-// in its judgment form (MUL-5442): three paragraphs — the platform fact
+// in its judgment form (MUL-5442): four paragraphs — the platform fact
// everything else derives from (turn exit is task-terminal, no wakeup
// exists, never background-and-yield), the external-systems/CI boundary
// with its single explicit-ask exception, and the persistent-service
@@ -101,6 +101,7 @@ func writeBackgroundTaskSafetySlim(b *strings.Builder) {
b.WriteString("Multica marks the task terminal the moment your top-level turn exits — any run-owned work still active is orphaned, its result lost, and the final comment you meant to post never sends. There is no background-completion wakeup, whatever a tool response promises. Never background-and-yield: collect required results inside foreground tool calls that block to completion, run unobservable work synchronously, and never end a turn \"standing by\" for something to finish — that message becomes your final output.\n\n")
b.WriteString("External systems triggered by your completed actions — CI, GitHub Actions after a successful push — are not run-owned: do not wait for them, and do not run `gh pr checks --watch`, `gh run watch`, or sleep/retry polls. A repo's merge gate (\"CI must be green before merge\") is NOT your delivery acceptance criteria. Deliver what you have — \"Local tests pass; CI running: <PR link>\" is a complete hand-off. The one exception: when the trigger comment or the issue's acceptance criteria explicitly ask for the CI result, collect it as ONE foreground blocking call (`gh pr checks <pr> --watch`) inside this same turn.\n\n")
b.WriteString("A user explicitly asking for a local service to stay available after the turn is a persistent service handoff, not background-and-yield — allowed only when the running service itself is the requested deliverable. Detach its lifecycle from this run first (durable logs, a recorded cleanup handle such as PID/profile), verify readiness, and reply with the URL, logs, and stop instructions. Without a supervisor, describe survival as best-effort, not guaranteed.\n\n")
+ b.WriteString("Never terminate `multica` or `multica.exe` by executable name: a long-lived matching process may be the workspace daemon. Cancel only the exact child PID you started, and before terminating it compare that PID with `multica daemon status --output json`; never kill it if it is the reported daemon PID.\n\n")
}
// writeAgentIdentity emits the Agent Identity heading and (optionally) the