Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix: broken "Add a computer" command on Multica Cloud + two CLI amplifiers (MUL-3087) (#3817)
Xinmin Zeng270d17747555
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.tsindex 87af1a47f2..62af33f155 100644--- a/apps/desktop/src/main/daemon-manager.ts+++ b/apps/desktop/src/main/daemon-manager.ts@@ -17,6 +17,7 @@ import {import { join } from "path";import { homedir, hostname } from "os";import type { DaemonStatus, DaemonPrefs } from "../shared/daemon-types";+import { daemonStatusAlive } from "../shared/daemon-types";import { ensureManagedCli, managedCliPath } from "./cli-bootstrap";import { decideVersionAction } from "./version-decision";import {@@ -35,6 +36,13 @@ const LOG_TAIL_MAX_RETRIES = 5;// take a while (it renews the PAT and lists workspaces before serving /health), so we// wait past the common case to avoid probing healthy-but-slow starts.const AUTH_PROBE_GRACE_MS = 10_000;+// `multica daemon start` blocks until the daemon reports ready, polling /health+// for up to its own startup timeout (45s in server/cmd/multica/cmd_daemon.go) to+// cover cold-start agent-version detection. This execFile timeout MUST stay+// above that — otherwise Electron kills the CLI supervisor mid-startup and a+// healthy-but-slow start is misreported as a failure (the detached daemon child+// keeps running, so the UI flashes "stopped" then "running").+const DAEMON_START_EXEC_TIMEOUT_MS = 60_000;const DEFAULT_PREFS: DaemonPrefs = { autoStart: true, autoStop: false };@@ -321,6 +329,13 @@ async function fetchHealth(): Promise<DaemonStatus> {if (authExpired) {return { state: "auth_expired", profile: active.name };}+ // The daemon binds /health before preflight finishes and self-reports+ // "starting" until it's ready. Trust that over our own currentState, so a+ // daemon booting on its own — or started via the CLI — surfaces as+ // "starting" instead of "stopped".+ if (data?.status === "starting") {+ return { state: "starting", profile: active.name };+ }return {state: currentState === "starting" ? "starting" : "stopped",profile: active.name,@@ -663,7 +678,10 @@ async function syncToken(if (userChanged) {try {const existing = await fetchHealthAtPort(active.port);- if (existing?.status === "running") {+ if (daemonStatusAlive(existing?.status)) {+ // Restart whether it's "running" or still "starting" — a booting daemon+ // already loaded the old token at startup, so it must be restarted to+ // pick up the rotated credentials.console.log("[daemon] user switched — restarting daemon with new credentials",);@@ -780,7 +798,10 @@ async function startDaemon(): Promise<{ success: boolean; error?: string }> {const active = await ensureActiveProfile();const existing = await fetchHealthAtPort(active.port);- if (existing?.status === "running") {+ if (daemonStatusAlive(existing?.status)) {+ // A daemon is already up ("running") or booting ("starting") on this port —+ // don't spawn a second one (the CLI rejects that as "already running").+ // Let polling track it through to "running".pollOnce();return { success: true };}@@ -798,7 +819,7 @@ async function startDaemon(): Promise<{ success: boolean; error?: string }> {execFile(bin,args,- { timeout: 20_000, env: desktopSpawnEnv() },+ { timeout: DAEMON_START_EXEC_TIMEOUT_MS, env: desktopSpawnEnv() },(err) => {if (err) {currentState = "stopped";diff --git a/apps/desktop/src/shared/daemon-types.test.ts b/apps/desktop/src/shared/daemon-types.test.tsnew file mode 100644index 0000000000..76c3bbf801--- /dev/null+++ b/apps/desktop/src/shared/daemon-types.test.ts@@ -0,0 +1,22 @@+import { describe, it, expect } from "vitest";+import { daemonStatusAlive } from "./daemon-types";++describe("daemonStatusAlive", () => {+ it("treats a ready daemon as alive", () => {+ expect(daemonStatusAlive("running")).toBe(true);+ });++ it("treats a still-booting daemon as alive", () => {+ // /health binds before preflight and reports "starting" until ready; the+ // Desktop must not spawn a second daemon over it (the CLI rejects that as+ // "already running").+ expect(daemonStatusAlive("starting")).toBe(true);+ });++ it("treats stopped / unknown / missing as not alive", () => {+ expect(daemonStatusAlive("stopped")).toBe(false);+ expect(daemonStatusAlive("bogus")).toBe(false);+ expect(daemonStatusAlive("")).toBe(false);+ expect(daemonStatusAlive(undefined)).toBe(false);+ });+});diff --git a/apps/desktop/src/shared/daemon-types.ts b/apps/desktop/src/shared/daemon-types.tsindex ed7f2b4fd2..4116ccb3f9 100644--- a/apps/desktop/src/shared/daemon-types.ts+++ b/apps/desktop/src/shared/daemon-types.ts@@ -58,6 +58,19 @@ export function formatUptime(uptime?: string): string {return `${h}${m}`.trim() || uptime;}+/**+ * Whether a raw daemon `/health` `status` value means a live daemon is on the+ * port — either fully "running" (ready) or still "starting" (port bound,+ * preflight in progress). Mirrors the Go `daemonAlive()` in+ * server/cmd/multica/cmd_daemon.go so the Desktop lifecycle agrees with the+ * CLI: a "starting" daemon is already there and must not be spawned over (the+ * CLI rejects that as "already running"). This is liveness, not readiness —+ * version-restart decisions still gate on the stricter "running".+ */+export function daemonStatusAlive(status: string | undefined): boolean {+ return status === "running" || status === "starting";+}+/*** User-facing description for the local daemon's current state. Replaces the* raw state label ("Running" / "Stopped") with a sentence that answersdiff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.goindex 96123b2b33..93cab6bc2a 100644--- a/server/cmd/multica/cmd_daemon.go+++ b/server/cmd/multica/cmd_daemon.go@@ -169,7 +169,7 @@ func runDaemonBackground(cmd *cobra.Command) error {ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)defer cancel()health := checkDaemonHealthOnPort(ctx, healthPort)- if health["status"] == "running" {+ if daemonAlive(health) {label := "daemon"if profile != "" {label = fmt.Sprintf("daemon [%s]", profile)@@ -238,21 +238,33 @@ func runDaemonBackground(cmd *cobra.Command) error {fmt.Fprintf(os.Stderr, "Warning: could not write PID file: %v\n", err)}- // Poll health endpoint until the daemon is ready or timeout.- deadline := time.Now().Add(15 * time.Second)+ // Poll the health endpoint until the daemon reports ready ("running") or we+ // time out. The daemon binds the health port almost immediately but reports+ // status:"starting" until preflight finishes (PAT renew + initial workspace+ // sync, which exec's every configured agent for version detection and can+ // take ~20s on a cold cache). Wait long enough to cover that so a healthy+ // cold start is not misreported as a failure.+ const startupTimeout = 45 * time.Second+ deadline := time.Now().Add(startupTimeout)started := false+ lastStatus := ""for time.Now().Before(deadline) {time.Sleep(500 * time.Millisecond)hctx, hcancel := context.WithTimeout(context.Background(), 2*time.Second)health = checkDaemonHealthOnPort(hctx, healthPort)hcancel()- if health["status"] == "running" {+ lastStatus, _ = health["status"].(string)+ if lastStatus == "running" {started = truebreak}}if !started {- fmt.Fprintf(os.Stderr, "Daemon may not have started successfully. Check logs:\n %s\n", logPath)+ if lastStatus == "starting" {+ fmt.Fprintf(os.Stderr, "Daemon is still starting after %s (agent detection / workspace sync is taking longer than expected). Check logs:\n %s\n", startupTimeout, logPath)+ } else {+ fmt.Fprintf(os.Stderr, "Daemon may not have started successfully. Check logs:\n %s\n", logPath)+ }return nil}@@ -443,7 +455,7 @@ func runDaemonRestart(cmd *cobra.Command, args []string) error {ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)defer cancel()health := checkDaemonHealthOnPort(ctx, healthPort)- if health["status"] == "running" {+ if daemonAlive(health) {pid, _ := health["pid"].(float64)if pid > 0 {fmt.Fprintf(os.Stderr, "Stopping daemon (pid %d)...\n", int(pid))@@ -452,12 +464,14 @@ func runDaemonRestart(cmd *cobra.Command, args []string) error {_ = p.Kill()}}+ // Wait until the port is fully released (not merely past "running"),+ // otherwise the fresh start below races the old daemon's listener.for i := 0; i < 10; i++ {time.Sleep(500 * time.Millisecond)sctx, scancel := context.WithTimeout(context.Background(), 1*time.Second)h := checkDaemonHealthOnPort(sctx, healthPort)scancel()- if h["status"] != "running" {+ if !daemonAlive(h) {break}}@@ -478,7 +492,7 @@ func runDaemonStop(cmd *cobra.Command, _ []string) error {defer cancel()health := checkDaemonHealthOnPort(ctx, healthPort)- if health["status"] != "running" {+ if !daemonAlive(health) {label := "Daemon"if profile != "" {label = fmt.Sprintf("Daemon [%s]", profile)@@ -518,7 +532,7 @@ func runDaemonStop(cmd *cobra.Command, _ []string) error {ctx2, cancel2 := context.WithTimeout(context.Background(), 1*time.Second)h := checkDaemonHealthOnPort(ctx2, healthPort)cancel2()- if h["status"] != "running" {+ if !daemonAlive(h) {os.Remove(daemonPIDPathForProfile(profile))fmt.Fprintln(os.Stderr, "Daemon stopped.")return nil@@ -571,12 +585,14 @@ func runDaemonStatus(cmd *cobra.Command, _ []string) error {label = fmt.Sprintf("Daemon [%s]", profile)}- if health["status"] != "running" {+ switch health["status"] {+ case "running":+ printDaemonStatusReport(os.Stdout, label, health)+ case "starting":+ fmt.Fprintf(os.Stdout, "%s: starting (pid %v)\n", label, health["pid"])+ default:fmt.Fprintf(os.Stdout, "%s: stopped\n", label)- return nil}-- printDaemonStatusReport(os.Stdout, label, health)return nil}@@ -628,6 +644,20 @@ func runDaemonLogs(cmd *cobra.Command, _ []string) error {return tailLogFile(logPath, lines, follow)}+// daemonAlive reports whether a health response indicates a live daemon+// process on the port — either fully "running" (ready) or still "starting"+// (port bound, preflight in progress). Lifecycle commands that only need to+// know "is a daemon there" (already-running guard, restart, stop) use this,+// whereas `daemon start`'s readiness wait gates on the stricter "running".+func daemonAlive(health map[string]any) bool {+ switch health["status"] {+ case "running", "starting":+ return true+ default:+ return false+ }+}+// checkDaemonHealthOnPort calls the daemon's local health endpoint on the given port.func checkDaemonHealthOnPort(ctx context.Context, port int) map[string]any {addr := fmt.Sprintf("http://127.0.0.1:%d/health", port)diff --git a/server/cmd/multica/cmd_daemon_test.go b/server/cmd/multica/cmd_daemon_test.goindex 473cb1383d..5db31fd8ae 100644--- a/server/cmd/multica/cmd_daemon_test.go+++ b/server/cmd/multica/cmd_daemon_test.go@@ -6,6 +6,35 @@ import ("testing")+// TestDaemonAlive locks in the liveness predicate the lifecycle commands rely+// on: both a ready ("running") and a still-booting ("starting") daemon count as+// alive, so `daemon start` won't double-spawn over a starting daemon and+// `restart`/`stop` will act on one; only "stopped"/unknown is "no daemon".+func TestDaemonAlive(t *testing.T) {+ t.Parallel()++ cases := []struct {+ status any+ want bool+ }{+ {"running", true},+ {"starting", true},+ {"stopped", false},+ {"", false},+ {nil, false},+ {"bogus", false},+ }+ for _, c := range cases {+ if got := daemonAlive(map[string]any{"status": c.status}); got != c.want {+ t.Errorf("daemonAlive(status=%v) = %v, want %v", c.status, got, c.want)+ }+ }+ // A response with no status key at all (e.g. malformed) is not alive.+ if daemonAlive(map[string]any{}) {+ t.Errorf("daemonAlive(no status) = true, want false")+ }+}+func TestPrintDaemonStatusIncludesCLIVersion(t *testing.T) {t.Parallel()diff --git a/server/cmd/multica/cmd_setup.go b/server/cmd/multica/cmd_setup.goindex 5966cd34bf..75f374ed6f 100644--- a/server/cmd/multica/cmd_setup.go+++ b/server/cmd/multica/cmd_setup.go@@ -190,26 +190,26 @@ func runSetupSelfHost(cmd *cobra.Command, args []string) error {}}- cfg := cli.CLIConfig{- ServerURL: serverURL,- AppURL: appURL,- }- if err := cli.SaveCLIConfigForProfile(cfg, profile); err != nil {+ // Probe before persisting anything. A failed setup must never overwrite a+ // working config or wipe the saved token: persistSelfHostConfigIfReachable+ // writes only when the server answers, so an unreachable host leaves the+ // existing config untouched and the user stays logged in.+ reachable, err := persistSelfHostConfigIfReachable(serverURL, appURL, profile, probeServer)+ if err != nil {return fmt.Errorf("save config: %w", err)}-- fmt.Fprintln(os.Stderr, "Configured for self-hosted server.")- fmt.Fprintf(os.Stderr, " server_url: %s\n", cfg.ServerURL)- fmt.Fprintf(os.Stderr, " app_url: %s\n", cfg.AppURL)- printConfigLocation(profile)-- // Check if the server is reachable.- if !probeServer(serverURL) {+ if !reachable {fmt.Fprintf(os.Stderr, "\n⚠ Server at %s is not reachable.\n", serverURL)- fmt.Fprintln(os.Stderr, " Make sure the server is running, then run 'multica login'.")+ fmt.Fprintln(os.Stderr, " Your existing configuration was left unchanged.")+ fmt.Fprintln(os.Stderr, " Verify the URL, then re-run 'multica setup self-host' once it's reachable.")return nil}+ fmt.Fprintln(os.Stderr, "Configured for self-hosted server.")+ fmt.Fprintf(os.Stderr, " server_url: %s\n", serverURL)+ fmt.Fprintf(os.Stderr, " app_url: %s\n", appURL)+ printConfigLocation(profile)+// Authenticate.fmt.Fprintln(os.Stderr, "")if err := runLogin(cmd, args); err != nil {@@ -225,6 +225,27 @@ func runSetupSelfHost(cmd *cobra.Command, args []string) error {return nil}+// persistSelfHostConfigIfReachable probes serverURL and, only when it answers,+// overwrites the profile config with the given self-host URLs. When the server+// is unreachable it leaves any existing config — and its auth token — untouched+// and returns false, so a failed `setup self-host` never logs the user out or+// clobbers a working config (the original ordering saved first, then probed,+// then bailed — wiping the token on every failed probe). The prober is injected+// so tests can exercise both branches without real network I/O.+func persistSelfHostConfigIfReachable(serverURL, appURL, profile string, probe func(string) bool) (bool, error) {+ if !probe(serverURL) {+ return false, nil+ }+ cfg := cli.CLIConfig{+ ServerURL: serverURL,+ AppURL: appURL,+ }+ if err := cli.SaveCLIConfigForProfile(cfg, profile); err != nil {+ return false, err+ }+ return true, nil+}+// serverHostIsLocal reports whether serverURL points at the same machine as// the CLI (loopback literal or "localhost"). Used to decide whether to infer// app_url from server_url or fall back to the local-dev default.diff --git a/server/cmd/multica/cmd_setup_test.go b/server/cmd/multica/cmd_setup_test.goindex c2d7a4fd11..7ed8988a8a 100644--- a/server/cmd/multica/cmd_setup_test.go+++ b/server/cmd/multica/cmd_setup_test.go@@ -1,6 +1,74 @@package main-import "testing"+import (+ "testing"++ "github.com/multica-ai/multica/server/internal/cli"+)++// TestPersistSelfHostConfigIfReachable verifies the fix for the+// setup-wipes-token bug: a failed reachability probe must leave the existing+// config (and its auth token) untouched, instead of overwriting it before the+// probe and bailing — which left the user logged out with no recovery.+func TestPersistSelfHostConfigIfReachable(t *testing.T) {+ t.Run("unreachable server preserves existing config and token", func(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ existing := cli.CLIConfig{+ ServerURL: "https://api.old.example",+ AppURL: "https://old.example",+ WorkspaceID: "ws-1",+ Token: "mul_existing_token",+ }+ if err := cli.SaveCLIConfig(existing); err != nil {+ t.Fatalf("seed config: %v", err)+ }++ proceed, err := persistSelfHostConfigIfReachable(+ "https://api.new.example", "https://new.example", "",+ func(string) bool { return false },+ )+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if proceed {+ t.Fatalf("proceed: want false for unreachable server")+ }++ got, err := cli.LoadCLIConfig()+ if err != nil {+ t.Fatalf("load config: %v", err)+ }+ if got.Token != "mul_existing_token" {+ t.Fatalf("token: want preserved, got %q", got.Token)+ }+ if got.ServerURL != "https://api.old.example" {+ t.Fatalf("server_url: want unchanged, got %q", got.ServerURL)+ }+ })++ t.Run("reachable server writes new self-host config", func(t *testing.T) {+ t.Setenv("HOME", t.TempDir())++ proceed, err := persistSelfHostConfigIfReachable(+ "https://api.new.example", "https://new.example", "",+ func(string) bool { return true },+ )+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !proceed {+ t.Fatalf("proceed: want true for reachable server")+ }++ got, err := cli.LoadCLIConfig()+ if err != nil {+ t.Fatalf("load config: %v", err)+ }+ if got.ServerURL != "https://api.new.example" || got.AppURL != "https://new.example" {+ t.Fatalf("config not written: %+v", got)+ }+ })+}func TestServerHostIsLocal(t *testing.T) {cases := []struct {@@ -24,4 +92,3 @@ func TestServerHostIsLocal(t *testing.T) {})}}-diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 64b90f1523..8a78c27d7a 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -112,6 +112,7 @@ type Daemon struct {restartBinary string // non-empty after a successful update; path to the new binaryupdating atomic.Bool // prevents concurrent update attemptsactiveTasks atomic.Int64 // number of tasks currently in handleTask; exposed via /health+ ready atomic.Bool // false until preflight completes; gates /health status (starting -> running)// claimMu guards pauseClaims and claimsInFlight. It is held only for the// microseconds it takes to make a decision; ClaimTask itself runs without@@ -620,6 +621,17 @@ func (d *Daemon) Run(ctx context.Context) error {return err}+ // Bind and serve the health port before the (potentially slow) preflight,+ // so `daemon start` and the desktop see a live "starting" daemon instead+ // of connection-refused while preflightAuth runs. preflightAuth's initial+ // workspace sync detects every configured agent's version by exec'ing it,+ // which on a cold cache with many agents takes ~20s. Liveness (port up) and+ // readiness (status:"running") are reported separately: /health stays+ // "starting" until d.ready is set after preflight, so a slow or *failing*+ // preflight is never misreported as a started daemon. resolveAuth has+ // already run, so a missing token still fails fast before we begin serving.+ go d.serveHealth(ctx, healthLn, time.Now())+// Renew the PAT before the first API call, then do the initial// workspace sync. Both steps live in preflightAuth so the ordering// invariant (renew first) is enforced at one site instead of@@ -641,8 +653,14 @@ func (d *Daemon) Run(ctx context.Context) error {go d.gcLoop(ctx)go d.autoUpdateLoop(ctx)go d.tokenRenewalLoop(ctx)- go d.serveHealth(ctx, healthLn, time.Now())- d.logger.Debug("background loops launched (workspace-sync, task-wakeup, heartbeat, gc, auto-update, token-renewal, health)")++ // Preflight succeeded and the background loops are up: the daemon has+ // registered its runtimes and can now claim and run tasks. Flip /health+ // from "starting" to "running" — this is the signal `daemon start`'s+ // readiness wait blocks on, so success is reported only after startup+ // actually completed, not merely because the health port came up.+ d.ready.Store(true)+ d.logger.Debug("background loops launched (workspace-sync, task-wakeup, heartbeat, gc, auto-update, token-renewal); health now reporting ready")err = d.pollLoop(ctx, taskWakeups)d.logger.Debug("daemon main loop returning", "error", err)return errdiff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.goindex e8238b5552..82efcb64f4 100644--- a/server/internal/daemon/health.go+++ b/server/internal/daemon/health.go@@ -72,8 +72,19 @@ func (d *Daemon) healthHandler(startedAt time.Time) http.HandlerFunc {agents = append(agents, name)}+ // "starting" until preflight (PAT renew + initial workspace sync ++ // runtime registration) completes; "running" once the daemon can+ // actually claim tasks. The health port is bound before preflight for+ // liveness/diagnostics, so callers must not treat a reachable endpoint+ // as ready — they gate on this status. Consumers that only know+ // "running" (older CLI/desktop) safely treat "starting" as not-ready.+ status := "starting"+ if d.ready.Load() {+ status = "running"+ }+resp := HealthResponse{- Status: "running",+ Status: status,PID: os.Getpid(),Uptime: time.Since(startedAt).Truncate(time.Second).String(),DaemonID: d.cfg.DaemonID,diff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.goindex 470d637992..81818ce5c1 100644--- a/server/internal/daemon/health_test.go+++ b/server/internal/daemon/health_test.go@@ -27,6 +27,7 @@ func TestHealthHandlerReportsCLIVersionAndActiveTaskCount(t *testing.T) {logger: slog.Default(),}d.activeTasks.Store(3)+ d.ready.Store(true) // preflight done -> status should be "running"req := httptest.NewRequest(http.MethodGet, "/health", nil)rec := httptest.NewRecorder()@@ -68,6 +69,42 @@ func TestHealthHandlerReportsCLIVersionAndActiveTaskCount(t *testing.T) {}}+// TestHealthHandlerReportsStartingUntilReady pins the liveness/readiness split:+// the health server binds and answers before preflight finishes, but it must+// report "starting" until d.ready is set, and only then "running". Otherwise a+// slow or failing preflight would be misreported to `daemon start` (and the+// desktop) as a fully started daemon.+func TestHealthHandlerReportsStartingUntilReady(t *testing.T) {+ t.Parallel()++ d := &Daemon{+ cfg: Config{CLIVersion: "v1.0.0"},+ workspaces: map[string]*workspaceState{},+ logger: slog.Default(),+ }+ handler := d.healthHandler(time.Now())++ readStatus := func() string {+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/health", nil))+ var resp HealthResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ return resp.Status+ }++ if got := readStatus(); got != "starting" {+ t.Fatalf("status before ready: got %q, want \"starting\"", got)+ }++ d.ready.Store(true)++ if got := readStatus(); got != "running" {+ t.Fatalf("status after ready: got %q, want \"running\"", got)+ }+}+func TestHealthHandlerActiveTaskCountTracksCounter(t *testing.T) {t.Parallel()diff --git a/server/internal/handler/config.go b/server/internal/handler/config.goindex 720d4b6358..cda8e911a7 100644--- a/server/internal/handler/config.go+++ b/server/internal/handler/config.go@@ -80,7 +80,7 @@ func daemonSetupURLsFromEnv() (string, string) {if serverURL == "" {serverURL = appURL}- if isOfficialCloudDaemonConfig(serverURL, appURL) {+ if isOfficialCloudDaemonConfig(appURL) {return "", ""}return serverURL, appURL@@ -90,10 +90,16 @@ func normalizePublicURL(raw string) string {return strings.TrimRight(strings.TrimSpace(raw), "/")}-func isOfficialCloudDaemonConfig(serverURL, appURL string) bool {- if !urlHostEquals(serverURL, "api.multica.ai") {- return false- }+// isOfficialCloudDaemonConfig reports whether this deployment is the official+// Multica Cloud, identified by its frontend host alone (multica.ai /+// app.multica.ai). The daemon setup for the managed cloud is always+// `multica setup` (which hardcodes api.multica.ai), so the per-deployment URLs+// must be omitted from /api/config even when MULTICA_PUBLIC_URL is unset or+// misconfigured. Previously this also required serverURL==api.multica.ai, so a+// cloud deployment that forgot MULTICA_PUBLIC_URL fell through and emitted a+// `setup self-host --server-url https://multica.ai` command — pointing the+// daemon's backend at the frontend (no /health, no WebSocket proxy).+func isOfficialCloudDaemonConfig(appURL string) bool {return urlHostEquals(appURL, "multica.ai") || urlHostEquals(appURL, "app.multica.ai")}diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.goindex 9a9a29e63d..8189661947 100644--- a/server/internal/handler/config_test.go+++ b/server/internal/handler/config_test.go@@ -131,6 +131,67 @@ func TestGetConfigOmitsOfficialCloudDaemonSetup(t *testing.T) {}}+// TestGetConfigOmitsCloudDaemonSetupWithoutPublicURL reproduces the production+// regression behind the broken "Add a computer" command: the official cloud+// frontend is multica.ai, but the deployment does not set MULTICA_PUBLIC_URL to+// the api host. Previously this fell through to the same-origin branch and+// emitted daemon_server_url=https://multica.ai, which the dialog turned into+// `multica setup self-host --server-url https://multica.ai` — pointing the+// daemon's backend at the frontend (no /health, no WebSocket proxy). The+// official cloud must be recognised by its frontend host alone so the daemon+// setup URLs are omitted and the dialog falls back to `multica setup`.+func TestGetConfigOmitsCloudDaemonSetupWithoutPublicURL(t *testing.T) {+ t.Setenv("MULTICA_PUBLIC_URL", "")+ t.Setenv("MULTICA_APP_URL", "")+ t.Setenv("FRONTEND_ORIGIN", "https://multica.ai")++ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)+ w := httptest.NewRecorder()++ testHandler.GetConfig(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("GetConfig: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var cfg AppConfig+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {+ t.Fatalf("decode config: %v", err)+ }+ if cfg.DaemonServerURL != "" {+ t.Fatalf("daemon_server_url: want omitted for official cloud, got %q", cfg.DaemonServerURL)+ }+ if cfg.DaemonAppURL != "" {+ t.Fatalf("daemon_app_url: want omitted for official cloud, got %q", cfg.DaemonAppURL)+ }+}++// TestGetConfigOmitsCloudDaemonSetupForAppSubdomain covers the app.multica.ai+// frontend variant of the official cloud.+func TestGetConfigOmitsCloudDaemonSetupForAppSubdomain(t *testing.T) {+ t.Setenv("MULTICA_PUBLIC_URL", "")+ t.Setenv("MULTICA_APP_URL", "https://app.multica.ai")+ t.Setenv("FRONTEND_ORIGIN", "")++ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)+ w := httptest.NewRecorder()++ testHandler.GetConfig(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("GetConfig: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var cfg AppConfig+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {+ t.Fatalf("decode config: %v", err)+ }+ if cfg.DaemonServerURL != "" {+ t.Fatalf("daemon_server_url: want omitted for official cloud, got %q", cfg.DaemonServerURL)+ }+ if cfg.DaemonAppURL != "" {+ t.Fatalf("daemon_app_url: want omitted for official cloud, got %q", cfg.DaemonAppURL)+ }+}+func TestURLHostEqualsCanonicalizesCommonHostForms(t *testing.T) {tests := []struct {name string