Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(desktop): disable auto-start/stop toggles for a daemon the app can't control (WSL2) (#3940)
Bohan Jiangac75c977977d
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.tsindex 62af33f155..195db7aef6 100644--- a/apps/desktop/src/main/daemon-manager.ts+++ b/apps/desktop/src/main/daemon-manager.ts@@ -20,6 +20,11 @@ import type { DaemonStatus, DaemonPrefs } from "../shared/daemon-types";import { daemonStatusAlive } from "../shared/daemon-types";import { ensureManagedCli, managedCliPath } from "./cli-bootstrap";import { decideVersionAction } from "./version-decision";+import {+ daemonLifecycleUnreachable,+ isDaemonExternallyManaged,+ normalizeHostOS,+} from "./daemon-os";import {classifyAuthProbe,isAuthStatusError,@@ -161,6 +166,8 @@ function sendStatus(status: DaemonStatus): void {interface HealthPayload {status?: string;pid?: number;+ /** Daemon's runtime.GOOS. Absent on daemons older than the #3916 fix. */+ os?: string;uptime?: string;daemon_id?: string;device_name?: string;@@ -347,6 +354,16 @@ async function fetchHealth(): Promise<DaemonStatus> {authExpired = false;startingSince = null;+ // A running daemon whose OS differs from this host's is one we can't drive+ // via the native lifecycle CLI (e.g. Linux-in-WSL2 behind a Windows desktop,+ // reachable only over localhost forwarding). Surface it so the UI disables+ // the auto-start/auto-stop toggles instead of letting them silently no-op,+ // and so before-quit skips a stop that would never land. See #3916.+ const externallyManaged = isDaemonExternallyManaged(+ data.os,+ normalizeHostOS(process.platform),+ );+// Safety: if we have a target URL and the daemon on our port reports a// different server_url, it's not "our" daemon — drop it and re-resolve.if (@@ -370,6 +387,7 @@ async function fetchHealth(): Promise<DaemonStatus> {: 0,profile: active.name,serverUrl: data.server_url,+ externallyManaged,};}@@ -556,6 +574,15 @@ async function ensureRunningDaemonVersionMatches(): Promise<> {const active = await ensureActiveProfile();const running = await fetchHealthAtPort(active.port);++ // Don't try to version-match a daemon we can't restart (e.g. WSL2). Treat it+ // as up-to-date — restartDaemon would no-op anyway, and skipping here avoids+ // a misleading "restarting daemon" log on every auto-start. #3916.+ if (isDaemonExternallyManaged(running?.os, normalizeHostOS(process.platform))) {+ pendingVersionRestart = false;+ return "ok";+ }+const bundled = await getCliBinaryVersion();const action = decideVersionAction(bundled, running);@@ -837,7 +864,32 @@ async function startDaemon(): Promise<{ success: boolean; error?: string }> {});}+/**+ * Fresh boundary preflight for stop/restart: read the active profile's CURRENT+ * /health and decide whether the daemon runs somewhere the app can't drive+ * (WSL2 etc.). Done per call rather than off the poll cache, so a lifecycle op+ * never shells out to a CLI that can't reach the daemon's process — even on+ * paths that didn't just poll (e.g. restart-on-user-switch in syncToken, which+ * calls restartDaemon directly). See #3916.+ */+async function lifecycleBlockedByForeignDaemon(): Promise<boolean> {+ const active = await ensureActiveProfile();+ return daemonLifecycleUnreachable(+ async () => (await fetchHealthAtPort(active.port))?.os,+ normalizeHostOS(process.platform),+ );+}+async function stopDaemon(): Promise<{ success: boolean; error?: string }> {+ // 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+ // still flipping our state to "stopped". Bail as a successful no-op so every+ // caller (logout, quit, restart, the Runtime card) is covered in one place+ // rather than each remembering to check. Preflighted against live /health so+ // it holds even when no poll ran first. #3916.+ if (await lifecycleBlockedByForeignDaemon()) return { success: true };+const bin = await resolveCliBinary();if (!bin) return { success: false, error: "multica CLI is not installed" };@@ -864,6 +916,11 @@ async function stopDaemon(): Promise<{ success: boolean; error?: string }> {}async function restartDaemon(): Promise<{ success: boolean; error?: string }> {+ // 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).+ // #3916.+ if (await lifecycleBlockedByForeignDaemon()) return { success: true };const stopResult = await stopDaemon();if (!stopResult.success) return stopResult;return startDaemon();@@ -1111,6 +1168,8 @@ export function setupDaemonManager(isQuitting = true;event.preventDefault();try {+ // stopDaemon no-ops for an externally-managed daemon (WSL2 etc.), so+ // this is safe and instant in that case — the guard lives there. #3916await stopDaemon();} catch {// Best-effort stop on quitdiff --git a/apps/desktop/src/main/daemon-os.test.ts b/apps/desktop/src/main/daemon-os.test.tsnew file mode 100644index 0000000000..87240d1f8e--- /dev/null+++ b/apps/desktop/src/main/daemon-os.test.ts@@ -0,0 +1,80 @@+import { describe, expect, it, vi } from "vitest";++import {+ daemonLifecycleUnreachable,+ isDaemonExternallyManaged,+ normalizeHostOS,+} from "./daemon-os";++describe("normalizeHostOS", () => {+ it("maps win32 to the GOOS spelling 'windows'", () => {+ expect(normalizeHostOS("win32")).toBe("windows");+ });++ it("passes darwin and linux through unchanged (already GOOS spellings)", () => {+ expect(normalizeHostOS("darwin")).toBe("darwin");+ expect(normalizeHostOS("linux")).toBe("linux");+ });+});++describe("isDaemonExternallyManaged", () => {+ it("flags a Linux (WSL2) daemon behind a Windows desktop — the #3916 case", () => {+ expect(isDaemonExternallyManaged("linux", normalizeHostOS("win32"))).toBe(+ true,+ );+ });++ // These three are the "不误伤" guarantees: a native daemon on each platform+ // must keep its auto-start/auto-stop toggles.+ it("does NOT flag a native Windows daemon under a Windows desktop", () => {+ expect(isDaemonExternallyManaged("windows", normalizeHostOS("win32"))).toBe(+ false,+ );+ });++ it("does NOT flag a native macOS daemon under a macOS desktop", () => {+ expect(isDaemonExternallyManaged("darwin", normalizeHostOS("darwin"))).toBe(+ false,+ );+ });++ it("does NOT flag a native Linux daemon under a Linux desktop", () => {+ expect(isDaemonExternallyManaged("linux", normalizeHostOS("linux"))).toBe(+ false,+ );+ });++ // Fail safe: an older daemon that predates the `os` field reports nothing.+ // Hiding a toggle on a guess would 误伤, so unknown OS = treat as manageable.+ it("fails safe to false when the daemon reports no OS", () => {+ expect(isDaemonExternallyManaged(undefined, "windows")).toBe(false);+ expect(isDaemonExternallyManaged("", "windows")).toBe(false);+ });+});++// The stop/restart lifecycle boundary funnels through this. It must read the+// daemon's LIVE OS (not a cached poll value), so a restart on a path that+// didn't just poll — e.g. user-switch — still can't shell out at a WSL2 daemon.+describe("daemonLifecycleUnreachable", () => {+ it("consults the live OS reader and blocks a foreign-OS (WSL2) daemon", async () => {+ const readDaemonOS = vi.fn().mockResolvedValue("linux");+ expect(await daemonLifecycleUnreachable(readDaemonOS, "windows")).toBe(true);+ // Proves the decision came from a fresh read, not a stale cache.+ expect(readDaemonOS).toHaveBeenCalledTimes(1);+ });++ it("allows a native daemon whose live OS matches the host", async () => {+ expect(+ await daemonLifecycleUnreachable(async () => "windows", "windows"),+ ).toBe(false);+ expect(+ await daemonLifecycleUnreachable(async () => "darwin", "darwin"),+ ).toBe(false);+ });++ it("fails safe to false when the live OS is unknown (older daemon / none running)", async () => {+ expect(+ await daemonLifecycleUnreachable(async () => undefined, "windows"),+ ).toBe(false);+ });+});diff --git a/apps/desktop/src/main/daemon-os.ts b/apps/desktop/src/main/daemon-os.tsnew file mode 100644index 0000000000..77135fba54--- /dev/null+++ b/apps/desktop/src/main/daemon-os.ts@@ -0,0 +1,67 @@+/**+ * Detecting a daemon the desktop app can't manage.+ *+ * The app reads daemon liveness over HTTP at 127.0.0.1:{port}/health, but it+ * starts/stops the daemon by shelling out to the bundled native CLI, which acts+ * on the *host* OS process namespace. On Windows with the daemon running inside+ * WSL2, /health is reachable via localhost forwarding (so status looks fine) but+ * the daemon's process lives in a separate Linux namespace the Windows CLI can't+ * touch — so auto-start / auto-stop silently do nothing (#3916).+ *+ * The reliable, low-false-positive signal is the daemon's own OS (reported as+ * `os` on /health, = runtime.GOOS) vs the desktop host OS. They only disagree+ * when the daemon runs in a foreign environment we can't drive. This module is+ * the single source of truth for that comparison so it stays unit-tested — the+ * cost of a false positive is hiding a working toggle from a native user, so the+ * logic must fail safe (treat unknown / matching as manageable).+ */++/**+ * Normalize a Node `process.platform` value to the daemon's `runtime.GOOS`+ * vocabulary so the two are directly comparable. Only `win32` -> `windows`+ * actually differs across the platforms we ship (darwin/linux already match);+ * any other value passes through unchanged.+ */+export function normalizeHostOS(platform: NodeJS.Platform): string {+ return platform === "win32" ? "windows" : platform;+}++/**+ * Whether a running daemon is in an environment the desktop app can't control.+ *+ * Returns true ONLY when the daemon reports a concrete OS that differs from the+ * host's. Fails safe to false when:+ * - `daemonOS` is missing/empty (older daemon that predates the `os` field, or+ * a malformed response) — we can't prove it's foreign, so keep toggles live.+ * - the OSes match — a normally-managed native daemon.+ *+ * Callers must only invoke this for a daemon that is actually running; a stopped+ * daemon has no OS to compare and its toggles must stay enabled.+ */+export function isDaemonExternallyManaged(+ daemonOS: string | undefined,+ hostOS: string,+): boolean {+ if (typeof daemonOS !== "string" || daemonOS.length === 0) return false;+ return daemonOS !== hostOS;+}++/**+ * Boundary preflight for daemon lifecycle ops (stop / restart): resolve the+ * daemon's CURRENT OS via `readDaemonOS` and return true when it's running+ * somewhere the app can't drive.+ *+ * `readDaemonOS` is a live `/health` read performed at the call site — never a+ * cached poll value. That is the whole point: a stale "manageable" cache would+ * let a lifecycle op shell out to a native CLI that can't reach a WSL2 daemon+ * (the PID lives in another namespace), which is exactly the bug. Taking the+ * reader as a parameter keeps this unit-testable without the electron-coupled+ * daemon-manager module, and lets the test prove the live value — not a cache —+ * drives the decision. See #3916.+ */+export async function daemonLifecycleUnreachable(+ readDaemonOS: () => Promise<string | undefined>,+ hostOS: string,+): Promise<boolean> {+ return isDaemonExternallyManaged(await readDaemonOS(), hostOS);+}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.tsxnew file mode 100644index 0000000000..69656dce88--- /dev/null+++ b/apps/desktop/src/renderer/src/components/daemon-runtime-card.test.tsx@@ -0,0 +1,66 @@+import { describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";++import type { DaemonStatus } from "../../../shared/daemon-types";++// The component only needs these to render; stub them so the test focuses on+// the externally-managed branching, not data fetching.+vi.mock("@tanstack/react-query", () => ({+ useQuery: () => ({ data: [] }),+}));+vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "ws-1",+}));+vi.mock("@multica/core/runtimes", () => ({+ runtimeListOptions: () => ({ queryKey: ["runtimes"] }),+}));+vi.mock("@multica/core/agents", () => ({+ agentTaskSnapshotOptions: () => ({ queryKey: ["snapshot"] }),+}));+vi.mock("./daemon-panel", () => ({ DaemonPanel: () => null }));+vi.mock("../platform/daemon-reauth", () => ({+ reauthenticateDaemon: vi.fn(),+}));+vi.mock("sonner", () => ({+ toast: { error: vi.fn(), success: vi.fn() },+}));++import { DaemonRuntimeActions } from "./daemon-runtime-card";++function stubDaemonAPI(status: DaemonStatus) {+ Object.defineProperty(window, "daemonAPI", {+ configurable: true,+ value: {+ getStatus: vi.fn().mockResolvedValue(status),+ onStatusChange: vi.fn(() => () => {}),+ },+ });+}++describe("DaemonRuntimeActions — externally managed daemon (#3916)", () => {+ it("hides Stop/Restart and shows the managed-outside hint for a daemon the app can't control", async () => {+ stubDaemonAPI({ state: "running", daemonId: "d1", externallyManaged: true });+ render(<DaemonRuntimeActions />);++ // View logs still renders, confirming the running branch mounted.+ expect(await screen.findByText("View logs")).toBeInTheDocument();+ expect(screen.getByText("Managed outside the app")).toBeInTheDocument();+ expect(screen.queryByText("Restart")).not.toBeInTheDocument();+ expect(screen.queryByText("Stop")).not.toBeInTheDocument();+ });++ it("shows Stop/Restart for a normally-managed running daemon (no 误伤)", async () => {+ stubDaemonAPI({+ state: "running",+ daemonId: "d1",+ externallyManaged: false,+ });+ render(<DaemonRuntimeActions />);++ expect(await screen.findByText("Restart")).toBeInTheDocument();+ expect(screen.getByText("Stop")).toBeInTheDocument();+ expect(+ screen.queryByText("Managed outside the app"),+ ).not.toBeInTheDocument();+ });+});diff --git a/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx b/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsxindex 9794d947de..691ab12efb 100644--- a/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx+++ b/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx@@ -7,6 +7,7 @@ import {Activity,ScrollText,LogIn,+ Info,} from "lucide-react";import { useQuery } from "@tanstack/react-query";import { useWorkspaceId } from "@multica/core/hooks";@@ -126,6 +127,12 @@ export function DaemonRuntimeActions() {}, []);const isRunning = status.state === "running";+ // The daemon runs somewhere the app can't drive (e.g. inside WSL2): the+ // lifecycle CLI acts on the host process namespace and can't reach it. Hide+ // Stop/Restart so they don't silently no-op, mirroring the Settings tab. The+ // 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 isCliMissing = status.state === "cli_not_found";const isAuthExpired = status.state === "auth_expired";@@ -142,24 +149,33 @@ export function DaemonRuntimeActions() {<ScrollText className="size-3.5 mr-1.5" />View logs</Button>- <Button- size="sm"- variant="outline"- onClick={handleRestart}- disabled={actionLoading}- >- <RotateCw className="size-3.5 mr-1.5" />- Restart- </Button>- <Button- size="sm"- variant="destructive"- onClick={handleStopClick}- disabled={actionLoading}- >- <Square className="size-3.5 mr-1.5" />- Stop- </Button>+ {externallyManaged ? (+ <span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">+ <Info className="size-3.5 shrink-0" />+ Managed outside the app+ </span>+ ) : (+ <>+ <Button+ size="sm"+ variant="outline"+ onClick={handleRestart}+ disabled={actionLoading}+ >+ <RotateCw className="size-3.5 mr-1.5" />+ Restart+ </Button>+ <Button+ size="sm"+ variant="destructive"+ onClick={handleStopClick}+ disabled={actionLoading}+ >+ <Square className="size-3.5 mr-1.5" />+ Stop+ </Button>+ </>+ )}</>)}diff --git a/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx b/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsxindex f40c4d59ee..9fd108caa7 100644--- a/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx+++ b/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx@@ -1,5 +1,5 @@import { useState, useEffect, useCallback, type ReactNode } from "react";-import { AlertCircle, LogIn } from "lucide-react";+import { AlertCircle, Info, LogIn } from "lucide-react";import { Button } from "@multica/ui/components/ui/button";import { Switch } from "@multica/ui/components/ui/switch";import { cn } from "@multica/ui/lib/utils";@@ -88,6 +88,12 @@ export function DaemonSettingsTab() {[],);+ // The daemon runs somewhere the app can't drive (e.g. inside WSL2 behind a+ // Windows desktop): /health is reachable but the lifecycle CLI can't reach+ // its process. Auto-start/auto-stop can't work, so disable them and say why+ // rather than letting the toggles silently no-op. See #3916.+ const externallyManaged = status.externallyManaged === true;+return (<div><h2 className="text-lg font-semibold">Daemon</h2>@@ -119,6 +125,19 @@ export function DaemonSettingsTab() {</div>)}+ {externallyManaged && (+ <div className="mt-4 flex items-start gap-3 rounded-lg border bg-muted/30 px-4 py-3">+ <Info className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ <p className="min-w-0 text-sm text-muted-foreground">+ This device's daemon runs outside the app — for example inside+ WSL2 — so the app can't start or stop it. Start or stop it from+ that environment with{" "}+ <code className="font-mono text-xs">multica daemon start</code> /{" "}+ <code className="font-mono text-xs">multica daemon stop</code>.+ </p>+ </div>+ )}+<div className="mt-6 divide-y"><SettingRowlabel="Auto-start on launch"@@ -127,7 +146,7 @@ export function DaemonSettingsTab() {<Switchchecked={prefs.autoStart}onCheckedChange={(checked) => updatePref("autoStart", checked)}- disabled={saving}+ disabled={saving || externallyManaged}/></SettingRow>@@ -138,7 +157,7 @@ export function DaemonSettingsTab() {<Switchchecked={prefs.autoStop}onCheckedChange={(checked) => updatePref("autoStop", checked)}- disabled={saving}+ disabled={saving || externallyManaged}/></SettingRow>diff --git a/apps/desktop/src/shared/daemon-types.ts b/apps/desktop/src/shared/daemon-types.tsindex 4116ccb3f9..d0932f61dc 100644--- a/apps/desktop/src/shared/daemon-types.ts+++ b/apps/desktop/src/shared/daemon-types.ts@@ -22,6 +22,16 @@ export interface DaemonStatus {profile?: string;/** Backend URL the daemon connects to. */serverUrl?: string;+ /**+ * True when a daemon is running but in an environment the app can't control+ * — its reported OS differs from the desktop host's (e.g. a Linux daemon+ * inside WSL2 behind a Windows desktop, reachable only via localhost+ * forwarding). The app's start/stop CLI acts on the host process namespace,+ * so auto-start/auto-stop can't reach it; the UI disables those toggles+ * instead of silently no-op'ing. Only ever set on a running daemon, so it+ * never disables the toggles for a normally-managed native daemon. See #3916.+ */+ externallyManaged?: boolean;}export interface DaemonPrefs {diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.goindex 82efcb64f4..c601005478 100644--- a/server/internal/daemon/health.go+++ b/server/internal/daemon/health.go@@ -8,6 +8,7 @@ import ("net""net/http""os"+ "runtime""time""github.com/multica-ai/multica/server/internal/daemon/repocache"@@ -15,8 +16,15 @@ import (// HealthResponse is returned by the daemon's local health endpoint.type HealthResponse struct {- Status string `json:"status"`- PID int `json:"pid"`+ Status string `json:"status"`+ PID int `json:"pid"`+ // OS is the daemon's runtime.GOOS. The desktop app compares it against its+ // own host OS to detect a daemon it cannot manage — e.g. a Windows desktop+ // reaching a Linux daemon inside WSL2 over localhost forwarding. The+ // lifecycle CLI (`daemon start/stop`) acts on the host process namespace,+ // so a foreign-OS daemon can't be started/stopped by the app even though+ // /health is reachable. See #3916.+ OS string `json:"os"`Uptime string `json:"uptime"`DaemonID string `json:"daemon_id"`DeviceName string `json:"device_name"`@@ -86,6 +94,7 @@ func (d *Daemon) healthHandler(startedAt time.Time) http.HandlerFunc {resp := HealthResponse{Status: status,PID: os.Getpid(),+ OS: runtime.GOOS,Uptime: time.Since(startedAt).Truncate(time.Second).String(),DaemonID: d.cfg.DaemonID,DeviceName: d.cfg.DeviceName,diff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.goindex a4a9f8bd74..1a6d366d23 100644--- a/server/internal/daemon/health_test.go+++ b/server/internal/daemon/health_test.go@@ -6,6 +6,7 @@ import ("log/slog""net/http""net/http/httptest"+ "runtime""sync""testing""time"@@ -54,6 +55,12 @@ func TestHealthHandlerReportsCLIVersionAndActiveTaskCount(t *testing.T) {if got, want := raw["status"], "running"; got != want {t.Errorf("status key: got %v, want %q", got, want)}+ // The desktop relies on the `os` key (runtime.GOOS) to detect a daemon it+ // can't manage (e.g. Linux-in-WSL behind a Windows desktop). A rename or+ // drop would silently re-break #3916, so lock both the key and its value.+ if got, want := raw["os"], runtime.GOOS; got != want {+ t.Errorf("os key: got %v, want %q", got, want)+ }// Also round-trip into the typed struct as a separate check that the// field values match, independent of key naming.