Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): discover agent CLIs installed after startup (MUL-5439) (#6086)
Multica Eve07a78d910d96
diff --git a/packages/views/onboarding/templates/install-runtime-issue.ts b/packages/views/onboarding/templates/install-runtime-issue.tsindex ff1688d34a..90914761e0 100644--- a/packages/views/onboarding/templates/install-runtime-issue.ts+++ b/packages/views/onboarding/templates/install-runtime-issue.ts@@ -56,9 +56,12 @@ For English users, the fastest first path is Codex:4. Confirm your terminal can find it:which codexcodex --version-5. Restart the Multica daemon:+5. Wait for Multica to pick it up. A running daemon re-checks for newly+ installed CLIs every couple of minutes, so no restart is normally needed.+ To apply it immediately:multica daemon restart- If you use the desktop app, restarting the app is enough.+ In the desktop app, open any local runtime and click Restart. Quitting and+ reopening the app is NOT enough — the daemon keeps running in the background.6. Return to Runtimes and refresh. You should see a Codex runtime online.7. Create your first agent from that runtime, then assign an issue to the agent and set status to todo.@@ -96,9 +99,10 @@ const zh = `欢迎来到 Multica。3. 在你想让 Kimi 工作的项目目录里启动一次:kimi4. 首次启动后输入 /login,按提示完成 Kimi Code 或 API key 配置。-5. 重启 Multica 守护进程:+5. 等 Multica 识别到它。运行中的守护进程每隔几分钟会重新检查一次新装的 CLI,通常不需要重启。+ 想立刻生效:multica daemon restart- 如果你用桌面端,重启 app 即可。+ 桌面端请打开任意一个本机 runtime 并点 Restart。退出再打开 app 是不够的 —— 守护进程会继续在后台运行。6. 回到 Runtimes 页面刷新。你应该能看到一个在线的 Kimi 运行时。7. 用这个运行时创建第一个智能体,再把一个 issue 分配给它,并把状态切到 todo。@@ -135,9 +139,12 @@ runtime이 준비되기 전에는 다음을 해볼 수 있습니다:4. 터미널에서 찾을 수 있는지 확인합니다:which codexcodex --version-5. Multica daemon을 재시작합니다:+5. Multica가 인식할 때까지 기다립니다. 실행 중인 daemon은 몇 분마다 새로 설치된 CLI를+ 다시 확인하므로 보통 재시작이 필요하지 않습니다.+ 바로 적용하려면:multica daemon restart- 데스크톱 앱을 사용한다면 앱을 재시작해도 됩니다.+ 데스크톱 앱에서는 아무 로컬 runtime을 열고 Restart를 누르세요. 앱을 종료하고 다시 여는+ 것만으로는 충분하지 않습니다 — daemon은 백그라운드에서 계속 실행됩니다.6. Runtimes로 돌아가 새로고침합니다. Codex runtime이 online으로 보여야 합니다.7. 해당 runtime으로 첫 agent를 만든 뒤 issue를 agent에게 배정하고 status를 todo로 바꿉니다.@@ -174,9 +181,12 @@ runtime が準備できる前に、次のことを試せます:4. ターミナルから見つけられるか確認します:which codexcodex --version-5. Multica daemon を再起動します:+5. Multica が認識するまで待ちます。動作中の daemon は数分ごとに新しくインストールされた+ CLI を再チェックするため、通常は再起動は不要です。+ すぐに反映したい場合:multica daemon restart- デスクトップアプリを使っている場合は、アプリを再起動するだけで十分です。+ デスクトップアプリではローカル runtime を開いて Restart を押してください。アプリを終了して+ 開き直すだけでは不十分です — daemon はバックグラウンドで動き続けます。6. Runtimes に戻って再読み込みします。Codex runtime が online と表示されるはずです。7. その runtime から最初の agent を作り、issue を agent に割り当てて status を todo にします。diff --git a/server/internal/daemon/agents_probe.go b/server/internal/daemon/agents_probe.gonew file mode 100644index 0000000000..e5f4a6bfcb--- /dev/null+++ b/server/internal/daemon/agents_probe.go@@ -0,0 +1,220 @@+package daemon++import (+ "os"+ "strings"+ "sync"+ "time"+)++// shellResolveTTL bounds how long one login-shell PATH resolution is reused+// across probeAgentCLIs calls.+//+// This is deliberately much longer than agentDiscoveryInterval so the frequent+// discovery round stays a pure exec.LookPath sweep: resolveAgentsViaLoginShell+// forks the user's login shell and runs their rc files, and there is almost+// always at least one uninstalled provider to miss LookPath on, so a short TTL+// would turn discovery into a shell fork every few minutes for the life of the+// daemon.+//+// The practical effect: a CLI on the daemon's own PATH is discovered within+// agentDiscoveryInterval, while one reachable only through the login shell+// (nvm/fnm shims, a ~/.local/bin that only ~/.zshrc adds) takes up to this long+// — still without a restart, which is the part that was previously impossible.+var shellResolveTTL = 30 * time.Minute++var (+ shellResolveMu sync.Mutex+ shellResolveCache map[string]string+ shellResolveKey string+ shellResolvedAt time.Time+)++// shellResolveEnvKey fingerprints the environment that determines what a login+// shell resolves. A change to any of these invalidates the cache immediately,+// independent of the TTL — the cached answer was for a different environment.+func shellResolveEnvKey() string {+ return strings.Join([]string{+ os.Getenv("PATH"),+ os.Getenv("SHELL"),+ os.Getenv("HOME"),+ }, "\x00")+}++// cachedShellResolvedAgents resolves every standard agent command name through+// the user's login shell, reusing the previous result for shellResolveTTL as+// long as the resolution-relevant environment is unchanged.+//+// resolveAgentsViaLoginShell forks the user's login shell, which runs their rc+// files, so this must stay a cache and not a per-probe call: probeAgentCLIs now+// runs periodically on a live daemon, and there is almost always at least one+// uninstalled provider to miss LookPath on.+func cachedShellResolvedAgents() map[string]string {+ shellResolveMu.Lock()+ defer shellResolveMu.Unlock()+ key := shellResolveEnvKey()+ if shellResolveCache != nil && shellResolveKey == key && time.Since(shellResolvedAt) < shellResolveTTL {+ return shellResolveCache+ }+ resolved := resolveAgentsViaLoginShell(defaultAgentCommandNames)+ if resolved == nil {+ // Distinguish "resolved nothing" from "never resolved" so a failing+ // shell doesn't get re-forked on every probe inside the TTL window.+ resolved = map[string]string{}+ }+ shellResolveCache = resolved+ shellResolveKey = key+ shellResolvedAt = time.Now()+ return shellResolveCache+}++// probeAgentCLIs discovers which built-in agent CLIs are installed on this+// machine and returns one AgentEntry per provider that resolved.+//+// This is pure discovery: no version detection and no minimum-version gate+// (detectBuiltinRuntimes owns those, per registration round). The result is+// therefore the machine's *availability* set, which is exactly what+// /health.agents reports and what `multica daemon probe-runtimes` prints.+//+// It is called once from LoadConfig at startup and again from the periodic+// workspace sync (refreshAgentAvailability), so a CLI the user installs while+// the daemon is already running gets picked up without a restart (MUL-5439).+// Everything it reads is process-external (PATH, MULTICA_*_PATH, MULTICA_*_MODEL),+// so re-running it is the only way to observe such an install.+//+// A var so tests can stub discovery without installing real CLIs.+var probeAgentCLIs = func() map[string]AgentEntry {+ // Probe available agent CLIs. exec.LookPath is the primary path, but on+ // macOS/Linux a GUI-launched daemon (Electron, Launchpad) does not+ // inherit the user's interactive shell PATH — fnm/nvm/volta multishells,+ // the Anthropic native installer prefix, and per-user npm prefixes all+ // live in dirs that only get added to PATH by ~/.zshrc or ~/.bashrc.+ // shellResolvedAgents asks the user's login shell, lazily on first miss,+ // to resolve every standard agent name to its canonical absolute path,+ // so we can find binaries the bare daemon process can't see. See+ // resolveAgentsViaLoginShell for the details and constraints.+ //+ // Laziness matters: the happy path (every agent on the daemon's PATH or+ // pinned to an explicit MULTICA_*_PATH) must not pay the cost of+ // spawning the user's login shell — that touches their rc files and+ // adds startup latency that scales with whatever they put in there. We+ // only fork a shell when a bare command name actually missed LookPath.+ //+ // The resolution is cached process-wide with a TTL (not per call) because+ // this function now also runs periodically on a live daemon: a per-call+ // sync.Once would fork a login shell on every discovery round, since there+ // is almost always at least one uninstalled provider to miss on. The TTL+ // still lets a CLI installed into a login-shell-only PATH dir (nvm, fnm,+ // ~/.local/bin via ~/.zshrc) be discovered without a restart (MUL-5439).+ getShellResolved := cachedShellResolvedAgents+ probe := func(envVar, defaultCmd, modelEnv string) (AgentEntry, bool) {+ cmd := envOrDefault(envVar, defaultCmd)+ if path, err := resolveAgentExecutablePath(cmd); err == nil {+ return AgentEntry{+ Path: path,+ Command: cmd,+ Model: strings.TrimSpace(os.Getenv(modelEnv)),+ }, true+ }+ // The shell fallback only rescues bare command names. An operator+ // who pinned MULTICA_*_PATH to an absolute or relative path that+ // doesn't exist should hard-miss, not silently get a different+ // binary.+ if strings.ContainsAny(cmd, "/\\") {+ return AgentEntry{}, false+ }+ if path, ok := getShellResolved()[cmd]; ok {+ return AgentEntry{+ Path: path,+ Command: cmd,+ Model: strings.TrimSpace(os.Getenv(modelEnv)),+ }, true+ }+ if defaultCmd == "codex" && cmd == defaultCmd {+ // Codex Desktop bundles its CLI inside the macOS app instead of+ // installing it onto PATH.+ for _, p := range codexDesktopAppBundlePaths() {+ if _, err := os.Stat(p); err == nil {+ return AgentEntry{+ Path: p,+ Command: cmd,+ Model: strings.TrimSpace(os.Getenv(modelEnv)),+ }, true+ }+ }+ }+ return AgentEntry{}, false+ }++ agents := map[string]AgentEntry{}+ if e, ok := probe("MULTICA_CLAUDE_PATH", "claude", "MULTICA_CLAUDE_MODEL"); ok {+ agents["claude"] = e+ }+ if e, ok := probe("MULTICA_CODEX_PATH", "codex", "MULTICA_CODEX_MODEL"); ok {+ agents["codex"] = e+ }+ if e, ok := probe("MULTICA_OPENCODE_PATH", "opencode", "MULTICA_OPENCODE_MODEL"); ok {+ agents["opencode"] = e+ }+ if e, ok := probe("MULTICA_DEVECO_PATH", "deveco", "MULTICA_DEVECO_MODEL"); ok {+ agents["deveco"] = e+ }+ if e, ok := probe("MULTICA_OPENCLAW_PATH", "openclaw", "MULTICA_OPENCLAW_MODEL"); ok {+ agents["openclaw"] = e+ }+ if e, ok := probe("MULTICA_HERMES_PATH", "hermes", "MULTICA_HERMES_MODEL"); ok {+ agents["hermes"] = e+ }+ if e, ok := probe("MULTICA_PI_PATH", "pi", "MULTICA_PI_MODEL"); ok {+ agents["pi"] = e+ }+ if e, ok := probe("MULTICA_CURSOR_PATH", "cursor-agent", "MULTICA_CURSOR_MODEL"); ok {+ agents["cursor"] = e+ }+ if e, ok := probe("MULTICA_COPILOT_PATH", "copilot", "MULTICA_COPILOT_MODEL"); ok {+ agents["copilot"] = e+ }+ if e, ok := probe("MULTICA_KIMI_PATH", "kimi", "MULTICA_KIMI_MODEL"); ok {+ agents["kimi"] = e+ }+ if e, ok := probe("MULTICA_KIRO_PATH", "kiro-cli", "MULTICA_KIRO_MODEL"); ok {+ agents["kiro"] = e+ }+ if e, ok := probe("MULTICA_CODEBUDDY_PATH", "codebuddy", "MULTICA_CODEBUDDY_MODEL"); ok {+ agents["codebuddy"] = e+ }+ // agy 1.0.6 added a `--model` flag (MUL-3125), so Antigravity now takes a+ // model env like every other backend. MULTICA_ANTIGRAVITY_MODEL seeds the+ // daemon-wide default; its value is the exact `agy models` display string+ // (e.g. "Claude Opus 4.6 (Thinking)"), not a provider/model slug.+ if e, ok := probe("MULTICA_ANTIGRAVITY_PATH", "agy", "MULTICA_ANTIGRAVITY_MODEL"); ok {+ agents["antigravity"] = e+ }+ qoderPath := envOrDefault("MULTICA_QODER_PATH", "qodercli")+ if path, err := resolveAgentExecutablePath(qoderPath); err == nil {+ agents["qoder"] = AgentEntry{+ Path: path,+ Command: qoderPath,+ Model: strings.TrimSpace(os.Getenv("MULTICA_QODER_MODEL")),+ }+ }+ // ByteDance official TRAE CLI (the `traecli` binary from https://docs.trae.cn/cli),+ // driven over ACP via `traecli acp serve --yolo`. MULTICA_TRAECLI_MODEL seeds+ // the daemon-wide default model (a model id from the user's logged-in traecli+ // catalog).+ if e, ok := probe("MULTICA_TRAECLI_PATH", "traecli", "MULTICA_TRAECLI_MODEL"); ok {+ agents["traecli"] = e+ }+ // xAI Grok Build CLI (`grok`), driven over ACP via+ // `grok agent --always-approve stdio`. MULTICA_GROK_MODEL seeds the+ // daemon-wide default (e.g. grok-4.5).+ if e, ok := probe("MULTICA_GROK_PATH", "grok", "MULTICA_GROK_MODEL"); ok {+ agents["grok"] = e+ }+ // Qwen Code (`qwen`) runs headlessly with -p and stream-json. Its native+ // QWEN.md and .qwen/skills task context is prepared by execenv.+ if e, ok := probe("MULTICA_QWEN_PATH", "qwen", "MULTICA_QWEN_MODEL"); ok {+ agents["qwen"] = e+ }+ return agents+}diff --git a/server/internal/daemon/agents_refresh.go b/server/internal/daemon/agents_refresh.gonew file mode 100644index 0000000000..3f81e9f427--- /dev/null+++ b/server/internal/daemon/agents_refresh.go@@ -0,0 +1,298 @@+package daemon++import (+ "context"+ "sort"+ "time"+)++// agentDiscoveryInterval is how often a running daemon re-checks which agent+// CLIs are installed. A round is a handful of exec.LookPath calls — the+// login-shell fallback is separately rate-limited by the much longer+// shellResolveTTL — so this can be short enough that installing a CLI feels+// immediate. Overridable for tests.+var agentDiscoveryInterval = 2 * time.Minute++// agentConvergeMaxBackoff caps the retry delay for a discovered provider that+// keeps failing to register (permanently below the minimum supported version, a+// CLI whose --version never succeeds, a server that keeps rejecting the+// register). Discovery itself stays on agentDiscoveryInterval; only the+// expensive half — version probes plus one register call per workspace — backs+// off, so a stuck provider cannot turn into a busy loop. Overridable for tests.+var agentConvergeMaxBackoff = 30 * time.Minute++// agentDiscoveryLoop keeps the registered runtime set converged on the agent+// CLIs actually installed on this machine, so a CLI installed while the daemon+// is running comes online without a restart (MUL-5439).+//+// Each tick does the cheap half unconditionally: re-probe availability and+// publish anything new. The expensive half (version probes + registration) runs+// only when some discovered provider is not yet registered for every tracked+// workspace — which is derived from live state, not remembered from the round+// that discovered it. That is what makes a failed first attempt retry: a+// provider whose version probe timed out, or whose register call failed, is+// still "missing" on the next tick and gets tried again. It also means a+// provider rejected for being below the minimum version recovers on its own+// after an in-place upgrade.+func (d *Daemon) agentDiscoveryLoop(ctx context.Context) {+ ticker := time.NewTicker(agentDiscoveryInterval)+ defer ticker.Stop()++ var (+ backoff time.Duration+ nextRetry time.Time+ )+ for {+ select {+ case <-ctx.Done():+ return+ case now := <-ticker.C:+ gained := d.refreshAgentAvailability()+ missing := d.providersMissingRuntimes()+ if len(missing) == 0 {+ backoff = 0+ continue+ }+ // A newly discovered provider always gets an immediate attempt;+ // otherwise honor the backoff earned by previous failures.+ if len(gained) == 0 && now.Before(nextRetry) {+ continue+ }+ before := len(missing)+ d.convergeRuntimeRegistrations(ctx)+ if len(d.providersMissingRuntimes()) < before {+ backoff = 0+ } else {+ backoff = nextConvergeBackoff(backoff)+ }+ nextRetry = now.Add(backoff)+ }+ }+}++// nextConvergeBackoff doubles the retry delay, starting at one discovery+// interval and capped at agentConvergeMaxBackoff.+func nextConvergeBackoff(current time.Duration) time.Duration {+ if current <= 0 {+ return agentDiscoveryInterval+ }+ next := current * 2+ if next > agentConvergeMaxBackoff {+ return agentConvergeMaxBackoff+ }+ return next+}++// agents returns the current built-in agent availability set.+//+// The returned map is shared and MUST NOT be mutated: refreshAgentAvailability+// publishes a whole new map rather than editing this one, which is what makes+// unlocked reads from task-execution paths safe.+func (d *Daemon) agents() map[string]AgentEntry {+ if m := d.agentsAvailable.Load(); m != nil {+ return *m+ }+ // Zero-value Daemon (tests construct one directly): fall back to the+ // startup config so behavior matches the pre-refresh code path.+ return d.cfg.Agents+}++// setSkippedAgents replaces the diagnostic "discovered but not registered" set+// reported on /health. Called at the end of every registration round with the+// providers that round dropped.+func (d *Daemon) setSkippedAgents(skipped map[string]string) {+ d.skippedAgentsMu.Lock()+ defer d.skippedAgentsMu.Unlock()+ d.skippedAgents = skipped+}++// skippedAgentsSnapshot copies the current skip reasons for the health handler.+func (d *Daemon) skippedAgentsSnapshot() map[string]string {+ d.skippedAgentsMu.RLock()+ defer d.skippedAgentsMu.RUnlock()+ if len(d.skippedAgents) == 0 {+ return nil+ }+ out := make(map[string]string, len(d.skippedAgents))+ for name, reason := range d.skippedAgents {+ out[name] = reason+ }+ return out+}++// refreshAgentAvailability re-runs CLI discovery and publishes providers that+// appeared since the last probe. It performs no registration — that is+// convergeRuntimeRegistrations, driven by live state so a failure retries.+//+// Deliberately one-directional: only providers GAINED are acted on. A provider+// that stops resolving is kept, because a transient environment difference (a+// daemon restarted from a narrower PATH, a version manager mid-upgrade) would+// otherwise tear down a runtime that is working — and possibly executing a+// task. Removal stays the job of an explicit restart, where the user chose the+// environment.+//+// Returns the providers that were added, for logging and tests.+func (d *Daemon) refreshAgentAvailability() []string {+ current := d.agents()+ probed := probeAgentCLIs()++ var gained []string+ for name := range probed {+ if _, known := current[name]; !known {+ gained = append(gained, name)+ }+ }+ if len(gained) == 0 {+ return nil+ }+ sort.Strings(gained)++ // Copy-on-write: build the union, then publish. Entries for providers we+ // already knew about are preserved as-is so this never fights the pinned+ // path / self-heal bookkeeping (resolvedPaths) for a running provider.+ merged := make(map[string]AgentEntry, len(current)+len(gained))+ for name, entry := range current {+ merged[name] = entry+ }+ for _, name := range gained {+ merged[name] = probed[name]+ }+ d.agentsAvailable.Store(&merged)+ d.logger.Info("agent CLI discovered after startup", "providers", gained)+ return gained+}++// providersMissingRuntimes returns the discovered providers that do not have a+// built-in runtime registered for every tracked workspace.+//+// This is the retry signal for the discovery loop, and it is derived from live+// state rather than remembered: a provider only leaves this set once the daemon+// actually holds a runtime row for it in every workspace it watches. Custom+// profile runtimes (ProfileID set) are ignored — they register from a+// workspace's profile list, not from CLI discovery, and a profile that happens+// to share a protocol_family with a built-in must not mask the built-in.+//+// Returns nothing when no workspace is tracked yet: there is nothing to+// register against, and the initial registration will carry the full set.+func (d *Daemon) providersMissingRuntimes() []string {+ available := d.agents()+ if len(available) == 0 {+ return nil+ }++ d.mu.Lock()+ defer d.mu.Unlock()+ if len(d.workspaces) == 0 {+ return nil+ }+ missing := make(map[string]struct{})+ for _, ws := range d.workspaces {+ registered := make(map[string]struct{}, len(ws.runtimeIDs))+ for _, id := range ws.runtimeIDs {+ rt, ok := d.runtimeIndex[id]+ if !ok || rt.ProfileID != "" {+ continue+ }+ registered[rt.Provider] = struct{}{}+ }+ for name := range available {+ if _, ok := registered[name]; !ok {+ missing[name] = struct{}{}+ }+ }+ }+ if len(missing) == 0 {+ return nil+ }+ out := make([]string, 0, len(missing))+ for name := range missing {+ out = append(out, name)+ }+ sort.Strings(out)+ return out+}++// convergeRuntimeRegistrations registers the current built-in set for every+// tracked workspace that is missing one of them.+//+// One version-probe round serves every workspace (built-in CLIs are per+// machine, not per workspace). Failures are logged and left for the next+// discovery tick — nothing here records "already handled", so a partial+// failure across workspaces retries only the workspaces that still need it.+//+// Strictly built-ins: this path never fetches, sends, or observes custom runtime+// profiles. Custom profile add/edit/disable remains owned by the drift path+// (refreshWorkspaceRuntimeProfiles), which is the only place allowed to cache a+// profile-set signature.+//+// RecoverOrphans is deliberately NOT called: unlike the runtime_gone recovery+// path, the surviving runtime IDs may still be executing tasks for the user,+// and failing those as orphans would kill live work (MUL-3332).+func (d *Daemon) convergeRuntimeRegistrations(ctx context.Context) {+ // detectBuiltinRuntimes version-gates the availability set and publishes+ // this round's drops for /health, so a provider that cannot register still+ // gets a visible reason even though registration is skipped.+ builtins := d.detectBuiltinRuntimes(ctx)+ if len(builtins) == 0 {+ return+ }+ detected := make(map[string]struct{}, len(builtins))+ for _, rt := range builtins {+ detected[rt["type"]] = struct{}{}+ }++ d.mu.Lock()+ type target struct {+ id string+ missing []string+ }+ var targets []target+ for id, ws := range d.workspaces {+ registered := make(map[string]struct{}, len(ws.runtimeIDs))+ for _, rid := range ws.runtimeIDs {+ rt, ok := d.runtimeIndex[rid]+ if !ok || rt.ProfileID != "" {+ continue+ }+ registered[rt.Provider] = struct{}{}+ }+ var missing []string+ for name := range detected {+ if _, ok := registered[name]; !ok {+ missing = append(missing, name)+ }+ }+ if len(missing) > 0 {+ sort.Strings(missing)+ targets = append(targets, target{id: id, missing: missing})+ }+ }+ d.mu.Unlock()+ if len(targets) == 0 {+ return+ }+ sort.Slice(targets, func(i, j int) bool { return targets[i].id < targets[j].id })++ var changed bool+ for _, t := range targets {+ resp, err := d.registerBuiltinRuntimesForWorkspace(ctx, t.id, builtins)+ if err != nil {+ // Left in the missing set on purpose: the next tick retries.+ d.logger.Warn("register newly available runtimes failed; will retry",+ "workspace_id", t.id, "providers", t.missing, "error", err)+ continue+ }+ newIDs, ok := d.mergeBuiltinRegisterResponse(t.id, resp)+ if !ok {+ continue+ }+ if len(newIDs) > 0 {+ changed = true+ d.logger.Info("registered runtime for newly installed agent CLI",+ "workspace_id", t.id, "providers", t.missing, "runtime_ids", newIDs)+ }+ }+ if changed {+ d.notifyRuntimeSetChanged()+ }+}diff --git a/server/internal/daemon/agents_refresh_test.go b/server/internal/daemon/agents_refresh_test.gonew file mode 100644index 0000000000..116fe12db9--- /dev/null+++ b/server/internal/daemon/agents_refresh_test.go@@ -0,0 +1,820 @@+package daemon++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "sort"+ "sync"+ "testing"+ "time"+)++// stubAgentProbe replaces CLI discovery for the duration of a test. The returned+// setter swaps in the next probe result, simulating the user installing or+// uninstalling a CLI while the daemon runs.+//+// Goroutine-safe: agentDiscoveryLoop calls the probe from its own goroutine+// while the test body swaps the result.+func stubAgentProbe(t *testing.T, initial map[string]AgentEntry) func(map[string]AgentEntry) {+ t.Helper()+ orig := probeAgentCLIs+ t.Cleanup(func() { probeAgentCLIs = orig })+ var (+ mu sync.Mutex+ current = initial+ )+ probeAgentCLIs = func() map[string]AgentEntry {+ mu.Lock()+ defer mu.Unlock()+ // Copy so the caller can iterate without holding the lock.+ out := make(map[string]AgentEntry, len(current))+ for name, entry := range current {+ out[name] = entry+ }+ return out+ }+ return func(next map[string]AgentEntry) {+ mu.Lock()+ defer mu.Unlock()+ current = next+ }+}++// registeredProviders returns the built-in providers the daemon currently holds+// a runtime for in a workspace, as the daemon itself sees them.+func registeredProviders(t *testing.T, d *Daemon, workspaceID string) []string {+ t.Helper()+ d.mu.Lock()+ defer d.mu.Unlock()+ ws, ok := d.workspaces[workspaceID]+ if !ok {+ return nil+ }+ var out []string+ for _, id := range ws.runtimeIDs {+ rt, found := d.runtimeIndex[id]+ if !found || rt.ProfileID != "" {+ continue+ }+ out = append(out, rt.Provider)+ }+ sort.Strings(out)+ return out+}++// TestDiscovery_RegistersCLIInstalledAfterStartup is the MUL-5439 regression+// (GH #6077): the availability set used to be built once in LoadConfig, so a CLI+// installed while the daemon was running never registered — and on Desktop,+// quitting the app does not restart the daemon, so the user had no way to+// recover short of an explicit daemon restart.+func TestDiscovery_RegistersCLIInstalledAfterStartup(t *testing.T) {+ fx := newBatchFixture(t)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})++ setProbe := stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {+ t.Fatalf("syncWorkspacesFromAPI: %v", err)+ }+ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 || got[0] != "codex" {+ t.Fatalf("initial providers = %v, want [codex]", got)+ }++ // The user now installs Antigravity.+ setProbe(map[string]AgentEntry{+ "codex": {Path: "/fake/codex"},+ "antigravity": {Path: "/fake/agy"},+ })++ gained := d.refreshAgentAvailability()+ if len(gained) != 1 || gained[0] != "antigravity" {+ t.Fatalf("gained = %v, want [antigravity]", gained)+ }+ d.convergeRuntimeRegistrations(context.Background())++ got := registeredProviders(t, d, "ws-1")+ if len(got) != 2 || got[0] != "antigravity" || got[1] != "codex" {+ t.Errorf("providers after converge = %v, want [antigravity codex]", got)+ }+ if missing := d.providersMissingRuntimes(); missing != nil {+ t.Errorf("still missing %v after a successful converge", missing)+ }+}++// TestDiscovery_RetriesAfterVersionProbeFailure is the review's P1: publishing a+// provider into the availability set must not be mistaken for "handled". A+// version probe that fails the first time (timeout, CLI busy) has to be retried+// on a later round, or the user is back to restarting the daemon.+func TestDiscovery_RetriesAfterVersionProbeFailure(t *testing.T) {+ fx := newBatchFixture(t)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})+ setProbe := stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {+ t.Fatalf("syncWorkspacesFromAPI: %v", err)+ }++ // agy is installed, but every `agy --version` in this round fails.+ fx.setProbeErr(func(path string, _ int) error {+ if path == "/fake/agy" {+ return errors.New("boom")+ }+ return nil+ })+ setProbe(map[string]AgentEntry{+ "codex": {Path: "/fake/codex"},+ "antigravity": {Path: "/fake/agy"},+ })++ d.refreshAgentAvailability()+ d.convergeRuntimeRegistrations(context.Background())+ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 {+ t.Fatalf("providers = %v, want only codex while the version probe fails", got)+ }+ missing := d.providersMissingRuntimes()+ if len(missing) != 1 || missing[0] != "antigravity" {+ t.Fatalf("missing = %v, want [antigravity] so a later round retries", missing)+ }+ // The failure is visible, not just retried.+ if _, ok := d.skippedAgentsSnapshot()["antigravity"]; !ok {+ t.Error("antigravity missing from skipped_agents while its version probe fails")+ }++ // The CLI starts responding. No new discovery happens — the retry must be+ // driven by the still-missing runtime, not by a fresh "gained" event.+ fx.setProbeErr(nil)+ if gained := d.refreshAgentAvailability(); gained != nil {+ t.Fatalf("gained = %v, want none (antigravity was already discovered)", gained)+ }+ d.convergeRuntimeRegistrations(context.Background())++ got := registeredProviders(t, d, "ws-1")+ if len(got) != 2 || got[0] != "antigravity" {+ t.Errorf("providers after recovery = %v, want antigravity registered", got)+ }+ if missing := d.providersMissingRuntimes(); missing != nil {+ t.Errorf("still missing %v after recovery", missing)+ }+}++// TestDiscovery_RetriesAfterRegisterRequestFailure covers the other half of the+// same P1: the register HTTP call failing must also leave the provider pending.+func TestDiscovery_RetriesAfterRegisterRequestFailure(t *testing.T) {+ fx := newBatchFixture(t)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})+ setProbe := stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {+ t.Fatalf("syncWorkspacesFromAPI: %v", err)+ }++ fx.failRegister(true)+ setProbe(map[string]AgentEntry{+ "codex": {Path: "/fake/codex"},+ "antigravity": {Path: "/fake/agy"},+ })+ d.refreshAgentAvailability()+ d.convergeRuntimeRegistrations(context.Background())++ missing := d.providersMissingRuntimes()+ if len(missing) != 1 || missing[0] != "antigravity" {+ t.Fatalf("missing = %v, want [antigravity] after a failed register", missing)+ }+ // The failed register must not have corrupted what was already there.+ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 || got[0] != "codex" {+ t.Fatalf("providers = %v, want codex preserved through the failure", got)+ }++ fx.failRegister(false)+ d.convergeRuntimeRegistrations(context.Background())+ if got := registeredProviders(t, d, "ws-1"); len(got) != 2 || got[0] != "antigravity" {+ t.Errorf("providers after retry = %v, want antigravity registered", got)+ }+}++// TestDiscovery_RetriesOnlyTheWorkspacesThatStillNeedIt covers a partial failure+// across workspaces: the workspace that registered must not be re-registered,+// and the one that failed must be.+func TestDiscovery_RetriesOnlyTheWorkspacesThatStillNeedIt(t *testing.T) {+ fx := newBatchFixture(t)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}+ fx.setWorkspaces(+ WorkspaceInfo{ID: "ws-1", Name: "one"},+ WorkspaceInfo{ID: "ws-2", Name: "two"},+ )+ setProbe := stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {+ t.Fatalf("syncWorkspacesFromAPI: %v", err)+ }++ fx.failRegisterFor("ws-2", true)+ setProbe(map[string]AgentEntry{+ "codex": {Path: "/fake/codex"},+ "antigravity": {Path: "/fake/agy"},+ })+ d.refreshAgentAvailability()+ d.convergeRuntimeRegistrations(context.Background())++ if got := registeredProviders(t, d, "ws-1"); len(got) != 2 {+ t.Fatalf("ws-1 providers = %v, want both registered", got)+ }+ if got := registeredProviders(t, d, "ws-2"); len(got) != 1 {+ t.Fatalf("ws-2 providers = %v, want only codex after its register failed", got)+ }++ fx.failRegisterFor("ws-2", false)+ before := fx.registerCallCount()+ d.convergeRuntimeRegistrations(context.Background())+ if got := registeredProviders(t, d, "ws-2"); len(got) != 2 {+ t.Errorf("ws-2 providers after retry = %v, want both registered", got)+ }+ if got := fx.registerCallCount() - before; got != 1 {+ t.Errorf("retry made %d register calls, want 1 (only the workspace that needed it)", got)+ }+}++// TestDiscovery_KeepsCustomRuntimeWhenProfileFetchFails is the review's second+// P1. The discovery path registers built-ins only, so its response never+// mentions custom profile runtimes. Applying that as authoritative would evict+// them from the local index and stop their heartbeats — the opposite of+// "existing runtimes are unaffected". The profile fetch failing is the sharpest+// version of the same hazard.+func TestDiscovery_KeepsCustomRuntimeWhenProfileFetchFails(t *testing.T) {+ fx := newBatchFixture(t)+ stubLookPath(t, map[string]string{"company-codex": "/opt/bin/company-codex"})+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})+ fx.profiles["ws-1"] = []RuntimeProfile{{+ ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Company Codex",+ ProtocolFamily: "codex", CommandName: "company-codex",+ Visibility: "workspace", Enabled: true,+ }}+ setProbe := stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {+ t.Fatalf("syncWorkspacesFromAPI: %v", err)+ }++ customID := ""+ d.mu.Lock()+ sigBefore := d.workspaces["ws-1"].profileSetSig+ for _, id := range d.workspaces["ws-1"].runtimeIDs {+ if d.runtimeIndex[id].ProfileID == "prof-1" {+ customID = id+ }+ }+ d.mu.Unlock()+ if customID == "" {+ t.Fatal("custom profile runtime was never registered; fixture setup is wrong")+ }++ // The profile fetch now fails, and a newly installed CLI triggers a+ // discovery-driven registration.+ fx.failProfiles(true)+ setProbe(map[string]AgentEntry{+ "codex": {Path: "/fake/codex"},+ "antigravity": {Path: "/fake/agy"},+ })+ d.refreshAgentAvailability()+ d.convergeRuntimeRegistrations(context.Background())++ d.mu.Lock()+ _, stillIndexed := d.runtimeIndex[customID]+ var stillWatched bool+ for _, id := range d.workspaces["ws-1"].runtimeIDs {+ if id == customID {+ stillWatched = true+ }+ }+ sigAfter := d.workspaces["ws-1"].profileSetSig+ d.mu.Unlock()++ if !stillIndexed {+ t.Error("custom profile runtime was evicted from runtimeIndex by a builtins-only response")+ }+ if !stillWatched {+ t.Error("custom profile runtime was dropped from the workspace's runtime set (heartbeats would stop)")+ }+ if sigAfter != sigBefore {+ t.Errorf("profileSetSig changed %q -> %q; discovery must not touch it", sigBefore, sigAfter)+ }+ if got := registeredProviders(t, d, "ws-1"); len(got) != 2 || got[0] != "antigravity" {+ t.Errorf("providers = %v, want the new built-in registered alongside codex", got)+ }+}++// TestDiscovery_DoesNotMaskAProfileDisabledConcurrently is the second review+// round's P1. Discovery used to register through the profile-appending path and+// cache the resulting signature. If a user disabled a custom profile at the same+// moment a new CLI was discovered, the additive merge correctly kept the old+// runtime ID but recorded the post-disable signature — so+// refreshWorkspaceRuntimeProfiles saw "no drift", returned early, and the+// disabled runtime stayed tracked and heartbeating forever.+func TestDiscovery_DoesNotMaskAProfileDisabledConcurrently(t *testing.T) {+ fx := newBatchFixture(t)+ stubLookPath(t, map[string]string{"company-codex": "/opt/bin/company-codex"})+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})+ fx.profiles["ws-1"] = []RuntimeProfile{{+ ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Company Codex",+ ProtocolFamily: "codex", CommandName: "company-codex",+ Visibility: "workspace", Enabled: true,+ }}+ setProbe := stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {+ t.Fatalf("syncWorkspacesFromAPI: %v", err)+ }++ customID := ""+ d.mu.Lock()+ for _, id := range d.workspaces["ws-1"].runtimeIDs {+ if d.runtimeIndex[id].ProfileID == "prof-1" {+ customID = id+ }+ }+ d.mu.Unlock()+ if customID == "" {+ t.Fatal("custom profile runtime was never registered; fixture setup is wrong")+ }++ // The user disables the profile at the same time as installing a new CLI.+ fx.profiles["ws-1"] = nil+ setProbe(map[string]AgentEntry{+ "codex": {Path: "/fake/codex"},+ "antigravity": {Path: "/fake/agy"},+ })+ d.refreshAgentAvailability()+ d.convergeRuntimeRegistrations(context.Background())++ // Discovery must not have decided the profile set is converged.+ if err := d.refreshWorkspaceRuntimeProfiles(context.Background(), "ws-1"); err != nil {+ t.Fatalf("refreshWorkspaceRuntimeProfiles: %v", err)+ }++ d.mu.Lock()+ _, stillIndexed := d.runtimeIndex[customID]+ var stillWatched bool+ for _, id := range d.workspaces["ws-1"].runtimeIDs {+ if id == customID {+ stillWatched = true+ }+ }+ d.mu.Unlock()++ if stillWatched || stillIndexed {+ t.Errorf("disabled custom runtime %s remained tracked (indexed=%v watched=%v); discovery masked the drift",+ customID, stillIndexed, stillWatched)+ }+ if got := registeredProviders(t, d, "ws-1"); len(got) == 0 {+ t.Error("built-in runtimes were lost while converging the disabled profile")+ }+}++// TestDiscovery_BelowMinVersionRecoversAfterUpgrade covers the review's ask that+// a version-gated provider be re-checked rather than written off, so an in-place+// CLI upgrade brings it online without a restart.+func TestDiscovery_BelowMinVersionRecoversAfterUpgrade(t *testing.T) {+ fx := newBatchFixture(t)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})+ setProbe := stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {+ t.Fatalf("syncWorkspacesFromAPI: %v", err)+ }++ tooOld := true+ origCheck := checkAgentMinVersion+ t.Cleanup(func() { checkAgentMinVersion = origCheck })+ checkAgentMinVersion = func(provider, _ string) error {+ if provider == "antigravity" && tooOld {+ return errors.New("antigravity version 1.0.0 is below minimum required 1.1.0")+ }+ return nil+ }++ setProbe(map[string]AgentEntry{+ "codex": {Path: "/fake/codex"},+ "antigravity": {Path: "/fake/agy"},+ })+ d.refreshAgentAvailability()+ d.convergeRuntimeRegistrations(context.Background())++ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 {+ t.Fatalf("providers = %v, want antigravity rejected while below minimum", got)+ }+ reason, ok := d.skippedAgentsSnapshot()["antigravity"]+ if !ok || reason == "" {+ t.Error("below-minimum antigravity should be reported in skipped_agents with a reason")+ }++ // User upgrades the CLI in place.+ tooOld = false+ d.convergeRuntimeRegistrations(context.Background())+ if got := registeredProviders(t, d, "ws-1"); len(got) != 2 || got[0] != "antigravity" {+ t.Errorf("providers after upgrade = %v, want antigravity registered", got)+ }+ if got := d.skippedAgentsSnapshot(); len(got) != 0 {+ t.Errorf("skipped agents = %v after recovery, want empty", got)+ }+}++// TestDiscovery_NoopWhenNothingNew keeps the loop cheap in the steady state: an+// unchanged, fully registered set must not re-register or re-probe.+func TestDiscovery_NoopWhenNothingNew(t *testing.T) {+ fx := newBatchFixture(t)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})+ stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {+ t.Fatalf("syncWorkspacesFromAPI: %v", err)+ }+ registersBefore := fx.registerCallCount()+ probesBefore := fx.probeCount("/fake/codex")++ if gained := d.refreshAgentAvailability(); gained != nil {+ t.Fatalf("gained = %v, want none", gained)+ }+ if missing := d.providersMissingRuntimes(); missing != nil {+ t.Fatalf("missing = %v, want none in the steady state", missing)+ }+ if got := fx.registerCallCount(); got != registersBefore {+ t.Errorf("register calls went %d -> %d, want no change", registersBefore, got)+ }+ if got := fx.probeCount("/fake/codex"); got != probesBefore {+ t.Errorf("version probes went %d -> %d; the steady state must not re-probe", probesBefore, got)+ }+}++// TestDiscovery_KeepsProviderThatStoppedResolving pins the one-directional+// contract. A provider vanishing from a probe is usually an environment+// difference or a version manager mid-upgrade, not an uninstall, so dropping it+// would tear down a runtime that may be executing a task.+func TestDiscovery_KeepsProviderThatStoppedResolving(t *testing.T) {+ fx := newBatchFixture(t)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{+ "codex": {Path: "/fake/codex"},+ "claude": {Path: "/fake/claude"},+ }+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})+ setProbe := stubAgentProbe(t, map[string]AgentEntry{+ "codex": {Path: "/fake/codex"},+ "claude": {Path: "/fake/claude"},+ })+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {+ t.Fatalf("syncWorkspacesFromAPI: %v", err)+ }+ before := fx.registerCallCount()++ setProbe(map[string]AgentEntry{"codex": {Path: "/fake/codex"}})++ if gained := d.refreshAgentAvailability(); gained != nil {+ t.Fatalf("gained = %v, want none", gained)+ }+ if _, ok := d.agents()["claude"]; !ok {+ t.Error("claude was dropped from the availability set; refresh must be additive only")+ }+ if missing := d.providersMissingRuntimes(); missing != nil {+ t.Errorf("missing = %v, want none — a lost provider must not trigger work", missing)+ }+ if after := fx.registerCallCount(); after != before {+ t.Errorf("register calls went %d -> %d, want no change on a lost provider", before, after)+ }+}++// TestDiscovery_GainWithNoWorkspacesStillPublishes covers a bootstrap daemon:+// the provider must join the availability set (so /health and the first+// registration see it) even when there is no workspace to register against.+func TestDiscovery_GainWithNoWorkspacesStillPublishes(t *testing.T) {+ fx := newBatchFixture(t)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{}+ stubAgentProbe(t, map[string]AgentEntry{"antigravity": {Path: "/fake/agy"}})++ gained := d.refreshAgentAvailability()+ if len(gained) != 1 || gained[0] != "antigravity" {+ t.Fatalf("gained = %v, want [antigravity]", gained)+ }+ if _, ok := d.agents()["antigravity"]; !ok {+ t.Error("antigravity missing from the availability set")+ }+ if missing := d.providersMissingRuntimes(); missing != nil {+ t.Errorf("missing = %v, want none with no tracked workspaces", missing)+ }+ if got := fx.registerCallCount(); got != 0 {+ t.Errorf("made %d register calls with no tracked workspaces, want 0", got)+ }+}++// TestHealth_ReportsSkippedAgents covers the diagnostic half of MUL-5439: a CLI+// that IS installed but gets dropped at registration used to be+// indistinguishable from a CLI that is not installed — both produced no runtime.+func TestHealth_ReportsSkippedAgents(t *testing.T) {+ fx := newBatchFixture(t)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{+ "codex": {Path: "/fake/codex"},+ "antigravity": {Path: "/fake/agy"},+ }+ fx.setProbeErr(func(path string, _ int) error {+ if path == "/fake/agy" {+ return context.DeadlineExceeded+ }+ return nil+ })++ d.detectBuiltinRuntimes(context.Background())++ rec := httptest.NewRecorder()+ d.healthHandler(time.Now())(rec, httptest.NewRequest(http.MethodGet, "/health", nil))+ if rec.Code != http.StatusOK {+ t.Fatalf("health status = %d, want 200", rec.Code)+ }+ var resp HealthResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode health: %v", err)+ }+ reason, ok := resp.SkippedAgents["antigravity"]+ if !ok {+ t.Fatalf("skipped_agents = %v, want an antigravity entry", resp.SkippedAgents)+ }+ if reason == "" {+ t.Error("antigravity skip reason is empty; the UI needs something to show")+ }+ if _, ok := resp.SkippedAgents["codex"]; ok {+ t.Error("codex registered successfully but is listed as skipped")+ }++ // A later round where the CLI works must clear the entry, not accumulate.+ fx.setProbeErr(nil)+ d.detectBuiltinRuntimes(context.Background())+ if got := d.skippedAgentsSnapshot(); len(got) != 0 {+ t.Errorf("skipped agents = %v after a clean round, want empty", got)+ }+}++// TestMergeBuiltinRegisterResponse_ReplacesRotatedRuntimeID guards the one case+// the additive merge still has to handle destructively: the server returning a+// new ID for a runtime the workspace already had must swap, not duplicate, or+// the daemon would run two heartbeat goroutines for one runtime.+func TestMergeBuiltinRegisterResponse_ReplacesRotatedRuntimeID(t *testing.T) {+ d := freshDaemon("http://localhost:0")+ d.workspaces["ws-1"] = newWorkspaceState("ws-1", []string{"rt-old"}, "", nil, nil)+ d.runtimeIndex["rt-old"] = Runtime{ID: "rt-old", Provider: "codex"}++ newIDs, ok := d.mergeBuiltinRegisterResponse("ws-1", &RegisterResponse{+ Runtimes: []Runtime{{ID: "rt-new", Provider: "codex"}},+ })+ if !ok {+ t.Fatal("merge reported the workspace as untracked")+ }+ if len(newIDs) != 1 || newIDs[0] != "rt-new" {+ t.Fatalf("newIDs = %v, want [rt-new]", newIDs)+ }+ if got := d.workspaces["ws-1"].runtimeIDs; len(got) != 1 || got[0] != "rt-new" {+ t.Errorf("runtimeIDs = %v, want [rt-new] (rotated, not duplicated)", got)+ }+ if _, stale := d.runtimeIndex["rt-old"]; stale {+ t.Error("rt-old left in runtimeIndex; its heartbeat goroutine would leak")+ }+}++// TestMergeBuiltinRegisterResponse_IgnoresCustomProfileRuntimes pins the+// invariant guard: only the drift path may introduce a custom profile runtime, so+// a profile-bearing entry arriving here must be ignored rather than adopted.+func TestMergeBuiltinRegisterResponse_IgnoresCustomProfileRuntimes(t *testing.T) {+ d := freshDaemon("http://localhost:0")+ d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "", nil, nil)++ newIDs, ok := d.mergeBuiltinRegisterResponse("ws-1", &RegisterResponse{+ Runtimes: []Runtime{+ {ID: "rt-builtin", Provider: "codex"},+ {ID: "rt-custom", Provider: "codex", ProfileID: "prof-1"},+ },+ })+ if !ok {+ t.Fatal("merge reported the workspace as untracked")+ }+ if len(newIDs) != 1 || newIDs[0] != "rt-builtin" {+ t.Errorf("newIDs = %v, want only the built-in runtime", newIDs)+ }+ if _, adopted := d.runtimeIndex["rt-custom"]; adopted {+ t.Error("custom profile runtime was adopted by the discovery merge")+ }+}++// TestMergeBuiltinRegisterResponse_NeverTouchesProfileSignature is the direct+// unit-level pin for the second review round's P1.+func TestMergeBuiltinRegisterResponse_NeverTouchesProfileSignature(t *testing.T) {+ d := freshDaemon("http://localhost:0")+ ws := newWorkspaceState("ws-1", nil, "", nil, nil)+ ws.profileSetSig = "sig-before"+ d.workspaces["ws-1"] = ws++ if _, ok := d.mergeBuiltinRegisterResponse("ws-1", &RegisterResponse{+ Runtimes: []Runtime{{ID: "rt-1", Provider: "codex"}},+ }); !ok {+ t.Fatal("merge reported the workspace as untracked")+ }+ if got := d.workspaces["ws-1"].profileSetSig; got != "sig-before" {+ t.Errorf("profileSetSig = %q, want it untouched at sig-before", got)+ }+}++// TestAgentDiscoveryLoop_PicksUpInstallWithoutRestart covers the loop wiring:+// the fix is only useful if something calls the convergence on a schedule.+func TestAgentDiscoveryLoop_PicksUpInstallWithoutRestart(t *testing.T) {+ fx := newBatchFixture(t)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})+ setProbe := stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {+ t.Fatalf("syncWorkspacesFromAPI: %v", err)+ }++ origInterval := agentDiscoveryInterval+ agentDiscoveryInterval = 5 * time.Millisecond+ t.Cleanup(func() { agentDiscoveryInterval = origInterval })++ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan struct{})+ // Stop the loop and WAIT for it before the test returns: the fixture's+ // t.Cleanup restores the global version-probe stub, which would otherwise+ // race a probe still in flight inside the loop goroutine.+ defer func() {+ cancel()+ <-done+ }()+ go func() {+ defer close(done)+ d.agentDiscoveryLoop(ctx)+ }()++ setProbe(map[string]AgentEntry{+ "codex": {Path: "/fake/codex"},+ "antigravity": {Path: "/fake/agy"},+ })++ deadline := time.Now().Add(3 * time.Second)+ for {+ got := registeredProviders(t, d, "ws-1")+ if len(got) == 2 && got[0] == "antigravity" && got[1] == "codex" {+ break+ }+ if time.Now().After(deadline) {+ t.Fatalf("discovery loop never registered the newly installed CLI; providers = %v", got)+ }+ time.Sleep(5 * time.Millisecond)+ }+}++// TestAgentDiscoveryLoop_BacksOffStuckProvider keeps a permanently unregisterable+// provider (below minimum version forever, --version always broken) from turning+// the loop into a version-probe and register-call busy loop.+func TestAgentDiscoveryLoop_BacksOffStuckProvider(t *testing.T) {+ fx := newBatchFixture(t)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})+ setProbe := stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {+ t.Fatalf("syncWorkspacesFromAPI: %v", err)+ }+ fx.setProbeErr(func(path string, _ int) error {+ if path == "/fake/agy" {+ return errors.New("permanently broken")+ }+ return nil+ })++ origInterval, origMax := agentDiscoveryInterval, agentConvergeMaxBackoff+ origRetryDelay := runtimeVersionProbeRetryDelay+ agentDiscoveryInterval = 2 * time.Millisecond+ agentConvergeMaxBackoff = 50 * time.Millisecond+ // Each convergence version-probes the stuck provider up to+ // runtimeVersionProbeAttempts times; keep that budget short so the+ // observation window below measures backoff rather than probe latency.+ runtimeVersionProbeRetryDelay = time.Millisecond+ t.Cleanup(func() {+ agentDiscoveryInterval = origInterval+ agentConvergeMaxBackoff = origMax+ runtimeVersionProbeRetryDelay = origRetryDelay+ })++ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan struct{})+ defer func() {+ cancel()+ <-done+ }()+ go func() {+ defer close(done)+ d.agentDiscoveryLoop(ctx)+ }()++ setProbe(map[string]AgentEntry{+ "codex": {Path: "/fake/codex"},+ "antigravity": {Path: "/fake/agy"},+ })++ // Wait for the first failing convergence, then measure how many further+ // attempts happen over a window many ticks long. With backoff, attempts+ // must be far fewer than ticks.+ deadline := time.Now().Add(2 * time.Second)+ for fx.probeCount("/fake/agy") == 0 {+ if time.Now().After(deadline) {+ t.Fatal("loop never attempted the stuck provider")+ }+ time.Sleep(2 * time.Millisecond)+ }+ start := fx.probeCount("/fake/agy")+ time.Sleep(400 * time.Millisecond) // ~200 ticks at a 2ms interval+ attempts := fx.probeCount("/fake/agy") - start+ // Ticks in the window: ~200. Convergences allowed by a 50ms cap: ~8, each+ // costing runtimeVersionProbeAttempts probes. The point is the order of+ // magnitude: retries must track the backoff, not the tick rate.+ if attempts > 40 {+ t.Errorf("stuck provider was probed %d times in ~200 ticks; backoff is not limiting retries", attempts)+ }+ if attempts == 0 {+ t.Error("stuck provider was never retried; backoff must not give up entirely")+ }+}++// TestCachedShellResolvedAgents_ReusesResultWithinTTL guards the cost side of+// running discovery periodically: resolveAgentsViaLoginShell forks the user's+// login shell and runs their rc files, so repeated probes must not repeat it.+func TestCachedShellResolvedAgents_ReusesResultWithinTTL(t *testing.T) {+ var calls int+ orig := resolveAgentsViaLoginShell+ t.Cleanup(func() { resolveAgentsViaLoginShell = orig })+ resolveAgentsViaLoginShell = func([]string) map[string]string {+ calls+++ return map[string]string{"agy": "/fake/agy"}+ }+ resetShellResolveCacheForTest(t)++ for i := 0; i < 5; i++ {+ if got := cachedShellResolvedAgents()["agy"]; got != "/fake/agy" {+ t.Fatalf("resolution %d = %q, want /fake/agy", i, got)+ }+ }+ if calls != 1 {+ t.Errorf("forked the login shell %d times, want 1 within the TTL", calls)+ }++ // An expired TTL must re-resolve, otherwise a CLI installed into a+ // login-shell-only PATH dir would never be discovered.+ shellResolveMu.Lock()+ shellResolvedAt = time.Now().Add(-2 * shellResolveTTL)+ shellResolveMu.Unlock()+ cachedShellResolvedAgents()+ if calls != 2 {+ t.Errorf("forked the login shell %d times, want 2 after the TTL expired", calls)+ }+}++// TestCachedShellResolvedAgents_InvalidatesOnEnvChange keeps the cache honest+// when the resolution-relevant environment changes.+func TestCachedShellResolvedAgents_InvalidatesOnEnvChange(t *testing.T) {+ var calls int+ orig := resolveAgentsViaLoginShell+ t.Cleanup(func() { resolveAgentsViaLoginShell = orig })+ resolveAgentsViaLoginShell = func([]string) map[string]string {+ calls+++ return map[string]string{}+ }+ resetShellResolveCacheForTest(t)++ t.Setenv("PATH", "/one")+ cachedShellResolvedAgents()+ t.Setenv("PATH", "/two")+ cachedShellResolvedAgents()+ if calls != 2 {+ t.Errorf("resolved %d times across a PATH change, want 2", calls)+ }+}++func resetShellResolveCacheForTest(t *testing.T) {+ t.Helper()+ reset := func() {+ shellResolveMu.Lock()+ shellResolveCache = nil+ shellResolveKey = ""+ shellResolvedAt = time.Time{}+ shellResolveMu.Unlock()+ }+ reset()+ t.Cleanup(reset)+}diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 2960e4a223..45dc191da5 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -9,7 +9,6 @@ import ("os/exec""path/filepath""strings"- "sync""time""github.com/mattn/go-shellwords"@@ -214,140 +213,9 @@ func LoadConfig(overrides Overrides) (Config, error) {}}- // Probe available agent CLIs. exec.LookPath is the primary path, but on- // macOS/Linux a GUI-launched daemon (Electron, Launchpad) does not- // inherit the user's interactive shell PATH — fnm/nvm/volta multishells,- // the Anthropic native installer prefix, and per-user npm prefixes all- // live in dirs that only get added to PATH by ~/.zshrc or ~/.bashrc.- // shellResolvedAgents asks the user's login shell, lazily on first miss,- // to resolve every standard agent name to its canonical absolute path,- // so we can find binaries the bare daemon process can't see. See- // resolveAgentsViaLoginShell for the details and constraints.- //- // Laziness matters: the happy path (every agent on the daemon's PATH or- // pinned to an explicit MULTICA_*_PATH) must not pay the cost of- // spawning the user's login shell — that touches their rc files and- // adds startup latency that scales with whatever they put in there. We- // only fork a shell when a bare command name actually missed LookPath.- var (- shellResolveOnce sync.Once- shellResolved map[string]string- )- getShellResolved := func() map[string]string {- shellResolveOnce.Do(func() {- shellResolved = resolveAgentsViaLoginShell(defaultAgentCommandNames)- })- return shellResolved- }- probe := func(envVar, defaultCmd, modelEnv string) (AgentEntry, bool) {- cmd := envOrDefault(envVar, defaultCmd)- if path, err := resolveAgentExecutablePath(cmd); err == nil {- return AgentEntry{- Path: path,- Command: cmd,- Model: strings.TrimSpace(os.Getenv(modelEnv)),- }, true- }- // The shell fallback only rescues bare command names. An operator- // who pinned MULTICA_*_PATH to an absolute or relative path that- // doesn't exist should hard-miss, not silently get a different- // binary.- if strings.ContainsAny(cmd, "/\\") {- return AgentEntry{}, false- }- if path, ok := getShellResolved()[cmd]; ok {- return AgentEntry{- Path: path,- Command: cmd,- Model: strings.TrimSpace(os.Getenv(modelEnv)),- }, true- }- if defaultCmd == "codex" && cmd == defaultCmd {- // Codex Desktop bundles its CLI inside the macOS app instead of- // installing it onto PATH.- for _, p := range codexDesktopAppBundlePaths() {- if _, err := os.Stat(p); err == nil {- return AgentEntry{- Path: p,- Command: cmd,- Model: strings.TrimSpace(os.Getenv(modelEnv)),- }, true- }- }- }- return AgentEntry{}, false- }-- agents := map[string]AgentEntry{}- if e, ok := probe("MULTICA_CLAUDE_PATH", "claude", "MULTICA_CLAUDE_MODEL"); ok {- agents["claude"] = e- }- if e, ok := probe("MULTICA_CODEX_PATH", "codex", "MULTICA_CODEX_MODEL"); ok {- agents["codex"] = e- }- if e, ok := probe("MULTICA_OPENCODE_PATH", "opencode", "MULTICA_OPENCODE_MODEL"); ok {- agents["opencode"] = e- }- if e, ok := probe("MULTICA_DEVECO_PATH", "deveco", "MULTICA_DEVECO_MODEL"); ok {- agents["deveco"] = e- }- if e, ok := probe("MULTICA_OPENCLAW_PATH", "openclaw", "MULTICA_OPENCLAW_MODEL"); ok {- agents["openclaw"] = e- }- if e, ok := probe("MULTICA_HERMES_PATH", "hermes", "MULTICA_HERMES_MODEL"); ok {- agents["hermes"] = e- }- if e, ok := probe("MULTICA_PI_PATH", "pi", "MULTICA_PI_MODEL"); ok {- agents["pi"] = e- }- if e, ok := probe("MULTICA_CURSOR_PATH", "cursor-agent", "MULTICA_CURSOR_MODEL"); ok {- agents["cursor"] = e- }- if e, ok := probe("MULTICA_COPILOT_PATH", "copilot", "MULTICA_COPILOT_MODEL"); ok {- agents["copilot"] = e- }- if e, ok := probe("MULTICA_KIMI_PATH", "kimi", "MULTICA_KIMI_MODEL"); ok {- agents["kimi"] = e- }- if e, ok := probe("MULTICA_KIRO_PATH", "kiro-cli", "MULTICA_KIRO_MODEL"); ok {- agents["kiro"] = e- }- if e, ok := probe("MULTICA_CODEBUDDY_PATH", "codebuddy", "MULTICA_CODEBUDDY_MODEL"); ok {- agents["codebuddy"] = e- }- // agy 1.0.6 added a `--model` flag (MUL-3125), so Antigravity now takes a- // model env like every other backend. MULTICA_ANTIGRAVITY_MODEL seeds the- // daemon-wide default; its value is the exact `agy models` display string- // (e.g. "Claude Opus 4.6 (Thinking)"), not a provider/model slug.- if e, ok := probe("MULTICA_ANTIGRAVITY_PATH", "agy", "MULTICA_ANTIGRAVITY_MODEL"); ok {- agents["antigravity"] = e- }- qoderPath := envOrDefault("MULTICA_QODER_PATH", "qodercli")- if path, err := resolveAgentExecutablePath(qoderPath); err == nil {- agents["qoder"] = AgentEntry{- Path: path,- Command: qoderPath,- Model: strings.TrimSpace(os.Getenv("MULTICA_QODER_MODEL")),- }- }- // ByteDance official TRAE CLI (the `traecli` binary from https://docs.trae.cn/cli),- // driven over ACP via `traecli acp serve --yolo`. MULTICA_TRAECLI_MODEL seeds- // the daemon-wide default model (a model id from the user's logged-in traecli- // catalog).- if e, ok := probe("MULTICA_TRAECLI_PATH", "traecli", "MULTICA_TRAECLI_MODEL"); ok {- agents["traecli"] = e- }- // xAI Grok Build CLI (`grok`), driven over ACP via- // `grok agent --always-approve stdio`. MULTICA_GROK_MODEL seeds the- // daemon-wide default (e.g. grok-4.5).- if e, ok := probe("MULTICA_GROK_PATH", "grok", "MULTICA_GROK_MODEL"); ok {- agents["grok"] = e- }- // Qwen Code (`qwen`) runs headlessly with -p and stream-json. Its native- // QWEN.md and .qwen/skills task context is prepared by execenv.- if e, ok := probe("MULTICA_QWEN_PATH", "qwen", "MULTICA_QWEN_MODEL"); ok {- agents["qwen"] = e- }+ // Discover installed agent CLIs. Extracted so the periodic workspace sync+ // can re-run the same discovery on a live daemon (MUL-5439).+ agents := probeAgentCLIs()if len(agents) == 0 && !overrides.AllowNoAgents {return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codex, copilot, opencode, deveco, openclaw, hermes, pi, cursor-agent, kimi, kiro-cli, agy, qodercli, traecli, grok, or qwen and ensure it is on PATH")}@@ -949,7 +817,9 @@ var supportedLoginShells = map[string]struct{}{// (`[A-Za-z0-9._-]` only); we inline them into the script unquoted to// keep the script readable. Custom MULTICA_*_PATH values never reach this// resolver — those go through exec.LookPath directly.-func resolveAgentsViaLoginShell(names []string) map[string]string {+//+// A var so tests can stub the fork without a real login shell.+var resolveAgentsViaLoginShell = func(names []string) map[string]string {out := map[string]string{}if len(names) == 0 {return outdiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex cce96ba36d..7559847a98 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -251,6 +251,24 @@ type Daemon struct {versionsMu sync.RWMutex // guards agentVersionsagentVersions map[string]string // provider -> detected CLI version (set during registration)+ // agentsAvailable holds the current built-in agent CLI availability set —+ // the same shape as cfg.Agents, which it supersedes as the read path.+ //+ // It is copy-on-write, NOT a mutable map: refreshAgentAvailability swaps in+ // a whole new map, and readers (agents()) take the pointer once and then+ // only read. cfg.Agents used to be read unlocked from task-execution paths+ // (resolveAgentEntry, runTask), so making the discovery set refreshable at+ // runtime (MUL-5439) would otherwise be a data race.+ agentsAvailable atomic.Pointer[map[string]AgentEntry]++ // skippedAgents records why a discovered provider did not make it into the+ // last registration round (version undetectable, below minimum). Purely+ // diagnostic: surfaced on /health so the UI can tell "not installed" apart+ // from "installed but dropped", instead of silently showing nothing+ // (MUL-5439). Guarded by skippedAgentsMu.+ skippedAgentsMu sync.RWMutex+ skippedAgents map[string]string // provider -> human-readable reason+// resolvedPathsMu guards resolvedPaths, the self-healed executable paths.// The daemon pins each agent's absolute path at startup so a later PATH// change can't redirect a task launch. When that pinned path later vanishes@@ -396,6 +414,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {profileLaunchSpecs: make(map[string]profileLaunchSpec),runtimeSet: newRuntimeSetWatcher(),agentVersions: make(map[string]string),+ skippedAgents: make(map[string]string),resolvedPaths: make(map[string]healedAgent),wsHBLastAck: make(map[string]time.Time),activeEnvRoots: make(map[string]int),@@ -414,6 +433,14 @@ func New(cfg Config, logger *slog.Logger) *Daemon {}d.activeEnvRootsCond = sync.NewCond(&d.activeEnvRootsMu)d.activeCodexStoresCond = sync.NewCond(&d.activeCodexStoresMu)+ // Seed the copy-on-write availability set from the startup probe. Callers+ // must go through d.agents() from here on; cfg.Agents is the initial value+ // only and does not track later refreshes.+ initialAgents := make(map[string]AgentEntry, len(cfg.Agents))+ for name, entry := range cfg.Agents {+ initialAgents[name] = entry+ }+ d.agentsAvailable.Store(&initialAgents)d.executionEnvironmentCommand = defaultExecutionEnvironmentCommandd.runner = taskRunnerFunc(d.runTask)d.runUpdateFn = d.runUpdate@@ -883,6 +910,91 @@ func (d *Daemon) applyRegisterResponseInPlace(workspaceID string, resp *Registerreturn newIDs, droppedIDs, true}+// mergeBuiltinRegisterResponse applies a builtins-only register response+// ADDITIVELY: returned built-in runtimes are indexed and appended, and a prior+// runtime ID that the response did not mention is left alone.+//+// applyRegisterResponseInPlace treats the response as authoritative and drops+// unmentioned IDs, which is right for the convergence paths that deliberately+// re-derive a workspace's whole runtime set. It is wrong for CLI discovery+// (MUL-5439): that payload carries built-in runtimes only, so under the+// authoritative rule it would evict the workspace's custom profile runtimes from+// runtimeIndex and stop their heartbeats, possibly mid-task. The server's+// register endpoint is a pure per-entry upsert and prunes nothing, so omitted+// runtimes still exist server-side and must be kept locally.+//+// Two deliberate omissions keep this path out of custom-profile business:+//+// - Entries with a ProfileID are ignored. Discovery registers built-ins only,+// so this is an invariant guard: a custom runtime must never enter the set+// through here.+// - profileSetSig is neither read nor written. Caching a signature observed+// during discovery would tell refreshWorkspaceRuntimeProfiles that the+// profile set was already converged, and a profile disabled at that moment+// would keep its runtime alive forever.+//+// ID rotation is still handled: when the response returns a different ID for a+// built-in provider the workspace already had, that specific old ID is replaced+// rather than accumulating a duplicate heartbeat.+func (d *Daemon) mergeBuiltinRegisterResponse(workspaceID string, resp *RegisterResponse) (newIDs []string, ok bool) {+ d.mu.Lock()+ defer d.mu.Unlock()+ ws, exists := d.workspaces[workspaceID]+ if !exists {+ return nil, false+ }++ // Index the workspace's current built-in runtimes by provider so a rotated+ // ID replaces its predecessor instead of doubling it.+ existingByProvider := make(map[string]string, len(ws.runtimeIDs))+ kept := make([]string, 0, len(ws.runtimeIDs)+len(resp.Runtimes))+ present := make(map[string]struct{}, len(ws.runtimeIDs))+ for _, id := range ws.runtimeIDs {+ if rt, found := d.runtimeIndex[id]; found && rt.ProfileID == "" {+ existingByProvider[rt.Provider] = id+ }+ kept = append(kept, id)+ present[id] = struct{}{}+ }++ for _, rt := range resp.Runtimes {+ if rt.ProfileID != "" {+ // Not ours to manage; the drift path owns custom profiles.+ continue+ }+ d.runtimeIndex[rt.ID] = rt+ if _, already := present[rt.ID]; already {+ continue+ }+ if oldID, rotated := existingByProvider[rt.Provider]; rotated && oldID != rt.ID {+ // Same runtime, new ID: swap in place and retire the old entry.+ for i, id := range kept {+ if id == oldID {+ kept[i] = rt.ID+ break+ }+ }+ delete(d.runtimeIndex, oldID)+ delete(present, oldID)+ } else {+ kept = append(kept, rt.ID)+ }+ present[rt.ID] = struct{}{}+ existingByProvider[rt.Provider] = rt.ID+ newIDs = append(newIDs, rt.ID)+ }+ ws.runtimeIDs = kept++ if resp.ReposVersion != "" {+ ws.reposVersion = resp.ReposVersion+ ws.allowedRepoURLs = repoAllowlist(resp.Repos)+ }+ if len(resp.Settings) > 0 {+ ws.settings = resp.Settings+ }+ return newIDs, true+}+func (d *Daemon) reregisterWorkspaceAfterRuntimeGone(ctx context.Context, workspaceID string) error {resp, profileSig, err := d.registerRuntimesForWorkspace(ctx, workspaceID)if err != nil {@@ -1020,8 +1132,8 @@ func (d *Daemon) Run(ctx context.Context) error {return err}- agentNames := make([]string, 0, len(d.cfg.Agents))- for name := range d.cfg.Agents {+ agentNames := make([]string, 0, len(d.agents()))+ for name := range d.agents() {agentNames = append(agentNames, name)}logFields := []any{"version", d.cfg.CLIVersion, "agents", agentNames, "server", d.cfg.ServerBaseURL}@@ -1086,6 +1198,11 @@ func (d *Daemon) Run(ctx context.Context) error {// Start workspace sync loop to discover newly created workspaces.go d.workspaceSyncLoop(ctx)+ // Discover agent CLIs installed after startup (MUL-5439). Separate from the+ // workspace sync loop because that one runs on a thirty-minute consistency+ // interval — far too slow for "install a CLI, see it under Runtimes".+ go d.agentDiscoveryLoop(ctx)+taskWakeups := make(chan taskWakeup, 256)go d.taskWakeupLoop(ctx, taskWakeups)go d.heartbeatLoop(ctx)@@ -1266,7 +1383,12 @@ var runtimeVersionProbeRetryWindow = time.Second// false when the provider must be dropped from this round's registration// payload: its version could not be detected, or it is below the minimum// supported version.-func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry AgentEntry) (string, bool) {+//+// The second return value is a short human-readable reason when ok is false.+// It is surfaced on /health as skipped_agents so a user can tell "CLI not+// installed" apart from "CLI installed but dropped at registration", which was+// previously only visible in the daemon log (MUL-5439).+func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry AgentEntry) (string, string, bool) {var (lastErr errorattempts int@@ -1316,14 +1438,18 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Age// so a retry would reach the same conclusion — drop the provider now.if err := checkAgentMinVersion(name, version); err != nil {d.logger.Warn("skip registering runtime: version too old", "name", name, "version", version, "error", err)- return "", false+ return "", err.Error(), false}d.setAgentVersion(name, version)d.logger.Debug("agent version detected", "name", name, "version", version, "path", resolved.Path)- return version, true+ return version, "", true}d.logger.Warn("skip registering runtime", "name", name, "attempts", attempts, "error", lastErr)- return "", false+ reason := "version detection failed"+ if lastErr != nil {+ reason = fmt.Sprintf("version detection failed: %v", lastErr)+ }+ return "", reason, false}// detectBuiltinRuntimes version-detects every configured built-in agent CLI and@@ -1358,14 +1484,18 @@ func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) []map[string]stringvar (mu sync.Mutexresults []detected+ skipped = map[string]string{}g errgroup.Group)g.SetLimit(runtimeVersionProbeConcurrency)- for name, entry := range d.cfg.Agents {+ for name, entry := range d.agents() {name, entry := name, entryg.Go(func() error {- version, ok := d.probeBuiltinRuntime(ctx, name, entry)+ version, reason, ok := d.probeBuiltinRuntime(ctx, name, entry)if !ok {+ mu.Lock()+ skipped[name] = reason+ mu.Unlock()return nil}mu.Lock()@@ -1378,6 +1508,11 @@ func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) []map[string]string// so Wait only blocks for the in-flight probes to finish._ = g.Wait()+ // Publish this round's drops for /health. Replacing (not merging) keeps the+ // diagnostic honest: a provider that registered successfully this round must+ // not stay listed as skipped.+ d.setSkippedAgents(skipped)+// Source iteration (a map) and parallel completion order are both// nondeterministic; sort by provider so the registration payload is stable// across runs and order-sensitive tests stay deterministic.@@ -1445,7 +1580,7 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s// builtins is treated as read-only and is copied before this workspace's custom// runtime profiles are appended.func (d *Daemon) registerRuntimesForWorkspaceBatch(ctx context.Context, workspaceID string, builtins []map[string]string) (*RegisterResponse, string, error) {- d.logger.Debug("registering runtimes for workspace", "workspace_id", workspaceID, "agent_count", len(d.cfg.Agents))+ d.logger.Debug("registering runtimes for workspace", "workspace_id", workspaceID, "agent_count", len(d.agents()))runtimes := cloneRuntimeEntries(builtins)var failedProfiles []map[string]string@@ -1493,6 +1628,48 @@ func (d *Daemon) registerRuntimesForWorkspaceBatch(ctx context.Context, workspacreturn resp, profileSig, nil}+// registerBuiltinRuntimesForWorkspace registers ONLY the built-in runtimes for a+// workspace: no custom runtime profiles are fetched or sent, and no profile+// signature is produced.+//+// This exists for the CLI-discovery path (MUL-5439), which must not participate+// in custom-profile convergence at all. Going through the profile-appending+// registration made discovery observe the profile set as a side effect, and+// caching that observation told the drift path "already converged" — so a+// profile disabled at the same moment a new CLI was discovered would keep its+// runtime alive forever (refreshWorkspaceRuntimeProfiles short-circuits on a+// matching signature). Custom profile add/edit/disable stays exclusively with+// the existing drift path.+//+// builtins is treated as read-only.+func (d *Daemon) registerBuiltinRuntimesForWorkspace(ctx context.Context, workspaceID string, builtins []map[string]string) (*RegisterResponse, error) {+ runtimes := cloneRuntimeEntries(builtins)+ if len(runtimes) == 0 {+ return nil, ErrNoRuntimesToRegister+ }+ req := map[string]any{+ "workspace_id": workspaceID,+ "daemon_id": d.cfg.DaemonID,+ "legacy_daemon_ids": d.cfg.LegacyDaemonIDs,+ "device_name": d.cfg.DeviceName,+ "cli_version": d.cfg.CLIVersion,+ "launched_by": d.cfg.LaunchedBy,+ "runtimes": runtimes,+ // Deliberately empty: this call carries no profiles, so it must not+ // report profile failures either.+ "failed_profiles": []map[string]string{},+ }+ resp, err := d.client.Register(ctx, req)+ if err != nil {+ return nil, fmt.Errorf("register builtin runtimes: %w", err)+ }+ if len(resp.Runtimes) == 0 {+ return nil, fmt.Errorf("register builtin runtimes: empty response")+ }+ d.logger.Debug("builtin register response", "workspace_id", workspaceID, "runtimes", len(resp.Runtimes))+ return resp, nil+}+// appendProfileRuntimes fetches the workspace's enabled custom runtime// profiles (MUL-3284) and appends a runtime registration entry for each one// whose command_name resolves on this host's PATH. For each resolved profile@@ -2610,7 +2787,7 @@ func (d *Daemon) handleHeartbeatActions(ctx context.Context, runtimeID string, rfunc (d *Daemon) handleModelList(ctx context.Context, rt Runtime, requestID string) {d.logger.Info("model list requested", "runtime_id", rt.ID, "request_id", requestID, "provider", rt.Provider)- entry, ok := d.cfg.Agents[rt.Provider]+ entry, ok := d.agents()[rt.Provider]if !ok {d.reportModelListResult(ctx, rt, requestID, map[string]any{"status": "failed",@@ -4367,7 +4544,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot id.registerTaskRepos(task.WorkspaceID, task.ID, task.Repos)defer d.clearTaskRepoRefs(task.WorkspaceID, task.ID)- entry, ok := d.cfg.Agents[provider]+ entry, ok := d.agents()[provider]// A custom runtime profile (MUL-3284) overrides the executable path: the// runtime's protocol_family is the provider (so agent.New still selects// the right backend), but the actual binary on PATH is the profile'sdiff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.goindex e62da8164e..d50e16e2c5 100644--- a/server/internal/daemon/health.go+++ b/server/internal/daemon/health.go@@ -25,15 +25,24 @@ type HealthResponse struct {// lifecycle CLI (`daemon start/stop`) acts on the host process namespace,// so a foreign-OS daemon can't be started/stopped by the app even though// /health is reachable. See #3916.- OS string `json:"os"`- Uptime string `json:"uptime"`- DaemonID string `json:"daemon_id"`- DeviceName string `json:"device_name"`- ServerURL string `json:"server_url"`- CLIVersion string `json:"cli_version"`- ActiveTaskCount int64 `json:"active_task_count"`- Agents []string `json:"agents"`- Workspaces []healthWorkspace `json:"workspaces"`+ OS string `json:"os"`+ Uptime string `json:"uptime"`+ DaemonID string `json:"daemon_id"`+ DeviceName string `json:"device_name"`+ ServerURL string `json:"server_url"`+ CLIVersion string `json:"cli_version"`+ ActiveTaskCount int64 `json:"active_task_count"`+ Agents []string `json:"agents"`+ // SkippedAgents maps a provider that WAS discovered on this machine to the+ // reason the last registration round dropped it (version undetectable,+ // below the minimum supported version). Purely diagnostic, and omitted when+ // empty so older consumers see no change.+ //+ // Without it, "CLI not installed" and "CLI installed but rejected" both+ // render as an absent runtime, which is what made GH #6077 unactionable for+ // the reporter (MUL-5439).+ SkippedAgents map[string]string `json:"skipped_agents,omitempty"`+ Workspaces []healthWorkspace `json:"workspaces"`}type healthWorkspace struct {@@ -77,8 +86,8 @@ func (d *Daemon) healthHandler(startedAt time.Time) http.HandlerFunc {}d.mu.Unlock()- agents := make([]string, 0, len(d.cfg.Agents))- for name := range d.cfg.Agents {+ agents := make([]string, 0, len(d.agents()))+ for name := range d.agents() {agents = append(agents, name)}@@ -104,6 +113,7 @@ func (d *Daemon) healthHandler(startedAt time.Time) http.HandlerFunc {CLIVersion: d.cfg.CLIVersion,ActiveTaskCount: d.activeTasks.Load(),Agents: agents,+ SkippedAgents: d.skippedAgentsSnapshot(),Workspaces: wsList,}diff --git a/server/internal/daemon/runtime_probe_batch_test.go b/server/internal/daemon/runtime_probe_batch_test.goindex 1b34b57e10..99e913b25a 100644--- a/server/internal/daemon/runtime_probe_batch_test.go+++ b/server/internal/daemon/runtime_probe_batch_test.go@@ -43,6 +43,54 @@ type batchFixture struct {// succeeds. It receives the executable path and the 1-based attempt count// for that path, and returns a non-nil error to fail that attempt.probeErr func(path string, attempt int) error+ // registerFail, when non-nil, makes /api/daemon/register return 500. A+ // non-empty string key scopes the failure to that workspace ID; the empty+ // string key fails every workspace. Used to exercise the discovery retry+ // paths (MUL-5439).+ registerFail map[string]bool+ // profilesFail makes the runtime-profiles route return 500, reproducing the+ // best-effort profile fetch failing while a discovery-driven registration+ // is in flight.+ profilesFail bool+}++// failRegister toggles register failure for every workspace.+func (fx *batchFixture) failRegister(fail bool) {+ fx.mu.Lock()+ defer fx.mu.Unlock()+ if fx.registerFail == nil {+ fx.registerFail = make(map[string]bool)+ }+ fx.registerFail[""] = fail+}++// failRegisterFor toggles register failure for one workspace.+func (fx *batchFixture) failRegisterFor(workspaceID string, fail bool) {+ fx.mu.Lock()+ defer fx.mu.Unlock()+ if fx.registerFail == nil {+ fx.registerFail = make(map[string]bool)+ }+ fx.registerFail[workspaceID] = fail+}++func (fx *batchFixture) registerShouldFail(workspaceID string) bool {+ fx.mu.Lock()+ defer fx.mu.Unlock()+ return fx.registerFail[""] || fx.registerFail[workspaceID]+}++// failProfiles toggles failure of the custom runtime profiles fetch.+func (fx *batchFixture) failProfiles(fail bool) {+ fx.mu.Lock()+ defer fx.mu.Unlock()+ fx.profilesFail = fail+}++func (fx *batchFixture) profilesShouldFail() bool {+ fx.mu.Lock()+ defer fx.mu.Unlock()+ return fx.profilesFail}type registeredCall struct {@@ -133,6 +181,11 @@ func newBatchFixture(t *testing.T) *batchFixture {Runtimes []map[string]string `json:"runtimes"`}_ = json.NewDecoder(r.Body).Decode(&body)+ if fx.registerShouldFail(body.WorkspaceID) {+ w.WriteHeader(http.StatusInternalServerError)+ _, _ = w.Write([]byte(`{"error":"injected register failure"}`))+ return+ }call := registeredCall{workspaceID: body.WorkspaceID}var resp RegisterResponsefor _, rt := range body.Runtimes {@@ -151,6 +204,11 @@ func newBatchFixture(t *testing.T) *batchFixture {w.Header().Set("Content-Type", "application/json")_ = json.NewEncoder(w).Encode(resp)case strings.HasSuffix(r.URL.Path, "/runtime-profiles"):+ if fx.profilesShouldFail() {+ w.WriteHeader(http.StatusInternalServerError)+ _, _ = w.Write([]byte(`{"error":"injected profiles failure"}`))+ return+ }workspaceID := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/api/daemon/workspaces/"), "/runtime-profiles")fx.mu.Lock()profiles := fx.profiles[workspaceID]