Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-3332: daemon picks up new custom runtime profiles without restart (#4225)
Multica Eve6bb8cac9ea19
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex dc9bec74fe..5ea7bb65b8 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -11,6 +11,7 @@ import ("os""os/exec""path/filepath"+ "sort""strconv""strings""sync"@@ -29,6 +30,19 @@ import (// server refresh.var ErrRepoNotConfigured = errors.New("repo is not configured for this workspace")+// ErrNoRuntimesToRegister is returned by registerRuntimesForWorkspace when+// the daemon has nothing to host on a workspace — typically a custom-only+// daemon whose only enabled custom runtime profile was just disabled, leaving+// zero built-in agents and zero resolvable profiles. Callers must+// differentiate by intent: initial registration (syncWorkspacesFromAPI's+// new-workspace branch) treats this as a config error and skips the+// workspace until something changes; the profile-drift refresh path+// (refreshWorkspaceRuntimeProfiles) treats it as a legitimate converged+// state and explicitly deregisters the now-stale local runtime IDs so the+// server marks them offline immediately instead of waiting on the 150 s+// stale-heartbeat sweep.+var ErrNoRuntimesToRegister = errors.New("no agent runtimes could be registered")+const (taskSlotWaitTimeout = 2 * time.SecondtaskSlotCapacityBackoff = 5 * time.Second@@ -108,6 +122,14 @@ type workspaceState struct {settings json.RawMessage // workspace settings (JSONB)lastRepoSyncErr stringrepoRefreshMu sync.Mutex+ // profileSetSig is a content hash of the workspace's custom runtime+ // profile list (MUL-3332) as last seen from the server. The+ // workspaceSyncLoop compares the live signature with this cached value;+ // any drift triggers a re-register so newly-added (or edited / disabled)+ // custom runtimes appear without a daemon restart. Empty before the+ // first successful profile fetch (older server / network blip); guarded+ // by Daemon.mu like every other field on this struct.+ profileSetSig string}type repoCacheBackend interface {@@ -475,13 +497,33 @@ func (d *Daemon) workspaceNeedsRuntimeRecovery(workspaceID string) bool {//// The workspaceState pointer is NEVER replaced (see syncWorkspacesFromAPI's// invariant about repoRefreshMu). Only fields are mutated.-func (d *Daemon) reregisterWorkspaceAfterRuntimeGone(ctx context.Context, workspaceID string) error {- resp, err := d.registerRuntimesForWorkspace(ctx, workspaceID)- if err != nil {- return fmt.Errorf("register runtimes: %w", err)- }-- newIDs := make([]string, 0, len(resp.Runtimes))+// applyRegisterResponseInPlace folds a fresh /api/daemon/register response+// back into the workspaceState and runtimeIndex without replacing the+// workspaceState pointer (see syncWorkspacesFromAPI's invariant about+// repoRefreshMu). It is the shared converger used by both the runtime_gone+// recovery and the profile-drift refresh; the two callers differ only in+// follow-up side effects (RecoverOrphans / Deregister), so those stay at the+// call site.+//+// Returns:+// - newIDs: the runtime IDs the server returned in this response, in+// the order they were returned. These are the daemon's authoritative+// current runtime set after the call.+// - droppedIDs: runtime IDs that were tracked before this call but did+// NOT survive the response. Drift callers Deregister these so the+// server marks them offline immediately instead of waiting on the 150 s+// stale-heartbeat sweep; the runtime_gone path can ignore them because+// those rows were already deleted server-side.+// - ok: false when the workspace was forgotten between the+// register call and this apply (e.g. the user left the workspace and+// syncWorkspacesFromAPI removed it). The caller must abort silently in+// that case — there is no state left to update.+//+// profileSig is the digest captured during the register; an empty value is+// the explicit "fetch failed, keep the previous signature" sentinel from+// appendProfileRuntimes.+func (d *Daemon) applyRegisterResponseInPlace(workspaceID string, resp *RegisterResponse, profileSig string) (newIDs, droppedIDs []string, ok bool) {+ newIDs = make([]string, 0, len(resp.Runtimes))newIDSet := make(map[string]struct{}, len(resp.Runtimes))for _, rt := range resp.Runtimes {newIDs = append(newIDs, rt.ID)@@ -489,17 +531,19 @@ func (d *Daemon) reregisterWorkspaceAfterRuntimeGone(ctx context.Context, worksp}d.mu.Lock()- ws, ok := d.workspaces[workspaceID]- if !ok {- d.mu.Unlock()- return fmt.Errorf("workspace %s no longer tracked", workspaceID)+ defer d.mu.Unlock()+ ws, exists := d.workspaces[workspaceID]+ if !exists {+ return nil, nil, false}// Drop runtimeIndex entries for prior runtime IDs that the server did not// return — typically there are none for upsert-on-existing-provider, but- // a daemon config change (provider removed) would leak entries otherwise.+ // a daemon config change (provider removed) or a profile disable would+ // leak entries otherwise.for _, oldID := range ws.runtimeIDs {if _, kept := newIDSet[oldID]; !kept {delete(d.runtimeIndex, oldID)+ droppedIDs = append(droppedIDs, oldID)}}for _, rt := range resp.Runtimes {@@ -517,7 +561,26 @@ func (d *Daemon) reregisterWorkspaceAfterRuntimeGone(ctx context.Context, workspif len(resp.Settings) > 0 {ws.settings = resp.Settings}- d.mu.Unlock()+ // Refresh the cached profile signature only when the fetch succeeded;+ // an empty sig means the GetRuntimeProfiles call failed and we must+ // preserve the previous signature so the next sync tick can still+ // detect a real drift instead of falsely thinking everything is in sync.+ if profileSig != "" {+ ws.profileSetSig = profileSig+ }+ return newIDs, droppedIDs, true+}++func (d *Daemon) reregisterWorkspaceAfterRuntimeGone(ctx context.Context, workspaceID string) error {+ resp, profileSig, err := d.registerRuntimesForWorkspace(ctx, workspaceID)+ if err != nil {+ return fmt.Errorf("register runtimes: %w", err)+ }++ newIDs, _, ok := d.applyRegisterResponseInPlace(workspaceID, resp, profileSig)+ if !ok {+ return fmt.Errorf("workspace %s no longer tracked", workspaceID)+ }for _, rid := range newIDs {d.logger.Info("re-registered runtime after server-side deletion",@@ -527,6 +590,13 @@ func (d *Daemon) reregisterWorkspaceAfterRuntimeGone(ctx context.Context, worksp// Tell the server about any tasks the previous (now-deleted) runtime// was working on, mirroring the registration path's recover-orphans call.+ // This is intentionally scoped to the runtime_gone recovery: the+ // runtimes were truly gone server-side, so anything still in+ // dispatched/running/waiting_local_directory on those rows is an orphan+ // that needs to be failed-and-retried. The drift-refresh path (which+ // also feeds applyRegisterResponseInPlace) deliberately skips this step+ // because its surviving runtime IDs may still be actively executing+ // tasks for the user (MUL-3332).for _, rid := range newIDs {if err := d.client.RecoverOrphans(ctx, rid); err != nil {d.logger.Warn("recover-orphans after re-register failed",@@ -817,7 +887,7 @@ func (d *Daemon) customCommandPathForRuntime(runtimeID string) (string, bool) {return path, true}-func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID string) (*RegisterResponse, error) {+func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID string) (*RegisterResponse, string, error) {d.logger.Debug("registering runtimes for workspace", "workspace_id", workspaceID, "agent_count", len(d.cfg.Agents))var runtimes []map[string]stringfor name, entry := range d.cfg.Agents {@@ -849,10 +919,21 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s// server returning 404) must never fail registration — the daemon simply// continues with the built-in runtimes it already collected. A profile// whose command_name is not on PATH is skipped (the host doesn't have it).- d.appendProfileRuntimes(ctx, workspaceID, &runtimes)+ //+ // profileSig is a content hash of the workspace's profile list captured+ // here so the workspaceSyncLoop can detect server-side profile changes+ // between sync ticks without making an extra round trip on every tick+ // (MUL-3332). An empty string means the fetch failed and the caller must+ // keep whatever signature was previously cached on the workspaceState.+ profileSig := d.appendProfileRuntimes(ctx, workspaceID, &runtimes)if len(runtimes) == 0 {- return nil, fmt.Errorf("no agent runtimes could be registered")+ // profileSig is still meaningful even when nothing resolves: the+ // drift-refresh path uses it to remember "we already converged on the+ // disabled-everywhere state" so the next sync tick is a no-op instead+ // of a re-empty-register loop. Initial-registration callers that don't+ // care about the sig discard it via _.+ return nil, profileSig, ErrNoRuntimesToRegister}req := map[string]any{@@ -867,13 +948,13 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID sresp, err := d.client.Register(ctx, req)if err != nil {- return nil, fmt.Errorf("register runtimes: %w", err)+ return nil, "", fmt.Errorf("register runtimes: %w", err)}if len(resp.Runtimes) == 0 {- return nil, fmt.Errorf("register runtimes: empty response")+ return nil, "", fmt.Errorf("register runtimes: empty response")}d.logger.Debug("register response", "workspace_id", workspaceID, "runtimes", len(resp.Runtimes), "repos", len(resp.Repos), "repos_version", resp.ReposVersion)- return resp, nil+ return resp, profileSig, nil}// appendProfileRuntimes fetches the workspace's enabled custom runtime@@ -892,17 +973,28 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s// (suffixed with the device name like the built-in path), type =// protocol_family (the routing provider), version = best-effort detected// version, status = "online", plus the profile_id the server validates.-func (d *Daemon) appendProfileRuntimes(ctx context.Context, workspaceID string, runtimes *[]map[string]string) {+//+// Returns a content signature of the fetched profile list (MUL-3332). The+// signature is used by the workspace sync loop to detect server-side profile+// changes between sync ticks and trigger a re-register without a daemon+// restart. Returns the empty string when the fetch failed — callers must+// treat that as "unknown, do not overwrite a previously-stored signature"+// (otherwise a transient 5xx would silently flip the daemon into thinking the+// workspace has zero profiles).+func (d *Daemon) appendProfileRuntimes(ctx context.Context, workspaceID string, runtimes *[]map[string]string) string {resp, err := d.client.GetRuntimeProfiles(ctx, workspaceID)if err != nil {// Best-effort: never fail registration because profiles couldn't be// fetched. An older server with no profiles route returns 404.d.logger.Info("skip custom runtime profiles: fetch failed (continuing with built-in runtimes)","workspace_id", workspaceID, "error", err)- return+ return ""}if resp == nil {- return+ // Empty payload — same shape as "server has zero profiles". Return+ // the digest of an empty list so the sync loop can still detect a+ // later transition (zero → first profile added).+ return profileSetSignature(nil)}for _, profile := range resp.RuntimeProfiles {if profile.CommandName == "" || profile.ProtocolFamily == "" {@@ -972,6 +1064,46 @@ func (d *Daemon) appendProfileRuntimes(ctx context.Context, workspaceID string,"profile_id": profile.ID,})}+ return profileSetSignature(resp.RuntimeProfiles)+}++// profileSetSignature is a stable content hash of the workspace's custom+// runtime profile list (MUL-3332). The workspaceSyncLoop diffs this against+// the cached value on each tick: a mismatch means the user added, edited, or+// disabled a profile via the web UI / CLI between syncs and the daemon must+// re-register so the new runtime instance shows up in the list without a+// restart.+//+// The hashed projection covers exactly the fields that affect what the+// daemon sends in a Register call: ID, Enabled, ProtocolFamily, CommandName,+// FixedArgs (the launch args every agent on this runtime inherits) and+// Visibility (so a hypothetical future per-creator filter still triggers+// drift). Profiles are sorted by ID first so the digest is order-independent+// (the server is allowed to return them in any order).+func profileSetSignature(profiles []RuntimeProfile) string {+ if len(profiles) == 0 {+ return "0"+ }+ sorted := append([]RuntimeProfile(nil), profiles...)+ sort.Slice(sorted, func(i, j int) bool { return sorted[i].ID < sorted[j].ID })+ h := fnv.New64a()+ // Field separator chosen to never appear in a UUID, slug, or arg.+ const sep = "\x1f"+ for _, p := range sorted {+ fmt.Fprintf(h, "%s%s%t%s%s%s%s%s%s%s",+ p.ID, sep,+ p.Enabled, sep,+ p.ProtocolFamily, sep,+ p.CommandName, sep,+ p.Visibility, sep,+ )+ for _, a := range p.FixedArgs {+ fmt.Fprintf(h, "%s%s", a, sep)+ }+ // Record list end so [a,b] and [ab] hash differently.+ h.Write([]byte("\x1e"))+ }+ return strconv.FormatUint(h.Sum64(), 16)}func newWorkspaceState(workspaceID string, runtimeIDs []string, reposVersion string, repos []RepoData, settings json.RawMessage) *workspaceState {@@ -1172,6 +1304,161 @@ func (d *Daemon) refreshWorkspaceRepos(ctx context.Context, workspaceID string)return resp, nil}+// refreshWorkspaceRuntimeProfiles fetches the workspace's enabled custom+// runtime profile list (MUL-3332), compares its content signature against+// the value cached on the workspaceState, and triggers a re-register when+// the signature has drifted. This is the entry point that lets profiles+// added / edited / disabled via the web UI or CLI become visible in the+// runtime list within one workspaceSyncLoop tick instead of requiring a+// daemon restart.+//+// Best-effort: a fetch error (older server, network blip) is logged and+// swallowed — the cached signature is preserved so the next tick can still+// detect a real drift. A successfully-fetched-but-unchanged signature is the+// expected steady state and short-circuits without any further work.+//+// On drift the function takes a path that deliberately differs from+// reregisterWorkspaceAfterRuntimeGone in two ways:+//+// 1. It does NOT call RecoverOrphans for the returned runtime IDs. The+// server's RecoverOrphanedTasksForRuntime hard-fails every+// dispatched/running/waiting_local_directory task on a runtime, which is+// the correct response when a runtime row was actually deleted server-+// side, but a catastrophic false positive on profile drift: a built-in+// runtime still actively executing tasks would have its work killed+// just because the user added a sibling custom profile.+//+// 2. It tolerates ErrNoRuntimesToRegister (custom-only daemon disables its+// only profile) by Deregistering the now-stale local runtime IDs and+// clearing local tracking. Without this, registerRuntimesForWorkspace+// would short-circuit on the empty list, the daemon would keep polling+// and heartbeating runtimes that should be offline, and the server+// would leave them online for the full 150 s stale-heartbeat window.+//+// The workspaceState pointer is never replaced (matches the invariant+// documented on syncWorkspacesFromAPI and reregisterWorkspaceAfterRuntimeGone).+func (d *Daemon) refreshWorkspaceRuntimeProfiles(ctx context.Context, workspaceID string) error {+ refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()++ resp, err := d.client.GetRuntimeProfiles(refreshCtx, workspaceID)+ if err != nil {+ // Older server (no profiles route) returns 404; the daemon should not+ // log a noisy warning on every sync tick in that case.+ return err+ }+ var profiles []RuntimeProfile+ if resp != nil {+ profiles = resp.RuntimeProfiles+ }+ live := profileSetSignature(profiles)++ d.mu.Lock()+ ws, ok := d.workspaces[workspaceID]+ if !ok {+ d.mu.Unlock()+ // Workspace was removed between sync ticks — nothing to do.+ return nil+ }+ cached := ws.profileSetSig+ d.mu.Unlock()++ if cached == live {+ return nil+ }++ d.logger.Info("custom runtime profile set changed; refreshing workspace runtimes",+ "workspace_id", workspaceID, "previous_sig", cached, "current_sig", live,+ "profile_count", len(profiles))++ regResp, profileSig, err := d.registerRuntimesForWorkspace(ctx, workspaceID)+ if err != nil {+ if errors.Is(err, ErrNoRuntimesToRegister) {+ // Convergence-to-zero: a custom-only daemon's only enabled+ // profile was just disabled / deleted, and there are no built-in+ // agents to fall back on. Drop the daemon's local tracking and+ // proactively Deregister the orphaned server-side rows so the+ // runtime list converges to empty without waiting on the 150 s+ // stale-heartbeat sweep.+ return d.convergeWorkspaceRuntimesToZero(ctx, workspaceID, profileSig)+ }+ return err+ }++ newIDs, droppedIDs, ok := d.applyRegisterResponseInPlace(workspaceID, regResp, profileSig)+ if !ok {+ return fmt.Errorf("workspace %s no longer tracked", workspaceID)+ }++ for _, rid := range newIDs {+ d.logger.Info("re-registered runtime after profile drift",+ "workspace_id", workspaceID, "runtime_id", rid)+ }+ d.notifyRuntimeSetChanged()++ // Drift may have shrunk the runtime set (a profile got disabled while+ // other runtimes survive). Eagerly mark those server-side rows offline+ // so the runtime list reflects reality immediately; a 5xx blip here is+ // fine because the server's stale-heartbeat sweep will pick them up+ // within ~150 s as a backstop.+ if len(droppedIDs) > 0 {+ if err := d.client.Deregister(ctx, droppedIDs); err != nil {+ d.logger.Warn("deregister of dropped runtimes after profile drift failed",+ "workspace_id", workspaceID, "runtime_ids", droppedIDs, "error", err)+ }+ }++ // Intentionally NO RecoverOrphans here: see method doc.+ return nil+}++// convergeWorkspaceRuntimesToZero handles the drift-refresh case where+// registerRuntimesForWorkspace would have short-circuited because the daemon+// has nothing to host on this workspace anymore. It Deregisters the+// previously-tracked runtime IDs (best-effort) and clears the daemon's local+// tracking so taskWakeup / heartbeat / poll loops stop attempting work+// against runtimes that should now be offline.+//+// The workspaceState pointer is preserved: the workspace itself is still a+// valid workspace the user belongs to, just one with no agents on this+// daemon for the moment. If the user re-enables a profile or installs a+// built-in agent, the next sync tick's profile-drift detection (or a daemon+// restart) will register it again.+func (d *Daemon) convergeWorkspaceRuntimesToZero(ctx context.Context, workspaceID, profileSig string) error {+ d.mu.Lock()+ ws, ok := d.workspaces[workspaceID]+ if !ok {+ d.mu.Unlock()+ return nil+ }+ oldRuntimeIDs := append([]string(nil), ws.runtimeIDs...)+ for _, rid := range oldRuntimeIDs {+ delete(d.runtimeIndex, rid)+ }+ ws.runtimeIDs = nil+ if profileSig != "" {+ // Cache the converged-empty signature so we don't loop into+ // re-converging on every subsequent sync tick.+ ws.profileSetSig = profileSig+ }+ d.mu.Unlock()++ d.logger.Info("custom runtime profile drift converged to zero; clearing local tracking",+ "workspace_id", workspaceID, "deregistered_runtime_ids", oldRuntimeIDs)++ if len(oldRuntimeIDs) > 0 {+ if err := d.client.Deregister(ctx, oldRuntimeIDs); err != nil {+ // Best-effort: the server's stale-heartbeat sweep marks the rows+ // offline within ~150 s as a backstop, and on the daemon side+ // we have already stopped heartbeating them.+ d.logger.Warn("deregister after zero-runtime convergence failed",+ "workspace_id", workspaceID, "runtime_ids", oldRuntimeIDs, "error", err)+ }+ }+ d.notifyRuntimeSetChanged()+ return nil+}+func (d *Daemon) ensureRepoReady(ctx context.Context, workspaceID, repoURL string) error {if d.repoCache == nil {return fmt.Errorf("repo cache not initialized")@@ -1376,6 +1663,18 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context) error {if _, err := d.refreshWorkspaceRepos(ctx, id); err != nil {d.logger.Debug("workspace sync: refresh settings failed", "workspace_id", id, "error", err)}+ // Pick up custom runtime profiles created/edited/disabled via+ // the web UI or CLI between sync ticks (MUL-3332). Without this,+ // a profile added on the server would only become a runtime row+ // after a daemon restart or a runtime_gone recovery, because the+ // already-tracked branch never re-runs registerRuntimesForWorkspace+ // otherwise. refreshWorkspaceRuntimeProfiles is best-effort and+ // only re-registers when it observes a real signature drift, so+ // quiet workspaces incur exactly one cheap GetRuntimeProfiles+ // round trip per sync tick.+ if err := d.refreshWorkspaceRuntimeProfiles(ctx, id); err != nil {+ d.logger.Debug("workspace sync: profile refresh failed", "workspace_id", id, "error", err)+ }// Only intervene further if the workspace lost all of its// runtimes (most commonly because handleRuntimeGone pruned them// and its inline re-register failed). The pointer is not replaced@@ -1392,7 +1691,7 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context) error {registered++continue}- resp, err := d.registerRuntimesForWorkspace(ctx, id)+ resp, profileSig, err := d.registerRuntimesForWorkspace(ctx, id)if err != nil {d.logger.Error("failed to register runtimes", "workspace_id", id, "name", name, "error", err)continue@@ -1403,7 +1702,14 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context) error {d.logger.Info("registered runtime", "workspace_id", id, "runtime_id", rt.ID, "provider", rt.Provider)}d.mu.Lock()- d.workspaces[id] = newWorkspaceState(id, runtimeIDs, resp.ReposVersion, resp.Repos, resp.Settings)+ ws := newWorkspaceState(id, runtimeIDs, resp.ReposVersion, resp.Repos, resp.Settings)+ // Seed the profile signature so the next sync tick can detect drift+ // without re-registering on a transient fetch failure (empty sig is+ // the explicit "unknown — keep the previous value" sentinel from+ // appendProfileRuntimes; on first registration there is no previous+ // value, so empty stays empty).+ ws.profileSetSig = profileSig+ d.workspaces[id] = wsfor _, rt := range resp.Runtimes {d.runtimeIndex[rt.ID] = rt}diff --git a/server/internal/daemon/runtime_profile_drift_test.go b/server/internal/daemon/runtime_profile_drift_test.gonew file mode 100644index 0000000000..cf7a672978--- /dev/null+++ b/server/internal/daemon/runtime_profile_drift_test.go@@ -0,0 +1,614 @@+package daemon++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strconv"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+)++// TestProfileSetSignature_StableUnderReorder ensures the digest only+// captures the *content* of the profile set, not the order the server+// happened to return profiles in. Without this property the+// workspaceSyncLoop would re-register on every tick whenever the server+// shuffled rows (which the API contract does not forbid).+func TestProfileSetSignature_StableUnderReorder(t *testing.T) {+ a := []RuntimeProfile{+ {ID: "p-a", ProtocolFamily: "codex", CommandName: "a", Enabled: true},+ {ID: "p-b", ProtocolFamily: "claude", CommandName: "b", Enabled: true},+ }+ b := []RuntimeProfile{+ {ID: "p-b", ProtocolFamily: "claude", CommandName: "b", Enabled: true},+ {ID: "p-a", ProtocolFamily: "codex", CommandName: "a", Enabled: true},+ }+ if profileSetSignature(a) != profileSetSignature(b) {+ t.Errorf("digest must be order-independent")+ }+}++// TestProfileSetSignature_DetectsRegistrationAffectingChanges asserts the+// digest covers exactly the fields the daemon sends in a Register call.+// Coverage gaps here would mean a real server-side change goes undetected+// and the user has to restart the daemon — the bug MUL-3332 is about.+func TestProfileSetSignature_DetectsRegistrationAffectingChanges(t *testing.T) {+ base := []RuntimeProfile{{+ ID: "p1",+ ProtocolFamily: "codex",+ CommandName: "company-codex",+ FixedArgs: []string{"--foo"},+ Visibility: "workspace",+ Enabled: true,+ }}+ baseSig := profileSetSignature(base)++ // Empty list must hash differently from a one-profile list.+ if profileSetSignature(nil) == baseSig {+ t.Errorf("empty list must hash differently from a populated list")+ }++ cases := []struct {+ name string+ mutate func([]RuntimeProfile) []RuntimeProfile+ }{+ {"add new profile", func(in []RuntimeProfile) []RuntimeProfile {+ return append(in, RuntimeProfile{ID: "p2", ProtocolFamily: "claude", CommandName: "c", Enabled: true})+ }},+ {"flip enabled", func(in []RuntimeProfile) []RuntimeProfile {+ out := append([]RuntimeProfile(nil), in...)+ out[0].Enabled = !out[0].Enabled+ return out+ }},+ {"change command_name", func(in []RuntimeProfile) []RuntimeProfile {+ out := append([]RuntimeProfile(nil), in...)+ out[0].CommandName = "different-bin"+ return out+ }},+ {"change protocol_family", func(in []RuntimeProfile) []RuntimeProfile {+ out := append([]RuntimeProfile(nil), in...)+ out[0].ProtocolFamily = "claude"+ return out+ }},+ {"change fixed_args", func(in []RuntimeProfile) []RuntimeProfile {+ out := append([]RuntimeProfile(nil), in...)+ out[0].FixedArgs = []string{"--foo", "--bar"}+ return out+ }},+ {"change visibility", func(in []RuntimeProfile) []RuntimeProfile {+ out := append([]RuntimeProfile(nil), in...)+ out[0].Visibility = "private"+ return out+ }},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := profileSetSignature(tc.mutate(base))+ if got == baseSig {+ t.Errorf("digest must change when %s; baseSig=%s mutatedSig=%s",+ tc.name, baseSig, got)+ }+ })+ }+}++// driftFixture wires a Daemon against a fake server whose runtime-profiles+// response can be swapped at runtime. It also tracks how many times the+// server saw a /api/daemon/register, /api/daemon/runtimes/:id/recover-orphans,+// and /api/daemon/deregister call so tests can assert exactly which side+// effects the drift refresh triggered (or didn't).+type driftFixture struct {+ daemon *Daemon+ server *httptest.Server+ registerCalls atomic.Int32+ recoverOrphansCalls []string // runtime IDs the server received recover-orphans for, in order+ recoverOrphansMu sync.Mutex+ deregisterCalls [][]string // each entry is one Deregister call's runtime_ids payload, in order+ deregisterMu sync.Mutex+ currentProfiles []RuntimeProfile+}++// setProfiles swaps the profile set returned by the fake server. The+// next GetRuntimeProfiles call observes the new value. Tests in this file+// drive the fixture from a single goroutine, so the field is unguarded;+// add a mutex if a future test publishes profile updates concurrently with+// daemon background work.+func (fx *driftFixture) setProfiles(profiles []RuntimeProfile) {+ fx.currentProfiles = profiles+}++// recordedRecoverOrphans returns a copy of the runtime IDs the fake server+// received /recover-orphans calls for since the fixture was created.+func (fx *driftFixture) recordedRecoverOrphans() []string {+ fx.recoverOrphansMu.Lock()+ defer fx.recoverOrphansMu.Unlock()+ out := make([]string, len(fx.recoverOrphansCalls))+ copy(out, fx.recoverOrphansCalls)+ return out+}++// recordedDeregisters returns a copy of every Deregister call's runtime_ids+// payload, in the order the fake server received them.+func (fx *driftFixture) recordedDeregisters() [][]string {+ fx.deregisterMu.Lock()+ defer fx.deregisterMu.Unlock()+ out := make([][]string, len(fx.deregisterCalls))+ for i, ids := range fx.deregisterCalls {+ cp := make([]string, len(ids))+ copy(cp, ids)+ out[i] = cp+ }+ return out+}++func newDriftFixture(t *testing.T, initial []RuntimeProfile) *driftFixture {+ t.Helper()+ fx := &driftFixture{currentProfiles: initial}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.URL.Path == "/api/daemon/register":+ fx.registerCalls.Add(1)+ var body struct {+ Runtimes []map[string]any `json:"runtimes"`+ }+ _ = json.NewDecoder(r.Body).Decode(&body)+ var resp RegisterResponse+ for i, rt := range body.Runtimes {+ id := "rt-" + strconv.Itoa(i)+ profileID, _ := rt["profile_id"].(string)+ typ, _ := rt["type"].(string)+ resp.Runtimes = append(resp.Runtimes, Runtime{+ ID: id, Name: "n", Provider: typ, Status: "online", ProfileID: profileID,+ })+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(resp)+ case strings.HasPrefix(r.URL.Path, "/api/daemon/runtimes/") && strings.HasSuffix(r.URL.Path, "/recover-orphans"):+ // /api/daemon/runtimes/<id>/recover-orphans+ parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/daemon/runtimes/"), "/")+ runtimeID := parts[0]+ fx.recoverOrphansMu.Lock()+ fx.recoverOrphansCalls = append(fx.recoverOrphansCalls, runtimeID)+ fx.recoverOrphansMu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"orphaned":0,"retried":0}`))+ case r.URL.Path == "/api/daemon/deregister":+ var body struct {+ RuntimeIDs []string `json:"runtime_ids"`+ }+ _ = json.NewDecoder(r.Body).Decode(&body)+ fx.deregisterMu.Lock()+ ids := make([]string, len(body.RuntimeIDs))+ copy(ids, body.RuntimeIDs)+ fx.deregisterCalls = append(fx.deregisterCalls, ids)+ fx.deregisterMu.Unlock()+ w.WriteHeader(http.StatusOK)+ case strings.HasSuffix(r.URL.Path, "/runtime-profiles"):+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(RuntimeProfilesResponse{+ WorkspaceID: "ws-1",+ RuntimeProfiles: fx.currentProfiles,+ })+ default:+ w.WriteHeader(http.StatusOK)+ }+ }))+ t.Cleanup(srv.Close)+ d := freshDaemon(srv.URL)+ d.profileCommandPaths = make(map[string]string)+ fx.daemon = d+ fx.server = srv+ return fx+}++// TestRefreshWorkspaceRuntimeProfiles_NoDrift_DoesNotReregister verifies the+// hot-path: when the server's profile set has not changed since the daemon+// last registered the workspace, the sync tick must NOT fire a re-register.+// Without this guarantee every quiet sync tick would cost an extra Register+// HTTP call per workspace.+func TestRefreshWorkspaceRuntimeProfiles_NoDrift_DoesNotReregister(t *testing.T) {+ t.Cleanup(stubAgentVersion(t))+ stubLookPath(t, map[string]string{"company-codex": "/opt/bin/company-codex"})+ profiles := []RuntimeProfile{{+ ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Company Codex",+ ProtocolFamily: "codex", CommandName: "company-codex",+ Visibility: "workspace", Enabled: true,+ }}+ fx := newDriftFixture(t, profiles)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{}++ // Initial register seeds workspaceState (and ws.profileSetSig).+ resp, profileSig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")+ if err != nil {+ t.Fatalf("initial register: %v", err)+ }+ d.workspaces["ws-1"] = newWorkspaceState("ws-1", []string{resp.Runtimes[0].ID}, "", nil, nil)+ d.workspaces["ws-1"].profileSetSig = profileSig+ for _, rt := range resp.Runtimes {+ d.runtimeIndex[rt.ID] = rt+ }+ if fx.registerCalls.Load() != 1 {+ t.Fatalf("setup expected 1 register call, got %d", fx.registerCalls.Load())+ }++ // Server returns the same profile set: refresh must not re-register.+ if err := d.refreshWorkspaceRuntimeProfiles(context.Background(), "ws-1"); err != nil {+ t.Fatalf("refreshWorkspaceRuntimeProfiles: %v", err)+ }+ if fx.registerCalls.Load() != 1 {+ t.Errorf("no-drift refresh must not re-register; got %d total register calls", fx.registerCalls.Load())+ }+}++// TestRefreshWorkspaceRuntimeProfiles_NewProfileTriggersReregister verifies+// the user-visible fix for MUL-3332: a profile created via the web UI on an+// already-tracked workspace becomes a registered runtime within one+// workspaceSyncLoop tick — no daemon restart required.+func TestRefreshWorkspaceRuntimeProfiles_NewProfileTriggersReregister(t *testing.T) {+ t.Cleanup(stubAgentVersion(t))+ stubLookPath(t, map[string]string{+ "company-codex": "/opt/bin/company-codex",+ "team-claude": "/opt/bin/team-claude",+ })+ initial := []RuntimeProfile{{+ ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Company Codex",+ ProtocolFamily: "codex", CommandName: "company-codex",+ Visibility: "workspace", Enabled: true,+ }}+ fx := newDriftFixture(t, initial)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{}++ // Initial register with one profile.+ resp, profileSig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")+ if err != nil {+ t.Fatalf("initial register: %v", err)+ }+ ids := make([]string, 0, len(resp.Runtimes))+ for _, rt := range resp.Runtimes {+ ids = append(ids, rt.ID)+ d.runtimeIndex[rt.ID] = rt+ }+ d.workspaces["ws-1"] = newWorkspaceState("ws-1", ids, "", nil, nil)+ d.workspaces["ws-1"].profileSetSig = profileSig+ beforeRegisterCalls := fx.registerCalls.Load()++ // User adds a second profile via the web UI: server's response now+ // includes prof-2.+ fx.setProfiles([]RuntimeProfile{+ {ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Company Codex",+ ProtocolFamily: "codex", CommandName: "company-codex",+ Visibility: "workspace", Enabled: true},+ {ID: "prof-2", WorkspaceID: "ws-1", DisplayName: "Team Claude",+ ProtocolFamily: "claude", CommandName: "team-claude",+ Visibility: "workspace", Enabled: true},+ })++ if err := d.refreshWorkspaceRuntimeProfiles(context.Background(), "ws-1"); err != nil {+ t.Fatalf("refreshWorkspaceRuntimeProfiles: %v", err)+ }++ // Drift must fire a new register call.+ if got := fx.registerCalls.Load(); got != beforeRegisterCalls+1 {+ t.Errorf("new profile must trigger one re-register; before=%d after=%d", beforeRegisterCalls, got)+ }++ // The daemon's runtimeIndex must now hold a runtime for the new profile.+ d.mu.Lock()+ var seenProf2 bool+ for _, rt := range d.runtimeIndex {+ if rt.ProfileID == "prof-2" {+ seenProf2 = true+ break+ }+ }+ d.mu.Unlock()+ if !seenProf2 {+ t.Errorf("expected runtimeIndex to contain a runtime for prof-2 after refresh")+ }++ // And the cached signature must now match the new profile set, so a+ // follow-up refresh with no further changes is a no-op.+ stableCalls := fx.registerCalls.Load()+ if err := d.refreshWorkspaceRuntimeProfiles(context.Background(), "ws-1"); err != nil {+ t.Fatalf("second refresh: %v", err)+ }+ if got := fx.registerCalls.Load(); got != stableCalls {+ t.Errorf("steady-state refresh must not re-register; before=%d after=%d", stableCalls, got)+ }++ // MUL-3332 review (concern 1): the drift path MUST NOT call recover-+ // orphans on any returned runtime. Recover-orphans hard-fails every+ // dispatched/running task on a runtime, so calling it for a built-in+ // runtime that the user had been actively running tasks on would kill+ // real work just because they added an unrelated sibling profile. The+ // runtime_gone recovery path keeps recover-orphans because those rows+ // were truly deleted server-side; drift surfaces existing runtimes.+ if got := fx.recordedRecoverOrphans(); len(got) != 0 {+ t.Errorf("drift path must not trigger recover-orphans for any runtime; got %v", got)+ }+}++// TestRefreshWorkspaceRuntimeProfiles_DriftWithRunningRuntimeSkipsOrphanRecovery+// is the targeted regression for MUL-3332 review concern #1: a daemon that+// is actively executing tasks on its existing runtime (built-in or+// previously-registered profile) must NOT have those tasks killed when+// the user adds a *new* sibling profile. Adding a profile must surface as+// a re-register that includes the new profile while LEAVING the existing+// runtime IDs untouched and recover-orphans untriggered.+func TestRefreshWorkspaceRuntimeProfiles_DriftWithRunningRuntimeSkipsOrphanRecovery(t *testing.T) {+ t.Cleanup(stubAgentVersion(t))+ stubLookPath(t, map[string]string{+ "company-codex": "/opt/bin/company-codex",+ "team-claude": "/opt/bin/team-claude",+ })+ // Mixed setup: one built-in runtime (claude) plus one custom profile,+ // the closest analogue of "a daemon that is running real work and the+ // user just added another profile". Profile drift fires next.+ initial := []RuntimeProfile{{+ ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Company Codex",+ ProtocolFamily: "codex", CommandName: "company-codex",+ Visibility: "workspace", Enabled: true,+ }}+ fx := newDriftFixture(t, initial)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{"claude": {Path: "/usr/bin/true"}}++ resp, profileSig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")+ if err != nil {+ t.Fatalf("initial register: %v", err)+ }+ ids := make([]string, 0, len(resp.Runtimes))+ for _, rt := range resp.Runtimes {+ ids = append(ids, rt.ID)+ d.runtimeIndex[rt.ID] = rt+ }+ d.workspaces["ws-1"] = newWorkspaceState("ws-1", ids, "", nil, nil)+ d.workspaces["ws-1"].profileSetSig = profileSig+ if len(ids) < 2 {+ t.Fatalf("setup expected at least 2 runtimes (built-in + custom); got %d", len(ids))+ }++ // User adds a second profile.+ fx.setProfiles([]RuntimeProfile{+ {ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Company Codex",+ ProtocolFamily: "codex", CommandName: "company-codex",+ Visibility: "workspace", Enabled: true},+ {ID: "prof-2", WorkspaceID: "ws-1", DisplayName: "Team Claude",+ ProtocolFamily: "claude", CommandName: "team-claude",+ Visibility: "workspace", Enabled: true},+ })++ if err := d.refreshWorkspaceRuntimeProfiles(context.Background(), "ws-1"); err != nil {+ t.Fatalf("refreshWorkspaceRuntimeProfiles: %v", err)+ }++ // Hard regression: zero recover-orphans calls for ANY runtime ID.+ // The whole point of MUL-3332 review concern #1 is that adding a+ // profile must not nuke in-flight work on existing runtimes.+ if got := fx.recordedRecoverOrphans(); len(got) != 0 {+ t.Errorf("drift refresh leaked recover-orphans calls (would fail running tasks on existing runtimes): %v", got)+ }+}++// TestRefreshWorkspaceRuntimeProfiles_DisableConvergesCustomOnlyDaemon is the+// targeted regression for MUL-3332 review concern #2: when a custom-only+// daemon (no built-in agents) has its only enabled profile disabled, the+// daemon must converge to a zero-runtime state — clear local tracking AND+// tell the server to mark the orphaned runtime row offline immediately,+// rather than leaving the daemon polling/heartbeating a runtime the user+// can no longer use.+func TestRefreshWorkspaceRuntimeProfiles_DisableConvergesCustomOnlyDaemon(t *testing.T) {+ t.Cleanup(stubAgentVersion(t))+ stubLookPath(t, map[string]string{"company-codex": "/opt/bin/company-codex"})+ initial := []RuntimeProfile{{+ ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Company Codex",+ ProtocolFamily: "codex", CommandName: "company-codex",+ Visibility: "workspace", Enabled: true,+ }}+ fx := newDriftFixture(t, initial)+ d := fx.daemon+ // Custom-only daemon: no built-in agents at all.+ d.cfg.Agents = map[string]AgentEntry{}++ // Initial register: one custom runtime.+ resp, profileSig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")+ if err != nil {+ t.Fatalf("initial register: %v", err)+ }+ if len(resp.Runtimes) != 1 {+ t.Fatalf("setup expected exactly one runtime; got %d", len(resp.Runtimes))+ }+ initialRuntimeID := resp.Runtimes[0].ID+ d.runtimeIndex[initialRuntimeID] = resp.Runtimes[0]+ d.workspaces["ws-1"] = newWorkspaceState("ws-1", []string{initialRuntimeID}, "", nil, nil)+ d.workspaces["ws-1"].profileSetSig = profileSig++ // User disables the only profile: server's daemon-facing list now+ // returns zero enabled profiles.+ fx.setProfiles(nil)++ if err := d.refreshWorkspaceRuntimeProfiles(context.Background(), "ws-1"); err != nil {+ t.Fatalf("refreshWorkspaceRuntimeProfiles: %v", err)+ }++ // Local tracking must be empty: the daemon stops polling/heartbeating+ // runtimes that no longer represent anything the user can run.+ d.mu.Lock()+ gotRuntimeIDs := append([]string(nil), d.workspaces["ws-1"].runtimeIDs...)+ _, stillIndexed := d.runtimeIndex[initialRuntimeID]+ gotSig := d.workspaces["ws-1"].profileSetSig+ d.mu.Unlock()+ if len(gotRuntimeIDs) != 0 {+ t.Errorf("workspaceState.runtimeIDs must be empty after convergence-to-zero; got %v", gotRuntimeIDs)+ }+ if stillIndexed {+ t.Errorf("runtimeIndex must drop the previously-tracked runtime %q after convergence-to-zero", initialRuntimeID)+ }+ if gotSig != profileSetSignature(nil) {+ t.Errorf("converged signature must match the empty-profile-list digest so the next sync tick is a no-op; got %q want %q", gotSig, profileSetSignature(nil))+ }++ // Server-side cleanup: the daemon must Deregister the orphaned runtime+ // ID so the runtime row goes offline immediately instead of waiting+ // 150 s for the stale-heartbeat sweep.+ deregs := fx.recordedDeregisters()+ if len(deregs) == 0 {+ t.Fatalf("expected one Deregister call for the orphaned runtime ID; got none")+ }+ var sawInitial bool+ for _, ids := range deregs {+ for _, id := range ids {+ if id == initialRuntimeID {+ sawInitial = true+ }+ }+ }+ if !sawInitial {+ t.Errorf("Deregister payload must include the initial runtime ID %q; got %v", initialRuntimeID, deregs)+ }++ // Convergence-to-zero must NOT call recover-orphans either: the daemon+ // has nothing actively running for the user once they disabled the+ // profile, but if it had, killing those tasks for a profile DISABLE+ // (vs delete) would still be wrong — the user might re-enable.+ if got := fx.recordedRecoverOrphans(); len(got) != 0 {+ t.Errorf("convergence-to-zero must not trigger recover-orphans; got %v", got)+ }++ // Steady state: a follow-up refresh with the same (empty) profile set+ // is a no-op. No new register / deregister / recover-orphans calls.+ stableRegisters := fx.registerCalls.Load()+ stableDeregs := len(fx.recordedDeregisters())+ if err := d.refreshWorkspaceRuntimeProfiles(context.Background(), "ws-1"); err != nil {+ t.Fatalf("second refresh after convergence: %v", err)+ }+ if got := fx.registerCalls.Load(); got != stableRegisters {+ t.Errorf("converged steady state must not re-register; before=%d after=%d", stableRegisters, got)+ }+ if got := len(fx.recordedDeregisters()); got != stableDeregs {+ t.Errorf("converged steady state must not deregister again; before=%d after=%d", stableDeregs, got)+ }+}++// TestRefreshWorkspaceRuntimeProfiles_DisableOneOfManyDeregistersDroppedID+// covers the partial-drift case: a daemon hosting both a built-in runtime+// and a custom profile has its custom profile disabled. The built-in+// survives (Register call carries it forward), the daemon's runtime set+// converges to just the built-in, and the dropped custom runtime ID is+// Deregistered so the server marks it offline immediately.+func TestRefreshWorkspaceRuntimeProfiles_DisableOneOfManyDeregistersDroppedID(t *testing.T) {+ t.Cleanup(stubAgentVersion(t))+ stubLookPath(t, map[string]string{"company-codex": "/opt/bin/company-codex"})+ initial := []RuntimeProfile{{+ ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Company Codex",+ ProtocolFamily: "codex", CommandName: "company-codex",+ Visibility: "workspace", Enabled: true,+ }}+ fx := newDriftFixture(t, initial)+ d := fx.daemon+ // Mixed: one built-in + one custom.+ d.cfg.Agents = map[string]AgentEntry{"claude": {Path: "/usr/bin/true"}}++ resp, profileSig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")+ if err != nil {+ t.Fatalf("initial register: %v", err)+ }+ if len(resp.Runtimes) != 2 {+ t.Fatalf("setup expected 2 runtimes; got %d (%+v)", len(resp.Runtimes), resp.Runtimes)+ }+ var customID string+ for _, rt := range resp.Runtimes {+ d.runtimeIndex[rt.ID] = rt+ if rt.ProfileID == "prof-1" {+ customID = rt.ID+ }+ }+ if customID == "" {+ t.Fatalf("setup expected a runtime for prof-1; got %+v", resp.Runtimes)+ }+ initialIDs := []string{resp.Runtimes[0].ID, resp.Runtimes[1].ID}+ d.workspaces["ws-1"] = newWorkspaceState("ws-1", initialIDs, "", nil, nil)+ d.workspaces["ws-1"].profileSetSig = profileSig++ // User disables the custom profile.+ fx.setProfiles(nil)++ if err := d.refreshWorkspaceRuntimeProfiles(context.Background(), "ws-1"); err != nil {+ t.Fatalf("refreshWorkspaceRuntimeProfiles: %v", err)+ }++ // The custom runtime ID must be Deregistered.+ deregs := fx.recordedDeregisters()+ var sawCustom bool+ for _, ids := range deregs {+ for _, id := range ids {+ if id == customID {+ sawCustom = true+ }+ }+ }+ if !sawCustom {+ t.Errorf("Deregister payload must include the dropped custom runtime ID %q; got %v", customID, deregs)+ }++ // Surviving built-in must NOT be in any deregister payload.+ for _, ids := range deregs {+ for _, id := range ids {+ if id != customID {+ t.Errorf("Deregister leaked surviving runtime ID %q (only %q should be deregistered)", id, customID)+ }+ }+ }++ // And the still-surviving built-in must NOT have recover-orphans called+ // against it (concern #1 again, partial-drift flavour).+ if got := fx.recordedRecoverOrphans(); len(got) != 0 {+ t.Errorf("partial-drift refresh leaked recover-orphans calls: %v", got)+ }+}++// TestRefreshWorkspaceRuntimeProfiles_FetchErrorIsBestEffort verifies that+// a network blip or older server (404) does NOT clear the cached signature+// or trigger a spurious re-register. Without this, a transient 5xx during+// the workspace sync loop would loop the daemon into re-registering forever.+func TestRefreshWorkspaceRuntimeProfiles_FetchErrorIsBestEffort(t *testing.T) {+ t.Cleanup(stubAgentVersion(t))+ stubLookPath(t, map[string]string{"company-codex": "/opt/bin/company-codex"})+ profiles := []RuntimeProfile{{+ ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Company Codex",+ ProtocolFamily: "codex", CommandName: "company-codex",+ Visibility: "workspace", Enabled: true,+ }}+ // Server that returns 404 for the profiles route.+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if strings.HasSuffix(r.URL.Path, "/runtime-profiles") {+ w.WriteHeader(http.StatusNotFound)+ return+ }+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(srv.Close)+ d := freshDaemon(srv.URL)+ d.profileCommandPaths = make(map[string]string)+ knownSig := profileSetSignature(profiles)+ d.workspaces["ws-1"] = newWorkspaceState("ws-1", []string{"rt-1"}, "", nil, nil)+ d.workspaces["ws-1"].profileSetSig = knownSig++ err := d.refreshWorkspaceRuntimeProfiles(context.Background(), "ws-1")+ if err == nil {+ t.Fatalf("404 must surface as an error so the caller can log it at debug")+ }++ // Cached signature must be preserved (no overwrite on transient failures).+ d.mu.Lock()+ gotSig := d.workspaces["ws-1"].profileSetSig+ d.mu.Unlock()+ if gotSig != knownSig {+ t.Errorf("transient fetch error must not clobber cached sig; want %q got %q", knownSig, gotSig)+ }+}diff --git a/server/internal/daemon/runtime_profile_test.go b/server/internal/daemon/runtime_profile_test.goindex 82cc8de69c..aaf8ab191c 100644--- a/server/internal/daemon/runtime_profile_test.go+++ b/server/internal/daemon/runtime_profile_test.go@@ -3,6 +3,7 @@ package daemonimport ("context""encoding/json"+ "errors""net/http""net/http/httptest""strconv"@@ -168,7 +169,7 @@ func TestRegisterRuntimes_AppendsProfileRuntime(t *testing.T) {// Custom-only host: no built-in agents configured.d.cfg.Agents = map[string]AgentEntry{}- resp, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")+ resp, _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")if err != nil {t.Fatalf("registerRuntimesForWorkspace: %v", err)}@@ -201,7 +202,9 @@ func TestRegisterRuntimes_AppendsProfileRuntime(t *testing.T) {// TestRegisterRuntimes_SkipsProfileNotOnPath verifies a profile whose command// is missing on this host is skipped, and that a host with no built-in agents-// and no resolvable profiles fails registration (len==0 guard preserved).+// and no resolvable profiles fails registration with the documented sentinel+// (the drift-refresh path keys off ErrNoRuntimesToRegister to take the+// convergence-to-zero branch instead of treating it as a hard error).func TestRegisterRuntimes_SkipsProfileNotOnPath(t *testing.T) {t.Cleanup(stubAgentVersion(t))stubLookPath(t, map[string]string{}) // nothing resolves@@ -218,9 +221,12 @@ func TestRegisterRuntimes_SkipsProfileNotOnPath(t *testing.T) {d := fx.daemond.cfg.Agents = map[string]AgentEntry{}- _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")- if err == nil {- t.Fatalf("expected error when no runtimes resolve, got nil")+ _, sig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")+ if !errors.Is(err, ErrNoRuntimesToRegister) {+ t.Fatalf("expected ErrNoRuntimesToRegister, got %v", err)+ }+ if sig == "" {+ t.Errorf("profileSig must still be returned even when registration short-circuits, so the drift path can cache the converged-empty signature")}if _, ok := d.profileCommandPaths["prof-1"]; ok {t.Errorf("profileCommandPaths should not record an unresolved profile")@@ -238,7 +244,7 @@ func TestRegisterRuntimes_ProfilesFetchErrorIsBestEffort(t *testing.T) {// Built-in agent present so registration has something to register.d.cfg.Agents = map[string]AgentEntry{"claude": {Path: "/usr/bin/true"}}- resp, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")+ resp, _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")if err != nil {t.Fatalf("registration should succeed despite profiles 404: %v", err)}@@ -273,7 +279,7 @@ func TestRegisterRuntimes_PrefersCommandPathOverride(t *testing.T) {d.cfg.Agents = map[string]AgentEntry{}d.cfg.ProfileCommandOverrides = map[string]string{"prof-1": "/opt/custom/company-codex"}- if _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1"); err != nil {+ if _, _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1"); err != nil {t.Fatalf("registerRuntimesForWorkspace: %v", err)}@@ -307,7 +313,7 @@ func TestRegisterRuntimes_OverrideNotExecutableFallsBackToPath(t *testing.T) {d.cfg.Agents = map[string]AgentEntry{}d.cfg.ProfileCommandOverrides = map[string]string{"prof-1": "/opt/stale/company-codex"}- if _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1"); err != nil {+ if _, _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1"); err != nil {t.Fatalf("registerRuntimesForWorkspace: %v", err)}