Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7988: recover daemon when profile health port is unavailable (#9217)
Multica Eve191c782d60f8
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 948de8a1fc..14dc0dcab8 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -508,7 +508,7 @@ multica daemon start --profile stagingmultica daemon start```-Each profile gets its own config directory (`~/.multica/profiles/<name>/`), daemon state, health port, and workspace root. Daemon state means that profile's own `daemon.log`, `daemon.err.log`, and `daemon.pid` live in that directory too — see [Start](#start) for the layout, and pass `--profile <name>` to `daemon status` / `daemon logs` to act on it.+Each profile gets its own config directory (`~/.multica/profiles/<name>/`), daemon state, health port, and workspace root. Daemon state means that profile's own `daemon.log`, `daemon.err.log`, `daemon.pid`, and `daemon.port` live in that directory too — see [Start](#start) for the layout, and pass `--profile <name>` to `daemon status` / `daemon logs` to act on it. The daemon normally uses the profile-derived health port. If the OS refuses that port, it binds an available loopback port and records the actual port in `daemon.port` for lifecycle commands. The record is valid only while its daemon is alive; do not edit it to configure a port.## Workspacesdiff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.tsindex 365eb55665..4b645baf59 100644--- a/apps/desktop/src/main/daemon-manager.ts+++ b/apps/desktop/src/main/daemon-manager.ts@@ -26,7 +26,6 @@ import { ensureManagedCli, managedCliPath } from "./cli-bootstrap";import { decideVersionAction } from "./version-decision";import {deriveProfileName,- healthPortForProfile,profileArgs,profileConfigPath,profileDir,@@ -34,6 +33,7 @@ import {profilePidPath,profileUserIdPath,} from "./daemon-profile";+import { probeProfileHealth } from "./daemon-port";import {DaemonOperationGate,DaemonRecoveryPolicy,@@ -80,7 +80,6 @@ const DEFAULT_PREFS: DaemonPrefs = { autoStart: true, autoStop: false };// `null` at every call site, never by an empty name — see daemon-profile.ts.interface ActiveProfile {name: string;- port: number;}let statusPollTimer: ReturnType<typeof setInterval> | null = null;@@ -171,6 +170,7 @@ function sendStatus(status: DaemonStatus): void {interface HealthPayload {status?: string;pid?: number;+ profile?: string;/** Daemon's runtime.GOOS. Absent on daemons older than the #3916 fix. */os?: string;uptime?: string;@@ -202,6 +202,15 @@ async function fetchHealthAtPort(}}+async function fetchProfileHealth(+ active: ActiveProfile,+ timeoutMs = HEALTH_PROBE_TIMEOUT_MS,+): Promise<HealthPayload | null> {+ return probeProfileHealth(active.name, (port) =>+ fetchHealthAtPort(port, timeoutMs),+ );+}+/*** Validates the daemon profile's token against the backend to find out whether* a stuck start is an auth problem. Hits the same endpoint `multica auth status`@@ -283,7 +292,7 @@ async function resolveActiveProfile(): Promise<ActiveProfile | null> {console.log(`[daemon] initialized profile "${name}" → ${target}`);}- return { name, port: healthPortForProfile(name) };+ return { name };}async function ensureActiveProfile(): Promise<ActiveProfile | null> {@@ -328,7 +337,7 @@ async function fetchHealth(): Promise<DaemonStatus> {// 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);+ const data = await fetchProfileHealth(active);if (!data || data.status !== "running") {// A start that never reaches "running" is the symptom; an expired/invalid@@ -600,7 +609,7 @@ async function ensureRunningDaemonVersionMatches(): Promise<> {const active = await ensureActiveProfile();if (!active) return "not_running";- const running = await fetchHealthAtPort(active.port);+ const running = await fetchProfileHealth(active);// Don't try to version-match a daemon we can't restart (e.g. WSL2). Treat it// as up-to-date — restartDaemon would no-op anyway, and skipping here avoids@@ -741,7 +750,7 @@ async function restartDaemonAfterUserSwitch(): Promise<void> {// If we just rotated credentials onto a running daemon, restart it so the// in-memory token in the Go process matches the new config.- const existing = await fetchHealthAtPort(active.port);+ const existing = await fetchProfileHealth(active);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@@ -960,7 +969,7 @@ async function startDaemon() {return { success: false, error: "Daemon recovery was superseded" };}- const existing = await fetchHealthAtPort(active.port);+ const existing = await fetchProfileHealth(active);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").@@ -1028,7 +1037,7 @@ async function lifecycleBlockedByForeignDaemon(): Promise<boolean> {const active = await ensureActiveProfile();if (!active) return false;return daemonLifecycleUnreachable(- async () => (await fetchHealthAtPort(active.port))?.os,+ async () => (await fetchProfileHealth(active))?.os,normalizeHostOS(process.platform),);}@@ -1119,10 +1128,7 @@ async function attemptDaemonRecovery(active: ActiveProfile): Promise<void> {// as process death, use an independent longer probe so a busy daemon is// not restarted merely because one health request was slow.confirmAlive: async () => {- const health = await fetchHealthAtPort(- active.port,- RECOVERY_HEALTH_PROBE_TIMEOUT_MS,- );+ const health = await fetchProfileHealth(active, RECOVERY_HEALTH_PROBE_TIMEOUT_MS);if (!daemonStatusAlive(health?.status)) return false;externalDaemonObserved = isDaemonExternallyManaged(health?.os,diff --git a/apps/desktop/src/main/daemon-port.test.ts b/apps/desktop/src/main/daemon-port.test.tsnew file mode 100644index 0000000000..ace34c6479--- /dev/null+++ b/apps/desktop/src/main/daemon-port.test.ts@@ -0,0 +1,57 @@+// @vitest-environment node+import { describe, expect, it, vi } from "vitest";++import { healthPortForProfile } from "./daemon-profile";+import { parseDaemonPortRecord, probeProfileHealth } from "./daemon-port";++const profile = "desktop-api.multica.ai";++describe("daemon port discovery", () => {+ it("accepts only a live matching profile and PID from daemon.port", async () => {+ const probe = vi.fn(async (port: number) =>+ port === 30001+ ? { status: "running", profile, pid: 42 }+ : null,+ );+ const health = await probeProfileHealth(profile, probe, async () => ({+ port: 30001,+ pid: 42,+ }));+ expect(health?.pid).toBe(42);+ expect(probe).toHaveBeenCalledTimes(1);+ });++ it.each([+ { status: "running", profile, pid: 99 },+ { status: "running", profile: "other", pid: 42 },+ { status: "stopped", profile, pid: 42 },+ ])("ignores a stale record and probes the legacy port: %o", async (stale) => {+ const fallback = { status: "running", profile, pid: 7 };+ const probe = vi.fn(async (port: number) =>+ port === 30001 ? stale : fallback,+ );+ expect(+ await probeProfileHealth(profile, probe, async () => ({ port: 30001, pid: 42 })),+ ).toEqual(fallback);+ expect(probe).toHaveBeenLastCalledWith(healthPortForProfile(profile));+ });++ it("reads a changed port for every poll", async () => {+ let port = 30001;+ const probe = vi.fn(async (candidate: number) =>+ candidate === port ? { status: "starting", profile, pid: 42 } : null,+ );+ const readRecord = async () => ({ port, pid: 42 });+ expect(await probeProfileHealth(profile, probe, readRecord)).not.toBeNull();+ port = 30002;+ expect(await probeProfileHealth(profile, probe, readRecord)).not.toBeNull();+ expect(probe.mock.calls.map(([candidate]) => candidate)).toEqual([30001, 30002]);+ });++ it("rejects malformed records", () => {+ for (const raw of ["", "null", "{}", '{"port":0,"pid":1}', '{"port":65536,"pid":1}', '{"port":30001,"pid":0}']) {+ expect(parseDaemonPortRecord(raw)).toBeNull();+ }+ expect(parseDaemonPortRecord('{"port":30001,"pid":42}')).toEqual({ port: 30001, pid: 42 });+ });+});diff --git a/apps/desktop/src/main/daemon-port.ts b/apps/desktop/src/main/daemon-port.tsnew file mode 100644index 0000000000..7ad8b59b68--- /dev/null+++ b/apps/desktop/src/main/daemon-port.ts@@ -0,0 +1,64 @@+import { readFile } from "fs/promises";+import { healthPortForProfile, profilePortPath } from "./daemon-profile";++export interface DaemonPortRecord {+ port: number;+ pid: number;+}++export function parseDaemonPortRecord(raw: string): DaemonPortRecord | null {+ try {+ const value: unknown = JSON.parse(raw);+ if (!value || typeof value !== "object") return null;+ const { port, pid } = value as Record<string, unknown>;+ if (+ typeof port !== "number" ||+ !Number.isInteger(port) ||+ port < 1 ||+ port > 65535 ||+ typeof pid !== "number" ||+ !Number.isSafeInteger(pid) ||+ pid < 1+ ) return null;+ return { port, pid };+ } catch {+ return null;+ }+}++export async function readDaemonPortRecord(profile: string): Promise<DaemonPortRecord | null> {+ try {+ return parseDaemonPortRecord(await readFile(profilePortPath(profile), "utf-8"));+ } catch {+ return null;+ }+}++interface ProfileHealth {+ status?: string;+ profile?: string;+ pid?: number;+}++// The record can survive a crash or a supervisor handoff. Probe it on every+// call; only a live daemon with the expected identity is allowed to replace the+// profile's legacy port. This also lets Desktop follow a changed port without+// rebuilding its cached profile.+export async function probeProfileHealth<T extends ProfileHealth>(+ profile: string,+ probe: (port: number) => Promise<T | null>,+ readRecord: () => Promise<DaemonPortRecord | null> = () => readDaemonPortRecord(profile),+): Promise<T | null> {+ const record = await readRecord();+ if (record) {+ const health = await probe(record.port);+ if (+ (health?.status === "running" || health?.status === "starting") &&+ health.profile === profile &&+ health.pid === record.pid+ ) return health;+ }+ const health = await probe(healthPortForProfile(profile));+ if (health?.profile !== undefined && health.profile !== profile) return null;+ return health;+}diff --git a/apps/desktop/src/main/daemon-profile.ts b/apps/desktop/src/main/daemon-profile.tsindex 00b2fc729c..19e4345d82 100644--- a/apps/desktop/src/main/daemon-profile.ts+++ b/apps/desktop/src/main/daemon-profile.ts@@ -64,6 +64,10 @@ export function profilePidPath(profile: string): string {return join(profileDir(profile), "daemon.pid");}+export function profilePortPath(profile: string): string {+ return join(profileDir(profile), "daemon.port");+}+// 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 adiff --git a/apps/desktop/src/main/daemon-recovery.test.ts b/apps/desktop/src/main/daemon-recovery.test.tsindex 9e6517fe6e..e35d1acc71 100644--- a/apps/desktop/src/main/daemon-recovery.test.ts+++ b/apps/desktop/src/main/daemon-recovery.test.ts@@ -151,7 +151,7 @@ describe("DaemonRecoveryPolicy", () => {});describe("recovery orchestration guards", () => {- const profile = { name: "desktop-api.multica.ai", port: 19_999 };+ const profile = { name: "desktop-api.multica.ai" };it("allows first-start recovery for a Desktop-owned profile", () => {expect(@@ -285,7 +285,6 @@ describe("recovery orchestration guards", () => {{ externalDaemonObserved: true },{ current: null },{ current: { ...profile, name: "desktop-other" } },- { current: { ...profile, port: profile.port + 1 } },])("rejects a superseded recovery: %o", (override) => {expect(recoveryStartAllowed({diff --git a/apps/desktop/src/main/daemon-recovery.ts b/apps/desktop/src/main/daemon-recovery.tsindex e86bc84fd3..f3ac4ea9a8 100644--- a/apps/desktop/src/main/daemon-recovery.ts+++ b/apps/desktop/src/main/daemon-recovery.ts@@ -140,7 +140,6 @@ export class DaemonRecoveryPolicy {export interface RecoveryProfile {name: string;- port: number;}export interface DaemonLifecycleResult {@@ -214,8 +213,7 @@ export function recoveryStartAllowed(input: {input.desiredRunning &&!input.externalDaemonObserved &&input.current &&- input.current.name === input.expected.name &&- input.current.port === input.expected.port,+ input.current.name === input.expected.name,);}diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex a5af845337..4b3cd77c16 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -229,7 +229,7 @@ multica config showmultica config show --profile staging```-Do not set `MULTICA_DAEMON_PORT` in the host shell, Compose service, or container entrypoint that starts a daemon. The host daemon derives its health port from `--profile` and injects this variable into agent tasks itself. Remove the variable from older startup environments entirely: versions 0.4.22 and 0.4.23 otherwise mistake that shell for a managed task and reject login. Newer versions let guarded human login and `daemon status` recover when the port is the only task signal, but ordinary API and profile-resolving commands intentionally remain fail-closed until the variable is removed.+Do not set `MULTICA_DAEMON_PORT` in the host shell, Compose service, or container entrypoint that starts a daemon. The host daemon normally derives its health port from `--profile`; if that port cannot be bound, it uses an available loopback port and injects the actual port into agent tasks itself. Remove the variable from older startup environments entirely: versions 0.4.22 and 0.4.23 otherwise mistake that shell for a managed task and reject login. Newer versions let guarded human login and `daemon status` recover when the port is the only task signal, but ordinary API and profile-resolving commands intentionally remain fail-closed until the variable is removed.When the CLI runs inside a daemon-managed agent task, it does not load or modify these human-owned profile files. Multica API commands authenticate with the task-scoped credential injected by the daemon. `config show` and `config set` use private task-local state; human/local commands such as `login`, `logout`, `setup`, `workspace switch`, local runtime profile path changes, `daemon start` / `stop` / `restart`, `daemon logs`, and `daemon probe-runtimes` are unavailable. `auth status` does not print token material in this context.diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.goindex 01b1777c62..6b7a3ee598 100644--- a/server/cmd/multica/cmd_daemon.go+++ b/server/cmd/multica/cmd_daemon.go@@ -8,6 +8,7 @@ import ("io""io/fs""log/slog"+ "net""net/http""os""os/exec"@@ -557,7 +558,7 @@ func runDaemonStart(cmd *cobra.Command, _ []string) error {func runDaemonBackground(cmd *cobra.Command) error {profile := resolveProfile(cmd)- healthPort := healthPortForProfile(profile)+ healthPort := resolveHealthPort(profile)// Check if daemon is already running.ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)@@ -565,21 +566,20 @@ func runDaemonBackground(cmd *cobra.Command) error {health := checkDaemonHealthOnPort(ctx, healthPort)if daemonAlive(health) {// A live daemon on our port that belongs to someone else is a- // collision, not an "already running" — starting would fail to bind- // and "already running" would send the user looking for a daemon of- // theirs that does not exist.+ // collision. The foreground child can safely use a fallback port.if err := daemonIdentityMismatch(health, profile, healthPort); err != nil {- return err- }- // Even a no-op start keeps the autostart contract: hint when nothing- // is registered, silently refresh an entry Multica owns.- syncDaemonAutostart(profile, true)- label := "daemon"- if profile != "" {- label = fmt.Sprintf("daemon [%s]", profile)+ fmt.Fprintf(os.Stderr, "Preferred health port %d belongs to another profile; trying a fallback port.\n", healthPort)+ } else {+ // Even a no-op start keeps the autostart contract: hint when nothing+ // is registered, silently refresh an entry Multica owns.+ syncDaemonAutostart(profile, true)+ label := "daemon"+ if profile != "" {+ label = fmt.Sprintf("daemon [%s]", profile)+ }+ pid, _ := health["pid"].(float64)+ return fmt.Errorf("%s is already running (pid %v). Use 'daemon restart' to restart it", label, int(pid))}- pid, _ := health["pid"].(float64)- return fmt.Errorf("%s is already running (pid %v). Use 'daemon restart' to restart it", label, int(pid))}if err := requireDaemonAuth(profile); err != nil {@@ -604,6 +604,9 @@ func runDaemonBackground(cmd *cobra.Command) error {if err := os.MkdirAll(dir, 0o755); err != nil {return fmt.Errorf("create daemon directory: %w", err)}+ if err := waitForDaemonProfileRelease(profile, daemonShutdownLockWait); err != nil {+ return err+ }// The child (foreground daemon) writes daemon.log itself through a// rotating writer; its inherited stdout/stderr only need to catch raw@@ -697,11 +700,17 @@ func runDaemonBackground(cmd *cobra.Command) error {}, waitErr, profile, resolveDaemonServerURL(cmd, profile))case <-time.After(500 * time.Millisecond):}+ // The child publishes the port only after it has bound the listener.+ // Ignore a stale record from a previous daemon, even if its port works.+ record, ok := readDaemonPortRecord(profile)+ if !ok || record.PID != pid {+ continue+ }hctx, hcancel := context.WithTimeout(context.Background(), 2*time.Second)- health = checkDaemonHealthOnPort(hctx, healthPort)+ health = checkDaemonHealthOnPort(hctx, record.Port)hcancel()lastStatus, _ = health["status"].(string)- if lastStatus == "running" {+ if lastStatus == "running" && health["profile"] == profile && health["pid"] == float64(pid) {started = truebreak}@@ -1094,6 +1103,31 @@ func runDaemonForeground(cmd *cobra.Command) error {// 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")+ lock, err := acquireDaemonProfileLock(profile, os.Getenv("MULTICA_DAEMON_HANDOFF") == "1")+ if err != nil {+ return err+ }+ defer lock.Close()+ _ = os.Unsetenv("MULTICA_DAEMON_HANDOFF")+ // An older daemon has no profile lock. A direct --foreground start must+ // still refuse to launch a second daemon for that same profile.+ port := resolveHealthPort(profile)+ probeCtx, probeCancel := context.WithTimeout(context.Background(), 2*time.Second)+ existing := checkDaemonHealthOnPort(probeCtx, port)+ probeCancel()+ if daemonAlive(existing) && daemonIdentityMismatch(existing, profile, port) == nil {+ return fmt.Errorf("daemon %s is already running or starting", describeProfile(profile))+ }+ healthLn, actualPort, err := bindDaemonHealthPort(cfg.HealthPort, net.Listen)+ if err != nil {+ return err+ }+ defer healthLn.Close()+ cfg.HealthPort = actualPort+ if err := publishDaemonPort(profile, daemonPortRecord{Port: actualPort, PID: os.Getpid()}); err != nil {+ return fmt.Errorf("publish daemon health port: %w", err)+ }+ defer removeDaemonPortIfOwned(profile, os.Getpid())ctx, stop := notifyShutdownContext(context.Background())defer stop()@@ -1107,7 +1141,7 @@ func runDaemonForeground(cmd *cobra.Command) error {}defer os.Remove(daemonPIDPathForProfile(profile))- if err := d.Run(ctx); err != nil && !errors.Is(err, context.Canceled) {+ if err := d.RunWithHealthListener(ctx, healthLn); err != nil && !errors.Is(err, context.Canceled) {return err}@@ -1144,6 +1178,7 @@ func runDaemonForeground(cmd *cobra.Command) error {args := buildDaemonStartArgs(cmd)child := exec.Command(restartBin, args...)+ child.Env = append(os.Environ(), "MULTICA_DAEMON_HANDOFF=1")// The successor is a fresh foreground daemon that will open daemon.log// through its own rotating writer; hand it the raw-stderr sink so its@@ -1169,6 +1204,7 @@ func runDaemonForeground(cmd *cobra.Command) error {// duplicate cleanup here.if isAccessDeniedSpawnErr(err) {child = exec.Command(restartBin, args...)+ child.Env = append(os.Environ(), "MULTICA_DAEMON_HANDOFF=1")child.Stdout = logFilechild.Stderr = logFilechild.SysProcAttr = daemonSysProcAttr(false)@@ -1252,7 +1288,7 @@ func runDaemonRestart(cmd *cobra.Command, args []string) error {if err := requireKnownProfile(profile); err != nil {return err}- healthPort := healthPortForProfile(profile)+ healthPort := resolveHealthPort(profile)ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)defer cancel()@@ -1297,6 +1333,13 @@ func runDaemonRestart(cmd *cobra.Command, args []string) error {}// Start fresh.+ // Foreground restarts do not pass through runDaemonBackground, so they+ // need the same shutdown wait before their short child lock timeout.+ if foreground, _ := cmd.Flags().GetBool("foreground"); foreground {+ if err := waitForDaemonProfileRelease(profile, daemonShutdownLockWait); err != nil {+ return err+ }+ }return runDaemonStart(cmd, args)}@@ -1310,7 +1353,7 @@ func runDaemonStop(cmd *cobra.Command, _ []string) error {if err := requireKnownProfile(profile); err != nil {return err}- healthPort := healthPortForProfile(profile)+ healthPort := resolveHealthPort(profile)ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)defer cancel()@@ -1482,7 +1525,7 @@ func runDaemonStatus(cmd *cobra.Command, _ []string) error {func daemonStatusHealthPort(cmd *cobra.Command) (int, error) {profile := resolveProfile(cmd)if !inDaemonTaskIdentityContext() {- return healthPortForProfile(profile), nil+ return resolveHealthPort(profile), nil}if profile != "" {return 0, fmt.Errorf("daemon status --profile is not available inside a daemon-managed task")diff --git a/server/cmd/multica/cmd_daemon_identity_test.go b/server/cmd/multica/cmd_daemon_identity_test.goindex ce1fb578ac..261c1ebc16 100644--- a/server/cmd/multica/cmd_daemon_identity_test.go+++ b/server/cmd/multica/cmd_daemon_identity_test.go@@ -180,7 +180,6 @@ func TestDaemonLifecycleRefusesForeignDaemon(t *testing.T) {}{{"stop", func(c *cobra.Command) error { return runDaemonStop(c, nil) }},{"restart", func(c *cobra.Command) error { return runDaemonRestart(c, nil) }},- {"start", func(c *cobra.Command) error { return runDaemonBackground(c) }},}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {@@ -205,6 +204,18 @@ func TestDaemonLifecycleRefusesForeignDaemon(t *testing.T) {}}+func TestDaemonStartCanFallBackFromForeignProfilePort(t *testing.T) {+ clearDaemonTaskEnv(t)+ mkProfiles(t, "collide-ab", "collide-ba")+ serveHealthAs(t, "collide-ab", map[string]any{"profile": "collide-ab"})+ cmd := daemonStatusCmdFor(t, "collide-ba", "")+ cmd.Flags().Bool("foreground", false, "")+ err := runDaemonBackground(cmd)+ if err == nil || !strings.Contains(err.Error(), "not logged in") {+ t.Fatalf("start error = %v, want auth check after allowing a fallback port", err)+ }+}+// A daemon too old to identify itself must keep working: stop runs to// completion against it rather than refusing.//diff --git a/server/cmd/multica/cmd_daemon_port.go b/server/cmd/multica/cmd_daemon_port.gonew file mode 100644index 0000000000..8302d7644a--- /dev/null+++ b/server/cmd/multica/cmd_daemon_port.go@@ -0,0 +1,122 @@+package main++import (+ "context"+ "encoding/json"+ "fmt"+ "net"+ "os"+ "path/filepath"+ "runtime"+ "time"+)++type daemonPortRecord struct {+ Port int `json:"port"`+ PID int `json:"pid"`+}++func daemonPortPathForProfile(profile string) string {+ return filepath.Join(daemonDirForProfile(profile), "daemon.port")+}++func readDaemonPortRecord(profile string) (daemonPortRecord, bool) {+ if daemonDirForProfile(profile) == "" {+ return daemonPortRecord{}, false+ }+ data, err := os.ReadFile(daemonPortPathForProfile(profile))+ if err != nil {+ return daemonPortRecord{}, false+ }+ var record daemonPortRecord+ if json.Unmarshal(data, &record) != nil || record.Port < 1 || record.Port > 65535 || record.PID < 1 {+ return daemonPortRecord{}, false+ }+ return record, true+}++// resolveHealthPort treats daemon.port as a hint, never as proof of ownership.+// A crash or systemd handoff can leave it behind. Old daemons without this file+// remain discoverable at the profile-derived port.+func resolveHealthPort(profile string) int {+ if record, ok := readDaemonPortRecord(profile); ok {+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ health := checkDaemonHealthOnPort(ctx, record.Port)+ cancel()+ if daemonAlive(health) && health["profile"] == profile && health["pid"] == float64(record.PID) {+ return record.Port+ }+ }+ return healthPortForProfile(profile)+}++func publishDaemonPort(profile string, record daemonPortRecord) error {+ dir := daemonDirForProfile(profile)+ if dir == "" {+ return fmt.Errorf("resolve daemon profile directory")+ }+ if err := os.MkdirAll(dir, 0o755); err != nil {+ return err+ }+ f, err := os.CreateTemp(dir, ".daemon.port-*")+ if err != nil {+ return err+ }+ tmp := f.Name()+ defer os.Remove(tmp)+ if err := f.Chmod(0o600); err != nil {+ f.Close()+ return err+ }+ data, err := json.Marshal(record)+ if err == nil {+ _, err = f.Write(data)+ }+ if err == nil {+ err = f.Sync()+ }+ if closeErr := f.Close(); err == nil {+ err = closeErr+ }+ if err != nil {+ return err+ }+ path := daemonPortPathForProfile(profile)+ for attempt := 0; ; attempt++ {+ err = os.Rename(tmp, path)+ if err == nil || runtime.GOOS != "windows" || attempt == 9 {+ return err+ }+ // Windows readers can momentarily deny replacement of the old file.+ time.Sleep(50 * time.Millisecond)+ }+}++// The holder still owns the profile lock when this runs, so a successor cannot+// publish its record between the ownership check and the remove.+func removeDaemonPortIfOwned(profile string, pid int) {+ if record, ok := readDaemonPortRecord(profile); ok && record.PID == pid {+ _ = os.Remove(daemonPortPathForProfile(profile))+ }+}++// bindDaemonHealthPort holds the successful listener. A probe-and-close would+// leave a race for another process to claim the selected port.+func bindDaemonHealthPort(preferred int, listen func(string, string) (net.Listener, error)) (net.Listener, int, error) {+ addr := fmt.Sprintf("127.0.0.1:%d", preferred)+ ln, preferredErr := listen("tcp", addr)+ if preferredErr == nil {+ return ln, preferred, nil+ }+ ln, err := listen("tcp", "127.0.0.1:0")+ if err != nil {+ hint := ""+ if runtime.GOOS == "windows" {+ hint = "; inspect reserved ports with 'netsh interface ipv4 show excludedportrange protocol=tcp'"+ }+ return nil, 0, fmt.Errorf("bind health port %s: %w; fallback bind: %v%s", addr, preferredErr, err, hint)+ }+ port := ln.Addr().(*net.TCPAddr).Port+ fmt.Fprintf(os.Stderr, "Health port %s could not be bound: %v; using 127.0.0.1:%d instead.\n", addr, preferredErr, port)+ return ln, port, nil+}diff --git a/server/cmd/multica/cmd_daemon_port_test.go b/server/cmd/multica/cmd_daemon_port_test.gonew file mode 100644index 0000000000..09c7fb30f5--- /dev/null+++ b/server/cmd/multica/cmd_daemon_port_test.go@@ -0,0 +1,258 @@+package main++import (+ "bufio"+ "context"+ "fmt"+ "net"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "syscall"+ "testing"+ "time"++ "github.com/spf13/cobra"++ "github.com/multica-ai/multica/server/internal/cli"+)++func TestBindDaemonHealthPortFallsBackWithoutReleasingListener(t *testing.T) {+ preferred := healthPortForProfile("desktop-api.multica.ai")+ var attempts []string+ ln, port, err := bindDaemonHealthPort(preferred, func(network, addr string) (net.Listener, error) {+ attempts = append(attempts, addr)+ if addr == fmt.Sprintf("127.0.0.1:%d", preferred) {+ return nil, syscall.EACCES+ }+ return net.Listen(network, addr)+ })+ if err != nil {+ t.Fatal(err)+ }+ defer ln.Close()+ if len(attempts) != 2 || attempts[1] != "127.0.0.1:0" || port == preferred || port != ln.Addr().(*net.TCPAddr).Port {+ t.Fatalf("attempts=%v port=%d listener=%v", attempts, port, ln.Addr())+ }+ if second, err := net.Listen("tcp", ln.Addr().String()); err == nil {+ second.Close()+ t.Fatal("fallback listener was released before the caller could use it")+ }+}++func TestResolveHealthPortValidatesRecordAndFallsBack(t *testing.T) {+ mkProfiles(t, "desktop-api.multica.ai")+ profile := "desktop-api.multica.ai"+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ fmt.Fprint(w, `{"status":"running","profile":"desktop-api.multica.ai","pid":12345}`)+ }))+ defer server.Close()+ port := server.Listener.Addr().(*net.TCPAddr).Port+ if port == healthPortForProfile(profile) {+ t.Skip("test server selected the legacy profile port")+ }+ if err := publishDaemonPort(profile, daemonPortRecord{Port: port, PID: 12345}); err != nil {+ t.Fatal(err)+ }+ if got := resolveHealthPort(profile); got != port {+ t.Fatalf("resolved port=%d, want live record %d", got, port)+ }+ if err := publishDaemonPort(profile, daemonPortRecord{Port: port, PID: 999}); err != nil {+ t.Fatal(err)+ }+ if got := resolveHealthPort(profile); got != healthPortForProfile(profile) {+ t.Fatalf("resolved stale PID port=%d, want legacy %d", got, healthPortForProfile(profile))+ }+ removeDaemonPortIfOwned(profile, 12345)+ if _, err := os.Stat(daemonPortPathForProfile(profile)); err != nil {+ t.Fatalf("different PID removed the record: %v", err)+ }+ removeDaemonPortIfOwned(profile, 999)+ if _, err := os.Stat(daemonPortPathForProfile(profile)); !os.IsNotExist(err) {+ t.Fatalf("owner cleanup left record: %v", err)+ }+}++func TestResolveHealthPortRejectsAnotherProfile(t *testing.T) {+ mkProfiles(t, "desktop-api.multica.ai")+ profile := "desktop-api.multica.ai"+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ fmt.Fprint(w, `{"status":"running","profile":"other","pid":12345}`)+ }))+ defer server.Close()+ if err := publishDaemonPort(profile, daemonPortRecord{+ Port: server.Listener.Addr().(*net.TCPAddr).Port,+ PID: 12345,+ }); err != nil {+ t.Fatal(err)+ }+ if got := resolveHealthPort(profile); got != healthPortForProfile(profile) {+ t.Fatalf("resolved foreign daemon port=%d, want legacy %d", got, healthPortForProfile(profile))+ }+}++func TestDaemonProfileLockExcludesSecondProcessHandle(t *testing.T) {+ mkProfiles(t, "desktop-api.multica.ai")+ lock, err := acquireDaemonProfileLock("desktop-api.multica.ai", false)+ if err != nil {+ t.Fatal(err)+ }+ defer lock.Close()+ second, acquired, err := tryLockDaemonProfile(lock.Name())+ if err != nil {+ t.Fatal(err)+ }+ if second != nil {+ second.Close()+ }+ if acquired {+ t.Fatal("second handle acquired the active profile lock")+ }+}++func TestWaitForDaemonProfileReleaseAllowsSuccessorAfterLongShutdown(t *testing.T) {+ const profile = "shutdown-lock-test"+ mkProfiles(t, profile)+ lockPath := filepath.Join(daemonDirForProfile(profile), "daemon.lock")+ releasePath := filepath.Join(t.TempDir(), "release")+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ old := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDaemonProfileLockHolderProcess$")+ old.Env = append(os.Environ(), "MULTICA_TEST_DAEMON_LOCK_PATH="+lockPath, "MULTICA_TEST_DAEMON_LOCK_RELEASE="+releasePath)+ stdout, err := old.StdoutPipe()+ if err != nil {+ t.Fatal(err)+ }+ if err := old.Start(); err != nil {+ t.Fatal(err)+ }+ ready, err := bufio.NewReader(stdout).ReadString('\n')+ if err != nil || ready != "locked\n" {+ _ = old.Wait()+ t.Fatalf("lock holder did not start: line=%q error=%v", ready, err)+ }+ releaseErr := make(chan error, 1)+ go func() {+ time.Sleep(6 * time.Second)+ releaseErr <- os.WriteFile(releasePath, nil, 0o600)+ }()++ start := time.Now()+ waitErr := waitForDaemonProfileRelease(profile, 15*time.Second)+ elapsed := time.Since(start)+ if err := <-releaseErr; err != nil {+ t.Fatal(err)+ }+ if err := old.Wait(); err != nil {+ t.Fatalf("lock holder failed: %v", err)+ }+ if waitErr != nil {+ t.Fatal(waitErr)+ }+ if elapsed < 5*time.Second {+ t.Fatalf("lock wait ended after %s while the previous daemon was still exiting", elapsed)+ }+ successor, err := acquireDaemonProfileLock(profile, false)+ if err != nil {+ t.Fatalf("successor could not acquire the profile lock: %v", err)+ }+ successor.Close()+}++// A separate process owns the old daemon's lock after its health listener is+// gone. The parent test releases it only after a longer-than-child-wait delay.+func TestDaemonProfileLockHolderProcess(t *testing.T) {+ path := os.Getenv("MULTICA_TEST_DAEMON_LOCK_PATH")+ if path == "" {+ return+ }+ lock, acquired, err := tryLockDaemonProfile(path)+ if err != nil || !acquired {+ t.Fatalf("acquire holder lock: acquired=%t error=%v", acquired, err)+ }+ defer lock.Close()+ fmt.Fprintln(os.Stdout, "locked")+ releasePath := os.Getenv("MULTICA_TEST_DAEMON_LOCK_RELEASE")+ deadline := time.Now().Add(15 * time.Second)+ for time.Now().Before(deadline) {+ if _, err := os.Stat(releasePath); err == nil {+ return+ }+ time.Sleep(50 * time.Millisecond)+ }+ t.Fatal("lock holder was never released")+}++func TestWaitForDaemonProfileReleaseDetectsConcurrentStart(t *testing.T) {+ const profile = "concurrent-start-test"+ mkProfiles(t, profile)+ lock, err := acquireDaemonProfileLock(profile, false)+ if err != nil {+ t.Fatal(err)+ }+ defer lock.Close()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ fmt.Fprint(w, `{"status":"starting","profile":"concurrent-start-test","pid":12345}`)+ }))+ defer server.Close()+ if err := publishDaemonPort(profile, daemonPortRecord{Port: server.Listener.Addr().(*net.TCPAddr).Port, PID: 12345}); err != nil {+ t.Fatal(err)+ }+ start := time.Now()+ err = waitForDaemonProfileRelease(profile, 3*time.Second)+ if err == nil || !strings.Contains(err.Error(), "already running or starting") {+ t.Fatalf("lock wait = %v, want concurrent daemon error", err)+ }+ if elapsed := time.Since(start); elapsed > time.Second {+ t.Fatalf("concurrent daemon took %s to detect", elapsed)+ }+}++func TestDaemonBackgroundWaitsForShutdownBeforeSpawning(t *testing.T) {+ const profile = "background-lock-test"+ mkProfiles(t, profile)+ if err := cli.SaveCLIConfigForProfile(cli.CLIConfig{Token: "mul_fake"}, profile); err != nil {+ t.Fatal(err)+ }+ falseBin, err := exec.LookPath("false")+ if err != nil {+ t.Skipf("false binary unavailable: %v", err)+ }+ old, err := acquireDaemonProfileLock(profile, false)+ if err != nil {+ t.Fatal(err)+ }+ defer old.Close()+ released := make(chan struct{})+ go func() {+ time.Sleep(700 * time.Millisecond)+ old.Close()+ close(released)+ }()++ originalExecutable := daemonExecutable+ daemonExecutable = func() (string, error) { return falseBin, nil }+ t.Cleanup(func() { daemonExecutable = originalExecutable })+ originalSync := syncDaemonAutostart+ syncDaemonAutostart = func(string, bool) {}+ t.Cleanup(func() { syncDaemonAutostart = originalSync })++ cmd := &cobra.Command{Use: "start"}+ cmd.Flags().String("profile", profile, "")+ cmd.Flags().String("server-url", "", "")+ start := time.Now()+ err = runDaemonBackground(cmd)+ elapsed := time.Since(start)+ <-released+ // The fake child exits immediately. Reaching its startup failure proves+ // the launcher waited for the old lock before starting the replacement.+ if err == nil || !strings.Contains(err.Error(), "daemon exited during startup") {+ t.Fatalf("background start = %v, want fake child startup failure after lock release", err)+ }+ if elapsed < 600*time.Millisecond {+ t.Fatalf("background child started after %s, before the previous daemon released its lock", elapsed)+ }+}diff --git a/server/cmd/multica/cmd_daemon_profile_lock.go b/server/cmd/multica/cmd_daemon_profile_lock.gonew file mode 100644index 0000000000..1cabdb2bf6--- /dev/null+++ b/server/cmd/multica/cmd_daemon_profile_lock.go@@ -0,0 +1,80 @@+package main++import (+ "context"+ "fmt"+ "os"+ "path/filepath"+ "time"+)++const daemonShutdownLockWait = 40 * time.Second++// A fallback port no longer acts as the profile's single-instance guard.+// Keep this OS lock for the daemon's entire lifetime. A successor spawned by+// self-update may wait briefly for its predecessor to release it.+func acquireDaemonProfileLock(profile string, handoff bool) (*os.File, error) {+ dir := daemonDirForProfile(profile)+ if dir == "" {+ return nil, fmt.Errorf("resolve daemon profile directory")+ }+ if err := os.MkdirAll(dir, 0o755); err != nil {+ return nil, err+ }+ path := filepath.Join(dir, "daemon.lock")+ deadline := time.Now().Add(5 * time.Second)+ if handoff {+ deadline = deadline.Add(30 * time.Second)+ }+ for {+ f, acquired, err := tryLockDaemonProfile(path)+ if err != nil {+ return nil, fmt.Errorf("lock daemon profile %q: %w", profile, err)+ }+ if acquired {+ return f, nil+ }+ if !time.Now().Before(deadline) {+ return nil, fmt.Errorf("daemon profile %q is already running or starting", profile)+ }+ time.Sleep(100 * time.Millisecond)+ }+}++// Wait in the launcher, before spawning a child with its own startup timeout.+// During shutdown the health listener closes before active tasks and runtime+// cleanup finish, so an immediate successor would exhaust its 5-second lock+// wait and exit while the predecessor is still holding the lock.+func waitForDaemonProfileRelease(profile string, timeout time.Duration) error {+ path := filepath.Join(daemonDirForProfile(profile), "daemon.lock")+ deadline := time.Now().Add(timeout)+ nextHealthCheck := time.Time{}+ warned := false+ for {+ lock, acquired, err := tryLockDaemonProfile(path)+ if err != nil {+ return fmt.Errorf("check daemon profile %q lock: %w", profile, err)+ }+ if acquired {+ return lock.Close()+ }+ if !time.Now().Before(deadline) {+ return fmt.Errorf("daemon %s did not finish starting or shutting down within %s; retry once it exits", describeProfile(profile), timeout)+ }+ if !time.Now().Before(nextHealthCheck) {+ port := resolveHealthPort(profile)+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ health := checkDaemonHealthOnPort(ctx, port)+ cancel()+ if daemonAlive(health) && daemonIdentityMismatch(health, profile, port) == nil {+ return fmt.Errorf("daemon %s is already running or starting", describeProfile(profile))+ }+ if !warned {+ fmt.Fprintf(os.Stderr, "Daemon %s is still shutting down or starting; waiting for its profile lock...\n", describeProfile(profile))+ warned = true+ }+ nextHealthCheck = time.Now().Add(time.Second)+ }+ time.Sleep(100 * time.Millisecond)+ }+}diff --git a/server/cmd/multica/cmd_daemon_profile_lock_unix.go b/server/cmd/multica/cmd_daemon_profile_lock_unix.gonew file mode 100644index 0000000000..4bfedd3c37--- /dev/null+++ b/server/cmd/multica/cmd_daemon_profile_lock_unix.go@@ -0,0 +1,24 @@+//go:build !windows++package main++import (+ "os"++ "golang.org/x/sys/unix"+)++func tryLockDaemonProfile(path string) (*os.File, bool, error) {+ f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)+ if err != nil {+ return nil, false, err+ }+ if err := unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {+ f.Close()+ if err == unix.EWOULDBLOCK {+ return nil, false, nil+ }+ return nil, false, err+ }+ return f, true, nil+}diff --git a/server/cmd/multica/cmd_daemon_profile_lock_windows.go b/server/cmd/multica/cmd_daemon_profile_lock_windows.gonew file mode 100644index 0000000000..024fef4469--- /dev/null+++ b/server/cmd/multica/cmd_daemon_profile_lock_windows.go@@ -0,0 +1,34 @@+//go:build windows++package main++import (+ "errors"+ "os"++ "golang.org/x/sys/windows"+)++func tryLockDaemonProfile(path string) (*os.File, bool, error) {+ p, err := windows.UTF16PtrFromString(path)+ if err != nil {+ return nil, false, err+ }+ h, err := windows.CreateFile(p, windows.GENERIC_READ|windows.GENERIC_WRITE,+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,+ nil, windows.OPEN_ALWAYS, windows.FILE_ATTRIBUTE_NORMAL, 0)+ if err != nil {+ return nil, false, err+ }+ f := os.NewFile(uintptr(h), path)+ err = windows.LockFileEx(h, windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY,+ 0, 1, 0, new(windows.Overlapped))+ if err != nil {+ f.Close()+ if errors.Is(err, windows.ERROR_LOCK_VIOLATION) || errors.Is(err, windows.ERROR_IO_PENDING) {+ return nil, false, nil+ }+ return nil, false, err+ }+ return f, true, nil+}diff --git a/server/cmd/multica/cmd_setup.go b/server/cmd/multica/cmd_setup.goindex 43b042f092..3d251c6ca3 100644--- a/server/cmd/multica/cmd_setup.go+++ b/server/cmd/multica/cmd_setup.go@@ -270,7 +270,7 @@ func runDaemonAfterSetup(cmd *cobra.Command, args []string) error {profile := resolveProfile(cmd)ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)defer cancel()- health := checkDaemonHealthOnPort(ctx, healthPortForProfile(profile))+ health := checkDaemonHealthOnPort(ctx, resolveHealthPort(profile))return dispatchDaemonAfterSetup(cmd,diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 9f48e3c53a..7ee8ad541b 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -2101,6 +2101,17 @@ func (d *Daemon) clearWSHeartbeatAcks() {// Run starts the daemon: resolves auth, registers runtimes, then polls for tasks.func (d *Daemon) Run(ctx context.Context) error {+ return d.run(ctx, nil)+}++// RunWithHealthListener uses an already-bound loopback listener. The CLI keeps+// that listener open while publishing its actual port for other processes.+func (d *Daemon) RunWithHealthListener(ctx context.Context, healthLn net.Listener) error {+ return d.run(ctx, healthLn)+}++func (d *Daemon) run(ctx context.Context, healthLn net.Listener) error {+ var err error// Wrap context so handleUpdate can cancel the daemon for restart.ctx, cancel := context.WithCancel(ctx)d.cancelFunc = cancel@@ -2108,10 +2119,13 @@ func (d *Daemon) Run(ctx context.Context) error {d.rootCtx = ctx// Bind health port early to detect another running daemon.- healthLn, err := d.listenHealth()- if err != nil {- return err+ if healthLn == nil {+ healthLn, err = d.listenHealth()+ if err != nil {+ return err+ }}+ defer healthLn.Close()agentNames := make([]string, 0, len(d.agents()))for name := range d.agents() {diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.goindex 7aad07c305..5ef71ab191 100644--- a/server/internal/daemon/health.go+++ b/server/internal/daemon/health.go@@ -94,13 +94,12 @@ type healthWorkspace struct {Runtimes []string `json:"runtimes"`}-// listenHealth binds the health port. Returns the listener or an error if-// another daemon is already running (port taken).+// listenHealth binds the health port for callers without a prebound listener.func (d *Daemon) listenHealth() (net.Listener, error) {addr := fmt.Sprintf("127.0.0.1:%d", d.cfg.HealthPort)ln, err := net.Listen("tcp", addr)if err != nil {- return nil, fmt.Errorf("another daemon is already running on %s: %w", addr, err)+ return nil, fmt.Errorf("bind health port %s: %w", addr, err)}return ln, nil}