Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(desktop): load runtime self-host config (#2012)
Cong Vu Chi820d57535e04
diff --git a/apps/desktop/.env.production b/apps/desktop/.env.productiondeleted file mode 100644index e6e6affb4a..0000000000--- a/apps/desktop/.env.production+++ /dev/null@@ -1,12 +0,0 @@-# Production environment for `pnpm package` / `pnpm build`.-# electron-vite (Vite under the hood) reads this automatically in-# production mode and inlines the values into the renderer bundle via-# import.meta.env.VITE_*. These are public URLs, not secrets.--# Backend API + websocket the desktop app talks to.-VITE_API_URL=https://api.multica.ai-VITE_WS_URL=wss://api.multica.ai/ws--# Public web app URL — used to build shareable links like "Copy link to-# issue" that users paste into Slack / messages. See platform/navigation.tsx.-VITE_APP_URL=https://multica.aidiff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 4f068501e5..57ef427191 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -8,6 +8,8 @@ import { setupDaemonManager } from "./daemon-manager";import { openExternalSafely } from "./external-url";import { installContextMenu } from "./context-menu";import { getAppVersion } from "./app-version";+import { loadRuntimeConfig } from "./runtime-config-loader";+import type { RuntimeConfigResult } from "../shared/runtime-config";// Bundled icon used for dev-mode dock/taskbar branding. In production the// app bundle icon (from electron-builder) wins; this path is only consumed@@ -37,6 +39,10 @@ if (process.platform !== "win32") {const PROTOCOL = "multica";let mainWindow: BrowserWindow | null = null;+let runtimeConfigResult: RuntimeConfigResult = {+ ok: false,+ error: { message: "Runtime config has not loaded yet" },+};// --- Deep link helpers ---------------------------------------------------@@ -187,7 +193,25 @@ if (!gotTheLock) {if (deepLinkUrl) handleDeepLink(deepLinkUrl);});- app.whenReady().then(() => {+ app.whenReady().then(async () => {+ const viteEnv = import.meta.env as ImportMetaEnv & {+ readonly VITE_API_URL?: string;+ readonly VITE_WS_URL?: string;+ readonly VITE_APP_URL?: string;+ };++ runtimeConfigResult = await loadRuntimeConfig({+ isDev: is.dev,+ // electron-vite exposes VITE_* on import.meta.env for the main process;+ // keep dev URL overrides on the same source the renderer used before+ // runtime config moved endpoint resolution into main/preload.+ env: {+ apiUrl: viteEnv.VITE_API_URL,+ wsUrl: viteEnv.VITE_WS_URL,+ appUrl: viteEnv.VITE_APP_URL,+ },+ });+electronApp.setAppUserModelId(is.dev ? "ai.multica.desktop.dev" : "ai.multica.desktop",);@@ -223,6 +247,13 @@ if (!gotTheLock) {event.returnValue = { version: getAppVersion(), os };});+ // Sync IPC: preload exposes the validated runtime config before renderer+ // boot. If desktop.json exists but is invalid, renderer receives the+ // blocking error and must not silently fall back to the cloud defaults.+ ipcMain.on("runtime-config:get", (event) => {+ event.returnValue = runtimeConfigResult;+ });+// IPC: toggle immersive mode — hides the macOS traffic lights so full-screen// modals (e.g. create-workspace) can place UI in the top-left corner// without fighting the native window controls' hit-test.diff --git a/apps/desktop/src/main/runtime-config-loader.test.ts b/apps/desktop/src/main/runtime-config-loader.test.tsnew file mode 100644index 0000000000..1415b150e5--- /dev/null+++ b/apps/desktop/src/main/runtime-config-loader.test.ts@@ -0,0 +1,90 @@+import { mkdtemp, writeFile } from "fs/promises";+import { join } from "path";+import { tmpdir } from "os";+import { describe, expect, it } from "vitest";+import { loadRuntimeConfig } from "./runtime-config-loader";++describe("loadRuntimeConfig", () => {+ it("uses dev env and ignores desktop.json during electron-vite dev", async () => {+ const dir = await mkdtemp(join(tmpdir(), "multica-desktop-config-"));+ const configPath = join(dir, "desktop.json");+ await writeFile(+ configPath,+ JSON.stringify({ schemaVersion: 1, apiUrl: "https://prod.example.com" }),+ );++ await expect(+ loadRuntimeConfig({+ isDev: true,+ configPath,+ env: {+ apiUrl: "http://localhost:8080",+ wsUrl: "ws://localhost:8080/ws",+ appUrl: "http://localhost:3000",+ },+ }),+ ).resolves.toEqual({+ ok: true,+ config: {+ schemaVersion: 1,+ apiUrl: "http://localhost:8080",+ wsUrl: "ws://localhost:8080/ws",+ appUrl: "http://localhost:3000",+ },+ });+ });++ it("uses cloud defaults when packaged config is absent", async () => {+ const dir = await mkdtemp(join(tmpdir(), "multica-desktop-config-"));+ await expect(+ loadRuntimeConfig({+ isDev: false,+ configPath: join(dir, "missing.json"),+ env: {},+ }),+ ).resolves.toEqual({+ ok: true,+ config: {+ schemaVersion: 1,+ apiUrl: "https://api.multica.ai",+ wsUrl: "wss://api.multica.ai/ws",+ appUrl: "https://multica.ai",+ },+ });+ });++ it("parses a valid packaged desktop.json", async () => {+ const dir = await mkdtemp(join(tmpdir(), "multica-desktop-config-"));+ const configPath = join(dir, "desktop.json");+ await writeFile(+ configPath,+ JSON.stringify({ schemaVersion: 1, apiUrl: "https://api.example.com" }),+ );++ await expect(+ loadRuntimeConfig({ isDev: false, configPath, env: {} }),+ ).resolves.toEqual({+ ok: true,+ config: {+ schemaVersion: 1,+ apiUrl: "https://api.example.com",+ wsUrl: "wss://api.example.com/ws",+ appUrl: "https://api.example.com",+ },+ });+ });++ it("fails closed when packaged desktop.json is invalid", async () => {+ const dir = await mkdtemp(join(tmpdir(), "multica-desktop-config-"));+ const configPath = join(dir, "desktop.json");+ await writeFile(configPath, "{");++ const result = await loadRuntimeConfig({ isDev: false, configPath, env: {} });++ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.error.message).toContain(configPath);+ expect(result.error.message).toContain("Invalid desktop runtime config JSON");+ }+ });+});diff --git a/apps/desktop/src/main/runtime-config-loader.ts b/apps/desktop/src/main/runtime-config-loader.tsnew file mode 100644index 0000000000..5fb9734c93--- /dev/null+++ b/apps/desktop/src/main/runtime-config-loader.ts@@ -0,0 +1,60 @@+import { app } from "electron";+import { readFile } from "fs/promises";+import { join } from "path";+import {+ DEFAULT_RUNTIME_CONFIG,+ parseRuntimeConfig,+ runtimeConfigFromDevEnv,+ type RuntimeConfig,+ type RuntimeConfigEnv,+ type RuntimeConfigResult,+} from "../shared/runtime-config";++export async function loadRuntimeConfig(options: {+ isDev: boolean;+ env: RuntimeConfigEnv;+ configPath?: string;+}): Promise<RuntimeConfigResult> {+ if (options.isDev) {+ try {+ return { ok: true, config: runtimeConfigFromDevEnv(options.env) };+ } catch (err) {+ return { ok: false, error: { message: errorMessage(err) } };+ }+ }++ const configPath = options.configPath ?? desktopConfigPath();+ try {+ const raw = await readFile(configPath, "utf-8");+ return { ok: true, config: parseRuntimeConfig(raw) };+ } catch (err) {+ if (isMissingFileError(err)) {+ return { ok: true, config: { ...DEFAULT_RUNTIME_CONFIG } };+ }+ return {+ ok: false,+ error: {+ message: `Invalid ${configPath}: ${errorMessage(err)}`,+ },+ };+ }+}++export function desktopConfigPath(): string {+ return join(app.getPath("home"), ".multica", "desktop.json");+}++function isMissingFileError(err: unknown): boolean {+ return Boolean(+ err &&+ typeof err === "object" &&+ "code" in err &&+ (err as NodeJS.ErrnoException).code === "ENOENT",+ );+}++function errorMessage(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++export type { RuntimeConfig, RuntimeConfigResult };diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.tsindex e9136e4c27..f8525b6862 100644--- a/apps/desktop/src/preload/index.d.ts+++ b/apps/desktop/src/preload/index.d.ts@@ -1,4 +1,5 @@import { ElectronAPI } from "@electron-toolkit/preload";+import type { RuntimeConfigResult } from "../shared/runtime-config";interface DesktopAPI {/** App version + normalized OS, captured synchronously at preload time. */@@ -6,6 +7,8 @@ interface DesktopAPI {version: string;os: "macos" | "windows" | "linux" | "unknown";};+ /** Validated runtime endpoint config, or a blocking config error. */+ runtimeConfig: RuntimeConfigResult;/** Listen for auth token delivered via deep link. Returns an unsubscribe function. */onAuthToken: (callback: (token: string) => void) => () => void;/** Listen for invitation IDs delivered via deep link. Returns an unsubscribe function. */diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex 78d45de63e..ecadf16330 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -1,5 +1,6 @@import { contextBridge, ipcRenderer } from "electron";import { electronAPI } from "@electron-toolkit/preload";+import type { RuntimeConfigResult } from "../shared/runtime-config";// Synchronously fetch app metadata from main at preload time so the renderer// can pass it into CoreProvider during the initial render — the alternative@@ -21,12 +22,30 @@ function fetchAppInfo(): { version: string; os: "macos" | "windows" | "linux" |return { version: "unknown", os };}+function fetchRuntimeConfig(): RuntimeConfigResult {+ try {+ const result = ipcRenderer.sendSync("runtime-config:get") as RuntimeConfigResult | undefined;+ if (result && typeof result === "object" && "ok" in result) return result;+ } catch (err) {+ return {+ ok: false,+ error: {+ message: err instanceof Error ? err.message : String(err),+ },+ };+ }+ return { ok: false, error: { message: "Runtime config unavailable" } };+}+const appInfo = fetchAppInfo();+const runtimeConfig = fetchRuntimeConfig();const desktopAPI = {/** App version + normalized OS. Read once at preload time so the renderer* can use it synchronously when initializing the API client. */appInfo,+ /** Validated runtime endpoint config, or a blocking config error. */+ runtimeConfig,/** Listen for auth token delivered via deep link */onAuthToken: (callback: (token: string) => void) => {const handler = (_event: Electron.IpcRendererEvent, token: string) =>diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex 9718c55820..ddf1426bae 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -30,11 +30,16 @@ function AppContent() {// first render.const [bootstrapping, setBootstrapping] = useState(false);+ const runtimeConfig = window.desktopAPI.runtimeConfig.ok+ ? window.desktopAPI.runtimeConfig.config+ : null;+// 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);- }, []);+ if (!runtimeConfig) return;+ window.daemonAPI.setTargetApiUrl(runtimeConfig.apiUrl);+ }, [runtimeConfig]);// Listen for invite IDs delivered via deep link (multica://invite/<id>).// We open the overlay regardless of login state — if the user isn't logged@@ -226,9 +231,21 @@ function AppContent() {);}-// Backend the daemon should connect to — same URL the renderer talks to.-const DAEMON_TARGET_API_URL =- import.meta.env.VITE_API_URL || "http://localhost:8080";+function BlockingRuntimeConfigError({ message }: { message: string }) {+ return (+ <div className="flex h-screen items-center justify-center bg-background p-8 text-foreground">+ <div className="max-w-xl rounded-lg border bg-card p-6 shadow-sm">+ <h1 className="text-lg font-semibold">Desktop configuration error</h1>+ <p className="mt-3 text-sm text-muted-foreground">+ Multica Desktop could not load <code>~/.multica/desktop.json</code>. Fix or remove the file and restart the app.+ </p>+ <pre className="mt-4 whitespace-pre-wrap rounded-md bg-muted p-3 text-xs text-muted-foreground">+ {message}+ </pre>+ </div>+ </div>+ );+}// On logout, wipe desktop-only in-memory state and stop the daemon so that// a subsequent login as a different user never inherits the previous user's@@ -252,6 +269,7 @@ async function handleDaemonLogout() {export default function App() {const { version, os } = window.desktopAPI.appInfo;+ const runtimeConfigResult = window.desktopAPI.runtimeConfig;// Stable identity reference so downstream effects (WS reconnect) don't// tear down on every parent render.const identity = useMemo(@@ -260,14 +278,18 @@ export default function App() {);return (<ThemeProvider>- <CoreProvider- apiBaseUrl={import.meta.env.VITE_API_URL || "http://localhost:8080"}- wsUrl={import.meta.env.VITE_WS_URL || "ws://localhost:8080/ws"}- onLogout={handleDaemonLogout}- identity={identity}- >- <AppContent />- </CoreProvider>+ {runtimeConfigResult.ok ? (+ <CoreProvider+ apiBaseUrl={runtimeConfigResult.config.apiUrl}+ wsUrl={runtimeConfigResult.config.wsUrl}+ onLogout={handleDaemonLogout}+ identity={identity}+ >+ <AppContent />+ </CoreProvider>+ ) : (+ <BlockingRuntimeConfigError message={runtimeConfigResult.error.message} />+ )}<Toaster /><UpdateNotification /></ThemeProvider>diff --git a/apps/desktop/src/renderer/src/pages/login.tsx b/apps/desktop/src/renderer/src/pages/login.tsxindex e0f7efdc27..4bf6aa34ea 100644--- a/apps/desktop/src/renderer/src/pages/login.tsx+++ b/apps/desktop/src/renderer/src/pages/login.tsx@@ -2,14 +2,23 @@ import { LoginPage } from "@multica/views/auth";import { DragStrip } from "@multica/views/platform";import { MulticaIcon } from "@multica/ui/components/common/multica-icon";-const WEB_URL = import.meta.env.VITE_APP_URL || "http://localhost:3000";+function requireRuntimeAppUrl(): string {+ const runtimeConfig = window.desktopAPI.runtimeConfig;+ if (!runtimeConfig.ok) {+ throw new Error(+ "Invariant violated: DesktopLoginPage rendered before App accepted runtime config",+ );+ }+ return runtimeConfig.config.appUrl;+}export function DesktopLoginPage() {+ const webUrl = requireRuntimeAppUrl();const handleGoogleLogin = () => {// Open web login page in the default browser with platform=desktop flag.// The web callback will redirect back via multica:// deep link with the token.window.desktopAPI.openExternal(- `${WEB_URL}/login?platform=desktop`,+ `${webUrl}/login?platform=desktop`,);};diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsxindex 729071cf5f..bc78278dd8 100644--- a/apps/desktop/src/renderer/src/platform/navigation.tsx+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx@@ -15,11 +15,15 @@ import {} from "@/stores/tab-store";import { useWindowOverlayStore } from "@/stores/window-overlay-store";-// Public web app URL — injected at build time via .env.production. In dev-// (no VITE_APP_URL set) falls back to the local web dev server so "Copy-// link" in a dev build yields a URL that points at the running dev-// frontend, not the prod host. Matches the fallback used in pages/login.tsx.-const APP_URL = import.meta.env.VITE_APP_URL || "http://localhost:3000";+function requireRuntimeAppUrl(scope: string): string {+ const runtimeConfig = window.desktopAPI.runtimeConfig;+ if (!runtimeConfig.ok) {+ throw new Error(+ `Invariant violated: ${scope} rendered before App accepted runtime config`,+ );+ }+ return runtimeConfig.config.appUrl;+}/*** Extract the leading workspace slug from a path, or null if the path isn't@@ -116,6 +120,7 @@ export function DesktopNavigationProvider({}: {children: React.ReactNode;}) {+ const appUrl = requireRuntimeAppUrl("DesktopNavigationProvider");// Primitive-only subscriptions so this component doesn't re-render on// unrelated store updates (e.g. an inactive tab's router tick). We// resolve the active router here only to subscribe once per tab switch.@@ -186,9 +191,9 @@ export function DesktopNavigationProvider({const tabId = store.openTab(path, title ?? path, icon);if (tabId) store.setActiveTab(tabId);},- getShareableUrl: (path: string) => `${APP_URL}${path}`,+ getShareableUrl: (path: string) => `${appUrl}${path}`,}),- [location],+ [appUrl, location],);return <NavigationProvider value={adapter}>{children}</NavigationProvider>;@@ -211,6 +216,7 @@ export function TabNavigationProvider({router: DataRouter;children: React.ReactNode;}) {+ const appUrl = requireRuntimeAppUrl("TabNavigationProvider");const [location, setLocation] = useState(router.state.location);useEffect(() => {@@ -246,9 +252,9 @@ export function TabNavigationProvider({const tabId = store.openTab(path, title ?? path, icon);if (tabId) store.setActiveTab(tabId);},- getShareableUrl: (path: string) => `${APP_URL}${path}`,+ getShareableUrl: (path: string) => `${appUrl}${path}`,}),- [router, location],+ [appUrl, router, location],);return <NavigationProvider value={adapter}>{children}</NavigationProvider>;diff --git a/apps/desktop/src/shared/runtime-config.test.ts b/apps/desktop/src/shared/runtime-config.test.tsnew file mode 100644index 0000000000..86a69119b3--- /dev/null+++ b/apps/desktop/src/shared/runtime-config.test.ts@@ -0,0 +1,99 @@+import { describe, expect, it } from "vitest";+import {+ DEFAULT_RUNTIME_CONFIG,+ deriveWsUrl,+ parseRuntimeConfig,+ runtimeConfigFromDevEnv,+} from "./runtime-config";++describe("runtime config", () => {+ it("uses cloud defaults without a desktop.json file", () => {+ expect(DEFAULT_RUNTIME_CONFIG).toEqual({+ schemaVersion: 1,+ apiUrl: "https://api.multica.ai",+ wsUrl: "wss://api.multica.ai/ws",+ appUrl: "https://multica.ai",+ });+ });++ it("derives https/wss compatible URLs from apiUrl", () => {+ expect(+ parseRuntimeConfig(+ JSON.stringify({+ schemaVersion: 1,+ apiUrl: "https://congvc-x99.taila6fa8a.ts.net:18443",+ }),+ ),+ ).toEqual({+ schemaVersion: 1,+ apiUrl: "https://congvc-x99.taila6fa8a.ts.net:18443",+ wsUrl: "wss://congvc-x99.taila6fa8a.ts.net:18443/ws",+ appUrl: "https://congvc-x99.taila6fa8a.ts.net:18443",+ });+ });++ it("derives ws for http api URLs", () => {+ expect(deriveWsUrl("http://localhost:8080")).toBe("ws://localhost:8080/ws");+ });++ it("accepts explicit appUrl and wsUrl", () => {+ expect(+ parseRuntimeConfig(+ JSON.stringify({+ schemaVersion: 1,+ apiUrl: "https://api.example.com/",+ wsUrl: "wss://ws.example.com/socket/",+ appUrl: "https://app.example.com/",+ }),+ ),+ ).toEqual({+ schemaVersion: 1,+ apiUrl: "https://api.example.com",+ wsUrl: "wss://ws.example.com/socket",+ appUrl: "https://app.example.com",+ });+ });++ it("rejects invalid JSON", () => {+ expect(() => parseRuntimeConfig("{")).toThrow(/Invalid desktop runtime config JSON/);+ });++ it("rejects unsupported schema versions", () => {+ expect(() =>+ parseRuntimeConfig(JSON.stringify({ schemaVersion: 2, apiUrl: "https://api.example.com" })),+ ).toThrow(/schemaVersion/);+ });++ it("rejects non-http api schemes", () => {+ expect(() =>+ parseRuntimeConfig(JSON.stringify({ schemaVersion: 1, apiUrl: "file:///tmp/multica" })),+ ).toThrow(/apiUrl must use http or https/);+ });++ it("rejects non-ws websocket schemes", () => {+ expect(() =>+ parseRuntimeConfig(+ JSON.stringify({+ schemaVersion: 1,+ apiUrl: "https://api.example.com",+ wsUrl: "https://api.example.com/ws",+ }),+ ),+ ).toThrow(/wsUrl must use ws or wss/);+ });++ it("preserves electron-vite dev env precedence", () => {+ expect(+ runtimeConfigFromDevEnv({+ apiUrl: "http://dev-api.example.test:8080/",+ wsUrl: "ws://dev-api.example.test:8080/ws/",+ appUrl: "http://dev-app.example.test:3000/",+ }),+ ).toEqual({+ schemaVersion: 1,+ apiUrl: "http://dev-api.example.test:8080",+ wsUrl: "ws://dev-api.example.test:8080/ws",+ appUrl: "http://dev-app.example.test:3000",+ });+ });+});diff --git a/apps/desktop/src/shared/runtime-config.ts b/apps/desktop/src/shared/runtime-config.tsnew file mode 100644index 0000000000..27e3d54fd9--- /dev/null+++ b/apps/desktop/src/shared/runtime-config.ts@@ -0,0 +1,157 @@+export interface RuntimeConfig {+ schemaVersion: 1;+ apiUrl: string;+ wsUrl: string;+ appUrl: string;+}++export interface RuntimeConfigError {+ message: string;+}++export type RuntimeConfigResult =+ | { ok: true; config: RuntimeConfig }+ | { ok: false; error: RuntimeConfigError };++export const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = Object.freeze({+ schemaVersion: 1,+ apiUrl: "https://api.multica.ai",+ wsUrl: "wss://api.multica.ai/ws",+ appUrl: "https://multica.ai",+});++const LOCAL_DEV_RUNTIME_CONFIG: RuntimeConfig = Object.freeze({+ schemaVersion: 1,+ apiUrl: "http://localhost:8080",+ wsUrl: "ws://localhost:8080/ws",+ appUrl: "http://localhost:3000",+});++export interface RuntimeConfigEnv {+ apiUrl?: string;+ wsUrl?: string;+ appUrl?: string;+}++export function runtimeConfigFromDevEnv(env: RuntimeConfigEnv): RuntimeConfig {+ const apiUrl = normalizeHttpUrl(+ env.apiUrl || LOCAL_DEV_RUNTIME_CONFIG.apiUrl,+ "VITE_API_URL",+ );+ return {+ schemaVersion: 1,+ apiUrl,+ wsUrl: env.wsUrl+ ? normalizeWsUrl(env.wsUrl, "VITE_WS_URL")+ : deriveWsUrl(apiUrl),+ appUrl: normalizeHttpUrl(+ env.appUrl || LOCAL_DEV_RUNTIME_CONFIG.appUrl,+ "VITE_APP_URL",+ ),+ };+}++export function parseRuntimeConfig(raw: string): RuntimeConfig {+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (err) {+ throw new Error(+ `Invalid desktop runtime config JSON: ${err instanceof Error ? err.message : "parse failed"}`,+ );+ }++ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ throw new Error("Invalid desktop runtime config: expected a JSON object");+ }++ const obj = parsed as Record<string, unknown>;+ if (obj.schemaVersion !== 1) {+ throw new Error("Unsupported desktop runtime config schemaVersion: expected 1");+ }++ const apiUrl = requiredString(obj.apiUrl, "apiUrl");+ const appUrl = optionalString(obj.appUrl, "appUrl");+ const wsUrl = optionalString(obj.wsUrl, "wsUrl");++ const normalizedApiUrl = normalizeHttpUrl(apiUrl, "apiUrl");+ return {+ schemaVersion: 1,+ apiUrl: normalizedApiUrl,+ wsUrl: wsUrl ? normalizeWsUrl(wsUrl, "wsUrl") : deriveWsUrl(normalizedApiUrl),+ appUrl: appUrl ? normalizeHttpUrl(appUrl, "appUrl") : deriveAppUrl(normalizedApiUrl),+ };+}++export function deriveWsUrl(apiUrl: string): string {+ const url = new URL(apiUrl);+ if (url.protocol === "https:") url.protocol = "wss:";+ else if (url.protocol === "http:") url.protocol = "ws:";+ else throw new Error("apiUrl must use http or https");+ url.pathname = joinPath(url.pathname, "/ws");+ url.search = "";+ url.hash = "";+ return trimTrailingSlash(url.toString());+}++export function deriveAppUrl(apiUrl: string): string {+ const url = new URL(apiUrl);+ url.pathname = "";+ url.search = "";+ url.hash = "";+ return trimTrailingSlash(url.toString());+}++function requiredString(value: unknown, field: string): string {+ if (typeof value !== "string" || value.trim().length === 0) {+ throw new Error(`Invalid desktop runtime config: ${field} must be a non-empty string`);+ }+ return value;+}++function optionalString(value: unknown, field: string): string | undefined {+ if (value === undefined) return undefined;+ if (typeof value !== "string" || value.trim().length === 0) {+ throw new Error(`Invalid desktop runtime config: ${field} must be a non-empty string when set`);+ }+ return value;+}++function normalizeHttpUrl(value: string, field: string): string {+ let url: URL;+ try {+ url = new URL(value.trim());+ } catch {+ throw new Error(`Invalid desktop runtime config: ${field} must be a valid URL`);+ }+ if (url.protocol !== "http:" && url.protocol !== "https:") {+ throw new Error(`Invalid desktop runtime config: ${field} must use http or https`);+ }+ url.search = "";+ url.hash = "";+ return trimTrailingSlash(url.toString());+}++function normalizeWsUrl(value: string, field: string): string {+ let url: URL;+ try {+ url = new URL(value.trim());+ } catch {+ throw new Error(`Invalid desktop runtime config: ${field} must be a valid URL`);+ }+ if (url.protocol !== "ws:" && url.protocol !== "wss:") {+ throw new Error(`Invalid desktop runtime config: ${field} must use ws or wss`);+ }+ url.search = "";+ url.hash = "";+ return trimTrailingSlash(url.toString());+}++function joinPath(base: string, suffix: string): string {+ const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;+ return `${normalizedBase}${suffix}`;+}++function trimTrailingSlash(value: string): string {+ return value.replace(/\/+$/, "");+}diff --git a/apps/docs/content/docs/desktop-app.mdx b/apps/docs/content/docs/desktop-app.mdxindex a988c092f8..1665448ca4 100644--- a/apps/docs/content/docs/desktop-app.mdx+++ b/apps/docs/content/docs/desktop-app.mdx@@ -5,7 +5,7 @@ description: What Multica Desktop is, how it differs from the web app, and whenimport { Callout } from "fumadocs-ui/components/callout";-Multica Desktop is a native desktop app for macOS, Windows, and Linux. It talks to the same backend as the web app and shows the same data, but it adds a few things the browser can't: **independent tab groups per [workspace](/workspaces)**, **automatic [daemon](/daemon-runtimes) startup**, and **one-click upgrades**.+Multica Desktop is a native desktop app for macOS, Windows, and Linux. For the environment it is configured for, it talks to the same backend as the web app and shows the same data. By default Desktop uses Multica Cloud; self-hosted instances can be configured with a local runtime config file. Desktop also adds a few things the browser can't: **independent tab groups per [workspace](/workspaces)**, **automatic [daemon](/daemon-runtimes) startup**, and **one-click upgrades**.## Desktop or web — which to pick@@ -66,25 +66,34 @@ Grab the installer for your platform from the [Multica downloads page](https://mOn first launch you'll need to sign in — the same email + verification code flow as the web app. Once you're in, Desktop syncs your workspace list automatically.-<Callout type="warning">-**Released Desktop builds are pinned to Multica Cloud.** The backend, websocket, and web URLs are baked in at build time (`VITE_API_URL` / `VITE_WS_URL` / `VITE_APP_URL`) — there is no in-app option to point Desktop at a self-hosted instance. To use Desktop against a self-hosted backend you need to build it yourself:--```bash-git clone https://github.com/multica-ai/multica.git-cd multica-# Edit apps/desktop/.env.production:-# VITE_API_URL=https://api.your-domain-# VITE_WS_URL=wss://api.your-domain/ws-# VITE_APP_URL=https://your-domain-pnpm install-pnpm --filter @multica/desktop package+<Callout type="info">+**Desktop defaults to Multica Cloud, but can be pointed at a self-hosted instance with a local config file.** There is still no in-app "connect to self-host" picker. Desktop reads `~/.multica/desktop.json` before the renderer starts; if the file is missing, it uses the Cloud defaults.++Minimal self-host config:++```json+{+ "schemaVersion": 1,+ "apiUrl": "https://api.your-domain"+}+```++`apiUrl` is required and must use `http` or `https`. Desktop derives `wsUrl` as `/ws` on the same origin (`wss` for `https`, `ws` for `http`) and derives `appUrl` from the API origin. If your deployment uses different origins, set them explicitly:++```json+{+ "schemaVersion": 1,+ "apiUrl": "https://api.your-domain",+ "wsUrl": "wss://api.your-domain/ws",+ "appUrl": "https://your-domain"+}```-If you'd rather not build from source, the supported self-hosted path is **web frontend + CLI** — see [Self-host quickstart](/self-host-quickstart). Runtime backend configuration in Desktop is tracked in [issue #1371](https://github.com/multica-ai/multica/issues/1371).+If `desktop.json` exists but is invalid, Desktop fails closed and shows a blocking config error instead of silently falling back to Cloud. For development builds, `VITE_API_URL` / `VITE_WS_URL` / `VITE_APP_URL` still take precedence during `electron-vite dev`. Runtime Desktop self-host configuration was implemented for [issue #1371](https://github.com/multica-ai/multica/issues/1371).</Callout>## Next steps- [Cloud Quickstart](/cloud-quickstart) — the Cloud onboarding flow for Desktop-- [Self-Host Quickstart](/self-host-quickstart) — running your own backend (Desktop against self-host requires a custom build, see the callout above)+- [Self-Host Quickstart](/self-host-quickstart) — running your own backend and connecting with the CLI or Desktop runtime config- [Daemon and runtimes](/daemon-runtimes) — how the daemon works (Desktop starts it for you, but the behavior is the same)diff --git a/apps/docs/content/docs/desktop-app.zh.mdx b/apps/docs/content/docs/desktop-app.zh.mdxindex 30e6bd8034..c2334eb518 100644--- a/apps/docs/content/docs/desktop-app.zh.mdx+++ b/apps/docs/content/docs/desktop-app.zh.mdx@@ -5,7 +5,7 @@ description: Multica Desktop 是什么、和 Web 有什么区别、什么时候import { Callout } from "fumadocs-ui/components/callout";-Multica Desktop 是原生桌面应用——macOS / Windows / Linux 三个平台。它和 Web 版连同一个后端,看到的数据完全一样,但给了几个 Web 做不到的能力:**[工作区](/workspaces) 独立的多标签页**、**自动启动 [守护进程](/daemon-runtimes)**、**一键升级**。+Multica Desktop 是原生桌面应用——macOS / Windows / Linux 三个平台。对它当前配置的环境来说,它和 Web 版连同一个后端、看到的数据完全一样。Desktop 默认使用 Multica Cloud;自部署实例可以通过本地运行时配置文件接入。它还给了几个 Web 做不到的能力:**[工作区](/workspaces) 独立的多标签页**、**自动启动 [守护进程](/daemon-runtimes)**、**一键升级**。## Desktop 和 Web 该用哪个@@ -66,25 +66,34 @@ macOS 版本已经签名 + 公证,第一次打开不会有"未知开发者"的安装后第一次打开需要登录——和 Web 版一样的 email + 验证码流程。登录成功后 Desktop 自动把工作区列表同步下来。-<Callout type="warning">-**发布版的 Desktop 是锁死连 Multica Cloud 的**。后端 / WebSocket / Web 前端 URL(`VITE_API_URL` / `VITE_WS_URL` / `VITE_APP_URL`)在构建时就写死了,应用内**没有切换后端的入口**。要让 Desktop 连自部署后端,需要你自己从源码 build:--```bash-git clone https://github.com/multica-ai/multica.git-cd multica-# 编辑 apps/desktop/.env.production:-# VITE_API_URL=https://api.your-domain-# VITE_WS_URL=wss://api.your-domain/ws-# VITE_APP_URL=https://your-domain-pnpm install-pnpm --filter @multica/desktop package+<Callout type="info">+**Desktop 默认连接 Multica Cloud,但可以通过本地配置文件指向自部署实例。** 应用内仍然没有“连接自部署”的切换入口。Desktop 会在 renderer 启动前读取 `~/.multica/desktop.json`;如果这个文件不存在,就使用 Cloud 默认值。++最小自部署配置:++```json+{+ "schemaVersion": 1,+ "apiUrl": "https://api.your-domain"+}+```++`apiUrl` 是必填项,必须使用 `http` 或 `https`。Desktop 会自动从它推导 `wsUrl`(同源 `/ws`,`https` 对应 `wss`,`http` 对应 `ws`)和 `appUrl`(API 的同源地址)。如果你的部署使用不同域名,可以显式设置:++```json+{+ "schemaVersion": 1,+ "apiUrl": "https://api.your-domain",+ "wsUrl": "wss://api.your-domain/ws",+ "appUrl": "https://your-domain"+}```-不想自己 build 的话,自部署的官方路径是 **Web 前端 + CLI**——见 [自部署快速上手](/self-host-quickstart)。Desktop 运行时切换后端的能力跟踪在 [issue #1371](https://github.com/multica-ai/multica/issues/1371)。+如果 `desktop.json` 存在但内容无效,Desktop 会 fail closed,显示阻塞式配置错误,而不是悄悄回退到 Cloud。开发构建里,`electron-vite dev` 仍然优先使用 `VITE_API_URL` / `VITE_WS_URL` / `VITE_APP_URL`。Desktop 运行时自部署配置能力对应 [issue #1371](https://github.com/multica-ai/multica/issues/1371)。</Callout>## 下一步- [Cloud Quickstart](/cloud-quickstart) —— Desktop 版的 Cloud 接入流程-- [Self-Host Quickstart](/self-host-quickstart) —— 自部署后端(Desktop 连自部署需要自行构建,见上方提示)+- [Self-Host Quickstart](/self-host-quickstart) —— 自部署后端,并通过 CLI 或 Desktop 运行时配置连接- [守护进程与运行时](/daemon-runtimes) —— 守护进程机制(Desktop 自动起它,但行为一样)diff --git a/apps/docs/content/docs/self-host-quickstart.mdx b/apps/docs/content/docs/self-host-quickstart.mdxindex 6acb73e188..12811bf455 100644--- a/apps/docs/content/docs/self-host-quickstart.mdx+++ b/apps/docs/content/docs/self-host-quickstart.mdx@@ -116,4 +116,4 @@ Same flow as Cloud — see [Cloud quickstart → Steps 5-6](/cloud-quickstart#5-- [Environment variables](/environment-variables) — full env reference- [Auth setup](/auth-setup) — Resend / OAuth / signup allowlist in detail- [Troubleshooting](/troubleshooting) — start here when things go wrong-- [Desktop app](/desktop-app) — released Desktop builds connect to Multica Cloud only; using Desktop with self-host requires a custom build (see the callout in the desktop-app page)+- [Desktop app](/desktop-app) — optional Desktop setup via `~/.multica/desktop.json`; the web frontend + CLI remains the quickest self-host pathdiff --git a/apps/docs/content/docs/self-host-quickstart.zh.mdx b/apps/docs/content/docs/self-host-quickstart.zh.mdxindex 8321de6484..c1a9dee06c 100644--- a/apps/docs/content/docs/self-host-quickstart.zh.mdx+++ b/apps/docs/content/docs/self-host-quickstart.zh.mdx@@ -115,4 +115,4 @@ multica setup self-host- [环境变量](/environment-variables) —— 完整 env 清单- [登录与注册配置](/auth-setup) —— Resend / OAuth / 注册白名单详细配置- [故障排查](/troubleshooting) —— 遇到问题先来这里-- [桌面应用](/desktop-app) —— 发布版 Desktop 只连 Multica Cloud;要让 Desktop 连自部署后端需要自行构建(详见 desktop-app 页的提示)+- [桌面应用](/desktop-app) —— 可以通过 `~/.multica/desktop.json` 连接 Desktop;Web 前端 + CLI 仍然是最快的自部署路径