Skip to content

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

Go

feat(desktop): daemon management panel with sidebar status bar (#952)

devv-eve40aa23a528ba
diff --git a/apps/desktop/.gitignore b/apps/desktop/.gitignore
index 75ef73cdb5..a95e840530 100644
--- a/apps/desktop/.gitignore
+++ b/apps/desktop/.gitignore
@@ -4,3 +4,5 @@ out
.DS_Store
.eslintcache
*.log*
+# CLI binary bundled at build time (from server/bin/)
+resources/bin/
diff --git a/apps/desktop/eslint.config.mjs b/apps/desktop/eslint.config.mjs
index 026a773d6c..b4f5a45c31 100644
--- a/apps/desktop/eslint.config.mjs
+++ b/apps/desktop/eslint.config.mjs
@@ -1,6 +1,13 @@
+import globals from "globals";
import reactConfig from "@multica/eslint-config/react";
export default [
...reactConfig,
{ ignores: ["out/", "dist/"] },
+ {
+ files: ["scripts/**/*.{mjs,js}"],
+ languageOptions: {
+ globals: { ...globals.node },
+ },
+ },
];
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 2ae19c04bf..71c88a4e43 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -4,14 +4,15 @@
"private": true,
"main": "./out/main/index.js",
"scripts": {
- "dev": "electron-vite dev",
- "dev:remote": "electron-vite dev --mode remote",
- "build": "electron-vite build",
+ "bundle-cli": "node scripts/bundle-cli.mjs",
+ "dev": "pnpm run bundle-cli && electron-vite dev",
+ "dev:remote": "pnpm run bundle-cli && electron-vite dev --mode remote",
+ "build": "pnpm run bundle-cli && electron-vite build",
"typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false",
"typecheck:web": "tsc --noEmit -p tsconfig.web.json --composite false",
"typecheck": "pnpm run typecheck:node && pnpm run typecheck:web",
"preview": "electron-vite preview",
- "package": "electron-builder",
+ "package": "pnpm run bundle-cli && electron-builder",
"lint": "eslint .",
"postinstall": "electron-builder install-app-deps"
},
diff --git a/apps/desktop/scripts/bundle-cli.mjs b/apps/desktop/scripts/bundle-cli.mjs
new file mode 100644
index 0000000000..f9796fcd31
--- /dev/null
+++ b/apps/desktop/scripts/bundle-cli.mjs
@@ -0,0 +1,58 @@
+#!/usr/bin/env node
+// Copies the locally-built `multica` CLI into apps/desktop/resources/bin/
+// so electron-vite (dev) and electron-builder (prod) pick it up. Desktop's
+// cli-bootstrap prefers this bundled copy over the GitHub Releases download
+// path, which keeps dev iteration fast (edit Go → make build → restart
+// Desktop) and lets the released .app ship with a CLI out of the box.
+//
+// Graceful: if server/bin/multica is missing, prints a warning and exits
+// with status 0 so the Desktop can still boot with auto-install fallback.
+
+import { access, chmod, copyFile, mkdir } from "node:fs/promises";
+import { constants } from "node:fs";
+import { execSync } from "node:child_process";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(here, "..", "..", "..");
+
+const binName = process.platform === "win32" ? "multica.exe" : "multica";
+const srcBinary = join(repoRoot, "server", "bin", binName);
+const destDir = join(repoRoot, "apps", "desktop", "resources", "bin");
+const destBinary = join(destDir, binName);
+
+async function exists(p) {
+ try {
+ await access(p, constants.F_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+if (!(await exists(srcBinary))) {
+ console.warn(
+ `[bundle-cli] ${srcBinary} not found — run 'make build' to bundle the CLI. ` +
+ `Desktop will fall back to auto-installing the latest release at runtime.`,
+ );
+ process.exit(0);
+}
+
+await mkdir(destDir, { recursive: true });
+await copyFile(srcBinary, destBinary);
+await chmod(destBinary, 0o755);
+
+// macOS: ad-hoc sign so Gatekeeper doesn't complain when the parent app
+// (which itself may be unsigned in dev) spawns the child.
+if (process.platform === "darwin") {
+ try {
+ execSync(`codesign -s - --force ${JSON.stringify(destBinary)}`, {
+ stdio: "pipe",
+ });
+ } catch {
+ // Non-fatal. Unsigned binaries still run when the parent is trusted.
+ }
+}
+
+console.log(`[bundle-cli] bundled ${srcBinary} → ${destBinary}`);
diff --git a/apps/desktop/src/main/cli-bootstrap.ts b/apps/desktop/src/main/cli-bootstrap.ts
new file mode 100644
index 0000000000..4a3a8130a6
--- /dev/null
+++ b/apps/desktop/src/main/cli-bootstrap.ts
@@ -0,0 +1,173 @@
+import { app } from "electron";
+import { execFile } from "child_process";
+import { createHash } from "crypto";
+import { createReadStream, createWriteStream, existsSync } from "fs";
+import { chmod, mkdir, rename, rm } from "fs/promises";
+import { join, dirname } from "path";
+import { pipeline } from "stream/promises";
+import { tmpdir } from "os";
+import { Readable } from "stream";
+
+// Desktop bootstraps its own copy of the `multica` CLI into userData on first
+// launch, so users never have to brew-install anything. Build-time decoupled:
+// we don't bundle the binary into the .app, we download whatever the upstream
+// release is at first run.
+
+const GITHUB_LATEST_BASE =
+ "https://github.com/multica-ai/multica/releases/latest/download";
+
+function platformAssetName(): string {
+ const osMap: Record<string, string> = {
+ darwin: "darwin",
+ linux: "linux",
+ win32: "windows",
+ };
+ const archMap: Record<string, string> = {
+ x64: "amd64",
+ arm64: "arm64",
+ };
+ const os = osMap[process.platform];
+ const arch = archMap[process.arch];
+ if (!os || !arch) {
+ throw new Error(
+ `unsupported platform for CLI auto-install: ${process.platform}/${process.arch}`,
+ );
+ }
+ const ext = process.platform === "win32" ? "zip" : "tar.gz";
+ return `multica_${os}_${arch}.${ext}`;
+}
+
+function binaryName(): string {
+ return process.platform === "win32" ? "multica.exe" : "multica";
+}
+
+export function managedCliPath(): string {
+ return join(app.getPath("userData"), "bin", binaryName());
+}
+
+function run(cmd: string, args: string[], cwd?: string): Promise<void> {
+ return new Promise((resolve, reject) => {
+ execFile(cmd, args, { cwd }, (err) => (err ? reject(err) : resolve()));
+ });
+}
+
+async function downloadToFile(url: string, dest: string): Promise<void> {
+ const res = await fetch(url, { redirect: "follow" });
+ if (!res.ok || !res.body) {
+ throw new Error(`download failed: ${res.status} ${res.statusText}`);
+ }
+ await mkdir(dirname(dest), { recursive: true });
+ // Node's fetch returns a web ReadableStream; adapt to a Node stream for pipeline.
+ const nodeStream = Readable.fromWeb(res.body as Parameters<typeof Readable.fromWeb>[0]);
+ await pipeline(nodeStream, createWriteStream(dest));
+}
+
+// Fetch goreleaser's published checksums.txt and parse it into a
+// filename → sha256 lookup. Format is `<hex> <filename>` per line.
+async function fetchChecksums(): Promise<Map<string, string>> {
+ const url = `${GITHUB_LATEST_BASE}/checksums.txt`;
+ const res = await fetch(url, { redirect: "follow" });
+ if (!res.ok) {
+ throw new Error(
+ `checksums.txt fetch failed: ${res.status} ${res.statusText}`,
+ );
+ }
+ const text = await res.text();
+ const map = new Map<string, string>();
+ for (const rawLine of text.split("\n")) {
+ const line = rawLine.trim();
+ if (!line) continue;
+ const match = line.match(/^([a-f0-9]{64})\s+\*?(\S+)$/i);
+ if (match) map.set(match[2], match[1].toLowerCase());
+ }
+ return map;
+}
+
+async function sha256OfFile(path: string): Promise<string> {
+ const hash = createHash("sha256");
+ await pipeline(createReadStream(path), hash);
+ return hash.digest("hex");
+}
+
+async function verifyChecksum(
+ archivePath: string,
+ assetName: string,
+): Promise<void> {
+ const checksums = await fetchChecksums();
+ const expected = checksums.get(assetName);
+ if (!expected) {
+ throw new Error(
+ `no checksum for ${assetName} in checksums.txt — refusing to install unverified binary`,
+ );
+ }
+ const actual = await sha256OfFile(archivePath);
+ if (actual.toLowerCase() !== expected) {
+ throw new Error(
+ `checksum mismatch for ${assetName}: expected ${expected}, got ${actual}`,
+ );
+ }
+}
+
+async function extractArchive(archive: string, dest: string): Promise<void> {
+ await mkdir(dest, { recursive: true });
+ // Modern OSes all ship a `tar` that auto-detects tar.gz and zip:
+ // - macOS/Linux: GNU tar or bsdtar
+ // - Windows 10+: bsdtar is bundled as `tar.exe` since build 17063
+ await run("tar", ["-xf", archive, "-C", dest]);
+}
+
+async function installFresh(): Promise<string> {
+ const target = managedCliPath();
+ const assetName = platformAssetName();
+ const url = `${GITHUB_LATEST_BASE}/${assetName}`;
+
+ const workDir = join(tmpdir(), `multica-cli-${Date.now()}`);
+ await mkdir(workDir, { recursive: true });
+
+ try {
+ const archivePath = join(workDir, assetName);
+ console.log(`[cli-bootstrap] downloading ${url}`);
+ await downloadToFile(url, archivePath);
+
+ console.log(`[cli-bootstrap] verifying ${assetName} against checksums.txt`);
+ await verifyChecksum(archivePath, assetName);
+
+ console.log(`[cli-bootstrap] extracting ${assetName}`);
+ await extractArchive(archivePath, workDir);
+
+ const extractedBin = join(workDir, binaryName());
+ if (!existsSync(extractedBin)) {
+ throw new Error(
+ `archive ${assetName} did not contain ${binaryName()} at its root`,
+ );
+ }
+
+ await mkdir(dirname(target), { recursive: true });
+ await rename(extractedBin, target);
+ await chmod(target, 0o755);
+
+ // macOS: ad-hoc sign so spawning the child never hits a gatekeeper quirk.
+ // Non-fatal: unsigned binaries still execute when the parent app is trusted.
+ if (process.platform === "darwin") {
+ await run("codesign", ["-s", "-", "--force", target]).catch((err) => {
+ console.warn("[cli-bootstrap] ad-hoc codesign failed:", err);
+ });
+ }
+
+ console.log(`[cli-bootstrap] installed CLI at ${target}`);
+ return target;
+ } finally {
+ await rm(workDir, { recursive: true, force: true }).catch(() => {});
+ }
+}
+
+/**
+ * Returns the path to a usable `multica` binary. If one is already present at
+ * the managed userData location, returns it immediately. Otherwise downloads
+ * the latest release asset for the current platform and installs it.
+ */
+export async function ensureManagedCli(): Promise<string> {
+ const target = managedCliPath();
+ if (existsSync(target)) return target;
+ return installFresh();
+}
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.ts
new file mode 100644
index 0000000000..42d11305b9
--- /dev/null
+++ b/apps/desktop/src/main/daemon-manager.ts
@@ -0,0 +1,877 @@
+import { app, ipcMain, BrowserWindow } from "electron";
+import { execFile } from "child_process";
+import {
+ readFile,
+ writeFile,
+ mkdir,
+ rm,
+ open,
+ stat,
+} from "fs/promises";
+import {
+ existsSync,
+ watchFile,
+ unwatchFile,
+ type StatsListener,
+} from "fs";
+import { join } from "path";
+import { homedir } from "os";
+import type { DaemonStatus, DaemonPrefs } from "../shared/daemon-types";
+import { ensureManagedCli, managedCliPath } from "./cli-bootstrap";
+
+const DEFAULT_HEALTH_PORT = 19514;
+const POLL_INTERVAL_MS = 5_000;
+const PREFS_PATH = join(homedir(), ".multica", "desktop_prefs.json");
+const LOG_TAIL_RETRY_MS = 2_000;
+const LOG_TAIL_MAX_RETRIES = 5;
+
+const DEFAULT_PREFS: DaemonPrefs = { autoStart: true, autoStop: false };
+
+interface ActiveProfile {
+ name: string; // "" = default profile
+ port: number;
+}
+
+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 cachedCliBinary: string | null | undefined = undefined;
+let cliResolvePromise: Promise<string | null> | null = null;
+let targetApiBaseUrl: string | null = null;
+let activeProfile: ActiveProfile | null = null;
+
+// Serialize all writes to any profile config file. Multiple paths
+// (syncToken, resolveActiveProfile, clearToken, watch/unwatch handlers)
+// may try to write concurrently; chaining them avoids interleaved writes
+// corrupting the JSON.
+let configWriteChain: Promise<void> = Promise.resolve();
+
+// Keep the Go impl in sync: server/cmd/multica/cmd_daemon.go healthPortForProfile.
+function healthPortForProfile(profile: string): number {
+ if (!profile) return DEFAULT_HEALTH_PORT;
+ let sum = 0;
+ for (const b of Buffer.from(profile, "utf-8")) sum += b;
+ return DEFAULT_HEALTH_PORT + 1 + (sum % 1000);
+}
+
+function profileDir(profile: string): string {
+ return profile
+ ? join(homedir(), ".multica", "profiles", profile)
+ : join(homedir(), ".multica");
+}
+
+function profileConfigPath(profile: string): string {
+ return join(profileDir(profile), "config.json");
+}
+
+function profileLogPath(profile: string): string {
+ return join(profileDir(profile), "daemon.log");
+}
+
+// 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
+// fresh PAT instead of reusing a token that belongs to a previous user.
+function profileUserIdPath(profile: string): string {
+ return join(profileDir(profile), ".desktop-user-id");
+}
+
+async function readProfileUserId(profile: string): Promise<string | null> {
+ try {
+ const raw = await readFile(profileUserIdPath(profile), "utf-8");
+ const trimmed = raw.trim();
+ return trimmed || null;
+ } catch {
+ return null;
+ }
+}
+
+async function writeProfileUserId(
+ profile: string,
+ userId: string,
+): Promise<void> {
+ await mkdir(profileDir(profile), { recursive: true });
+ await writeFile(profileUserIdPath(profile), userId, "utf-8");
+}
+
+async function removeProfileUserId(profile: string): Promise<void> {
+ try {
+ await rm(profileUserIdPath(profile));
+ } catch {
+ // Already gone — nothing to do.
+ }
+}
+
+function normalizeUrl(u: string): string {
+ if (!u) return "";
+ try {
+ const parsed = new URL(u);
+ return `${parsed.protocol}//${parsed.host}`.toLowerCase();
+ } catch {
+ return u.replace(/\/+$/, "").toLowerCase();
+ }
+}
+
+function urlsMatch(a: string, b: string): boolean {
+ const na = normalizeUrl(a);
+ const nb = normalizeUrl(b);
+ return na.length > 0 && na === nb;
+}
+
+function sendStatus(status: DaemonStatus): void {
+ const win = getMainWindow();
+ win?.webContents.send("daemon:status", status);
+}
+
+interface HealthPayload {
+ status?: string;
+ pid?: number;
+ uptime?: string;
+ daemon_id?: string;
+ device_name?: string;
+ server_url?: string;
+ agents?: string[];
+ workspaces?: unknown[];
+}
+
+async function fetchHealthAtPort(
+ port: number,
+): Promise<HealthPayload | null> {
+ 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;
+ }
+}
+
+// Desktop owns a dedicated CLI profile named after the target API host, so it
+// never reads or writes the user's hand-configured profiles. Profile dir:
+// ~/.multica/profiles/desktop-<host>/
+function deriveProfileName(targetUrl: string): string {
+ try {
+ const url = new URL(targetUrl);
+ const host = url.host.replace(/:/g, "-").toLowerCase();
+ return `desktop-${host}`;
+ } catch {
+ return "desktop";
+ }
+}
+
+async function readProfileConfig(
+ profile: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const raw = await readFile(profileConfigPath(profile), "utf-8");
+ const parsed = JSON.parse(raw);
+ return parsed && typeof parsed === "object" ? parsed : {};
+ } catch {
+ return {};
+ }
+}
+
+async function writeProfileConfig(
+ profile: string,
+ cfg: Record<string, unknown>,
+): Promise<void> {
+ const op = async () => {
+ await mkdir(profileDir(profile), { recursive: true });
+ await writeFile(
+ profileConfigPath(profile),
+ JSON.stringify(cfg, null, 2),
+ "utf-8",
+ );
+ };
+ const next = configWriteChain.catch(() => {}).then(op);
+ configWriteChain = next.catch(() => {});
+ return next;
+}
+
+/**
+ * Returns the Desktop-owned profile for the current target API URL. Creates
+ * the profile's config.json on demand with `server_url` pinned to the target.
+ *
+ * This function never falls back to the default profile, and never touches a
+ * profile whose name doesn't start with `desktop-`, so the user's manually
+ * configured CLI profiles are untouched.
+ */
+async function resolveActiveProfile(): Promise<ActiveProfile> {
+ const target = targetApiBaseUrl;
+ if (!target) return { name: "", port: DEFAULT_HEALTH_PORT };
+
+ const name = deriveProfileName(target);
+ const cfg = await readProfileConfig(name);
+
+ if (cfg.server_url !== target) {
+ cfg.server_url = target;
+ await writeProfileConfig(name, cfg);
+ console.log(`[daemon] initialized profile "${name}" → ${target}`);
+ }
+
+ return { name, port: healthPortForProfile(name) };
+}
+
+async function ensureActiveProfile(): Promise<ActiveProfile> {
+ if (activeProfile) return activeProfile;
+ activeProfile = await resolveActiveProfile();
+ return activeProfile;
+}
+
+function invalidateActiveProfile(): void {
+ activeProfile = null;
+}
+
+async function fetchHealth(): Promise<DaemonStatus> {
+ // While the CLI is being downloaded or has permanently failed, short-circuit
+ // polling — there's nothing to probe yet and /health calls would just return
+ // "stopped", which would overwrite the correct setup state in the UI.
+ if (currentState === "installing_cli" || currentState === "cli_not_found") {
+ return { state: currentState };
+ }
+
+ const active = await ensureActiveProfile();
+ const data = await fetchHealthAtPort(active.port);
+
+ if (!data || data.status !== "running") {
+ return {
+ state: currentState === "starting" ? "starting" : "stopped",
+ profile: active.name,
+ };
+ }
+
+ // 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 (
+ targetApiBaseUrl &&
+ data.server_url &&
+ !urlsMatch(data.server_url, targetApiBaseUrl)
+ ) {
+ invalidateActiveProfile();
+ return { state: "stopped" };
+ }
+
+ return {
+ state: "running",
+ pid: data.pid,
+ uptime: data.uptime,
+ daemonId: data.daemon_id,
+ deviceName: data.device_name,
+ agents: data.agents ?? [],
+ workspaceCount: Array.isArray(data.workspaces)
+ ? data.workspaces.length
+ : 0,
+ profile: active.name,
+ serverUrl: data.server_url,
+ };
+}
+
+function findCliOnPath(): string | null {
+ const candidates = process.platform === "win32" ? ["multica.exe"] : ["multica"];
+ const paths = (process.env["PATH"] ?? "").split(
+ process.platform === "win32" ? ";" : ":",
+ );
+ if (process.platform === "darwin") {
+ paths.push("/opt/homebrew/bin", "/usr/local/bin");
+ }
+ for (const name of candidates) {
+ for (const dir of paths) {
+ const full = join(dir, name);
+ if (existsSync(full)) return full;
+ }
+ }
+ return null;
+}
+
+/**
+ * Returns the path to the CLI binary bundled inside the Desktop app.
+ *
+ * - Dev (`electron-vite dev`): `app.getAppPath()` → `apps/desktop`, resolving
+ * to `apps/desktop/resources/bin/multica`. `bundle-cli.mjs` populates this
+ * before dev starts, so iterating on Go changes is "make build → restart".
+ * - Packaged: `app.getAppPath()` → `<Multica.app>/Contents/Resources/app.asar`.
+ * electron-builder's `asarUnpack: resources/**` extracts the binary to
+ * `app.asar.unpacked/`, so we swap the path segment to execute it.
+ */
+function bundledCliPath(): string {
+ const binName = process.platform === "win32" ? "multica.exe" : "multica";
+ return join(app.getAppPath(), "resources", "bin", binName).replace(
+ "app.asar",
+ "app.asar.unpacked",
+ );
+}
+
+/**
+ * Returns a usable `multica` binary path. Priority:
+ * 1. Cached result from a previous successful resolve.
+ * 2. Bundled binary shipped with the Desktop app (`bundle-cli.mjs`).
+ * 3. Managed binary already installed in userData (`managedCliPath`).
+ * 4. Download + install latest release into userData.
+ * 5. `multica` on PATH (dev convenience / user-installed via brew).
+ * Returns `null` only when all of the above fail.
+ *
+ * Bundled is preferred so Desktop iterates in lockstep with Go changes in
+ * the same repo — avoids the 404 / stale-API problem when the Desktop's
+ * TS side is ahead of the last published CLI release.
+ *
+ * This function is idempotent and safe to call concurrently — in-flight
+ * installs are de-duplicated via `cliResolvePromise`.
+ */
+async function resolveCliBinary(): Promise<string | null> {
+ if (cachedCliBinary !== undefined) return cachedCliBinary;
+ if (cliResolvePromise) return cliResolvePromise;
+
+ cliResolvePromise = (async () => {
+ const bundled = bundledCliPath();
+ if (existsSync(bundled)) {
+ console.log(`[daemon] using bundled CLI at ${bundled}`);
+ cachedCliBinary = bundled;
+ return bundled;
+ }
+
+ const managed = managedCliPath();
+ if (existsSync(managed)) {
+ cachedCliBinary = managed;
+ return managed;
+ }
+
+ try {
+ const installed = await ensureManagedCli();
+ cachedCliBinary = installed;
+ return installed;
+ } catch (err) {
+ console.warn("[daemon] CLI auto-install failed, falling back to PATH:", err);
+ const onPath = findCliOnPath();
+ cachedCliBinary = onPath;
+ return onPath;
+ }
+ })();
+
+ try {
+ return await cliResolvePromise;
+ } finally {
+ cliResolvePromise = null;
+ }
+}
+
+/**
+ * Exchange the user's JWT for a long-lived PAT via POST /api/tokens. The
+ * daemon needs a PAT (or `mul_` / `mdt_` token) because JWTs expire in 30
+ * days and signatures are tied to a specific backend instance.
+ */
+async function mintPat(jwt: string): Promise<string> {
+ if (!targetApiBaseUrl) {
+ throw new Error("mint PAT: target API URL not set");
+ }
+ const url = `${targetApiBaseUrl.replace(/\/+$/, "")}/api/tokens`;
+ const res = await fetch(url, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${jwt}`,
+ },
+ // Omit expires_in_days → server treats as null → non-expiring PAT.
+ body: JSON.stringify({ name: "Multica Desktop" }),
+ });
+ if (!res.ok) {
+ const body = await res.text().catch(() => "");
+ throw new Error(`mint PAT failed: ${res.status} ${res.statusText} ${body}`);
+ }
+ const data = (await res.json()) as { token?: unknown };
+ if (typeof data.token !== "string" || !data.token.startsWith("mul_")) {
+ throw new Error("mint PAT: response missing token");
+ }
+ return data.token;
+}
+
+/**
+ * Ensure the active profile's config.json has a usable token for the daemon.
+ *
+ * - Input from the renderer is the user's JWT (from localStorage) plus the
+ * current user's id, so we can detect session changes.
+ * - If the profile already has a cached PAT (`mul_...`) AND the sidecar user
+ * id matches the caller, reuse it — minting fresh on every launch would
+ * accumulate garbage in the user's tokens page.
+ * - On user mismatch (or first run) call POST /api/tokens with the JWT to
+ * 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).
+ */
+async function syncToken(
+ tokenFromRenderer: string,
+ userId: string,
+): Promise<void> {
+ const active = await ensureActiveProfile();
+ const config = await readProfileConfig(active.name);
+ const previousUserId = await readProfileUserId(active.name);
+ const userChanged = Boolean(previousUserId) && previousUserId !== userId;
+ const sameUserWithCachedPat =
+ !userChanged &&
+ previousUserId === userId &&
+ typeof config.token === "string" &&
+ config.token.startsWith("mul_");
+
+ let finalToken: string;
+ if (tokenFromRenderer.startsWith("mul_")) {
+ finalToken = tokenFromRenderer;
+ } else if (sameUserWithCachedPat) {
+ finalToken = config.token as string;
+ } else {
+ try {
+ finalToken = await mintPat(tokenFromRenderer);
+ console.log(
+ `[daemon] minted PAT for profile "${active.name}" (user_changed=${userChanged})`,
+ );
+ } catch (err) {
+ console.error("[daemon] failed to mint PAT:", err);
+ throw err;
+ }
+ }
+
+ config.token = finalToken;
+ if (targetApiBaseUrl) config.server_url = targetApiBaseUrl;
+ await writeProfileConfig(active.name, config);
+ await writeProfileUserId(active.name, userId);
+
+ // 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 (existing?.status === "running") {
+ console.log(
+ "[daemon] user switched — restarting daemon with new credentials",
+ );
+ void restartDaemon();
+ }
+ } catch (err) {
+ console.warn("[daemon] restart-on-user-switch failed:", err);
+ }
+ }
+}
+
+async function loadPrefs(): Promise<DaemonPrefs> {
+ try {
+ const raw = await readFile(PREFS_PATH, "utf-8");
+ const parsed = JSON.parse(raw);
+ return { ...DEFAULT_PREFS, ...parsed };
+ } catch {
+ return { ...DEFAULT_PREFS };
+ }
+}
+
+async function savePrefs(prefs: DaemonPrefs): Promise<void> {
+ const dir = join(homedir(), ".multica");
+ await mkdir(dir, { recursive: true });
+ await writeFile(PREFS_PATH, JSON.stringify(prefs, null, 2), "utf-8");
+}
+
+async function clearToken(): Promise<void> {
+ const active = await ensureActiveProfile();
+ const config = await readProfileConfig(active.name);
+ if ("token" in config) {
+ delete config.token;
+ await writeProfileConfig(active.name, config);
+ }
+ // Always drop the sidecar so a subsequent syncToken from any user is
+ // treated as a fresh mint, not a reuse of a stale cached PAT.
+ await removeProfileUserId(active.name);
+}
+
+interface WatchedWorkspace {
+ id: string;
+ name: string;
+ runtime_count?: number;
+}
+
+interface WatchListResponse {
+ watched: WatchedWorkspace[];
+ unwatched: string[];
+}
+
+async function daemonFetch(
+ path: string,
+ init?: RequestInit,
+): Promise<Response> {
+ const active = await ensureActiveProfile();
+ const url = `http://127.0.0.1:${active.port}${path}`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10_000);
+ try {
+ return await fetch(url, { ...init, signal: controller.signal });
+ } finally {
+ clearTimeout(timeout);
+ }
+}
+
+async function listWatchedWorkspaces(): Promise<WatchListResponse> {
+ const empty: WatchListResponse = { watched: [], unwatched: [] };
+ try {
+ const res = await daemonFetch("/watch");
+ if (!res.ok) {
+ // Older daemon versions don't have /watch. Treat as "nothing watched
+ // yet" so the UI renders cleanly; the user can take manual action.
+ if (res.status === 404) return empty;
+ throw new Error(`list /watch failed: ${res.status} ${res.statusText}`);
+ }
+ const data = (await res.json()) as WatchListResponse;
+ return {
+ watched: Array.isArray(data.watched) ? data.watched : [],
+ unwatched: Array.isArray(data.unwatched) ? data.unwatched : [],
+ };
+ } catch (err) {
+ // Network errors (ECONNREFUSED when daemon is still starting, etc.) are
+ // expected during startup races — return empty instead of throwing so
+ // we don't spam the main-process error log on every poll.
+ const msg = err instanceof Error ? err.message : String(err);
+ console.log(`[daemon] list /watch unreachable: ${msg}`);
+ return empty;
+ }
+}
+
+async function watchWorkspace(id: string, name: string): Promise<void> {
+ const res = await daemonFetch("/watch", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ workspace_id: id, name }),
+ });
+ if (!res.ok) {
+ const body = await res.text().catch(() => "");
+ throw new Error(`watch failed: ${res.status} ${body}`);
+ }
+}
+
+async function unwatchWorkspace(id: string): Promise<void> {
+ const res = await daemonFetch(`/watch/${encodeURIComponent(id)}`, {
+ method: "DELETE",
+ });
+ if (!res.ok) {
+ const body = await res.text().catch(() => "");
+ throw new Error(`unwatch failed: ${res.status} ${body}`);
+ }
+}
+
+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 profileArgs(active: ActiveProfile): string[] {
+ return active.name ? ["--profile", active.name] : [];
+}
+
+// Env passed to every CLI child so the daemon process knows it was spawned
+// by the Desktop app. The server uses this to mark runtimes as managed and
+// hide CLI self-update UI.
+const DESKTOP_SPAWN_ENV = {
+ ...process.env,
+ MULTICA_LAUNCHED_BY: "desktop",
+};
+
+async function startDaemon(): Promise<{ success: boolean; error?: string }> {
+ const bin = await resolveCliBinary();
+ if (!bin) return { success: false, error: "multica CLI is not installed" };
+
+ const active = await ensureActiveProfile();
+ const existing = await fetchHealthAtPort(active.port);
+ if (existing?.status === "running") {
+ pollOnce();
+ return { success: true };
+ }
+
+ currentState = "starting";
+ sendStatus({ state: "starting" });
+
+ const args = ["daemon", "start", ...profileArgs(active)];
+
+ return new Promise((resolve) => {
+ execFile(
+ bin,
+ args,
+ { timeout: 20_000, env: DESKTOP_SPAWN_ENV },
+ (err) => {
+ if (err) {
+ currentState = "stopped";
+ sendStatus({ state: "stopped" });
+ resolve({ success: false, error: err.message });
+ return;
+ }
+ // 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();
+ resolve({ success: true });
+ },
+ );
+ });
+}
+
+async function stopDaemon(): Promise<{ success: boolean; error?: string }> {
+ const bin = await resolveCliBinary();
+ if (!bin) return { success: false, error: "multica CLI is not installed" };
+
+ const active = await ensureActiveProfile();
+ currentState = "stopping";
+ sendStatus({ state: "stopping" });
+
+ const args = ["daemon", "stop", ...profileArgs(active)];
+
+ return new Promise((resolve) => {
+ execFile(bin, args, { timeout: 15_000 }, (err) => {
+ if (err) {
+ resolve({ success: false, error: err.message });
+ } else {
+ resolve({ success: true });
+ }
+ currentState = "stopped";
+ sendStatus({ state: "stopped" });
+ });
+ });
+}
+
+async function restartDaemon(): Promise<{ success: boolean; error?: string }> {
+ const stopResult = await stopDaemon();
+ if (!stopResult.success) return stopResult;
+ return startDaemon();
+}
+
+async function pollOnce(): Promise<void> {
+ const status = await fetchHealth();
+ currentState = status.state;
+ sendStatus(status);
+}
+
+function startPolling(): void {
+ if (statusPollTimer) return;
+ pollOnce();
+ statusPollTimer = setInterval(pollOnce, POLL_INTERVAL_MS);
+}
+
+/**
+ * Ensures the CLI binary is available, then transitions into the normal
+ * stopped/running state machine. Called once at startup and again on
+ * user-triggered `daemon:retry-install`.
+ */
+async function bootstrapCli(): Promise<void> {
+ const bin = await resolveCliBinary();
+ if (!bin) {
+ currentState = "cli_not_found";
+ sendStatus({ state: "cli_not_found" });
+ return;
+ }
+ currentState = "stopped";
+ sendStatus({ state: "stopped" });
+ startPolling();
+}
+
+function stopPolling(): void {
+ if (statusPollTimer) {
+ clearInterval(statusPollTimer);
+ statusPollTimer = null;
+ }
+}
+
+const LOG_TAIL_INITIAL_WINDOW_BYTES = 32 * 1024;
+const LOG_TAIL_INITIAL_LINES = 200;
+const LOG_TAIL_POLL_MS = 500;
+
+async function readLogRange(
+ path: string,
+ startAt: number,
+ length: number,
+): Promise<string> {
+ const handle = await open(path, "r");
+ try {
+ const buffer = Buffer.alloc(length);
+ const { bytesRead } = await handle.read(buffer, 0, length, startAt);
+ return buffer.subarray(0, bytesRead).toString("utf-8");
+ } finally {
+ await handle.close();
+ }
+}
+
+function sendLines(win: BrowserWindow, text: string): void {
+ const lines = text.split("\n").filter((line) => line.length > 0);
+ for (const line of lines) {
+ win.webContents.send("daemon:log-line", line);
+ }
+}
+
+// Cross-platform tail -f replacement: read the tail of the file once, then
+// poll its stat with fs.watchFile and forward any new bytes since the last
+// known offset. watchFile works on macOS, Linux, and Windows; spawn("tail")
+// would silently fail on Windows.
+function startLogTail(win: BrowserWindow, retryCount = 0): void {
+ stopLogTail();
+
+ void ensureActiveProfile().then(async (active) => {
+ const logPath = profileLogPath(active.name);
+ if (!existsSync(logPath)) {
+ if (retryCount < LOG_TAIL_MAX_RETRIES) {
+ setTimeout(() => startLogTail(win, retryCount + 1), LOG_TAIL_RETRY_MS);
+ }
+ return;
+ }
+
+ let position = 0;
+ try {
+ const initialStats = await stat(logPath);
+ const windowBytes = Math.min(
+ initialStats.size,
+ LOG_TAIL_INITIAL_WINDOW_BYTES,
+ );
+ const startAt = initialStats.size - windowBytes;
+ if (windowBytes > 0) {
+ const text = await readLogRange(logPath, startAt, windowBytes);
+ const lines = text
+ .split("\n")
+ .filter((line) => line.length > 0)
+ .slice(-LOG_TAIL_INITIAL_LINES);
+ for (const line of lines) {
+ win.webContents.send("daemon:log-line", line);
+ }
+ }
+ position = initialStats.size;
+ } catch (err) {
+ console.warn("[daemon] log tail initial read failed:", err);
+ return;
+ }
+
+ const listener: StatsListener = (curr) => {
+ const target = getMainWindow();
+ if (!target) return;
+ // File rotated/truncated — restart from the new beginning.
+ if (curr.size < position) position = 0;
+ if (curr.size === position) return;
+ const from = position;
+ const length = curr.size - from;
+ position = curr.size;
+ readLogRange(logPath, from, length)
+ .then((text) => sendLines(target, text))
+ .catch((err) => {
+ console.warn("[daemon] log tail read failed:", err);
+ });
+ };
+
+ watchFile(logPath, { interval: LOG_TAIL_POLL_MS }, listener);
+ logTailWatcher = { path: logPath, listener };
+ });
+}
+
+function stopLogTail(): void {
+ if (logTailWatcher) {
+ unwatchFile(logTailWatcher.path, logTailWatcher.listener);
+ logTailWatcher = null;
+ }
+}
+
+export function setupDaemonManager(
+ windowGetter: () => BrowserWindow | null,
+): void {
+ getMainWindow = windowGetter;
+
+ ipcMain.handle("daemon:set-target-api-url", async (_e, url: string) => {
+ const normalized = url || null;
+ if (targetApiBaseUrl !== normalized) {
+ console.log(`[daemon] target API URL set to ${normalized ?? "(none)"}`);
+ 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:get-status", () => fetchHealth());
+ ipcMain.handle(
+ "daemon:sync-token",
+ (_event, token: string, userId: string) => syncToken(token, userId),
+ );
+ ipcMain.handle("daemon:clear-token", () => clearToken());
+ ipcMain.handle("daemon:list-watched", () => listWatchedWorkspaces());
+ ipcMain.handle(
+ "daemon:watch-workspace",
+ (_event, id: string, name: string) => watchWorkspace(id, name),
+ );
+ ipcMain.handle("daemon:unwatch-workspace", (_event, id: string) =>
+ unwatchWorkspace(id),
+ );
+ ipcMain.handle("daemon:is-cli-installed", async () => {
+ const bin = await resolveCliBinary();
+ return bin !== null;
+ });
+ ipcMain.handle("daemon:retry-install", async () => {
+ cachedCliBinary = undefined;
+ cliResolvePromise = null;
+ await bootstrapCli();
+ });
+ ipcMain.handle("daemon:get-prefs", () => loadPrefs());
+ ipcMain.handle(
+ "daemon:set-prefs",
+ (_event, prefs: Partial<DaemonPrefs>) =>
+ loadPrefs().then((cur) => {
+ const merged = { ...cur, ...prefs };
+ return savePrefs(merged).then(() => merged);
+ }),
+ );
+ ipcMain.handle("daemon:auto-start", async () => {
+ const prefs = await loadPrefs();
+ if (!prefs.autoStart) return;
+ const bin = await resolveCliBinary();
+ if (!bin) return;
+ const health = await fetchHealth();
+ if (health.state === "running") return;
+ await startDaemon();
+ });
+
+ ipcMain.on("daemon:start-log-stream", () => {
+ const win = getMainWindow();
+ if (win) startLogTail(win);
+ });
+
+ ipcMain.on("daemon:stop-log-stream", () => {
+ stopLogTail();
+ });
+
+ // First-run CLI install kicks off here. Status bar shows "Setting up…"
+ // until the managed binary is on disk (instant on subsequent launches).
+ currentState = "installing_cli";
+ sendStatus({ state: "installing_cli" });
+ void bootstrapCli();
+
+ let isQuitting = false;
+ app.on("before-quit", (event) => {
+ if (isQuitting) return;
+ stopPolling();
+ stopLogTail();
+
+ loadPrefs().then(async (prefs) => {
+ if (prefs.autoStop) {
+ isQuitting = true;
+ event.preventDefault();
+ try {
+ await stopDaemon();
+ } catch {
+ // Best-effort stop on quit
+ }
+ app.quit();
+ }
+ });
+ });
+}
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 3fae852f9a..a93828e123 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -2,6 +2,7 @@ import { app, shell, BrowserWindow, ipcMain } from "electron";
import { join } from "path";
import { electronApp, optimizer, is } from "@electron-toolkit/utils";
import { setupAutoUpdater } from "./updater";
+import { setupDaemonManager } from "./daemon-manager";
const PROTOCOL = "multica";
@@ -116,6 +117,7 @@ if (!gotTheLock) {
createWindow();
setupAutoUpdater(() => mainWindow);
+ setupDaemonManager(() => mainWindow);
// macOS: deep link arrives via open-url event
app.on("open-url", (_event, url) => {
diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.ts
index d15c31f37f..d009486979 100644
--- a/apps/desktop/src/preload/index.d.ts
+++ b/apps/desktop/src/preload/index.d.ts
@@ -7,6 +7,48 @@ interface DesktopAPI {
openExternal: (url: string) => Promise<void>;
}
+interface DaemonStatus {
+ state: "running" | "stopped" | "starting" | "stopping" | "installing_cli" | "cli_not_found";
+ pid?: number;
+ uptime?: string;
+ daemonId?: string;
+ deviceName?: string;
+ agents?: string[];
+ workspaceCount?: number;
+ profile?: string;
+ serverUrl?: string;
+}
+
+interface DaemonPrefs {
+ autoStart: boolean;
+ autoStop: boolean;
+}
+
+interface DaemonAPI {
+ start: () => Promise<{ success: boolean; error?: string }>;
+ stop: () => Promise<{ success: boolean; error?: string }>;
+ restart: () => Promise<{ success: boolean; error?: string }>;
+ getStatus: () => Promise<DaemonStatus>;
+ onStatusChange: (callback: (status: DaemonStatus) => void) => () => void;
+ setTargetApiUrl: (url: string) => Promise<void>;
+ syncToken: (token: string, userId: string) => Promise<void>;
+ clearToken: () => Promise<void>;
+ listWatched: () => Promise<{
+ watched: Array<{ id: string; name: string; runtime_count?: number }>;
+ unwatched: string[];
+ }>;
+ watchWorkspace: (id: string, name: string) => Promise<void>;
+ unwatchWorkspace: (id: string) => Promise<void>;
+ isCliInstalled: () => Promise<boolean>;
+ getPrefs: () => Promise<DaemonPrefs>;
+ setPrefs: (prefs: Partial<DaemonPrefs>) => Promise<DaemonPrefs>;
+ autoStart: () => Promise<void>;
+ retryInstall: () => Promise<void>;
+ startLogStream: () => void;
+ stopLogStream: () => void;
+ onLogLine: (callback: (line: string) => void) => () => void;
+}
+
interface UpdaterAPI {
onUpdateAvailable: (callback: (info: { version: string; releaseNotes?: string }) => void) => () => void;
onDownloadProgress: (callback: (progress: { percent: number }) => void) => () => void;
@@ -19,6 +61,7 @@ declare global {
interface Window {
electron: ElectronAPI;
desktopAPI: DesktopAPI;
+ daemonAPI: DaemonAPI;
updater: UpdaterAPI;
}
}
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 470e4ac585..dcdaee9dd7 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -15,6 +15,65 @@ const desktopAPI = {
openExternal: (url: string) => ipcRenderer.invoke("shell:openExternal", url),
};
+interface DaemonStatus {
+ state: "running" | "stopped" | "starting" | "stopping" | "installing_cli" | "cli_not_found";
+ pid?: number;
+ uptime?: string;
+ daemonId?: string;
+ deviceName?: string;
+ agents?: string[];
+ workspaceCount?: number;
+ profile?: string;
+ serverUrl?: string;
+}
+
+const daemonAPI = {
+ start: (): Promise<{ success: boolean; error?: string }> =>
+ ipcRenderer.invoke("daemon:start"),
+ stop: (): Promise<{ success: boolean; error?: string }> =>
+ ipcRenderer.invoke("daemon:stop"),
+ restart: (): Promise<{ success: boolean; error?: string }> =>
+ ipcRenderer.invoke("daemon:restart"),
+ getStatus: (): Promise<DaemonStatus> =>
+ ipcRenderer.invoke("daemon:get-status"),
+ onStatusChange: (callback: (status: DaemonStatus) => void) => {
+ const handler = (_: unknown, status: DaemonStatus) => callback(status);
+ ipcRenderer.on("daemon:status", handler);
+ return () => ipcRenderer.removeListener("daemon:status", handler);
+ },
+ setTargetApiUrl: (url: string): Promise<void> =>
+ ipcRenderer.invoke("daemon:set-target-api-url", url),
+ syncToken: (token: string, userId: string): Promise<void> =>
+ ipcRenderer.invoke("daemon:sync-token", token, userId),
+ clearToken: (): Promise<void> =>
+ ipcRenderer.invoke("daemon:clear-token"),
+ listWatched: (): Promise<{
+ watched: Array<{ id: string; name: string; runtime_count?: number }>;
+ unwatched: string[];
+ }> => ipcRenderer.invoke("daemon:list-watched"),
+ watchWorkspace: (id: string, name: string): Promise<void> =>
+ ipcRenderer.invoke("daemon:watch-workspace", id, name),
+ unwatchWorkspace: (id: string): Promise<void> =>
+ ipcRenderer.invoke("daemon:unwatch-workspace", id),
+ isCliInstalled: (): Promise<boolean> =>
+ ipcRenderer.invoke("daemon:is-cli-installed"),
+ getPrefs: (): Promise<{ autoStart: boolean; autoStop: boolean }> =>
+ ipcRenderer.invoke("daemon:get-prefs"),
+ setPrefs: (prefs: Partial<{ autoStart: boolean; autoStop: boolean }>): Promise<{ autoStart: boolean; autoStop: boolean }> =>
+ ipcRenderer.invoke("daemon:set-prefs", prefs),
+ autoStart: (): Promise<void> =>
+ ipcRenderer.invoke("daemon:auto-start"),
+ retryInstall: (): Promise<void> =>
+ ipcRenderer.invoke("daemon:retry-install"),
+ startLogStream: () => ipcRenderer.send("daemon:start-log-stream"),
+ stopLogStream: () => ipcRenderer.send("daemon:stop-log-stream"),
+ onLogLine: (callback: (line: string) => void) => {
+ const handler = (_: unknown, line: string) => callback(line);
+ ipcRenderer.on("daemon:log-line", handler);
+ return () => ipcRenderer.removeListener("daemon:log-line", handler);
+ },
+};
+
const updaterAPI = {
onUpdateAvailable: (callback: (info: { version: string; releaseNotes?: string }) => void) => {
const handler = (_: unknown, info: { version: string; releaseNotes?: string }) => callback(info);
@@ -38,6 +97,7 @@ const updaterAPI = {
if (process.contextIsolated) {
contextBridge.exposeInMainWorld("electron", electronAPI);
contextBridge.exposeInMainWorld("desktopAPI", desktopAPI);
+ contextBridge.exposeInMainWorld("daemonAPI", daemonAPI);
contextBridge.exposeInMainWorld("updater", updaterAPI);
} else {
// @ts-expect-error - fallback for non-isolated context
@@ -45,5 +105,7 @@ if (process.contextIsolated) {
// @ts-expect-error - fallback for non-isolated context
window.desktopAPI = desktopAPI;
// @ts-expect-error - fallback for non-isolated context
+ window.daemonAPI = daemonAPI;
+ // @ts-expect-error - fallback for non-isolated context
window.updater = updaterAPI;
}
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsx
index 8702a475aa..bcc4dbd37c 100644
--- a/apps/desktop/src/renderer/src/App.tsx
+++ b/apps/desktop/src/renderer/src/App.tsx
@@ -1,7 +1,8 @@
-import { useEffect } from "react";
+import { useEffect, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
import { CoreProvider } from "@multica/core/platform";
import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { useWorkspaceStore, workspaceListOptions } from "@multica/core/workspace";
import { api } from "@multica/core/api";
import { ThemeProvider } from "@multica/ui/components/common/theme-provider";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
@@ -13,12 +14,33 @@ import { UpdateNotification } from "./components/update-notification";
function AppContent() {
const user = useAuthStore((s) => s.user);
const isLoading = useAuthStore((s) => s.isLoading);
+ const [daemonRunning, setDaemonRunning] = useState(false);
+
+ // Tell the main process which backend URL we talk to, so daemon-manager
+ // can pick the matching CLI profile (server_url from ~/.multica config).
+ useEffect(() => {
+ window.daemonAPI.setTargetApiUrl(DAEMON_TARGET_API_URL);
+ }, []);
+
+ // Track daemon lifecycle so workspace reconciliation only runs when the
+ // daemon is actually listening — avoids a startup race where the reconcile
+ // effect fires before autoStart has spawned the child process.
+ useEffect(() => {
+ const unsub = window.daemonAPI.onStatusChange((s) => {
+ setDaemonRunning(s.state === "running");
+ });
+ window.daemonAPI.getStatus().then((s) => {
+ setDaemonRunning(s.state === "running");
+ });
+ return unsub;
+ }, []);
// Listen for auth token delivered via deep link (multica://auth/callback?token=...)
useEffect(() => {
return window.desktopAPI.onAuthToken(async (token) => {
try {
- await useAuthStore.getState().loginWithToken(token);
+ const loggedIn = await useAuthStore.getState().loginWithToken(token);
+ await window.daemonAPI.syncToken(token, loggedIn.id);
const wsList = await api.listWorkspaces();
const lastWsId = localStorage.getItem("multica_workspace_id");
useWorkspaceStore.getState().hydrateWorkspace(wsList, lastWsId);
@@ -28,6 +50,64 @@ function AppContent() {
});
}, []);
+ // Sync token and start the daemon whenever the user logs in.
+ useEffect(() => {
+ if (!user) return;
+ const token = localStorage.getItem("multica_token");
+ if (!token) return;
+ const userId = user.id;
+ (async () => {
+ try {
+ await window.daemonAPI.syncToken(token, userId);
+ await window.daemonAPI.autoStart();
+ } catch (err) {
+ console.error("Failed to sync daemon on login", err);
+ }
+ })();
+ }, [user]);
+
+ // Reconcile the daemon's watched workspaces with what the user is a member
+ // of. The query already hydrates on login and invalidates on create/delete
+ // mutations, so this one effect covers both initial sync and incremental
+ // updates. Opt-outs (unwatched denylist) are respected.
+ const { data: workspaces } = useQuery({
+ ...workspaceListOptions(),
+ enabled: !!user,
+ });
+ const lastSyncedIds = useRef<Set<string>>(new Set());
+ useEffect(() => {
+ if (!user || !workspaces || !daemonRunning) return;
+ (async () => {
+ const state = await window.daemonAPI.listWatched().catch(() => null);
+ if (!state) return;
+ const watchedIds = new Set(state.watched.map((w) => w.id));
+ const unwatchedIds = new Set(state.unwatched);
+ const currentIds = new Set(workspaces.map((w) => w.id));
+
+ // Add: anything in the API list but not yet watched (and not opted out).
+ for (const ws of workspaces) {
+ if (watchedIds.has(ws.id) || unwatchedIds.has(ws.id)) continue;
+ try {
+ await window.daemonAPI.watchWorkspace(ws.id, ws.name);
+ } catch (err) {
+ console.warn("watch workspace failed", ws.id, err);
+ }
+ }
+ // Remove: anything we previously synced that is no longer in the API
+ // list (the user left or deleted it).
+ for (const prevId of lastSyncedIds.current) {
+ if (!currentIds.has(prevId)) {
+ try {
+ await window.daemonAPI.unwatchWorkspace(prevId);
+ } catch (err) {
+ console.warn("unwatch workspace failed", prevId, err);
+ }
+ }
+ }
+ lastSyncedIds.current = currentIds;
+ })();
+ }, [user, workspaces, daemonRunning]);
+
if (isLoading) {
return (
<div className="flex h-screen items-center justify-center">
@@ -41,6 +121,29 @@ function AppContent() {
}
const remoteProxy = Boolean(import.meta.env.VITE_REMOTE_API);
+// Backend the daemon should connect to. In remote-proxy mode the renderer
+// talks through a local Vite proxy, but the daemon needs the real upstream
+// URL — which is what VITE_REMOTE_API holds. Fall back to VITE_API_URL
+// (direct mode) and finally localhost:8080 (local dev default).
+const DAEMON_TARGET_API_URL =
+ import.meta.env.VITE_REMOTE_API ||
+ import.meta.env.VITE_API_URL ||
+ "http://localhost:8080";
+
+// On logout, clear any cached PAT and stop the daemon so that a subsequent
+// login as a different user never inherits the previous user's credentials.
+async function handleDaemonLogout() {
+ try {
+ await window.daemonAPI.clearToken();
+ } catch {
+ // Best-effort — clearing is followed by stop which also hardens state.
+ }
+ try {
+ await window.daemonAPI.stop();
+ } catch {
+ // Daemon may already be stopped.
+ }
+}
export default function App() {
return (
@@ -48,6 +151,7 @@ export default function App() {
<CoreProvider
apiBaseUrl={remoteProxy ? "" : (import.meta.env.VITE_API_URL || "http://localhost:8080")}
wsUrl={remoteProxy ? "ws://localhost:5173/ws" : (import.meta.env.VITE_WS_URL || "ws://localhost:8080/ws")}
+ onLogout={handleDaemonLogout}
>
<AppContent />
</CoreProvider>
diff --git a/apps/desktop/src/renderer/src/components/daemon-panel.tsx b/apps/desktop/src/renderer/src/components/daemon-panel.tsx
new file mode 100644
index 0000000000..ade57c95e7
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/daemon-panel.tsx
@@ -0,0 +1,384 @@
+import { useState, useEffect, useRef, useCallback } from "react";
+import {
+ Play,
+ Square,
+ RotateCw,
+ Server,
+ ChevronDown,
+ X,
+} from "lucide-react";
+import { useQuery } from "@tanstack/react-query";
+import { workspaceListOptions } from "@multica/core/workspace";
+import { cn } from "@multica/ui/lib/utils";
+import { Button } from "@multica/ui/components/ui/button";
+import { Checkbox } from "@multica/ui/components/ui/checkbox";
+import { toast } from "sonner";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+} from "@multica/ui/components/ui/sheet";
+import type { DaemonStatus, DaemonState } from "../../../shared/daemon-types";
+import { DAEMON_STATE_COLORS, DAEMON_STATE_LABELS } from "../../../shared/daemon-types";
+
+interface DaemonPanelProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ status: DaemonStatus;
+}
+
+const LOG_LEVEL_COLORS: Record<string, string> = {
+ INFO: "text-info",
+ WARN: "text-warning",
+ ERROR: "text-destructive",
+ DEBUG: "text-muted-foreground",
+};
+
+function colorizeLogLine(line: string): { level: string; className: string } {
+ for (const [level, className] of Object.entries(LOG_LEVEL_COLORS)) {
+ if (line.includes(level)) return { level, className };
+ }
+ return { level: "", className: "text-muted-foreground" };
+}
+
+function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
+ return (
+ <div className="flex items-baseline justify-between gap-4 py-1">
+ <span className="shrink-0 text-xs text-muted-foreground">{label}</span>
+ <span className="truncate text-right text-sm">{value}</span>
+ </div>
+ );
+}
+
+function StatusDot({ state }: { state: DaemonState }) {
+ return <span className={cn("inline-block size-2 rounded-full", DAEMON_STATE_COLORS[state])} />;
+}
+
+interface LogEntry {
+ id: number;
+ line: string;
+}
+
+const MAX_LOG_LINES = 500;
+let logIdCounter = 0;
+
+export function DaemonPanel({ open, onOpenChange, status }: DaemonPanelProps) {
+ const [logs, setLogs] = useState<LogEntry[]>([]);
+ const [autoScroll, setAutoScroll] = useState(true);
+ const [actionLoading, setActionLoading] = useState(false);
+ const logContainerRef = useRef<HTMLDivElement>(null);
+
+ // Watched workspaces — populated from the daemon when the panel opens and
+ // refreshed after every toggle so the checkbox state reflects reality.
+ const { data: allWorkspaces } = useQuery({
+ ...workspaceListOptions(),
+ enabled: open,
+ });
+ const [watchedIds, setWatchedIds] = useState<Set<string>>(new Set());
+ const [togglingId, setTogglingId] = useState<string | null>(null);
+
+ const refreshWatched = useCallback(async () => {
+ const state = await window.daemonAPI.listWatched().catch(() => null);
+ if (state) setWatchedIds(new Set(state.watched.map((w) => w.id)));
+ }, []);
+
+ useEffect(() => {
+ if (open && status.state === "running") void refreshWatched();
+ }, [open, status.state, refreshWatched]);
+
+ const handleToggleWatch = useCallback(
+ async (id: string, name: string, nextChecked: boolean) => {
+ setTogglingId(id);
+ try {
+ if (nextChecked) {
+ await window.daemonAPI.watchWorkspace(id, name);
+ } else {
+ await window.daemonAPI.unwatchWorkspace(id);
+ }
+ await refreshWatched();
+ } catch (err) {
+ toast.error(
+ nextChecked ? "Failed to watch workspace" : "Failed to unwatch workspace",
+ { description: err instanceof Error ? err.message : String(err) },
+ );
+ } finally {
+ setTogglingId(null);
+ }
+ },
+ [refreshWatched],
+ );
+
+ useEffect(() => {
+ if (!open) return;
+
+ window.daemonAPI.startLogStream();
+ const unsub = window.daemonAPI.onLogLine((line) => {
+ setLogs((prev) => {
+ const next = [...prev, { id: ++logIdCounter, line }];
+ return next.length > MAX_LOG_LINES ? next.slice(-MAX_LOG_LINES) : next;
+ });
+ });
+
+ return () => {
+ unsub();
+ window.daemonAPI.stopLogStream();
+ };
+ }, [open]);
+
+ useEffect(() => {
+ if (autoScroll && logContainerRef.current) {
+ logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
+ }
+ }, [logs, autoScroll]);
+
+ const handleLogScroll = useCallback(() => {
+ const el = logContainerRef.current;
+ if (!el) return;
+ const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
+ setAutoScroll(atBottom);
+ }, []);
+
+ const scrollToBottom = useCallback(() => {
+ if (logContainerRef.current) {
+ logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
+ setAutoScroll(true);
+ }
+ }, []);
+
+ const handleStart = useCallback(async () => {
+ setActionLoading(true);
+ const result = await window.daemonAPI.start();
+ setActionLoading(false);
+ if (!result.success) {
+ toast.error("Failed to start daemon", { description: result.error });
+ }
+ }, []);
+
+ const handleStop = useCallback(async () => {
+ setActionLoading(true);
+ const result = await window.daemonAPI.stop();
+ setActionLoading(false);
+ if (!result.success) {
+ toast.error("Failed to stop daemon", { description: result.error });
+ }
+ }, []);
+
+ const handleRestart = useCallback(async () => {
+ setActionLoading(true);
+ const result = await window.daemonAPI.restart();
+ setActionLoading(false);
+ if (!result.success) {
+ toast.error("Failed to restart daemon", { description: result.error });
+ }
+ }, []);
+
+ const isTransitioning = status.state === "starting" || status.state === "stopping";
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent
+ side="right"
+ className="flex flex-col sm:max-w-md"
+ showCloseButton={false}
+ style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
+ >
+ <SheetHeader className="flex-row items-center justify-between gap-2 pr-3">
+ <SheetTitle className="flex items-center gap-2">
+ <Server className="size-4" />
+ Local Daemon
+ </SheetTitle>
+ <button
+ type="button"
+ onClick={() => onOpenChange(false)}
+ aria-label="Close"
+ className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <X className="size-4" />
+ </button>
+ </SheetHeader>
+
+ <div className="flex-1 min-h-0 flex flex-col gap-4 px-4">
+ <div className="shrink-0 space-y-4">
+ {/* Status info */}
+ <div className="rounded-lg border p-3 space-y-0.5">
+ <InfoRow
+ label="Status"
+ value={
+ <span className="flex items-center gap-1.5">
+ <StatusDot state={status.state} />
+ {DAEMON_STATE_LABELS[status.state]}
+ </span>
+ }
+ />
+ {status.uptime && <InfoRow label="Uptime" value={status.uptime} />}
+ <InfoRow label="Profile" value={status.profile || "default"} />
+ {status.serverUrl && (
+ <InfoRow
+ label="Server"
+ value={
+ <span className="font-mono text-xs" title={status.serverUrl}>
+ {status.serverUrl}
+ </span>
+ }
+ />
+ )}
+ {status.agents && status.agents.length > 0 && (
+ <InfoRow label="Agents" value={status.agents.join(", ")} />
+ )}
+ {status.deviceName && <InfoRow label="Device" value={status.deviceName} />}
+ {status.daemonId && (
+ <InfoRow
+ label="Daemon ID"
+ value={<span className="font-mono text-xs">{status.daemonId}</span>}
+ />
+ )}
+ {typeof status.workspaceCount === "number" && (
+ <InfoRow label="Workspaces" value={status.workspaceCount} />
+ )}
+ {status.pid && (
+ <InfoRow
+ label="PID"
+ value={<span className="font-mono text-xs">{status.pid}</span>}
+ />
+ )}
+ </div>
+
+ {/* Actions */}
+ {status.state === "installing_cli" ? (
+ <div className="rounded-lg border border-dashed p-3 text-sm text-muted-foreground">
+ Setting up the local runtime… this only happens the first time.
+ </div>
+ ) : status.state === "cli_not_found" ? (
+ <div className="rounded-lg border border-destructive/40 bg-destructive/5 p-3 space-y-2">
+ <p className="text-sm">
+ Couldn&apos;t download the local runtime. Check your network
+ connection and try again.
+ </p>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={async () => {
+ setActionLoading(true);
+ try {
+ await window.daemonAPI.retryInstall();
+ } finally {
+ setActionLoading(false);
+ }
+ }}
+ disabled={actionLoading}
+ >
+ <RotateCw className="size-3.5 mr-1.5" />
+ Retry
+ </Button>
+ </div>
+ ) : (
+ <div className="flex gap-2">
+ {status.state === "stopped" ? (
+ <Button size="sm" onClick={handleStart} disabled={actionLoading}>
+ <Play className="size-3.5 mr-1.5" />
+ Start
+ </Button>
+ ) : (
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleStop}
+ disabled={actionLoading || isTransitioning}
+ >
+ <Square className="size-3.5 mr-1.5" />
+ Stop
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleRestart}
+ disabled={actionLoading || isTransitioning}
+ >
+ <RotateCw className="size-3.5 mr-1.5" />
+ Restart
+ </Button>
+ </>
+ )}
+ </div>
+ )}
+
+ {/* Watched workspaces */}
+ {status.state === "running" && allWorkspaces && allWorkspaces.length > 0 && (
+ <div className="space-y-2">
+ <h3 className="text-sm font-medium">Watched Workspaces</h3>
+ <div className="rounded-lg border divide-y max-h-48 overflow-y-auto">
+ {allWorkspaces.map((ws) => {
+ const checked = watchedIds.has(ws.id);
+ const disabled = togglingId === ws.id;
+ return (
+ <label
+ key={ws.id}
+ className={cn(
+ "flex items-center gap-2.5 px-3 py-2",
+ disabled
+ ? "opacity-60 cursor-wait"
+ : "cursor-pointer hover:bg-muted/40",
+ )}
+ >
+ <Checkbox
+ checked={checked}
+ disabled={disabled}
+ onCheckedChange={(next) =>
+ handleToggleWatch(ws.id, ws.name, next === true)
+ }
+ />
+ <span className="truncate text-sm">{ws.name}</span>
+ </label>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Logs — fills remaining vertical space down to the sheet bottom */}
+ <div className="flex-1 min-h-0 flex flex-col gap-2 pb-4">
+ <div className="flex items-center justify-between shrink-0">
+ <h3 className="text-sm font-medium">Logs</h3>
+ {!autoScroll && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 px-2 text-xs"
+ onClick={scrollToBottom}
+ >
+ <ChevronDown className="size-3 mr-1" />
+ Scroll to bottom
+ </Button>
+ )}
+ </div>
+ <div
+ ref={logContainerRef}
+ onScroll={handleLogScroll}
+ className="flex-1 min-h-0 overflow-y-auto rounded-lg border bg-muted/30 p-2 font-mono text-xs leading-relaxed"
+ >
+ {logs.length === 0 ? (
+ <p className="text-muted-foreground/50 text-center py-8">
+ {status.state === "running"
+ ? "Waiting for logs…"
+ : "Start the daemon to see logs"}
+ </p>
+ ) : (
+ logs.map((entry) => {
+ const { className } = colorizeLogLine(entry.line);
+ return (
+ <div key={entry.id} className={cn("whitespace-pre-wrap break-all", className)}>
+ {entry.line}
+ </div>
+ );
+ })
+ )}
+ </div>
+ </div>
+ </div>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx b/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx
new file mode 100644
index 0000000000..0b13a0391e
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx
@@ -0,0 +1,155 @@
+import { useState, useEffect, useCallback } from "react";
+import {
+ Play,
+ Square,
+ RotateCw,
+ Server,
+ Activity,
+} from "lucide-react";
+import { cn } from "@multica/ui/lib/utils";
+import { Button } from "@multica/ui/components/ui/button";
+import { toast } from "sonner";
+import { DaemonPanel } from "./daemon-panel";
+import type { DaemonStatus } from "../../../shared/daemon-types";
+import { DAEMON_STATE_COLORS, DAEMON_STATE_LABELS, formatUptime } from "../../../shared/daemon-types";
+
+export function DaemonRuntimeCard() {
+ const [status, setStatus] = useState<DaemonStatus>({ state: "stopped" });
+ const [panelOpen, setPanelOpen] = useState(false);
+ const [actionLoading, setActionLoading] = useState(false);
+
+ useEffect(() => {
+ window.daemonAPI.getStatus().then((s) => setStatus(s));
+ const unsub = window.daemonAPI.onStatusChange((s) => {
+ setStatus(s);
+ setActionLoading(false);
+ });
+ return unsub;
+ }, []);
+
+ const handleStart = useCallback(async () => {
+ setActionLoading(true);
+ const result = await window.daemonAPI.start();
+ if (!result.success) {
+ setActionLoading(false);
+ toast.error("Failed to start daemon", { description: result.error });
+ }
+ }, []);
+
+ const handleStop = useCallback(async () => {
+ setActionLoading(true);
+ const result = await window.daemonAPI.stop();
+ if (!result.success) {
+ toast.error("Failed to stop daemon", { description: result.error });
+ }
+ }, []);
+
+ const handleRestart = useCallback(async () => {
+ setActionLoading(true);
+ const result = await window.daemonAPI.restart();
+ if (!result.success) {
+ toast.error("Failed to restart daemon", { description: result.error });
+ }
+ }, []);
+
+ const isTransitioning = status.state === "starting" || status.state === "stopping";
+ const isRunning = status.state === "running";
+ const isStopped = status.state === "stopped" || status.state === "cli_not_found";
+
+ const stopPropagation = (e: React.MouseEvent) => e.stopPropagation();
+
+ return (
+ <>
+ <div
+ role="button"
+ tabIndex={0}
+ onClick={() => setPanelOpen(true)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ setPanelOpen(true);
+ }
+ }}
+ className="border-b px-4 py-3 cursor-pointer transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:bg-muted/40"
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex items-center gap-2.5">
+ <div className="flex size-8 items-center justify-center rounded-lg bg-muted">
+ <Server className="size-4 text-muted-foreground" />
+ </div>
+ <div>
+ <h3 className="text-sm font-medium">Local Daemon</h3>
+ <div className="flex items-center gap-1.5 mt-0.5">
+ <span className={cn("size-1.5 rounded-full", DAEMON_STATE_COLORS[status.state])} />
+ <span className="text-xs text-muted-foreground">{DAEMON_STATE_LABELS[status.state]}</span>
+ {isRunning && status.uptime && (
+ <>
+ <span className="text-xs text-muted-foreground">·</span>
+ <span className="text-xs text-muted-foreground">{formatUptime(status.uptime)}</span>
+ </>
+ )}
+ {isRunning && status.agents && status.agents.length > 0 && (
+ <>
+ <span className="text-xs text-muted-foreground">·</span>
+ <span className="text-xs text-muted-foreground">{status.agents.join(", ")}</span>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <div
+ className="flex items-center gap-1.5 shrink-0"
+ onClick={stopPropagation}
+ >
+ {isStopped && (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={handleStart}
+ disabled={actionLoading || status.state === "cli_not_found"}
+ >
+ {actionLoading ? (
+ <Activity className="size-3.5 mr-1.5 animate-pulse" />
+ ) : (
+ <Play className="size-3.5 mr-1.5" />
+ )}
+ Start
+ </Button>
+ )}
+ {isRunning && (
+ <>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={handleRestart}
+ disabled={actionLoading}
+ >
+ <RotateCw className="size-3.5 mr-1.5" />
+ Restart
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={handleStop}
+ disabled={actionLoading}
+ >
+ <Square className="size-3.5 mr-1.5" />
+ Stop
+ </Button>
+ </>
+ )}
+ {isTransitioning && (
+ <Button size="sm" variant="outline" disabled>
+ <Activity className="size-3.5 mr-1.5 animate-pulse" />
+ {DAEMON_STATE_LABELS[status.state]}
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <DaemonPanel open={panelOpen} onOpenChange={setPanelOpen} status={status} />
+ </>
+ );
+}
diff --git a/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx b/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx
new file mode 100644
index 0000000000..b2be04e79c
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx
@@ -0,0 +1,103 @@
+import { useState, useEffect, useCallback } from "react";
+import { Button } from "@multica/ui/components/ui/button";
+import { Switch } from "@multica/ui/components/ui/switch";
+import type { DaemonPrefs } from "../../../shared/daemon-types";
+
+function SettingRow({
+ label,
+ description,
+ children,
+}: {
+ label: string;
+ description: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="flex items-center justify-between gap-6 py-4">
+ <div className="min-w-0">
+ <p className="text-sm font-medium">{label}</p>
+ <p className="text-sm text-muted-foreground mt-0.5">{description}</p>
+ </div>
+ <div className="shrink-0">{children}</div>
+ </div>
+ );
+}
+
+export function DaemonSettingsTab() {
+ const [prefs, setPrefs] = useState<DaemonPrefs>({ autoStart: true, autoStop: false });
+ const [cliInstalled, setCliInstalled] = useState<boolean | null>(null);
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => {
+ window.daemonAPI.getPrefs().then(setPrefs);
+ window.daemonAPI.isCliInstalled().then(setCliInstalled);
+ }, []);
+
+ const updatePref = useCallback(
+ async (key: keyof DaemonPrefs, value: boolean) => {
+ setSaving(true);
+ const updated = await window.daemonAPI.setPrefs({ [key]: value });
+ setPrefs(updated);
+ setSaving(false);
+ },
+ [],
+ );
+
+ return (
+ <div>
+ <h2 className="text-lg font-semibold">Daemon</h2>
+ <p className="text-sm text-muted-foreground mt-1">
+ Configure how the local agent daemon behaves with the desktop app.
+ </p>
+
+ <div className="mt-6 divide-y">
+ <SettingRow
+ label="Auto-start on launch"
+ description="Automatically start the daemon when the app opens and you are logged in."
+ >
+ <Switch
+ checked={prefs.autoStart}
+ onCheckedChange={(checked) => updatePref("autoStart", checked)}
+ disabled={saving}
+ />
+ </SettingRow>
+
+ <SettingRow
+ label="Auto-stop on quit"
+ description="Stop the daemon when the desktop app is closed. Disable this to keep the daemon running in the background."
+ >
+ <Switch
+ checked={prefs.autoStop}
+ onCheckedChange={(checked) => updatePref("autoStop", checked)}
+ disabled={saving}
+ />
+ </SettingRow>
+
+ <div className="py-4">
+ <p className="text-sm font-medium">CLI Status</p>
+ <p className="text-sm text-muted-foreground mt-1">
+ {cliInstalled === null
+ ? "Checking…"
+ : cliInstalled
+ ? "multica CLI is installed and available in PATH."
+ : "multica CLI not found. Install it to enable daemon management."}
+ </p>
+ {cliInstalled === false && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="mt-2"
+ onClick={() =>
+ window.desktopAPI.openExternal(
+ "https://github.com/multica-ai/multica#cli-installation",
+ )
+ }
+ >
+ Installation Guide
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsx
index 32a25b1539..6d12a3a6f5 100644
--- a/apps/desktop/src/renderer/src/routes.tsx
+++ b/apps/desktop/src/renderer/src/routes.tsx
@@ -13,9 +13,14 @@ import { ProjectsPage } from "@multica/views/projects/components";
import { MyIssuesPage } from "@multica/views/my-issues";
import { RuntimesPage } from "@multica/views/runtimes";
import { SkillsPage } from "@multica/views/skills";
+import { DaemonRuntimeCard } from "./components/daemon-runtime-card";
import { AgentsPage } from "@multica/views/agents";
import { InboxPage } from "@multica/views/inbox";
import { SettingsPage } from "@multica/views/settings";
+import { OnboardingWizard } from "@multica/views/onboarding";
+import { useNavigation } from "@multica/views/navigation";
+import { Server } from "lucide-react";
+import { DaemonSettingsTab } from "./components/daemon-settings-tab";
/**
* Sets document.title from the deepest matched route's handle.title.
@@ -47,6 +52,11 @@ function PageShell() {
);
}
+function OnboardingRoute() {
+ const nav = useNavigation();
+ return <OnboardingWizard onComplete={() => nav.push("/issues")} />;
+}
+
/** Route definitions shared by all tabs (no layout wrapper). */
export const appRoutes: RouteObject[] = [
{
@@ -76,15 +86,31 @@ export const appRoutes: RouteObject[] = [
},
{
path: "runtimes",
- element: <RuntimesPage />,
+ element: <RuntimesPage topSlot={<DaemonRuntimeCard />} />,
handle: { title: "Runtimes" },
},
{ path: "skills", element: <SkillsPage />, handle: { title: "Skills" } },
{ path: "agents", element: <AgentsPage />, handle: { title: "Agents" } },
{ path: "inbox", element: <InboxPage />, handle: { title: "Inbox" } },
+ {
+ path: "onboarding",
+ element: <OnboardingRoute />,
+ handle: { title: "Get Started" },
+ },
{
path: "settings",
- element: <SettingsPage />,
+ element: (
+ <SettingsPage
+ extraAccountTabs={[
+ {
+ value: "daemon",
+ label: "Daemon",
+ icon: Server,
+ content: <DaemonSettingsTab />,
+ },
+ ]}
+ />
+ ),
handle: { title: "Settings" },
},
],
diff --git a/apps/desktop/src/shared/daemon-types.ts b/apps/desktop/src/shared/daemon-types.ts
new file mode 100644
index 0000000000..17e2a9e854
--- /dev/null
+++ b/apps/desktop/src/shared/daemon-types.ts
@@ -0,0 +1,53 @@
+export type DaemonState =
+ | "running"
+ | "stopped"
+ | "starting"
+ | "stopping"
+ | "installing_cli"
+ | "cli_not_found";
+
+export interface DaemonStatus {
+ state: DaemonState;
+ pid?: number;
+ uptime?: string;
+ daemonId?: string;
+ deviceName?: string;
+ agents?: string[];
+ workspaceCount?: number;
+ /** CLI profile this daemon belongs to. Empty string means the default profile. */
+ profile?: string;
+ /** Backend URL the daemon connects to. */
+ serverUrl?: string;
+}
+
+export interface DaemonPrefs {
+ autoStart: boolean;
+ autoStop: boolean;
+}
+
+export const DAEMON_STATE_COLORS: Record<DaemonState, string> = {
+ running: "bg-emerald-500",
+ stopped: "bg-muted-foreground/40",
+ starting: "bg-amber-500 animate-pulse",
+ stopping: "bg-amber-500 animate-pulse",
+ installing_cli: "bg-sky-500 animate-pulse",
+ cli_not_found: "bg-red-500",
+};
+
+export const DAEMON_STATE_LABELS: Record<DaemonState, string> = {
+ running: "Running",
+ stopped: "Stopped",
+ starting: "Starting…",
+ stopping: "Stopping…",
+ installing_cli: "Setting up…",
+ cli_not_found: "Setup Failed",
+};
+
+export function formatUptime(uptime?: string): string {
+ if (!uptime) return "";
+ const match = uptime.match(/(?:(\d+)h)?(\d+)m/);
+ if (!match) return uptime;
+ const h = match[1] ? `${match[1]}h ` : "";
+ const m = match[2] ? `${match[2]}m` : "";
+ return `${h}${m}`.trim() || uptime;
+}
diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsx
index ad5ccef9ff..24f64a676e 100644
--- a/packages/views/runtimes/components/runtime-detail.tsx
+++ b/packages/views/runtimes/components/runtime-detail.tsx
@@ -39,9 +39,22 @@ function getCliVersion(metadata: Record<string, unknown>): string | null {
return null;
}
+function getLaunchedBy(metadata: Record<string, unknown>): string | null {
+ if (
+ metadata &&
+ typeof metadata.launched_by === "string" &&
+ metadata.launched_by
+ ) {
+ return metadata.launched_by;
+ }
+ return null;
+}
+
export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
const cliVersion =
runtime.runtime_mode === "local" ? getCliVersion(runtime.metadata) : null;
+ const launchedBy =
+ runtime.runtime_mode === "local" ? getLaunchedBy(runtime.metadata) : null;
const user = useAuthStore((s) => s.user);
const wsId = useWorkspaceId();
@@ -146,6 +159,7 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
runtimeId={runtime.id}
currentVersion={cliVersion}
isOnline={runtime.status === "online"}
+ launchedBy={launchedBy}
/>
</div>
)}
diff --git a/packages/views/runtimes/components/runtimes-page.tsx b/packages/views/runtimes/components/runtimes-page.tsx
index b9e9073c4d..bf426b04c2 100644
--- a/packages/views/runtimes/components/runtimes-page.tsx
+++ b/packages/views/runtimes/components/runtimes-page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useCallback } from "react";
+import React, { useState, useCallback } from "react";
import { Server } from "lucide-react";
import { useDefaultLayout } from "react-resizable-panels";
import { useQuery, useQueryClient } from "@tanstack/react-query";
@@ -20,7 +20,12 @@ import { RuntimeDetail } from "./runtime-detail";
type RuntimeFilter = "mine" | "all";
-export default function RuntimesPage() {
+interface RuntimesPageProps {
+ /** Desktop-only slot rendered above the runtime list (e.g. local daemon card) */
+ topSlot?: React.ReactNode;
+}
+
+export default function RuntimesPage({ topSlot }: RuntimesPageProps = {}) {
const isLoading = useAuthStore((s) => s.isLoading);
const wsId = useWorkspaceId();
const qc = useQueryClient();
@@ -86,43 +91,46 @@ export default function RuntimesPage() {
}
return (
- <ResizablePanelGroup
- orientation="horizontal"
- className="flex-1 min-h-0"
- defaultLayout={defaultLayout}
- onLayoutChanged={onLayoutChanged}
- >
- <ResizablePanel
- id="list"
- defaultSize={280}
- minSize={240}
- maxSize={400}
- groupResizeBehavior="preserve-pixel-size"
+ <div className="flex flex-1 min-h-0 flex-col">
+ {topSlot}
+ <ResizablePanelGroup
+ orientation="horizontal"
+ className="flex-1 min-h-0"
+ defaultLayout={defaultLayout}
+ onLayoutChanged={onLayoutChanged}
>
- <RuntimeList
- runtimes={runtimes}
- selectedId={effectiveSelectedId}
- onSelect={setSelectedId}
- filter={filter}
- onFilterChange={setFilter}
- ownerFilter={ownerFilter}
- onOwnerFilterChange={setOwnerFilter}
- updatableIds={updatableIds}
- />
- </ResizablePanel>
+ <ResizablePanel
+ id="list"
+ defaultSize={280}
+ minSize={240}
+ maxSize={400}
+ groupResizeBehavior="preserve-pixel-size"
+ >
+ <RuntimeList
+ runtimes={runtimes}
+ selectedId={effectiveSelectedId}
+ onSelect={setSelectedId}
+ filter={filter}
+ onFilterChange={setFilter}
+ ownerFilter={ownerFilter}
+ onOwnerFilterChange={setOwnerFilter}
+ updatableIds={updatableIds}
+ />
+ </ResizablePanel>
- <ResizableHandle />
+ <ResizableHandle />
- <ResizablePanel id="detail" minSize="50%">
- {selected ? (
- <RuntimeDetail key={selected.id} runtime={selected} />
- ) : (
- <div className="flex h-full flex-col items-center justify-center text-muted-foreground">
- <Server className="h-10 w-10 text-muted-foreground/30" />
- <p className="mt-3 text-sm">Select a runtime to view details</p>
- </div>
- )}
- </ResizablePanel>
- </ResizablePanelGroup>
+ <ResizablePanel id="detail" minSize="50%">
+ {selected ? (
+ <RuntimeDetail key={selected.id} runtime={selected} />
+ ) : (
+ <div className="flex h-full flex-col items-center justify-center text-muted-foreground">
+ <Server className="h-10 w-10 text-muted-foreground/30" />
+ <p className="mt-3 text-sm">Select a runtime to view details</p>
+ </div>
+ )}
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ </div>
);
}
diff --git a/packages/views/runtimes/components/update-section.tsx b/packages/views/runtimes/components/update-section.tsx
index d14d4e5bc4..df44a3b64c 100644
--- a/packages/views/runtimes/components/update-section.tsx
+++ b/packages/views/runtimes/components/update-section.tsx
@@ -78,13 +78,22 @@ interface UpdateSectionProps {
runtimeId: string;
currentVersion: string | null;
isOnline: boolean;
+ /**
+ * Non-null when the daemon process was spawned by a managed launcher
+ * (e.g. "desktop" for the Electron app). In that case the CLI binary
+ * is shipped and upgraded by the launcher itself, so in-app self-update
+ * is disabled — upgrading would be clobbered on the next launch anyway.
+ */
+ launchedBy?: string | null;
}
export function UpdateSection({
runtimeId,
currentVersion,
isOnline,
+ launchedBy,
}: UpdateSectionProps) {
+ const isManaged = launchedBy === "desktop";
const [latestVersion, setLatestVersion] = useState<string | null>(null);
const [status, setStatus] = useState<RuntimeUpdateStatus | null>(null);
const [error, setError] = useState("");
@@ -165,35 +174,46 @@ export function UpdateSection({
{currentVersion ?? "unknown"}
</span>
- {!hasUpdate && currentVersion && latestVersion && !status && (
- <span className="inline-flex items-center gap-1 text-xs text-success">
- <Check className="h-3 w-3" />
- Latest
+ {isManaged ? (
+ <span
+ className="inline-flex items-center gap-1 text-xs text-muted-foreground"
+ title="The CLI binary is managed by Multica Desktop — update Desktop to upgrade the CLI."
+ >
+ Managed by Desktop
</span>
- )}
-
- {hasUpdate && !status && (
+ ) : (
<>
- <span className="text-xs text-muted-foreground">→</span>
- <span className="text-xs font-mono text-info">
- {latestVersion}
- </span>
- <span className="text-xs text-muted-foreground">available</span>
+ {!hasUpdate && currentVersion && latestVersion && !status && (
+ <span className="inline-flex items-center gap-1 text-xs text-success">
+ <Check className="h-3 w-3" />
+ Latest
+ </span>
+ )}
+
+ {hasUpdate && !status && (
+ <>
+ <span className="text-xs text-muted-foreground">→</span>
+ <span className="text-xs font-mono text-info">
+ {latestVersion}
+ </span>
+ <span className="text-xs text-muted-foreground">available</span>
+ </>
+ )}
+
+ {hasUpdate && isOnline && !status && (
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={handleUpdate}
+ disabled={updating}
+ >
+ <ArrowUpCircle className="h-3 w-3" />
+ Update
+ </Button>
+ )}
</>
)}
- {hasUpdate && isOnline && !status && (
- <Button
- variant="outline"
- size="xs"
- onClick={handleUpdate}
- disabled={updating}
- >
- <ArrowUpCircle className="h-3 w-3" />
- Update
- </Button>
- )}
-
{config && Icon && (
<span
className={`inline-flex items-center gap-1 text-xs ${config.color}`}
diff --git a/packages/views/settings/components/index.ts b/packages/views/settings/components/index.ts
index 544ba343a1..1116afeddc 100644
--- a/packages/views/settings/components/index.ts
+++ b/packages/views/settings/components/index.ts
@@ -1 +1,2 @@
export { SettingsPage } from "./settings-page";
+export type { ExtraSettingsTab } from "./settings-page";
diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsx
index 025f15ce48..778bcf01f9 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -1,5 +1,6 @@
"use client";
+import React from "react";
import { User, Palette, Key, Settings, Users, FolderGit2 } from "lucide-react";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@multica/ui/components/ui/tabs";
import { useWorkspaceStore } from "@multica/core/workspace";
@@ -22,7 +23,19 @@ const workspaceTabs = [
{ value: "members", label: "Members", icon: Users },
];
-export function SettingsPage() {
+export interface ExtraSettingsTab {
+ value: string;
+ label: string;
+ icon: React.ComponentType<{ className?: string }>;
+ content: React.ReactNode;
+}
+
+interface SettingsPageProps {
+ /** Additional tabs injected by platform (e.g. desktop daemon settings) */
+ extraAccountTabs?: ExtraSettingsTab[];
+}
+
+export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
const workspaceName = useWorkspaceStore((s) => s.workspace?.name);
return (
@@ -41,6 +54,12 @@ export function SettingsPage() {
{tab.label}
</TabsTrigger>
))}
+ {extraAccountTabs?.map((tab) => (
+ <TabsTrigger key={tab.value} value={tab.value}>
+ <tab.icon className="h-4 w-4" />
+ {tab.label}
+ </TabsTrigger>
+ ))}
{/* Workspace group */}
<span className="px-2 pb-1 pt-4 text-xs font-medium text-muted-foreground truncate">
@@ -64,6 +83,9 @@ export function SettingsPage() {
<TabsContent value="workspace"><WorkspaceTab /></TabsContent>
<TabsContent value="repositories"><RepositoriesTab /></TabsContent>
<TabsContent value="members"><MembersTab /></TabsContent>
+ {extraAccountTabs?.map((tab) => (
+ <TabsContent key={tab.value} value={tab.value}>{tab.content}</TabsContent>
+ ))}
</div>
</div>
</Tabs>
diff --git a/packages/views/settings/index.ts b/packages/views/settings/index.ts
index 3195fd5a72..fef5002273 100644
--- a/packages/views/settings/index.ts
+++ b/packages/views/settings/index.ts
@@ -1 +1,2 @@
export { SettingsPage } from "./components";
+export type { ExtraSettingsTab } from "./components";
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index 7a6f89b90b..742b0a41cd 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -272,6 +272,9 @@ func runDaemonForeground(cmd *cobra.Command) error {
return err
}
cfg.CLIVersion = version
+ // Set by the Electron Desktop app when it spawns the CLI so the server
+ // can mark those runtimes as "managed" and hide CLI self-update UI.
+ cfg.LaunchedBy = os.Getenv("MULTICA_LAUNCHED_BY")
ctx, stop := notifyShutdownContext(context.Background())
defer stop()
diff --git a/server/internal/cli/config.go b/server/internal/cli/config.go
index d8d74c0174..0ee73de0a0 100644
--- a/server/internal/cli/config.go
+++ b/server/internal/cli/config.go
@@ -18,11 +18,45 @@ type WatchedWorkspace struct {
// CLIConfig holds persistent CLI settings.
type CLIConfig struct {
- ServerURL string `json:"server_url,omitempty"`
- AppURL string `json:"app_url,omitempty"`
- WorkspaceID string `json:"workspace_id,omitempty"`
- Token string `json:"token,omitempty"`
- WatchedWorkspaces []WatchedWorkspace `json:"watched_workspaces,omitempty"`
+ ServerURL string `json:"server_url,omitempty"`
+ AppURL string `json:"app_url,omitempty"`
+ WorkspaceID string `json:"workspace_id,omitempty"`
+ Token string `json:"token,omitempty"`
+ WatchedWorkspaces []WatchedWorkspace `json:"watched_workspaces,omitempty"`
+ // UnwatchedWorkspaces is a denylist of workspace IDs the user has
+ // explicitly opted out of. The daemon's periodic sync from the API
+ // respects this list and won't re-add excluded workspaces.
+ UnwatchedWorkspaces []string `json:"unwatched_workspaces,omitempty"`
+}
+
+// IsUnwatched reports whether the given workspace ID is in the denylist.
+func (c *CLIConfig) IsUnwatched(id string) bool {
+ for _, u := range c.UnwatchedWorkspaces {
+ if u == id {
+ return true
+ }
+ }
+ return false
+}
+
+// AddUnwatchedWorkspace adds an ID to the denylist. Returns true if added.
+func (c *CLIConfig) AddUnwatchedWorkspace(id string) bool {
+ if c.IsUnwatched(id) {
+ return false
+ }
+ c.UnwatchedWorkspaces = append(c.UnwatchedWorkspaces, id)
+ return true
+}
+
+// RemoveUnwatchedWorkspace removes an ID from the denylist. Returns true if removed.
+func (c *CLIConfig) RemoveUnwatchedWorkspace(id string) bool {
+ for i, u := range c.UnwatchedWorkspaces {
+ if u == id {
+ c.UnwatchedWorkspaces = append(c.UnwatchedWorkspaces[:i], c.UnwatchedWorkspaces[i+1:]...)
+ return true
+ }
+ }
+ return false
}
// AddWatchedWorkspace adds a workspace to the watch list. Returns true if added.
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index 69ae571abc..007c126b92 100644
--- a/server/internal/daemon/config.go
+++ b/server/internal/daemon/config.go
@@ -32,6 +32,7 @@ type Config struct {
DeviceName string
RuntimeName string
CLIVersion string // multica CLI version (e.g. "0.1.13")
+ LaunchedBy string // "desktop" when spawned by the Electron app, empty for standalone
Profile string // profile name (empty = default)
Agents map[string]AgentEntry // keyed by provider: claude, codex, opencode, openclaw, hermes, gemini
WorkspacesRoot string // base path for execution envs (default: ~/multica_workspaces)
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 0ac4a594cb..be9a592092 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -156,8 +156,13 @@ func (d *Daemon) loadWatchedWorkspaces(ctx context.Context) error {
return fmt.Errorf("load CLI config: %w", err)
}
+ // It's fine to start with an empty watched list — workspaceSyncLoop runs
+ // immediately on startup and will populate the list from the server. The
+ // daemon also accepts HTTP POST /watch for explicit adds from clients
+ // like the Desktop app.
if len(cfg.WatchedWorkspaces) == 0 {
- return fmt.Errorf("no watched workspaces configured: run 'multica workspace watch <id>' to add one")
+ d.logger.Info("no watched workspaces in config; workspaceSyncLoop will populate from API")
+ return nil
}
var registered int
@@ -263,6 +268,7 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s
"daemon_id": d.cfg.DaemonID,
"device_name": d.cfg.DeviceName,
"cli_version": d.cfg.CLIVersion,
+ "launched_by": d.cfg.LaunchedBy,
"runtimes": runtimes,
}
@@ -350,6 +356,9 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context) {
var added int
for _, ws := range workspaces {
+ if cfg.IsUnwatched(ws.ID) {
+ continue // user explicitly opted out
+ }
if cfg.AddWatchedWorkspace(ws.ID, ws.Name) {
added++
d.logger.Info("workspace sync: discovered new workspace", "workspace_id", ws.ID, "name", ws.Name)
@@ -562,6 +571,19 @@ func (d *Daemon) handlePing(ctx context.Context, rt Runtime, pingID string) {
// handleUpdate performs the CLI update when triggered by the server via heartbeat.
func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *PendingUpdate) {
+ // Desktop-managed daemons share their CLI binary with the Electron app,
+ // which is responsible for shipping and replacing it. Letting the daemon
+ // self-update would just get overwritten on the next Desktop launch and
+ // could brick the embedded binary mid-update. Refuse cleanly.
+ if d.cfg.LaunchedBy == "desktop" {
+ d.logger.Info("refusing CLI self-update: daemon is managed by Desktop", "runtime_id", runtimeID, "update_id", update.ID)
+ d.client.ReportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ "status": "failed",
+ "error": "CLI is managed by Multica Desktop — update the Desktop app to upgrade the CLI",
+ })
+ return
+ }
+
// Prevent concurrent update attempts.
if !d.updating.CompareAndSwap(false, true) {
d.logger.Warn("update already in progress, ignoring", "runtime_id", runtimeID, "update_id", update.ID)
diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.go
index 4f06d6e78f..2f921c802d 100644
--- a/server/internal/daemon/health.go
+++ b/server/internal/daemon/health.go
@@ -7,8 +7,10 @@ import (
"net"
"net/http"
"os"
+ "strings"
"time"
+ "github.com/multica-ai/multica/server/internal/cli"
"github.com/multica-ai/multica/server/internal/daemon/repocache"
)
@@ -49,6 +51,19 @@ type repoCheckoutRequest struct {
TaskID string `json:"task_id"`
}
+// watchWorkspaceRequest is the body of a POST /watch request.
+type watchWorkspaceRequest struct {
+ WorkspaceID string `json:"workspace_id"`
+ Name string `json:"name"`
+}
+
+// watchedWorkspaceItem is one entry in the GET /watch response.
+type watchedWorkspaceItem struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Runtime int `json:"runtime_count"`
+}
+
// serveHealth runs the health HTTP server on the given listener.
// Blocks until ctx is cancelled.
func (d *Daemon) serveHealth(ctx context.Context, ln net.Listener, startedAt time.Time) {
@@ -84,6 +99,31 @@ func (d *Daemon) serveHealth(ctx context.Context, ln net.Listener, startedAt tim
json.NewEncoder(w).Encode(resp)
})
+ mux.HandleFunc("/watch", func(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ d.handleListWatched(w, r)
+ case http.MethodPost:
+ d.handleWatchWorkspace(w, r)
+ default:
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ }
+ })
+
+ // DELETE /watch/{workspace_id}
+ mux.HandleFunc("/watch/", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodDelete {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ id := strings.TrimPrefix(r.URL.Path, "/watch/")
+ if id == "" {
+ http.Error(w, "workspace_id is required in path", http.StatusBadRequest)
+ return
+ }
+ d.handleUnwatchWorkspace(w, r, id)
+ })
+
mux.HandleFunc("/repo/checkout", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
@@ -138,3 +178,135 @@ func (d *Daemon) serveHealth(ctx context.Context, ln net.Listener, startedAt tim
d.logger.Warn("health server error", "error", err)
}
}
+
+// handleListWatched returns the daemon's current watched workspaces merged
+// with the persisted config so clients can reflect "what is watched" and
+// "what has been explicitly opted out".
+func (d *Daemon) handleListWatched(w http.ResponseWriter, _ *http.Request) {
+ cfg, err := cli.LoadCLIConfigForProfile(d.cfg.Profile)
+ if err != nil {
+ http.Error(w, "load config: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ d.mu.Lock()
+ items := make([]watchedWorkspaceItem, 0, len(cfg.WatchedWorkspaces))
+ for _, ws := range cfg.WatchedWorkspaces {
+ rc := 0
+ if state, ok := d.workspaces[ws.ID]; ok {
+ rc = len(state.runtimeIDs)
+ }
+ items = append(items, watchedWorkspaceItem{
+ ID: ws.ID,
+ Name: ws.Name,
+ Runtime: rc,
+ })
+ }
+ d.mu.Unlock()
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]any{
+ "watched": items,
+ "unwatched": cfg.UnwatchedWorkspaces,
+ })
+}
+
+// handleWatchWorkspace registers a new workspace at runtime. Updates config
+// (removes from denylist, adds to watched list), registers runtimes via the
+// API, and records the result in daemon state. Idempotent.
+func (d *Daemon) handleWatchWorkspace(w http.ResponseWriter, r *http.Request) {
+ var req watchWorkspaceRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
+ return
+ }
+ if req.WorkspaceID == "" {
+ http.Error(w, "workspace_id is required", http.StatusBadRequest)
+ return
+ }
+
+ cfg, err := cli.LoadCLIConfigForProfile(d.cfg.Profile)
+ if err != nil {
+ http.Error(w, "load config: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ cfg.RemoveUnwatchedWorkspace(req.WorkspaceID)
+ cfg.AddWatchedWorkspace(req.WorkspaceID, req.Name)
+ if err := cli.SaveCLIConfigForProfile(cfg, d.cfg.Profile); err != nil {
+ http.Error(w, "save config: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ // Skip registration if we're already tracking this workspace.
+ d.mu.Lock()
+ _, already := d.workspaces[req.WorkspaceID]
+ d.mu.Unlock()
+ if already {
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]any{"status": "already_watching"})
+ return
+ }
+
+ resp, err := d.registerRuntimesForWorkspace(r.Context(), req.WorkspaceID)
+ if err != nil {
+ d.logger.Error("watch: register failed", "workspace_id", req.WorkspaceID, "error", err)
+ http.Error(w, "register runtimes: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ runtimeIDs := make([]string, len(resp.Runtimes))
+ for i, rt := range resp.Runtimes {
+ runtimeIDs[i] = rt.ID
+ }
+ d.mu.Lock()
+ d.workspaces[req.WorkspaceID] = &workspaceState{workspaceID: req.WorkspaceID, runtimeIDs: runtimeIDs}
+ for _, rt := range resp.Runtimes {
+ d.runtimeIndex[rt.ID] = rt
+ }
+ d.mu.Unlock()
+
+ if d.repoCache != nil && len(resp.Repos) > 0 {
+ go func(wsID string, repos []RepoData) {
+ if err := d.repoCache.Sync(wsID, repoDataToInfo(repos)); err != nil {
+ d.logger.Warn("repo cache sync failed", "workspace_id", wsID, "error", err)
+ }
+ }(req.WorkspaceID, resp.Repos)
+ }
+
+ d.logger.Info("watch: now watching workspace", "workspace_id", req.WorkspaceID, "name", req.Name, "runtimes", len(resp.Runtimes))
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]any{
+ "status": "watching",
+ "workspace_id": req.WorkspaceID,
+ "runtime_count": len(runtimeIDs),
+ })
+}
+
+// handleUnwatchWorkspace stops tracking a workspace and records the opt-out
+// in the denylist so the periodic API sync won't revive it.
+func (d *Daemon) handleUnwatchWorkspace(w http.ResponseWriter, _ *http.Request, id string) {
+ cfg, err := cli.LoadCLIConfigForProfile(d.cfg.Profile)
+ if err != nil {
+ http.Error(w, "load config: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ cfg.RemoveWatchedWorkspace(id)
+ cfg.AddUnwatchedWorkspace(id)
+ if err := cli.SaveCLIConfigForProfile(cfg, d.cfg.Profile); err != nil {
+ http.Error(w, "save config: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ d.mu.Lock()
+ if state, ok := d.workspaces[id]; ok {
+ for _, rid := range state.runtimeIDs {
+ delete(d.runtimeIndex, rid)
+ }
+ delete(d.workspaces, id)
+ }
+ d.mu.Unlock()
+
+ d.logger.Info("watch: stopped watching workspace", "workspace_id", id)
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]any{"status": "unwatched", "workspace_id": id})
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 8b5f5014fa..d454d3bd54 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -117,6 +117,7 @@ type DaemonRegisterRequest struct {
DaemonID string `json:"daemon_id"`
DeviceName string `json:"device_name"`
CLIVersion string `json:"cli_version"` // multica CLI version
+ LaunchedBy string `json:"launched_by"` // "desktop" when spawned by the Electron app
Runtimes []struct {
Name string `json:"name"`
Type string `json:"type"`
@@ -200,6 +201,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
metadata, _ := json.Marshal(map[string]any{
"version": runtime.Version,
"cli_version": req.CLIVersion,
+ "launched_by": req.LaunchedBy,
})
registered, err := h.Queries.UpsertAgentRuntime(r.Context(), db.UpsertAgentRuntimeParams{
diff --git a/server/internal/logger/logger.go b/server/internal/logger/logger.go
index ef177da92c..3ea62d7f52 100644
--- a/server/internal/logger/logger.go
+++ b/server/internal/logger/logger.go
@@ -10,24 +10,39 @@ import (
"github.com/lmittmann/tint"
)
-// Init initializes the global slog logger with colored terminal output.
-// Reads LOG_LEVEL env var (debug, info, warn, error). Default: debug.
+// isTerminal reports whether the given file descriptor is connected to a
+// terminal. Used to suppress ANSI color escapes when stderr is redirected
+// to a file (e.g. daemon.log), so log files stay clean.
+func isTerminal(f *os.File) bool {
+ fi, err := f.Stat()
+ if err != nil {
+ return false
+ }
+ return fi.Mode()&os.ModeCharDevice != 0
+}
+
+// Init initializes the global slog logger. Colors are enabled when stderr
+// is a terminal and disabled otherwise. Reads LOG_LEVEL env var (debug,
+// info, warn, error). Default: debug.
func Init() {
level := parseLevel(os.Getenv("LOG_LEVEL"))
handler := tint.NewHandler(os.Stderr, &tint.Options{
Level: level,
TimeFormat: "15:04:05.000",
+ NoColor: !isTerminal(os.Stderr),
})
slog.SetDefault(slog.New(handler))
}
-// NewLogger creates a named slog logger with colored terminal output.
-// Useful for standalone processes (daemon, migrate) that want a component prefix.
+// NewLogger creates a named slog logger. Colors follow the same
+// TTY-detection rule as Init. Useful for standalone processes (daemon,
+// migrate) that want a component prefix.
func NewLogger(component string) *slog.Logger {
level := parseLevel(os.Getenv("LOG_LEVEL"))
handler := tint.NewHandler(os.Stderr, &tint.Options{
Level: level,
TimeFormat: "15:04:05.000",
+ NoColor: !isTerminal(os.Stderr),
})
return slog.New(handler).With("component", component)
}