Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7409 fix(runtime): stop steering stale-instance cleanup at the shared profile (#8483)

Bohan Jiangb425073caeb2
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.json
index 17de77117b..587293bfd8 100644
--- a/packages/views/locales/en/runtimes.json
+++ b/packages/views/locales/en/runtimes.json
@@ -399,7 +399,7 @@
"cancel": "Cancel",
"deleting": "Deleting…",
"toast_deleted": "Custom runtime deleted from workspace",
- "error_bound": "This runtime can't be deleted while agents are still using it.",
+ "error_bound": "This custom runtime can't be deleted while agents are still using it — including agents on other machines that registered it.",
"error_generic": "Failed to delete the runtime."
}
},
diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.json
index aae162c3f2..7ee94ca279 100644
--- a/packages/views/locales/ja/runtimes.json
+++ b/packages/views/locales/ja/runtimes.json
@@ -386,7 +386,7 @@
"cancel": "キャンセル",
"deleting": "削除中…",
"toast_deleted": "カスタムランタイムをワークスペースから削除しました",
- "error_bound": "まだエージェントが使用しているため、このランタイムは削除できません。",
+ "error_bound": "まだエージェントが使用しているため、このカスタムランタイムは削除できません。該当のエージェントは、このランタイムを登録した別のマシン上にいる場合があります。",
"error_generic": "ランタイムの削除に失敗しました。"
}
},
diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.json
index 41c1c28ec3..206e3f89dc 100644
--- a/packages/views/locales/ko/runtimes.json
+++ b/packages/views/locales/ko/runtimes.json
@@ -386,7 +386,7 @@
"cancel": "취소",
"deleting": "삭제 중…",
"toast_deleted": "사용자 지정 런타임이 워크스페이스에서 삭제되었습니다",
- "error_bound": "아직 에이전트가 사용 중이어서 이 런타임을 삭제할 수 없습니다.",
+ "error_bound": "아직 에이전트가 사용 중이어서 이 사용자 지정 런타임을 삭제할 수 없습니다. 해당 에이전트는 이 런타임을 등록한 다른 컴퓨터에 있을 수 있습니다.",
"error_generic": "런타임 삭제에 실패했습니다."
}
},
diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.json
index 8efb0c881d..823eae705c 100644
--- a/packages/views/locales/zh-Hans/runtimes.json
+++ b/packages/views/locales/zh-Hans/runtimes.json
@@ -386,7 +386,7 @@
"cancel": "取消",
"deleting": "正在删除...",
"toast_deleted": "已从工作区删除自定义运行时",
- "error_bound": "仍有智能体在使用此运行时,无法删除。",
+ "error_bound": "仍有智能体在使用此自定义运行时,无法删除;这些智能体可能位于注册了该运行时的其他机器上。",
"error_generic": "删除运行时失败。"
}
},
diff --git a/server/cmd/multica/cmd_runtime.go b/server/cmd/multica/cmd_runtime.go
index cd7a029d21..dd197b550e 100644
--- a/server/cmd/multica/cmd_runtime.go
+++ b/server/cmd/multica/cmd_runtime.go
@@ -232,6 +232,13 @@ func runRuntimeDelete(cmd *cobra.Command, args []string) error {
conflict, ok := runtimeDeleteConflict(err)
if !ok {
+ // Any other 409 is a deliberate, already-explained refusal — most often
+ // a profile-backed instance that cannot be deleted on its own. Show the
+ // server's guidance instead of a raw HTTP wrapper; --cascade cannot get
+ // past these, so there is nothing more for this command to try.
+ if _, msg, isConflict := serverConflictMessage(err); isConflict {
+ return errors.New(msg)
+ }
return fmt.Errorf("delete runtime: %w", err)
}
@@ -350,6 +357,38 @@ func runRuntimeUpdate(cmd *cobra.Command, args []string) error {
}
}
+// serverConflictMessage pulls the server's own sentence out of a 409 body.
+//
+// The refusals behind runtime and profile deletion are written to be read by
+// the person who ran the command — they name the machine, the profile and what
+// to do instead. HTTPError.Error() would bury that sentence inside a raw JSON
+// dump of the whole response, which is what a blocked user used to see.
+func serverConflictMessage(err error) (code string, message string, ok bool) {
+ var httpErr *cli.HTTPError
+ if !errors.As(err, &httpErr) || httpErr.StatusCode != http.StatusConflict {
+ return "", "", false
+ }
+ body := strings.TrimSpace(httpErr.Body)
+ if body == "" {
+ return "", "", false
+ }
+ var payload struct {
+ Code string `json:"code"`
+ Error string `json:"error"`
+ }
+ if json.Unmarshal([]byte(body), &payload) != nil {
+ // Not JSON. An older or proxied server can still put a readable
+ // sentence here, and swallowing it would be worse than passing it
+ // through — there is nothing to leak when the body was never
+ // structured in the first place.
+ return "", body, true
+ }
+ if strings.TrimSpace(payload.Error) == "" {
+ return payload.Code, "", false
+ }
+ return payload.Code, payload.Error, true
+}
+
type runtimeDeleteConflictPayload struct {
Code string `json:"code"`
Error string `json:"error"`
diff --git a/server/cmd/multica/cmd_runtime_profile.go b/server/cmd/multica/cmd_runtime_profile.go
index 1b84a16b55..c24d6867f8 100644
--- a/server/cmd/multica/cmd_runtime_profile.go
+++ b/server/cmd/multica/cmd_runtime_profile.go
@@ -269,16 +269,17 @@ func runRuntimeProfileDelete(cmd *cobra.Command, args []string) error {
path := runtimeProfilesPath(workspaceID) + "/" + profileID
if err := client.DeleteJSON(ctx, path); err != nil {
- // 409 means the server refused because active agents are still bound
- // to this profile. Surface the server's explanation verbatim rather
- // than the generic HTTP wrapper so the user sees what to unbind.
+ // 409 means the server refused — usually because active agents are
+ // still bound to this profile, on machines it names. Surface that
+ // sentence rather than the raw response body: it already reads as
+ // guidance, and it is what tells the user the blockers may be sitting
+ // on a machine other than the one they were cleaning up.
+ if _, msg, isConflict := serverConflictMessage(err); isConflict {
+ return errors.New(msg)
+ }
var httpErr *cli.HTTPError
if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusConflict {
- msg := strings.TrimSpace(httpErr.Body)
- if msg == "" {
- msg = "profile still has active agents bound to it"
- }
- return fmt.Errorf("cannot delete runtime profile %s: %s", profileID, msg)
+ return fmt.Errorf("cannot delete runtime profile %s: profile still has active agents bound to it", profileID)
}
return fmt.Errorf("delete runtime profile: %w", err)
}
diff --git a/server/cmd/multica/cmd_runtime_test.go b/server/cmd/multica/cmd_runtime_test.go
index eab0182afc..bec708e547 100644
--- a/server/cmd/multica/cmd_runtime_test.go
+++ b/server/cmd/multica/cmd_runtime_test.go
@@ -145,7 +145,7 @@ func TestRunRuntimeDeleteCascadeConfirmsActiveAgentSnapshot(t *testing.T) {
gotExpectedIDs = body.ExpectedActiveAgentIDs
_ = json.NewEncoder(w).Encode(map[string]any{
"status": "ok",
- "agents_unbound": 2,
+ "agents_unbound": 2,
"tasks_cancelled": 1,
})
default:
@@ -179,3 +179,57 @@ func TestRunRuntimeDeleteCascadeConfirmsActiveAgentSnapshot(t *testing.T) {
t.Fatalf("stdout = %#v, want cascade result", got)
}
}
+
+// A profile-backed instance refusal is not something --cascade can retry past,
+// and the server already explains what to do instead. Wrapping it in
+// HTTPError.Error() used to print the whole JSON response at the user, burying
+// that guidance (GH #8456).
+func TestRunRuntimeDeleteProfileInstanceConflictShowsServerGuidance(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ const guidance = `cannot delete "MSI-S3TEST" on its own: it is registered from the custom runtime profile "Devin CLI (WSL)". It is offline, and Multica removes offline runtimes automatically after 7 days.`
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusConflict)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": "runtime_profile_instance_delete_unsupported",
+ "error": guidance,
+ "profile_name": "Devin CLI (WSL)",
+ "auto_cleanup_after_days": 7,
+ })
+ }))
+ defer srv.Close()
+
+ err := runRuntimeDelete(newRuntimeDeleteTestCmd(srv.URL), []string{"rt-1"})
+ if err == nil {
+ t.Fatal("expected the profile-instance refusal to surface as an error")
+ }
+ if err.Error() != guidance {
+ t.Fatalf("error = %q, want the server's guidance verbatim", err.Error())
+ }
+ if strings.Contains(err.Error(), "auto_cleanup_after_days") {
+ t.Fatalf("raw JSON leaked into the user-facing error: %q", err.Error())
+ }
+}
+
+// A 409 with no readable sentence must still fall back to the wrapper rather
+// than surfacing an empty error.
+func TestRunRuntimeDeleteConflictWithoutMessageKeepsWrapper(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusConflict)
+ _, _ = w.Write([]byte(`{"code":"something_new"}`))
+ }))
+ defer srv.Close()
+
+ err := runRuntimeDelete(newRuntimeDeleteTestCmd(srv.URL), []string{"rt-1"})
+ if err == nil {
+ t.Fatal("expected an error")
+ }
+ if !strings.Contains(err.Error(), "delete runtime:") {
+ t.Fatalf("error = %q, want the generic wrapper", err.Error())
+ }
+}
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index 8715f05e3a..73447182e5 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -53,7 +53,10 @@ const (
reconnectRetryExpireBatchSize = 500
// offlineRuntimeTTLSeconds deletes offline runtimes with no active agents
// after this duration. 7 days gives users plenty of time to restart daemons.
- offlineRuntimeTTLSeconds = 7 * 24 * 3600.0
+ // Shared with the delete handlers, which quote the same window when they
+ // refuse to remove a profile-backed instance the user could otherwise only
+ // wait out.
+ offlineRuntimeTTLSeconds = service.OfflineRuntimeTTLSeconds
// runtimeGCBatchSize bounds both the candidate scan and the number of
// per-runtime transactions one sweeper tick may open. At the hourly cadence,
// 500 preserves a theoretical capacity of 12,000 candidates per day; the
diff --git a/server/internal/handler/agent_builder.go b/server/internal/handler/agent_builder.go
index 7f4ba0227b..014eb59052 100644
--- a/server/internal/handler/agent_builder.go
+++ b/server/internal/handler/agent_builder.go
@@ -113,7 +113,7 @@ func (h *Handler) CreateAgentBuilderSession(w http.ResponseWriter, r *http.Reque
Instructions: agentBuilderInstructions,
Model: pgtype.Text{String: model, Valid: model != ""},
SystemKey: pgtype.Text{
- String: fmt.Sprintf("agent_builder:%s", flowID),
+ String: agentBuilderSystemKeyPrefix + flowID,
Valid: true,
},
})
@@ -508,5 +508,5 @@ func (h *Handler) SwitchAgentBuilderRuntime(w http.ResponseWriter, r *http.Reque
func isAgentBuilderCarrier(agent db.Agent) bool {
return agent.Kind == "system" &&
agent.SystemKey.Valid &&
- strings.HasPrefix(agent.SystemKey.String, "agent_builder:")
+ strings.HasPrefix(agent.SystemKey.String, agentBuilderSystemKeyPrefix)
}
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index e9aba7716f..3d0bb4f9dc 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"log/slog"
"net/http"
"strconv"
@@ -689,20 +690,175 @@ func (h *Handler) requireRuntimeReadAccess(w http.ResponseWriter, r *http.Reques
return rt, member, true
}
-func (h *Handler) runtimeHasLiveProfile(ctx context.Context, rt db.AgentRuntime) (bool, error) {
+// runtimeLiveProfile returns the custom runtime profile that owns rt, if that
+// profile still exists in the same workspace. A profile-backed instance whose
+// profile is gone is an orphan and stays directly deletable (MUL-4158).
+//
+// The profile row itself — not just "one exists" — is what the caller needs:
+// the refusal it writes names the profile, so the user can tell which shared
+// definition they would be reaching for if they followed the old advice.
+func (h *Handler) runtimeLiveProfile(ctx context.Context, rt db.AgentRuntime) (db.RuntimeProfile, bool, error) {
if !rt.ProfileID.Valid {
- return false, nil
+ return db.RuntimeProfile{}, false, nil
}
- if _, err := h.Queries.GetRuntimeProfileForWorkspace(ctx, db.GetRuntimeProfileForWorkspaceParams{
+ profile, err := h.Queries.GetRuntimeProfileForWorkspace(ctx, db.GetRuntimeProfileForWorkspaceParams{
ID: rt.ProfileID,
WorkspaceID: rt.WorkspaceID,
- }); err != nil {
+ })
+ if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
- return false, nil
+ return db.RuntimeProfile{}, false, nil
+ }
+ return db.RuntimeProfile{}, false, err
+ }
+ return profile, true, nil
+}
+
+// profileInstanceDeleteRefusal explains why this one runtime row cannot be
+// deleted on its own, and — the part that matters — what the user should
+// actually do instead.
+//
+// The previous wording said only "delete its runtime profile instead", which
+// is actively harmful advice for the case that produces this error most often
+// (GH #8456, #6671): a retired machine's leftover row inside a profile that
+// other, healthy machines still use. Following it means reaching for a
+// workspace-wide delete that takes those machines' runtimes with it, and that
+// a bound agent will refuse anyway. So the refusal now leads with the outcome
+// the user wants — an offline row is reclaimed automatically — and states the
+// blast radius of the profile delete rather than recommending it.
+//
+// blockers are the non-archived user agents bound to rt, matching the predicate
+// retention GC applies; known is false when that read failed. They decide two
+// things. Whether the promise of automatic cleanup is one this server can keep
+// at all — GC skips a runtime that still has a bound agent — and, when it is
+// not, which of those blockers the user can actually do anything about. Mika is
+// a user-kind agent that can be neither archived nor moved, so "reassign or
+// archive them" is not a universal instruction here either.
+func profileInstanceDeleteRefusal(rt db.AgentRuntime, profile db.RuntimeProfile, blockers profileInstanceBlockers) map[string]any {
+ known := blockers.known
+ ttlDays := service.OfflineRuntimeTTLDays()
+ name := rt.Name
+ if rt.CustomName.Valid && strings.TrimSpace(rt.CustomName.String) != "" {
+ name = rt.CustomName.String
+ }
+
+ lead := fmt.Sprintf(
+ "cannot delete %q on its own: it is registered from the custom runtime profile %q.",
+ name, profile.DisplayName,
+ )
+ scope := "Deleting the profile instead would remove this runtime on every machine that registered it, not just this one."
+
+ parts := []string{lead}
+ switch {
+ case rt.Status == "online":
+ parts = append(parts, fmt.Sprintf(
+ "It is still online, so its daemon would register it again. Stop that daemon first; Multica then removes the runtime automatically after %d days offline, once no agent is bound to it and nothing is still running on it.",
+ ttlDays,
+ ))
+ case !known:
+ // Blocker set unavailable; promise only what holds regardless of it.
+ parts = append(parts, fmt.Sprintf(
+ "It is offline, and Multica removes offline runtimes automatically after %d days, once no agent is bound to them and nothing is still running on them.",
+ ttlDays,
+ ))
+ case len(blockers.agents) > 0 || blockers.undrainedTasks > 0:
+ // GC needs BOTH gone. Naming only the agents would send a user who
+ // clears them straight back here a week later, still waiting on a task
+ // nothing told them about — a deferred run left behind when its agent
+ // was rebound elsewhere is the ordinary way this happens.
+ var holds []string
+ if n := len(blockers.agents); n > 0 {
+ holds = append(holds, fmt.Sprintf("%d agent(s) are still bound to it", n))
+ }
+ if n := blockers.undrainedTasks; n > 0 {
+ holds = append(holds, fmt.Sprintf("%d unfinished task(s) belong to it or to agents bound to it", n))
+ }
+ parts = append(parts, fmt.Sprintf(
+ "It is offline, but %s, which holds it in place; Multica removes the runtime automatically after %d days offline once that is cleared.",
+ strings.Join(holds, " and "), ttlDays,
+ ))
+ parts = append(parts, blockingAgentRemedies(blockingAgentClassesFromAgents(blockers.agents), blockingAgentScopeInstance)...)
+ if blockers.undrainedTasks > 0 {
+ parts = append(parts, "Let those tasks finish, or cancel them — one can be running on a different machine if its agent was moved there.")
}
- return false, err
+ default:
+ parts = append(parts, fmt.Sprintf(
+ "It is offline with no agents bound and nothing still running on it, so Multica removes it automatically after %d days offline — this row will be reclaimed without any action from you.",
+ ttlDays,
+ ))
+ }
+ parts = append(parts, scope)
+
+ msg := strings.Join(parts, " ")
+
+ resp := map[string]any{
+ "error": msg,
+ "code": "runtime_profile_instance_delete_unsupported",
+ // Structured companions to the sentence above so a client can render
+ // its own localized copy instead of echoing the English (see
+ // writeErrorCode's rationale). The sentence stays the fallback.
+ "profile_id": uuidToString(profile.ID),
+ "profile_name": profile.DisplayName,
+ "runtime_status": rt.Status,
+ "last_seen_at": timestampToPtr(rt.LastSeenAt),
+ "auto_cleanup_after_days": ttlDays,
+ }
+ if known {
+ resp["active_agent_count"] = len(blockers.agents)
+ resp["undrained_task_count"] = blockers.undrainedTasks
+ }
+ return resp
+}
+
+// profileInstanceBlockers is everything retention GC checks before it will
+// reclaim an offline runtime, which is more than its candidate query asks for:
+// the candidate scan wants no non-archived user agent and no runtime-owned task
+// with completed_at NULL, and then gcRuntime re-checks the drain across every
+// user agent bound to the runtime, archived ones included. Reporting any subset
+// of that promises a cleanup the sweeper then skips.
+type profileInstanceBlockers struct {
+ agents []db.Agent
+ undrainedTasks int64
+ known bool
+}
+
+// profileInstanceRefusalBlockers reads what would stop retention GC from
+// reclaiming this runtime. A read failure is not worth failing the request
+// over: it only costs the refusal its most specific sentence, so report it as
+// unknown and let the caller fall back to the cautious wording.
+//
+// Already bounded — a single runtime's bound agents, unlike a profile's, are
+// capped by what one machine can host.
+func (h *Handler) profileInstanceRefusalBlockers(ctx context.Context, runtimeID pgtype.UUID) profileInstanceBlockers {
+ agents, err := h.Queries.ListActiveAgentsByRuntime(ctx, runtimeID)
+ if err != nil {
+ slog.Warn("profile instance refusal: active agent lookup failed",
+ "runtime_id", uuidToString(runtimeID), "error", err)
+ return profileInstanceBlockers{}
+ }
+ // The same drain gate gcRuntime applies, and deliberately not just the
+ // candidate query's runtime-owned predicate: gcRuntime widens it to every
+ // user agent bound to this runtime, archived included, and skips the delete
+ // when any of them still owns a non-terminal task. That task can sit on a
+ // different machine — an agent moved away leaves its deferred run behind —
+ // so a check scoped to this runtime's own rows reports a row as reclaimable
+ // that the sweeper will pass over every hour.
+ agentIDs, err := h.Queries.ListUserAgentIDsByRuntime(ctx, runtimeID)
+ if err != nil {
+ slog.Warn("profile instance refusal: bound agent id lookup failed",
+ "runtime_id", uuidToString(runtimeID), "error", err)
+ return profileInstanceBlockers{}
+ }
+ tasks, err := h.Queries.CountUndrainedTasksByRuntimeOrAgent(ctx, db.CountUndrainedTasksByRuntimeOrAgentParams{
+ RuntimeIds: []pgtype.UUID{runtimeID},
+ AgentIds: agentIDs,
+ })
+ if err != nil {
+ slog.Warn("profile instance refusal: undrained task lookup failed",
+ "runtime_id", uuidToString(runtimeID), "error", err)
+ return profileInstanceBlockers{}
}
- return true, nil
+ return profileInstanceBlockers{agents: agents, undrainedTasks: tasks, known: true}
}
// canUseRuntimeForAgent reports whether a workspace member is allowed to
@@ -858,16 +1014,14 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
}
userID := uuidToString(member.UserID)
- hasLiveProfile, err := h.runtimeHasLiveProfile(r.Context(), rt)
+ profile, hasLiveProfile, err := h.runtimeLiveProfile(r.Context(), rt)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to check runtime profile")
return
}
if hasLiveProfile {
- writeJSON(w, http.StatusConflict, map[string]any{
- "error": "cannot delete a custom runtime instance directly; delete its runtime profile instead.",
- "code": "runtime_profile_instance_delete_unsupported",
- })
+ blockers := h.profileInstanceRefusalBlockers(r.Context(), rt.ID)
+ writeJSON(w, http.StatusConflict, profileInstanceDeleteRefusal(rt, profile, blockers))
return
}
if rt.ProfileID.Valid {
@@ -1078,16 +1232,14 @@ func (h *Handler) UnbindAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.Re
}
userID := uuidToString(member.UserID)
- hasLiveProfile, err := h.runtimeHasLiveProfile(r.Context(), rt)
+ profile, hasLiveProfile, err := h.runtimeLiveProfile(r.Context(), rt)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to check runtime profile")
return
}
if hasLiveProfile {
- writeJSON(w, http.StatusConflict, map[string]any{
- "error": "cannot delete a custom runtime instance directly; delete its runtime profile instead.",
- "code": "runtime_profile_instance_delete_unsupported",
- })
+ blockers := h.profileInstanceRefusalBlockers(r.Context(), rt.ID)
+ writeJSON(w, http.StatusConflict, profileInstanceDeleteRefusal(rt, profile, blockers))
return
}
if rt.ProfileID.Valid {
diff --git a/server/internal/handler/runtime_blocking_agents.go b/server/internal/handler/runtime_blocking_agents.go
new file mode 100644
index 0000000000..cf8db3f2df
--- /dev/null
+++ b/server/internal/handler/runtime_blocking_agents.go
@@ -0,0 +1,175 @@
+package handler
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/service"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// agentBuilderSystemKeyPrefix marks the hidden execution carrier behind an
+// unfinished AI agent-creation flow. The suffix is the flow id.
+const agentBuilderSystemKeyPrefix = "agent_builder:"
+
+// A runtime or profile delete is refused while agents are still bound. Telling
+// the user to "reassign or archive them" is only true for agents they can
+// actually reach: the archive endpoint rejects anything carrying a system_key
+// outright, and a builder carrier is not in the agent list at all. Naming one
+// remedy for every blocker therefore hands some users an instruction that
+// cannot be carried out — the same class of defect this whole change set exists
+// to remove, so the refusals classify their blockers instead.
+//
+// system_key, not kind, is the discriminator. Mika is deliberately kind='user'
+// (it must stay visible and assignable) while still being product-owned and
+// unarchivable; builder carriers are kind='system'.
+type blockingAgentClass int
+
+const (
+ // blockingAgentUser is an ordinary workspace agent: rebind or archive it.
+ blockingAgentUser blockingAgentClass = iota
+ // blockingAgentMika is the workspace's built-in Mika. It cannot be archived
+ // (agent.go rejects any system_key there) but it CAN be rebound: UpdateAgent
+ // takes runtime_id for it like any other manageable agent. Those two halves
+ // have to be stated separately or the remedy is wrong in one direction.
+ blockingAgentMika
+ // blockingAgentBuilderCarrier is the hidden carrier behind an unfinished
+ // Agent Builder flow. It is released through that session, not the agent list.
+ blockingAgentBuilderCarrier
+ // blockingAgentOtherSystem is any future product-owned agent. Unarchivable
+ // like the rest, with no remedy this code can name specifically.
+ blockingAgentOtherSystem
+)
+
+// Class keys shared with the SQL CASE in ListActiveAgentsByProfile. That query
+// has to classify server-side so its per-class counts can cover rows the LIMIT
+// excludes, which means the mapping exists in two places; these constants give
+// both the same vocabulary, and TestBlockingAgentClassMatchesSQLClassification
+// pins them to each other.
+const (
+ blockingAgentClassKeyUser = "user"
+ blockingAgentClassKeyMika = "mika"
+ blockingAgentClassKeyBuilder = "agent_builder"
+ blockingAgentClassKeyOtherSystem = "other_system"
+)
+
+// Unknown keys fall to other_system, not user. Only the exact "user" key may
+// produce the one class whose remedy claims an action ("reassign or archive"):
+// if a future class is added to the SQL CASE and not here, the refusal should
+// say it cannot name a remedy rather than confidently hand out one that does
+// not apply.
+func blockingAgentClassFromKey(key string) blockingAgentClass {
+ switch key {
+ case blockingAgentClassKeyUser:
+ return blockingAgentUser
+ case blockingAgentClassKeyMika:
+ return blockingAgentMika
+ case blockingAgentClassKeyBuilder:
+ return blockingAgentBuilderCarrier
+ default:
+ return blockingAgentOtherSystem
+ }
+}
+
+func classifyBlockingAgent(systemKey pgtype.Text) blockingAgentClass {
+ key := strings.TrimSpace(systemKey.String)
+ if !systemKey.Valid || key == "" {
+ return blockingAgentUser
+ }
+ switch {
+ case key == service.MikaSystemKey:
+ return blockingAgentMika
+ case strings.HasPrefix(key, agentBuilderSystemKeyPrefix):
+ return blockingAgentBuilderCarrier
+ default:
+ return blockingAgentOtherSystem
+ }
+}
+
+// blockingAgentLabel renders one blocker for a refusal sentence. Product-owned
+// agents are marked so the reader can tell at a glance why the plain remedy
+// does not apply to them.
+func blockingAgentLabel(name, runtimeName, runtimeStatus string, class blockingAgentClass) string {
+ switch class {
+ case blockingAgentBuilderCarrier:
+ return fmt.Sprintf("an unfinished Agent Builder session on %q (%s)", runtimeName, runtimeStatus)
+ case blockingAgentMika, blockingAgentOtherSystem:
+ return fmt.Sprintf("%q on %q (%s, built into Multica)", name, runtimeName, runtimeStatus)
+ default:
+ return fmt.Sprintf("%q on %q (%s)", name, runtimeName, runtimeStatus)
+ }
+}
+
+// blockingAgentScope distinguishes the two refusals, because one remedy differs
+// between them: moving Mika off this runtime clears an instance refusal, but a
+// profile refusal only clears if the destination is not another runtime of the
+// same profile.
+type blockingAgentScope int
+
+const (
+ blockingAgentScopeInstance blockingAgentScope = iota
+ blockingAgentScopeProfile
+)
+
+// blockingAgentRemedies returns one clause per distinct recovery path present,
+// in a fixed order so the sentence is stable. An empty result means every
+// blocker was product-owned and the caller should say so rather than suggest
+// an action.
+func blockingAgentRemedies(classes map[blockingAgentClass]bool, scope blockingAgentScope) []string {
+ // "Reassign or archive them" must not appear to cover the product-owned
+ // blockers listed beside them, which is exactly the instruction they cannot
+ // follow. When both are present the clause names which ones it applies to.
+ mixed := classes[blockingAgentMika] ||
+ classes[blockingAgentBuilderCarrier] ||
+ classes[blockingAgentOtherSystem]
+
+ var out []string
+ if classes[blockingAgentUser] && mixed {
+ out = append(out, "The agents above that are not marked as built into Multica can be reassigned or archived.")
+ } else if classes[blockingAgentUser] {
+ out = append(out, "Reassign or archive them first.")
+ }
+ if classes[blockingAgentBuilderCarrier] {
+ // Addressed to the creator, not to whoever hit this error. Builder
+ // sessions are creator-scoped: ListAgentBuilderSessions returns 200 but
+ // omits other members' sessions, and switch/discard go through
+ // loadChatSessionForUser and return 403. So an admin who is not the
+ // creator cannot even see the session to act on it, and telling them to
+ // reopen it would be another instruction that cannot be carried out.
+ out = append(out, "The unfinished Agent Builder session(s) here are hidden from the agent list, and only their creator can open them — ask the member who started the session to switch its runtime or discard it; another admin cannot do that for them.")
+ }
+ if classes[blockingAgentMika] {
+ // Mika is unarchivable but NOT immovable: UpdateAgent takes runtime_id
+ // for it like any other agent an admin can manage (the only system_key
+ // guard in agent.go is on archive), and the agent detail page shows it
+ // an editable runtime picker. An earlier version of this message said
+ // there was no supported way to move it, which told an owner who could
+ // have fixed this in one edit to give up instead — the exact failure
+ // this whole change set is about. TestMikaRemedyMatchesWhatMikaCanDo
+ // exercises both halves against the real endpoints so the claim cannot
+ // drift from the product again.
+ target := "another runtime"
+ if scope == blockingAgentScopeProfile {
+ target = "a runtime that this profile does not provide"
+ }
+ out = append(out, fmt.Sprintf(
+ "Mika is built into Multica, so it cannot be archived — but it can be moved: open Mika's agent page and bind it to %s.",
+ target,
+ ))
+ }
+ if classes[blockingAgentOtherSystem] {
+ out = append(out, "Some blockers are agents built into Multica and cannot be archived.")
+ }
+ return out
+}
+
+// blockingAgentClassesFromAgents collects the classes present on a plain agent
+// set, for the callers that already hold db.Agent rows.
+func blockingAgentClassesFromAgents(agents []db.Agent) map[blockingAgentClass]bool {
+ classes := make(map[blockingAgentClass]bool, 2)
+ for _, a := range agents {
+ classes[classifyBlockingAgent(a.SystemKey)] = true
+ }
+ return classes
+}
diff --git a/server/internal/handler/runtime_delete_guidance_test.go b/server/internal/handler/runtime_delete_guidance_test.go
new file mode 100644
index 0000000000..2a5e57ef88
--- /dev/null
+++ b/server/internal/handler/runtime_delete_guidance_test.go
@@ -0,0 +1,935 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// The refusals these tests cover are the ones a user acts on. A profile spans
+// every machine that registered it, so "delete its runtime profile instead" —
+// the advice the instance refusal used to give — points at a workspace-wide
+// delete that takes healthy machines' runtimes with it, and that a bound agent
+// refuses anyway. GH #8456 is a report of exactly that dead end. What both
+// messages must now carry is asserted here rather than left to review, because
+// the damage is done by the wording, not by the status code.
+
+func decodeConflict(t *testing.T, w *httptest.ResponseRecorder) map[string]any {
+ t.Helper()
+ var body map[string]any
+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ return body
+}
+
+func conflictMessage(t *testing.T, body map[string]any) string {
+ t.Helper()
+ msg, _ := body["error"].(string)
+ if strings.TrimSpace(msg) == "" {
+ t.Fatalf("expected a human-readable error message, got %#v", body)
+ }
+ return msg
+}
+
+// An offline profile-backed instance is the GH #8456 shape: the row the user
+// wants gone, on a machine that is never coming back. The refusal has to tell
+// them it is reclaimed on its own, because that is the whole answer — every
+// other route they could take from here is destructive.
+func TestDeleteAgentRuntime_OfflineProfileInstanceRefusalPointsAtAutoCleanup(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID, _ := createProfileBackedRuntime(t, ctx, "Retired Test Machine")
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent_runtime SET status = 'offline' WHERE id = $1`, runtimeID); err != nil {
+ t.Fatalf("mark runtime offline: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.DeleteAgentRuntime(w, req)
+
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+ body := decodeConflict(t, w)
+ msg := conflictMessage(t, body)
+
+ if got, _ := body["code"].(string); got != "runtime_profile_instance_delete_unsupported" {
+ t.Fatalf("code changed, installed clients branch on it: %q", got)
+ }
+ if !strings.Contains(msg, "automatically") {
+ t.Fatalf("refusal must say the row is reclaimed automatically, got: %s", msg)
+ }
+ if !strings.Contains(msg, "Retired Test Machine Profile") {
+ t.Fatalf("refusal must name the owning profile, got: %s", msg)
+ }
+ // The old advice. Sending a user to a workspace-wide delete to clean up one
+ // machine is the defect; a message may mention the profile's blast radius,
+ // but must not recommend it as the fix.
+ if strings.Contains(msg, "delete its runtime profile instead") {
+ t.Fatalf("refusal still recommends deleting the shared profile: %s", msg)
+ }
+
+ if got, _ := body["auto_cleanup_after_days"].(float64); int(got) != service.OfflineRuntimeTTLDays() {
+ t.Fatalf("auto_cleanup_after_days = %v, want %d", got, service.OfflineRuntimeTTLDays())
+ }
+ if got, _ := body["runtime_status"].(string); got != "offline" {
+ t.Fatalf("runtime_status = %q, want offline", got)
+ }
+ if got, _ := body["profile_name"].(string); got != "Retired Test Machine Profile" {
+ t.Fatalf("profile_name = %q", got)
+ }
+}
+
+// Online is the one case where waiting is not the answer — the daemon would
+// re-register the row immediately. The refusal has to say so instead of
+// promising a cleanup that will not happen.
+func TestDeleteAgentRuntime_OnlineProfileInstanceRefusalSaysStopTheDaemon(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID, _ := createProfileBackedRuntime(t, ctx, "Live Machine")
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.DeleteAgentRuntime(w, req)
+
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+ body := decodeConflict(t, w)
+ msg := conflictMessage(t, body)
+
+ if !strings.Contains(msg, "still online") {
+ t.Fatalf("online refusal must explain the daemon would re-register, got: %s", msg)
+ }
+ if got, _ := body["runtime_status"].(string); got != "online" {
+ t.Fatalf("runtime_status = %q, want online", got)
+ }
+}
+
+// The cascade endpoint shares the guard, so it must share the guidance —
+// `multica runtime delete --cascade` is the retry a blocked user reaches for.
+func TestUnbindAgentsAndDeleteRuntime_ProfileInstanceRefusalCarriesGuidance(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID, _ := createProfileBackedRuntime(t, ctx, "Cascade Guidance Machine")
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent_runtime SET status = 'offline' WHERE id = $1`, runtimeID); err != nil {
+ t.Fatalf("mark runtime offline: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete",
+ strings.NewReader(`{"expected_active_agent_ids":[]}`))
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.UnbindAgentsAndDeleteRuntime(w, req)
+
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+ body := decodeConflict(t, w)
+ msg := conflictMessage(t, body)
+ if !strings.Contains(msg, "automatically") {
+ t.Fatalf("cascade refusal must carry the same guidance, got: %s", msg)
+ }
+ if got, _ := body["auto_cleanup_after_days"].(float64); int(got) != service.OfflineRuntimeTTLDays() {
+ t.Fatalf("auto_cleanup_after_days = %v", got)
+ }
+}
+
+// The profile refusal's job is to show that the agents blocking the delete sit
+// on a *different* machine than the stale one the user was cleaning up. A bare
+// count cannot do that, and the user's reasonable next move — unbinding agents
+// that were working fine — is the damage this message exists to prevent.
+func TestDeleteRuntimeProfile_ActiveAgentConflictNamesAgentsAndMachines(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ profileID := insertRuntimeProfileFixture(t, ctx, "Shared Devin Profile", "codex", "shared-devin")
+ healthyRuntimeID := insertProfileRuntimeFixture(t, ctx, profileID, "HEALTHY-DESKTOP", "codex")
+ staleRuntimeID := insertProfileRuntimeFixture(t, ctx, profileID, "RETIRED-LAPTOP", "codex")
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent_runtime SET status = 'offline' WHERE id = $1`, staleRuntimeID); err != nil {
+ t.Fatalf("mark stale runtime offline: %v", err)
+ }
+ // The blocker is bound to the healthy machine, not the one being cleaned up.
+ _ = createCascadeFixtureAgent(t, ctx, healthyRuntimeID, "Production Agent")
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles/"+profileID, nil)
+ req = withURLParams(req, "id", testWorkspaceID, "profileId", profileID)
+ notifier := &recordingRuntimeGoneNotifier{}
+ h := *testHandler
+ h.DaemonRuntimeGone = notifier
+ h.DeleteRuntimeProfile(w, req)
+
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+ body := decodeConflict(t, w)
+ msg := conflictMessage(t, body)
+
+ if got, _ := body["code"].(string); got != "runtime_profile_has_active_agents" {
+ t.Fatalf("code = %q", got)
+ }
+ if !strings.Contains(msg, "Production Agent") {
+ t.Fatalf("refusal must name the blocking agent, got: %s", msg)
+ }
+ if !strings.Contains(msg, "HEALTHY-DESKTOP") {
+ t.Fatalf("refusal must name the machine the blocker is on, got: %s", msg)
+ }
+ if !strings.Contains(msg, "Shared Devin Profile") {
+ t.Fatalf("refusal must name the profile, got: %s", msg)
+ }
+
+ agents, _ := body["active_agents"].([]any)
+ if len(agents) != 1 {
+ t.Fatalf("expected 1 blocking agent on the response, got %d", len(agents))
+ }
+ entry, _ := agents[0].(map[string]any)
+ if got, _ := entry["runtime_name"].(string); got != "HEALTHY-DESKTOP" {
+ t.Fatalf("active_agents[0].runtime_name = %q", got)
+ }
+ if got, _ := entry["name"].(string); got != "Production Agent" {
+ t.Fatalf("active_agents[0].name = %q", got)
+ }
+
+ // The guard itself must not have moved: both rows and the profile survive.
+ var profileRows, rtRows int
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM runtime_profile WHERE id = $1`, profileID).Scan(&profileRows); err != nil {
+ t.Fatalf("count profile rows: %v", err)
+ }
+ if profileRows != 1 {
+ t.Fatalf("profile should survive the refusal, found %d", profileRows)
+ }
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM agent_runtime WHERE profile_id = $1`, profileID).Scan(&rtRows); err != nil {
+ t.Fatalf("count runtime rows: %v", err)
+ }
+ if rtRows != 2 {
+ t.Fatalf("both runtimes should survive the refusal, found %d", rtRows)
+ }
+}
+
+// Above maxNamedBlockingAgents the message must stay readable without hiding
+// the scale of what the user is about to unbind.
+func TestDeleteRuntimeProfile_ActiveAgentConflictTruncatesLongAgentLists(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ profileID := insertRuntimeProfileFixture(t, ctx, "Crowded Profile", "codex", "crowded-codex")
+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "CROWDED-HOST", "codex")
+ total := maxNamedBlockingAgents + 3
+ for i := 0; i < total; i++ {
+ _ = createCascadeFixtureAgent(t, ctx, runtimeID, "Crowd Agent "+string(rune('A'+i)))
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles/"+profileID, nil)
+ req = withURLParams(req, "id", testWorkspaceID, "profileId", profileID)
+ notifier := &recordingRuntimeGoneNotifier{}
+ h := *testHandler
+ h.DaemonRuntimeGone = notifier
+ h.DeleteRuntimeProfile(w, req)
+
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+ body := decodeConflict(t, w)
+ msg := conflictMessage(t, body)
+
+ if !strings.Contains(msg, "and 3 more") {
+ t.Fatalf("expected a truncation tail for %d agents, got: %s", total, msg)
+ }
+ // The full set still reaches a client that wants to render it.
+ agents, _ := body["active_agents"].([]any)
+ if len(agents) != total {
+ t.Fatalf("active_agents should carry every blocker, got %d want %d", len(agents), total)
+ }
+}
+
+// Retention GC skips a runtime that still has a bound agent, so an offline
+// instance in that state must NOT be told to sit and wait — that would be a
+// fresh piece of wrong advice replacing the old one.
+func TestDeleteAgentRuntime_OfflineProfileInstanceWithBoundAgentsDoesNotPromiseCleanup(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID, _ := createProfileBackedRuntime(t, ctx, "Held Machine")
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent_runtime SET status = 'offline' WHERE id = $1`, runtimeID); err != nil {
+ t.Fatalf("mark runtime offline: %v", err)
+ }
+ _ = createCascadeFixtureAgent(t, ctx, runtimeID, "Still Bound Agent")
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.DeleteAgentRuntime(w, req)
+
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+ body := decodeConflict(t, w)
+ msg := conflictMessage(t, body)
+
+ if strings.Contains(msg, "without any action from you") {
+ t.Fatalf("must not promise cleanup while an agent holds the runtime: %s", msg)
+ }
+ if !strings.Contains(msg, "still bound to it") {
+ t.Fatalf("refusal should say the bound agents hold it in place, got: %s", msg)
+ }
+ if got, _ := body["active_agent_count"].(float64); int(got) != 1 {
+ t.Fatalf("active_agent_count = %v, want 1", got)
+ }
+}
+
+// createSystemFixtureAgent inserts a product-owned agent. kind and system_key
+// are independent here on purpose: Mika is kind='user' with system_key='mika'
+// (it must stay visible and assignable), while a builder carrier is
+// kind='system'. The refusals key off system_key for exactly that reason.
+func createSystemFixtureAgent(t *testing.T, ctx context.Context, runtimeID, name, kind, systemKey string) string {
+ t.Helper()
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, max_concurrent_tasks, owner_id, kind, system_key
+ )
+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'private', 1, $4, $5, $6)
+ RETURNING id
+ `, testWorkspaceID, name, runtimeID, testUserID, kind, systemKey).Scan(&agentID); err != nil {
+ t.Fatalf("insert system fixture agent (%s): %v", systemKey, err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID)
+ })
+ return agentID
+}
+
+// Mika cannot be archived — the archive endpoint rejects any agent carrying a
+// system_key — but it CAN be rebound, so the generic "reassign or archive them"
+// clause is wrong for it in both directions: half of it is impossible and the
+// half that works needs a destination the generic wording never gives. The
+// refusal has to carry Mika's own path instead. Capability itself is asserted
+// against the real endpoints in TestMikaRemedyMatchesWhatMikaCanDo.
+func TestDeleteRuntimeProfile_MikaBlockerGetsItsOwnRemedy(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ profileID := insertRuntimeProfileFixture(t, ctx, "Mika Held Profile", "codex", "mika-held")
+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "MIKA-HOST", "codex")
+ createSystemFixtureAgent(t, ctx, runtimeID, "Mika (profile guard)", "user", "mika")
+
+ body := deleteProfileExpectingConflict(t, ctx, profileID)
+ msg := conflictMessage(t, body)
+
+ if strings.Contains(msg, "can be reassigned or archived") || strings.Contains(msg, "Reassign or archive them first.") {
+ t.Fatalf("the generic reassign-or-archive clause does not apply to Mika: %s", msg)
+ }
+ if !strings.Contains(msg, "cannot be archived") {
+ t.Fatalf("refusal must still say Mika cannot be archived, got: %s", msg)
+ }
+ // The other half: Mika IS movable, and saying otherwise tells an owner who
+ // could fix this in one edit to give up. Scoped for a profile delete —
+ // moving Mika to a sibling runtime of the same profile would not help.
+ if !strings.Contains(msg, "a runtime that this profile does not provide") {
+ t.Fatalf("refusal must point at the rebind that actually clears this, got: %s", msg)
+ }
+ if !strings.Contains(msg, "built into Multica)") {
+ t.Fatalf("the listed blocker should be marked as product-owned, got: %s", msg)
+ }
+
+ agents, _ := body["active_agents"].([]any)
+ if len(agents) != 1 {
+ t.Fatalf("expected 1 blocker, got %d", len(agents))
+ }
+ entry, _ := agents[0].(map[string]any)
+ if got, _ := entry["system_key"].(string); got != "mika" {
+ t.Fatalf("system_key = %q, want mika — clients need it to localize", got)
+ }
+ if got, _ := entry["kind"].(string); got != "user" {
+ t.Fatalf("kind = %q; Mika is deliberately kind=user, so kind must not be the discriminator", got)
+ }
+}
+
+// A builder carrier is hidden from the agent list entirely, so neither
+// "reassign" nor "archive" is reachable. The way out is its Builder session.
+func TestDeleteRuntimeProfile_BuilderCarrierBlockerPointsAtItsSession(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ profileID := insertRuntimeProfileFixture(t, ctx, "Builder Held Profile", "codex", "builder-held")
+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "BUILDER-HOST", "codex")
+ createSystemFixtureAgent(t, ctx, runtimeID,
+ ".multica-agent-builder-flow1", "system", "agent_builder:flow1")
+
+ body := deleteProfileExpectingConflict(t, ctx, profileID)
+ msg := conflictMessage(t, body)
+
+ if strings.Contains(msg, "can be reassigned or archived") || strings.Contains(msg, "Reassign or archive them first.") {
+ t.Fatalf("a builder carrier is not in the agent list; refusal must not say so: %s", msg)
+ }
+ if !strings.Contains(msg, "Agent Builder session") {
+ t.Fatalf("refusal must point at the Builder session, got: %s", msg)
+ }
+
+ agents, _ := body["active_agents"].([]any)
+ entry, _ := agents[0].(map[string]any)
+ if got, _ := entry["system_key"].(string); got != "agent_builder:flow1" {
+ t.Fatalf("system_key = %q", got)
+ }
+}
+
+// With both kinds present each needs its own clause: the user agent is
+// actionable, the carrier is not, and collapsing them loses one or the other.
+func TestDeleteRuntimeProfile_MixedBlockersGiveEachItsOwnRemedy(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ profileID := insertRuntimeProfileFixture(t, ctx, "Mixed Held Profile", "codex", "mixed-held")
+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "MIXED-HOST", "codex")
+ _ = createCascadeFixtureAgent(t, ctx, runtimeID, "Ordinary Agent")
+ createSystemFixtureAgent(t, ctx, runtimeID, "Mika (mixed guard)", "user", "mika")
+ createSystemFixtureAgent(t, ctx, runtimeID,
+ ".multica-agent-builder-flow2", "system", "agent_builder:flow2")
+
+ body := deleteProfileExpectingConflict(t, ctx, profileID)
+ msg := conflictMessage(t, body)
+
+ for _, want := range []string{
+ "not marked as built into Multica can be reassigned or archived",
+ "Agent Builder session",
+ "Mika is built into Multica, so it cannot be archived",
+ } {
+ if !strings.Contains(msg, want) {
+ t.Fatalf("mixed refusal missing %q, got: %s", want, msg)
+ }
+ }
+ if got, _ := body["active_agent_count"].(float64); int(got) != 3 {
+ t.Fatalf("active_agent_count = %v, want 3", got)
+ }
+}
+
+// The response carries a bounded sample, not the profile's whole agent set:
+// this query runs inside the delete transaction with rows locked, and the
+// response is buffered whole before it is written.
+func TestDeleteRuntimeProfile_ActiveAgentResponseIsBounded(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ profileID := insertRuntimeProfileFixture(t, ctx, "Crowded Bounded Profile", "codex", "crowded-bounded")
+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "CROWDED-HOST", "codex")
+ total := maxReportedBlockingAgents + 7
+ for i := 0; i < total; i++ {
+ _ = createCascadeFixtureAgent(t, ctx, runtimeID, fmt.Sprintf("Crowd Agent %03d", i))
+ }
+
+ body := deleteProfileExpectingConflict(t, ctx, profileID)
+
+ agents, _ := body["active_agents"].([]any)
+ if len(agents) != maxReportedBlockingAgents {
+ t.Fatalf("active_agents = %d entries, want the cap %d", len(agents), maxReportedBlockingAgents)
+ }
+ // The exact size still has to reach the caller, or the cap would silently
+ // understate how much is bound to the profile.
+ if got, _ := body["active_agent_count"].(float64); int(got) != total {
+ t.Fatalf("active_agent_count = %v, want the true total %d", got, total)
+ }
+ if truncated, _ := body["active_agents_truncated"].(bool); !truncated {
+ t.Fatal("active_agents_truncated should be true when the sample is capped")
+ }
+ if msg := conflictMessage(t, body); !strings.Contains(msg,
+ fmt.Sprintf("and %d more", total-maxNamedBlockingAgents)) {
+ t.Fatalf("the sentence must count from the true total, got: %s", msg)
+ }
+}
+
+// An offline instance held by Mika alone hits the same trap as the profile
+// refusal: the generic clause does not fit, and here the destination is any
+// other runtime rather than one outside the profile.
+func TestDeleteAgentRuntime_OfflineInstanceHeldByMikaGetsMikasOwnRemedy(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID, _ := createProfileBackedRuntime(t, ctx, "Mika Held Machine")
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent_runtime SET status = 'offline' WHERE id = $1`, runtimeID); err != nil {
+ t.Fatalf("mark runtime offline: %v", err)
+ }
+ createSystemFixtureAgent(t, ctx, runtimeID, "Mika (instance guard)", "user", "mika")
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.DeleteAgentRuntime(w, req)
+
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+ msg := conflictMessage(t, decodeConflict(t, w))
+
+ if strings.Contains(msg, "can be reassigned or archived") || strings.Contains(msg, "Reassign or archive them first.") {
+ t.Fatalf("the generic reassign-or-archive clause does not apply to Mika: %s", msg)
+ }
+ if !strings.Contains(msg, "cannot be archived") {
+ t.Fatalf("instance refusal must still say Mika cannot be archived, got: %s", msg)
+ }
+ if !strings.Contains(msg, "bind it to another runtime") {
+ t.Fatalf("instance refusal must point at the rebind, got: %s", msg)
+ }
+ if strings.Contains(msg, "without any action from you") {
+ t.Fatalf("must not promise cleanup while Mika holds the runtime: %s", msg)
+ }
+}
+
+func deleteProfileExpectingConflict(t *testing.T, ctx context.Context, profileID string) map[string]any {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles/"+profileID, nil)
+ req = withURLParams(req, "id", testWorkspaceID, "profileId", profileID)
+ h := *testHandler
+ h.DaemonRuntimeGone = &recordingRuntimeGoneNotifier{}
+ h.DeleteRuntimeProfile(w, req)
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+ return decodeConflict(t, w)
+}
+
+// The remedies must come from the whole blocker set, not the sample. Sorting
+// puts the sample's contents outside the caller's control, so a class can fall
+// entirely past the cap: twenty ordinary agents that sort first push Mika to
+// position 21, and a message built from the sample would then tell the user to
+// archive all 21 — the exact unactionable instruction this change removes, just
+// deferred until they have worked through the first twenty.
+func TestDeleteRuntimeProfile_RemedyCoversBlockersBeyondTheSample(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ profileID := insertRuntimeProfileFixture(t, ctx, "Beyond Sample Profile", "codex", "beyond-sample")
+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "BEYOND-HOST", "codex")
+ // "Agent NNN" sorts before "Mika ...", filling the whole sample.
+ for i := 0; i < maxReportedBlockingAgents; i++ {
+ _ = createCascadeFixtureAgent(t, ctx, runtimeID, fmt.Sprintf("Agent %03d", i))
+ }
+ createSystemFixtureAgent(t, ctx, runtimeID, "Mika (beyond sample)", "user", "mika")
+
+ body := deleteProfileExpectingConflict(t, ctx, profileID)
+ msg := conflictMessage(t, body)
+
+ if !strings.Contains(msg, "Mika is built into Multica") {
+ t.Fatalf("Mika is blocker #21 and must still be reported, got: %s", msg)
+ }
+ if !strings.Contains(msg, "a runtime that this profile does not provide") {
+ t.Fatalf("the out-of-sample Mika must still get its real remedy, got: %s", msg)
+ }
+ if strings.Contains(msg, "Reassign or archive them first.") {
+ t.Fatalf("the blanket remedy must not cover a Mika the sample never showed: %s", msg)
+ }
+ if got, _ := body["active_agent_count"].(float64); int(got) != maxReportedBlockingAgents+1 {
+ t.Fatalf("active_agent_count = %v", got)
+ }
+}
+
+// Same boundary for a builder carrier: its remedy is a different surface
+// entirely, so losing it past the cap strands the user just as badly.
+func TestDeleteRuntimeProfile_BuilderCarrierBeyondTheSampleStillReported(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ profileID := insertRuntimeProfileFixture(t, ctx, "Beyond Sample Builder", "codex", "beyond-builder")
+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "BEYOND-BUILD-HOST", "codex")
+ for i := 0; i < maxReportedBlockingAgents; i++ {
+ _ = createCascadeFixtureAgent(t, ctx, runtimeID, fmt.Sprintf("Agent %03d", i))
+ }
+ // "zzz-" sorts last, so the carrier lands past the cap.
+ createSystemFixtureAgent(t, ctx, runtimeID,
+ "zzz-multica-agent-builder-flow9", "system", "agent_builder:flow9")
+
+ msg := conflictMessage(t, deleteProfileExpectingConflict(t, ctx, profileID))
+ if !strings.Contains(msg, "Agent Builder session") {
+ t.Fatalf("builder carrier is blocker #21 and must still be reported, got: %s", msg)
+ }
+}
+
+// The class mapping exists twice — the SQL CASE in ListActiveAgentsByProfile,
+// because per-class counts have to cover rows the LIMIT excludes, and
+// classifyBlockingAgent in Go for the instance path, which reads plain agent
+// rows. This pins them to each other: if a future system_key is added to one
+// and not the other, the refusal would name a remedy for the wrong blocker.
+func TestBlockingAgentClassMatchesSQLClassification(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ profileID := insertRuntimeProfileFixture(t, ctx, "Classifier Pin Profile", "codex", "classifier-pin")
+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "CLASSIFIER-HOST", "codex")
+
+ _ = createCascadeFixtureAgent(t, ctx, runtimeID, "Pin Ordinary")
+ createSystemFixtureAgent(t, ctx, runtimeID, "Pin Mika", "user", "mika")
+ createSystemFixtureAgent(t, ctx, runtimeID, "Pin Builder", "system", "agent_builder:pinflow")
+ createSystemFixtureAgent(t, ctx, runtimeID, "Pin Future", "system", "some_future_facility")
+ // Near misses for the builder prefix. '_' is a single-character wildcard in
+ // SQL LIKE, so a LIKE-based CASE classifies both of these as carriers while
+ // Go's HasPrefix does not — and the refusal would then send the user to an
+ // Agent Builder session that does not exist.
+ createSystemFixtureAgent(t, ctx, runtimeID, "Pin Dash", "system", "agent-builder:not-a-carrier")
+ createSystemFixtureAgent(t, ctx, runtimeID, "Pin Wildcard", "system", "agentXbuilder:not-a-carrier")
+
+ rows, err := testHandler.Queries.ListActiveAgentsByProfile(ctx, db.ListActiveAgentsByProfileParams{
+ ProfileID: parseUUID(profileID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ MaxRows: maxReportedBlockingAgents,
+ })
+ if err != nil {
+ t.Fatalf("list blockers: %v", err)
+ }
+ if len(rows) != 6 {
+ t.Fatalf("expected 6 blockers, got %d", len(rows))
+ }
+
+ for _, row := range rows {
+ fromSQL := blockingAgentClassFromKey(row.BlockerClass)
+ fromGo := classifyBlockingAgent(row.SystemKey)
+ if fromSQL != fromGo {
+ t.Fatalf("%q (system_key=%q): SQL says %q -> %v, Go says %v",
+ row.Name, row.SystemKey.String, row.BlockerClass, fromSQL, fromGo)
+ }
+ }
+
+ // And the per-class counts have to agree with the rows they summarise.
+ summary := rows[0]
+ for _, tc := range []struct {
+ name string
+ got int64
+ class blockingAgentClass
+ }{
+ {"user", summary.UserCount, blockingAgentUser},
+ {"mika", summary.MikaCount, blockingAgentMika},
+ {"agent_builder", summary.AgentBuilderCount, blockingAgentBuilderCarrier},
+ {"other_system", summary.OtherSystemCount, blockingAgentOtherSystem},
+ } {
+ var want int64
+ for _, row := range rows {
+ if classifyBlockingAgent(row.SystemKey) == tc.class {
+ want++
+ }
+ }
+ if tc.got != want {
+ t.Fatalf("%s_count = %d, rows of that class = %d", tc.name, tc.got, want)
+ }
+ }
+}
+
+// Retention GC needs both no bound agents AND no unfinished task. An agent
+// rebound to another machine can leave a deferred run pinned to the old
+// runtime, so "no agents bound" alone is not a cleanup promise this server can
+// keep. Regression contributed by review.
+func TestDeleteAgentRuntime_OfflineInstanceWithUnfinishedTaskDoesNotPromiseCleanup(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID, _ := createProfileBackedRuntime(t, ctx, "Review Retired Host")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Review Moved Agent")
+ issueID := dbfx.Issue(t, "Review deferred task")
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID, "issue_id": issueID, "status": "deferred",
+ "fire_at": testutil.Raw("now() + interval '30 days'"),
+ })
+ targetID := newTestRuntime(t, "Review New Host", "online")
+ w := httptest.NewRecorder()
+ testHandler.UpdateAgent(w, withURLParam(newRequest("PATCH", "/api/agents/"+agentID,
+ map[string]any{"runtime_id": targetID}), "id", agentID))
+ if w.Code != http.StatusOK {
+ t.Fatalf("rebind: %d %s", w.Code, w.Body.String())
+ }
+ dbfx.Exec(t, `UPDATE agent_runtime SET status='offline', last_seen_at=now()-interval '8 days' WHERE id=$1`, runtimeID)
+ var taskRuntime, taskStatus string
+ dbfx.QueryRow(t, `SELECT runtime_id::text, status FROM agent_task_queue WHERE id=$1`, taskID).Scan(&taskRuntime, &taskStatus)
+ if taskRuntime != runtimeID || taskStatus != "deferred" {
+ t.Fatalf("unexpected task after rebind: %s %s", taskRuntime, taskStatus)
+ }
+ rows, err := testHandler.Queries.ListStaleOfflineRuntimeGCCandidates(ctx, db.ListStaleOfflineRuntimeGCCandidatesParams{
+ StaleSeconds: service.OfflineRuntimeTTLSeconds, MaxPerTick: 10000,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, id := range rows {
+ if uuidToString(id) == runtimeID {
+ t.Fatal("GC unexpectedly allows runtime with deferred task")
+ }
+ }
+ for _, cascade := range []bool{false, true} {
+ w = httptest.NewRecorder()
+ if cascade {
+ r := newRequest("POST", "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete", map[string]any{"expected_active_agent_ids": []string{}})
+ testHandler.UnbindAgentsAndDeleteRuntime(w, withURLParam(r, "runtimeId", runtimeID))
+ } else {
+ testHandler.DeleteAgentRuntime(w, withURLParam(newRequest("DELETE", "/api/runtimes/"+runtimeID, nil), "runtimeId", runtimeID))
+ }
+ if w.Code != http.StatusConflict {
+ t.Fatalf("delete: %d %s", w.Code, w.Body.String())
+ }
+ body := decodeConflict(t, w)
+ msg := conflictMessage(t, body)
+ if body["active_agent_count"] != float64(0) {
+ t.Fatalf("expected no agent bindings: %#v", body)
+ }
+ if strings.Contains(msg, "without any action from you") {
+ t.Errorf("cascade=%v: GC excludes this 8-day-old runtime with a deferred task, but guidance promises cleanup: %s", cascade, msg)
+ }
+ }
+}
+
+// Builder sessions are creator-scoped reads, so an admin who is not the
+// creator gets 403 from list, switch and discard alike. Telling that admin to
+// reopen the session is another instruction they cannot carry out.
+// Regression contributed by review.
+func TestDeleteRuntimeProfile_BuilderRemedyAddressesTheSessionCreator(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ creatorID := dbfx.User(t, "Review Builder Owner", "[email protected]")
+ dbfx.Insert(t, "member", testutil.Cols{"workspace_id": testWorkspaceID, "user_id": creatorID, "role": "member"})
+ runtimeID, profileID := createProfileBackedRuntime(t, ctx, "Review Shared Builder Host")
+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility='public' WHERE id=$1`, runtimeID)
+ w := httptest.NewRecorder()
+ testHandler.CreateAgentBuilderSession(w, newRequestAs(creatorID, "POST", "/api/agent-builder/sessions", map[string]any{"runtime_id": runtimeID}))
+ if w.Code != http.StatusCreated {
+ t.Fatalf("create builder: %d %s", w.Code, w.Body.String())
+ }
+ var session CreateAgentBuilderSessionResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &session); err != nil {
+ t.Fatal(err)
+ }
+ dbfx.Exec(t, `INSERT INTO agent_builder_draft (chat_session_id, workspace_id, draft) VALUES ($1, $2, '{"name":"Saved draft"}'::jsonb)`, session.SessionID, testWorkspaceID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_builder_draft WHERE chat_session_id=$1`, session.SessionID)
+ })
+ msg := conflictMessage(t, deleteProfileExpectingConflict(t, ctx, profileID))
+ w = httptest.NewRecorder()
+ testHandler.ListAgentBuilderSessions(w, newRequest("GET", "/api/agent-builder/sessions", nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("list: %d %s", w.Code, w.Body.String())
+ }
+ if strings.Contains(w.Body.String(), session.SessionID) {
+ t.Fatal("other member's private session unexpectedly visible")
+ }
+ w = switchBuilderRuntime(t, session.SessionID, runtimeID)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("switch: %d %s", w.Code, w.Body.String())
+ }
+ w = httptest.NewRecorder()
+ r := withURLParam(newRequest("DELETE", "/api/chat/sessions/"+session.SessionID, nil), "sessionId", session.SessionID)
+ testHandler.DeleteChatSession(w, withChatTestWorkspaceCtx(t, r))
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("discard: %d %s", w.Code, w.Body.String())
+ }
+ if strings.Contains(msg, "reopen the session") && !strings.Contains(msg, "creator") && !strings.Contains(msg, "owner") {
+ t.Fatalf("admin cannot see, switch, or discard the member's Builder, but guidance tells the admin to reopen it: %s", msg)
+ }
+}
+
+// Forces the archive path's task-cancellation transaction to fail, which is
+// how a task is realistically left behind on an agent that then gets archived.
+type reviewArchiveCancelUnavailable struct{}
+
+func (reviewArchiveCancelUnavailable) Begin(context.Context) (pgx.Tx, error) {
+ return nil, errors.New("injected task cancellation database outage")
+}
+
+// Entering the GC candidate set is not the same as being deletable. gcRuntime
+// re-checks the drain across every user agent bound to the runtime, archived
+// ones included, before it calls teardown — and those agents can own tasks
+// pinned to a different machine. A refusal that only mirrored the candidate
+// query's runtime-owned predicate promised cleanup for a row the sweeper skips
+// on every pass. Regression contributed by review.
+func TestDeleteAgentRuntime_OfflineInstanceMatchesTheRealGCDrainGate(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID, _ := createProfileBackedRuntime(t, ctx, "Review Archived Agent Host")
+ otherID := newTestRuntime(t, "Review Original Task Host", "online")
+ agentID := createCascadeFixtureAgent(t, ctx, otherID, "Review Archived Agent")
+ issueID := dbfx.Issue(t, "Review cross-runtime deferred task")
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": otherID, "issue_id": issueID, "status": "deferred",
+ "fire_at": testutil.Raw("now() + interval '30 days'"),
+ })
+ w := httptest.NewRecorder()
+ testHandler.UpdateAgent(w, withURLParam(newRequest("PATCH", "/api/agents/"+agentID, map[string]any{"runtime_id": runtimeID}), "id", agentID))
+ if w.Code != http.StatusOK {
+ t.Fatalf("rebind: %d %s", w.Code, w.Body.String())
+ }
+ // The real archive handler commits archive first and only logs a failure
+ // of its subsequent task-cancellation transaction. It still returns 200.
+ h := *testHandler
+ h.TaskService = service.NewTaskService(testHandler.Queries, reviewArchiveCancelUnavailable{}, nil, nil)
+ w = httptest.NewRecorder()
+ h.ArchiveAgent(w, withURLParam(newRequest("POST", "/api/agents/"+agentID+"/archive", nil), "id", agentID))
+ if w.Code != http.StatusOK {
+ t.Fatalf("archive: %d %s", w.Code, w.Body.String())
+ }
+ dbfx.Exec(t, `UPDATE agent_runtime SET status='offline', last_seen_at=now()-interval '8 days' WHERE id=$1`, runtimeID)
+ var archived bool
+ var taskStatus string
+ dbfx.QueryRow(t, `SELECT archived_at IS NOT NULL FROM agent WHERE id=$1`, agentID).Scan(&archived)
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id=$1`, taskID).Scan(&taskStatus)
+ if !archived || taskStatus != "deferred" {
+ t.Fatalf("unexpected post-archive state: archived=%v task=%s", archived, taskStatus)
+ }
+
+ // Use the same agent set and final drain query as gcRuntime, after taking
+ // the runtime lock. The candidate filter alone is not the deletion gate.
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(ctx)
+ q := testHandler.Queries.WithTx(tx)
+ if _, err := q.LockAgentRuntime(ctx, parseUUID(runtimeID)); err != nil {
+ t.Fatal(err)
+ }
+ agents, err := q.ListUserAgentsByRuntimeForUpdate(ctx, parseUUID(runtimeID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ids := make([]pgtype.UUID, len(agents))
+ for i, a := range agents {
+ ids[i] = a.ID
+ }
+ undrained, err := q.CountUndrainedTasksByRuntimeOrAgent(ctx, db.CountUndrainedTasksByRuntimeOrAgentParams{RuntimeIds: []pgtype.UUID{parseUUID(runtimeID)}, AgentIds: ids})
+ if err != nil || undrained != 1 {
+ t.Fatalf("actual GC drain check = %d, err=%v", undrained, err)
+ }
+ if err := tx.Rollback(ctx); err != nil {
+ t.Fatal(err)
+ }
+ for _, cascade := range []bool{false, true} {
+ w = httptest.NewRecorder()
+ if cascade {
+ testHandler.UnbindAgentsAndDeleteRuntime(w, withURLParam(newRequest("POST", "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete", map[string]any{"expected_active_agent_ids": []string{}}), "runtimeId", runtimeID))
+ } else {
+ testHandler.DeleteAgentRuntime(w, withURLParam(newRequest("DELETE", "/api/runtimes/"+runtimeID, nil), "runtimeId", runtimeID))
+ }
+ if w.Code != http.StatusConflict {
+ t.Fatalf("delete: %d %s", w.Code, w.Body.String())
+ }
+ body := decodeConflict(t, w)
+ msg := conflictMessage(t, body)
+ if strings.Contains(msg, "without any action from you") {
+ t.Errorf("cascade=%v: actual GC drain count=1, but active_agent_count=%v undrained_task_count=%v: %s", cascade, body["active_agent_count"], body["undrained_task_count"], msg)
+ }
+ }
+}
+
+// The Mika clause makes two claims about product capability, and an earlier
+// version of it had the second one backwards — it said Mika could not be moved,
+// which told an owner who could have fixed the block in one edit to give up.
+// Both halves are therefore asserted against the real endpoints rather than
+// against anyone's reading of them, so the message cannot drift from the
+// product again. Correction contributed by review.
+func TestMikaRemedyMatchesWhatMikaCanDo(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ source, _ := createProfileBackedRuntime(t, ctx, "Mika Remedy Source")
+ target := newTestRuntime(t, "Mika Remedy Target", "online")
+ mikaID := createSystemFixtureAgent(t, ctx, source, "Mika", "user", "mika")
+
+ // Claim 1: Mika cannot be archived.
+ w := httptest.NewRecorder()
+ testHandler.ArchiveAgent(w, withURLParam(
+ newRequest("POST", "/api/agents/"+mikaID+"/archive", nil), "id", mikaID))
+ if w.Code == http.StatusOK {
+ t.Fatalf("Mika archived successfully; the refusal claims it cannot be: %s", w.Body.String())
+ }
+
+ // Claim 2: Mika can be rebound to another runtime.
+ w = httptest.NewRecorder()
+ testHandler.UpdateAgent(w, withURLParam(
+ newRequest("PATCH", "/api/agents/"+mikaID, map[string]any{"runtime_id": target}), "id", mikaID))
+ if w.Code != http.StatusOK {
+ t.Fatalf("rebinding Mika failed (%d), but the refusal tells the user to do it: %s",
+ w.Code, w.Body.String())
+ }
+ var bound string
+ if err := testPool.QueryRow(ctx,
+ `SELECT runtime_id::text FROM agent WHERE id = $1`, mikaID).Scan(&bound); err != nil {
+ t.Fatalf("read mika binding: %v", err)
+ }
+ if bound != target {
+ t.Fatalf("Mika still bound to %s, expected the move to %s to take effect", bound, target)
+ }
+
+ // And the move is what actually clears the instance refusal.
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent_runtime SET status = 'offline' WHERE id = $1`, source); err != nil {
+ t.Fatalf("mark source offline: %v", err)
+ }
+ w = httptest.NewRecorder()
+ testHandler.DeleteAgentRuntime(w, withURLParam(
+ newRequest("DELETE", "/api/runtimes/"+source, nil), "runtimeId", source))
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+ body := decodeConflict(t, w)
+ if got, _ := body["active_agent_count"].(float64); int(got) != 0 {
+ t.Fatalf("after the rebind the source should hold no agents, got %v", got)
+ }
+ if msg := conflictMessage(t, body); strings.Contains(msg, "Mika is built into Multica") {
+ t.Fatalf("Mika moved away but is still named as a blocker: %s", msg)
+ }
+}
diff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.go
index c76ebf13d1..8adb4b62a3 100644
--- a/server/internal/handler/runtime_profile.go
+++ b/server/internal/handler/runtime_profile.go
@@ -3,6 +3,7 @@ package handler
import (
"encoding/json"
"errors"
+ "fmt"
"log/slog"
"net/http"
"strings"
@@ -340,6 +341,114 @@ func (h *Handler) UpdateRuntimeProfile(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, runtimeProfileToResponse(profile))
}
+// maxNamedBlockingAgents caps how many agents the refusal spells out before it
+// falls back to a count. Enough to recognise the machine they sit on without
+// turning a CLI error into a wall of text.
+const maxNamedBlockingAgents = 5
+
+// maxReportedBlockingAgents caps both the rows read inside the delete
+// transaction and the entries put on the response. A profile accumulates agents
+// across every machine that registered it, and neither the sentence nor any
+// client needs the whole set to do its job — the exact size travels separately
+// as active_agent_count.
+const maxReportedBlockingAgents = 20
+
+// profileDeleteBlockedByAgents explains which agents are keeping this profile
+// alive and, crucially, which machine each one is on.
+//
+// A profile is workspace-wide, so its bound agents are frequently on a
+// different machine than the stale instance the user is actually trying to
+// clean up. The old message said only "active agents are still bound to its
+// runtimes", which left that user with no way to tell whether the blocker was
+// the dead machine or the healthy one — and the natural next move, unbinding
+// agents that were working fine, is exactly the damage worth preventing
+// (GH #8456).
+// agents is the bounded sample the query returned; its first row carries the
+// full-set totals every caller here needs.
+//
+// The recovery paths come from those totals, never from the sample. Which rows
+// survive the LIMIT is arbitrary with respect to class — twenty ordinary agents
+// sorting first push the one Mika to position 21 — so advice derived from the
+// visible rows would tell the user to archive blockers that cannot be archived,
+// which is the defect this whole change set removes.
+func profileDeleteBlockedByAgents(profileName string, agents []db.ListActiveAgentsByProfileRow) map[string]any {
+ if len(agents) == 0 {
+ // Caller only builds a refusal when there is at least one blocker.
+ return map[string]any{
+ "error": "cannot delete this custom runtime profile: active agents are still bound to its runtimes.",
+ "code": "runtime_profile_has_active_agents",
+ }
+ }
+ summary := agents[0]
+ total := summary.TotalCount
+
+ classes := map[blockingAgentClass]bool{
+ blockingAgentUser: summary.UserCount > 0,
+ blockingAgentMika: summary.MikaCount > 0,
+ blockingAgentBuilderCarrier: summary.AgentBuilderCount > 0,
+ blockingAgentOtherSystem: summary.OtherSystemCount > 0,
+ }
+
+ named := make([]string, 0, maxNamedBlockingAgents)
+ for _, a := range agents {
+ class := blockingAgentClassFromKey(a.BlockerClass)
+ if len(named) >= maxNamedBlockingAgents {
+ continue
+ }
+ runtimeName := a.RuntimeName
+ if a.RuntimeCustomName.Valid && strings.TrimSpace(a.RuntimeCustomName.String) != "" {
+ runtimeName = a.RuntimeCustomName.String
+ }
+ named = append(named, blockingAgentLabel(a.Name, runtimeName, a.RuntimeStatus, class))
+ }
+ listed := strings.Join(named, ", ")
+ if remaining := total - int64(len(named)); remaining > 0 {
+ listed = fmt.Sprintf("%s, and %d more", listed, remaining)
+ }
+
+ subject := "this custom runtime profile"
+ if strings.TrimSpace(profileName) != "" {
+ subject = fmt.Sprintf("the custom runtime profile %q", profileName)
+ }
+
+ remedies := blockingAgentRemedies(classes, blockingAgentScopeProfile)
+ if len(remedies) == 0 {
+ remedies = []string{"None of them can be released from here."}
+ }
+
+ resp := make([]map[string]any, len(agents))
+ for i, a := range agents {
+ resp[i] = map[string]any{
+ "id": uuidToString(a.ID),
+ "name": a.Name,
+ "kind": a.Kind,
+ "system_key": textToPtr(a.SystemKey),
+ "runtime_id": uuidToString(a.RuntimeID),
+ "runtime_name": a.RuntimeName,
+ // Deliberately separate from runtime_name: a client that renders
+ // its own copy shows custom_name ?? name, same as everywhere else.
+ "runtime_custom_name": textToPtr(a.RuntimeCustomName),
+ "runtime_status": a.RuntimeStatus,
+ }
+ }
+
+ sentences := append([]string{fmt.Sprintf(
+ "cannot delete %s: %d active agent(s) are still bound to its runtimes — %s.",
+ subject, total, listed,
+ )}, remedies...)
+ sentences = append(sentences,
+ "Deleting this profile removes its runtime on every machine that registered it, so agents on a machine you did not intend to touch will be affected too.")
+
+ return map[string]any{
+ "error": strings.Join(sentences, " "),
+ "code": "runtime_profile_has_active_agents",
+ "active_agents": resp,
+ // The sample above is capped; this is the real number.
+ "active_agent_count": total,
+ "active_agents_truncated": total > int64(len(resp)),
+ }
+}
+
// DeleteRuntimeProfile removes a profile and, in the same transaction, the
// agent_runtime instance rows registered against it. Migration 120 dropped the
// DB ON DELETE CASCADE, so this app-layer cleanup is what prevents orphaned
@@ -381,7 +490,7 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {
// a conflicting KEY SHARE lock in its own transaction, so it cannot insert
// a runtime after the plan and have that row escape deletion. If the profile
// row is already gone, still clean up any orphaned profile_id rows.
- _, profileErr := qtx.LockRuntimeProfileForDelete(r.Context(), db.LockRuntimeProfileForDeleteParams{
+ profile, profileErr := qtx.LockRuntimeProfileForDelete(r.Context(), db.LockRuntimeProfileForDeleteParams{
ID: profileUUID,
WorkspaceID: wsUUID,
})
@@ -413,16 +522,23 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {
}
}
- agentCount, err := qtx.CountAgentsByProfile(r.Context(), db.CountAgentsByProfileParams{
+ // Bounded read: the guard only needs "is there at least one", and the
+ // refusal needs a few names plus the exact total, which rides on each row.
+ blockingAgents, err := qtx.ListActiveAgentsByProfile(r.Context(), db.ListActiveAgentsByProfileParams{
ProfileID: profileUUID,
WorkspaceID: wsUUID,
+ MaxRows: maxReportedBlockingAgents,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to check profile usage")
return
}
- if agentCount > 0 {
- writeError(w, http.StatusConflict, "cannot delete runtime profile: active agents are still bound to its runtimes")
+ if len(blockingAgents) > 0 {
+ profileName := profile.DisplayName
+ if profileMissing {
+ profileName = ""
+ }
+ writeJSON(w, http.StatusConflict, profileDeleteBlockedByAgents(profileName, blockingAgents))
return
}
diff --git a/server/internal/service/runtime_teardown.go b/server/internal/service/runtime_teardown.go
index 5079fe066f..9aa1c1ac37 100644
--- a/server/internal/service/runtime_teardown.go
+++ b/server/internal/service/runtime_teardown.go
@@ -9,6 +9,20 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
+// OfflineRuntimeTTLSeconds is how long an offline runtime is kept before
+// retention GC deletes it, once no active agent and no non-terminal task
+// remain on it. GC applies this to every runtime row, including the
+// profile-backed ones the interactive delete endpoints refuse — so those
+// refusal messages quote this same number to tell the user when the row they
+// cannot delete will disappear on its own. Keeping one constant is what stops
+// that promise from drifting away from the sweeper that has to honour it.
+const OfflineRuntimeTTLSeconds = 7 * 24 * 3600.0
+
+// OfflineRuntimeTTLDays renders OfflineRuntimeTTLSeconds for user-facing copy.
+func OfflineRuntimeTTLDays() int {
+ return int(OfflineRuntimeTTLSeconds / 86400)
+}
+
var (
// ErrRuntimeNotDrained means a runtime or one of its bound user agents
// still owns a non-terminal task. Callers must abort the transaction rather
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index b0cccb32ee..f0a7cacad7 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -6312,6 +6312,39 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
return items, nil
}
+const listUserAgentIDsByRuntime = `-- name: ListUserAgentIDsByRuntime :many
+SELECT id FROM agent
+WHERE runtime_id = $1 AND kind = 'user'
+ORDER BY id
+`
+
+// Non-locking companion to ListUserAgentsByRuntimeForUpdate, for callers that
+// must reason about retention GC without taking the teardown's locks.
+//
+// Archived rows are included deliberately, and that is the whole point: an
+// archived agent can still own a non-terminal task, and gcRuntime counts those
+// before it will delete a runtime. A read that filtered them would report a
+// runtime as reclaimable when the sweeper is going to skip it.
+func (q *Queries) ListUserAgentIDsByRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listUserAgentIDsByRuntime, runtimeID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var id pgtype.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ items = append(items, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listUserAgentsByRuntimeForUpdate = `-- name: ListUserAgentsByRuntimeForUpdate :many
SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent
WHERE runtime_id = $1 AND kind = 'user'
diff --git a/server/pkg/db/generated/runtime_profile.sql.go b/server/pkg/db/generated/runtime_profile.sql.go
index 12cf9cd540..2dbdc6447c 100644
--- a/server/pkg/db/generated/runtime_profile.sql.go
+++ b/server/pkg/db/generated/runtime_profile.sql.go
@@ -11,27 +11,6 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
-const countAgentsByProfile = `-- name: CountAgentsByProfile :one
-SELECT count(*) FROM agent a
-JOIN agent_runtime ar ON ar.id = a.runtime_id
-WHERE ar.profile_id = $1 AND ar.workspace_id = $2 AND a.archived_at IS NULL
-`
-
-type CountAgentsByProfileParams struct {
- ProfileID pgtype.UUID `json:"profile_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
-}
-
-// Counts active (non-archived) agents bound to any runtime instance of this
-// profile. The profile-delete path uses this to refuse deletion (409) while
-// agents still depend on it, mirroring the runtime-delete guard.
-func (q *Queries) CountAgentsByProfile(ctx context.Context, arg CountAgentsByProfileParams) (int64, error) {
- row := q.db.QueryRow(ctx, countAgentsByProfile, arg.ProfileID, arg.WorkspaceID)
- var count int64
- err := row.Scan(&count)
- return count, err
-}
-
const createRuntimeProfile = `-- name: CreateRuntimeProfile :one
INSERT INTO runtime_profile (
@@ -212,6 +191,148 @@ func (q *Queries) GetRuntimeProfileForWorkspace(ctx context.Context, arg GetRunt
return i, err
}
+const listActiveAgentsByProfile = `-- name: ListActiveAgentsByProfile :many
+WITH blockers AS (
+ SELECT
+ a.id,
+ a.name,
+ a.kind,
+ a.system_key,
+ ar.id AS runtime_id,
+ ar.name AS runtime_name,
+ ar.custom_name AS runtime_custom_name,
+ ar.status AS runtime_status,
+ CASE
+ WHEN a.system_key IS NULL OR btrim(a.system_key) = '' THEN 'user'
+ WHEN btrim(a.system_key) = 'mika' THEN 'mika'
+ -- starts_with, not LIKE: '_' is a single-character wildcard in
+ -- LIKE, so 'agent_builder:%' also matches 'agent-builder:x' and
+ -- 'agentXbuilder:x'. Those would be classified here as carriers
+ -- and by the Go side as other_system, and the refusal would send
+ -- the user to an Agent Builder session that does not exist.
+ WHEN starts_with(btrim(a.system_key), 'agent_builder:') THEN 'agent_builder'
+ ELSE 'other_system'
+ END AS blocker_class
+ FROM agent a
+ JOIN agent_runtime ar ON ar.id = a.runtime_id
+ WHERE ar.profile_id = $1 AND ar.workspace_id = $2 AND a.archived_at IS NULL
+)
+SELECT
+ id,
+ name,
+ kind,
+ system_key,
+ runtime_id,
+ runtime_name,
+ runtime_custom_name,
+ runtime_status,
+ blocker_class,
+ count(*) OVER () AS total_count,
+ count(*) FILTER (WHERE blocker_class = 'user') OVER () AS user_count,
+ count(*) FILTER (WHERE blocker_class = 'mika') OVER () AS mika_count,
+ count(*) FILTER (WHERE blocker_class = 'agent_builder') OVER () AS agent_builder_count,
+ count(*) FILTER (WHERE blocker_class = 'other_system') OVER () AS other_system_count
+FROM blockers
+ORDER BY runtime_name ASC, name ASC
+LIMIT $3::int
+`
+
+type ListActiveAgentsByProfileParams struct {
+ ProfileID pgtype.UUID `json:"profile_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ MaxRows int32 `json:"max_rows"`
+}
+
+type ListActiveAgentsByProfileRow struct {
+ ID pgtype.UUID `json:"id"`
+ Name string `json:"name"`
+ Kind string `json:"kind"`
+ SystemKey pgtype.Text `json:"system_key"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ RuntimeName string `json:"runtime_name"`
+ RuntimeCustomName pgtype.Text `json:"runtime_custom_name"`
+ RuntimeStatus string `json:"runtime_status"`
+ BlockerClass string `json:"blocker_class"`
+ TotalCount int64 `json:"total_count"`
+ UserCount int64 `json:"user_count"`
+ MikaCount int64 `json:"mika_count"`
+ AgentBuilderCount int64 `json:"agent_builder_count"`
+ OtherSystemCount int64 `json:"other_system_count"`
+}
+
+// Active (non-archived) agents bound to any runtime instance of this profile.
+// The profile-delete path uses this to refuse deletion (409) while agents
+// still depend on it, mirroring the runtime-delete guard.
+//
+// It returns the rows rather than a count because the refusal has to name
+// them: a profile spans every machine that registered it, so the agents
+// blocking the delete are routinely bound to a different machine than the one
+// the user was trying to clean up, and a bare count gives them no way to tell
+// (GH #8456). Carrying the runtime is what lets the message say which machine.
+//
+// Deliberately not filtered by kind: it defines when deletion is refused, and
+// narrowing it to user agents here would let a profile with a bound builder
+// carrier through, whereupon TeardownRuntime would hard-delete that carrier.
+//
+// system_key rides along because it, not kind, decides what the user can
+// actually do about a blocker. Mika is kind='user' with system_key='mika' and
+// can be neither archived nor moved; a builder carrier is kind='system' and is
+// released by its Builder session, not from the agent list.
+//
+// Bounded on purpose. The caller only needs to know that blockers exist, name a
+// few, and report how many there are — it never needs every row. This runs
+// inside the delete transaction while profile, runtime and agent rows are
+// locked, and the response is buffered whole before it is written, so an
+// unbounded read here would make both the time under lock and the response body
+// grow with the number of agents a profile has accumulated across machines.
+//
+// The per-class counts are what let the refusal stay correct while bounded.
+// Rows are ordered by machine and name, so which blockers land inside the LIMIT
+// is arbitrary with respect to class: twenty ordinary agents can push the one
+// Mika to position 21. A message whose advice came from the visible rows would
+// then tell the user to archive all of them — the unactionable instruction this
+// whole change removes, just deferred. So the recovery paths are chosen from
+// these counts and only the names come from the rows.
+//
+// Every count is a window function over the pre-LIMIT result, so they stay
+// exact no matter how small max_rows is. blocker_class is emitted per row as
+// well, giving the classification one definition that the Go classifier is
+// pinned against in tests.
+func (q *Queries) ListActiveAgentsByProfile(ctx context.Context, arg ListActiveAgentsByProfileParams) ([]ListActiveAgentsByProfileRow, error) {
+ rows, err := q.db.Query(ctx, listActiveAgentsByProfile, arg.ProfileID, arg.WorkspaceID, arg.MaxRows)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListActiveAgentsByProfileRow{}
+ for rows.Next() {
+ var i ListActiveAgentsByProfileRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.Name,
+ &i.Kind,
+ &i.SystemKey,
+ &i.RuntimeID,
+ &i.RuntimeName,
+ &i.RuntimeCustomName,
+ &i.RuntimeStatus,
+ &i.BlockerClass,
+ &i.TotalCount,
+ &i.UserCount,
+ &i.MikaCount,
+ &i.AgentBuilderCount,
+ &i.OtherSystemCount,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listAgentRuntimeIDsByProfile = `-- name: ListAgentRuntimeIDsByProfile :many
SELECT id FROM agent_runtime
WHERE profile_id = $1 AND workspace_id = $2
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index d6224e5170..953dc368b6 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -257,6 +257,18 @@ WHERE runtime_id = $1 AND archived_at IS NULL AND kind = 'user'
ORDER BY name ASC
FOR UPDATE;
+-- name: ListUserAgentIDsByRuntime :many
+-- Non-locking companion to ListUserAgentsByRuntimeForUpdate, for callers that
+-- must reason about retention GC without taking the teardown's locks.
+--
+-- Archived rows are included deliberately, and that is the whole point: an
+-- archived agent can still own a non-terminal task, and gcRuntime counts those
+-- before it will delete a runtime. A read that filtered them would report a
+-- runtime as reclaimable when the sweeper is going to skip it.
+SELECT id FROM agent
+WHERE runtime_id = $1 AND kind = 'user'
+ORDER BY id;
+
-- name: ListUserAgentsByRuntimeForUpdate :many
-- Locks active AND archived user agents before a runtime teardown. Locking only
-- the active snapshot leaves a restore race: an archived row can become active
diff --git a/server/pkg/db/queries/runtime_profile.sql b/server/pkg/db/queries/runtime_profile.sql
index c7ab935b63..84691d19fb 100644
--- a/server/pkg/db/queries/runtime_profile.sql
+++ b/server/pkg/db/queries/runtime_profile.sql
@@ -81,13 +81,88 @@ DELETE FROM agent_runtime
WHERE profile_id = $1 AND workspace_id = $2
RETURNING id, workspace_id, owner_id, daemon_id, provider;
--- name: CountAgentsByProfile :one
--- Counts active (non-archived) agents bound to any runtime instance of this
--- profile. The profile-delete path uses this to refuse deletion (409) while
--- agents still depend on it, mirroring the runtime-delete guard.
-SELECT count(*) FROM agent a
-JOIN agent_runtime ar ON ar.id = a.runtime_id
-WHERE ar.profile_id = $1 AND ar.workspace_id = $2 AND a.archived_at IS NULL;
+-- name: ListActiveAgentsByProfile :many
+-- Active (non-archived) agents bound to any runtime instance of this profile.
+-- The profile-delete path uses this to refuse deletion (409) while agents
+-- still depend on it, mirroring the runtime-delete guard.
+--
+-- It returns the rows rather than a count because the refusal has to name
+-- them: a profile spans every machine that registered it, so the agents
+-- blocking the delete are routinely bound to a different machine than the one
+-- the user was trying to clean up, and a bare count gives them no way to tell
+-- (GH #8456). Carrying the runtime is what lets the message say which machine.
+--
+-- Deliberately not filtered by kind: it defines when deletion is refused, and
+-- narrowing it to user agents here would let a profile with a bound builder
+-- carrier through, whereupon TeardownRuntime would hard-delete that carrier.
+--
+-- system_key rides along because it, not kind, decides what the user can
+-- actually do about a blocker. Mika is kind='user' with system_key='mika' and
+-- can be neither archived nor moved; a builder carrier is kind='system' and is
+-- released by its Builder session, not from the agent list.
+--
+-- Bounded on purpose. The caller only needs to know that blockers exist, name a
+-- few, and report how many there are — it never needs every row. This runs
+-- inside the delete transaction while profile, runtime and agent rows are
+-- locked, and the response is buffered whole before it is written, so an
+-- unbounded read here would make both the time under lock and the response body
+-- grow with the number of agents a profile has accumulated across machines.
+--
+-- The per-class counts are what let the refusal stay correct while bounded.
+-- Rows are ordered by machine and name, so which blockers land inside the LIMIT
+-- is arbitrary with respect to class: twenty ordinary agents can push the one
+-- Mika to position 21. A message whose advice came from the visible rows would
+-- then tell the user to archive all of them — the unactionable instruction this
+-- whole change removes, just deferred. So the recovery paths are chosen from
+-- these counts and only the names come from the rows.
+--
+-- Every count is a window function over the pre-LIMIT result, so they stay
+-- exact no matter how small max_rows is. blocker_class is emitted per row as
+-- well, giving the classification one definition that the Go classifier is
+-- pinned against in tests.
+WITH blockers AS (
+ SELECT
+ a.id,
+ a.name,
+ a.kind,
+ a.system_key,
+ ar.id AS runtime_id,
+ ar.name AS runtime_name,
+ ar.custom_name AS runtime_custom_name,
+ ar.status AS runtime_status,
+ CASE
+ WHEN a.system_key IS NULL OR btrim(a.system_key) = '' THEN 'user'
+ WHEN btrim(a.system_key) = 'mika' THEN 'mika'
+ -- starts_with, not LIKE: '_' is a single-character wildcard in
+ -- LIKE, so 'agent_builder:%' also matches 'agent-builder:x' and
+ -- 'agentXbuilder:x'. Those would be classified here as carriers
+ -- and by the Go side as other_system, and the refusal would send
+ -- the user to an Agent Builder session that does not exist.
+ WHEN starts_with(btrim(a.system_key), 'agent_builder:') THEN 'agent_builder'
+ ELSE 'other_system'
+ END AS blocker_class
+ FROM agent a
+ JOIN agent_runtime ar ON ar.id = a.runtime_id
+ WHERE ar.profile_id = $1 AND ar.workspace_id = $2 AND a.archived_at IS NULL
+)
+SELECT
+ id,
+ name,
+ kind,
+ system_key,
+ runtime_id,
+ runtime_name,
+ runtime_custom_name,
+ runtime_status,
+ blocker_class,
+ count(*) OVER () AS total_count,
+ count(*) FILTER (WHERE blocker_class = 'user') OVER () AS user_count,
+ count(*) FILTER (WHERE blocker_class = 'mika') OVER () AS mika_count,
+ count(*) FILTER (WHERE blocker_class = 'agent_builder') OVER () AS agent_builder_count,
+ count(*) FILTER (WHERE blocker_class = 'other_system') OVER () AS other_system_count
+FROM blockers
+ORDER BY runtime_name ASC, name ASC
+LIMIT @max_rows::int;
-- name: ListAgentRuntimeIDsByProfile :many
-- Enumerates the runtime instance rows registered against a profile. The