Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(desktop): never fall back to the user's default CLI profile (MUL-5737) (#6487)
Bohan Jiang53122a123d9e
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.tsindex 18fa3a39bb..edaa3aba9d 100644--- a/apps/desktop/src/main/daemon-manager.ts+++ b/apps/desktop/src/main/daemon-manager.ts@@ -24,6 +24,15 @@ import type {import { daemonStatusAlive } from "../shared/daemon-types";import { ensureManagedCli, managedCliPath } from "./cli-bootstrap";import { decideVersionAction } from "./version-decision";+import {+ deriveProfileName,+ healthPortForProfile,+ profileArgs,+ profileConfigPath,+ profileDir,+ profileLogPath,+ profileUserIdPath,+} from "./daemon-profile";import {daemonLifecycleUnreachable,isDaemonExternallyManaged,@@ -35,7 +44,6 @@ import {type AuthProbeResult,} from "./daemon-auth-probe";-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;@@ -55,8 +63,10 @@ const DAEMON_START_EXEC_TIMEOUT_MS = 60_000;const DEFAULT_PREFS: DaemonPrefs = { autoStart: true, autoStop: false };+// Always a resolved Desktop-owned profile. "Not resolved yet" is represented by+// `null` at every call site, never by an empty name — see daemon-profile.ts.interface ActiveProfile {- name: string; // "" = default profile+ name: string;port: number;}@@ -90,36 +100,6 @@ let authExpired = false;// 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");@@ -229,19 +209,6 @@ async function probeTokenValidity(profile: string): Promise<AuthProbeResult> {}}-// 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>> {@@ -275,13 +242,14 @@ async function writeProfileConfig(* 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.+ * Returns `null` until the renderer reports its `apiUrl`. There is no profile+ * to act on in that window, and callers must do nothing rather than reach for+ * the user's default CLI profile at `~/.multica/` — neither its files nor its+ * health port.*/-async function resolveActiveProfile(): Promise<ActiveProfile> {+async function resolveActiveProfile(): Promise<ActiveProfile | null> {const target = targetApiBaseUrl;- if (!target) return { name: "", port: DEFAULT_HEALTH_PORT };+ if (!target) return null;const name = deriveProfileName(target);const cfg = await readProfileConfig(name);@@ -295,8 +263,11 @@ async function resolveActiveProfile(): Promise<ActiveProfile> {return { name, port: healthPortForProfile(name) };}-async function ensureActiveProfile(): Promise<ActiveProfile> {+async function ensureActiveProfile(): Promise<ActiveProfile | null> {if (activeProfile) return activeProfile;+ // Only a resolved profile is cached; the target URL arrives over IPC shortly+ // after startup, and caching "unresolved" would persist until something+ // happened to invalidate it.activeProfile = await resolveActiveProfile();return activeProfile;}@@ -314,6 +285,10 @@ async function fetchHealth(): Promise<DaemonStatus> {}const active = await ensureActiveProfile();+ // No profile yet means no daemon of ours to probe. Reporting "stopped" is the+ // honest answer; probing the default port would surface the user's own CLI+ // daemon as if it were Desktop's.+ if (!active) return { state: "stopped" };const data = await fetchHealthAtPort(active.port);if (!data || data.status !== "running") {@@ -577,6 +552,7 @@ async function ensureRunningDaemonVersionMatches(): Promise<"restarted" | "deferred" | "ok" | "not_running"> {const active = await ensureActiveProfile();+ if (!active) return "not_running";const running = await fetchHealthAtPort(active.port);// Don't try to version-match a daemon we can't restart (e.g. WSL2). Treat it@@ -673,6 +649,12 @@ async function syncToken(userId: string,): Promise<void> {const active = await ensureActiveProfile();+ if (!active) {+ // Writing here would land the token and server_url in the user's default+ // CLI config. The renderer awaits setTargetApiUrl before calling this, so+ // reaching this branch is a real error rather than a normal startup race.+ throw new Error("daemon profile is not resolved yet; token sync skipped");+ }const config = await readProfileConfig(active.name);const previousUserId = await readProfileUserId(active.name);const userChanged = Boolean(previousUserId) && previousUserId !== userId;@@ -742,6 +724,9 @@ async function savePrefs(prefs: DaemonPrefs): Promise<void> {async function clearToken(): Promise<void> {const active = await ensureActiveProfile();+ // Nothing of ours to clear yet, and the default CLI profile is not ours to+ // strip a token from.+ if (!active) return;const config = await readProfileConfig(active.name);if ("token" in config) {delete config.token;@@ -810,10 +795,6 @@ async function withGuard<T>(fn: () => Promise<T>): Promise<T | { success: false;}}-function profileArgs(active: ActiveProfile): string[] {- return active.name ? ["--profile", active.name] : [];-}-function successfulRuntimeProbe(providers: string[],daemonRunning: boolean,@@ -846,10 +827,11 @@ async function probeLocalRuntimes(): Promise<LocalRuntimeProbe> {const bin = await resolveCliBinary();if (!bin) return { probeResult: "error" };const active = await ensureActiveProfile();+ if (!active) return { probeResult: "error" };return new Promise((resolve) => {execFile(bin,- ["daemon", "probe-runtimes", ...profileArgs(active)],+ ["daemon", "probe-runtimes", ...profileArgs(active.name)],{ timeout: 15_000, env: desktopSpawnEnv(), maxBuffer: 64 * 1024 },(error, stdout) => {if (error) {@@ -914,6 +896,9 @@ async function startDaemon(): Promise<{ success: boolean; error?: string }> {if (!bin) return { success: false, error: "multica CLI is not installed" };const active = await ensureActiveProfile();+ if (!active) {+ return { success: false, error: "Waiting for the service address" };+ }const existing = await fetchHealthAtPort(active.port);if (daemonStatusAlive(existing?.status)) {// A daemon is already up ("running") or booting ("starting") on this port —@@ -930,7 +915,7 @@ async function startDaemon(): Promise<{ success: boolean; error?: string }> {authExpired = false;sendStatus({ state: "starting" });- const args = ["daemon", "start", ...profileArgs(active)];+ const args = ["daemon", "start", ...profileArgs(active.name)];return new Promise((resolve) => {execFile(@@ -964,6 +949,7 @@ async function startDaemon(): Promise<{ success: boolean; error?: string }> {*/async function lifecycleBlockedByForeignDaemon(): Promise<boolean> {const active = await ensureActiveProfile();+ if (!active) return false;return daemonLifecycleUnreachable(async () => (await fetchHealthAtPort(active.port))?.os,normalizeHostOS(process.platform),@@ -984,13 +970,14 @@ async function stopDaemon(): Promise<{ success: boolean; error?: string }> {if (!bin) return { success: false, error: "multica CLI is not installed" };const active = await ensureActiveProfile();+ if (!active) return { success: true };currentState = "stopping";// An explicit stop is a clean reset — drop any pending auth-failure verdict.authExpired = false;startingSince = null;sendStatus({ state: "stopping" });- const args = ["daemon", "stop", ...profileArgs(active)];+ const args = ["daemon", "stop", ...profileArgs(active.name)];return new Promise((resolve) => {execFile(bin, args, { timeout: 15_000 }, (err) => {@@ -1090,8 +1077,11 @@ function startLogTail(win: BrowserWindow, retryCount = 0): void {stopLogTail();void ensureActiveProfile().then(async (active) => {- const logPath = profileLogPath(active.name);- if (!existsSync(logPath)) {+ // Before the renderer reports its apiUrl there is no Desktop-owned profile+ // yet, and therefore no log file of ours to tail. Retry rather than reach+ // for the default profile's log.+ const logPath = active ? profileLogPath(active.name) : null;+ if (!logPath || !existsSync(logPath)) {if (retryCount < LOG_TAIL_MAX_RETRIES) {setTimeout(() => startLogTail(win, retryCount + 1), LOG_TAIL_RETRY_MS);}@@ -1233,8 +1223,8 @@ export function setupDaemonManager(// (full history, complex search, copy-to-clipboard at scale).ipcMain.handle("daemon:open-log-file", async () => {const active = await ensureActiveProfile();- const logPath = profileLogPath(active.name);- if (!existsSync(logPath)) {+ const logPath = active ? profileLogPath(active.name) : null;+ if (!logPath || !existsSync(logPath)) {return { success: false, error: "Log file not found yet" };}// shell.openPath returns "" on success, error string on failure.diff --git a/apps/desktop/src/main/daemon-profile.test.ts b/apps/desktop/src/main/daemon-profile.test.tsnew file mode 100644index 0000000000..ce61abedf1--- /dev/null+++ b/apps/desktop/src/main/daemon-profile.test.ts@@ -0,0 +1,103 @@+import { homedir } from "os";+import { join } from "path";+import { describe, expect, it } from "vitest";++import {+ DEFAULT_HEALTH_PORT,+ deriveProfileName,+ healthPortForProfile,+ profileArgs,+ profileConfigPath,+ profileDir,+ profileLogPath,+ profileUserIdPath,+} from "./daemon-profile";++const MULTICA_DIR = join(homedir(), ".multica");+const DEFAULT_CLI_CONFIG = join(MULTICA_DIR, "config.json");++describe("deriveProfileName", () => {+ it("names the profile after the target host", () => {+ expect(deriveProfileName("https://api.multica.ai")).toBe(+ "desktop-api.multica.ai",+ );+ });++ it("replaces the port colon so the name is path-safe", () => {+ expect(deriveProfileName("http://localhost:8080")).toBe(+ "desktop-localhost-8080",+ );+ });++ it("falls back to a fixed name on an unparseable URL", () => {+ expect(deriveProfileName("not a url")).toBe("desktop");+ });+});++describe("profile paths", () => {+ it("always resolves under profiles/<name>", () => {+ const dir = join(MULTICA_DIR, "profiles", "desktop-api.multica.ai");+ expect(profileDir("desktop-api.multica.ai")).toBe(dir);+ expect(profileConfigPath("desktop-api.multica.ai")).toBe(+ join(dir, "config.json"),+ );+ expect(profileLogPath("desktop-api.multica.ai")).toBe(+ join(dir, "daemon.log"),+ );+ expect(profileUserIdPath("desktop-api.multica.ai")).toBe(+ join(dir, ".desktop-user-id"),+ );+ });++ // Regression: an unresolved profile used to resolve to ~/.multica, so Desktop+ // could overwrite server_url and token in the user's own CLI config. #6399.+ it("refuses to build a path for an unresolved profile", () => {+ expect(() => profileDir("")).toThrow(/unresolved/);+ expect(() => profileConfigPath("")).toThrow(/unresolved/);+ expect(() => profileLogPath("")).toThrow(/unresolved/);+ expect(() => profileUserIdPath("")).toThrow(/unresolved/);+ });++ it("never yields the default CLI config path for any input", () => {+ for (const name of ["desktop-api.multica.ai", "desktop", "x"]) {+ expect(profileConfigPath(name)).not.toBe(DEFAULT_CLI_CONFIG);+ }+ expect(() => profileConfigPath("")).toThrow();+ });+});++describe("profileArgs", () => {+ it("selects the Desktop-owned profile", () => {+ expect(profileArgs("desktop-api.multica.ai")).toEqual([+ "--profile",+ "desktop-api.multica.ai",+ ]);+ });++ // Regression: this returned [] for an unresolved profile, so the bundled CLI+ // ran against the user's default profile instead of Desktop's. #6399.+ it("refuses to spawn the CLI without a profile flag", () => {+ expect(() => profileArgs("")).toThrow(/unresolved/);+ });+});++describe("healthPortForProfile", () => {+ // Regression: this returned 19514 — the default profile's port — for an+ // unresolved profile, so Desktop would probe the user's own CLI daemon and+ // report it as its own. #6399.+ it("refuses to hand out a port for an unresolved profile", () => {+ expect(() => healthPortForProfile("")).toThrow(/unresolved/);+ });++ it("never derives the default profile's port", () => {+ for (const name of ["desktop-api.multica.ai", "desktop", "x", "a".repeat(50)]) {+ expect(healthPortForProfile(name)).not.toBe(DEFAULT_HEALTH_PORT);+ }+ });++ it("derives a stable per-profile port above the default", () => {+ const port = healthPortForProfile("desktop-api.multica.ai");+ expect(port).toBeGreaterThan(DEFAULT_HEALTH_PORT);+ expect(port).toBe(healthPortForProfile("desktop-api.multica.ai"));+ });+});diff --git a/apps/desktop/src/main/daemon-profile.ts b/apps/desktop/src/main/daemon-profile.tsnew file mode 100644index 0000000000..a52b13efc8--- /dev/null+++ b/apps/desktop/src/main/daemon-profile.ts@@ -0,0 +1,79 @@+import { homedir } from "os";+import { join } from "path";++// Keep the Go impl in sync: server/cmd/multica/cmd_daemon.go healthPortForProfile.+export const DEFAULT_HEALTH_PORT = 19514;++/**+ * Desktop owns only `~/.multica/profiles/desktop-<host>/`. The default profile+ * at `~/.multica/` — config, daemon log, and health port 19514 — belongs to the+ * user's terminal CLI and must never be read, written, probed, or passed to the+ * bundled CLI.+ *+ * Callers signal "target API URL not known yet" with `null`, never with an+ * empty name, so there is no value that can quietly resolve to the default+ * profile. This guard is the backstop for that. See #6399.+ */+export function assertResolvedProfile(profile: string): void {+ if (!profile) {+ throw new Error(+ "daemon profile is unresolved — refusing to fall back to the default CLI profile",+ );+ }+}++// 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>/+export function deriveProfileName(targetUrl: string): string {+ try {+ const url = new URL(targetUrl);+ const host = url.host.replace(/:/g, "-").toLowerCase();+ return `desktop-${host}`;+ } catch {+ return "desktop";+ }+}++/**+ * Port 19514 itself is the default profile's, so an unresolved profile must+ * never produce one: probing it would report the user's own CLI daemon as+ * Desktop's, and lifecycle commands would act on it.+ */+export function healthPortForProfile(profile: string): number {+ assertResolvedProfile(profile);+ let sum = 0;+ for (const b of Buffer.from(profile, "utf-8")) sum += b;+ return DEFAULT_HEALTH_PORT + 1 + (sum % 1000);+}++export function profileDir(profile: string): string {+ assertResolvedProfile(profile);+ return join(homedir(), ".multica", "profiles", profile);+}++export function profileConfigPath(profile: string): string {+ return join(profileDir(profile), "config.json");+}++export 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.+export function profileUserIdPath(profile: string): string {+ return join(profileDir(profile), ".desktop-user-id");+}++/**+ * CLI args selecting the Desktop-owned profile. An unresolved profile must+ * never produce an empty arg list: the bundled CLI would then act on the+ * user's default profile at `~/.multica/config.json`.+ */+export function profileArgs(profile: string): string[] {+ assertResolvedProfile(profile);+ return ["--profile", profile];+}diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex de894d01eb..b4490a5f83 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -18,6 +18,7 @@ import { IssueWindow } from "./components/issue-window";import { useTabStore } from "./stores/tab-store";import { useWindowOverlayStore } from "./stores/window-overlay-store";import { useDaemonIPCBridge } from "./platform/daemon-ipc-bridge";+import { syncDaemonOnLogin } from "./platform/daemon-login-sync";import { createDesktopLocaleAdapter } from "./platform/i18n-adapter";import { captureEvent } from "@multica/core/analytics";import { RESOURCES } from "@multica/views/locales";@@ -168,21 +169,26 @@ function AppContent() {});}, [qc]);- // Sync token and start the daemon whenever the user logs in.+ // Sync token and start the daemon whenever the user logs in. The ordering+ // inside syncDaemonOnLogin is load-bearing — see that module.useEffect(() => {- if (!user) return;+ if (!user || !runtimeConfig) 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();+ await syncDaemonOnLogin(+ window.daemonAPI,+ runtimeConfig.apiUrl,+ token,+ userId,+ );} catch (err) {console.error("Failed to sync daemon on login", err);}})();- }, [user]);+ }, [user, runtimeConfig]);// When a user who started the session with zero workspaces creates their// first one, restart the daemon so it picks up the new workspacediff --git a/apps/desktop/src/renderer/src/platform/daemon-login-sync.test.ts b/apps/desktop/src/renderer/src/platform/daemon-login-sync.test.tsnew file mode 100644index 0000000000..3de432a1eb--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/daemon-login-sync.test.ts@@ -0,0 +1,78 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import {+ syncDaemonOnLogin,+ type DaemonLoginSyncAPI,+} from "./daemon-login-sync";++const calls: string[] = [];++function makeApi(overrides: Partial<DaemonLoginSyncAPI> = {}): DaemonLoginSyncAPI {+ return {+ setTargetApiUrl: vi.fn(async () => {+ calls.push("setTargetApiUrl");+ }),+ syncToken: vi.fn(async () => {+ calls.push("syncToken");+ }),+ autoStart: vi.fn(async () => {+ calls.push("autoStart");+ }),+ ...overrides,+ };+}++beforeEach(() => {+ calls.length = 0;+ vi.clearAllMocks();+});++describe("syncDaemonOnLogin", () => {+ // Regression: syncToken used to race a separate effect's setTargetApiUrl.+ // Arriving first meant main had no resolved profile and wrote the token to+ // the user's default CLI profile. #6399.+ it("pushes the target URL before syncing the token", async () => {+ const api = makeApi();+ await syncDaemonOnLogin(api, "https://api.example.com", "tok", "user-1");++ expect(calls).toEqual(["setTargetApiUrl", "syncToken", "autoStart"]);+ expect(api.setTargetApiUrl).toHaveBeenCalledWith("https://api.example.com");+ expect(api.syncToken).toHaveBeenCalledWith("tok", "user-1");+ });++ it("awaits the target URL rather than firing it off", async () => {+ let released: (() => void) | undefined;+ const api = makeApi({+ setTargetApiUrl: vi.fn(+ () =>+ new Promise<void>((resolve) => {+ released = () => {+ calls.push("setTargetApiUrl");+ resolve();+ };+ }),+ ),+ });++ const pending = syncDaemonOnLogin(api, "https://api.example.com", "t", "u");+ await Promise.resolve();+ expect(api.syncToken).not.toHaveBeenCalled();++ released?.();+ await pending;+ expect(calls).toEqual(["setTargetApiUrl", "syncToken", "autoStart"]);+ });++ it("does not start the daemon when the token sync fails", async () => {+ const api = makeApi({+ syncToken: vi.fn(async () => {+ throw new Error("daemon profile is not resolved yet");+ }),+ });++ await expect(+ syncDaemonOnLogin(api, "https://api.example.com", "t", "u"),+ ).rejects.toThrow(/not resolved/);+ expect(api.autoStart).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/src/platform/daemon-login-sync.ts b/apps/desktop/src/renderer/src/platform/daemon-login-sync.tsnew file mode 100644index 0000000000..13de2930a8--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/daemon-login-sync.ts@@ -0,0 +1,30 @@+/**+ * Bring the local daemon up for a freshly signed-in user.+ *+ * The order matters and is the reason this is a function rather than three+ * inline awaits. Desktop's daemon profile is derived from the target API URL,+ * so until the main process has that URL there is no Desktop-owned profile —+ * and main now refuses to write the token at all rather than fall back to the+ * user's default CLI profile at `~/.multica/` (#6399).+ *+ * That refusal has no retry of its own: the login effect re-runs on `user`, not+ * on the target URL. So the URL must be pushed and awaited here, before the+ * token sync, instead of racing a separate effect's IPC message. Re-sending it+ * is cheap — the main-process handler ignores an unchanged value.+ */+export interface DaemonLoginSyncAPI {+ setTargetApiUrl: (url: string) => Promise<void>;+ syncToken: (token: string, userId: string) => Promise<void>;+ autoStart: () => Promise<unknown>;+}++export async function syncDaemonOnLogin(+ api: DaemonLoginSyncAPI,+ apiUrl: string,+ token: string,+ userId: string,+): Promise<void> {+ await api.setTargetApiUrl(apiUrl);+ await api.syncToken(token, userId);+ await api.autoStart();+}