Skip to content

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

Go

feat(runtime): unbind agents on runtime delete instead of destroying them (#6220)

Multica Eveb06af2ae1748
diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdx
index c92f42751a..96e47b6617 100644
--- a/apps/docs/content/docs/cli.ja.mdx
+++ b/apps/docs/content/docs/cli.ja.mdx
@@ -154,7 +154,7 @@ multica runtime usage <runtime-id>
multica runtime activity <runtime-id>
```
-アクティブなエージェントがまだ紐付いているランタイムの削除は、デフォルトで拒否されます。`multica runtime delete <id> --cascade` は、それらのエージェントをアーカイブし、アクティブなタスクもキャンセルします。
+アクティブなエージェントがまだ紐付いているランタイムの削除は、デフォルトで拒否されます。`multica runtime delete <id> --cascade` は、それらのエージェントをランタイムから解除して設定と履歴を保持し、アクティブなタスクをキャンセルします。
仕組みとカスタムプロファイルについては[デーモンとランタイム](/daemon-runtimes)を参照してください。
@@ -279,7 +279,7 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで
| | `stop` / `status` / `restart` | 停止、状態の確認、再起動(`restart` は `start` と同じフラグ) | |
| | `logs` | デーモンのログを表示 | `--follow`、`--lines` |
| | `disk-usage` | ローカルのディスク使用量を表示 | `--by-workspace`、`--by-task`、`--top` |
-| `runtime` | `list/usage/activity/update/rename/delete` | ランタイムを表示・管理 | `delete`: `--cascade`(紐付くエージェントをアーカイブし、そのタスクもキャンセル) |
+| `runtime` | `list/usage/activity/update/rename/delete` | ランタイムを表示・管理 | `delete`: `--cascade`(紐付くエージェントを解除してデータを保持し、そのタスクをキャンセル) |
| | `profile list/create/update/delete` | カスタムランタイムプロファイルを管理 | |
| | `profile set-path/unset-path <profile-id>` | ローカルの実行ファイルパスを固定(ローカルのみ有効。サーバーには送信されません) | |
diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdx
index f499c1369b..1d23c7e3db 100644
--- a/apps/docs/content/docs/cli.ko.mdx
+++ b/apps/docs/content/docs/cli.ko.mdx
@@ -154,7 +154,7 @@ multica runtime usage <runtime-id>
multica runtime activity <runtime-id>
```
-활성 에이전트가 계속 연결된 런타임을 삭제하면 명령이 기본적으로 거부됩니다. `multica runtime delete <id> --cascade`는 연결된 에이전트도 함께 보관하고 활성 태스크를 취소합니다.
+활성 에이전트가 계속 연결된 런타임을 삭제하면 명령이 기본적으로 거부됩니다. `multica runtime delete <id> --cascade`는 에이전트의 런타임 연결을 해제하고 설정과 기록을 보존하며 활성 태스크를 취소합니다.
실행 메커니즘과 사용자 지정 profile은 [데몬과 런타임](/daemon-runtimes)을 참고하세요.
@@ -279,7 +279,7 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t
| | `stop` / `status` / `restart` | 중지, 상태 확인, 다시 시작(`restart`와 `start`의 flag가 같음) | |
| | `logs` | 데몬 로그 확인 | `--follow`, `--lines` |
| | `disk-usage` | 로컬 디스크 사용량 확인 | `--by-workspace`, `--by-task`, `--top` |
-| `runtime` | `list/usage/activity/update/rename/delete` | 런타임 확인 및 관리 | `delete`: `--cascade`(연결된 에이전트도 보관하고 해당 태스크 취소) |
+| `runtime` | `list/usage/activity/update/rename/delete` | 런타임 확인 및 관리 | `delete`: `--cascade`(연결된 에이전트의 런타임을 해제하고 데이터를 보존하며 태스크 취소) |
| | `profile list/create/update/delete` | 사용자 지정 런타임 profile 관리 | |
| | `profile set-path/unset-path <profile-id>` | 로컬 실행 파일 경로 고정(로컬에만 적용되고 서버에 업로드되지 않음) | |
diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdx
index 59f0cac6f5..9204307bb6 100644
--- a/apps/docs/content/docs/cli.mdx
+++ b/apps/docs/content/docs/cli.mdx
@@ -154,7 +154,7 @@ multica runtime usage <runtime-id>
multica runtime activity <runtime-id>
```
-Deleting a runtime that still has active agents bound to it is refused by default. `multica runtime delete <id> --cascade` also archives those agents and cancels their active tasks.
+Deleting a runtime that still has active agents bound to it is refused by default. `multica runtime delete <id> --cascade` unbinds those agents, preserves their configuration and history, and cancels their active tasks.
See [Daemon and runtimes](/daemon-runtimes) for how it works and for custom profiles.
@@ -279,7 +279,7 @@ The tables below cover every current top-level command, grouped the way the CLI
| | `stop` / `status` / `restart` | Stop, check status, restart (`restart` takes the same flags as `start`) | |
| | `logs` | View daemon logs | `--follow`, `--lines` |
| | `disk-usage` | View local disk usage | `--by-workspace`, `--by-task`, `--top` |
-| `runtime` | `list/usage/activity/update/rename/delete` | View and manage runtimes | `delete`: `--cascade` (also archives bound agents and cancels their tasks) |
+| `runtime` | `list/usage/activity/update/rename/delete` | View and manage runtimes | `delete`: `--cascade` (unbinds bound agents, preserves their data, and cancels their tasks) |
| | `profile list/create/update/delete` | Manage custom runtime profiles | |
| | `profile set-path/unset-path <profile-id>` | Pin a local executable path (local only, never uploaded to the server) | |
diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdx
index 5f172a3eb3..694ef84c28 100644
--- a/apps/docs/content/docs/cli.zh.mdx
+++ b/apps/docs/content/docs/cli.zh.mdx
@@ -154,7 +154,7 @@ multica runtime usage <runtime-id>
multica runtime activity <runtime-id>
```
-删除仍绑定活跃智能体的运行时时,命令默认拒绝。`multica runtime delete <id> --cascade` 会同时归档这些智能体并取消它们的活动 task。
+删除仍绑定活跃智能体的运行时时,命令默认拒绝。`multica runtime delete <id> --cascade` 会解绑这些智能体、保留其配置与历史记录,并取消它们的活动 task。
运行机制和自定义 profile 见[守护进程与运行时](/daemon-runtimes)。
@@ -279,7 +279,7 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓
| | `stop` / `status` / `restart` | 停止、查看状态、重启(`restart` 与 `start` 同一套 flag) | |
| | `logs` | 查看守护进程日志 | `--follow`、`--lines` |
| | `disk-usage` | 查看本机磁盘占用 | `--by-workspace`、`--by-task`、`--top` |
-| `runtime` | `list/usage/activity/update/rename/delete` | 查看和管理运行时 | `delete`:`--cascade`(同时归档绑定的智能体并取消其 task) |
+| `runtime` | `list/usage/activity/update/rename/delete` | 查看和管理运行时 | `delete`:`--cascade`(解绑绑定的智能体、保留其数据并取消其 task) |
| | `profile list/create/update/delete` | 管理自定义运行时 profile | |
| | `profile set-path/unset-path <profile-id>` | 固定本机可执行文件路径(仅本地生效,不上传服务器) | |
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
index 5f43d6f01a..474c3424bf 100644
--- a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
+++ b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
@@ -79,7 +79,9 @@ import { ChatComposer } from "@/components/chat/chat-composer";
import { AgentPickerSheet } from "@/components/chat/agent-picker-sheet";
import { NoAgentBanner } from "@/components/chat/no-agent-banner";
import { OfflineBanner } from "@/components/chat/offline-banner";
+import { RuntimeRequiredBanner } from "@/components/chat/runtime-required-banner";
import { useChatSelectStore } from "@/data/chat-select-store";
+import { isAgentRuntimeBound } from "@/lib/is-agent-runtime-bound";
export default function ChatTab() {
const qc = useQueryClient();
@@ -176,6 +178,8 @@ export default function ChatTab() {
const presenceAvailability =
presenceDetail === "loading" ? undefined : presenceDetail.availability;
const isArchived = activeSession?.status === "archived";
+ const runtimeBound =
+ currentAgent !== null && isAgentRuntimeBound(currentAgent);
const sending = !!pendingTask?.task_id;
// ── Drafts ─────────────────────────────────────────────────────────────
@@ -245,6 +249,13 @@ export default function ChatTab() {
options: { clearDraft?: boolean } = {},
) => {
if (!currentAgent) return;
+ if (!runtimeBound) {
+ Alert.alert(
+ "Runtime required",
+ "Bind a runtime to this agent on web or desktop before sending a message.",
+ );
+ return;
+ }
const isNewSession = !activeSessionId;
const sessionId = await ensureSession(content);
@@ -296,6 +307,7 @@ export default function ChatTab() {
[
activeSessionId,
currentAgent,
+ runtimeBound,
ensureSession,
qc,
promoteNewDraft,
@@ -359,13 +371,18 @@ export default function ChatTab() {
// ── Composer disabled-state ────────────────────────────────────────────
const disabled =
- !currentAgent || availability === "none" || isArchived === true;
+ !currentAgent ||
+ availability === "none" ||
+ isArchived === true ||
+ !runtimeBound;
const disabledReason = !currentAgent
? "No agent selected"
: availability === "none"
? "No agents in this workspace"
: isArchived
? "This chat is archived"
+ : !runtimeBound
+ ? "Agent needs a runtime"
: undefined;
return (
@@ -411,10 +428,14 @@ export default function ChatTab() {
liveTaskMessages={liveTaskMessages}
availability={presenceAvailability}
/>
- <OfflineBanner
- agentName={currentAgent?.name}
- availability={presenceAvailability}
- />
+ {runtimeBound ? (
+ <OfflineBanner
+ agentName={currentAgent?.name}
+ availability={presenceAvailability}
+ />
+ ) : currentAgent ? (
+ <RuntimeRequiredBanner agentName={currentAgent.name} />
+ ) : null}
<ChatComposer
value={draft}
onChangeText={(next) => setDraft(draftKey, next)}
diff --git a/apps/mobile/components/chat/agent-picker-sheet.tsx b/apps/mobile/components/chat/agent-picker-sheet.tsx
index 6cfd7a3306..66805a26da 100644
--- a/apps/mobile/components/chat/agent-picker-sheet.tsx
+++ b/apps/mobile/components/chat/agent-picker-sheet.tsx
@@ -18,6 +18,7 @@ import type { Agent } from "@multica/core/types";
import { Text } from "@/components/ui/text";
import { ActorAvatar } from "@/components/ui/actor-avatar";
import { cn } from "@/lib/utils";
+import { isAgentRuntimeBound } from "@/lib/is-agent-runtime-bound";
interface Props {
visible: boolean;
@@ -61,9 +62,11 @@ export function AgentPickerSheet({
) : (
agents.map((agent) => {
const selected = agent.id === currentAgentId;
+ const runtimeBound = isAgentRuntimeBound(agent);
return (
<Pressable
key={agent.id}
+ disabled={!runtimeBound}
onPress={() => {
onPick(agent);
onClose();
@@ -71,6 +74,7 @@ export function AgentPickerSheet({
className={cn(
"flex-row items-center gap-3 px-4 py-3 active:bg-secondary",
selected && "bg-secondary/60",
+ !runtimeBound && "opacity-50",
)}
>
<ActorAvatar type="agent" id={agent.id} size={32} showPresence />
@@ -90,6 +94,11 @@ export function AgentPickerSheet({
</Text>
) : null}
</View>
+ {!runtimeBound ? (
+ <Text className="text-xs font-medium text-warning">
+ Needs runtime
+ </Text>
+ ) : null}
{selected ? (
<Text className="text-sm text-primary font-semibold">
✓
diff --git a/apps/mobile/components/chat/runtime-required-banner.tsx b/apps/mobile/components/chat/runtime-required-banner.tsx
new file mode 100644
index 0000000000..7f7fae7ab6
--- /dev/null
+++ b/apps/mobile/components/chat/runtime-required-banner.tsx
@@ -0,0 +1,15 @@
+import { Ionicons } from "@expo/vector-icons";
+import { View } from "react-native";
+import { Text } from "@/components/ui/text";
+
+export function RuntimeRequiredBanner({ agentName }: { agentName?: string }) {
+ const name = agentName?.trim() || "This agent";
+ return (
+ <View className="mx-3 mb-1.5 flex-row items-center gap-1.5 rounded-md bg-warning/15 px-2.5 py-1.5">
+ <Ionicons name="server-outline" size={14} color="#a16207" />
+ <Text className="flex-1 text-xs text-warning">
+ {name} needs a runtime before it can run. Bind one on web or desktop.
+ </Text>
+ </View>
+ );
+}
diff --git a/apps/mobile/components/issue/mention-suggestion-bar.tsx b/apps/mobile/components/issue/mention-suggestion-bar.tsx
index d2b3ccec35..e752642af7 100644
--- a/apps/mobile/components/issue/mention-suggestion-bar.tsx
+++ b/apps/mobile/components/issue/mention-suggestion-bar.tsx
@@ -43,6 +43,7 @@ import {
} from "@/data/viewed-issues-store";
import type { MentionMarker } from "@/lib/mention-serialize";
import { cn } from "@/lib/utils";
+import { isAgentRuntimeBound } from "@/lib/is-agent-runtime-bound";
type Mode = "comment" | "chat";
@@ -159,10 +160,19 @@ export function MentionSuggestionBar({
// assignee can never act on; web hides them, mobile must too.
const myRole =
members.find((m) => m.user_id === userId)?.role ?? null;
+ const runnableAgentIds = new Set(
+ agents
+ .filter(
+ (agent) =>
+ !agent.archived_at && isAgentRuntimeBound(agent),
+ )
+ .map((agent) => agent.id),
+ );
const matchedAgents = [...agents]
.filter(
(a) =>
!a.archived_at &&
+ isAgentRuntimeBound(a) &&
(!q || a.name.toLowerCase().includes(q)) &&
canAssignAgentToIssue(a, { userId, role: myRole }).allowed,
)
@@ -171,7 +181,10 @@ export function MentionSuggestionBar({
// A re-activated squad re-appears on the next list refetch.
const matchedSquads = [...squads]
.filter(
- (s) => !s.archived_at && (!q || s.name.toLowerCase().includes(q)),
+ (s) =>
+ !s.archived_at &&
+ runnableAgentIds.has(s.leader_id) &&
+ (!q || s.name.toLowerCase().includes(q)),
)
.sort((a, b) => a.name.localeCompare(b.name));
@@ -289,8 +302,10 @@ export function MentionSuggestionBar({
);
}
if (item.kind === "agent") {
+ const runtimeBound = isAgentRuntimeBound(item.agent);
return (
<Pressable
+ disabled={!runtimeBound}
onPress={() =>
onSelect({
type: "agent",
@@ -298,13 +313,19 @@ export function MentionSuggestionBar({
name: item.agent.name,
})
}
- className="flex-row items-center gap-3 px-3 py-2 active:bg-secondary"
+ className={cn(
+ "flex-row items-center gap-3 px-3 py-2 active:bg-secondary",
+ !runtimeBound && "opacity-50",
+ )}
>
<ActorAvatar type="agent" id={item.agent.id} size={28} showPresence />
<Text className="flex-1 text-sm text-foreground">
{item.agent.name}
</Text>
- <Badge label="Agent" tone="brand" />
+ <Badge
+ label={runtimeBound ? "Agent" : "Needs runtime"}
+ tone={runtimeBound ? "brand" : "outline"}
+ />
</Pressable>
);
}
diff --git a/apps/mobile/components/issue/pickers/assignee-picker-body.tsx b/apps/mobile/components/issue/pickers/assignee-picker-body.tsx
index c327ca8c4d..ad33de65b2 100644
--- a/apps/mobile/components/issue/pickers/assignee-picker-body.tsx
+++ b/apps/mobile/components/issue/pickers/assignee-picker-body.tsx
@@ -31,6 +31,8 @@ import { squadListOptions } from "@/data/queries/squads";
import { useWorkspaceStore } from "@/data/workspace-store";
import { useScrollToTopOnChange } from "@/lib/use-scroll-to-top-on-change";
import { THEME } from "@/lib/theme";
+import { cn } from "@/lib/utils";
+import { isAgentRuntimeBound } from "@/lib/is-agent-runtime-bound";
const AVATAR_SIZE = 36;
@@ -66,6 +68,15 @@ export function AssigneePickerBody({ value, query, onChange }: Props) {
const { data: members = [] } = useQuery(memberListOptions(wsId));
const { data: agents = [] } = useQuery(agentListOptions(wsId));
const { data: squads = [] } = useQuery(squadListOptions(wsId));
+ const runnableAgentIds = useMemo(
+ () =>
+ new Set(
+ agents
+ .filter((agent) => !agent.archived_at && isAgentRuntimeBound(agent))
+ .map((agent) => agent.id),
+ ),
+ [agents],
+ );
const listRef = useScrollToTopOnChange(query);
const { colorScheme } = useColorScheme();
// Tint color for the checkmark accessory. Project uses a monochrome
@@ -139,10 +150,19 @@ export function AssigneePickerBody({ value, query, onChange }: Props) {
if (row.kind === "agent") return `a:${row.agent.id}`;
return `s:${row.squad.id}`;
}}
- renderItem={({ item }) => (
- <Pressable
+ renderItem={({ item }) => {
+ const needsRuntime =
+ (item.kind === "agent" && !isAgentRuntimeBound(item.agent)) ||
+ (item.kind === "squad" &&
+ !runnableAgentIds.has(item.squad.leader_id));
+ return (
+ <Pressable
+ disabled={needsRuntime}
onPress={() => select(item)}
- className="flex-row items-center gap-3 px-4 py-3 active:bg-secondary"
+ className={cn(
+ "flex-row items-center gap-3 px-4 py-3 active:bg-secondary",
+ needsRuntime && "opacity-50",
+ )}
>
{item.kind === "unassigned" ? (
<View
@@ -176,15 +196,20 @@ export function AssigneePickerBody({ value, query, onChange }: Props) {
pattern used throughout iOS Settings — type tag in lighter font on
the same row. Members carry no tag (they're the default actor). */}
{item.kind === "agent" ? (
- <Text className="text-sm text-muted-foreground">Agent</Text>
+ <Text className="text-sm text-muted-foreground">
+ {isAgentRuntimeBound(item.agent) ? "Agent" : "Needs runtime"}
+ </Text>
) : item.kind === "squad" ? (
- <Text className="text-sm text-muted-foreground">Squad</Text>
+ <Text className="text-sm text-muted-foreground">
+ {needsRuntime ? "Leader needs runtime" : "Squad"}
+ </Text>
) : null}
{isSelected(item) ? (
<Ionicons name="checkmark" size={20} color={checkColor} />
) : null}
- </Pressable>
- )}
+ </Pressable>
+ );
+ }}
ListEmptyComponent={
<View className="px-3 py-8 items-center">
<Text className="text-sm text-muted-foreground">No matches.</Text>
diff --git a/apps/mobile/components/issue/pickers/mention-picker-body.tsx b/apps/mobile/components/issue/pickers/mention-picker-body.tsx
index c7756879d9..835c434208 100644
--- a/apps/mobile/components/issue/pickers/mention-picker-body.tsx
+++ b/apps/mobile/components/issue/pickers/mention-picker-body.tsx
@@ -45,6 +45,8 @@ import {
} from "@/data/stores/mention-draft-store";
import { useScrollToTopOnChange } from "@/lib/use-scroll-to-top-on-change";
import { THEME } from "@/lib/theme";
+import { isAgentRuntimeBound } from "@/lib/is-agent-runtime-bound";
+import { cn } from "@/lib/utils";
const AVATAR_SIZE = 36;
@@ -71,6 +73,15 @@ export function MentionPickerBody({ query, mode = "comment" }: Props) {
const { data: members = [] } = useQuery(memberListOptions(wsId));
const { data: agents = [] } = useQuery(agentListOptions(wsId));
const { data: squads = [] } = useQuery(squadListOptions(wsId));
+ const runnableAgentIds = useMemo(
+ () =>
+ new Set(
+ agents
+ .filter((agent) => !agent.archived_at && isAgentRuntimeBound(agent))
+ .map((agent) => agent.id),
+ ),
+ [agents],
+ );
const listRef = useScrollToTopOnChange(query);
const { colorScheme } = useColorScheme();
const checkColor =
@@ -215,10 +226,18 @@ export function MentionPickerBody({ query, mode = "comment" }: Props) {
</View>
);
}
+ const needsRuntime =
+ (item.kind === "agent" && !isAgentRuntimeBound(item.agent)) ||
+ (item.kind === "squad" &&
+ !runnableAgentIds.has(item.squad.leader_id));
return (
<Pressable
+ disabled={needsRuntime}
onPress={() => pick(item)}
- className="flex-row items-center gap-3 px-4 py-3 active:bg-secondary"
+ className={cn(
+ "flex-row items-center gap-3 px-4 py-3 active:bg-secondary",
+ needsRuntime && "opacity-50",
+ )}
>
{item.kind === "all" ? (
<View
@@ -269,9 +288,13 @@ export function MentionPickerBody({ query, mode = "comment" }: Props) {
</Text>
)}
{item.kind === "agent" ? (
- <Text className="text-sm text-muted-foreground">Agent</Text>
+ <Text className="text-sm text-muted-foreground">
+ {isAgentRuntimeBound(item.agent) ? "Agent" : "Needs runtime"}
+ </Text>
) : item.kind === "squad" ? (
- <Text className="text-sm text-muted-foreground">Squad</Text>
+ <Text className="text-sm text-muted-foreground">
+ {needsRuntime ? "Leader needs runtime" : "Squad"}
+ </Text>
) : null}
{isSelected(item) ? (
<Ionicons name="checkmark" size={20} color={checkColor} />
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.ts
index 41f2671742..6f35d5cfae 100644
--- a/apps/mobile/data/schemas.ts
+++ b/apps/mobile/data/schemas.ts
@@ -586,6 +586,7 @@ export const AgentSchema: z.ZodType<Agent> = z.object({
id: z.string(),
workspace_id: z.string().default(""),
runtime_id: z.string().default(""),
+ runtime_bound: z.boolean().optional(),
name: z.string().default(""),
description: z.string().default(""),
instructions: z.string().default(""),
diff --git a/apps/mobile/lib/agent-schema.test.ts b/apps/mobile/lib/agent-schema.test.ts
index fe1970ee78..fb5e37670f 100644
--- a/apps/mobile/lib/agent-schema.test.ts
+++ b/apps/mobile/lib/agent-schema.test.ts
@@ -38,4 +38,15 @@ describe("AgentSchema invocation permissions", () => {
{ target_type: "team", target_id: null },
]);
});
+
+ it("preserves the additive runtime binding signal", () => {
+ const parsed = AgentSchema.parse({
+ id: "agent-1",
+ runtime_id: "",
+ runtime_bound: false,
+ });
+
+ expect(parsed.runtime_id).toBe("");
+ expect(parsed.runtime_bound).toBe(false);
+ });
});
diff --git a/apps/mobile/lib/is-agent-runtime-bound.ts b/apps/mobile/lib/is-agent-runtime-bound.ts
new file mode 100644
index 0000000000..b661099606
--- /dev/null
+++ b/apps/mobile/lib/is-agent-runtime-bound.ts
@@ -0,0 +1,15 @@
+import type { Agent } from "@multica/core/types";
+
+/**
+ * Mobile-owned mirror of packages/core/agents/runtime-binding.ts.
+ * New servers expose `runtime_bound`; older servers only expose a non-empty
+ * `runtime_id`. Requiring both available signals fails closed on partial data.
+ */
+export function isAgentRuntimeBound(
+ agent: Pick<Agent, "runtime_id" | "runtime_bound">,
+): boolean {
+ return (
+ agent.runtime_bound !== false &&
+ (agent.runtime_id ?? "").trim().length > 0
+ );
+}
diff --git a/packages/core/agents/index.ts b/packages/core/agents/index.ts
index c689d569e5..a0e8180a4a 100644
--- a/packages/core/agents/index.ts
+++ b/packages/core/agents/index.ts
@@ -12,3 +12,4 @@ export * from "./visibility-label";
export * from "./use-workspace-agent-availability";
export * from "./mcp-support";
export * from "./openclaw-runtime-config";
+export * from "./runtime-binding";
diff --git a/packages/core/agents/runtime-binding.test.ts b/packages/core/agents/runtime-binding.test.ts
new file mode 100644
index 0000000000..75e65a519d
--- /dev/null
+++ b/packages/core/agents/runtime-binding.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vitest";
+import { isAgentRuntimeBound } from "./runtime-binding";
+
+describe("isAgentRuntimeBound", () => {
+ it("accepts a bound response from new and old servers", () => {
+ expect(
+ isAgentRuntimeBound({ runtime_id: "runtime-1", runtime_bound: true }),
+ ).toBe(true);
+ expect(isAgentRuntimeBound({ runtime_id: "runtime-1" })).toBe(true);
+ });
+
+ it("rejects explicit and legacy unbound responses", () => {
+ expect(
+ isAgentRuntimeBound({ runtime_id: "", runtime_bound: false }),
+ ).toBe(false);
+ expect(isAgentRuntimeBound({ runtime_id: "" })).toBe(false);
+ });
+
+ it("fails closed when additive and legacy signals disagree", () => {
+ expect(
+ isAgentRuntimeBound({ runtime_id: "runtime-1", runtime_bound: false }),
+ ).toBe(false);
+ expect(
+ isAgentRuntimeBound({ runtime_id: "", runtime_bound: true }),
+ ).toBe(false);
+ });
+
+ it("fails closed for partial legacy payloads", () => {
+ expect(
+ isAgentRuntimeBound({
+ runtime_id: undefined as unknown as string,
+ runtime_bound: true,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/core/agents/runtime-binding.ts b/packages/core/agents/runtime-binding.ts
new file mode 100644
index 0000000000..e884eafb53
--- /dev/null
+++ b/packages/core/agents/runtime-binding.ts
@@ -0,0 +1,16 @@
+import type { Agent } from "../types";
+
+/**
+ * Treat the additive server signal and the legacy runtime id as one invariant.
+ * New servers expose `runtime_bound`; older servers only expose a non-empty
+ * `runtime_id`. Requiring both available signals also fails closed if a partial
+ * response ever carries contradictory data.
+ */
+export function isAgentRuntimeBound(
+ agent: Pick<Agent, "runtime_id" | "runtime_bound">,
+): boolean {
+ return (
+ agent.runtime_bound !== false &&
+ (agent.runtime_id ?? "").trim().length > 0
+ );
+}
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index ce4ba2c99a..43bb7eedea 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -1442,19 +1442,30 @@ export class ApiClient {
await this.fetch(`/api/runtimes/${runtimeId}`, { method: "DELETE" });
}
- // Cascade variant of deleteRuntime. The strict DELETE refuses with
+ // Confirmed variant of deleteRuntime. The strict DELETE refuses with
// structured 409 (`code: "runtime_has_active_agents"`, body carries the
// blocking agents) when active agents are bound; the front-end then opens
- // the cascade-mode confirmation dialog and submits the user-confirmed
- // active agent set here. Server compares the snapshot to the live set
- // inside the transaction and refuses with `code: "runtime_delete_plan_changed"`
- // (same shape, fresh `active_agents`) if they don't match — caller should
- // re-render the agent list and force the user to re-confirm.
- async archiveAgentsAndDeleteRuntime(
+ // the confirmation dialog and submits the user-confirmed active agent set
+ // here. Server compares the snapshot to the live set inside the transaction
+ // and refuses with `code: "runtime_delete_plan_changed"` (same shape, fresh
+ // `active_agents`) if they don't match — caller should re-render the agent
+ // list and force the user to re-confirm.
+ //
+ // The agents are UNBOUND, not archived or deleted (MUL-5559): they keep their
+ // configuration, chats and task history and need a new runtime to run again.
+ // `agents_archived` is the server's deprecated mirror of `agents_unbound`,
+ // kept because installed clients read it; prefer `agents_unbound`.
+ async unbindAgentsAndDeleteRuntime(
runtimeId: string,
expectedActiveAgentIds: string[],
- ): Promise<{ status: string; agents_archived: number; tasks_cancelled: number }> {
- return this.fetch(`/api/runtimes/${runtimeId}/archive-agents-and-delete`, {
+ ): Promise<{
+ status: string;
+ agents_unbound?: number;
+ agents_archived?: number;
+ tasks_cancelled: number;
+ autopilots_paused?: number;
+ }> {
+ return this.fetch(`/api/runtimes/${runtimeId}/unbind-agents-and-delete`, {
method: "POST",
body: JSON.stringify({ expected_active_agent_ids: expectedActiveAgentIds }),
});
diff --git a/packages/core/runtimes/mutations.ts b/packages/core/runtimes/mutations.ts
index 0711cab275..74f55b6b71 100644
--- a/packages/core/runtimes/mutations.ts
+++ b/packages/core/runtimes/mutations.ts
@@ -14,17 +14,17 @@ export function useDeleteRuntime(wsId: string) {
});
}
-// Cascade-mode counterpart to useDeleteRuntime. The dialog routes here when
+// Confirmed-delete counterpart to useDeleteRuntime. The dialog routes here when
// the strict DELETE refused with `runtime_has_active_agents` (or when the
// caller already knows the runtime has active agents and wants to skip the
// pre-flight refusal). Mutation fn returns the server-reported counts so
// the caller can render a richer success toast.
//
-// Invalidates runtimes (the list / detail), workspace agents (the cascade
-// archives them) and the agent presence snapshot (cascade also cancels
-// queued/running tasks). Without the agent-side invalidation the Agents
-// page would keep showing the just-archived rows as live until a refetch.
-export function useArchiveAgentsAndDeleteRuntime(wsId: string) {
+// Invalidates runtimes (the list / detail), workspace agents (they are unbound,
+// so their runtime column and readiness change) and the agent presence snapshot
+// (the delete also cancels queued/running tasks). Without the agent-side
+// invalidation the Agents page would keep showing them as runnable.
+export function useUnbindAgentsAndDeleteRuntime(wsId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: ({
@@ -33,7 +33,7 @@ export function useArchiveAgentsAndDeleteRuntime(wsId: string) {
}: {
runtimeId: string;
expectedActiveAgentIds: string[];
- }) => api.archiveAgentsAndDeleteRuntime(runtimeId, expectedActiveAgentIds),
+ }) => api.unbindAgentsAndDeleteRuntime(runtimeId, expectedActiveAgentIds),
onSettled: () => {
qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
diff --git a/packages/core/runtimes/profiles.ts b/packages/core/runtimes/profiles.ts
index 11104912b9..73acceecad 100644
--- a/packages/core/runtimes/profiles.ts
+++ b/packages/core/runtimes/profiles.ts
@@ -11,8 +11,8 @@ import { runtimeKeys } from "./queries";
// Query keys for the workspace-scoped custom runtime profile catalog. Kept
// separate from `runtimeKeys` (which key the registered runtime *instances*)
// because the two resources invalidate on different events — but a profile
-// delete can archive bound agents and therefore must also invalidate the
-// instance list, so the mutations below touch both.
+// delete removes its registered instances and can unbind their agents, so it
+// must also invalidate the instance list; the mutations below touch both.
export const runtimeProfileKeys = {
all: (wsId: string) => ["runtime-profiles", wsId] as const,
list: (wsId: string) => [...runtimeProfileKeys.all(wsId), "list"] as const,
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 3b49e0181f..115acceb49 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -373,7 +373,16 @@ export interface AgentTask {
export interface Agent {
id: string;
workspace_id: string;
+ /**
+ * Empty string when the agent is unbound: it kept its configuration, chats and
+ * task history when its runtime was deleted, and needs a new runtime before it
+ * can run again (MUL-5559). Use `isAgentRuntimeBound` so additive and legacy
+ * signals stay compatible, and do not confuse it with a bound-but-offline
+ * runtime — that one just needs the machine back.
+ */
runtime_id: string;
+ /** False exactly when the agent has no runtime. Older backends omit it. */
+ runtime_bound?: boolean;
name: string;
description: string;
instructions: string;
diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.ts
index e6e1fdc588..ade8be86fd 100644
--- a/packages/core/types/autopilot.ts
+++ b/packages/core/types/autopilot.ts
@@ -32,6 +32,9 @@ export interface Autopilot {
assignee_type: AutopilotAssigneeType;
assignee_id: string;
status: AutopilotStatus;
+ // Additive machine-readable explanation for a system pause. Null for manual
+ // pauses and older servers.
+ pause_reason?: string | null;
execution_mode: AutopilotExecutionMode;
issue_title_template: string | null;
created_by_type: string;
diff --git a/packages/views/agents/components/agent-detail-page.test.tsx b/packages/views/agents/components/agent-detail-page.test.tsx
index 27fe4073c3..3556a1c99e 100644
--- a/packages/views/agents/components/agent-detail-page.test.tsx
+++ b/packages/views/agents/components/agent-detail-page.test.tsx
@@ -42,6 +42,8 @@ vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-1",
}));
vi.mock("@multica/core/agents", () => ({
+ isAgentRuntimeBound: (agent: { runtime_id: string; runtime_bound?: boolean }) =>
+ agent.runtime_bound !== false && agent.runtime_id.length > 0,
useWorkspacePresenceMap: () => ({ byAgent: new Map() }),
}));
vi.mock("@multica/core/workspace/queries", () => ({
@@ -208,4 +210,29 @@ describe("AgentDetailPage DM button", () => {
await screen.findByText(/This agent is archived/);
expect(screen.queryByRole("button", { name: "DM" })).not.toBeInTheDocument();
});
+
+ it("explains an unbound agent and blocks run actions without losing the profile", async () => {
+ agentsRef.current = [
+ {
+ ...baseAgent,
+ owner_id: "user-1",
+ runtime_id: "",
+ runtime_bound: false,
+ },
+ ];
+ renderPage();
+
+ expect(
+ await screen.findByText(/needs a runtime before it can run/i),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Bind runtime" }),
+ ).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "DM" }));
+ expect(mockToastError).toHaveBeenCalledWith(
+ "Bind a runtime before running this agent.",
+ );
+ expect(mockModalOpen).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsx
index 3e565c225d..e476ef8f0e 100644
--- a/packages/views/agents/components/agent-detail-page.tsx
+++ b/packages/views/agents/components/agent-detail-page.tsx
@@ -22,6 +22,7 @@ import type {
} from "@multica/core/types";
import {
type AgentPresenceDetail,
+ isAgentRuntimeBound,
useWorkspacePresenceMap,
} from "@multica/core/agents";
import { api, ApiError } from "@multica/core/api";
@@ -134,17 +135,23 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
// would clobber a concurrent successful mutation if the failing call
// resolves last (e.g. flipping visibility then runtime simultaneously
// and only the visibility PATCH fails).
+ const optimisticData =
+ typeof data.runtime_id === "string"
+ ? { ...data, runtime_bound: data.runtime_id.trim().length > 0 }
+ : data;
const queryKey = workspaceKeys.agents(wsId);
const prevAgents = qc.getQueryData<Agent[]>(queryKey);
const prevAgent = prevAgents?.find((a) => a.id === id);
const prevFields: Record<string, unknown> = {};
if (prevAgent) {
- for (const key of Object.keys(data)) {
+ for (const key of Object.keys(optimisticData)) {
prevFields[key] = (prevAgent as unknown as Record<string, unknown>)[key];
}
}
qc.setQueryData<Agent[]>(queryKey, (old) =>
- old?.map((a) => (a.id === id ? ({ ...a, ...data } as Agent) : a)),
+ old?.map((a) =>
+ a.id === id ? ({ ...a, ...optimisticData } as Agent) : a,
+ ),
);
try {
await api.updateAgent(id, data as UpdateAgentRequest);
@@ -252,7 +259,8 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
}
const isArchived = !!agent.archived_at;
- const runtime = agent.runtime_id
+ const runtimeBound = isAgentRuntimeBound(agent);
+ const runtime = runtimeBound
? runtimes.find((r) => r.id === agent.runtime_id) ?? null
: null;
const owner = agent.owner_id
@@ -270,8 +278,21 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
toast.error(t(($) => $.detail.dm_no_permission_toast));
return;
}
+ if (!runtimeBound) {
+ toast.error(t(($) => $.detail.runtime_required_toast));
+ return;
+ }
navigation.push(`${paths.chat()}?agent=${agent.id}`);
};
+ const handleAssign = () => {
+ if (!runtimeBound) {
+ toast.error(t(($) => $.detail.runtime_required_toast));
+ return;
+ }
+ useModalStore
+ .getState()
+ .open("quick-create-issue", { agent_id: agent.id });
+ };
return (
<div className="flex flex-1 min-h-0 flex-col">
@@ -284,11 +305,7 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
canArchive={canEdit.allowed}
dmPending={permissionsLoading}
onDm={handleDm}
- onAssign={() =>
- useModalStore
- .getState()
- .open("quick-create-issue", { agent_id: agent.id })
- }
+ onAssign={handleAssign}
onArchive={() => setConfirmArchive(true)}
/>
@@ -321,6 +338,25 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
</div>
)}
+ {!isArchived && !runtimeBound && (
+ <div className="flex shrink-0 items-center gap-2 border-b border-amber-500/30 bg-amber-500/10 px-6 py-2 text-caption text-amber-900 dark:text-amber-100">
+ <Server className="h-3.5 w-3.5 shrink-0" />
+ <span className="flex-1">
+ {t(($) => $.detail.runtime_required_banner)}
+ </span>
+ {canEdit.allowed && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-6 border-amber-500/40 bg-background/70 text-caption"
+ onClick={() => setTabNavIntent("general")}
+ >
+ {t(($) => $.detail.bind_runtime)}
+ </Button>
+ )}
+ </div>
+ )}
+
<div className="flex flex-1 min-h-0 flex-col overflow-hidden">
<AgentOverviewPane
agent={agent}
diff --git a/packages/views/agents/components/agents-page.test.tsx b/packages/views/agents/components/agents-page.test.tsx
index 005ecbb153..99d93515c3 100644
--- a/packages/views/agents/components/agents-page.test.tsx
+++ b/packages/views/agents/components/agents-page.test.tsx
@@ -90,6 +90,8 @@ vi.mock("sonner", () => ({
}));
vi.mock("@multica/core/agents", () => ({
+ isAgentRuntimeBound: (agent: { runtime_id: string; runtime_bound?: boolean }) =>
+ agent.runtime_bound !== false && agent.runtime_id.length > 0,
agentRunCounts30dOptions: () => ({ queryKey: ["agent-run-counts"] }),
useWorkspaceActivityMap: () => mocks.activity,
useWorkspacePresenceMap: () => mocks.presence,
diff --git a/packages/views/agents/components/agents-page.tsx b/packages/views/agents/components/agents-page.tsx
index 24e50d07b5..1cf129509d 100644
--- a/packages/views/agents/components/agents-page.tsx
+++ b/packages/views/agents/components/agents-page.tsx
@@ -18,6 +18,7 @@ import {
type AgentActivity,
agentRunCounts30dOptions,
effectiveAccessScope,
+ isAgentRuntimeBound,
useWorkspaceActivityMap,
useWorkspacePresenceMap,
VISIBILITY_TOOLTIP,
@@ -427,6 +428,16 @@ function StatusCell({ row }: { row: AgentListRow }) {
</ListGridCell>
);
}
+ if (!isAgentRuntimeBound(agent)) {
+ return (
+ <ListGridCell className="gap-1.5">
+ <AlertCircle className="size-3.5 shrink-0 text-amber-500" />
+ <span className="truncate text-caption text-amber-600 dark:text-amber-400">
+ {t(($) => $.row.needs_runtime)}
+ </span>
+ </ListGridCell>
+ );
+ }
if (!presence) {
return (
<ListGridCell>
@@ -504,6 +515,16 @@ export function AccessCell({ row }: { row: AgentListRow }) {
}
function RuntimeCell({ row }: { row: AgentListRow }) {
+ const { t } = useT("agents");
+ if (!isAgentRuntimeBound(row.agent)) {
+ return (
+ <ListGridCell className="hidden @2xl:flex">
+ <span className="truncate text-caption text-amber-600 dark:text-amber-400">
+ {t(($) => $.row.needs_runtime)}
+ </span>
+ </ListGridCell>
+ );
+ }
const runtime = row.runtime;
return (
<ListGridCell className="hidden @2xl:flex">
diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsx
index 7393442718..dc1b141a55 100644
--- a/packages/views/autopilots/components/autopilot-detail-page.tsx
+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx
@@ -4,7 +4,7 @@ import { useState } from "react";
import {
Zap, Play, Clock, Plus, Trash2, CheckCircle2, XCircle, Loader2, Pencil,
Ban, ChevronDown, ChevronRight,
- Webhook, RotateCw,
+ Webhook, RotateCw, Server,
} from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { autopilotDetailOptions, autopilotRunsOptions, autopilotRunOptions } from "@multica/core/autopilots/queries";
@@ -825,6 +825,23 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
}
/>
+ {autopilot.pause_reason === "agent_runtime_required" && (
+ <div className="flex shrink-0 items-center gap-2 border-b border-amber-500/30 bg-amber-500/10 px-6 py-2 text-caption text-amber-900 dark:text-amber-100">
+ <Server className="size-3.5 shrink-0" />
+ <span className="flex-1">
+ {t(($) => $.detail.paused_runtime_required)}
+ </span>
+ {autopilot.assignee_type === "agent" && (
+ <AppLink
+ href={`${wsPaths.agentDetail(autopilot.assignee_id)}?view=general`}
+ className="font-medium underline underline-offset-2"
+ >
+ {t(($) => $.detail.bind_runtime)}
+ </AppLink>
+ )}
+ </div>
+ )}
+
<div className="flex-1 overflow-y-auto">
<div className="max-w-4xl mx-auto p-6 space-y-8">
{/* Properties */}
diff --git a/packages/views/autopilots/components/autopilot-dialog.validation.test.tsx b/packages/views/autopilots/components/autopilot-dialog.validation.test.tsx
index a55c66a75a..9533419b7d 100644
--- a/packages/views/autopilots/components/autopilot-dialog.validation.test.tsx
+++ b/packages/views/autopilots/components/autopilot-dialog.validation.test.tsx
@@ -21,7 +21,13 @@ vi.mock("@multica/core/workspace/queries", () => ({
agentListOptions: (wsId: string) => ({
queryKey: ["agents", wsId],
queryFn: async () => [
- { id: "agent-1", name: "Scout", description: "Researches things", archived_at: null },
+ {
+ id: "agent-1",
+ name: "Scout",
+ description: "Researches things",
+ archived_at: null,
+ runtime_id: "runtime-1",
+ },
],
}),
squadListOptions: (wsId: string) => ({
diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsx
index a56ba15969..93c603806a 100644
--- a/packages/views/autopilots/components/autopilots-page.tsx
+++ b/packages/views/autopilots/components/autopilots-page.tsx
@@ -251,7 +251,11 @@ function NameCell({ autopilot }: { autopilot: Autopilot }) {
paused automation needs an inline signal. */}
{autopilot.status === "paused" && (
<span
- title={t(($) => $.status.paused)}
+ title={
+ autopilot.pause_reason === "agent_runtime_required"
+ ? t(($) => $.status.paused_runtime_required)
+ : t(($) => $.status.paused)
+ }
className="flex shrink-0 items-center text-amber-500"
>
<Pause className="size-3" />
diff --git a/packages/views/autopilots/components/pickers/agent-picker.tsx b/packages/views/autopilots/components/pickers/agent-picker.tsx
index ec45c6bac2..3b9fd16710 100644
--- a/packages/views/autopilots/components/pickers/agent-picker.tsx
+++ b/packages/views/autopilots/components/pickers/agent-picker.tsx
@@ -4,6 +4,7 @@ import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Bot } from "lucide-react";
import { useWorkspaceId } from "@multica/core/hooks";
+import { isAgentRuntimeBound } from "@multica/core/agents";
import { agentListOptions, squadListOptions } from "@multica/core/workspace/queries";
import type { AutopilotAssigneeType } from "@multica/core/types";
import { ActorAvatar } from "../../../common/actor-avatar";
@@ -43,6 +44,10 @@ export function AgentPicker({
const activeAgents = useMemo(() => agents.filter((a) => !a.archived_at), [agents]);
const activeSquads = useMemo(() => squads.filter((s) => !s.archived_at), [squads]);
+ const agentsById = useMemo(
+ () => new Map(activeAgents.map((agent) => [agent.id, agent])),
+ [activeAgents],
+ );
const selectedAgent =
assignee?.type === "agent" ? activeAgents.find((a) => a.id === assignee.id) : undefined;
@@ -103,30 +108,49 @@ export function AgentPicker({
<>
{filteredAgents.length > 0 && (
<PickerSection label={t(($) => $.agent_picker.agents_group)}>
- {filteredAgents.map((a) => (
- <PickerItem
- key={a.id}
- selected={isSelected("agent", a.id)}
- onClick={() => handlePick("agent", a.id)}
- >
- <ActorAvatar actorType="agent" actorId={a.id} size="sm" showStatusDot />
- <span className="truncate">{a.name}</span>
- </PickerItem>
- ))}
+ {filteredAgents.map((a) => {
+ const runtimeBound = isAgentRuntimeBound(a);
+ return (
+ <PickerItem
+ key={a.id}
+ selected={isSelected("agent", a.id)}
+ disabled={!runtimeBound}
+ tooltip={
+ runtimeBound
+ ? undefined
+ : t(($) => $.agent_picker.agent_runtime_required)
+ }
+ onClick={() => handlePick("agent", a.id)}
+ >
+ <ActorAvatar actorType="agent" actorId={a.id} size="sm" showStatusDot />
+ <span className="truncate">{a.name}</span>
+ </PickerItem>
+ );
+ })}
</PickerSection>
)}
{filteredSquads.length > 0 && (
<PickerSection label={t(($) => $.agent_picker.squads_group)}>
- {filteredSquads.map((s) => (
- <PickerItem
- key={s.id}
- selected={isSelected("squad", s.id)}
- onClick={() => handlePick("squad", s.id)}
- >
- <ActorAvatar actorType="squad" actorId={s.id} size="sm" />
- <span className="truncate">{s.name}</span>
- </PickerItem>
- ))}
+ {filteredSquads.map((s) => {
+ const leader = agentsById.get(s.leader_id);
+ const runtimeBound = !!leader && isAgentRuntimeBound(leader);
+ return (
+ <PickerItem
+ key={s.id}
+ selected={isSelected("squad", s.id)}
+ disabled={!runtimeBound}
+ tooltip={
+ runtimeBound
+ ? undefined
+ : t(($) => $.agent_picker.squad_runtime_required)
+ }
+ onClick={() => handlePick("squad", s.id)}
+ >
+ <ActorAvatar actorType="squad" actorId={s.id} size="sm" />
+ <span className="truncate">{s.name}</span>
+ </PickerItem>
+ );
+ })}
</PickerSection>
)}
</>
diff --git a/packages/views/autopilots/components/run-now-toast.ts b/packages/views/autopilots/components/run-now-toast.ts
index ebe9103a39..7412e4c315 100644
--- a/packages/views/autopilots/components/run-now-toast.ts
+++ b/packages/views/autopilots/components/run-now-toast.ts
@@ -32,6 +32,7 @@ export function runNowToastKind(status: string | undefined): RunNowToastKind {
export type RunNowBlockedKey =
| "run_blocked_invocation_not_allowed"
| "run_blocked_runtime_offline"
+ | "run_blocked_agent_runtime_required"
| "run_blocked_target_unavailable"
| "run_blocked_attribution"
| "run_blocked_already_active"
@@ -43,6 +44,10 @@ export function runNowBlockedKey(reasonCode: string | undefined): RunNowBlockedK
return "run_blocked_invocation_not_allowed";
case "runtime_offline":
return "run_blocked_runtime_offline";
+ // Unbound, not offline: nothing will claim the run until the agent is bound
+ // to a runtime (MUL-5559).
+ case "agent_runtime_required":
+ return "run_blocked_agent_runtime_required";
case "target_unavailable":
return "run_blocked_target_unavailable";
case "attribution_blocked":
diff --git a/packages/views/chat/chat-page.test.tsx b/packages/views/chat/chat-page.test.tsx
index 1a654eb037..5bd43d6a04 100644
--- a/packages/views/chat/chat-page.test.tsx
+++ b/packages/views/chat/chat-page.test.tsx
@@ -133,6 +133,7 @@ vi.mock("./components/use-chat-controller", async () => {
currentSession: null,
isSessionArchived: false,
isAgentArchived: false,
+ isAgentRuntimeBound: true,
activeAgent: availableAgentsRef.current[0] ?? null,
noAgent: false,
availability: "online",
diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsx
index fa467fbaba..6e5534ad84 100644
--- a/packages/views/chat/chat-page.tsx
+++ b/packages/views/chat/chat-page.tsx
@@ -32,6 +32,7 @@ import { useChatController } from "./components/use-chat-controller";
import { OfflineBanner } from "./components/offline-banner";
import { NoAgentBanner } from "./components/no-agent-banner";
import { ArchivedAgentBanner } from "./components/archived-agent-banner";
+import { RuntimeRequiredBanner } from "./components/runtime-required-banner";
/**
* Chat tab — the first-class two-pane surface (thread list on the left,
@@ -262,7 +263,11 @@ export function ChatPage() {
onLoadOlderMessages={() => void c.fetchOlderMessages()}
onQuickAction={(action) => c.handleSend(action.prompt)}
quickActionsDisabled={
- !!c.pendingTaskId || c.isSessionArchived || c.isAgentArchived || c.noAgent
+ !!c.pendingTaskId ||
+ c.isSessionArchived ||
+ c.isAgentArchived ||
+ !c.isAgentRuntimeBound ||
+ c.noAgent
}
onRegenerateQuickActions={(message) =>
c.activeSessionId
@@ -282,6 +287,11 @@ export function ChatPage() {
<NoAgentBanner />
) : c.isAgentArchived ? (
<ArchivedAgentBanner agentName={c.activeAgent?.name} />
+ ) : !c.isAgentRuntimeBound && c.activeAgent ? (
+ <RuntimeRequiredBanner
+ agentId={c.activeAgent.id}
+ agentName={c.activeAgent.name}
+ />
) : (
<OfflineBanner agentName={c.activeAgent?.name} availability={c.availability} />
)}
@@ -293,9 +303,12 @@ export function ChatPage() {
uploadEnabled={c.uploadEnabled}
onStop={c.handleStop}
isRunning={!!c.pendingTaskId}
- disabled={c.isSessionArchived || c.isAgentArchived}
+ disabled={
+ c.isSessionArchived || c.isAgentArchived || !c.isAgentRuntimeBound
+ }
noAgent={c.noAgent}
agentArchived={c.isAgentArchived}
+ agentRuntimeRequired={!c.isAgentRuntimeBound}
agentName={c.activeAgent?.name}
projects={c.projects}
projectId={c.activeProjectId}
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index f83f4ce317..0161c36c20 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -96,6 +96,7 @@ interface ChatInputProps {
* as opposed to the session itself being archived — swaps the placeholder
* copy so the read-only reason reads accurately. */
agentArchived?: boolean;
+ agentRuntimeRequired?: boolean;
/** Name of the currently selected agent, used in the placeholder. */
agentName?: string;
/** Rendered at the bottom-left of the input bar — typically the agent picker. */
@@ -136,6 +137,7 @@ export function ChatInput({
disabled,
noAgent,
agentArchived,
+ agentRuntimeRequired,
agentName,
leftAdornment,
contextItems,
@@ -527,6 +529,8 @@ export function ChatInput({
: disabled
? agentArchived
? t(($) => $.input.placeholder_archived_agent)
+ : agentRuntimeRequired
+ ? t(($) => $.input.placeholder_runtime_required)
: t(($) => $.input.placeholder_archived)
: agentName
? t(($) => $.input.placeholder_named, { name: agentName })
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index a362341f2f..5ba0fa5f88 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -18,8 +18,12 @@ import { useAuthStore } from "@multica/core/auth";
import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
import { projectListOptions } from "@multica/core/projects/queries";
import { canAssignAgent } from "@multica/views/issues/components";
-import { api } from "@multica/core/api";
-import { useAgentPresenceDetail, useWorkspaceAgentAvailability } from "@multica/core/agents";
+import { api, dispatchReasonCode } from "@multica/core/api";
+import {
+ isAgentRuntimeBound,
+ useAgentPresenceDetail,
+ useWorkspaceAgentAvailability,
+} from "@multica/core/agents";
import { ActorAvatar } from "../../common/actor-avatar";
import { useAppForeground } from "../../common/use-app-foreground";
import {
@@ -32,6 +36,7 @@ import { matchesPinyin } from "../../editor/extensions/pinyin-match";
import { OfflineBanner } from "./offline-banner";
import { NoAgentBanner } from "./no-agent-banner";
import { ArchivedAgentBanner } from "./archived-agent-banner";
+import { RuntimeRequiredBanner } from "./runtime-required-banner";
import {
chatSessionsOptions,
chatMessagesPageOptions,
@@ -240,6 +245,8 @@ export function ChatWindow() {
availableAgents.find((a) => a.id === selectedAgentId) ??
availableAgents[0] ??
null;
+ const activeAgentRuntimeBound =
+ !!activeAgent && isAgentRuntimeBound(activeAgent);
const projectContextSupport = useChatProjectContextSupport(wsId, activeAgent);
@@ -461,6 +468,10 @@ export function ChatWindow() {
});
return false;
}
+ if (!activeAgentRuntimeBound) {
+ toast.error(t(($) => $.input.runtime_required_toast));
+ return false;
+ }
const finalContent = content;
@@ -479,7 +490,14 @@ export function ChatWindow() {
sessionId = await ensureSession(finalContent);
} catch (err) {
apiLogger.error("sendChatMessage.ensureSession.error", err);
- toast.error(t(($) => $.input.send_failed_toast));
+ const reason = dispatchReasonCode(err);
+ toast.error(
+ reason === "invocation_not_allowed"
+ ? t(($) => $.input.send_blocked_toast)
+ : reason === "agent_runtime_required"
+ ? t(($) => $.input.runtime_required_toast)
+ : t(($) => $.input.send_failed_toast),
+ );
return false;
}
if (!sessionId) {
@@ -498,7 +516,14 @@ export function ChatWindow() {
result = await api.sendChatMessage(sessionId, finalContent, attachmentIds);
} catch (err) {
apiLogger.error("sendChatMessage.error", { sessionId, err });
- toast.error(t(($) => $.input.send_failed_toast));
+ const reason = dispatchReasonCode(err);
+ toast.error(
+ reason === "invocation_not_allowed"
+ ? t(($) => $.input.send_blocked_toast)
+ : reason === "agent_runtime_required"
+ ? t(($) => $.input.runtime_required_toast)
+ : t(($) => $.input.send_failed_toast),
+ );
return false;
}
apiLogger.info("sendChatMessage.success", {
@@ -580,6 +605,7 @@ export function ChatWindow() {
[
activeSessionId,
activeAgent,
+ activeAgentRuntimeBound,
isAgentArchived,
ensureSession,
cancelChatTask,
@@ -844,7 +870,11 @@ export function ChatWindow() {
onLoadOlderMessages={() => void fetchOlderMessages()}
onQuickAction={(action) => handleSend(action.prompt)}
quickActionsDisabled={
- !!pendingTaskId || isSessionArchived || isAgentArchived || noAgent
+ !!pendingTaskId ||
+ isSessionArchived ||
+ isAgentArchived ||
+ !activeAgentRuntimeBound ||
+ noAgent
}
onRegenerateQuickActions={(message) =>
activeSessionId
@@ -877,6 +907,11 @@ export function ChatWindow() {
<NoAgentBanner />
) : isAgentArchived ? (
<ArchivedAgentBanner agentName={activeAgent?.name} />
+ ) : !activeAgentRuntimeBound && activeAgent ? (
+ <RuntimeRequiredBanner
+ agentId={activeAgent.id}
+ agentName={activeAgent.name}
+ />
) : (
<OfflineBanner agentName={activeAgent?.name} availability={availability} />
)}
@@ -891,9 +926,12 @@ export function ChatWindow() {
uploadEnabled={!!activeAgent}
onStop={handleStop}
isRunning={!!pendingTaskId}
- disabled={isSessionArchived || isAgentArchived}
+ disabled={
+ isSessionArchived || isAgentArchived || !activeAgentRuntimeBound
+ }
noAgent={noAgent}
agentArchived={isAgentArchived}
+ agentRuntimeRequired={!activeAgentRuntimeBound}
agentName={activeAgent?.name}
projects={projects}
projectId={activeProjectId}
@@ -1036,9 +1074,15 @@ function AgentPickerItem({
isCurrent: boolean;
onSelect: (agent: Agent) => void;
}) {
+ const { t } = useT("chat");
+ const runtimeBound = isAgentRuntimeBound(agent);
return (
<PickerItem
selected={isCurrent}
+ disabled={!runtimeBound}
+ tooltip={
+ runtimeBound ? undefined : t(($) => $.window.agent_needs_runtime_hint)
+ }
onClick={() => onSelect(agent)}
>
<ActorAvatar
@@ -1049,6 +1093,11 @@ function AgentPickerItem({
showStatusDot
/>
<span className="truncate flex-1">{agent.name}</span>
+ {!runtimeBound && (
+ <span className="shrink-0 text-micro text-amber-600 dark:text-amber-400">
+ {t(($) => $.window.agent_needs_runtime)}
+ </span>
+ )}
</PickerItem>
);
}
diff --git a/packages/views/chat/components/new-chat-button.tsx b/packages/views/chat/components/new-chat-button.tsx
index a5576d48df..89922e53f5 100644
--- a/packages/views/chat/components/new-chat-button.tsx
+++ b/packages/views/chat/components/new-chat-button.tsx
@@ -13,6 +13,8 @@ import {
} from "../../issues/components/pickers/property-picker";
import { matchesPinyin } from "../../editor/extensions/pinyin-match";
import type { Agent } from "@multica/core/types";
+import { isAgentRuntimeBound } from "@multica/core/agents";
+import { toast } from "sonner";
import { useT } from "../../i18n";
/**
@@ -120,8 +122,17 @@ function AgentPickerItem({
isCurrent: boolean;
onSelect: (agent: Agent) => void;
}) {
+ const { t } = useT("chat");
+ const runtimeBound = isAgentRuntimeBound(agent);
return (
- <PickerItem selected={isCurrent} onClick={() => onSelect(agent)}>
+ <PickerItem
+ selected={isCurrent}
+ disabled={!runtimeBound}
+ tooltip={
+ runtimeBound ? undefined : t(($) => $.window.agent_needs_runtime_hint)
+ }
+ onClick={() => onSelect(agent)}
+ >
<ActorAvatar
actorType="agent"
actorId={agent.id}
@@ -130,6 +141,11 @@ function AgentPickerItem({
showStatusDot
/>
<span className="truncate flex-1">{agent.name}</span>
+ {!runtimeBound && (
+ <span className="shrink-0 text-micro text-amber-600 dark:text-amber-400">
+ {t(($) => $.window.agent_needs_runtime)}
+ </span>
+ )}
</PickerItem>
);
}
@@ -167,7 +183,13 @@ export function NewChatButton({
size="icon-sm"
className="rounded-full text-muted-foreground"
aria-label={label}
- onClick={() => onStart(only)}
+ onClick={() => {
+ if (only && !isAgentRuntimeBound(only)) {
+ toast.error(t(($) => $.input.runtime_required_toast));
+ return;
+ }
+ onStart(only);
+ }}
/>
}
>
diff --git a/packages/views/chat/components/runtime-required-banner.tsx b/packages/views/chat/components/runtime-required-banner.tsx
new file mode 100644
index 0000000000..70a9c477cb
--- /dev/null
+++ b/packages/views/chat/components/runtime-required-banner.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { Server } from "lucide-react";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { Button } from "@multica/ui/components/ui/button";
+import { cn } from "@multica/ui/lib/utils";
+import { useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";
+
+export function RuntimeRequiredBanner({
+ agentId,
+ agentName,
+}: {
+ agentId: string;
+ agentName?: string;
+}) {
+ const { t } = useT("chat");
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const name = agentName?.trim() || t(($) => $.runtime_required_banner.fallback_name);
+
+ return (
+ <div className={cn(CHAT_GUTTER, "mb-1.5")}>
+ <div
+ className={cn(
+ CHAT_COLUMN,
+ "flex items-center gap-2 rounded-md bg-amber-50 px-2.5 py-1.5 text-caption text-amber-900 ring-1 ring-amber-200/60 dark:bg-amber-950/40 dark:text-amber-200 dark:ring-amber-900/40",
+ )}
+ >
+ <Server className="size-3.5 shrink-0" />
+ <span className="min-w-0 flex-1 truncate">
+ {t(($) => $.runtime_required_banner.message, { name })}
+ </span>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-6 shrink-0 bg-background/70 text-caption"
+ onClick={() =>
+ navigation.push(`${paths.agentDetail(agentId)}?view=general`)
+ }
+ >
+ {t(($) => $.runtime_required_banner.action)}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsx
index 64a5f83d51..16e5bb8d9c 100644
--- a/packages/views/chat/components/use-chat-controller.test.tsx
+++ b/packages/views/chat/components/use-chat-controller.test.tsx
@@ -95,6 +95,8 @@ vi.mock("@multica/core/api", () => ({
dispatchReasonCode: () => undefined,
}));
vi.mock("@multica/core/agents", () => ({
+ isAgentRuntimeBound: (agent: { runtime_id: string; runtime_bound?: boolean }) =>
+ agent.runtime_bound !== false && agent.runtime_id.length > 0,
useAgentPresenceDetail: () => ({ availability: "online" }),
useWorkspaceAgentAvailability: () => "available",
}));
@@ -139,6 +141,7 @@ vi.mock("@tanstack/react-query", async (importOriginal) => {
if (key.includes("members")) {
return { data: [{ user_id: "user-1", role: "admin" }] };
}
+ if (key.includes("runtimes")) return { data: [] };
if (key.includes("sessions")) return { data: h.sessions, isSuccess: true };
if (key.includes("projects")) return { data: h.projects, isSuccess: true };
if (key.includes("draft-restores")) return { data: h.draftRestores };
@@ -181,8 +184,18 @@ function makeSession(
};
}
-const agentA = { id: "agent-a", name: "Alpha" } as unknown as Agent;
-const agentB = { id: "agent-b", name: "Beta" } as unknown as Agent;
+const agentA = {
+ id: "agent-a",
+ name: "Alpha",
+ runtime_id: "runtime-a",
+ runtime_bound: true,
+} as unknown as Agent;
+const agentB = {
+ id: "agent-b",
+ name: "Beta",
+ runtime_id: "runtime-b",
+ runtime_bound: true,
+} as unknown as Agent;
// Descending updated_at → sortChatSessions renders them sA, sB, sC.
const sA = makeSession({ id: "sA", agent_id: "agent-a", updated_at: "2026-07-08T03:00:00Z" });
@@ -713,6 +726,7 @@ describe("useChatController.handleSend — compose target tracking", () => {
h.store.setActiveSession.mockClear();
h.createSessionMutate.mockClear();
h.createSessionMutate.mockResolvedValue({ id: "new-session" });
+ vi.mocked(api.sendChatMessage).mockClear();
vi.mocked(api.sendChatMessage).mockResolvedValue({
message_id: "msg-1",
task_id: "task-1",
@@ -751,6 +765,25 @@ describe("useChatController.handleSend — compose target tracking", () => {
expect(h.store.setActiveSession).toHaveBeenCalledWith("new-session");
});
+ it("does not create or send a chat for an unbound agent", async () => {
+ h.store.activeSessionId = null;
+ h.store.selectedAgentId = "agent-a";
+ h.sessions = [];
+ h.agents = [{ ...agentA, runtime_id: "", runtime_bound: false }];
+ const { result } = renderHook(() => useChatController());
+ const commitInput = vi.fn();
+
+ let sent = true;
+ await act(async () => {
+ sent = await result.current.handleSend("hello", undefined, commitInput);
+ });
+
+ expect(sent).toBe(false);
+ expect(h.createSessionMutate).not.toHaveBeenCalled();
+ expect(api.sendChatMessage).not.toHaveBeenCalled();
+ expect(commitInput).not.toHaveBeenCalled();
+ });
+
it("scrubs the composer even if the agent picker moved mid-send", async () => {
// The sent text is still sitting in the one shared composer. Leaving it
// there would arm a second, unintended send to the agent just picked.
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index 87530ad580..a645658653 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -14,7 +14,11 @@ import { agentListOptions, memberListOptions } from "@multica/core/workspace/que
import { projectListOptions } from "@multica/core/projects/queries";
import { canAssignAgent } from "@multica/views/issues/components";
import { api, dispatchReasonCode } from "@multica/core/api";
-import { useAgentPresenceDetail, useWorkspaceAgentAvailability } from "@multica/core/agents";
+import {
+ isAgentRuntimeBound as hasAgentRuntime,
+ useAgentPresenceDetail,
+ useWorkspaceAgentAvailability,
+} from "@multica/core/agents";
import {
chatSessionsOptions,
chatMessagesPageOptions,
@@ -322,6 +326,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
availableAgents.find((a) => a.id === selectedAgentId) ??
availableAgents[0] ??
null;
+ const isAgentRuntimeBound = !!activeAgent && hasAgentRuntime(activeAgent);
const agentAvailability = useWorkspaceAgentAvailability();
const noAgent = agentAvailability === "none";
@@ -500,6 +505,10 @@ export function useChatController(opts?: { isActive?: boolean }) {
});
return false;
}
+ if (!isAgentRuntimeBound) {
+ toast.error(t(($) => $.input.runtime_required_toast));
+ return false;
+ }
const finalContent = content;
const isNewSession = !activeSessionId;
@@ -519,10 +528,13 @@ export function useChatController(opts?: { isActive?: boolean }) {
apiLogger.error("sendChatMessage.ensureSession.error", err);
// A revoked invoke permission blocks session create with a structured
// 403 (MUL-4525) — name the cause instead of a generic failure.
+ const reason = dispatchReasonCode(err);
toast.error(
- dispatchReasonCode(err) === "invocation_not_allowed"
+ reason === "invocation_not_allowed"
? t(($) => $.input.send_blocked_toast)
- : t(($) => $.input.send_failed_toast),
+ : reason === "agent_runtime_required"
+ ? t(($) => $.input.runtime_required_toast)
+ : t(($) => $.input.send_failed_toast),
);
return false;
}
@@ -546,10 +558,13 @@ export function useChatController(opts?: { isActive?: boolean }) {
// a structured 403 before anything persists (MUL-4525). Surface the
// specific cause so the user knows it is a permission change, not a
// transient failure they should retry.
+ const reason = dispatchReasonCode(err);
toast.error(
- dispatchReasonCode(err) === "invocation_not_allowed"
+ reason === "invocation_not_allowed"
? t(($) => $.input.send_blocked_toast)
- : t(($) => $.input.send_failed_toast),
+ : reason === "agent_runtime_required"
+ ? t(($) => $.input.runtime_required_toast)
+ : t(($) => $.input.send_failed_toast),
);
return false;
}
@@ -624,6 +639,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
activeSessionId,
activeAgent,
isAgentArchived,
+ isAgentRuntimeBound,
ensureSession,
cancelChatTask,
qc,
@@ -799,6 +815,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
currentSession,
isSessionArchived,
isAgentArchived,
+ isAgentRuntimeBound,
activeAgent,
noAgent,
availability,
diff --git a/packages/views/editor/extensions/mention-suggestion.test.tsx b/packages/views/editor/extensions/mention-suggestion.test.tsx
index 3967b7025b..789f671a5e 100644
--- a/packages/views/editor/extensions/mention-suggestion.test.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.test.tsx
@@ -1,4 +1,4 @@
-import { act, render, screen, waitFor } from "@testing-library/react";
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { createRef, type ReactNode } from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { workspaceKeys } from "@multica/core/workspace/queries";
@@ -10,9 +10,16 @@ import enCommon from "../../locales/en/common.json";
import enAuth from "../../locales/en/auth.json";
import enSettings from "../../locales/en/settings.json";
import enEditor from "../../locales/en/editor.json";
+import enIssues from "../../locales/en/issues.json";
const TEST_RESOURCES = {
- en: { common: enCommon, auth: enAuth, settings: enSettings, editor: enEditor },
+ en: {
+ common: enCommon,
+ auth: enAuth,
+ settings: enSettings,
+ editor: enEditor,
+ issues: enIssues,
+ },
};
function I18nWrapper({ children }: { children: ReactNode }) {
@@ -49,6 +56,12 @@ vi.mock("@multica/core/auth", () => ({
useAuthStore: { getState: () => authState },
}));
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: ({ actorId }: { actorId: string }) => (
+ <span data-testid={`actor-${actorId}`} />
+ ),
+}));
+
import {
createMentionSuggestion,
MentionList,
@@ -62,6 +75,8 @@ function fakeQc(data: {
id: string;
name: string;
archived_at: string | null;
+ runtime_id?: string;
+ runtime_bound?: boolean;
visibility?: "workspace" | "private";
owner_id?: string | null;
permission_mode?: "private" | "public_to";
@@ -74,6 +89,7 @@ function fakeQc(data: {
id: string;
name: string;
archived_at: string | null;
+ leader_id: string;
}>;
issues?: Array<{ id: string; identifier: string; title: string; status: string }>;
}): QueryClient {
@@ -86,6 +102,8 @@ function fakeQc(data: {
// private + no targets otherwise) unless a fixture sets them explicitly.
const agentsWithPermissions = (data.agents ?? []).map((a) => ({
...a,
+ runtime_id: a.runtime_id ?? "runtime-1",
+ runtime_bound: a.runtime_bound ?? true,
permission_mode:
a.permission_mode ?? (a.visibility === "private" ? "private" : "public_to"),
invocation_targets:
@@ -181,6 +199,68 @@ describe("createMentionSuggestion", () => {
expect(items.some((i) => i.type === "agent" && i.label === "Aegis")).toBe(true);
});
+ it("keeps an unbound agent discoverable but marks it as unselectable", () => {
+ const qc = fakeQc({
+ members: [{ user_id: "u1", name: "Alice", role: "member" }],
+ agents: [
+ {
+ id: "a1",
+ name: "Aegis",
+ archived_at: null,
+ runtime_id: "",
+ runtime_bound: false,
+ visibility: "workspace",
+ owner_id: null,
+ },
+ ],
+ });
+
+ const config = createMentionSuggestion(qc);
+ const items = config.items!(itemArgs("a")) as MentionItem[];
+
+ expect(items).toContainEqual(
+ expect.objectContaining({
+ type: "agent",
+ id: "a1",
+ disabledReason: "agent_runtime_required",
+ }),
+ );
+ });
+
+ it("does not select a runtime-required mention row by click or keyboard", () => {
+ const command = vi.fn<(item: MentionItem) => void>();
+ const ref = createRef<MentionListRef>();
+ render(
+ <I18nWrapper>
+ <MentionList
+ ref={ref}
+ items={[
+ {
+ id: "a1",
+ label: "Aegis",
+ type: "agent",
+ disabledReason: "agent_runtime_required",
+ },
+ ]}
+ query=""
+ command={command}
+ />
+ </I18nWrapper>,
+ );
+
+ const row = screen.getByRole("button", {
+ name: "Aegis: This target has no runtime — bind one to run it",
+ });
+ expect(row).toHaveAttribute("aria-disabled", "true");
+ fireEvent.click(row);
+ expect(
+ ref.current?.onKeyDown({
+ event: new KeyboardEvent("keydown", { key: "Enter" }),
+ }),
+ ).toBe(true);
+ expect(command).not.toHaveBeenCalled();
+ });
+
it("loads server issue matches into the popup when the list cache misses", async () => {
searchIssuesMock.mockResolvedValue({
issues: [
@@ -610,13 +690,37 @@ describe("createMentionSuggestion", () => {
expect(screen.getByText("Roadmap")).toBeInTheDocument();
});
- it("includes all non-archived squads in the mention list", () => {
+ it("includes squads with a runnable leader in the mention list", () => {
const qc = fakeQc({
members: [{ user_id: "u1", name: "Alice", role: "member" }],
+ agents: [
+ {
+ id: "leader-1",
+ name: "Leader",
+ archived_at: null,
+ visibility: "workspace",
+ owner_id: null,
+ },
+ ],
squads: [
- { id: "s1", name: "Jiayuan's Coding Team", archived_at: null },
- { id: "s2", name: "独立团", archived_at: null },
- { id: "s3", name: "Archived Squad", archived_at: "2026-01-01T00:00:00Z" },
+ {
+ id: "s1",
+ name: "Jiayuan's Coding Team",
+ archived_at: null,
+ leader_id: "leader-1",
+ },
+ {
+ id: "s2",
+ name: "独立团",
+ archived_at: null,
+ leader_id: "leader-1",
+ },
+ {
+ id: "s3",
+ name: "Archived Squad",
+ archived_at: "2026-01-01T00:00:00Z",
+ leader_id: "leader-1",
+ },
],
});
searchIssuesMock.mockReturnValue(new Promise(() => {}));
@@ -631,6 +735,90 @@ describe("createMentionSuggestion", () => {
expect(items.some((i) => i.type === "squad" && i.label === "Archived Squad")).toBe(false);
});
+ it("keeps a squad with an unbound leader discoverable but unselectable", () => {
+ const qc = fakeQc({
+ agents: [
+ {
+ id: "leader-1",
+ name: "Leader",
+ archived_at: null,
+ runtime_id: "",
+ runtime_bound: false,
+ visibility: "workspace",
+ owner_id: null,
+ },
+ ],
+ squads: [
+ {
+ id: "s1",
+ name: "Unrunnable Squad",
+ archived_at: null,
+ leader_id: "leader-1",
+ },
+ ],
+ });
+
+ const config = createMentionSuggestion(qc);
+ const items = config.items!(itemArgs("")) as MentionItem[];
+
+ expect(items).toContainEqual(
+ expect.objectContaining({
+ type: "squad",
+ id: "s1",
+ disabledReason: "agent_runtime_required",
+ }),
+ );
+ });
+
+ it("keeps squads discoverable while the agents cache is not ready", () => {
+ const qc = fakeQc({
+ squads: [
+ {
+ id: "s1",
+ name: "Cold Cache Squad",
+ archived_at: null,
+ leader_id: "leader-not-cached",
+ },
+ ],
+ });
+
+ const config = createMentionSuggestion(qc);
+ const items = config.items!(itemArgs("")) as MentionItem[];
+ const squad = items.find((item) => item.type === "squad" && item.id === "s1");
+
+ expect(squad).toBeDefined();
+ expect(squad?.disabledReason).toBeUndefined();
+ });
+
+ it("keeps a squad with an archived leader discoverable", () => {
+ const qc = fakeQc({
+ agents: [
+ {
+ id: "leader-1",
+ name: "Archived Leader",
+ archived_at: "2026-01-01T00:00:00Z",
+ visibility: "workspace",
+ owner_id: null,
+ },
+ ],
+ squads: [
+ {
+ id: "s1",
+ name: "Archived Leader Squad",
+ archived_at: null,
+ leader_id: "leader-1",
+ },
+ ],
+ });
+
+ const config = createMentionSuggestion(qc);
+ const items = config.items!(itemArgs("")) as MentionItem[];
+ const squad = items.find((item) => item.type === "squad" && item.id === "s1");
+
+ expect(squad).toBeDefined();
+ expect(squad?.disabledReason).toBeUndefined();
+ });
+
it("returns no squads when the squads cache is empty (not yet fetched)", () => {
const qc = fakeQc({
members: [{ user_id: "u1", name: "Alice", role: "member" }],
diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsx
index 90590c06ba..4d9a2e93a6 100644
--- a/packages/views/editor/extensions/mention-suggestion.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.tsx
@@ -16,6 +16,7 @@ import { flattenIssueBuckets, issueKeys } from "@multica/core/issues/queries";
import { workspaceKeys } from "@multica/core/workspace/queries";
import { useAuthStore } from "@multica/core/auth";
import { canAssignAgentToIssue } from "@multica/core/permissions";
+import { isAgentRuntimeBound } from "@multica/core/agents";
import { api } from "@multica/core/api";
import { isImeComposing } from "@multica/core/utils";
import type {
@@ -31,6 +32,11 @@ import { StatusIcon } from "../../issues/components/status-icon";
import { ProjectIcon } from "../../projects/components/project-icon";
import { useT } from "../../i18n";
import { Badge } from "@multica/ui/components/ui/badge";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
import { cn } from "@multica/ui/lib/utils";
import type { IssueStatus, ProjectStatus } from "@multica/core/types";
import { PROJECT_STATUS_CONFIG } from "@multica/core/projects/config";
@@ -48,6 +54,7 @@ import {
pickerNavigationDirection,
} from "./suggestion-popup";
import { isTriggerArmedAt } from "./suggestion-trigger-arming";
+import { blockedReasonLabel } from "../../issues/blocked-trigger-copy";
// ---------------------------------------------------------------------------
// Types
@@ -67,6 +74,8 @@ export interface MentionItem {
icon?: string | null;
/** Project status snapshot for recent/current project rendering */
projectStatus?: ProjectStatus;
+ /** Present when the target should remain discoverable but cannot be selected. */
+ disabledReason?: "agent_runtime_required";
}
interface MentionListProps {
@@ -257,18 +266,23 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(
// yet, fall back to the first row. This self-heals across reorders and
// async result arrival without ever force-resetting an active selection.
const selectedIndex = useMemo(() => {
- if (selectedKey === null) return 0;
+ const firstSelectable = orderedItems.findIndex((item) => !item.disabledReason);
+ if (selectedKey === null) return firstSelectable;
const i = orderedItems.findIndex((it) => mentionItemKey(it) === selectedKey);
- return i === -1 ? 0 : i;
+ return i === -1 || orderedItems[i]?.disabledReason
+ ? firstSelectable
+ : i;
}, [orderedItems, selectedKey]);
useEffect(() => {
- itemRefs.current[selectedIndex]?.scrollIntoView({ block: "nearest" });
+ if (selectedIndex >= 0) {
+ itemRefs.current[selectedIndex]?.scrollIntoView({ block: "nearest" });
+ }
}, [selectedIndex]);
const selectItem = useCallback(
(item: MentionItem | undefined) => {
- if (!item) return;
+ if (!item || item.disabledReason) return;
const wsId = getCurrentWsId();
if (wsId) recordMentionUsage(wsId, item);
command(item);
@@ -285,16 +299,25 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(
// see pickerNavigationDirection.
const direction = pickerNavigationDirection(event);
if (direction !== null) {
- if (orderedItems.length === 0) return true;
- const delta = direction === "next" ? 1 : orderedItems.length - 1;
- const next = (selectedIndex + delta) % orderedItems.length;
+ const selectableIndexes = orderedItems.flatMap((item, index) =>
+ item.disabledReason ? [] : [index],
+ );
+ if (selectableIndexes.length === 0) return true;
+ const current = selectableIndexes.indexOf(selectedIndex);
+ const delta =
+ direction === "next" ? 1 : selectableIndexes.length - 1;
+ const next =
+ selectableIndexes[
+ ((current === -1 ? 0 : current) + delta) %
+ selectableIndexes.length
+ ]!;
setSelectedKey(mentionItemKey(orderedItems[next]!));
return true;
}
// Enter is the canonical accept; plain Tab is an additive alias (see
// isPickerAcceptKey). Shift/modifier+Tab fall through to focus nav.
if (isPickerAcceptKey(event)) {
- if (orderedItems.length === 0) return true;
+ if (selectedIndex < 0) return true;
selectItem(orderedItems[selectedIndex]);
return true;
}
@@ -395,6 +418,7 @@ function MentionRow({
buttonRef: (el: HTMLButtonElement | null) => void;
}) {
const { t } = useT("editor");
+ const { t: issuesT } = useT("issues");
if (item.type === "issue") {
// Visually dim closed issues (done/cancelled) so they're distinguishable
// from active ones in the suggestion list — they're still selectable.
@@ -460,13 +484,20 @@ function MentionRow({
);
}
- return (
+ const disabledMessage = item.disabledReason
+ ? blockedReasonLabel(item.disabledReason, issuesT)
+ : null;
+ const button = (
<button
type="button"
ref={buttonRef}
+ aria-disabled={disabledMessage ? true : undefined}
+ aria-label={
+ disabledMessage ? `${item.label}: ${disabledMessage}` : undefined
+ }
className={`flex w-full items-center gap-2.5 px-3 py-1.5 text-left text-caption transition-colors ${
- selected ? "bg-accent" : "hover:bg-accent/50"
- }`}
+ selected ? "bg-accent" : disabledMessage ? "" : "hover:bg-accent/50"
+ } ${disabledMessage ? "cursor-not-allowed opacity-50" : ""}`}
onClick={onSelect}
>
<ActorAvatar
@@ -490,6 +521,17 @@ function MentionRow({
)}
</button>
);
+
+ if (!disabledMessage) return button;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger render={button} />
+ <TooltipContent side="top" className="max-w-72 text-caption">
+ {disabledMessage}
+ </TooltipContent>
+ </Tooltip>
+ );
}
// ---------------------------------------------------------------------------
@@ -589,11 +631,35 @@ export function createMentionSuggestion(
(a.name.toLowerCase().includes(q) || matchesPinyin(a.name, q)) &&
canAssignAgentToIssue(a, { userId, role: myRole }).allowed,
)
- .map((a) => ({ id: a.id, label: a.name, type: "agent" as const }));
+ .map((a) => ({
+ id: a.id,
+ label: a.name,
+ type: "agent" as const,
+ disabledReason: isAgentRuntimeBound(a)
+ ? undefined
+ : ("agent_runtime_required" as const),
+ }));
+ const activeAgentRuntimeBinding = new Map(
+ agents
+ .filter((agent) => !agent.archived_at)
+ .map((agent) => [agent.id, isAgentRuntimeBound(agent)]),
+ );
const squadItems: MentionItem[] = squads
- .filter((s) => !s.archived_at && (s.name.toLowerCase().includes(q) || matchesPinyin(s.name, q)))
- .map((s) => ({ id: s.id, label: s.name, type: "squad" as const }));
+ .filter(
+ (s) =>
+ !s.archived_at &&
+ (s.name.toLowerCase().includes(q) || matchesPinyin(s.name, q)),
+ )
+ .map((s) => ({
+ id: s.id,
+ label: s.name,
+ type: "squad" as const,
+ disabledReason:
+ activeAgentRuntimeBinding.get(s.leader_id) === false
+ ? ("agent_runtime_required" as const)
+ : undefined,
+ }));
// Members and agents share a single ranked list — recently mentioned
// targets come first regardless of type, with an alphabetical fallback
diff --git a/packages/views/issues/blocked-trigger-copy.test.ts b/packages/views/issues/blocked-trigger-copy.test.ts
new file mode 100644
index 0000000000..5488132a91
--- /dev/null
+++ b/packages/views/issues/blocked-trigger-copy.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from "vitest";
+
+import { blockedReasonLabel, blockedShortReasonLabel } from "./blocked-trigger-copy";
+import en from "../locales/en/issues.json";
+
+// A blocked mention's copy has to name the fix the user actually has. An unbound
+// agent (agent_runtime_required) and an agent whose machine is offline
+// (runtime_offline) need opposite actions — bind a runtime vs. bring the machine
+// back — so they must never collapse onto the same label. Before MUL-5559 the
+// server reported unbound agents as runtime_offline, which told people to
+// reconnect a computer that no longer existed.
+type Leaf = string | Record<string, unknown>;
+
+// Minimal stand-in for the i18n `t` used by the copy helpers: resolves the
+// selector against the real en bundle so the test fails if a key is missing.
+const t = ((selector: (bundle: unknown) => Leaf) => {
+ const value = selector(en as unknown);
+ if (typeof value !== "string") {
+ throw new Error("selector did not resolve to a string");
+ }
+ return value;
+}) as Parameters<typeof blockedReasonLabel>[1];
+
+describe("blocked trigger copy", () => {
+ it("distinguishes an unbound agent from an offline runtime", () => {
+ const unbound = blockedReasonLabel("agent_runtime_required", t);
+ const offline = blockedReasonLabel("runtime_offline", t);
+
+ expect(unbound).not.toBe(offline);
+ expect(unbound).toBe(en.comment.trigger_blocked_agent_runtime_required);
+ expect(offline).toBe(en.comment.trigger_blocked_runtime_offline);
+ // The unbound label must not tell the user their runtime is offline.
+ expect(unbound.toLowerCase()).not.toContain("offline");
+ });
+
+ it("distinguishes them in the short chip label too", () => {
+ const unbound = blockedShortReasonLabel("agent_runtime_required", t);
+ const offline = blockedShortReasonLabel("runtime_offline", t);
+
+ expect(unbound).not.toBe(offline);
+ expect(unbound).toBe(en.comment.trigger_blocked_short_agent_runtime_required);
+ });
+
+ it("degrades an unknown code to the generic label", () => {
+ expect(blockedReasonLabel("some_future_code", t)).toBe(en.comment.trigger_blocked_generic);
+ expect(blockedShortReasonLabel("some_future_code", t)).toBe(
+ en.comment.trigger_blocked_short_generic,
+ );
+ });
+});
diff --git a/packages/views/issues/blocked-trigger-copy.ts b/packages/views/issues/blocked-trigger-copy.ts
index 49cd204f10..41397cd50a 100644
--- a/packages/views/issues/blocked-trigger-copy.ts
+++ b/packages/views/issues/blocked-trigger-copy.ts
@@ -12,6 +12,11 @@ import type { useT } from "../i18n";
// that blamed permission alone sent people to audit agent visibility settings over
// what was really a mistyped mention uuid (MUL-5548), so both labels name the two
// possibilities instead.
+//
+// `agent_runtime_required` and `runtime_offline` are kept apart for the same
+// reason (MUL-5559): an unbound agent has no machine to reconnect, so "runtime
+// offline" copy sends the user looking for a computer that does not exist. The
+// fix it needs is binding the agent to a runtime.
type IssuesT = ReturnType<typeof useT<"issues">>["t"];
// Full sentence — for tooltips and other surfaces with room to explain.
@@ -23,6 +28,8 @@ export function blockedReasonLabel(reasonCode: string, t: IssuesT): string {
return t(($) => $.comment.trigger_blocked_target_unavailable);
case "runtime_offline":
return t(($) => $.comment.trigger_blocked_runtime_offline);
+ case "agent_runtime_required":
+ return t(($) => $.comment.trigger_blocked_agent_runtime_required);
default:
return t(($) => $.comment.trigger_blocked_generic);
}
@@ -38,6 +45,8 @@ export function blockedShortReasonLabel(reasonCode: string, t: IssuesT): string
return t(($) => $.comment.trigger_blocked_short_target_unavailable);
case "runtime_offline":
return t(($) => $.comment.trigger_blocked_short_runtime_offline);
+ case "agent_runtime_required":
+ return t(($) => $.comment.trigger_blocked_short_agent_runtime_required);
default:
return t(($) => $.comment.trigger_blocked_short_generic);
}
diff --git a/packages/views/issues/components/pickers/assignee-picker.tsx b/packages/views/issues/components/pickers/assignee-picker.tsx
index 0e89bfe498..cba0f111db 100644
--- a/packages/views/issues/components/pickers/assignee-picker.tsx
+++ b/packages/views/issues/components/pickers/assignee-picker.tsx
@@ -5,6 +5,7 @@ import { Lock, UserMinus } from "lucide-react";
import type { Agent, IssueAssigneeType, UpdateIssueRequest } from "@multica/core/types";
import { useQuery } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
+import { isAgentRuntimeBound } from "@multica/core/agents";
import { canAssignAgentToIssue } from "@multica/core/permissions";
import { useActorName } from "@multica/core/workspace/hooks";
import { useWorkspaceId } from "@multica/core/hooks";
@@ -136,6 +137,11 @@ function AssigneePickerImpl({
const filteredSquads = squads
.filter((s) => !s.archived_at && (s.name.toLowerCase().includes(query) || matchesPinyin(s.name, query)))
.sort((a, b) => getFreq("squad", b.id) - getFreq("squad", a.id));
+ const runnableAgentIds = new Set(
+ agents
+ .filter((agent) => !agent.archived_at && isAgentRuntimeBound(agent))
+ .map((agent) => agent.id),
+ );
const isSelected = (type: string, id: string) =>
assigneeType === type && assigneeId === id;
@@ -218,13 +224,20 @@ function AssigneePickerImpl({
? memberRole
: null,
});
- const allowed = decision.allowed;
+ const runtimeBound = isAgentRuntimeBound(a);
+ const allowed = decision.allowed && runtimeBound;
return (
<PickerItem
key={a.id}
selected={isSelected("agent", a.id)}
disabled={!allowed}
- tooltip={!allowed ? decision.message : undefined}
+ tooltip={
+ !decision.allowed
+ ? decision.message
+ : !runtimeBound
+ ? t(($) => $.pickers.assignee.agent_runtime_required)
+ : undefined
+ }
onClick={() => {
if (!allowed) return;
onUpdate({
@@ -249,22 +262,32 @@ function AssigneePickerImpl({
its leader agent on the backend. */}
{filteredSquads.length > 0 && (
<PickerSection label={t(($) => $.pickers.assignee.squads_group)}>
- {filteredSquads.map((s) => (
- <PickerItem
- key={s.id}
- selected={isSelected("squad", s.id)}
- onClick={() => {
- onUpdate({
- assignee_type: "squad",
- assignee_id: s.id,
- });
- setOpen(false);
- }}
- >
- <ActorAvatar actorType="squad" actorId={s.id} size="sm" />
- <span className="truncate">{s.name}</span>
- </PickerItem>
- ))}
+ {filteredSquads.map((s) => {
+ const runtimeBound = runnableAgentIds.has(s.leader_id);
+ return (
+ <PickerItem
+ key={s.id}
+ selected={isSelected("squad", s.id)}
+ disabled={!runtimeBound}
+ tooltip={
+ runtimeBound
+ ? undefined
+ : t(($) => $.pickers.assignee.squad_runtime_required)
+ }
+ onClick={() => {
+ if (!runtimeBound) return;
+ onUpdate({
+ assignee_type: "squad",
+ assignee_id: s.id,
+ });
+ setOpen(false);
+ }}
+ >
+ <ActorAvatar actorType="squad" actorId={s.id} size="sm" />
+ <span className="truncate">{s.name}</span>
+ </PickerItem>
+ );
+ })}
</PickerSection>
)}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index d4620b1b8e..eb4a7f4e76 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -77,6 +77,7 @@
"row": {
"you": "You",
"archived": "Archived",
+ "needs_runtime": "Needs a runtime",
"no_description": "No description",
"fallback_runtime_cloud": "Cloud",
"fallback_runtime_local": "Local",
@@ -139,6 +140,8 @@
"no_access_hint": "Only the agent owner or a workspace admin can view this private agent.",
"try_again": "Try again",
"archived_banner": "This agent is archived. It cannot be assigned or mentioned.",
+ "runtime_required_banner": "This agent kept its configuration and history, but needs a runtime before it can run.",
+ "bind_runtime": "Bind runtime",
"restore": "Restore",
"archive_dialog_title": "Archive agent?",
"archive_dialog_description": "\"{{name}}\" will be archived. It won't be assignable or mentionable, but all history is preserved. You can restore it later.",
@@ -153,6 +156,7 @@
"restore_failed_toast": "Failed to restore agent",
"dm": "DM",
"dm_no_permission_toast": "You don't have access to chat with this agent.",
+ "runtime_required_toast": "Bind a runtime before running this agent.",
"assign_work": "Assign work",
"more_actions_aria": "Agent actions",
"updated": "Updated {{when}}"
diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.json
index 5c5286ab72..4f04415bd9 100644
--- a/packages/views/locales/en/autopilots.json
+++ b/packages/views/locales/en/autopilots.json
@@ -27,6 +27,7 @@
"status": {
"active": "Active",
"paused": "Paused",
+ "paused_runtime_required": "Paused — the assignee needs a runtime",
"archived": "Archived"
},
"execution_mode": {
@@ -69,6 +70,8 @@
"not_found": "Autopilot not found",
"pause_aria": "Pause autopilot",
"activate_aria": "Activate autopilot",
+ "paused_runtime_required": "Paused because the assignee lost its runtime. Bind a runtime, then reactivate this autopilot.",
+ "bind_runtime": "Bind runtime",
"edit": "Edit",
"run_now": "Run now",
"running": "Running...",
@@ -76,6 +79,7 @@
"toast_trigger_failed": "Failed to trigger autopilot",
"run_blocked_invocation_not_allowed": "Not triggered — you don't have permission to use this autopilot's agent",
"run_blocked_runtime_offline": "Not triggered — the agent's runtime is offline",
+ "run_blocked_agent_runtime_required": "Not triggered — the agent has no runtime; bind one to run it",
"run_blocked_target_unavailable": "Not triggered — the agent is unavailable",
"run_blocked_attribution": "Not triggered — the run couldn't be attributed to a responsible member",
"run_blocked_already_active": "Not triggered — a recent run already covers this",
@@ -410,7 +414,9 @@
"select_agent": "Select agent",
"select_assignee": "Select agent or squad",
"agents_group": "Agents",
- "squads_group": "Squads"
+ "squads_group": "Squads",
+ "agent_runtime_required": "Bind a runtime before selecting this agent",
+ "squad_runtime_required": "Bind a runtime to this squad's leader before selecting it"
},
"timezone_picker": {
"search_placeholder": "Search timezone..."
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index b5e51458fe..aa82eec11a 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -14,12 +14,14 @@
"placeholder_no_agent": "Create an agent to start chatting",
"placeholder_archived": "This session is archived",
"placeholder_archived_agent": "This agent has been archived",
+ "placeholder_runtime_required": "Bind a runtime to continue",
"placeholder_named": "Message {{name}}…",
"placeholder_default": "Start a message…",
"send_tooltip": "Send",
"stop_tooltip": "Stop",
"send_failed_toast": "Failed to send message",
"send_blocked_toast": "Message not sent — you no longer have permission to use this agent",
+ "runtime_required_toast": "Message not sent — bind a runtime to this agent first",
"attachment_bind_failed_toast": "Message sent, but files were not attached. Please try again in a moment.",
"add_tooltip": "Add",
"upload_file": "Image or files",
@@ -115,7 +117,9 @@
"others": "Others",
"no_agents": "No agents",
"history_group": "Chat history",
- "agent_filter_placeholder": "Search agents..."
+ "agent_filter_placeholder": "Search agents...",
+ "agent_needs_runtime": "Needs runtime",
+ "agent_needs_runtime_hint": "Bind a runtime before starting a chat with this agent"
},
"empty_state": {
"first_time_title": "Chat with your agents",
@@ -135,6 +139,11 @@
},
"no_agent_banner": "You need an agent to start chatting.",
"archived_agent_banner": "{{name}} has been archived — this conversation is read-only.",
+ "runtime_required_banner": {
+ "fallback_name": "The agent",
+ "message": "{{name}} needs a runtime before it can reply.",
+ "action": "Bind runtime"
+ },
"offline_banner": {
"fallback_name": "the agent",
"unstable": "{{name}}'s connection is unstable — replies may be delayed.",
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 1ccf84ae5c..34434ca0d3 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -390,10 +390,12 @@
"trigger_blocked_invocation_not_allowed": "This target can't be found, or you don't have permission to use it",
"trigger_blocked_target_unavailable": "This target is unavailable",
"trigger_blocked_runtime_offline": "This target's runtime is offline",
+ "trigger_blocked_agent_runtime_required": "This target has no runtime — bind one to run it",
"trigger_blocked_generic": "This target won't be triggered",
"trigger_blocked_short_invocation_not_allowed": "Not found or no permission",
"trigger_blocked_short_target_unavailable": "Unavailable",
"trigger_blocked_short_runtime_offline": "Runtime offline",
+ "trigger_blocked_short_agent_runtime_required": "Needs a runtime",
"trigger_blocked_short_generic": "Won't start",
"send_reply_failed": "Failed to send reply",
"delete_failed": "Failed to delete comment",
@@ -598,7 +600,9 @@
"search_placeholder": "Assign to...",
"members_group": "Members",
"agents_group": "Agents",
- "squads_group": "Squads"
+ "squads_group": "Squads",
+ "agent_runtime_required": "Bind a runtime before assigning work to this agent",
+ "squad_runtime_required": "Bind a runtime to this squad's leader before assigning work"
},
"start_date": {
"trigger_label": "Start date",
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.json
index 142f553ec0..a1028aeb60 100644
--- a/packages/views/locales/en/runtimes.json
+++ b/packages/views/locales/en/runtimes.json
@@ -140,18 +140,18 @@
"submitting": "Deleting..."
},
"cascade": {
- "title_one": "Archive {{count}} agent and delete this Runtime?",
- "title_other": "Archive {{count}} agents and delete this Runtime?",
- "description": "Delete \"{{name}}\". The agents below will be archived and removed from active workflows; their queued or running tasks will be cancelled, and then the Runtime will be deleted.",
- "warning": "This is destructive. Archived agents will be removed from active workflows and their queued or running tasks will be cancelled.",
+ "title_one": "Unbind {{count}} agent and delete this Runtime?",
+ "title_other": "Unbind {{count}} agents and delete this Runtime?",
+ "description": "Delete \"{{name}}\". The agents below are kept — their instructions, chats and task history stay intact — but they will be unbound and cannot run until you bind them to another runtime. Their queued or running tasks will be cancelled, and then the Runtime will be deleted.",
+ "warning": "Queued and running tasks will be cancelled, and these agents cannot be assigned new work until they are bound to a runtime.",
"notice_runtime_has_active_agents": "Active agents were added since you opened this dialog. Review the new plan and confirm.",
"notice_runtime_delete_plan_changed": "The active agent set changed while this dialog was open. Review the new plan and confirm.",
- "checkbox_one": "I understand this {{count}} agent will be archived and any queued or running tasks will be cancelled.",
- "checkbox_other": "I understand these {{count}} agents will be archived and any queued or running tasks will be cancelled.",
+ "checkbox_one": "I understand this {{count}} agent will be unbound and cannot run until I bind it to a runtime, and that any queued or running tasks will be cancelled.",
+ "checkbox_other": "I understand these {{count}} agents will be unbound and cannot run until I bind them to a runtime, and that any queued or running tasks will be cancelled.",
"cancel": "Cancel",
- "confirm_one": "Archive {{count}} agent and delete runtime",
- "confirm_other": "Archive {{count}} agents and delete runtime",
- "submitting": "Archiving and deleting...",
+ "confirm_one": "Unbind {{count}} agent and delete runtime",
+ "confirm_other": "Unbind {{count}} agents and delete runtime",
+ "submitting": "Unbinding and deleting...",
"delete_failed_toast": "Failed to delete runtime",
"table": {
"header_agent": "Agent",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 7037310dc6..a28f0b86b0 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -68,6 +68,7 @@
"row": {
"you": "あなた",
"archived": "アーカイブ済み",
+ "needs_runtime": "ランタイム未設定",
"no_description": "説明なし",
"fallback_runtime_cloud": "クラウド",
"fallback_runtime_local": "ローカル",
@@ -123,6 +124,8 @@
"no_access_hint": "この非公開エージェントは、エージェントのオーナーまたはワークスペースの admin のみが閲覧できます。",
"try_again": "再試行",
"archived_banner": "このエージェントはアーカイブされています。割り当てやメンションはできません。",
+ "runtime_required_banner": "このエージェントの設定と履歴は保持されていますが、実行するにはランタイムを設定する必要があります。",
+ "bind_runtime": "ランタイムを設定",
"restore": "復元",
"archive_dialog_title": "エージェントをアーカイブしますか?",
"archive_dialog_description": "\"{{name}}\" がアーカイブされます。割り当てやメンションはできなくなりますが、履歴はすべて保持されます。後で復元できます。",
@@ -137,6 +140,7 @@
"restore_failed_toast": "エージェントを復元できませんでした",
"dm": "DM",
"dm_no_permission_toast": "このエージェントとチャットする権限がありません。",
+ "runtime_required_toast": "このエージェントを実行する前にランタイムを設定してください。",
"assign_work": "作業を割り当てる",
"more_actions_aria": "エージェントの操作",
"updated": "{{when}}に更新"
diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.json
index c6aae98393..c8a9727e96 100644
--- a/packages/views/locales/ja/autopilots.json
+++ b/packages/views/locales/ja/autopilots.json
@@ -27,6 +27,7 @@
"status": {
"active": "アクティブ",
"paused": "一時停止中",
+ "paused_runtime_required": "一時停止中 — 担当エージェントのランタイムが必要です",
"archived": "アーカイブ済み"
},
"execution_mode": {
@@ -69,6 +70,8 @@
"not_found": "オートパイロットが見つかりません",
"pause_aria": "オートパイロットを一時停止",
"activate_aria": "オートパイロットを有効化",
+ "paused_runtime_required": "担当エージェントのランタイムが失われたため一時停止しました。ランタイムを設定してから再度有効にしてください。",
+ "bind_runtime": "ランタイムを設定",
"edit": "編集",
"run_now": "今すぐ実行",
"running": "実行中...",
@@ -76,6 +79,7 @@
"toast_trigger_failed": "オートパイロットを実行できませんでした",
"run_blocked_invocation_not_allowed": "実行されませんでした — このオートパイロットのエージェントを使用する権限がありません",
"run_blocked_runtime_offline": "実行されませんでした — エージェントのランタイムがオフラインです",
+ "run_blocked_agent_runtime_required": "実行されませんでした — エージェントにランタイムがありません。実行するにはバインドしてください",
"run_blocked_target_unavailable": "実行されませんでした — エージェントを利用できません",
"run_blocked_attribution": "実行されませんでした — 実行の責任者を特定できませんでした",
"run_blocked_already_active": "実行されませんでした — 直近の実行が本件をカバーしています",
@@ -410,7 +414,9 @@
"select_agent": "エージェントを選択",
"select_assignee": "エージェントまたはスクワッドを選択",
"agents_group": "エージェント",
- "squads_group": "スクワッド"
+ "squads_group": "スクワッド",
+ "agent_runtime_required": "このエージェントを選択する前にランタイムをバインドしてください",
+ "squad_runtime_required": "選択する前に、このスクワッドのリーダーにランタイムをバインドしてください"
},
"timezone_picker": {
"search_placeholder": "タイムゾーンを検索..."
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index 270bd5bbdf..1c02524b02 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -13,12 +13,14 @@
"placeholder_no_agent": "チャットを始めるにはエージェントを作成してください",
"placeholder_archived": "このセッションはアーカイブされています",
"placeholder_archived_agent": "このエージェントはアーカイブされています",
+ "placeholder_runtime_required": "ランタイムを設定して続ける",
"placeholder_named": "{{name}} にメッセージ…",
"placeholder_default": "メッセージを入力…",
"send_tooltip": "送信",
"stop_tooltip": "停止",
"send_failed_toast": "メッセージを送信できませんでした",
"send_blocked_toast": "メッセージは送信されませんでした — このエージェントを使用する権限がありません",
+ "runtime_required_toast": "メッセージは送信されませんでした — 先にこのエージェントのランタイムを設定してください",
"attachment_bind_failed_toast": "メッセージは送信されましたが、ファイルを添付できませんでした。しばらくしてからもう一度お試しください。",
"add_tooltip": "追加",
"upload_file": "画像・ファイル",
@@ -112,7 +114,9 @@
"others": "その他",
"no_agents": "エージェントなし",
"history_group": "チャット履歴",
- "agent_filter_placeholder": "エージェントを検索..."
+ "agent_filter_placeholder": "エージェントを検索...",
+ "agent_needs_runtime": "ランタイム未設定",
+ "agent_needs_runtime_hint": "このエージェントとチャットする前にランタイムを設定してください"
},
"empty_state": {
"first_time_title": "エージェントとチャット",
@@ -132,6 +136,11 @@
},
"no_agent_banner": "チャットを始めるにはエージェントが必要です。",
"archived_agent_banner": "{{name}} はアーカイブされました。この会話は読み取り専用です。",
+ "runtime_required_banner": {
+ "fallback_name": "このエージェント",
+ "message": "{{name}} が返信するにはランタイムの設定が必要です。",
+ "action": "ランタイムを設定"
+ },
"offline_banner": {
"fallback_name": "エージェント",
"unstable": "{{name}} の接続が不安定です。返信が遅れる場合があります。",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 293b2037ed..37cb813bb0 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -382,10 +382,12 @@
"trigger_blocked_invocation_not_allowed": "この対象が見つからないか、使用する権限がありません",
"trigger_blocked_target_unavailable": "この対象は利用できません",
"trigger_blocked_runtime_offline": "この対象のランタイムがオフラインです",
+ "trigger_blocked_agent_runtime_required": "この対象にはランタイムがありません — 実行するにはバインドしてください",
"trigger_blocked_generic": "この対象はトリガーされません",
"trigger_blocked_short_invocation_not_allowed": "未検出または権限なし",
"trigger_blocked_short_target_unavailable": "利用不可",
"trigger_blocked_short_runtime_offline": "ランタイム オフライン",
+ "trigger_blocked_short_agent_runtime_required": "ランタイム未設定",
"trigger_blocked_short_generic": "トリガーされません",
"send_reply_failed": "返信を送信できませんでした",
"delete_failed": "コメントを削除できませんでした",
@@ -573,7 +575,9 @@
"search_placeholder": "担当者を割り当て...",
"members_group": "メンバー",
"agents_group": "エージェント",
- "squads_group": "スクワッド"
+ "squads_group": "スクワッド",
+ "agent_runtime_required": "作業を割り当てる前に、このエージェントにランタイムをバインドしてください",
+ "squad_runtime_required": "作業を割り当てる前に、このスクワッドのリーダーにランタイムをバインドしてください"
},
"start_date": {
"trigger_label": "開始日",
diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.json
index a776ce19db..af0482f2a7 100644
--- a/packages/views/locales/ja/runtimes.json
+++ b/packages/views/locales/ja/runtimes.json
@@ -135,15 +135,15 @@
"submitting": "削除中..."
},
"cascade": {
- "title_other": "エージェント {{count}} 個をアーカイブして、このランタイムを削除しますか?",
- "description": "「{{name}}」を削除します。下のエージェントはアーカイブされてアクティブなワークフローから除外され、キュー待ちまたは実行中のタスクはキャンセルされ、その後ランタイムが削除されます。",
- "warning": "これは破壊的な操作です。アーカイブされたエージェントはアクティブなワークフローから除外され、キュー待ちまたは実行中のタスクはキャンセルされます。",
+ "title_other": "{{count}} 体のエージェントのバインドを解除してこのランタイムを削除しますか?",
+ "description": "「{{name}}」を削除します。以下のエージェントは保持され、指示・チャット・タスク履歴は失われません。ただしバインドが解除されるため、別のランタイムにバインドするまで実行できません。キュー中または実行中のタスクはキャンセルされ、その後ランタイムが削除されます。",
+ "warning": "キュー中および実行中のタスクはキャンセルされます。ランタイムにバインドするまで、これらのエージェントに新しい作業を割り当てることはできません。",
"notice_runtime_has_active_agents": "このダイアログを開いてからアクティブなエージェントが追加されました。新しい計画を確認して承認してください。",
"notice_runtime_delete_plan_changed": "このダイアログを開いている間にアクティブなエージェントの一覧が変わりました。新しい計画を確認して承認してください。",
- "checkbox_other": "エージェント {{count}} 個がアーカイブされ、キュー待ちまたは実行中のタスクがキャンセルされることを理解しました。",
+ "checkbox_other": "これら {{count}} 体のエージェントはバインドが解除され、ランタイムにバインドするまで実行できないこと、キュー中または実行中のタスクがキャンセルされることを理解しました。",
"cancel": "キャンセル",
- "confirm_other": "エージェント {{count}} 個をアーカイブしてランタイムを削除",
- "submitting": "アーカイブして削除中...",
+ "confirm_other": "{{count}} 体のバインドを解除してランタイムを削除",
+ "submitting": "バインド解除して削除中...",
"delete_failed_toast": "ランタイムを削除できませんでした",
"table": {
"header_agent": "エージェント",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 3e326754d0..4af7f3744d 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -76,6 +76,7 @@
"row": {
"you": "나",
"archived": "보관됨",
+ "needs_runtime": "런타임 필요",
"no_description": "설명 없음",
"fallback_runtime_cloud": "클라우드",
"fallback_runtime_local": "로컬",
@@ -131,6 +132,8 @@
"no_access_hint": "비공개 에이전트는 에이전트 소유자 또는 워크스페이스 관리자만 볼 수 있습니다.",
"try_again": "다시 시도",
"archived_banner": "보관된 에이전트입니다. 할당하거나 멘션할 수 없습니다.",
+ "runtime_required_banner": "이 에이전트의 설정과 기록은 보존되었지만 실행하려면 런타임을 연결해야 합니다.",
+ "bind_runtime": "런타임 연결",
"restore": "복원",
"archive_dialog_title": "에이전트를 보관할까요?",
"archive_dialog_description": "\"{{name}}\"이(가) 보관됩니다. 할당하거나 멘션할 수 없지만 기록은 유지됩니다. 나중에 복원할 수 있습니다.",
@@ -145,6 +148,7 @@
"restore_failed_toast": "에이전트를 복원하지 못했습니다",
"dm": "DM",
"dm_no_permission_toast": "이 에이전트와 채팅할 권한이 없습니다.",
+ "runtime_required_toast": "이 에이전트를 실행하기 전에 런타임을 연결하세요.",
"assign_work": "작업 할당",
"more_actions_aria": "에이전트 작업",
"updated": "{{when}} 업데이트됨"
diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.json
index a6df211655..008d339c7d 100644
--- a/packages/views/locales/ko/autopilots.json
+++ b/packages/views/locales/ko/autopilots.json
@@ -27,6 +27,7 @@
"status": {
"active": "활성",
"paused": "일시 중지",
+ "paused_runtime_required": "일시 중지됨 — 담당 에이전트에 런타임이 필요합니다",
"archived": "보관됨"
},
"execution_mode": {
@@ -69,6 +70,8 @@
"not_found": "오토파일럿을 찾을 수 없습니다",
"pause_aria": "오토파일럿 일시 중지",
"activate_aria": "오토파일럿 활성화",
+ "paused_runtime_required": "담당 에이전트의 런타임이 없어 자동화가 일시 중지되었습니다. 런타임을 연결한 후 다시 활성화하세요.",
+ "bind_runtime": "런타임 연결",
"edit": "수정",
"run_now": "지금 실행",
"running": "실행 중...",
@@ -76,6 +79,7 @@
"toast_trigger_failed": "오토파일럿을 실행하지 못했습니다",
"run_blocked_invocation_not_allowed": "실행되지 않음 — 이 오토파일럿의 에이전트를 사용할 권한이 없습니다",
"run_blocked_runtime_offline": "실행되지 않음 — 에이전트의 런타임이 오프라인입니다",
+ "run_blocked_agent_runtime_required": "실행되지 않음 — 에이전트에 런타임이 없습니다. 실행하려면 런타임을 연결하세요",
"run_blocked_target_unavailable": "실행되지 않음 — 에이전트를 사용할 수 없습니다",
"run_blocked_attribution": "실행되지 않음 — 실행의 책임 구성원을 확인할 수 없습니다",
"run_blocked_already_active": "실행되지 않음 — 최근 실행이 이미 이 건을 처리했습니다",
@@ -410,7 +414,9 @@
"select_agent": "에이전트 선택",
"select_assignee": "에이전트 또는 스쿼드 선택",
"agents_group": "에이전트",
- "squads_group": "스쿼드"
+ "squads_group": "스쿼드",
+ "agent_runtime_required": "이 에이전트를 선택하기 전에 런타임을 연결하세요",
+ "squad_runtime_required": "선택하기 전에 이 스쿼드 리더에 런타임을 연결하세요"
},
"timezone_picker": {
"search_placeholder": "시간대 검색..."
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index 60b67332aa..d3984fe58f 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -13,12 +13,14 @@
"placeholder_no_agent": "채팅을 시작하려면 에이전트를 만드세요",
"placeholder_archived": "보관된 세션입니다",
"placeholder_archived_agent": "보관된 에이전트입니다",
+ "placeholder_runtime_required": "런타임을 연결한 후 계속하세요",
"placeholder_named": "{{name}}에게 메시지 보내기…",
"placeholder_default": "메시지 입력…",
"send_tooltip": "보내기",
"stop_tooltip": "중지",
"send_failed_toast": "메시지를 보내지 못했습니다",
"send_blocked_toast": "메시지가 전송되지 않았습니다 — 이 에이전트를 사용할 권한이 없습니다",
+ "runtime_required_toast": "메시지가 전송되지 않았습니다 — 먼저 이 에이전트에 런타임을 연결하세요",
"attachment_bind_failed_toast": "메시지는 보냈지만 파일이 첨부되지 않았습니다. 잠시 후 다시 시도해 주세요.",
"add_tooltip": "추가",
"upload_file": "이미지 또는 파일",
@@ -112,7 +114,9 @@
"others": "기타",
"no_agents": "에이전트 없음",
"history_group": "채팅 기록",
- "agent_filter_placeholder": "에이전트 검색..."
+ "agent_filter_placeholder": "에이전트 검색...",
+ "agent_needs_runtime": "런타임 필요",
+ "agent_needs_runtime_hint": "이 에이전트와 채팅하기 전에 런타임을 연결하세요"
},
"empty_state": {
"first_time_title": "에이전트와 채팅하기",
@@ -132,6 +136,11 @@
},
"no_agent_banner": "채팅을 시작하려면 에이전트가 필요합니다.",
"archived_agent_banner": "{{name}}은(는) 보관되었습니다. 이 대화는 읽기 전용입니다.",
+ "runtime_required_banner": {
+ "fallback_name": "이 에이전트",
+ "message": "{{name}} 에이전트가 응답하려면 런타임을 연결해야 합니다.",
+ "action": "런타임 연결"
+ },
"offline_banner": {
"fallback_name": "에이전트",
"unstable": "{{name}}의 연결이 불안정합니다. 답변이 지연될 수 있습니다.",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 701a5212dd..94b8d9f175 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -382,10 +382,12 @@
"trigger_blocked_invocation_not_allowed": "이 대상을 찾을 수 없거나 사용할 권한이 없습니다",
"trigger_blocked_target_unavailable": "이 대상을 사용할 수 없습니다",
"trigger_blocked_runtime_offline": "이 대상의 런타임이 오프라인입니다",
+ "trigger_blocked_agent_runtime_required": "이 대상에 런타임이 없습니다 — 실행하려면 런타임을 연결하세요",
"trigger_blocked_generic": "이 대상은 트리거되지 않습니다",
"trigger_blocked_short_invocation_not_allowed": "찾을 수 없음 또는 권한 없음",
"trigger_blocked_short_target_unavailable": "사용 불가",
"trigger_blocked_short_runtime_offline": "런타임 오프라인",
+ "trigger_blocked_short_agent_runtime_required": "런타임 필요",
"trigger_blocked_short_generic": "트리거 안 됨",
"send_reply_failed": "답글을 보내지 못했습니다",
"delete_failed": "댓글을 삭제하지 못했습니다",
@@ -573,7 +575,9 @@
"search_placeholder": "담당자 지정...",
"members_group": "멤버",
"agents_group": "에이전트",
- "squads_group": "스쿼드"
+ "squads_group": "스쿼드",
+ "agent_runtime_required": "작업을 할당하기 전에 이 에이전트에 런타임을 연결하세요",
+ "squad_runtime_required": "작업을 할당하기 전에 이 스쿼드의 리더에 런타임을 연결하세요"
},
"start_date": {
"trigger_label": "시작일",
diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.json
index 33754163e0..c06fc230f5 100644
--- a/packages/views/locales/ko/runtimes.json
+++ b/packages/views/locales/ko/runtimes.json
@@ -135,15 +135,15 @@
"submitting": "삭제하는 중..."
},
"cascade": {
- "title_other": "에이전트 {{count}}개를 보관하고 이 런타임을 삭제할까요?",
- "description": "\"{{name}}\"을(를) 삭제합니다. 아래 에이전트는 보관되어 활성 워크플로에서 제거되고, 대기 중이거나 실행 중인 작업은 취소된 뒤 런타임이 삭제됩니다.",
- "warning": "파괴적인 작업입니다. 보관된 에이전트는 활성 워크플로에서 제거되고 대기 중이거나 실행 중인 작업은 취소됩니다.",
+ "title_other": "에이전트 {{count}}개의 런타임 연결을 해제하고 이 런타임을 삭제할까요?",
+ "description": "\"{{name}}\"을 삭제합니다. 아래 에이전트는 유지되며 지침, 채팅, 작업 기록도 그대로 남습니다. 다만 런타임 연결이 해제되어 다른 런타임에 연결할 때까지 실행할 수 없습니다. 대기 중이거나 실행 중인 작업은 취소되고, 그다음 런타임이 삭제됩니다.",
+ "warning": "대기 중과 실행 중인 작업은 취소되며, 런타임에 연결하기 전까지 이 에이전트에 새 작업을 할당할 수 없습니다.",
"notice_runtime_has_active_agents": "이 대화상자를 연 뒤 활성 에이전트가 추가되었습니다. 새 계획을 확인한 뒤 승인하세요.",
"notice_runtime_delete_plan_changed": "대화상자가 열린 동안 활성 에이전트 목록이 바뀌었습니다. 새 계획을 확인한 뒤 승인하세요.",
- "checkbox_other": "에이전트 {{count}}개가 보관되고 대기 중이거나 실행 중인 작업이 취소된다는 점을 이해했습니다.",
+ "checkbox_other": "이 에이전트 {{count}}개의 런타임 연결이 해제되어 런타임에 연결할 때까지 실행할 수 없고, 대기 중이거나 실행 중인 작업이 취소된다는 점을 이해했습니다.",
"cancel": "취소",
- "confirm_other": "에이전트 {{count}}개 보관 및 런타임 삭제",
- "submitting": "보관하고 삭제하는 중...",
+ "confirm_other": "에이전트 {{count}}개 연결 해제 후 런타임 삭제",
+ "submitting": "연결 해제 후 삭제 중...",
"delete_failed_toast": "런타임을 삭제하지 못했습니다",
"table": {
"header_agent": "에이전트",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index a96650a6e8..db62668304 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -76,6 +76,7 @@
"row": {
"you": "你",
"archived": "已归档",
+ "needs_runtime": "需绑定运行时",
"no_description": "暂无描述",
"fallback_runtime_cloud": "云端",
"fallback_runtime_local": "本地",
@@ -131,6 +132,8 @@
"no_access_hint": "只有该私密智能体的拥有者或工作区管理员可以查看。",
"try_again": "重试",
"archived_banner": "该智能体已归档,无法被分配或提及。",
+ "runtime_required_banner": "该智能体的配置和历史记录已保留,但需要绑定运行时后才能运行。",
+ "bind_runtime": "绑定运行时",
"restore": "恢复",
"archive_dialog_title": "归档智能体?",
"archive_dialog_description": "\"{{name}}\"将被归档,无法被分配或提及,但所有历史会被保留。可以稍后恢复。",
@@ -145,6 +148,7 @@
"restore_failed_toast": "恢复智能体失败",
"dm": "私信",
"dm_no_permission_toast": "你没有权限与该智能体聊天。",
+ "runtime_required_toast": "请先绑定运行时,再运行该智能体。",
"assign_work": "分配工作",
"more_actions_aria": "智能体操作",
"updated": "{{when}}更新"
diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.json
index b8e2622daf..26abb72edf 100644
--- a/packages/views/locales/zh-Hans/autopilots.json
+++ b/packages/views/locales/zh-Hans/autopilots.json
@@ -27,6 +27,7 @@
"status": {
"active": "启用",
"paused": "已暂停",
+ "paused_runtime_required": "已暂停——执行智能体需绑定运行时",
"archived": "已归档"
},
"execution_mode": {
@@ -69,6 +70,8 @@
"not_found": "未找到该自动化",
"pause_aria": "暂停自动化",
"activate_aria": "启用自动化",
+ "paused_runtime_required": "由于执行智能体失去运行时,自动化已暂停。绑定运行时后请重新启用。",
+ "bind_runtime": "绑定运行时",
"edit": "编辑",
"run_now": "立即运行",
"running": "运行中...",
@@ -76,6 +79,7 @@
"toast_trigger_failed": "触发自动化失败",
"run_blocked_invocation_not_allowed": "未触发——你没有该自动化所用智能体的使用权限",
"run_blocked_runtime_offline": "未触发——该智能体的运行时已离线",
+ "run_blocked_agent_runtime_required": "未触发——该智能体未绑定运行时,绑定后才能运行",
"run_blocked_target_unavailable": "未触发——该智能体不可用",
"run_blocked_attribution": "未触发——无法确定本次运行的负责成员",
"run_blocked_already_active": "未触发——最近已有一次运行覆盖了本次",
@@ -410,7 +414,9 @@
"select_agent": "选择智能体",
"select_assignee": "选择智能体或小队",
"agents_group": "智能体",
- "squads_group": "小队"
+ "squads_group": "小队",
+ "agent_runtime_required": "请先为该智能体绑定运行时",
+ "squad_runtime_required": "请先为该小队的负责人绑定运行时"
},
"timezone_picker": {
"search_placeholder": "搜索时区..."
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index ef63277e51..e5f6d592c2 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -13,12 +13,14 @@
"placeholder_no_agent": "创建一个智能体后才能开始对话",
"placeholder_archived": "此会话已归档",
"placeholder_archived_agent": "该智能体已归档",
+ "placeholder_runtime_required": "绑定运行时后继续",
"placeholder_named": "给 {{name}} 发消息…",
"placeholder_default": "输入消息…",
"send_tooltip": "发送",
"stop_tooltip": "停止",
"send_failed_toast": "发送消息失败",
"send_blocked_toast": "消息未发送——你已没有该智能体的使用权限",
+ "runtime_required_toast": "消息未发送——请先为该智能体绑定运行时",
"attachment_bind_failed_toast": "消息已发送,但文件未能附加。请稍后重试。",
"add_tooltip": "添加",
"upload_file": "图片或文件",
@@ -112,7 +114,9 @@
"others": "其他",
"no_agents": "暂无智能体",
"history_group": "历史对话",
- "agent_filter_placeholder": "搜索智能体..."
+ "agent_filter_placeholder": "搜索智能体...",
+ "agent_needs_runtime": "需绑定运行时",
+ "agent_needs_runtime_hint": "请先绑定运行时,再与该智能体开始对话"
},
"empty_state": {
"first_time_title": "和你的智能体对话",
@@ -132,6 +136,11 @@
},
"no_agent_banner": "需要先有一个智能体才能开始对话。",
"archived_agent_banner": "{{name}} 已归档——此会话为只读。",
+ "runtime_required_banner": {
+ "fallback_name": "该智能体",
+ "message": "{{name}} 需要绑定运行时后才能回复。",
+ "action": "绑定运行时"
+ },
"offline_banner": {
"fallback_name": "智能体",
"unstable": "{{name}} 的连接不稳定——回复可能延迟。",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index d4b5d569a7..3dbb0aa963 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -382,10 +382,12 @@
"trigger_blocked_invocation_not_allowed": "找不到该目标,或你没有它的使用权限",
"trigger_blocked_target_unavailable": "该目标不可用",
"trigger_blocked_runtime_offline": "该目标的运行时已离线",
+ "trigger_blocked_agent_runtime_required": "该目标未绑定运行时——绑定后才能运行",
"trigger_blocked_generic": "该目标不会被触发",
"trigger_blocked_short_invocation_not_allowed": "找不到或无权限",
"trigger_blocked_short_target_unavailable": "不可用",
"trigger_blocked_short_runtime_offline": "运行时离线",
+ "trigger_blocked_short_agent_runtime_required": "需绑定运行时",
"trigger_blocked_short_generic": "不会触发",
"send_reply_failed": "发送回复失败",
"delete_failed": "删除评论失败",
@@ -573,7 +575,9 @@
"search_placeholder": "分配给...",
"members_group": "成员",
"agents_group": "智能体",
- "squads_group": "小队"
+ "squads_group": "小队",
+ "agent_runtime_required": "请先为该智能体绑定运行时,再分配工作",
+ "squad_runtime_required": "请先为该小队的负责人绑定运行时,再分配工作"
},
"start_date": {
"trigger_label": "开始日期",
diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.json
index abb940d37f..e2292e933a 100644
--- a/packages/views/locales/zh-Hans/runtimes.json
+++ b/packages/views/locales/zh-Hans/runtimes.json
@@ -135,15 +135,15 @@
"submitting": "删除中..."
},
"cascade": {
- "title_other": "归档 {{count}} 个智能体并删除该运行时?",
- "description": "删除「{{name}}」。下列智能体将被归档并从可用工作流中移除,其排队中或运行中的 task 会被取消,随后运行时本身会被删除。",
- "warning": "此操作具有破坏性。归档的智能体将从可用工作流中移除,其排队中或运行中的 task 会被取消。",
+ "title_other": "解绑 {{count}} 个智能体并删除该运行时?",
+ "description": "删除「{{name}}」。下列智能体会保留——其指令、聊天记录和任务历史都不会丢失——但它们将被解绑,在重新绑定运行时之前无法运行。其排队中或运行中的 task 会被取消,随后运行时本身会被删除。",
+ "warning": "排队中和运行中的 task 会被取消;在重新绑定运行时之前,这些智能体无法接受新任务。",
"notice_runtime_has_active_agents": "自打开此弹窗后,又有新的活动智能体加入。请确认新方案后继续。",
"notice_runtime_delete_plan_changed": "在弹窗打开期间,活动智能体集合发生了变化。请确认新方案后继续。",
- "checkbox_other": "我已了解:这 {{count}} 个智能体将被归档,其排队中或运行中的 task 会被取消。",
+ "checkbox_other": "我已了解:这 {{count}} 个智能体将被解绑,在重新绑定运行时之前无法运行,其排队中或运行中的 task 会被取消。",
"cancel": "取消",
- "confirm_other": "归档 {{count}} 个智能体并删除运行时",
- "submitting": "正在归档并删除...",
+ "confirm_other": "解绑 {{count}} 个智能体并删除运行时",
+ "submitting": "正在解绑并删除...",
"delete_failed_toast": "删除运行时失败",
"table": {
"header_agent": "智能体",
diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsx
index 4dfd9869af..457bc3b287 100644
--- a/packages/views/modals/quick-create-issue.tsx
+++ b/packages/views/modals/quick-create-issue.tsx
@@ -60,6 +60,7 @@ import { PillButton } from "../common/pill-button";
import { ProjectPicker } from "../projects/components/project-picker";
import { DueDatePicker, PriorityIcon, PriorityPicker } from "../issues/components";
import { canAssignAgent } from "../issues/components/pickers/assignee-picker";
+import { isAgentRuntimeBound } from "@multica/core/agents";
import {
PropertyPicker,
PickerItem,
@@ -142,7 +143,10 @@ export function AgentCreatePanel({
const visibleAgents = useMemo(
() =>
agents.filter(
- (a) => !a.archived_at && canAssignAgent(a, userId, memberRole),
+ (a) =>
+ !a.archived_at &&
+ isAgentRuntimeBound(a) &&
+ canAssignAgent(a, userId, memberRole),
),
[agents, userId, memberRole],
);
diff --git a/packages/views/runtimes/components/delete-runtime-dialog.test.tsx b/packages/views/runtimes/components/delete-runtime-dialog.test.tsx
index 5eb82abfe0..3d0ae97756 100644
--- a/packages/views/runtimes/components/delete-runtime-dialog.test.tsx
+++ b/packages/views/runtimes/components/delete-runtime-dialog.test.tsx
@@ -18,7 +18,7 @@ const TEST_RESOURCES = {
// mocked api throws. vi.hoisted is required because vi.mock is hoisted above
// imports — a top-level class declaration would not be visible to the mock
// factory at hoist time.
-const { ApiError, apiDeleteRuntime, apiArchiveAgentsAndDeleteRuntime } = vi.hoisted(() => {
+const { ApiError, apiDeleteRuntime, apiUnbindAgentsAndDeleteRuntime } = vi.hoisted(() => {
class ApiError extends Error {
status: number;
body: unknown;
@@ -31,15 +31,15 @@ const { ApiError, apiDeleteRuntime, apiArchiveAgentsAndDeleteRuntime } = vi.hois
return {
ApiError,
apiDeleteRuntime: vi.fn(),
- apiArchiveAgentsAndDeleteRuntime: vi.fn(),
+ apiUnbindAgentsAndDeleteRuntime: vi.fn(),
};
});
vi.mock("@multica/core/api", () => ({
api: {
deleteRuntime: (...args: unknown[]) => apiDeleteRuntime(...args),
- archiveAgentsAndDeleteRuntime: (...args: unknown[]) =>
- apiArchiveAgentsAndDeleteRuntime(...args),
+ unbindAgentsAndDeleteRuntime: (...args: unknown[]) =>
+ apiUnbindAgentsAndDeleteRuntime(...args),
listAgents: vi.fn(),
listMembers: vi.fn(),
},
@@ -55,11 +55,11 @@ vi.mock("@multica/core/runtimes/mutations", () => ({
mutate: vi.fn(),
mutateAsync: (...args: unknown[]) => apiDeleteRuntime(...args),
}),
- useArchiveAgentsAndDeleteRuntime: () => ({
+ useUnbindAgentsAndDeleteRuntime: () => ({
isPending: false,
mutate: vi.fn(),
mutateAsync: (vars: { runtimeId: string; expectedActiveAgentIds: string[] }) =>
- apiArchiveAgentsAndDeleteRuntime(vars.runtimeId, vars.expectedActiveAgentIds),
+ apiUnbindAgentsAndDeleteRuntime(vars.runtimeId, vars.expectedActiveAgentIds),
}),
}));
@@ -209,7 +209,7 @@ describe("DeleteRuntimeDialog", () => {
expect(screen.getByText("Delete runtime")).toBeInTheDocument();
// No checkbox, no agent table in light mode.
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
- expect(screen.queryByText(/Archive .* and delete this Runtime/)).not.toBeInTheDocument();
+ expect(screen.queryByText(/Unbind .* and delete this Runtime/)).not.toBeInTheDocument();
});
it("opens directly in cascade mode when local cache shows bound agents, with the destructive button gated by the checkbox", async () => {
@@ -221,11 +221,11 @@ describe("DeleteRuntimeDialog", () => {
});
expect(
- screen.getByText(/Archive 2 agents and delete this Runtime/),
+ screen.getByText(/Unbind 2 agents and delete this Runtime/),
).toBeInTheDocument();
// Destructive confirm starts disabled until the user ticks the checkbox.
const confirm = screen.getByRole("button", {
- name: /Archive 2 agents and delete runtime/,
+ name: /Unbind 2 agents and delete runtime/,
}) as HTMLButtonElement;
expect(confirm.disabled).toBe(true);
@@ -233,14 +233,14 @@ describe("DeleteRuntimeDialog", () => {
fireEvent.click(checkbox);
await waitFor(() => expect(confirm.disabled).toBe(false));
- apiArchiveAgentsAndDeleteRuntime.mockResolvedValueOnce({
+ apiUnbindAgentsAndDeleteRuntime.mockResolvedValueOnce({
status: "ok",
- agents_archived: 2,
+ agents_unbound: 2,
tasks_cancelled: 0,
});
fireEvent.click(confirm);
await waitFor(() =>
- expect(apiArchiveAgentsAndDeleteRuntime).toHaveBeenCalledWith("rt-1", [
+ expect(apiUnbindAgentsAndDeleteRuntime).toHaveBeenCalledWith("rt-1", [
"a-1",
"a-2",
]),
@@ -265,7 +265,7 @@ describe("DeleteRuntimeDialog", () => {
await waitFor(() =>
expect(
- screen.getByText(/Archive 1 agent and delete this Runtime/),
+ screen.getByText(/Unbind 1 agent and delete this Runtime/),
).toBeInTheDocument(),
);
expect(screen.getByText("FreshAgent")).toBeInTheDocument();
@@ -276,7 +276,7 @@ describe("DeleteRuntimeDialog", () => {
});
it("re-prompts when the cascade returns runtime_delete_plan_changed", async () => {
- apiArchiveAgentsAndDeleteRuntime.mockRejectedValueOnce(
+ apiUnbindAgentsAndDeleteRuntime.mockRejectedValueOnce(
new ApiError("plan changed", 409, {
code: "runtime_delete_plan_changed",
active_agents: [
@@ -298,13 +298,13 @@ describe("DeleteRuntimeDialog", () => {
fireEvent.click(screen.getByRole("checkbox"));
fireEvent.click(
screen.getByRole("button", {
- name: /Archive 2 agents and delete runtime/,
+ name: /Unbind 2 agents and delete runtime/,
}),
);
await waitFor(() =>
expect(
- screen.getByText(/Archive 3 agents and delete this Runtime/),
+ screen.getByText(/Unbind 3 agents and delete this Runtime/),
).toBeInTheDocument(),
);
// The new third agent shows in the plan.
@@ -367,7 +367,7 @@ describe("DeleteRuntimeDialog", () => {
screen.getByText(/registered from a custom runtime profile/i),
).toBeInTheDocument();
expect(
- screen.getByText(/Archive 1 agent and delete this Runtime/),
+ screen.getByText(/Unbind 1 agent and delete this Runtime/),
).toBeInTheDocument();
});
@@ -383,7 +383,7 @@ describe("DeleteRuntimeDialog", () => {
screen.getByText(/managed by a running local daemon/i),
).toBeInTheDocument();
expect(
- screen.getByText(/Archive 1 agent and delete this Runtime/),
+ screen.getByText(/Unbind 1 agent and delete this Runtime/),
).toBeInTheDocument();
});
diff --git a/packages/views/runtimes/components/delete-runtime-dialog.tsx b/packages/views/runtimes/components/delete-runtime-dialog.tsx
index 8f6acc3fbf..fa8a321c31 100644
--- a/packages/views/runtimes/components/delete-runtime-dialog.tsx
+++ b/packages/views/runtimes/components/delete-runtime-dialog.tsx
@@ -9,7 +9,7 @@ import type { Agent, AgentRuntime, MemberWithUser } from "@multica/core/types";
import { runtimeDisplayLabel } from "@multica/core/runtimes";
import {
useDeleteRuntime,
- useArchiveAgentsAndDeleteRuntime,
+ useUnbindAgentsAndDeleteRuntime,
} from "@multica/core/runtimes/mutations";
import {
agentListOptions,
@@ -35,7 +35,12 @@ import { isSelfHealingRuntime } from "../utils";
// deletion across the list-page kebab and the detail-page Diagnostics
// card. It runs in two modes that share the same shell — light when no
// agents are bound (matches the legacy "are you sure" prompt) and
-// cascade when active agents would be archived as part of the delete.
+// cascade when active agents would be unbound as part of the delete.
+//
+// "Unbound" is the load-bearing word (MUL-5559): the agents are kept, with
+// their instructions, chats and task history, and only lose their runtime —
+// they cannot run until bound to another one. The dialog used to say those
+// agents would be "archived" while the server hard-deleted them.
//
// Mode is decided dynamically:
// 1. Initial: peek at the cached agent list and pick light vs cascade
@@ -115,7 +120,7 @@ export function DeleteRuntimeDialog({
}, [open, cachedActiveAgents]);
const lightMutation = useDeleteRuntime(wsId);
- const cascadeMutation = useArchiveAgentsAndDeleteRuntime(wsId);
+ const cascadeMutation = useUnbindAgentsAndDeleteRuntime(wsId);
const handleConfirm = async () => {
setSubmitting(true);
diff --git a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
index e65bc34424..88ca3d29b3 100644
--- a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
+++ b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
@@ -28,7 +28,7 @@ vi.mock("@multica/core/api", () => ({
api: {
updateRuntime: (...args: unknown[]) => mockUpdateRuntime(...args),
deleteRuntime: vi.fn(),
- archiveAgentsAndDeleteRuntime: vi.fn(),
+ unbindAgentsAndDeleteRuntime: vi.fn(),
deleteRuntimeProfile: (...args: unknown[]) =>
mockDeleteRuntimeProfile(...args),
},
@@ -111,7 +111,7 @@ vi.mock("@multica/core/runtimes/mutations", () => ({
isPending: false,
}),
useDeleteRuntime: () => ({ mutate: vi.fn(), isPending: false, mutateAsync: vi.fn() }),
- useArchiveAgentsAndDeleteRuntime: () => ({
+ useUnbindAgentsAndDeleteRuntime: () => ({
mutate: vi.fn(),
isPending: false,
mutateAsync: vi.fn(),
diff --git a/packages/views/runtimes/components/runtime-row-menu.test.tsx b/packages/views/runtimes/components/runtime-row-menu.test.tsx
index 0ad252ba2b..22450380ce 100644
--- a/packages/views/runtimes/components/runtime-row-menu.test.tsx
+++ b/packages/views/runtimes/components/runtime-row-menu.test.tsx
@@ -29,7 +29,7 @@ vi.mock("@tanstack/react-query", async () => {
vi.mock("@multica/core/runtimes/mutations", () => ({
useDeleteRuntime: () => ({ mutate: vi.fn(), isPending: false, mutateAsync: vi.fn() }),
- useArchiveAgentsAndDeleteRuntime: () => ({
+ useUnbindAgentsAndDeleteRuntime: () => ({
mutate: vi.fn(),
isPending: false,
mutateAsync: vi.fn(),
@@ -72,7 +72,7 @@ vi.mock("@multica/core/auth", () => ({
vi.mock("@multica/core/api", () => ({
api: {
deleteRuntime: vi.fn(),
- archiveAgentsAndDeleteRuntime: vi.fn(),
+ unbindAgentsAndDeleteRuntime: vi.fn(),
},
ApiError: class ApiError extends Error {},
}));
diff --git a/server/cmd/multica/cmd_runtime.go b/server/cmd/multica/cmd_runtime.go
index 5bc0f127c9..10c5b39429 100644
--- a/server/cmd/multica/cmd_runtime.go
+++ b/server/cmd/multica/cmd_runtime.go
@@ -62,7 +62,8 @@ var runtimeDeleteCmd = &cobra.Command{
Short: "Delete a runtime from the workspace",
Long: "Delete a runtime registration from the workspace.\n\n" +
"By default this refuses when active agents are still bound to the runtime. " +
- "Pass --cascade to archive those agents, cancel their queued/running tasks, and delete the runtime.",
+ "Pass --cascade to unbind those agents, cancel their queued/running tasks, and delete the runtime. " +
+ "Unbound agents keep their configuration, chats and task history; bind them to another runtime to run them again.",
Args: exactArgs(1),
RunE: runRuntimeDelete,
}
@@ -95,7 +96,7 @@ func init() {
runtimeRenameCmd.Flags().String("output", "table", "Output format: table or json")
// runtime delete
- runtimeDeleteCmd.Flags().Bool("cascade", false, "Archive active agents bound to the runtime, cancel their tasks, then delete the runtime")
+ runtimeDeleteCmd.Flags().Bool("cascade", false, "Unbind active agents from the runtime, cancel their tasks, then delete the runtime")
runtimeDeleteCmd.Flags().String("output", "table", "Output format: table or json")
}
@@ -237,7 +238,7 @@ func runRuntimeDelete(cmd *cobra.Command, args []string) error {
cascade, _ := cmd.Flags().GetBool("cascade")
if !cascade {
return fmt.Errorf(
- "delete runtime: runtime has active agents bound to it (%s); archive or reassign them first, or rerun with --cascade to archive them and delete the runtime",
+ "delete runtime: runtime has active agents bound to it (%s); rebind them to another runtime first, or rerun with --cascade to unbind them and delete the runtime (the agents and their history are kept)",
strings.Join(conflict.AgentDisplays(), ", "),
)
}
@@ -246,7 +247,7 @@ func runRuntimeDelete(cmd *cobra.Command, args []string) error {
"expected_active_agent_ids": conflict.AgentIDs(),
}
var result map[string]any
- if err := client.PostJSON(ctx, "/api/runtimes/"+runtimeID+"/archive-agents-and-delete", body, &result); err != nil {
+ if err := client.PostJSON(ctx, "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete", body, &result); err != nil {
return fmt.Errorf("cascade delete runtime: %w", err)
}
result["id"] = runtimeID
@@ -404,8 +405,18 @@ func printRuntimeDeleteResult(cmd *cobra.Command, result map[string]any) error {
return cli.PrintJSON(os.Stdout, result)
}
+ if agentsUnbound, ok := result["agents_unbound"]; ok {
+ fmt.Fprintf(os.Stderr, "Runtime %s deleted; unbound %v agent(s)", strVal(result, "id"), agentsUnbound)
+ if paused, ok := result["autopilots_paused"]; ok {
+ fmt.Fprintf(os.Stderr, " and paused %v autopilot(s)", paused)
+ }
+ fmt.Fprintln(os.Stderr, ".")
+ return nil
+ }
+ // Compatibility fallback for an older server that only returns the
+ // pre-MUL-5559 mirror.
if agentsArchived, ok := result["agents_archived"]; ok {
- fmt.Fprintf(os.Stderr, "Runtime %s deleted; archived %v agent(s).\n", strVal(result, "id"), agentsArchived)
+ fmt.Fprintf(os.Stderr, "Runtime %s deleted; processed %v agent(s).\n", strVal(result, "id"), agentsArchived)
return nil
}
fmt.Fprintf(os.Stderr, "Runtime %s deleted.\n", strVal(result, "id"))
diff --git a/server/cmd/multica/cmd_runtime_test.go b/server/cmd/multica/cmd_runtime_test.go
index 0849e7dfa5..eab0182afc 100644
--- a/server/cmd/multica/cmd_runtime_test.go
+++ b/server/cmd/multica/cmd_runtime_test.go
@@ -134,7 +134,7 @@ func TestRunRuntimeDeleteCascadeConfirmsActiveAgentSnapshot(t *testing.T) {
{"id": "agent-2", "name": "Claude"},
},
})
- case r.Method == http.MethodPost && r.URL.Path == "/api/runtimes/rt-1/archive-agents-and-delete":
+ case r.Method == http.MethodPost && r.URL.Path == "/api/runtimes/rt-1/unbind-agents-and-delete":
cascadeCount++
var body struct {
ExpectedActiveAgentIDs []string `json:"expected_active_agent_ids"`
@@ -145,7 +145,7 @@ func TestRunRuntimeDeleteCascadeConfirmsActiveAgentSnapshot(t *testing.T) {
gotExpectedIDs = body.ExpectedActiveAgentIDs
_ = json.NewEncoder(w).Encode(map[string]any{
"status": "ok",
- "agents_archived": 2,
+ "agents_unbound": 2,
"tasks_cancelled": 1,
})
default:
@@ -175,7 +175,7 @@ func TestRunRuntimeDeleteCascadeConfirmsActiveAgentSnapshot(t *testing.T) {
if err := json.Unmarshal([]byte(out), &got); err != nil {
t.Fatalf("decode stdout JSON %q: %v", out, err)
}
- if got["id"] != "rt-1" || got["deleted"] != true || got["agents_archived"] != float64(2) {
+ if got["id"] != "rt-1" || got["deleted"] != true || got["agents_unbound"] != float64(2) {
t.Fatalf("stdout = %#v, want cascade result", got)
}
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 89604b43ea..82e2f328d4 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1392,13 +1392,18 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/local-skills/import", h.InitiateImportLocalSkill)
r.Get("/local-skills/import/{requestId}", h.GetLocalSkillImportRequest)
r.Delete("/", h.DeleteAgentRuntime)
- // Cascade variant of DELETE: archive every active agent
- // bound to this runtime, cancel their tasks, then delete
- // the runtime — all in one transaction. Used by the
- // DeleteRuntimeDialog when the strict DELETE refused with
- // `runtime_has_active_agents` and the user confirmed the
- // cascade plan.
- r.Post("/archive-agents-and-delete", h.ArchiveAgentsAndDeleteRuntime)
+ // Confirmed variant of DELETE: unbind every agent bound to
+ // this runtime (they keep their configuration and chats and
+ // need a new runtime to run again), cancel their tasks,
+ // detach their task history, then delete the runtime — all
+ // in one transaction. Used by the DeleteRuntimeDialog when
+ // the strict DELETE refused with
+ // `runtime_has_active_agents` and the user confirmed.
+ r.Post("/unbind-agents-and-delete", h.UnbindAgentsAndDeleteRuntime)
+ // Legacy path for installed clients built against the
+ // archive-and-delete contract (MUL-5559 renamed the
+ // behaviour, not just the route). Same handler.
+ r.Post("/archive-agents-and-delete", h.UnbindAgentsAndDeleteRuntime)
})
})
diff --git a/server/internal/daemon/workdir_race_test.go b/server/internal/daemon/workdir_race_test.go
index def8fa3fd0..f4061a1091 100644
--- a/server/internal/daemon/workdir_race_test.go
+++ b/server/internal/daemon/workdir_race_test.go
@@ -347,6 +347,18 @@ func TestRunTask_ExtendsPrepareLeaseDuringStartTask(t *testing.T) {
}
}
+type prepareLeaseCountingTransport struct {
+ base http.RoundTripper
+ calls *atomic.Int64
+}
+
+func (t *prepareLeaseCountingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ if strings.HasSuffix(req.URL.Path, "/prepare-lease") {
+ t.calls.Add(1)
+ }
+ return t.base.RoundTrip(req)
+}
+
func TestRunTask_PrepareTimeoutStopsLeaseDuringBlockedStartTask(t *testing.T) {
oldRefresh := taskPrepareLeaseRefresh
oldTimeout := taskPrepareLeaseTimeout
@@ -366,7 +378,6 @@ func TestRunTask_PrepareTimeoutStopsLeaseDuringBlockedStartTask(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/prepare-lease"):
- leaseCalls.Add(1)
w.WriteHeader(http.StatusOK)
case strings.HasSuffix(r.URL.Path, "/start"):
closeStartOnce.Do(func() { close(startEntered) })
@@ -378,13 +389,22 @@ func TestRunTask_PrepareTimeoutStopsLeaseDuringBlockedStartTask(t *testing.T) {
}))
t.Cleanup(srv.Close)
+ // Count requests where the extender starts them. A cancelled RoundTrip can
+ // return before httptest schedules its handler, so counting in the handler
+ // can make an already-in-flight request look like post-timeout activity.
+ client := NewClient(srv.URL)
+ client.client.Transport = &prepareLeaseCountingTransport{
+ base: client.client.Transport,
+ calls: &leaseCalls,
+ }
+
workspacesRoot := t.TempDir()
fakeBin := filepath.Join(t.TempDir(), "claude")
if err := os.WriteFile(fakeBin, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
t.Fatalf("write fake agent: %v", err)
}
d := &Daemon{
- client: NewClient(srv.URL),
+ client: client,
logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
workspaces: make(map[string]*workspaceState),
runtimeIndex: map[string]Runtime{"rt-1": {ID: "rt-1", Provider: "claude"}},
@@ -421,12 +441,12 @@ func TestRunTask_PrepareTimeoutStopsLeaseDuringBlockedStartTask(t *testing.T) {
}
releaseStartOnce.Do(func() { close(releaseStart) })
if got := leaseCalls.Load(); got == 0 {
- t.Fatal("prepare lease was never extended while /start was blocked")
+ t.Fatal("prepare lease request was never started while /start was blocked")
}
leaseCallsAtReturn := leaseCalls.Load()
time.Sleep(4 * taskPrepareLeaseRefresh)
if got := leaseCalls.Load(); got != leaseCallsAtReturn {
- t.Fatalf("prepare lease kept extending after timeout: calls %d -> %d", leaseCallsAtReturn, got)
+ t.Fatalf("prepare lease requests kept starting after timeout: calls %d -> %d", leaseCallsAtReturn, got)
}
if got := taskRunFailureReason(err); got != "timeout" {
t.Fatalf("taskRunFailureReason = %q, want retryable platform timeout", got)
diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.go
index ea953ac32d..d08a5c7646 100644
--- a/server/internal/dispatch/reason.go
+++ b/server/internal/dispatch/reason.go
@@ -27,9 +27,18 @@ const (
// ReasonTargetUnavailable: the target cannot run (archived agent, deleted /
// archived squad, unresolvable leader, or no assignee).
ReasonTargetUnavailable ReasonCode = "target_unavailable"
- // ReasonRuntimeOffline: the target is permitted but its runtime is not bound
- // / not online at dispatch time.
+ // ReasonRuntimeOffline: the target is permitted and bound to a runtime, but
+ // that runtime is not online at dispatch time. The task is not lost — the
+ // user's fix is to bring the machine back, and queued work waits for it.
ReasonRuntimeOffline ReasonCode = "runtime_offline"
+ // ReasonAgentRuntimeRequired: the target is permitted but bound to no
+ // runtime at all (agent.runtime_id IS NULL), which is where an agent lands
+ // when its runtime is deleted (MUL-5559). Distinct from runtime_offline on
+ // purpose: there is no machine to bring back, nothing will ever claim work
+ // for this agent, and the only fix is binding it to a runtime. Clients that
+ // collapse the two send the user looking for an offline computer that does
+ // not exist.
+ ReasonAgentRuntimeRequired ReasonCode = "agent_runtime_required"
// ReasonAttributionBlocked: a fail-closed workspace could not resolve a
// responsible human for the run, so it was refused.
ReasonAttributionBlocked ReasonCode = "attribution_blocked"
diff --git a/server/internal/handler/admission.go b/server/internal/handler/admission.go
index 1b57b8c0d6..7e864d4804 100644
--- a/server/internal/handler/admission.go
+++ b/server/internal/handler/admission.go
@@ -56,6 +56,7 @@ const (
ReasonInvocationNotAllowed = dispatch.ReasonInvocationNotAllowed
ReasonTargetUnavailable = dispatch.ReasonTargetUnavailable
ReasonRuntimeOffline = dispatch.ReasonRuntimeOffline
+ ReasonAgentRuntimeRequired = dispatch.ReasonAgentRuntimeRequired
ReasonAttributionBlocked = dispatch.ReasonAttributionBlocked
ReasonAlreadyActive = dispatch.ReasonAlreadyActive
ReasonSelfTriggerSuppressed = dispatch.ReasonSelfTriggerSuppressed
@@ -115,6 +116,8 @@ func dispatchBlockedFallbackMessage(code DispatchReasonCode) string {
return "the target is unavailable"
case ReasonRuntimeOffline:
return "the target's runtime is offline"
+ case ReasonAgentRuntimeRequired:
+ return "the target needs a runtime"
case ReasonAttributionBlocked:
return "the run couldn't be attributed to a responsible member"
case ReasonAlreadyActive:
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 800a9e5d71..c191c27af1 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -35,9 +35,18 @@ import (
const maxAgentDescriptionLength = 255
type AgentResponse struct {
- ID string `json:"id"`
- WorkspaceID string `json:"workspace_id"`
- RuntimeID string `json:"runtime_id"`
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ // RuntimeID is the empty string when the agent is unbound — it kept its
+ // configuration and history when its runtime was deleted, and needs a new
+ // runtime before it can run again (MUL-5559). The wire type stays a string
+ // so installed clients keep parsing; RuntimeBound is the explicit signal.
+ RuntimeID string `json:"runtime_id"`
+ // RuntimeBound is false exactly when the agent has no runtime. UI should
+ // branch on this rather than on RuntimeID being falsy, and must not confuse
+ // it with a bound-but-offline runtime (a different user story: reconnect the
+ // machine vs. pick a new one).
+ RuntimeBound bool `json:"runtime_bound"`
Name string `json:"name"`
Description string `json:"description"`
Instructions string `json:"instructions"`
@@ -159,6 +168,7 @@ func (h *Handler) agentToResponse(a db.Agent) AgentResponse {
ID: uuidToString(a.ID),
WorkspaceID: uuidToString(a.WorkspaceID),
RuntimeID: uuidToString(a.RuntimeID),
+ RuntimeBound: a.RuntimeID.Valid,
Name: a.Name,
Description: a.Description,
Instructions: a.Instructions,
diff --git a/server/internal/handler/agent_runtime_required_test.go b/server/internal/handler/agent_runtime_required_test.go
new file mode 100644
index 0000000000..96e41ac23a
--- /dev/null
+++ b/server/internal/handler/agent_runtime_required_test.go
@@ -0,0 +1,232 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+// An unbound agent is refused by every execution entry point — that part already
+// worked, because service.AgentReadiness and these gates all check
+// RuntimeID.Valid. What did not work is what the user is told: the refusal reused
+// runtime_offline, whose copy asks them to bring a machine back online. An
+// unbound agent has no machine to bring back; the fix is to bind one. These tests
+// pin the distinct reason code (MUL-5559).
+
+// TestCommentMention_UnboundAgentReportsRuntimeRequired: @mentioning an unbound
+// agent posts the comment, enqueues nothing, and reports agent_runtime_required
+// rather than runtime_offline.
+func TestCommentMention_UnboundAgentReportsRuntimeRequired(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Mention Unbound Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Mention Unbound Agent")
+ // Public so the invocation gate (which runs first, and is enumeration-safe)
+ // cannot be the reason we see a block.
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent SET visibility = 'workspace', permission_mode = 'public_to' WHERE id = $1`,
+ agentID); err != nil {
+ t.Fatalf("make agent invocable: %v", err)
+ }
+ if _, err := testPool.Exec(ctx,
+ `INSERT INTO agent_invocation_target (agent_id, target_type, target_id, created_by)
+ VALUES ($1, 'workspace', $2, $3)`,
+ agentID, testWorkspaceID, testUserID); err != nil {
+ t.Fatalf("allow-list agent: %v", err)
+ }
+
+ issueID := createMentionFixtureIssue(t, ctx, "Mention unbound agent")
+
+ // Bound but never mentioned yet: the same agent must be triggerable before we
+ // unbind it, otherwise this test could pass for the wrong reason.
+ if code := mentionAgentReasonCode(t, issueID, agentID); code != "" {
+ t.Fatalf("bound agent: expected a successful trigger, got blocked with %q", code)
+ }
+
+ unbindRuntime(t, ctx, runtimeID, agentID)
+
+ if code := mentionAgentReasonCode(t, issueID, agentID); code != string(ReasonAgentRuntimeRequired) {
+ t.Fatalf("unbound agent: reason_code = %q, want agent_runtime_required", code)
+ }
+}
+
+// TestChatSend_UnboundAgentReturnsStructuredConflict: the chat gate already
+// refused, but with a bare error string. The composer needs a code to offer
+// "bind a runtime" instead of a generic failure.
+func TestChatSend_UnboundAgentReturnsStructuredConflict(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Chat Unbound Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Chat Unbound Agent")
+ sessionID := createHandlerTestChatSession(t, agentID)
+
+ unbindRuntime(t, ctx, runtimeID, agentID)
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/chat/sessions/"+sessionID+"/messages",
+ map[string]any{"content": "are you still there?"})
+ req = withURLParam(req, "sessionId", sessionID)
+ req = withChatTestWorkspaceCtx(t, req)
+ testHandler.SendChatMessage(w, req)
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var body struct {
+ Error string `json:"error"`
+ ReasonCode string `json:"reason_code"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body.ReasonCode != string(ReasonAgentRuntimeRequired) {
+ t.Fatalf("reason_code = %q, want agent_runtime_required", body.ReasonCode)
+ }
+ if body.Error == "" {
+ t.Fatalf("expected a human-readable error alongside the code")
+ }
+}
+
+func TestCreateAutopilot_UnboundAgentRejected(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Autopilot Create Unbound Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Autopilot Create Unbound Agent")
+ unbindRuntime(t, ctx, runtimeID, agentID)
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "must not start unbound",
+ "assignee_id": agentID,
+ "execution_mode": "run_only",
+ })
+ testHandler.CreateAutopilot(w, req)
+ if w.Code != http.StatusUnprocessableEntity {
+ t.Fatalf("expected 422, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var rows int
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM autopilot WHERE title = 'must not start unbound' AND assignee_id = $1`,
+ agentID,
+ ).Scan(&rows); err != nil {
+ t.Fatalf("count autopilots: %v", err)
+ }
+ if rows != 0 {
+ t.Fatalf("unbound Agent received %d active Autopilots, want 0", rows)
+ }
+}
+
+func TestUpdateAutopilot_UnboundAgentCannotResume(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Autopilot Resume Unbound Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Autopilot Resume Unbound Agent")
+
+ var autopilotID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO autopilot (
+ workspace_id, title, assignee_type, assignee_id, status,
+ execution_mode, created_by_type, created_by_id
+ )
+ VALUES ($1, 'cannot resume unbound', 'agent', $2, 'active',
+ 'run_only', 'member', $3)
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID).Scan(&autopilotID); err != nil {
+ t.Fatalf("insert paused autopilot: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID)
+ })
+
+ unbindRuntime(t, ctx, runtimeID, agentID)
+
+ w := httptest.NewRecorder()
+ req := newRequest("PATCH", "/api/autopilots/"+autopilotID+"?workspace_id="+testWorkspaceID,
+ map[string]any{"status": "active"})
+ req = withURLParam(req, "id", autopilotID)
+ testHandler.UpdateAutopilot(w, req)
+ if w.Code != http.StatusUnprocessableEntity {
+ t.Fatalf("expected 422, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var status, pauseReason string
+ if err := testPool.QueryRow(ctx,
+ `SELECT status, pause_reason FROM autopilot WHERE id = $1`,
+ autopilotID,
+ ).Scan(&status, &pauseReason); err != nil {
+ t.Fatalf("read autopilot: %v", err)
+ }
+ if status != "paused" || pauseReason != string(ReasonAgentRuntimeRequired) {
+ t.Fatalf("autopilot = (%q, %q), want (paused, agent_runtime_required)", status, pauseReason)
+ }
+}
+
+// mentionAgentReasonCode posts a comment mentioning the agent and returns the
+// reason_code of its trigger outcome, or "" when the mention was admitted.
+func mentionAgentReasonCode(t *testing.T, issueID, agentID string) string {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{
+ "content": "[@Agent](mention://agent/" + agentID + ") please take a look",
+ })
+ req = withURLParam(req, "id", issueID)
+ testHandler.CreateComment(w, req)
+ if w.Code != http.StatusCreated && w.Code != http.StatusOK {
+ t.Fatalf("CreateComment: expected 200/201, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var body struct {
+ TriggerOutcomes []struct {
+ TargetType string `json:"target_type"`
+ TargetID string `json:"target_id"`
+ Status string `json:"status"`
+ ReasonCode string `json:"reason_code"`
+ } `json:"trigger_outcomes"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
+ t.Fatalf("decode comment response: %v", err)
+ }
+ for _, o := range body.TriggerOutcomes {
+ if o.TargetID != agentID {
+ continue
+ }
+ if o.Status == "blocked" {
+ return o.ReasonCode
+ }
+ return ""
+ }
+ t.Fatalf("no trigger outcome for agent %s in %s", agentID, w.Body.String())
+ return ""
+}
+
+func createMentionFixtureIssue(t *testing.T, ctx context.Context, title string) string {
+ t.Helper()
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, number, title, description, status, creator_type, creator_id)
+ VALUES ($1, (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1),
+ $2, '', 'todo', 'member', $3)
+ RETURNING id
+ `, testWorkspaceID, title, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("insert fixture issue: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+ return issueID
+}
diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.go
index a157bcfa04..746d34595d 100644
--- a/server/internal/handler/autopilot.go
+++ b/server/internal/handler/autopilot.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"net/http"
@@ -12,6 +13,7 @@ import (
"time"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
@@ -40,6 +42,7 @@ type AutopilotResponse struct {
AssigneeType string `json:"assignee_type"`
AssigneeID string `json:"assignee_id"`
Status string `json:"status"`
+ PauseReason *string `json:"pause_reason"`
ExecutionMode string `json:"execution_mode"`
IssueTitleTemplate *string `json:"issue_title_template"`
CreatedByType string `json:"created_by_type"`
@@ -190,6 +193,7 @@ func autopilotToResponse(a db.Autopilot, subscribers []db.AutopilotSubscriber) A
AssigneeType: assigneeType,
AssigneeID: uuidToString(a.AssigneeID),
Status: a.Status,
+ PauseReason: textToPtr(a.PauseReason),
ExecutionMode: a.ExecutionMode,
IssueTitleTemplate: textToPtr(a.IssueTitleTemplate),
CreatedByType: a.CreatedByType,
@@ -647,9 +651,6 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "assignee_type must be agent or squad")
return
}
- if !h.validateAutopilotAssignee(w, r, assigneeType, assigneeUUID, wsUUID) {
- return
- }
projectID, ok := h.parseAutopilotProjectID(w, r, req.ProjectID, wsUUID)
if !ok {
return
@@ -669,6 +670,13 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
+ // Keep save-time readiness validation in the same transaction as the
+ // insert. The assignment lock serializes this path with Runtime teardown,
+ // so an active Autopilot cannot slip in after teardown's pause sweep.
+ if !h.validateAutopilotAssigneeForSave(w, r, qtx, assigneeType, assigneeUUID, wsUUID, true) {
+ return
+ }
+
autopilot, err := qtx.CreateAutopilot(r.Context(), db.CreateAutopilotParams{
WorkspaceID: wsUUID,
Title: req.Title,
@@ -838,8 +846,9 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {
// rejected.
_, typeSent := rawFields["assignee_type"]
_, idSent := rawFields["assignee_id"]
+ nextType := prev.AssigneeType
+ nextID := prev.AssigneeID
if typeSent || idSent {
- nextType := prev.AssigneeType
if typeSent && req.AssigneeType != nil && *req.AssigneeType != "" {
nextType = *req.AssigneeType
}
@@ -847,7 +856,6 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "assignee_type must be agent or squad")
return
}
- nextID := prev.AssigneeID
if idSent {
if req.AssigneeID == nil {
writeError(w, http.StatusBadRequest, "assignee_id cannot be null")
@@ -866,9 +874,6 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "assignee_id is required when changing assignee_type")
return
}
- if !h.validateAutopilotAssignee(w, r, nextType, nextID, prev.WorkspaceID) {
- return
- }
if typeSent {
params.AssigneeType = pgtype.Text{String: nextType, Valid: true}
}
@@ -900,6 +905,45 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
+ // Retargeting must validate the polymorphic reference; resuming must also
+ // validate Runtime readiness. Keep both in this transaction so Runtime
+ // teardown either pauses an active row after it commits or wins first and
+ // makes activation fail with a useful recovery message.
+ nextStatus := prev.Status
+ if req.Status != nil {
+ nextStatus = *req.Status
+ }
+ validateAssignee := typeSent || idSent || (req.Status != nil && *req.Status == "active")
+ if validateAssignee && !h.validateAutopilotAssigneeForSave(
+ w, r, qtx, nextType, nextID, prev.WorkspaceID, nextStatus == "active",
+ ) {
+ return
+ }
+
+ // Assignment locks come first. Runtime teardown and squad leader changes
+ // also lock Agent/Squad before they update matching Autopilot rows; keeping
+ // that global order prevents an Agent↔Autopilot deadlock.
+ lockedPrev, err := qtx.LockAutopilotForUpdate(r.Context(), db.LockAutopilotForUpdateParams{
+ ID: prev.ID,
+ WorkspaceID: prev.WorkspaceID,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "autopilot not found")
+ return
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update autopilot")
+ return
+ }
+ if lockedPrev.UpdatedAt.Valid != prev.UpdatedAt.Valid ||
+ (lockedPrev.UpdatedAt.Valid && !lockedPrev.UpdatedAt.Time.Equal(prev.UpdatedAt.Time)) {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "the autopilot changed while it was being edited; reload and try again.",
+ "code": "autopilot_update_conflict",
+ })
+ return
+ }
+
autopilot, err := qtx.UpdateAutopilot(r.Context(), params)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to update autopilot")
@@ -1463,29 +1507,45 @@ func isValidAutopilotAssigneeType(t string) bool {
}
}
-// validateAutopilotAssignee checks that the assignee (agent or squad) exists
-// in the given workspace, and for squad assignees that the squad's leader
-// agent is in a workable state at create / update time. Writes an HTTP error
-// and returns false on any failure.
+// validateAutopilotAssigneeForSave checks that the assignee (agent or squad)
+// exists in the given workspace and, when requireRuntime is true, that its
+// effective Agent has a Runtime. It takes assignment locks through q so active
+// saves and the caller's Autopilot write are serialized with Runtime teardown.
//
// At dispatch time the same checks (resolveAutopilotLeader + AgentReadiness)
// run again — they live there to handle "leader was online at save time but
// went offline by trigger time". Save-time validation exists so the user gets
-// immediate feedback ("can't pick this squad because its leader is archived")
-// instead of discovering the autopilot is dead at the next schedule tick.
-func (h *Handler) validateAutopilotAssignee(w http.ResponseWriter, r *http.Request, assigneeType string, assigneeID, workspaceID pgtype.UUID) bool {
+// immediate feedback ("bind a runtime first") instead of discovering the
+// Autopilot is inert at the next schedule tick.
+func (h *Handler) validateAutopilotAssigneeForSave(
+ w http.ResponseWriter,
+ r *http.Request,
+ q *db.Queries,
+ assigneeType string,
+ assigneeID, workspaceID pgtype.UUID,
+ requireRuntime bool,
+) bool {
switch assigneeType {
case "agent":
- if _, err := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{
+ agent, err := q.LockAgentForAutopilotAssignment(r.Context(), db.LockAgentForAutopilotAssignmentParams{
ID: assigneeID,
WorkspaceID: workspaceID,
- }); err != nil {
+ })
+ if err != nil {
writeError(w, http.StatusBadRequest, "assignee must be a valid agent in this workspace")
return false
}
+ if agent.ArchivedAt.Valid {
+ writeError(w, http.StatusUnprocessableEntity, "assignee agent is archived; pick a different agent")
+ return false
+ }
+ if requireRuntime && !agent.RuntimeID.Valid {
+ writeError(w, http.StatusUnprocessableEntity, "assignee agent needs a runtime before this autopilot can be active")
+ return false
+ }
return true
case "squad":
- squad, err := h.Queries.GetSquadInWorkspace(r.Context(), db.GetSquadInWorkspaceParams{
+ squad, err := q.LockSquadForAutopilotAssignment(r.Context(), db.LockSquadForAutopilotAssignmentParams{
ID: assigneeID,
WorkspaceID: workspaceID,
})
@@ -1503,7 +1563,10 @@ func (h *Handler) validateAutopilotAssignee(w http.ResponseWriter, r *http.Reque
writeError(w, http.StatusUnprocessableEntity, "squad is archived; pick a different squad")
return false
}
- leader, err := h.Queries.GetAgent(r.Context(), squad.LeaderID)
+ leader, err := q.LockAgentForAutopilotAssignment(r.Context(), db.LockAgentForAutopilotAssignmentParams{
+ ID: squad.LeaderID,
+ WorkspaceID: workspaceID,
+ })
if err != nil {
writeError(w, http.StatusBadRequest, "squad leader agent not found")
return false
@@ -1512,6 +1575,10 @@ func (h *Handler) validateAutopilotAssignee(w http.ResponseWriter, r *http.Reque
writeError(w, http.StatusUnprocessableEntity, "squad leader is archived; pick a different squad or rotate the leader before assigning autopilot")
return false
}
+ if requireRuntime && !leader.RuntimeID.Valid {
+ writeError(w, http.StatusUnprocessableEntity, "squad leader needs a runtime before this autopilot can be active")
+ return false
+ }
// Private-leader gate: the member configuring the autopilot must have
// access to the private leader, same as validateAssigneePair.
actorType, actorID := h.resolveActor(r, requestUserID(r), util.UUIDToString(workspaceID))
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index 2357b977b3..f97504c7c4 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -750,7 +750,7 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
return
}
if !agent.RuntimeID.Valid {
- writeError(w, http.StatusConflict, "chat agent has no runtime")
+ h.writeDispatchBlocked(w, http.StatusConflict, ReasonAgentRuntimeRequired)
return
}
@@ -1241,17 +1241,16 @@ func (h *Handler) ConsumeChatDraftRestore(w http.ResponseWriter, r *http.Request
w.WriteHeader(http.StatusNoContent)
}
-// pruneRuntimeAgentChatDraftRestores drops the pending draft restores of every
-// chat_session a runtime teardown is about to remove through the agent cascade
-// (chat_session.agent_id is ON DELETE CASCADE, migration 033). chat_draft_restore
-// has no FK (MUL-3515) and no reaper, so a restore left behind keeps the user's
-// prompt text forever, unreachable and undeletable.
+// pruneRuntimeSystemAgentChatDraftRestores drops the pending draft restores of
+// every chat_session a runtime teardown is about to remove through the agent
+// cascade (chat_session.agent_id is ON DELETE CASCADE, migration 033).
+// chat_draft_restore has no FK (MUL-3515) and no reaper, so a restore left
+// behind keeps the user's prompt text forever, unreachable and undeletable.
//
// Every runtime/agent teardown path must call this in its own transaction and
-// BEFORE deleting the agent rows — the queries join through them. includeSystemAgents
-// mirrors whether the caller also runs DeleteSystemAgentsByRuntime: the
-// runtime-profile teardown deletes only archived agents, and pruning system-agent
-// sessions there would destroy restores whose session survives.
+// BEFORE deleting the agent rows — the queries join through them. Only system
+// agents are in scope: since MUL-5559 a runtime delete unbinds its user agents
+// instead of deleting them, so their sessions and restores must survive.
//
// The sessions are locked before the sweep: that is the deleter half of the
// mutual-exclusion protocol with FinalizeDeferredCancelledChat, which would
@@ -1261,16 +1260,7 @@ func (h *Handler) ConsumeChatDraftRestore(w http.ResponseWriter, r *http.Request
// The workspace teardown has its own copy of this shape (locks, then sweeps
// inside the DeleteWorkspace CTE) because that statement's prune must stay in
// the same statement as the workspace row it commits with.
-func pruneRuntimeAgentChatDraftRestores(ctx context.Context, q *db.Queries, runtimeID pgtype.UUID, includeSystemAgents bool) error {
- if _, err := q.LockChatSessionsByArchivedRuntimeAgents(ctx, runtimeID); err != nil {
- return err
- }
- if err := q.DeleteChatDraftRestoresByArchivedRuntimeAgents(ctx, runtimeID); err != nil {
- return err
- }
- if !includeSystemAgents {
- return nil
- }
+func pruneRuntimeSystemAgentChatDraftRestores(ctx context.Context, q *db.Queries, runtimeID pgtype.UUID) error {
if _, err := q.LockChatSessionsBySystemRuntimeAgents(ctx, runtimeID); err != nil {
return err
}
diff --git a/server/internal/handler/chat_draft_restore_test.go b/server/internal/handler/chat_draft_restore_test.go
index 2f249e00f0..2eddab1fbd 100644
--- a/server/internal/handler/chat_draft_restore_test.go
+++ b/server/internal/handler/chat_draft_restore_test.go
@@ -222,17 +222,22 @@ func countDraftRestores(t *testing.T, sessionID string) int {
}
// DeleteChatSession is not the only way a chat_session dies: it also cascades
-// from agent (migration 033). Hard-deleting a runtime's archived agents drops
-// their sessions silently, and with no FK on chat_draft_restore the pending
-// restores — each holding the user's prompt — would be stranded forever.
-func TestDeleteAgentRuntime_PrunesDraftRestoresOfCascadedSessions(t *testing.T) {
+// from agent (migration 033). Since MUL-5559 a runtime delete only hard-deletes
+// the runtime's SYSTEM agents, so that is the cascade whose draft restores would
+// otherwise be stranded (chat_draft_restore has no FK).
+func TestDeleteAgentRuntime_PrunesDraftRestoresOfSystemAgentSessions(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
runtimeID := seedIsolatedRuntime(t, "Runtime With Draft Restore")
- archivedAgent := seedAgentOnRuntime(t, runtimeID, "Archived Agent With Draft Restore", true)
- sessionID := createHandlerTestChatSession(t, archivedAgent)
+ systemAgent := seedAgentOnRuntime(t, runtimeID, "System Agent With Draft Restore", false)
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE agent SET kind = 'system', system_key = 'draft_restore_probe' WHERE id = $1`,
+ systemAgent); err != nil {
+ t.Fatalf("make agent a system agent: %v", err)
+ }
+ sessionID := createHandlerTestChatSession(t, systemAgent)
seedDraftRestore(t, sessionID, "prompt stranded by the agent cascade", nil)
w := httptest.NewRecorder()
@@ -242,14 +247,44 @@ func TestDeleteAgentRuntime_PrunesDraftRestoresOfCascadedSessions(t *testing.T)
t.Fatalf("DeleteAgentRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
}
- if agentExists(t, archivedAgent) {
- t.Fatal("archived agent should have been deleted — the cascade under test never ran")
+ if agentExists(t, systemAgent) {
+ t.Fatal("system agent should have been deleted — the cascade under test never ran")
}
if n := countDraftRestores(t, sessionID); n != 0 {
t.Errorf("draft restores of a cascade-deleted session must be pruned, count = %d", n)
}
}
+// The mirror case, and the regression for the cleanup scope: an ARCHIVED USER
+// agent is no longer deleted with its runtime, so its session and the pending
+// restore holding the user's prompt must both survive. Pruning by "archived
+// agents on this runtime" — what the old teardown did — would throw away the
+// draft of an agent that is still there.
+func TestDeleteAgentRuntime_KeepsDraftRestoresOfUnboundAgentSessions(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ runtimeID := seedIsolatedRuntime(t, "Runtime With Surviving Draft Restore")
+ archivedAgent := seedAgentOnRuntime(t, runtimeID, "Archived Agent With Surviving Draft", true)
+ sessionID := createHandlerTestChatSession(t, archivedAgent)
+ seedDraftRestore(t, sessionID, "prompt that must survive the machine being retired", nil)
+
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest(http.MethodDelete, "/api/runtimes/"+runtimeID, nil), "runtimeId", runtimeID)
+ testHandler.DeleteAgentRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("DeleteAgentRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ if !agentExists(t, archivedAgent) {
+ t.Fatal("archived user agent must survive its runtime as an unbound agent")
+ }
+ if n := countDraftRestores(t, sessionID); n != 1 {
+ t.Errorf("draft restore of a surviving agent must be kept, count = %d", n)
+ }
+}
+
// The workspace cascade, same class. DeleteWorkspace runs outside a transaction
// (its atomicity comes from being one multi-CTE statement), so the prune has to
// live inside that statement — this is what guards it.
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 0ffe9caa98..091cba404d 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -3039,7 +3039,9 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
continue
}
if !agent.RuntimeID.Valid {
- blockTarget("squad", m.ID, ReasonRuntimeOffline)
+ // Unbound, not offline: the leader survived its runtime's
+ // deletion and needs a new one (MUL-5559).
+ blockTarget("squad", m.ID, ReasonAgentRuntimeRequired)
continue
}
hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, leaderID, opts)
@@ -3092,7 +3094,9 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
continue
}
if !agent.RuntimeID.Valid {
- blockTarget("agent", m.ID, ReasonRuntimeOffline)
+ // Unbound, not offline: there is no machine to bring back, so the
+ // user needs "bind a runtime", not "reconnect it" (MUL-5559).
+ blockTarget("agent", m.ID, ReasonAgentRuntimeRequired)
continue
}
hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, agentUUID, opts)
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 44d0460a54..fbc4350acd 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -16,6 +16,7 @@ import (
"time"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/auth"
@@ -307,6 +308,49 @@ func (h *Handler) inheritMachineCustomName(ctx context.Context, rt db.AgentRunti
return updated
}
+var errRuntimeProfileDisabled = errors.New("runtime profile is disabled")
+
+// upsertRuntimeWithProfile serializes custom-runtime registration with profile
+// deletion. The profile row remains KEY SHARE locked until the runtime upsert
+// commits; DeleteRuntimeProfile takes a conflicting UPDATE lock before it
+// enumerates runtime rows. This closes the stale-read window where deletion
+// could miss an instance inserted by a concurrently registering daemon.
+func (h *Handler) upsertRuntimeWithProfile(
+ ctx context.Context,
+ workspaceID, profileID pgtype.UUID,
+ build func(db.RuntimeProfile) db.UpsertAgentRuntimeWithProfileParams,
+) (db.UpsertAgentRuntimeWithProfileRow, db.RuntimeProfile, error) {
+ var row db.UpsertAgentRuntimeWithProfileRow
+ var profile db.RuntimeProfile
+
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return row, profile, fmt.Errorf("begin profile runtime registration: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+
+ profile, err = qtx.LockRuntimeProfileForRegistration(ctx, db.LockRuntimeProfileForRegistrationParams{
+ ID: profileID,
+ WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ return row, profile, fmt.Errorf("lock runtime profile: %w", err)
+ }
+ if !profile.Enabled {
+ return row, profile, errRuntimeProfileDisabled
+ }
+
+ row, err = qtx.UpsertAgentRuntimeWithProfile(ctx, build(profile))
+ if err != nil {
+ return row, profile, fmt.Errorf("upsert profile runtime: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return row, profile, fmt.Errorf("commit profile runtime registration: %w", err)
+ }
+ return row, profile, nil
+}
+
// sharedDaemonCustomName returns the machine-level name shared by all of a
// daemon's runtimes — the same rule the frontend's sharedCustomName applies:
// every runtime must carry the identical non-empty custom_name. Returns
@@ -429,32 +473,33 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
// The profile must exist in this workspace and be enabled. Trust
// the profile's stored protocol_family over the daemon-sent type so
// the provider used for task routing cannot drift from the profile.
- profile, perr := h.Queries.GetRuntimeProfileForWorkspace(r.Context(), db.GetRuntimeProfileForWorkspaceParams{
- ID: profileUUID,
- WorkspaceID: wsUUID,
- })
- if perr != nil {
+ prow, profile, err := h.upsertRuntimeWithProfile(
+ r.Context(),
+ wsUUID,
+ profileUUID,
+ func(profile db.RuntimeProfile) db.UpsertAgentRuntimeWithProfileParams {
+ return db.UpsertAgentRuntimeWithProfileParams{
+ WorkspaceID: wsUUID,
+ DaemonID: strToText(req.DaemonID),
+ Name: name,
+ RuntimeMode: "local",
+ Provider: profile.ProtocolFamily,
+ Status: status,
+ DeviceInfo: deviceInfo,
+ Metadata: metadata,
+ OwnerID: ownerID,
+ ProfileID: profileUUID,
+ }
+ },
+ )
+ if errors.Is(err, pgx.ErrNoRows) {
writeError(w, http.StatusBadRequest, "unknown runtime profile: "+runtime.ProfileID)
return
}
- if !profile.Enabled {
+ if errors.Is(err, errRuntimeProfileDisabled) {
writeError(w, http.StatusConflict, "runtime profile is disabled: "+runtime.ProfileID)
return
}
- provider = profile.ProtocolFamily
-
- prow, err := h.Queries.UpsertAgentRuntimeWithProfile(r.Context(), db.UpsertAgentRuntimeWithProfileParams{
- WorkspaceID: wsUUID,
- DaemonID: strToText(req.DaemonID),
- Name: name,
- RuntimeMode: "local",
- Provider: provider,
- Status: status,
- DeviceInfo: deviceInfo,
- Metadata: metadata,
- OwnerID: ownerID,
- ProfileID: profileUUID,
- })
if err != nil {
obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeFailed(
uuidToString(ownerID),
@@ -468,6 +513,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to register runtime: "+err.Error())
return
}
+ provider = profile.ProtocolFamily
inserted = prow.Inserted
registered = db.AgentRuntime{
ID: prow.ID,
@@ -590,46 +636,46 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
if !pok {
return
}
- profile, perr := h.Queries.GetRuntimeProfileForWorkspace(r.Context(), db.GetRuntimeProfileForWorkspaceParams{
- ID: profileUUID,
- WorkspaceID: wsUUID,
- })
- if perr != nil || !profile.Enabled {
- continue
- }
- name := profile.DisplayName
- if req.DeviceName != "" {
- name = fmt.Sprintf("%s (%s)", name, req.DeviceName)
- }
- deviceInfo := strings.TrimSpace(req.DeviceName)
reason := strings.TrimSpace(failed.Reason)
if reason == "" {
reason = "custom runtime command could not be resolved"
}
commandName := strings.TrimSpace(failed.CommandName)
- if commandName == "" {
- commandName = profile.CommandName
- }
- metadata, _ := json.Marshal(map[string]any{
- "version": "",
- "cli_version": req.CLIVersion,
- "launched_by": req.LaunchedBy,
- "runtime_profile_registration_error": true,
- "runtime_profile_failure_reason": reason,
- "command_name": commandName,
- })
- prow, err := h.Queries.UpsertAgentRuntimeWithProfile(r.Context(), db.UpsertAgentRuntimeWithProfileParams{
- WorkspaceID: wsUUID,
- DaemonID: strToText(req.DaemonID),
- Name: name,
- RuntimeMode: "local",
- Provider: profile.ProtocolFamily,
- Status: "offline",
- DeviceInfo: deviceInfo,
- Metadata: metadata,
- OwnerID: ownerID,
- ProfileID: profileUUID,
- })
+ prow, _, err := h.upsertRuntimeWithProfile(
+ r.Context(),
+ wsUUID,
+ profileUUID,
+ func(profile db.RuntimeProfile) db.UpsertAgentRuntimeWithProfileParams {
+ name := profile.DisplayName
+ if req.DeviceName != "" {
+ name = fmt.Sprintf("%s (%s)", name, req.DeviceName)
+ }
+ resolvedCommandName := commandName
+ if resolvedCommandName == "" {
+ resolvedCommandName = profile.CommandName
+ }
+ metadata, _ := json.Marshal(map[string]any{
+ "version": "",
+ "cli_version": req.CLIVersion,
+ "launched_by": req.LaunchedBy,
+ "runtime_profile_registration_error": true,
+ "runtime_profile_failure_reason": reason,
+ "command_name": resolvedCommandName,
+ })
+ return db.UpsertAgentRuntimeWithProfileParams{
+ WorkspaceID: wsUUID,
+ DaemonID: strToText(req.DaemonID),
+ Name: name,
+ RuntimeMode: "local",
+ Provider: profile.ProtocolFamily,
+ Status: "offline",
+ DeviceInfo: strings.TrimSpace(req.DeviceName),
+ Metadata: metadata,
+ OwnerID: ownerID,
+ ProfileID: profileUUID,
+ }
+ },
+ )
if err != nil {
slog.Warn("failed to record runtime profile registration failure",
"workspace_id", req.WorkspaceID, "daemon_id", req.DaemonID,
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 07c1f2a6a8..7c296a3d73 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -18,6 +18,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/dispatch"
"github.com/multica-ai/multica/server/internal/issueguard"
"github.com/multica-ai/multica/server/internal/logger"
"github.com/multica-ai/multica/server/internal/middleware"
@@ -2192,11 +2193,11 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {
return
}
if !agent.RuntimeID.Valid {
- writeAgentUnavailable(w, "agent has no runtime")
+ writeAgentUnavailable(w, "agent has no runtime", ReasonAgentRuntimeRequired)
return
}
if !h.isRuntimeOnline(r.Context(), agent.RuntimeID) {
- writeAgentUnavailable(w, "agent's runtime is offline")
+ writeAgentUnavailable(w, "agent's runtime is offline", ReasonRuntimeOffline)
return
}
@@ -2280,12 +2281,17 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {
// writeAgentUnavailable returns 422 with a stable error code so the modal
// can show a "switch agent" hint without parsing the human-readable reason.
-func writeAgentUnavailable(w http.ResponseWriter, reason string) {
+// writeAgentUnavailable refuses a trigger whose agent cannot run. `code` stays
+// agent_unavailable for installed clients; reason_code carries the machine-
+// readable distinction they need to phrase the fix — agent_runtime_required
+// ("bind a runtime") is not runtime_offline ("reconnect the machine").
+func writeAgentUnavailable(w http.ResponseWriter, reason string, reasonCode dispatch.ReasonCode) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnprocessableEntity)
json.NewEncoder(w).Encode(map[string]any{
- "code": "agent_unavailable",
- "reason": reason,
+ "code": "agent_unavailable",
+ "reason": reason,
+ "reason_code": reasonCode,
})
}
diff --git a/server/internal/handler/resource_label_cascade_test.go b/server/internal/handler/resource_label_cascade_test.go
index 44da2f130f..aef91bc0f0 100644
--- a/server/internal/handler/resource_label_cascade_test.go
+++ b/server/internal/handler/resource_label_cascade_test.go
@@ -76,10 +76,11 @@ func countSkillLabelAssignments(t *testing.T, ctx context.Context, skillID strin
return n
}
-// TestDeleteAgentRuntime_CleansAgentLabelAssignments: the strict runtime delete
-// hard-deletes the archived agent bound to the runtime; its label link must go
-// with it in the same transaction.
-func TestDeleteAgentRuntime_CleansAgentLabelAssignments(t *testing.T) {
+// TestDeleteAgentRuntime_KeepsUnboundAgentLabelAssignments: since MUL-5559 the
+// strict runtime delete unbinds the archived agent instead of hard-deleting it,
+// so its label links must SURVIVE. Clearing them by runtime — which is what the
+// old sweep did — would strip labels off an agent that is still there.
+func TestDeleteAgentRuntime_KeepsUnboundAgentLabelAssignments(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
@@ -97,18 +98,17 @@ func TestDeleteAgentRuntime_CleansAgentLabelAssignments(t *testing.T) {
t.Fatalf("DeleteAgentRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
}
- if agentExists(t, agentID) {
- t.Fatalf("archived agent should have been hard-deleted with its runtime")
+ if !agentExists(t, agentID) {
+ t.Fatalf("archived agent must survive its runtime as an unbound agent")
}
- if n := countAgentLabelAssignments(t, ctx, agentID); n != 0 {
- t.Fatalf("agent_to_label rows survived runtime delete: %d (orphaned once resource labels ship)", n)
+ if n := countAgentLabelAssignments(t, ctx, agentID); n != 1 {
+ t.Fatalf("agent_to_label rows for a surviving agent: got %d, want 1", n)
}
}
-// TestArchiveAgentsAndDeleteRuntime_CleansAgentLabelAssignments: the cascade
-// endpoint archives the active agent and hard-deletes it with the runtime, so
-// the label link must be swept too.
-func TestArchiveAgentsAndDeleteRuntime_CleansAgentLabelAssignments(t *testing.T) {
+// TestUnbindAgentsAndDeleteRuntime_KeepsAgentLabelAssignments: the confirmed
+// endpoint unbinds the active agent, so its labels stay attached too.
+func TestUnbindAgentsAndDeleteRuntime_KeepsAgentLabelAssignments(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
@@ -119,23 +119,22 @@ func TestArchiveAgentsAndDeleteRuntime_CleansAgentLabelAssignments(t *testing.T)
seedAgentLabel(t, ctx, testWorkspaceID, agentID)
w := httptest.NewRecorder()
- req := newRequest("POST", "/api/runtimes/"+runtimeID+"/archive-agents-and-delete",
+ req := newRequest("POST", "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete",
map[string]any{"expected_active_agent_ids": []string{agentID}})
req = withURLParam(req, "runtimeId", runtimeID)
- testHandler.ArchiveAgentsAndDeleteRuntime(w, req)
+ testHandler.UnbindAgentsAndDeleteRuntime(w, req)
if w.Code != http.StatusOK {
- t.Fatalf("ArchiveAgentsAndDeleteRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ t.Fatalf("UnbindAgentsAndDeleteRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
}
- if n := countAgentLabelAssignments(t, ctx, agentID); n != 0 {
- t.Fatalf("agent_to_label rows survived cascade runtime delete: %d", n)
+ if n := countAgentLabelAssignments(t, ctx, agentID); n != 1 {
+ t.Fatalf("agent_to_label rows for a surviving agent: got %d, want 1", n)
}
}
-// TestDeleteRuntimeProfile_CleansAgentLabelAssignments: deleting a runtime
-// profile hard-deletes the archived agents on each of its runtimes; their label
-// links must go with them.
-func TestDeleteRuntimeProfile_CleansAgentLabelAssignments(t *testing.T) {
+// TestDeleteRuntimeProfile_KeepsAgentLabelAssignments: the profile teardown runs
+// the same unbind, so the archived agent and its label links survive there too.
+func TestDeleteRuntimeProfile_KeepsAgentLabelAssignments(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
@@ -157,11 +156,46 @@ func TestDeleteRuntimeProfile_CleansAgentLabelAssignments(t *testing.T) {
t.Fatalf("DeleteRuntimeProfile: expected 204, got %d: %s", w.Code, w.Body.String())
}
+ if !agentExists(t, agentID) {
+ t.Fatalf("archived agent must survive its runtime profile as an unbound agent")
+ }
+ if n := countAgentLabelAssignments(t, ctx, agentID); n != 1 {
+ t.Fatalf("agent_to_label rows for a surviving agent: got %d, want 1", n)
+ }
+}
+
+// TestDeleteAgentRuntime_CleansSystemAgentLabelAssignments: system agents are
+// still hard-deleted with their runtime (they are invisible infrastructure with
+// no rebind affordance), so their label links must still be swept — otherwise
+// they become the invisible orphan rows the sweep exists to prevent.
+func TestDeleteAgentRuntime_CleansSystemAgentLabelAssignments(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := seedIsolatedRuntime(t, "Label Cleanup System Runtime")
+ agentID := seedAgentOnRuntime(t, runtimeID, "Label Cleanup System Agent", false)
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent SET kind = 'system', system_key = 'label_cleanup_probe' WHERE id = $1`,
+ agentID); err != nil {
+ t.Fatalf("make agent a system agent: %v", err)
+ }
+ seedAgentLabel(t, ctx, testWorkspaceID, agentID)
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.DeleteAgentRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("DeleteAgentRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
if agentExists(t, agentID) {
- t.Fatalf("archived agent should have been hard-deleted with its runtime profile")
+ t.Fatalf("system agent should still be hard-deleted with its runtime")
}
if n := countAgentLabelAssignments(t, ctx, agentID); n != 0 {
- t.Fatalf("agent_to_label rows survived runtime-profile delete: %d", n)
+ t.Fatalf("agent_to_label rows survived system-agent delete: %d", n)
}
}
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index e2672f1d7c..9dedce42da 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"
@@ -718,9 +719,154 @@ func (h *Handler) ListAgentRuntimes(w http.ResponseWriter, r *http.Request) {
// The strict variant: refuses with 409 + structured `runtime_has_active_agents`
// when any non-archived agent is still bound to the runtime, and returns the
// blocking agent list in the response body so the front-end can pivot to the
-// cascade dialog without an extra round-trip. The cascade itself lives at
-// POST /api/runtimes/:id/archive-agents-and-delete (ArchiveAgentsAndDeleteRuntime
+// confirm dialog without an extra round-trip. The confirmed variant lives at
+// POST /api/runtimes/:id/unbind-agents-and-delete (UnbindAgentsAndDeleteRuntime
// below) and runs the multi-write teardown inside a single transaction.
+// errRuntimeNotDrained means the runtime still owned a non-terminal task after
+// the teardown's own cancel pass. That should be impossible — it only happens if
+// a new non-terminal task status was added without extending
+// CancelAgentTasksByRuntimeOrAgent — so the teardown refuses rather than
+// deleting the rows or tripping the agent_task_queue_active_requires_runtime
+// CHECK with an opaque 500.
+var errRuntimeNotDrained = errors.New("runtime still has non-terminal tasks")
+
+// runtimeTeardownResult reports what the shared teardown changed so the caller
+// can broadcast it after the transaction commits.
+type runtimeTeardownResult struct {
+ UnboundAgents []db.Agent
+ CancelledTasks []db.AgentTaskQueue
+ PausedAutopilots []db.Autopilot
+}
+
+// unbindRuntimeForDelete is the teardown every runtime-delete path runs inside
+// its transaction, immediately before deleting the agent_runtime row (MUL-5559).
+//
+// It replaces the old archive-then-hard-delete of the runtime's agents. An agent
+// is a persistent business object — identity, instructions, skills, chats,
+// labels, channel installations, autopilot config — while a runtime is
+// replaceable execution capacity, so retiring a machine unbinds its agents
+// instead of destroying them. Unbound (runtime_id IS NULL) is a normal state,
+// orthogonal to archived: service.AgentReadiness already refuses to give work to
+// an agent with no runtime, and every trigger entry point reports
+// agent_runtime_required.
+//
+// Order matters:
+//
+// 1. Unbind the user agents. Archived ones included: an agent archived earlier
+// is just as much the user's data. System agents are excluded — they are
+// invisible infrastructure with no rebind affordance, so they are deleted in
+// step 5 as before.
+// 2. Pause active Autopilots assigned directly to those agents or to squads
+// they lead. The automation config stays intact and the persisted reason
+// explains that rebinding the Agent is the recovery path.
+// 3. Cancel the non-terminal tasks of this runtime AND of the agents we just
+// unbound. The agent-side match is load-bearing: agent.runtime_id can move
+// without rewriting agent_task_queue.runtime_id, so a task an unbound agent
+// left pinned to another runtime would otherwise stay claimable while its
+// owner is no longer allowed to run.
+// 4. Assert the runtime is drained (see errRuntimeNotDrained).
+// 5. Detach the task history. Without this, deleting the runtime row would
+// cascade agent_task_queue away — and task_message / task_usage /
+// task_token with it — so the agents would survive with no record of what
+// they ever did.
+// 6. Hard-delete the system agents, clearing first the rows whose cleanup has
+// no FK to follow (invocation targets, channel installations, chat pins,
+// labels, chat draft restores).
+func unbindRuntimeForDelete(ctx context.Context, qtx *db.Queries, runtimeID pgtype.UUID) (runtimeTeardownResult, error) {
+ var out runtimeTeardownResult
+
+ unbound, err := qtx.UnbindUserAgentsFromRuntime(ctx, runtimeID)
+ if err != nil {
+ return out, fmt.Errorf("unbind agents: %w", err)
+ }
+ out.UnboundAgents = unbound
+
+ unboundIDs := make([]pgtype.UUID, len(unbound))
+ for i, a := range unbound {
+ unboundIDs[i] = a.ID
+ }
+ paused, err := qtx.PauseAutopilotsByUnboundAgents(ctx, unboundIDs)
+ if err != nil {
+ return out, fmt.Errorf("pause autopilots: %w", err)
+ }
+ out.PausedAutopilots = paused
+
+ cancelled, err := qtx.CancelAgentTasksByRuntimeOrAgent(ctx, db.CancelAgentTasksByRuntimeOrAgentParams{
+ RuntimeIds: []pgtype.UUID{runtimeID},
+ AgentIds: unboundIDs,
+ })
+ if err != nil {
+ return out, fmt.Errorf("cancel tasks: %w", err)
+ }
+ out.CancelledTasks = cancelled
+
+ undrained, err := qtx.CountUndrainedTasksByRuntimeOrAgent(ctx, db.CountUndrainedTasksByRuntimeOrAgentParams{
+ RuntimeIds: []pgtype.UUID{runtimeID},
+ AgentIds: unboundIDs,
+ })
+ if err != nil {
+ return out, fmt.Errorf("count undrained tasks: %w", err)
+ }
+ if undrained > 0 {
+ return out, fmt.Errorf("%w: %d", errRuntimeNotDrained, undrained)
+ }
+ if _, err := qtx.UnbindTasksFromRuntime(ctx, runtimeID); err != nil {
+ return out, fmt.Errorf("unbind task history: %w", err)
+ }
+
+ // agent_invocation_target has no agent_id FK (MUL-3963).
+ if err := qtx.DeleteAgentInvocationTargetsBySystemRuntimeAgents(ctx, runtimeID); err != nil {
+ return out, fmt.Errorf("clean up agent invocation targets: %w", err)
+ }
+ // channel_* has no workspace/agent FK (MUL-3515 §4); an orphaned
+ // installation would keep occupying its bot's (channel_type, app_id)
+ // routing slot and make that bot un-rebindable (#4810).
+ if err := qtx.DeleteChannelInstallationsBySystemRuntimeAgents(ctx, runtimeID); err != nil {
+ return out, fmt.Errorf("clean up channel installations: %w", err)
+ }
+ if err := qtx.DeleteChatPinnedAgentsBySystemRuntimeAgents(ctx, runtimeID); err != nil {
+ return out, fmt.Errorf("clean up chat pins: %w", err)
+ }
+ // agent_to_label has no agent_id FK.
+ if err := qtx.DeleteAgentLabelAssignmentsBySystemRuntimeAgents(ctx, runtimeID); err != nil {
+ return out, fmt.Errorf("clean up agent label assignments: %w", err)
+ }
+ // chat_session cascades from agent and chat_draft_restore has no FK to
+ // follow it (#5219), so prune the restores before the agent rows go.
+ if err := pruneRuntimeSystemAgentChatDraftRestores(ctx, qtx, runtimeID); err != nil {
+ return out, fmt.Errorf("clean up chat draft restores: %w", err)
+ }
+ if err := qtx.DeleteSystemAgentsByRuntime(ctx, runtimeID); err != nil {
+ return out, fmt.Errorf("clean up system agents: %w", err)
+ }
+ return out, nil
+}
+
+// publishRuntimeTeardown fans out a committed teardown. Ordering matches the
+// other revocation paths: task:cancelled, then per-agent and Autopilot updates,
+// then the runtime-list refresh.
+func (h *Handler) publishRuntimeTeardown(ctx context.Context, res runtimeTeardownResult, wsID, userID string) {
+ if h.TaskService != nil && len(res.CancelledTasks) > 0 {
+ h.TaskService.BroadcastCancelledTasks(ctx, res.CancelledTasks)
+ }
+ for _, a := range res.UnboundAgents {
+ // agent:status is the generic "this agent changed" broadcast the agent
+ // update path already uses; subscribers refresh the row and see
+ // runtime_bound=false. No agent:archived here — nothing was archived.
+ h.publish(protocol.EventAgentStatus, wsID, "member", userID, map[string]any{
+ "agent": broadcastAgentResponse(h.agentToResponse(a)),
+ })
+ }
+ for _, a := range res.PausedAutopilots {
+ h.publish(protocol.EventAutopilotUpdated, wsID, "member", userID, map[string]any{
+ "autopilot": autopilotToResponse(a, nil),
+ })
+ }
+ h.publish(protocol.EventDaemonRegister, wsID, "member", userID, map[string]any{
+ "action": "delete",
+ })
+}
+
func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
@@ -776,23 +922,15 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to check runtime dependencies")
return
}
+ // Refuse before any teardown-side effects while active agents are still
+ // bound. The user confirms the plan through
+ // POST /runtimes/:id/unbind-agents-and-delete, which reuses the same
+ // teardown once the confirmed set is verified.
if len(activeAgents) > 0 {
writeJSON(w, http.StatusConflict, h.runtimeHasActiveAgentsResponse(activeAgents))
return
}
- // Refuse before any teardown-side effects if the runtime still has active
- // squads whose leader is already archived on this runtime.
- activeSquadCount, err := h.Queries.CountActiveSquadsWithArchivedLeadersByRuntime(r.Context(), rt.ID)
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to check runtime squad dependencies")
- return
- }
- if activeSquadCount > 0 {
- writeError(w, http.StatusConflict, "cannot delete runtime: it has active squads led by archived agents. Archive those squads or assign them a new leader first.")
- return
- }
-
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to delete runtime")
@@ -801,74 +939,44 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
- // Pause autopilots pointing at the archived agents BEFORE we delete
- // them. Migration 096 dropped the autopilot.assignee_id agent FK, so a
- // hard-delete here would otherwise leave dangling rows that subsequent
- // scheduler ticks would skip with "assignee agent no longer exists" —
- // quiet, but burning a run record every tick until an operator notices.
- // Pausing makes the breakage visible in the autopilot list so the owner
- // can re-point or delete the row instead. This runs inside the teardown
- // transaction so a pause that lands but is followed by a failed delete
- // rolls back with everything else, matching ArchiveAgentsAndDeleteRuntime.
- archivedAgentIDs, err := qtx.ListArchivedAgentIDsByRuntime(r.Context(), rt.ID)
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to enumerate archived agents")
- return
- }
- if len(archivedAgentIDs) > 0 {
- if err := qtx.PauseAutopilotsByAgentAssignees(r.Context(), archivedAgentIDs); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to pause autopilots")
- return
- }
- }
-
- // Remove archived squads whose leader is an archived agent on this runtime
- // so the RESTRICT FK on squad.leader_id won't block the subsequent agent
- // deletion. Active squads are handled by the 409 guard above instead.
- if err := qtx.DeleteSquadsByArchivedAgentsOnRuntime(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up squads referencing archived agents")
- return
- }
-
- // Remove archived agents so the FK constraint (ON DELETE RESTRICT) won't block deletion.
- // First drop their invocation targets — agent_invocation_target has no
- // agent_id FK (MUL-3963), so cleanup is app-layer and MUST precede the
- // agent hard-delete to avoid orphan rows.
- if err := qtx.DeleteAgentInvocationTargetsByArchivedRuntimeAgents(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up agent invocation targets")
- return
- }
- // Same app-layer cleanup for channel installations: channel_* has no
- // workspace/agent FK (MUL-3515 §4), so an archived agent's bot installations
- // would otherwise survive the hard-delete as orphans and keep occupying their
- // (channel_type, app_id) routing slots, making those bots un-rebindable (#4810).
- if err := qtx.DeleteChannelInstallationsByArchivedRuntimeAgents(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up channel installations")
- return
- }
- if err := qtx.DeleteChatPinnedAgentsByArchivedRuntimeAgents(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up chat pins")
+ // Revalidate under the runtime row lock. Agent/task inserts take a
+ // KEY SHARE lock through their runtime FK, so no active agent can appear
+ // after this check and then be silently unbound by the teardown.
+ if _, err := qtx.LockAgentRuntime(r.Context(), rt.ID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to lock runtime")
return
}
- // agent_to_label has no agent_id FK, so clear the runtime's agents' label
- // links before those agents are hard-deleted below; otherwise they survive
- // as invisible orphan rows once resource labels are enabled.
- if err := qtx.DeleteAgentLabelAssignmentsByRuntime(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up agent label assignments")
+ if _, err := qtx.ListUserAgentsByRuntimeForUpdate(r.Context(), rt.ID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to lock runtime dependencies")
return
}
- // The agent deletes below cascade away these agents' chat_sessions, and
- // chat_draft_restore has no FK to follow them (#5219). Prune first.
- if err := pruneRuntimeAgentChatDraftRestores(r.Context(), qtx, rt.ID, true); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up chat draft restores")
+ activeAgents, err = qtx.ListActiveAgentsByRuntimeForUpdate(r.Context(), rt.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to check runtime dependencies")
return
}
- if err := qtx.DeleteArchivedAgentsByRuntime(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up archived agents")
+ if len(activeAgents) > 0 {
+ writeJSON(w, http.StatusConflict, h.runtimeHasActiveAgentsResponse(activeAgents))
return
}
- if err := qtx.DeleteSystemAgentsByRuntime(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up system agents")
+
+ // Same teardown the confirmed path runs: unbind the runtime's agents and
+ // their task history, cancel what was still active, remove only the system
+ // agents. There is no active agent here by definition, but archived ones and
+ // their history can still be bound to this runtime.
+ teardown, err := unbindRuntimeForDelete(r.Context(), qtx, rt.ID)
+ if err != nil {
+ if errors.Is(err, errRuntimeNotDrained) {
+ slog.Error("runtime delete aborted: tasks not drained",
+ "runtime_id", uuidToString(rt.ID), "error", err)
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "the runtime still has tasks in flight; retry in a moment.",
+ "code": "runtime_delete_not_drained",
+ })
+ return
+ }
+ slog.Error("runtime delete teardown failed", "runtime_id", uuidToString(rt.ID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to delete runtime")
return
}
@@ -881,18 +989,21 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
return
}
- slog.Info("runtime deleted", "runtime_id", uuidToString(rt.ID), "deleted_by", userID)
+ slog.Info("runtime deleted",
+ "runtime_id", uuidToString(rt.ID),
+ "deleted_by", userID,
+ "agents_unbound", len(teardown.UnboundAgents),
+ "tasks_cancelled", len(teardown.CancelledTasks),
+ "autopilots_paused", len(teardown.PausedAutopilots),
+ )
- // Notify frontend to refresh runtime list.
- h.publish(protocol.EventDaemonRegister, wsID, "member", userID, map[string]any{
- "action": "delete",
- })
+ h.publishRuntimeTeardown(r.Context(), teardown, wsID, userID)
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
// runtimeHasActiveAgentsResponse builds the structured 409 body shared by
-// DeleteAgentRuntime (light-mode block) and ArchiveAgentsAndDeleteRuntime
+// DeleteAgentRuntime (light-mode block) and UnbindAgentsAndDeleteRuntime
// (cascade-plan-changed). The shape is:
//
// {
@@ -909,36 +1020,44 @@ func (h *Handler) runtimeHasActiveAgentsResponse(agents []db.Agent) map[string]a
resp[i] = h.agentToResponse(a)
}
return map[string]any{
- "error": "cannot delete runtime: it has active agents bound to it. Archive or reassign the agents first.",
+ "error": "cannot delete runtime: it has active agents bound to it. Reassign them or confirm unbinding them first.",
"code": "runtime_has_active_agents",
"active_agents": resp,
}
}
-// archiveAgentsAndDeleteRuntimeRequest is the wire shape for the cascade
-// endpoint. expected_active_agent_ids is the snapshot the user just confirmed
-// in the dialog — the server compares it to the live set inside the
+// unbindAgentsAndDeleteRuntimeRequest is the wire shape for the confirmed
+// delete endpoint. expected_active_agent_ids is the snapshot the user just
+// confirmed in the dialog — the server compares it to the live set inside the
// transaction and refuses with runtime_delete_plan_changed if anything moved
// between dialog open and confirm. That guarantees the user is approving the
-// exact agent set that will be archived, even if a teammate adds or archives
-// an agent in the same window.
-type archiveAgentsAndDeleteRuntimeRequest struct {
+// exact agent set that will be unbound, even if a teammate adds or archives an
+// agent in the same window.
+//
+// The compared set is deliberately still "active agents on this runtime": it is
+// what installed clients send, and widening it would make every older client's
+// request mismatch and 409 forever, leaving the runtime undeletable. Extra
+// information for the dialog belongs in read-only fields, not in this set.
+type unbindAgentsAndDeleteRuntimeRequest struct {
ExpectedActiveAgentIDs []string `json:"expected_active_agent_ids"`
}
-// ArchiveAgentsAndDeleteRuntime is the cascade entry point: archive every
-// agent currently bound to the runtime, cancel their queued/running tasks,
-// pause autopilots that target them, hard-delete the now-detached archived
-// rows so the agent.runtime_id FK no longer pins the runtime, and finally
-// delete the runtime row itself — all inside a single transaction so a
-// partial failure never leaves a runtime half-torn-down.
+// UnbindAgentsAndDeleteRuntime is the confirmed delete entry point: unbind every
+// user agent bound to the runtime, pause affected Autopilots, cancel active
+// tasks, detach task history, hard-delete only the system agents, and finally
+// delete the runtime row — all inside a single transaction so a partial failure
+// never leaves a runtime half-torn-down.
+//
+// Before MUL-5559 this archived those agents and then hard-deleted the rows,
+// destroying every conversation with them; the dialog said "archive", so what
+// the user agreed to was not what happened. Now nothing of the user's is
+// destroyed: the agents survive unbound and need a new runtime to run again.
//
// Transaction order follows the reference revoke flow in
-// revokeAndRemoveMember (workspace_revoke.go) so the two cascade paths share
-// the same race-safety properties: the dispatcher can't claim a task whose
-// runtime is about to vanish, autopilots can't fire onto a dead assignee,
-// and post-commit publish events emit the same task:cancelled →
-// agent:archived → daemon:register fan-out.
+// revokeAndRemoveMember (workspace_revoke.go) so the two paths share the same
+// race-safety properties: the dispatcher can't claim a task whose runtime is
+// about to vanish, and post-commit publish events emit the same
+// task:cancelled → agent:status/autopilot:updated → daemon:register fan-out.
//
// The expected_active_agent_ids check is the load-bearing piece for the UX:
// the front-end snapshots the agent list when the dialog opens and presents
@@ -946,14 +1065,17 @@ type archiveAgentsAndDeleteRuntimeRequest struct {
// while that dialog is open, this endpoint refuses with
// runtime_delete_plan_changed and the latest list, so the user never confirms
// a stale plan.
-func (h *Handler) ArchiveAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.Request) {
+//
+// Served at POST /api/runtimes/:id/unbind-agents-and-delete and, for installed
+// clients, the original /archive-agents-and-delete path.
+func (h *Handler) UnbindAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
if !ok {
return
}
- var req archiveAgentsAndDeleteRuntimeRequest
+ var req unbindAgentsAndDeleteRuntimeRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
@@ -1014,11 +1136,15 @@ func (h *Handler) ArchiveAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.R
// which conflicts with FOR UPDATE — so any concurrent INSERT or
// UPDATE that would point a new/moved agent at this runtime now
// blocks until our tx finishes. This is the "兜底" lock that keeps
- // new actives from appearing between our snapshot and our archive.
+ // new actives from appearing between our snapshot and our unbind.
if _, err := qtx.LockAgentRuntime(r.Context(), rt.ID); err != nil {
writeError(w, http.StatusInternalServerError, "failed to lock runtime")
return
}
+ if _, err := qtx.ListUserAgentsByRuntimeForUpdate(r.Context(), rt.ID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to lock runtime dependencies")
+ return
+ }
// Re-list active agents inside the transaction, with FOR UPDATE on
// each row so a concurrent archive/move of one of those existing
@@ -1026,7 +1152,7 @@ func (h *Handler) ArchiveAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.R
// set here closes the dialog-open / user-confirm race: even if a
// teammate creates or archives an agent on this runtime while the
// dialog was open, the user is approving exactly the set the server
- // is about to archive.
+ // is about to unbind.
currentActive, err := qtx.ListActiveAgentsByRuntimeForUpdate(r.Context(), rt.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to enumerate active agents")
@@ -1045,107 +1171,27 @@ func (h *Handler) ArchiveAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.R
return
}
- // Build the agent ID list once — it's the explicit allowlist for the
- // archive UPDATE below and the runtime-or-agent task cancel further
- // down. By keying the archive off this list (not off runtime_id) we
- // guarantee that agents not in the user's confirmed set can never
- // be silently archived, even if the row-level locks above somehow
- // missed something. Defense in depth.
- currentActiveIDs := make([]pgtype.UUID, len(currentActive))
- for i, a := range currentActive {
- currentActiveIDs[i] = a.ID
- }
-
- // 1. Archive every active agent on this runtime, narrowed to the
- // user-confirmed expected_active_agent_ids set (which equals
- // currentActive at this point). Returns the affected rows so the
- // post-commit publish loop can fan out agent:archived per agent.
- archivedAgents, err := qtx.ArchiveAgentsByIDs(r.Context(), db.ArchiveAgentsByIDsParams{
- ArchivedBy: member.UserID,
- AgentIds: currentActiveIDs,
- })
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to archive agents")
- return
- }
-
- // 2. Cancel queued/dispatched/running tasks. Match by runtime_id AND
- // by archived agent ids: agent.runtime_id can be reassigned without
- // rewriting historical agent_task_queue rows, so an agent we just
- // archived may still own tasks pinned to a different runtime — and
- // ClaimAgentTask does not gate on agent.archived_at.
- archivedIDs := make([]pgtype.UUID, len(archivedAgents))
- for i, a := range archivedAgents {
- archivedIDs[i] = a.ID
- }
- cancelledTasks, err := qtx.CancelAgentTasksByRuntimeOrAgent(r.Context(), db.CancelAgentTasksByRuntimeOrAgentParams{
- RuntimeIds: []pgtype.UUID{rt.ID},
- AgentIds: archivedIDs,
- })
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to cancel tasks")
- return
- }
-
- // 3. Pause autopilots whose assignee is one of the archived agents.
- // Snapshots the full archived set on this runtime — including any
- // that were already archived before this call — because the
- // DeleteArchivedAgentsByRuntime below will hard-delete the lot, and
- // a paused autopilot is much louder in the UI than a silently-
- // dangling assignee_id (see migration 096 for why the FK is gone).
- allArchivedIDs, err := qtx.ListArchivedAgentIDsByRuntime(r.Context(), rt.ID)
+ // Single teardown, shared with the light DELETE path: unbind every user
+ // agent (active and archived) plus their task history, cancel what was
+ // running or queued, and hard-delete only the system agents. Nothing the
+ // user configured is destroyed — the agents just need a new runtime.
+ teardown, err := unbindRuntimeForDelete(r.Context(), qtx, rt.ID)
if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to enumerate archived agents")
- return
- }
- if len(allArchivedIDs) > 0 {
- if err := qtx.PauseAutopilotsByAgentAssignees(r.Context(), allArchivedIDs); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to pause autopilots")
+ if errors.Is(err, errRuntimeNotDrained) {
+ slog.Error("runtime delete aborted: tasks not drained",
+ "runtime_id", uuidToString(rt.ID), "error", err)
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "the runtime still has tasks in flight; retry in a moment.",
+ "code": "runtime_delete_not_drained",
+ })
return
}
- }
-
- // 4. Hard-delete the archived agents so the agent.runtime_id FK
- // (ON DELETE RESTRICT) no longer keeps the runtime alive.
- if err := qtx.DeleteAgentInvocationTargetsByArchivedRuntimeAgents(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up agent invocation targets")
- return
- }
- // Same app-layer cleanup for channel installations: channel_* has no
- // workspace/agent FK (MUL-3515 §4), so an archived agent's bot installations
- // would otherwise survive the hard-delete as orphans and keep occupying their
- // (channel_type, app_id) routing slots, making those bots un-rebindable (#4810).
- if err := qtx.DeleteChannelInstallationsByArchivedRuntimeAgents(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up channel installations")
- return
- }
- if err := qtx.DeleteChatPinnedAgentsByArchivedRuntimeAgents(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up chat pins")
- return
- }
- // agent_to_label has no agent_id FK, so clear the runtime's agents' label
- // links before those agents are hard-deleted below; otherwise they survive
- // as invisible orphan rows once resource labels are enabled.
- if err := qtx.DeleteAgentLabelAssignmentsByRuntime(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up agent label assignments")
- return
- }
- // The agent deletes below cascade away these agents' chat_sessions, and
- // chat_draft_restore has no FK to follow them (#5219). Prune first.
- if err := pruneRuntimeAgentChatDraftRestores(r.Context(), qtx, rt.ID, true); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up chat draft restores")
- return
- }
- if err := qtx.DeleteArchivedAgentsByRuntime(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up archived agents")
- return
- }
- if err := qtx.DeleteSystemAgentsByRuntime(r.Context(), rt.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up system agents")
+ slog.Error("runtime delete teardown failed", "runtime_id", uuidToString(rt.ID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to unbind agents")
return
}
- // 5. Finally delete the runtime row itself.
+ // Finally delete the runtime row itself.
if err := qtx.DeleteAgentRuntime(r.Context(), rt.ID); err != nil {
writeError(w, http.StatusInternalServerError, "failed to delete runtime")
return
@@ -1156,39 +1202,32 @@ func (h *Handler) ArchiveAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.R
return
}
- // Post-commit fan-out — same ordering as publishRevocation so subscribers
- // observe task:cancelled before agent:archived before the runtime list
- // refresh, matching the order other revocation paths use.
- if h.TaskService != nil && len(cancelledTasks) > 0 {
- h.TaskService.BroadcastCancelledTasks(r.Context(), cancelledTasks)
- }
- for _, a := range archivedAgents {
- h.publish(protocol.EventAgentArchived, wsID, "member", userID, map[string]any{
- "agent": h.agentToResponse(a),
- })
- }
- h.publish(protocol.EventDaemonRegister, wsID, "member", userID, map[string]any{
- "action": "delete",
- })
+ h.publishRuntimeTeardown(r.Context(), teardown, wsID, userID)
- slog.Info("runtime deleted via cascade",
+ slog.Info("runtime deleted, agents unbound",
"runtime_id", uuidToString(rt.ID),
"deleted_by", userID,
- "agents_archived", len(archivedAgents),
- "tasks_cancelled", len(cancelledTasks),
+ "agents_unbound", len(teardown.UnboundAgents),
+ "tasks_cancelled", len(teardown.CancelledTasks),
+ "autopilots_paused", len(teardown.PausedAutopilots),
)
writeJSON(w, http.StatusOK, map[string]any{
- "status": "ok",
- "agents_archived": len(archivedAgents),
- "tasks_cancelled": len(cancelledTasks),
+ "status": "ok",
+ "agents_unbound": len(teardown.UnboundAgents),
+ "tasks_cancelled": len(teardown.CancelledTasks),
+ "autopilots_paused": len(teardown.PausedAutopilots),
+ // Deprecated mirror of agents_unbound: installed clients built against
+ // the archive-and-delete contract read this key. The count is the same
+ // set of agents; they are no longer archived.
+ "agents_archived": len(teardown.UnboundAgents),
})
}
// parseExpectedActiveAgentIDs validates the cascade endpoint's
// expected_active_agent_ids list. nil / empty is allowed (an empty set is a
// valid plan: "I confirmed there are no active agents" — the cascade then
-// just deletes the runtime without archiving anything). Returns ok=false on
+// just deletes the runtime without unbinding an active agent). Returns ok=false on
// any malformed UUID so the handler responds 400 instead of silently
// matching a different set.
func parseExpectedActiveAgentIDs(raw []string) (map[string]struct{}, bool) {
diff --git a/server/internal/handler/runtime_archive_squad_cleanup_test.go b/server/internal/handler/runtime_archive_squad_cleanup_test.go
deleted file mode 100644
index fcfcdb5c55..0000000000
--- a/server/internal/handler/runtime_archive_squad_cleanup_test.go
+++ /dev/null
@@ -1,382 +0,0 @@
-package handler
-
-import (
- "context"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
-
- "github.com/multica-ai/multica/server/internal/util"
-)
-
-// These tests cover the squad-cleanup step added to DeleteAgentRuntime:
-// archived agents on a torn-down runtime can still be referenced
-// as leaders of squads (including archived ones), and the squad.leader_id
-// FK is ON DELETE RESTRICT, so the subsequent DELETE FROM agent would fail.
-// The fix runs DeleteSquadsByArchivedAgentsOnRuntime first to drop archived
-// squads referencing archived leaders, unblocking the agent delete in the
-// originally reported case.
-
-// seedIsolatedRuntime creates a fresh runtime in the shared test workspace
-// (so the seeded test user is owner/admin and passes canEditRuntime), and
-// returns its UUID. The runtime is auto-cleaned via t.Cleanup; tests that
-// successfully drive DeleteAgentRuntime through to the end will have already
-// deleted it, in which case the cleanup is a no-op.
-func seedIsolatedRuntime(t *testing.T, name string) string {
- t.Helper()
- ctx := context.Background()
- var runtimeID string
- if err := testPool.QueryRow(ctx, `
- INSERT INTO agent_runtime (
- workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at
- )
- VALUES ($1, NULL, $2, 'cloud', 'isolated_test', 'online', 'isolated test runtime', '{}'::jsonb, now())
- RETURNING id
- `, testWorkspaceID, name).Scan(&runtimeID); err != nil {
- t.Fatalf("seed runtime %q: %v", name, err)
- }
- t.Cleanup(func() {
- // Best-effort cascading cleanup; ignore errors because the handler
- // may have already removed the row in the happy path.
- testPool.Exec(ctx, `DELETE FROM agent WHERE runtime_id = $1`, runtimeID)
- testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)
- })
- return runtimeID
-}
-
-// seedAgentOnRuntime creates an agent on the given runtime. If archived is
-// true the row is created with archived_at = now().
-func seedAgentOnRuntime(t *testing.T, runtimeID, name string, archived bool) string {
- t.Helper()
- ctx := context.Background()
- 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
- )
- VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'workspace', 1, $4)
- RETURNING id
- `, testWorkspaceID, name, runtimeID, testUserID).Scan(&agentID); err != nil {
- t.Fatalf("seed agent %q: %v", name, err)
- }
- if archived {
- if _, err := testPool.Exec(ctx,
- `UPDATE agent SET archived_at = now(), archived_by = $1 WHERE id = $2`,
- testUserID, agentID,
- ); err != nil {
- t.Fatalf("archive agent %q: %v", name, err)
- }
- }
- t.Cleanup(func() {
- // Squad rows referencing this agent could block a plain DELETE; nuke
- // them first. Tests that complete through the handler will already
- // have done this.
- testPool.Exec(ctx, `DELETE FROM squad WHERE leader_id = $1`, agentID)
- testPool.Exec(ctx, `DELETE FROM agent WHERE id = $1`, agentID)
- })
- return agentID
-}
-
-// seedSquad creates a squad with the given leader. If archived is true the
-// row is created with archived_at = now() (the case the user originally hit
-// — `multica squad list` filters out archived squads, hiding the FK
-// blocker).
-func seedSquad(t *testing.T, leaderID, name string, archived bool) string {
- t.Helper()
- ctx := context.Background()
- var squadID string
- if err := testPool.QueryRow(ctx, `
- INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)
- VALUES ($1, $2, '', $3, $4)
- RETURNING id
- `, testWorkspaceID, name, leaderID, testUserID).Scan(&squadID); err != nil {
- t.Fatalf("seed squad %q: %v", name, err)
- }
- if archived {
- if _, err := testPool.Exec(ctx,
- `UPDATE squad SET archived_at = now(), archived_by = $1 WHERE id = $2`,
- testUserID, squadID,
- ); err != nil {
- t.Fatalf("archive squad %q: %v", name, err)
- }
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM squad WHERE id = $1`, squadID)
- })
- return squadID
-}
-
-func squadExists(t *testing.T, squadID string) bool {
- t.Helper()
- var count int
- if err := testPool.QueryRow(context.Background(),
- `SELECT count(*) FROM squad WHERE id = $1`, squadID,
- ).Scan(&count); err != nil {
- t.Fatalf("count squad %s: %v", squadID, err)
- }
- return count == 1
-}
-
-func agentExists(t *testing.T, agentID string) bool {
- t.Helper()
- var count int
- if err := testPool.QueryRow(context.Background(),
- `SELECT count(*) FROM agent WHERE id = $1`, agentID,
- ).Scan(&count); err != nil {
- t.Fatalf("count agent %s: %v", agentID, err)
- }
- return count == 1
-}
-
-func runtimeExists(t *testing.T, runtimeID string) bool {
- t.Helper()
- var count int
- if err := testPool.QueryRow(context.Background(),
- `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID,
- ).Scan(&count); err != nil {
- t.Fatalf("count runtime %s: %v", runtimeID, err)
- }
- return count == 1
-}
-
-// TestDeleteSquadsByArchivedAgentsOnRuntime_Query exercises the new query in
-// isolation. It has to delete archived squads whose leader is an archived
-// agent on the target runtime, AND only those — active squads, squads led by
-// active agents, or squads led by archived agents on a different runtime,
-// must be left alone.
-func TestDeleteSquadsByArchivedAgentsOnRuntime_Query(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
- ctx := context.Background()
-
- // Two distinct runtimes so we can prove scoping by runtime_id.
- runtimeA := seedIsolatedRuntime(t, "Squad Cleanup Query Runtime A")
- runtimeB := seedIsolatedRuntime(t, "Squad Cleanup Query Runtime B")
-
- // Leaders:
- // - archivedOnA: archived agent on runtime A -> its squads must be deleted
- // - activeOnA: active agent on runtime A -> its squad must survive
- // - archivedOnB: archived agent on runtime B -> its squad must survive
- archivedOnA := seedAgentOnRuntime(t, runtimeA, "ArchivedOnA", true)
- activeOnA := seedAgentOnRuntime(t, runtimeA, "ActiveOnA", false)
- archivedOnB := seedAgentOnRuntime(t, runtimeB, "ArchivedOnB", true)
-
- // Squads:
- // - activeSquadA: archived leader on A, squad itself active -> keep
- // - archivedSquadA: archived leader on A, squad itself archived -> delete (the bug)
- // - keptActiveLeader: active leader on A -> keep
- // - keptDifferentRuntime: archived leader but on B -> keep
- activeSquadOnA := seedSquad(t, archivedOnA, "Active Squad On Runtime A", false)
- archivedSquadOnA := seedSquad(t, archivedOnA, "Archived Squad On Runtime A", true)
- keptActiveLeader := seedSquad(t, activeOnA, "Squad With Active Leader", false)
- keptDifferentRuntime := seedSquad(t, archivedOnB, "Squad On Runtime B", false)
-
- // Run the query against runtime A.
- if err := testHandler.Queries.DeleteSquadsByArchivedAgentsOnRuntime(
- ctx, util.MustParseUUID(runtimeA),
- ); err != nil {
- t.Fatalf("DeleteSquadsByArchivedAgentsOnRuntime: %v", err)
- }
-
- if !squadExists(t, activeSquadOnA) {
- t.Errorf("active squad with archived leader on target runtime must NOT be deleted")
- }
- if squadExists(t, archivedSquadOnA) {
- t.Errorf("archived squad with archived leader on target runtime should be deleted (this is the bug case)")
- }
- if !squadExists(t, keptActiveLeader) {
- t.Errorf("squad with non-archived leader must NOT be deleted")
- }
- if !squadExists(t, keptDifferentRuntime) {
- t.Errorf("squad whose leader is on a different runtime must NOT be deleted")
- }
-
- // Run the query a second time — it must be idempotent / safe to call when
- // nothing matches anymore.
- if err := testHandler.Queries.DeleteSquadsByArchivedAgentsOnRuntime(
- ctx, util.MustParseUUID(runtimeA),
- ); err != nil {
- t.Fatalf("re-running DeleteSquadsByArchivedAgentsOnRuntime should be a no-op, got: %v", err)
- }
-
- // And running it against a runtime with no archived agents at all must
- // also be a no-op (the test workspace's seeded runtime has only one
- // active agent and no archived ones).
- if err := testHandler.Queries.DeleteSquadsByArchivedAgentsOnRuntime(
- ctx, util.MustParseUUID(testRuntimeID),
- ); err != nil {
- t.Fatalf("no-archived-agents runtime: expected no-op, got: %v", err)
- }
-}
-
-// TestDeleteAgentRuntime_RemovesArchivedSquadsLedByArchivedAgents is the end-to-end
-// regression test: a runtime whose only agents are archived but
-// still referenced as squad leaders must now delete cleanly.
-//
-// Before this fix the handler returned 500 "failed to clean up archived
-// agents" because squad.leader_id REFERENCES agent(id) ON DELETE RESTRICT
-// blocked the DELETE FROM agent step. With the squad-cleanup step in front
-// of the agent-cleanup, the delete succeeds.
-func TestDeleteAgentRuntime_RemovesArchivedSquadsLedByArchivedAgents(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
-
- runtimeID := seedIsolatedRuntime(t, "Runtime With Archived Squad Leader")
- archivedLeader := seedAgentOnRuntime(t, runtimeID, "Archived Squad Leader Agent", true)
- // Use an *archived* squad — that's the case the user originally hit, and
- // it's the one that's invisible from `multica squad list`.
- archivedSquad := seedSquad(t, archivedLeader, "Archived Squad For Runtime Delete", true)
-
- w := httptest.NewRecorder()
- req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
- req = withURLParam(req, "runtimeId", runtimeID)
- testHandler.DeleteAgentRuntime(w, req)
- if w.Code != http.StatusOK {
- t.Fatalf("DeleteAgentRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
- }
-
- if squadExists(t, archivedSquad) {
- t.Errorf("squad led by archived agent on the runtime should have been deleted")
- }
- if agentExists(t, archivedLeader) {
- t.Errorf("archived agent on the runtime should have been deleted")
- }
- if runtimeExists(t, runtimeID) {
- t.Errorf("runtime should have been deleted")
- }
-}
-
-// TestDeleteAgentRuntime_ActiveSquadWithArchivedLeaderReturnsConflict covers
-// the remaining reachable state from the public API: an active squad led by
-// an archived agent. Runtime delete must fail cleanly with a 409 before the
-// later archived-agent delete trips the RESTRICT FK and leaks a 500.
-func TestDeleteAgentRuntime_ActiveSquadWithArchivedLeaderReturnsConflict(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
-
- runtimeID := seedIsolatedRuntime(t, "Runtime With Active Squad And Archived Leader")
- archivedLeader := seedAgentOnRuntime(t, runtimeID, "Archived Leader Blocking Runtime Delete", true)
- activeSquad := seedSquad(t, archivedLeader, "Active Squad Blocking Runtime Delete", false)
-
- 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("DeleteAgentRuntime: expected 409 archived-leader squad guard, got %d: %s", w.Code, w.Body.String())
- }
- if !strings.Contains(w.Body.String(), "active squads led by archived agents") {
- t.Fatalf("DeleteAgentRuntime: expected actionable archived-leader squad message, got body %s", w.Body.String())
- }
-
- if !squadExists(t, activeSquad) {
- t.Errorf("active squad must NOT have been deleted by a refused runtime delete")
- }
- if !agentExists(t, archivedLeader) {
- t.Errorf("archived leader must NOT have been deleted by a refused runtime delete")
- }
- if !runtimeExists(t, runtimeID) {
- t.Errorf("runtime must NOT have been deleted by a refused delete")
- }
-}
-
-// TestDeleteAgentRuntime_ArchivedAndActiveSquadsReturnConflictWithoutDeletes
-// pins the combination case from review: if the same archived leader is
-// referenced by both an archived squad and an active squad on the runtime, the
-// handler must return 409 before deleting either squad.
-func TestDeleteAgentRuntime_ArchivedAndActiveSquadsReturnConflictWithoutDeletes(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
-
- runtimeID := seedIsolatedRuntime(t, "Runtime With Archived And Active Squads")
- archivedLeader := seedAgentOnRuntime(t, runtimeID, "Archived Leader With Mixed Squads", true)
- archivedSquad := seedSquad(t, archivedLeader, "Archived Squad On Refused Delete", true)
- activeSquad := seedSquad(t, archivedLeader, "Active Squad On Refused Delete", false)
-
- 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("DeleteAgentRuntime: expected 409 archived-leader squad guard, got %d: %s", w.Code, w.Body.String())
- }
- if !strings.Contains(w.Body.String(), "active squads led by archived agents") {
- t.Fatalf("DeleteAgentRuntime: expected actionable archived-leader squad message, got body %s", w.Body.String())
- }
-
- if !squadExists(t, archivedSquad) {
- t.Errorf("archived squad must NOT have been deleted by a refused runtime delete")
- }
- if !squadExists(t, activeSquad) {
- t.Errorf("active squad must NOT have been deleted by a refused runtime delete")
- }
- if !agentExists(t, archivedLeader) {
- t.Errorf("archived leader must NOT have been deleted by a refused runtime delete")
- }
- if !runtimeExists(t, runtimeID) {
- t.Errorf("runtime must NOT have been deleted by a refused delete")
- }
-}
-
-// TestDeleteAgentRuntime_NoSquadsRegression confirms the new pre-cleanup
-// step is a safe no-op when the runtime's archived agents were never squad
-// leaders. Without this, the fix could regress the common case.
-func TestDeleteAgentRuntime_NoSquadsRegression(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
-
- runtimeID := seedIsolatedRuntime(t, "Runtime With No Squad References")
- archivedAgent := seedAgentOnRuntime(t, runtimeID, "Archived Agent No Squad", true)
-
- w := httptest.NewRecorder()
- req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
- req = withURLParam(req, "runtimeId", runtimeID)
- testHandler.DeleteAgentRuntime(w, req)
- if w.Code != http.StatusOK {
- t.Fatalf("DeleteAgentRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
- }
-
- if agentExists(t, archivedAgent) {
- t.Errorf("archived agent should have been deleted")
- }
- if runtimeExists(t, runtimeID) {
- t.Errorf("runtime should have been deleted")
- }
-}
-
-// TestDeleteAgentRuntime_StillBlockedByActiveAgents preserves the existing
-// 409 contract: even with the new squad-cleanup step in place, a runtime
-// with at least one *active* agent must still refuse to be deleted, because
-// the squad-cleanup only targets squads led by archived agents and would
-// silently delete nothing here. Without this guard, a careless reorder of
-// the handler steps could let active agents get cascaded away.
-func TestDeleteAgentRuntime_StillBlockedByActiveAgents(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
-
- runtimeID := seedIsolatedRuntime(t, "Runtime With Active Agent")
- activeAgent := seedAgentOnRuntime(t, runtimeID, "Active Agent Blocking Delete", false)
-
- 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("DeleteAgentRuntime: expected 409 active-agent guard, got %d: %s", w.Code, w.Body.String())
- }
-
- if !agentExists(t, activeAgent) {
- t.Errorf("active agent must NOT have been deleted by a refused runtime delete")
- }
- if !runtimeExists(t, runtimeID) {
- t.Errorf("runtime must NOT have been deleted by a refused delete")
- }
-}
diff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.go
index 9313ce5111..611ceee720 100644
--- a/server/internal/handler/runtime_profile.go
+++ b/server/internal/handler/runtime_profile.go
@@ -359,10 +359,28 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {
return
}
- // Confirm the profile exists in this workspace. If the profile row is
- // already gone but runtime rows still carry this workspace/profile pair,
- // treat them as orphaned instances and clean them up below.
- _, profileErr := h.Queries.GetRuntimeProfileForWorkspace(r.Context(), db.GetRuntimeProfileForWorkspaceParams{
+ // The profile-delete cascade must run the SAME teardown the runtime-delete
+ // path uses for each one: agent.runtime_id is ON DELETE RESTRICT, so an
+ // agent still pointing at one of these rows would turn a bare delete into a
+ // 500. Active agents are refused (409); everything else is unbound rather
+ // than destroyed, exactly as in unbindRuntimeForDelete.
+ // Guard: refuse while any active (non-archived) agent is bound to one of
+ // the profile's runtimes. Keep this a 409 — the profile is the thing that
+ // defines those runtimes, so the user should retire the agents or move them
+ // deliberately instead of having them silently unbound in bulk.
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to begin transaction")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ // Lock the profile before planning the cascade. Daemon registration takes
+ // 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{
ID: profileUUID,
WorkspaceID: wsUUID,
})
@@ -372,11 +390,10 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {
return
}
- // Enumerate the runtime instance rows registered against this profile in
- // this workspace. The workspace predicate is important because profile_id has
- // no FK and should never let a malformed row in another workspace be cleaned
- // up from this workspace's profile endpoint.
- runtimeIDs, err := h.Queries.ListAgentRuntimeIDsByProfile(r.Context(), db.ListAgentRuntimeIDsByProfileParams{
+ // Lock runtime rows in deterministic ID order. Their agent/task foreign-key
+ // inserts take KEY SHARE locks, preventing dependencies from appearing after
+ // the active-agent check.
+ runtimeIDs, err := qtx.ListAgentRuntimeIDsByProfile(r.Context(), db.ListAgentRuntimeIDsByProfileParams{
ProfileID: profileUUID,
WorkspaceID: wsUUID,
})
@@ -388,16 +405,14 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "runtime profile not found")
return
}
+ for _, runtimeID := range runtimeIDs {
+ if _, err := qtx.ListUserAgentsByRuntimeForUpdate(r.Context(), runtimeID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to lock profile dependencies")
+ return
+ }
+ }
- // The profile-delete cascade must run the SAME teardown the runtime-delete
- // path uses for each one: agent.runtime_id is ON DELETE RESTRICT, so an
- // archived agent still pointing at one of these rows would turn a bare
- // delete into a 500. We refuse active agents (409) and clean archived
- // agents / their archived squad+autopilot references before deleting.
- // Guard 1: refuse while any active (non-archived) agent is bound to one of
- // the profile's runtimes. Keep this a 409 — deleting would orphan live
- // agents.
- agentCount, err := h.Queries.CountAgentsByProfile(r.Context(), db.CountAgentsByProfileParams{
+ agentCount, err := qtx.CountAgentsByProfile(r.Context(), db.CountAgentsByProfileParams{
ProfileID: profileUUID,
WorkspaceID: wsUUID,
})
@@ -410,81 +425,29 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {
return
}
- // Guard 2: refuse (before any teardown) if any runtime still has an active
- // squad whose leader is already archived on it — same rule the
- // runtime-delete path enforces. Checked per runtime up front so we never
- // half-tear-down and then 409.
- for _, rid := range runtimeIDs {
- activeSquadCount, err := h.Queries.CountActiveSquadsWithArchivedLeadersByRuntime(r.Context(), rid)
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to check runtime squad dependencies")
- return
- }
- if activeSquadCount > 0 {
- writeError(w, http.StatusConflict, "cannot delete runtime profile: a runtime has active squads led by archived agents. Archive those squads or assign them a new leader first.")
- return
- }
- }
-
- tx, err := h.TxStarter.Begin(r.Context())
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to begin transaction")
- return
- }
- defer tx.Rollback(r.Context())
- qtx := h.Queries.WithTx(tx)
-
- // App-layer cascade, per runtime, mirroring DeleteAgentRuntime: pause
- // autopilots pointing at the archived agents, drop archived squads led by
- // them, then hard-delete the archived agents so the RESTRICT FK on
- // agent.runtime_id no longer blocks removing the runtime row.
+ // App-layer cascade, per runtime, mirroring DeleteAgentRuntime: unbind the
+ // remaining (archived) agents and their task history, cancel anything still
+ // in flight, and hard-delete only the system agents, so removing the runtime
+ // rows below cannot destroy an agent, a conversation or a task record.
+ var teardowns []runtimeTeardownResult
for _, rid := range runtimeIDs {
- archivedAgentIDs, err := qtx.ListArchivedAgentIDsByRuntime(r.Context(), rid)
+ teardown, err := unbindRuntimeForDelete(r.Context(), qtx, rid)
if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to enumerate archived agents")
- return
- }
- if len(archivedAgentIDs) > 0 {
- if err := qtx.PauseAutopilotsByAgentAssignees(r.Context(), archivedAgentIDs); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to pause autopilots")
+ if errors.Is(err, errRuntimeNotDrained) {
+ slog.Error("runtime profile delete aborted: tasks not drained",
+ "runtime_id", uuidToString(rid), "profile_id", uuidToString(profileUUID), "error", err)
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "a runtime of this profile still has tasks in flight; retry in a moment.",
+ "code": "runtime_delete_not_drained",
+ })
return
}
- }
- if err := qtx.DeleteSquadsByArchivedAgentsOnRuntime(r.Context(), rid); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up squads referencing archived agents")
- return
- }
- if err := qtx.DeleteAgentInvocationTargetsByArchivedRuntimeAgents(r.Context(), rid); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up agent invocation targets")
- return
- }
- // Same app-layer cleanup for channel installations: channel_* has no
- // workspace/agent FK (MUL-3515 §4), so an archived agent's bot
- // installations would otherwise survive the hard-delete as orphans and
- // keep occupying their (channel_type, app_id) routing slots, making those
- // bots un-rebindable (#4810).
- if err := qtx.DeleteChannelInstallationsByArchivedRuntimeAgents(r.Context(), rid); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up channel installations")
- return
- }
- // agent_to_label has no agent_id FK; clear the runtime's agents' label
- // links before the archived agents are hard-deleted so they don't leak
- // as orphan rows once resource labels are enabled.
- if err := qtx.DeleteAgentLabelAssignmentsByRuntime(r.Context(), rid); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up agent label assignments")
- return
- }
- // chat_session cascades from agent, and chat_draft_restore has no FK to
- // follow it (#5219). This path deletes only archived agents, so the prune
- // is scoped to them too — system agents keep their sessions here.
- if err := pruneRuntimeAgentChatDraftRestores(r.Context(), qtx, rid, false); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up chat draft restores")
- return
- }
- if err := qtx.DeleteArchivedAgentsByRuntime(r.Context(), rid); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to clean up archived agents")
+ slog.Error("runtime profile delete teardown failed",
+ "runtime_id", uuidToString(rid), "profile_id", uuidToString(profileUUID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to unbind agents")
return
}
+ teardowns = append(teardowns, teardown)
}
// Now the runtime rows have no agent references; remove them, then the
@@ -512,10 +475,16 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {
return
}
- // Tell connected clients to refetch the runtime list (instances vanished).
+ // Tell connected clients to refetch the runtime list (instances vanished),
+ // and fan out the per-runtime teardown so unbound agents and cancelled
+ // tasks reach subscribers the same way the runtime-delete path emits them.
profileID := uuidToString(profileUUID)
+ userID := uuidToString(member.UserID)
+ for _, teardown := range teardowns {
+ h.publishRuntimeTeardown(r.Context(), teardown, wsID, userID)
+ }
h.requestDaemonRuntimeProfileRefresh(wsID, profileID)
- h.publish(protocol.EventDaemonRegister, wsID, "member", uuidToString(member.UserID), map[string]any{
+ h.publish(protocol.EventDaemonRegister, wsID, "member", userID, map[string]any{
"deleted_runtime_profile_id": profileID,
})
diff --git a/server/internal/handler/runtime_profile_handler_test.go b/server/internal/handler/runtime_profile_handler_test.go
index f33d22fc93..aa680795ab 100644
--- a/server/internal/handler/runtime_profile_handler_test.go
+++ b/server/internal/handler/runtime_profile_handler_test.go
@@ -7,6 +7,8 @@ import (
"net/http/httptest"
"strings"
"testing"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
// insertRuntimeProfileFixture creates a runtime_profile in testWorkspaceID and
@@ -49,13 +51,17 @@ func insertProfileRuntimeFixture(t *testing.T, ctx context.Context, profileID, n
return runtimeID
}
-// TestDeleteRuntimeProfile_ArchivedAgentCascade is the regression guard for the
-// FK-RESTRICT 500: a profile whose only remaining agent is ARCHIVED must still
-// delete cleanly. agent.runtime_id is ON DELETE RESTRICT, so without the
-// per-runtime archived-agent teardown the DELETE on agent_runtime would raise a
-// raw FK error and the handler would 500. The cascade must hard-delete the
-// archived agent, the runtime row, and the profile.
-func TestDeleteRuntimeProfile_ArchivedAgentCascade(t *testing.T) {
+// TestDeleteRuntimeProfile_ArchivedAgentUnbindCascade is the regression guard for
+// the FK-RESTRICT 500: a profile whose only remaining agent is ARCHIVED must
+// still delete cleanly. agent.runtime_id is ON DELETE RESTRICT, so without the
+// per-runtime teardown the DELETE on agent_runtime would raise a raw FK error and
+// the handler would 500.
+//
+// Since MUL-5559 the teardown unbinds that agent instead of hard-deleting it, so
+// this test also pins what must NOT happen: the agent survives with its channel
+// installation intact. Sweeping the installation of a surviving agent would take
+// a working bot away from it — the mirror of the #4810 orphan problem.
+func TestDeleteRuntimeProfile_ArchivedAgentUnbindCascade(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
@@ -66,16 +72,15 @@ func TestDeleteRuntimeProfile_ArchivedAgentCascade(t *testing.T) {
agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Cascade Profile Archived Agent")
// Archive the agent — the active-agent guard passes, but the FK still pins
- // the runtime row until the archived cascade clears it.
+ // the runtime row until the teardown unbinds it.
if _, err := testPool.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, agentID); err != nil {
t.Fatalf("archive agent: %v", err)
}
// Give the archived agent a channel installation (+ a dependent binding).
- // channel_* has no FK to agent (MUL-3515 §4), so this DeleteRuntimeProfile
- // teardown entry point must sweep it explicitly — otherwise the bot's app_id
- // slot stays occupied after the agent is hard-deleted, and the bot can never
- // rebind anywhere (#4810). This pins that sweep on the profile-delete path.
+ // The agent is no longer hard-deleted here, so the installation must be left
+ // alone: it belongs to an agent that still exists and whose bot must keep
+ // working once it is bound to a new runtime.
const rpApp = "cli_rp_cascade"
const rpChat = "cc000000-0000-4000-8000-0000000000f7"
_, _ = testPool.Exec(ctx, `DELETE FROM channel_installation WHERE config->>'app_id' = $1`, rpApp)
@@ -122,22 +127,30 @@ VALUES ($1, $2, 'feishu', 'oc_rp', 'p2p')`, rpChat, rpInstallID); err != nil {
if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent WHERE id = $1`, agentID).Scan(&agentRows); err != nil {
t.Fatalf("count agent rows: %v", err)
}
- if agentRows != 0 {
- t.Fatalf("expected archived agent hard-deleted by cascade, found %d", agentRows)
+ if agentRows != 1 {
+ t.Fatalf("expected the archived agent to survive as an unbound agent, found %d rows", agentRows)
+ }
+ var stillBound bool
+ if err := testPool.QueryRow(ctx,
+ `SELECT runtime_id IS NOT NULL FROM agent WHERE id = $1`, agentID).Scan(&stillBound); err != nil {
+ t.Fatalf("read agent binding: %v", err)
+ }
+ if stillBound {
+ t.Fatalf("surviving agent must be unbound (runtime_id IS NULL)")
}
var instRows, bindingRows int
if err := testPool.QueryRow(ctx, `SELECT count(*) FROM channel_installation WHERE id = $1`, rpInstallID).Scan(&instRows); err != nil {
t.Fatalf("count channel installation: %v", err)
}
- if instRows != 0 {
- t.Fatalf("archived agent's channel installation not swept on runtime-profile delete: %d rows (its bot's app_id slot stays occupied, #4810)", instRows)
+ if instRows != 1 {
+ t.Fatalf("surviving agent's channel installation was swept: %d rows (its bot would stop working)", instRows)
}
if err := testPool.QueryRow(ctx, `SELECT count(*) FROM channel_chat_session_binding WHERE installation_id = $1`, rpInstallID).Scan(&bindingRows); err != nil {
t.Fatalf("count channel chat-session binding: %v", err)
}
- if bindingRows != 0 {
- t.Fatalf("channel chat-session binding not swept: %d dangling rows", bindingRows)
+ if bindingRows != 1 {
+ t.Fatalf("surviving installation's chat-session binding was swept: %d rows", bindingRows)
}
}
@@ -224,6 +237,49 @@ func TestDeleteRuntimeProfile_MissingProfileNoOrphansStillReturns404(t *testing.
}
}
+func TestRuntimeProfileDeleteLockSerializesRegistration(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ profileID := insertRuntimeProfileFixture(
+ t,
+ ctx,
+ "Profile Registration Lock",
+ "codex",
+ "profile-lock-codex",
+ )
+ params := db.LockRuntimeProfileForDeleteParams{
+ ID: parseUUID(profileID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ }
+
+ deleteTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin delete transaction: %v", err)
+ }
+ defer deleteTx.Rollback(ctx)
+ if _, err := testHandler.Queries.WithTx(deleteTx).LockRuntimeProfileForDelete(ctx, params); err != nil {
+ t.Fatalf("lock profile for delete: %v", err)
+ }
+
+ registrationTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin registration transaction: %v", err)
+ }
+ defer registrationTx.Rollback(ctx)
+ if _, err := registrationTx.Exec(ctx, `SET LOCAL lock_timeout = '50ms'`); err != nil {
+ t.Fatalf("set lock timeout: %v", err)
+ }
+ _, err = testHandler.Queries.WithTx(registrationTx).LockRuntimeProfileForRegistration(
+ ctx,
+ db.LockRuntimeProfileForRegistrationParams(params),
+ )
+ if err == nil {
+ t.Fatal("registration lock unexpectedly bypassed the profile delete lock")
+ }
+}
+
// TestCreateRuntimeProfile_ForcesWorkspaceVisibility is the regression guard
// for the visibility leak: visibility=private is not user-settable in v1
// because the read paths don't enforce it. A client that POSTs
diff --git a/server/internal/handler/runtime_test.go b/server/internal/handler/runtime_test.go
index 3cc063f321..c85b417929 100644
--- a/server/internal/handler/runtime_test.go
+++ b/server/internal/handler/runtime_test.go
@@ -38,10 +38,17 @@ func TestRuntimeHandlersRejectMalformedRuntimeID(t *testing.T) {
handle: testHandler.DeleteAgentRuntime,
},
{
+ name: "unbind-agents-and-delete",
+ method: "POST",
+ path: "/api/runtimes/not-a-uuid/unbind-agents-and-delete",
+ handle: testHandler.UnbindAgentsAndDeleteRuntime,
+ },
+ {
+ // Legacy route kept for installed clients; same handler.
name: "archive-agents-and-delete",
method: "POST",
path: "/api/runtimes/not-a-uuid/archive-agents-and-delete",
- handle: testHandler.ArchiveAgentsAndDeleteRuntime,
+ handle: testHandler.UnbindAgentsAndDeleteRuntime,
},
{
name: "models",
diff --git a/server/internal/handler/runtime_cascade_test.go b/server/internal/handler/runtime_unbind_delete_test.go
similarity index 75%
rename from server/internal/handler/runtime_cascade_test.go
rename to server/internal/handler/runtime_unbind_delete_test.go
index 292648cf5a..a8e5e43c47 100644
--- a/server/internal/handler/runtime_cascade_test.go
+++ b/server/internal/handler/runtime_unbind_delete_test.go
@@ -168,6 +168,84 @@ func TestDeleteAgentRuntime_StructuredConflict(t *testing.T) {
}
}
+func TestRuntimeDeleteLockBlocksConcurrentAgentBinding(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Runtime Delete Lock")
+
+ deleteTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin delete transaction: %v", err)
+ }
+ defer deleteTx.Rollback(ctx)
+ if _, err := testHandler.Queries.WithTx(deleteTx).LockAgentRuntime(
+ ctx,
+ parseUUID(runtimeID),
+ ); err != nil {
+ t.Fatalf("lock runtime for delete: %v", err)
+ }
+
+ bindTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin bind transaction: %v", err)
+ }
+ defer bindTx.Rollback(ctx)
+ if _, err := bindTx.Exec(ctx, `SET LOCAL lock_timeout = '50ms'`); err != nil {
+ t.Fatalf("set lock timeout: %v", err)
+ }
+ if _, err := bindTx.Exec(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, max_concurrent_tasks, owner_id
+ )
+ VALUES ($1, 'concurrent bind probe', '', 'cloud', '{}'::jsonb,
+ $2, 'workspace', 1, $3)
+ `, testWorkspaceID, runtimeID, testUserID); err == nil {
+ t.Fatal("agent bind unexpectedly bypassed the runtime delete lock")
+ }
+}
+
+func TestAutopilotAssignmentLockBlocksRuntimeTeardown(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Autopilot Assignment Lock")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Autopilot Assignment Agent")
+
+ assignmentTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin assignment transaction: %v", err)
+ }
+ defer assignmentTx.Rollback(ctx)
+ if _, err := testHandler.Queries.WithTx(assignmentTx).LockAgentForAutopilotAssignment(
+ ctx,
+ db.LockAgentForAutopilotAssignmentParams{
+ ID: parseUUID(agentID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ },
+ ); err != nil {
+ t.Fatalf("lock Agent for Autopilot assignment: %v", err)
+ }
+
+ deleteTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin delete transaction: %v", err)
+ }
+ defer deleteTx.Rollback(ctx)
+ if _, err := deleteTx.Exec(ctx, `SET LOCAL lock_timeout = '50ms'`); err != nil {
+ t.Fatalf("set lock timeout: %v", err)
+ }
+ if _, err := testHandler.Queries.WithTx(deleteTx).ListUserAgentsByRuntimeForUpdate(
+ ctx,
+ parseUUID(runtimeID),
+ ); err == nil {
+ t.Fatal("runtime teardown unexpectedly bypassed the Autopilot assignment lock")
+ }
+}
+
func TestDeleteAgentRuntime_CustomProfileInstanceRefusesDirectDelete(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
@@ -231,11 +309,11 @@ func TestDeleteAgentRuntime_OrphanedProfileAllowsDirectDelete(t *testing.T) {
}
}
-// TestArchiveAgentsAndDeleteRuntime_HappyPath exercises the cascade endpoint
+// TestUnbindAgentsAndDeleteRuntime_HappyPath exercises the confirmed endpoint
// end-to-end: with the correct expected_active_agent_ids snapshot, it must
-// archive the active agent, delete the runtime row, and respond 200 with the
+// unbind the active agent, delete the runtime row, and respond 200 with the
// counts.
-func TestArchiveAgentsAndDeleteRuntime_HappyPath(t *testing.T) {
+func TestUnbindAgentsAndDeleteRuntime_HappyPath(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
@@ -245,10 +323,10 @@ func TestArchiveAgentsAndDeleteRuntime_HappyPath(t *testing.T) {
agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Cascade Happy Agent")
w := httptest.NewRecorder()
- req := newRequest("POST", "/api/runtimes/"+runtimeID+"/archive-agents-and-delete",
+ req := newRequest("POST", "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete",
map[string]any{"expected_active_agent_ids": []string{agentID}})
req = withURLParam(req, "runtimeId", runtimeID)
- testHandler.ArchiveAgentsAndDeleteRuntime(w, req)
+ testHandler.UnbindAgentsAndDeleteRuntime(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
@@ -261,18 +339,51 @@ func TestArchiveAgentsAndDeleteRuntime_HappyPath(t *testing.T) {
if rtRows != 0 {
t.Fatalf("expected runtime row to be deleted, found %d", rtRows)
}
- // Agent row must be gone too — DeleteArchivedAgentsByRuntime hard-deletes
- // the archived rows so the agent.runtime_id FK no longer pins the runtime.
- var agentRows int
- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent WHERE id = $1`, agentID).Scan(&agentRows); err != nil {
+ // The agent must SURVIVE, unbound and un-archived. This is the whole point
+ // of MUL-5559: the old flow archived it and then hard-deleted the row, taking
+ // its chat sessions with it, while the dialog promised an archive.
+ var (
+ agentRows int
+ hasRuntime bool
+ archived bool
+ )
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM agent WHERE id = $1`, agentID).Scan(&agentRows); err != nil {
t.Fatalf("count agent rows: %v", err)
}
- if agentRows != 0 {
- t.Fatalf("expected archived agent to be hard-deleted with runtime, found %d", agentRows)
+ if agentRows != 1 {
+ t.Fatalf("expected the agent to survive its runtime, found %d rows", agentRows)
+ }
+ if err := testPool.QueryRow(ctx,
+ `SELECT runtime_id IS NOT NULL, archived_at IS NOT NULL FROM agent WHERE id = $1`,
+ agentID).Scan(&hasRuntime, &archived); err != nil {
+ t.Fatalf("read agent binding: %v", err)
+ }
+ if hasRuntime {
+ t.Fatalf("expected the surviving agent to be unbound (runtime_id IS NULL)")
+ }
+ if archived {
+ t.Fatalf("unbinding must not archive the agent: unbound and archived are orthogonal")
+ }
+
+ var body struct {
+ AgentsUnbound int `json:"agents_unbound"`
+ AgentsArchived int `json:"agents_archived"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body.AgentsUnbound != 1 {
+ t.Fatalf("agents_unbound = %d, want 1", body.AgentsUnbound)
+ }
+ // Deprecated mirror kept for installed clients built against the
+ // archive-and-delete contract.
+ if body.AgentsArchived != 1 {
+ t.Fatalf("agents_archived mirror = %d, want 1", body.AgentsArchived)
}
}
-func TestArchiveAgentsAndDeleteRuntime_CustomProfileInstanceRefusesDirectDelete(t *testing.T) {
+func TestUnbindAgentsAndDeleteRuntime_CustomProfileInstanceRefusesDirectDelete(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
@@ -281,10 +392,10 @@ func TestArchiveAgentsAndDeleteRuntime_CustomProfileInstanceRefusesDirectDelete(
runtimeID, _ := createProfileBackedRuntime(t, ctx, "Custom Instance Cascade Guard")
w := httptest.NewRecorder()
- req := newRequest("POST", "/api/runtimes/"+runtimeID+"/archive-agents-and-delete",
+ req := newRequest("POST", "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete",
map[string]any{"expected_active_agent_ids": []string{}})
req = withURLParam(req, "runtimeId", runtimeID)
- testHandler.ArchiveAgentsAndDeleteRuntime(w, req)
+ testHandler.UnbindAgentsAndDeleteRuntime(w, req)
if w.Code != http.StatusConflict {
t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
}
@@ -308,7 +419,7 @@ func TestArchiveAgentsAndDeleteRuntime_CustomProfileInstanceRefusesDirectDelete(
}
}
-func TestArchiveAgentsAndDeleteRuntime_OrphanedProfileAllowsCascade(t *testing.T) {
+func TestUnbindAgentsAndDeleteRuntime_OrphanedProfileAllowsCascade(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
@@ -320,10 +431,10 @@ func TestArchiveAgentsAndDeleteRuntime_OrphanedProfileAllowsCascade(t *testing.T
}
w := httptest.NewRecorder()
- req := newRequest("POST", "/api/runtimes/"+runtimeID+"/archive-agents-and-delete",
+ req := newRequest("POST", "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete",
map[string]any{"expected_active_agent_ids": []string{}})
req = withURLParam(req, "runtimeId", runtimeID)
- testHandler.ArchiveAgentsAndDeleteRuntime(w, req)
+ testHandler.UnbindAgentsAndDeleteRuntime(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
@@ -337,12 +448,12 @@ func TestArchiveAgentsAndDeleteRuntime_OrphanedProfileAllowsCascade(t *testing.T
}
}
-// TestArchiveAgentsAndDeleteRuntime_PlanChanged proves the dialog-confirm
+// TestUnbindAgentsAndDeleteRuntime_PlanChanged proves the dialog-confirm
// race guard: if the user's snapshot of active agents drifts from the live
// set (somebody added or archived an agent while the dialog was open), the
// cascade endpoint must refuse with 409 + runtime_delete_plan_changed and
// surface the new live snapshot so the dialog can re-prompt.
-func TestArchiveAgentsAndDeleteRuntime_PlanChanged(t *testing.T) {
+func TestUnbindAgentsAndDeleteRuntime_PlanChanged(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
@@ -354,10 +465,10 @@ func TestArchiveAgentsAndDeleteRuntime_PlanChanged(t *testing.T) {
// User confirmed only agent1 — but the live set is {agent1, agent2}.
w := httptest.NewRecorder()
- req := newRequest("POST", "/api/runtimes/"+runtimeID+"/archive-agents-and-delete",
+ req := newRequest("POST", "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete",
map[string]any{"expected_active_agent_ids": []string{agent1}})
req = withURLParam(req, "runtimeId", runtimeID)
- testHandler.ArchiveAgentsAndDeleteRuntime(w, req)
+ testHandler.UnbindAgentsAndDeleteRuntime(w, req)
if w.Code != http.StatusConflict {
t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
}
diff --git a/server/internal/handler/runtime_unbind_preserves_data_test.go b/server/internal/handler/runtime_unbind_preserves_data_test.go
new file mode 100644
index 0000000000..3b1ad1649a
--- /dev/null
+++ b/server/internal/handler/runtime_unbind_preserves_data_test.go
@@ -0,0 +1,532 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// These are the regressions for MUL-5559. Deleting a runtime used to archive its
+// agents and then hard-delete the rows, so the agents, their conversations and
+// their task history all disappeared — while the confirmation dialog said
+// "archive". Each test below pins one thing that must now survive, plus the two
+// invariants that keep the new flow safe.
+
+// TestUnbindAgentsAndDeleteRuntime_KeepsChatHistory: the agent's chat sessions
+// and messages cascade from the agent row, so hard-deleting it destroyed every
+// conversation with it. Unbinding must leave them readable.
+func TestUnbindAgentsAndDeleteRuntime_KeepsChatHistory(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Unbind Chat Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Unbind Chat Agent")
+
+ var sessionID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, runtime_id, title)
+ VALUES ($1, $2, $3, $4, 'unbind chat history')
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&sessionID); err != nil {
+ t.Fatalf("insert chat session: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content)
+ VALUES ($1, 'user', 'does this survive the machine being retired?')
+ `, sessionID); err != nil {
+ t.Fatalf("insert chat message: %v", err)
+ }
+
+ unbindRuntime(t, ctx, runtimeID, agentID)
+
+ var sessions, messages int
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM chat_session WHERE id = $1`, sessionID).Scan(&sessions); err != nil {
+ t.Fatalf("count chat sessions: %v", err)
+ }
+ if sessions != 1 {
+ t.Fatalf("chat session rows = %d, want 1 (the conversation must survive)", sessions)
+ }
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM chat_message WHERE chat_session_id = $1`, sessionID).Scan(&messages); err != nil {
+ t.Fatalf("count chat messages: %v", err)
+ }
+ if messages != 1 {
+ t.Fatalf("chat message rows = %d, want 1", messages)
+ }
+ // chat_session.runtime_id is ON DELETE SET NULL, so the session detaches from
+ // the deleted runtime and a rebind starts a fresh provider session.
+ var sessionBound bool
+ if err := testPool.QueryRow(ctx,
+ `SELECT runtime_id IS NOT NULL FROM chat_session WHERE id = $1`, sessionID).Scan(&sessionBound); err != nil {
+ t.Fatalf("read chat session runtime: %v", err)
+ }
+ if sessionBound {
+ t.Fatalf("chat session must no longer point at the deleted runtime")
+ }
+}
+
+// TestUnbindAgentsAndDeleteRuntime_KeepsTaskHistory is the second half of the
+// data loss, and the one that needs agent_task_queue.runtime_id to be nullable:
+// that column is NOT NULL with an ON DELETE CASCADE FK, and task_message /
+// task_usage cascade from the task in turn. Unbinding only the agent would leave
+// it alive with no record of anything it ever did.
+func TestUnbindAgentsAndDeleteRuntime_KeepsTaskHistory(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Unbind Task History Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Unbind Task History Agent")
+
+ doneTask := insertFixtureTask(t, ctx, runtimeID, agentID, "completed", true)
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_message (task_id, seq, type, content)
+ VALUES ($1, 1, 'assistant', 'transcript that must not vanish')
+ `, doneTask); err != nil {
+ t.Fatalf("insert task message: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens)
+ VALUES ($1, 'anthropic', 'claude-test', 10, 20)
+ `, doneTask); err != nil {
+ t.Fatalf("insert task usage: %v", err)
+ }
+ runningTask := insertFixtureTask(t, ctx, runtimeID, agentID, "running", false)
+
+ unbindRuntime(t, ctx, runtimeID, agentID)
+
+ var (
+ taskRows int
+ taskBound bool
+ msgRows int
+ usageRows int
+ activeState string
+ )
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM agent_task_queue WHERE id = $1`, doneTask).Scan(&taskRows); err != nil {
+ t.Fatalf("count task rows: %v", err)
+ }
+ if taskRows != 1 {
+ t.Fatalf("completed task rows = %d, want 1 (history must survive)", taskRows)
+ }
+ if err := testPool.QueryRow(ctx,
+ `SELECT runtime_id IS NOT NULL FROM agent_task_queue WHERE id = $1`, doneTask).Scan(&taskBound); err != nil {
+ t.Fatalf("read task binding: %v", err)
+ }
+ if taskBound {
+ t.Fatalf("history task must be detached from the deleted runtime")
+ }
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM task_message WHERE task_id = $1`, doneTask).Scan(&msgRows); err != nil {
+ t.Fatalf("count task messages: %v", err)
+ }
+ if msgRows != 1 {
+ t.Fatalf("task_message rows = %d, want 1", msgRows)
+ }
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM task_usage WHERE task_id = $1`, doneTask).Scan(&usageRows); err != nil {
+ t.Fatalf("count task usage: %v", err)
+ }
+ if usageRows != 1 {
+ t.Fatalf("task_usage rows = %d, want 1", usageRows)
+ }
+
+ // The in-flight task is cancelled rather than deleted, so the record of it
+ // having been interrupted survives too.
+ if err := testPool.QueryRow(ctx,
+ `SELECT status FROM agent_task_queue WHERE id = $1`, runningTask).Scan(&activeState); err != nil {
+ t.Fatalf("read running task status: %v", err)
+ }
+ if activeState != "cancelled" {
+ t.Fatalf("in-flight task status = %q, want cancelled", activeState)
+ }
+}
+
+// TestUnbindAgentsAndDeleteRuntime_CancelsDeferredTasks covers the status the
+// cancel query used to miss. 'deferred' arrived with migration 128 and was never
+// added to CancelAgentTasksByRuntimeOrAgent; it went unnoticed only because the
+// runtime delete cascaded those rows away. With runtime_id nullable and the
+// active-requires-runtime CHECK in place, a missed status would abort the whole
+// delete — so this test is what keeps the runtime deletable.
+func TestUnbindAgentsAndDeleteRuntime_CancelsDeferredTasks(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Unbind Deferred Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Unbind Deferred Agent")
+ deferredTask := insertFixtureTask(t, ctx, runtimeID, agentID, "deferred", false)
+
+ unbindRuntime(t, ctx, runtimeID, agentID)
+
+ var status string
+ if err := testPool.QueryRow(ctx,
+ `SELECT status FROM agent_task_queue WHERE id = $1`, deferredTask).Scan(&status); err != nil {
+ t.Fatalf("read deferred task status: %v", err)
+ }
+ if status != "cancelled" {
+ t.Fatalf("deferred task status = %q, want cancelled", status)
+ }
+}
+
+func TestCountUndrainedTasksByRuntimeOrAgent_IncludesCrossRuntimeTask(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Drain Assertion Agent Runtime")
+ otherRuntimeID := createCascadeFixtureRuntime(t, ctx, "Drain Assertion Task Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Drain Assertion Agent")
+ _ = insertFixtureTask(t, ctx, otherRuntimeID, agentID, "queued", false)
+
+ count, err := testHandler.Queries.CountUndrainedTasksByRuntimeOrAgent(
+ ctx,
+ db.CountUndrainedTasksByRuntimeOrAgentParams{
+ RuntimeIds: []pgtype.UUID{parseUUID(runtimeID)},
+ AgentIds: []pgtype.UUID{parseUUID(agentID)},
+ },
+ )
+ if err != nil {
+ t.Fatalf("count undrained tasks: %v", err)
+ }
+ if count != 1 {
+ t.Fatalf("undrained count = %d, want 1 for task pinned to another runtime", count)
+ }
+}
+
+func TestDeleteStaleOfflineRuntimes_UnboundAgentDoesNotDisableGC(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ boundRuntimeID := createCascadeFixtureRuntime(t, ctx, "GC Unbound Agent Source")
+ agentID := createCascadeFixtureAgent(t, ctx, boundRuntimeID, "GC Unbound Agent")
+ if _, err := testPool.Exec(ctx, `UPDATE agent SET runtime_id = NULL WHERE id = $1`, agentID); err != nil {
+ t.Fatalf("unbind GC fixture agent: %v", err)
+ }
+
+ var staleRuntimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, name, runtime_mode, provider, status,
+ device_info, metadata, owner_id, last_seen_at
+ )
+ VALUES ($1, 'GC stale candidate', 'cloud', 'gc-regression', 'offline',
+ 'GC stale candidate', '{}'::jsonb, $2, now() - interval '200 years')
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&staleRuntimeID); err != nil {
+ t.Fatalf("seed stale runtime: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, staleRuntimeID)
+ })
+
+ deleted, err := testHandler.Queries.DeleteStaleOfflineRuntimes(ctx, 3_000_000_000)
+ if err != nil {
+ t.Fatalf("delete stale runtimes: %v", err)
+ }
+ found := false
+ for _, row := range deleted {
+ if uuidToString(row.ID) == staleRuntimeID {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatal("unbound agent made stale-runtime GC skip an unrelated candidate")
+ }
+}
+
+// TestUnbindAgentsAndDeleteRuntime_KeepsAutopilotConfig pauses an automation
+// whose assignee cannot run after teardown. Leaving it active would append an
+// identical skipped run every schedule tick forever. Its assignee and config
+// remain intact, and pause_reason tells the user how to recover.
+func TestUnbindAgentsAndDeleteRuntime_KeepsAutopilotConfig(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Unbind Autopilot Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Unbind Autopilot Agent")
+
+ var autopilotID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO autopilot (
+ workspace_id, title, description, assignee_type, assignee_id,
+ created_by_type, created_by_id, status, execution_mode
+ )
+ VALUES ($1, 'unbind autopilot', 'do the thing', 'agent', $2, 'member', $3, 'active', 'run_only')
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID).Scan(&autopilotID); err != nil {
+ t.Fatalf("insert autopilot: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID)
+ })
+
+ unbindRuntime(t, ctx, runtimeID, agentID)
+
+ var status, pauseReason string
+ var assigneeRows int
+ if err := testPool.QueryRow(ctx,
+ `SELECT status, pause_reason FROM autopilot WHERE id = $1`, autopilotID).Scan(&status, &pauseReason); err != nil {
+ t.Fatalf("read autopilot status: %v", err)
+ }
+ if status != "paused" {
+ t.Fatalf("autopilot status = %q, want paused", status)
+ }
+ if pauseReason != string(ReasonAgentRuntimeRequired) {
+ t.Fatalf("autopilot pause_reason = %q, want agent_runtime_required", pauseReason)
+ }
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM autopilot WHERE id = $1 AND assignee_id = $2`,
+ autopilotID, agentID).Scan(&assigneeRows); err != nil {
+ t.Fatalf("read autopilot assignee: %v", err)
+ }
+ if assigneeRows != 1 {
+ t.Fatalf("autopilot must still point at the surviving agent")
+ }
+}
+
+func TestUnbindAgentsAndDeleteRuntime_RedactsAgentBroadcast(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Unbind Broadcast Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Unbind Broadcast Agent")
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent
+ SET mcp_config = '{"servers":{"private":{"token":"secret"}}}'::jsonb,
+ composio_toolkit_allowlist = ARRAY['github']::text[]
+ WHERE id = $1
+ `, agentID); err != nil {
+ t.Fatalf("seed secret-bearing agent fields: %v", err)
+ }
+
+ var broadcast *AgentResponse
+ testHandler.Bus.Subscribe(protocol.EventAgentStatus, func(e events.Event) {
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ return
+ }
+ agent, ok := payload["agent"].(AgentResponse)
+ if !ok || agent.ID != agentID {
+ return
+ }
+ broadcast = &agent
+ })
+
+ unbindRuntime(t, ctx, runtimeID, agentID)
+
+ if broadcast == nil {
+ t.Fatal("expected agent:status broadcast for unbound agent")
+ }
+ if broadcast.McpConfig != nil {
+ t.Fatalf("broadcast leaked mcp_config: %s", string(broadcast.McpConfig))
+ }
+ if !broadcast.McpConfigRedacted {
+ t.Fatal("broadcast must mark mcp_config as redacted")
+ }
+ if broadcast.ComposioToolkitAllowlist != nil {
+ t.Fatalf("broadcast leaked Composio allowlist: %v", broadcast.ComposioToolkitAllowlist)
+ }
+ if !broadcast.ComposioToolkitAllowlistRedacted {
+ t.Fatal("broadcast must mark Composio allowlist as redacted")
+ }
+}
+
+// TestUnbindAgentsAndDeleteRuntime_DeletesSystemAgents: system agents are
+// invisible execution infrastructure (the Agent Builder, for example) with no UI
+// to rebind them, so leaving them unbound would strand rows no one can repair.
+// They are still hard-deleted with their runtime.
+func TestUnbindAgentsAndDeleteRuntime_DeletesSystemAgents(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Unbind System Runtime")
+ userAgent := createCascadeFixtureAgent(t, ctx, runtimeID, "Unbind System Runtime User Agent")
+ systemAgent := createCascadeFixtureAgent(t, ctx, runtimeID, "Unbind System Runtime System Agent")
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent SET kind = 'system', system_key = 'unbind_probe' WHERE id = $1`,
+ systemAgent); err != nil {
+ t.Fatalf("make agent a system agent: %v", err)
+ }
+
+ // Only the user agent is part of the confirmed plan: system agents never
+ // appear in the dialog (ListActiveAgentsByRuntimeForUpdate filters to
+ // kind='user').
+ unbindRuntime(t, ctx, runtimeID, userAgent)
+
+ var systemRows, userRows int
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM agent WHERE id = $1`, systemAgent).Scan(&systemRows); err != nil {
+ t.Fatalf("count system agent: %v", err)
+ }
+ if systemRows != 0 {
+ t.Fatalf("system agent rows = %d, want 0 (still deleted with its runtime)", systemRows)
+ }
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM agent WHERE id = $1`, userAgent).Scan(&userRows); err != nil {
+ t.Fatalf("count user agent: %v", err)
+ }
+ if userRows != 1 {
+ t.Fatalf("user agent rows = %d, want 1", userRows)
+ }
+}
+
+// TestUnbindAgentsAndDeleteRuntime_LegacyRouteBehavesTheSame: installed clients
+// still POST to /archive-agents-and-delete with an active-only expected set. That
+// request must keep working — a changed contract here would 409 forever and leave
+// the runtime undeletable — and it must perform the unbind, not the old archive.
+func TestUnbindAgentsAndDeleteRuntime_LegacyRouteBehavesTheSame(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Legacy Route Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Legacy Route Agent")
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/runtimes/"+runtimeID+"/archive-agents-and-delete",
+ map[string]any{"expected_active_agent_ids": []string{agentID}})
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.UnbindAgentsAndDeleteRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("legacy route: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var body struct {
+ AgentsUnbound int `json:"agents_unbound"`
+ AgentsArchived int `json:"agents_archived"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body.AgentsUnbound != 1 || body.AgentsArchived != 1 {
+ t.Fatalf("counts = unbound %d / archived-mirror %d, want 1/1", body.AgentsUnbound, body.AgentsArchived)
+ }
+
+ var archived, bound bool
+ if err := testPool.QueryRow(ctx,
+ `SELECT archived_at IS NOT NULL, runtime_id IS NOT NULL FROM agent WHERE id = $1`,
+ agentID).Scan(&archived, &bound); err != nil {
+ t.Fatalf("read agent state: %v", err)
+ }
+ if archived {
+ t.Fatalf("legacy route must unbind, not archive")
+ }
+ if bound {
+ t.Fatalf("legacy route must leave the agent unbound")
+ }
+}
+
+// TestAgentResponse_RuntimeBoundSignal pins the wire contract an unbound agent is
+// served with: runtime_id stays a string (empty), so installed clients keep
+// parsing, and runtime_bound is the explicit signal the UI branches on.
+func TestAgentResponse_RuntimeBoundSignal(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Runtime Bound Signal Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Runtime Bound Signal Agent")
+
+ bound := getAgentResponse(t, ctx, agentID)
+ if !bound.RuntimeBound {
+ t.Fatalf("bound agent: runtime_bound = false, want true")
+ }
+ if bound.RuntimeID == "" {
+ t.Fatalf("bound agent: runtime_id must be set")
+ }
+
+ unbindRuntime(t, ctx, runtimeID, agentID)
+
+ unboundResp := getAgentResponse(t, ctx, agentID)
+ if unboundResp.RuntimeBound {
+ t.Fatalf("unbound agent: runtime_bound = true, want false")
+ }
+ if unboundResp.RuntimeID != "" {
+ t.Fatalf("unbound agent: runtime_id = %q, want empty string", unboundResp.RuntimeID)
+ }
+ if unboundResp.ArchivedAt != nil {
+ t.Fatalf("unbound agent must not be reported as archived")
+ }
+}
+
+// unbindRuntime drives the confirmed delete endpoint for one runtime whose
+// confirmed active set is exactly the given agents, and fails the test if the
+// runtime does not go away.
+func unbindRuntime(t *testing.T, ctx context.Context, runtimeID string, activeAgentIDs ...string) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete",
+ map[string]any{"expected_active_agent_ids": activeAgentIDs})
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.UnbindAgentsAndDeleteRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UnbindAgentsAndDeleteRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var rtRows int
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&rtRows); err != nil {
+ t.Fatalf("count runtime rows: %v", err)
+ }
+ if rtRows != 0 {
+ t.Fatalf("runtime row survived the delete")
+ }
+}
+
+// insertFixtureTask seeds one agent_task_queue row in the given state. Terminal
+// rows get completed_at so they satisfy agent_task_queue_active_requires_runtime
+// once the runtime is detached.
+func insertFixtureTask(t *testing.T, ctx context.Context, runtimeID, agentID, status string, terminal bool) string {
+ t.Helper()
+ var taskID string
+ completedAt := "NULL"
+ if terminal {
+ completedAt = "now()"
+ }
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, context, completed_at)
+ VALUES ($1, $2, $3, '{"fixture":true}'::jsonb, `+completedAt+`)
+ RETURNING id
+ `, agentID, runtimeID, status).Scan(&taskID); err != nil {
+ t.Fatalf("insert fixture task (%s): %v", status, err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ })
+ return taskID
+}
+
+// getAgentResponse reads one agent through the handler's own serializer so the
+// test asserts the wire shape, not the row.
+func getAgentResponse(t *testing.T, ctx context.Context, agentID string) AgentResponse {
+ t.Helper()
+ agent, err := testHandler.Queries.GetAgent(ctx, parseUUID(agentID))
+ if err != nil {
+ t.Fatalf("load agent %s: %v", agentID, err)
+ }
+ return testHandler.agentToResponse(agent)
+}
diff --git a/server/internal/handler/runtime_unbind_squad_test.go b/server/internal/handler/runtime_unbind_squad_test.go
new file mode 100644
index 0000000000..7d282494e2
--- /dev/null
+++ b/server/internal/handler/runtime_unbind_squad_test.go
@@ -0,0 +1,397 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+// These tests cover what a runtime teardown does to squads whose leader lives
+// on that runtime.
+//
+// The problem they used to work around is gone. Because a runtime delete
+// hard-deleted its archived agents, and squad.leader_id REFERENCES agent(id) ON
+// DELETE RESTRICT, a squad led by such an agent blocked the delete with a 500 —
+// so the handler deleted archived squads first and refused (409) whenever an
+// ACTIVE squad still pointed at an archived leader, leaving the runtime
+// undeletable until the user archived the squad or replaced its leader.
+//
+// Since MUL-5559 the leader is not deleted at all: it is unbound and keeps
+// everything, so the RESTRICT FK is never challenged. Both the squad delete and
+// the 409 guard are therefore removed, and these tests pin the new contract —
+// squads and their leaders survive, and the runtime deletes cleanly.
+
+// seedIsolatedRuntime creates a fresh runtime in the shared test workspace
+// (so the seeded test user is owner/admin and passes canEditRuntime), and
+// returns its UUID. The runtime is auto-cleaned via t.Cleanup; tests that
+// successfully drive DeleteAgentRuntime through to the end will have already
+// deleted it, in which case the cleanup is a no-op.
+func seedIsolatedRuntime(t *testing.T, name string) string {
+ t.Helper()
+ ctx := context.Background()
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at
+ )
+ VALUES ($1, NULL, $2, 'cloud', 'isolated_test', 'online', 'isolated test runtime', '{}'::jsonb, now())
+ RETURNING id
+ `, testWorkspaceID, name).Scan(&runtimeID); err != nil {
+ t.Fatalf("seed runtime %q: %v", name, err)
+ }
+ t.Cleanup(func() {
+ // Best-effort cascading cleanup; ignore errors because the handler
+ // may have already removed the row in the happy path.
+ testPool.Exec(ctx, `DELETE FROM agent WHERE runtime_id = $1`, runtimeID)
+ testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)
+ })
+ return runtimeID
+}
+
+// seedAgentOnRuntime creates an agent on the given runtime. If archived is
+// true the row is created with archived_at = now().
+func seedAgentOnRuntime(t *testing.T, runtimeID, name string, archived bool) string {
+ t.Helper()
+ ctx := context.Background()
+ 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
+ )
+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'workspace', 1, $4)
+ RETURNING id
+ `, testWorkspaceID, name, runtimeID, testUserID).Scan(&agentID); err != nil {
+ t.Fatalf("seed agent %q: %v", name, err)
+ }
+ if archived {
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent SET archived_at = now(), archived_by = $1 WHERE id = $2`,
+ testUserID, agentID,
+ ); err != nil {
+ t.Fatalf("archive agent %q: %v", name, err)
+ }
+ }
+ t.Cleanup(func() {
+ // Squad rows referencing this agent could block a plain DELETE; nuke
+ // them first. Tests that complete through the handler will already
+ // have done this.
+ testPool.Exec(ctx, `DELETE FROM squad WHERE leader_id = $1`, agentID)
+ testPool.Exec(ctx, `DELETE FROM agent WHERE id = $1`, agentID)
+ })
+ return agentID
+}
+
+// seedSquad creates a squad with the given leader. If archived is true the
+// row is created with archived_at = now() (the case the user originally hit
+// — `multica squad list` filters out archived squads, hiding the FK
+// blocker).
+func seedSquad(t *testing.T, leaderID, name string, archived bool) string {
+ t.Helper()
+ ctx := context.Background()
+ var squadID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)
+ VALUES ($1, $2, '', $3, $4)
+ RETURNING id
+ `, testWorkspaceID, name, leaderID, testUserID).Scan(&squadID); err != nil {
+ t.Fatalf("seed squad %q: %v", name, err)
+ }
+ if archived {
+ if _, err := testPool.Exec(ctx,
+ `UPDATE squad SET archived_at = now(), archived_by = $1 WHERE id = $2`,
+ testUserID, squadID,
+ ); err != nil {
+ t.Fatalf("archive squad %q: %v", name, err)
+ }
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM squad WHERE id = $1`, squadID)
+ })
+ return squadID
+}
+
+func squadExists(t *testing.T, squadID string) bool {
+ t.Helper()
+ var count int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM squad WHERE id = $1`, squadID,
+ ).Scan(&count); err != nil {
+ t.Fatalf("count squad %s: %v", squadID, err)
+ }
+ return count == 1
+}
+
+func agentExists(t *testing.T, agentID string) bool {
+ t.Helper()
+ var count int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM agent WHERE id = $1`, agentID,
+ ).Scan(&count); err != nil {
+ t.Fatalf("count agent %s: %v", agentID, err)
+ }
+ return count == 1
+}
+
+func runtimeExists(t *testing.T, runtimeID string) bool {
+ t.Helper()
+ var count int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID,
+ ).Scan(&count); err != nil {
+ t.Fatalf("count runtime %s: %v", runtimeID, err)
+ }
+ return count == 1
+}
+
+// TestDeleteAgentRuntime_KeepsSquadsLedByUnboundAgents is the end-to-end
+// regression: a runtime whose only agents are archived squad leaders must delete
+// cleanly, and neither the squads nor the leaders may be destroyed.
+//
+// The archived squad in this fixture is the case originally reported: it is
+// invisible to `multica squad list`, so a user could not see what was blocking
+// the delete — and the old fix resolved that by deleting the squad.
+func TestDeleteAgentRuntime_KeepsSquadsLedByUnboundAgents(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ runtimeID := seedIsolatedRuntime(t, "Runtime With Archived Squad Leader")
+ archivedLeader := seedAgentOnRuntime(t, runtimeID, "Archived Squad Leader Agent", true)
+ archivedSquad := seedSquad(t, archivedLeader, "Archived Squad For Runtime Delete", true)
+ activeSquad := seedSquad(t, archivedLeader, "Active Squad For Runtime Delete", false)
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.DeleteAgentRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("DeleteAgentRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ if !squadExists(t, archivedSquad) {
+ t.Errorf("archived squad must survive: its leader is unbound, not deleted")
+ }
+ if !squadExists(t, activeSquad) {
+ t.Errorf("active squad must survive: its leader is unbound, not deleted")
+ }
+ if !agentExists(t, archivedLeader) {
+ t.Errorf("archived leader must survive its runtime as an unbound agent")
+ }
+ if runtimeExists(t, runtimeID) {
+ t.Errorf("runtime should have been deleted")
+ }
+ if bound := agentRuntimeBound(t, archivedLeader); bound {
+ t.Errorf("surviving leader must be unbound (runtime_id IS NULL)")
+ }
+}
+
+// TestDeleteAgentRuntime_ActiveSquadWithArchivedLeaderNoLongerConflicts is the
+// direct inversion of the old guard: this used to be a 409 telling the user to
+// archive the squad or assign a new leader. Nothing needs to be given up now.
+func TestDeleteAgentRuntime_ActiveSquadWithArchivedLeaderNoLongerConflicts(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ runtimeID := seedIsolatedRuntime(t, "Runtime With Active Squad And Archived Leader")
+ archivedLeader := seedAgentOnRuntime(t, runtimeID, "Archived Leader Formerly Blocking Delete", true)
+ activeSquad := seedSquad(t, archivedLeader, "Active Squad Formerly Blocking Delete", false)
+ var autopilotID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO autopilot (
+ workspace_id, title, assignee_type, assignee_id,
+ created_by_type, created_by_id, status, execution_mode
+ )
+ VALUES ($1, 'squad runtime pause', 'squad', $2, 'member', $3, 'active', 'run_only')
+ RETURNING id
+ `, testWorkspaceID, activeSquad, testUserID).Scan(&autopilotID); err != nil {
+ t.Fatalf("seed squad autopilot: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID)
+ })
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.DeleteAgentRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("DeleteAgentRuntime: expected 200 (guard removed), got %d: %s", w.Code, w.Body.String())
+ }
+
+ if !squadExists(t, activeSquad) {
+ t.Errorf("active squad must survive the runtime delete")
+ }
+ if !agentExists(t, archivedLeader) {
+ t.Errorf("archived leader must survive the runtime delete")
+ }
+ if runtimeExists(t, runtimeID) {
+ t.Errorf("runtime should have been deleted")
+ }
+ var status, pauseReason string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT status, pause_reason FROM autopilot WHERE id = $1`, autopilotID,
+ ).Scan(&status, &pauseReason); err != nil {
+ t.Fatalf("read squad autopilot: %v", err)
+ }
+ if status != "paused" || pauseReason != string(ReasonAgentRuntimeRequired) {
+ t.Fatalf("squad autopilot = (%q, %q), want (paused, agent_runtime_required)", status, pauseReason)
+ }
+}
+
+// TestDeleteAgentRuntime_NoSquadsRegression confirms the common case: an
+// archived agent with no squad references survives as an unbound agent and the
+// runtime is gone.
+func TestDeleteAgentRuntime_NoSquadsRegression(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ runtimeID := seedIsolatedRuntime(t, "Runtime With No Squad References")
+ archivedAgent := seedAgentOnRuntime(t, runtimeID, "Archived Agent No Squad", true)
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.DeleteAgentRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("DeleteAgentRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ if !agentExists(t, archivedAgent) {
+ t.Errorf("archived agent must survive its runtime as an unbound agent")
+ }
+ if agentRuntimeBound(t, archivedAgent) {
+ t.Errorf("surviving agent must be unbound (runtime_id IS NULL)")
+ }
+ if runtimeExists(t, runtimeID) {
+ t.Errorf("runtime should have been deleted")
+ }
+}
+
+func TestUpdateSquad_UnboundLeaderPausesOnlySquadAutopilots(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ boundRuntimeID := seedIsolatedRuntime(t, "Bound Squad Leader Runtime")
+ boundLeaderID := seedAgentOnRuntime(t, boundRuntimeID, "Bound Squad Leader", false)
+ squadID := seedSquad(t, boundLeaderID, "Squad Leader Rotation", false)
+
+ unboundRuntimeID := seedIsolatedRuntime(t, "Unbound Squad Leader Runtime")
+ unboundLeaderID := seedAgentOnRuntime(t, unboundRuntimeID, "Unbound Squad Leader", false)
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent SET runtime_id = NULL WHERE id = $1`,
+ unboundLeaderID,
+ ); err != nil {
+ t.Fatalf("unbind proposed leader: %v", err)
+ }
+
+ var squadAutopilotID, directAutopilotID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO autopilot (
+ workspace_id, title, assignee_type, assignee_id,
+ created_by_type, created_by_id, status, execution_mode
+ )
+ VALUES ($1, 'squad leader rotation pause', 'squad', $2,
+ 'member', $3, 'active', 'run_only')
+ RETURNING id
+ `, testWorkspaceID, squadID, testUserID).Scan(&squadAutopilotID); err != nil {
+ t.Fatalf("seed squad autopilot: %v", err)
+ }
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO autopilot (
+ workspace_id, title, assignee_type, assignee_id,
+ created_by_type, created_by_id, status, execution_mode
+ )
+ VALUES ($1, 'unrelated direct autopilot', 'agent', $2,
+ 'member', $3, 'active', 'run_only')
+ RETURNING id
+ `, testWorkspaceID, unboundLeaderID, testUserID).Scan(&directAutopilotID); err != nil {
+ t.Fatalf("seed direct autopilot: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM autopilot WHERE id = ANY($1::uuid[])`,
+ []string{squadAutopilotID, directAutopilotID},
+ )
+ })
+
+ w := httptest.NewRecorder()
+ testHandler.UpdateSquad(w, squadScopeReq(
+ "",
+ http.MethodPatch,
+ "/api/squads/"+squadID,
+ map[string]any{"leader_id": unboundLeaderID},
+ map[string]string{"id": squadID},
+ ))
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateSquad: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var squadStatus, pauseReason, directStatus string
+ if err := testPool.QueryRow(ctx,
+ `SELECT status, pause_reason FROM autopilot WHERE id = $1`,
+ squadAutopilotID,
+ ).Scan(&squadStatus, &pauseReason); err != nil {
+ t.Fatalf("read squad autopilot: %v", err)
+ }
+ if err := testPool.QueryRow(ctx,
+ `SELECT status FROM autopilot WHERE id = $1`,
+ directAutopilotID,
+ ).Scan(&directStatus); err != nil {
+ t.Fatalf("read direct autopilot: %v", err)
+ }
+ if squadStatus != "paused" || pauseReason != string(ReasonAgentRuntimeRequired) {
+ t.Fatalf("squad autopilot = (%q, %q), want (paused, agent_runtime_required)", squadStatus, pauseReason)
+ }
+ if directStatus != "active" {
+ t.Fatalf("unrelated direct autopilot status = %q, want active", directStatus)
+ }
+}
+
+// TestDeleteAgentRuntime_StillBlockedByActiveAgents preserves the existing 409
+// contract: a runtime with at least one ACTIVE agent must still refuse the
+// strict delete, so the user always sees and confirms which agents are about to
+// lose their runtime before anything happens.
+func TestDeleteAgentRuntime_StillBlockedByActiveAgents(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ runtimeID := seedIsolatedRuntime(t, "Runtime With Active Agent")
+ activeAgent := seedAgentOnRuntime(t, runtimeID, "Active Agent Blocking Delete", false)
+
+ 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("DeleteAgentRuntime: expected 409 active-agent guard, got %d: %s", w.Code, w.Body.String())
+ }
+
+ if !agentExists(t, activeAgent) {
+ t.Errorf("active agent must NOT have been touched by a refused runtime delete")
+ }
+ if !agentRuntimeBound(t, activeAgent) {
+ t.Errorf("active agent must still be bound after a refused runtime delete")
+ }
+ if !runtimeExists(t, runtimeID) {
+ t.Errorf("runtime must NOT have been deleted by a refused delete")
+ }
+}
+
+// agentRuntimeBound reports whether the agent still points at a runtime.
+func agentRuntimeBound(t *testing.T, agentID string) bool {
+ t.Helper()
+ var bound bool
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT runtime_id IS NOT NULL FROM agent WHERE id = $1`, agentID,
+ ).Scan(&bound); err != nil {
+ t.Fatalf("read runtime_id for agent %s: %v", agentID, err)
+ }
+ return bound
+}
diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.go
index ed4368e8a7..9b0a88d695 100644
--- a/server/internal/handler/squad.go
+++ b/server/internal/handler/squad.go
@@ -383,14 +383,39 @@ func (h *Handler) UpdateSquad(w http.ResponseWriter, r *http.Request) {
}
params.AvatarUrl = pgtype.Text{String: accepted, Valid: true}
}
+
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update squad")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ // Autopilot assignment takes FOR SHARE on the squad before locking its
+ // leader Agent. Take the exclusive side in the same order so leader
+ // rotation and active Autopilot saves cannot leave an automation pointing
+ // at an unbound effective Agent.
+ if _, err := qtx.LockSquadForUpdate(r.Context(), db.LockSquadForUpdateParams{
+ ID: squad.ID,
+ WorkspaceID: wsUUID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update squad")
+ return
+ }
+
+ newLeaderRuntimeBound := true
if req.LeaderID != nil {
lid, ok := parseUUIDOrBadRequest(w, *req.LeaderID, "leader_id")
if !ok {
return
}
- // Validate new leader is an agent in workspace.
- newLeader, err := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{
- ID: lid, WorkspaceID: wsUUID,
+ // Stabilize runtime_id through commit. Runtime teardown takes FOR UPDATE
+ // on this row and follows the same Agent→Autopilot lock order, so
+ // whichever operation starts first produces a complete result.
+ newLeader, err := qtx.LockAgentForAutopilotAssignment(r.Context(), db.LockAgentForAutopilotAssignmentParams{
+ ID: lid,
+ WorkspaceID: wsUUID,
})
if err != nil {
writeError(w, http.StatusBadRequest, "leader must be a valid agent in this workspace")
@@ -402,22 +427,42 @@ func (h *Handler) UpdateSquad(w http.ResponseWriter, r *http.Request) {
return
}
// Ensure new leader is a squad member; auto-add if not.
- isMember, _ := h.Queries.IsSquadMember(r.Context(), db.IsSquadMemberParams{
+ isMember, err := qtx.IsSquadMember(r.Context(), db.IsSquadMemberParams{
SquadID: squad.ID, MemberType: "agent", MemberID: lid,
})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update squad")
+ return
+ }
if !isMember {
- h.Queries.AddSquadMember(r.Context(), db.AddSquadMemberParams{
+ if _, err := qtx.AddSquadMember(r.Context(), db.AddSquadMemberParams{
SquadID: squad.ID, MemberType: "agent", MemberID: lid, Role: "leader",
- })
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update squad")
+ return
+ }
}
params.LeaderID = lid
+ newLeaderRuntimeBound = newLeader.RuntimeID.Valid
}
- updated, err := h.Queries.UpdateSquad(r.Context(), params)
+ updated, err := qtx.UpdateSquad(r.Context(), params)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to update squad")
return
}
+ var pausedAutopilots []db.Autopilot
+ if req.LeaderID != nil && !newLeaderRuntimeBound {
+ pausedAutopilots, err = qtx.PauseAutopilotsByUnrunnableSquad(r.Context(), squad.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update squad")
+ return
+ }
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update squad")
+ return
+ }
resp, err := h.squadToResponseWithPreview(r.Context(), updated)
if err != nil {
@@ -425,6 +470,11 @@ func (h *Handler) UpdateSquad(w http.ResponseWriter, r *http.Request) {
return
}
h.publish(protocol.EventSquadUpdated, workspaceID, "member", requestUserID(r), map[string]any{"squad": resp})
+ for _, autopilot := range pausedAutopilots {
+ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", requestUserID(r), map[string]any{
+ "autopilot": autopilotToResponse(autopilot, nil),
+ })
+ }
writeJSON(w, http.StatusOK, resp)
}
diff --git a/server/internal/handler/workspace_test.go b/server/internal/handler/workspace_test.go
index 0c1cb7ef95..9ec93d3609 100644
--- a/server/internal/handler/workspace_test.go
+++ b/server/internal/handler/workspace_test.go
@@ -11,6 +11,7 @@ import (
"sort"
"strings"
"testing"
+ "time"
)
func TestCreateWorkspace_RejectsReservedSlug(t *testing.T) {
@@ -1260,6 +1261,48 @@ RETURNING id
}
}
+// TestDeleteMember_CancelsDeferredTasks covers the second caller of
+// CancelAgentTasksByRuntimeOrAgent. Member revocation must cancel a scheduled
+// fallback just like queued/running work; otherwise it could become claimable
+// after its owner and runtime access have been removed.
+func TestDeleteMember_CancelsDeferredTasks(t *testing.T) {
+ fx := setupRevocationFixture(t, "handler-tests-revoke-deferred", "daemon-revoke-deferred")
+ ctx := context.Background()
+
+ var deferredTaskID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, fire_at)
+VALUES ($1, $2, 'deferred', 0, now() + interval '1 hour')
+RETURNING id
+`, fx.AgentID, fx.RuntimeID).Scan(&deferredTaskID); err != nil {
+ t.Fatalf("insert deferred task: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/workspaces/"+fx.WorkspaceID+"/members/"+fx.MemberID, nil)
+ req.Header.Set("X-Workspace-ID", fx.WorkspaceID)
+ req = withURLParams(req, "id", fx.WorkspaceID, "memberId", fx.MemberID)
+ testHandler.DeleteMember(w, req)
+
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("DeleteMember: expected 204, got %d: %s", w.Code, w.Body.String())
+ }
+
+ assertRevoked(t, fx)
+
+ var status string
+ var completedAt *time.Time
+ if err := testPool.QueryRow(ctx,
+ `SELECT status, completed_at FROM agent_task_queue WHERE id = $1`,
+ deferredTaskID,
+ ).Scan(&status, &completedAt); err != nil {
+ t.Fatalf("query deferred task: %v", err)
+ }
+ if status != "cancelled" || completedAt == nil {
+ t.Fatalf("deferred task = (%q, %v), want cancelled with completed_at", status, completedAt)
+ }
+}
+
// TestDeleteMember_NoRuntimes_DeletesMember covers the empty-revocation
// path: a member with no owned runtimes should still have their member row
// deleted by the same atomic transaction, with no spurious archive/cancel
diff --git a/server/internal/integrations/lark/channel_cleanup_test.go b/server/internal/integrations/lark/channel_cleanup_test.go
index 6bacda3763..30897721b8 100644
--- a/server/internal/integrations/lark/channel_cleanup_test.go
+++ b/server/internal/integrations/lark/channel_cleanup_test.go
@@ -132,10 +132,13 @@ func assertInstallationIntact(t *testing.T, ctx context.Context, pool *pgxpool.P
}
}
-// TestDeleteChannelInstallationsByArchivedRuntimeAgents: runtime teardown hard-
-// deletes archived agents; this cleanup must sweep exactly those agents'
-// installations (and dependents), leaving live agents on the runtime untouched.
-func TestDeleteChannelInstallationsByArchivedRuntimeAgents(t *testing.T) {
+// TestDeleteChannelInstallationsBySystemRuntimeAgents: runtime teardown hard-
+// deletes only the SYSTEM agents on the runtime (user agents are unbound and
+// keep everything since MUL-5559), so this cleanup must sweep exactly those
+// agents' installations and dependents. The archived user agent in the fixture
+// is the regression: sweeping it would take a working bot away from an agent
+// that is still there.
+func TestDeleteChannelInstallationsBySystemRuntimeAgents(t *testing.T) {
pool := channelScopeTestDB(t)
ctx := context.Background()
q := db.New(pool)
@@ -161,19 +164,19 @@ func TestDeleteChannelInstallationsByArchivedRuntimeAgents(t *testing.T) {
exec(`INSERT INTO workspace (id, name, slug, description) VALUES ($1, 'cc ws', 'cc-ws', '')`, ccWS)
exec(`INSERT INTO agent_runtime (id, workspace_id, name, runtime_mode, provider)
VALUES ($1, $2, 'cc runtime', 'local', 'multica_daemon')`, ccRuntime, ccWS)
- exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id, archived_at)
-VALUES ($1, $2, 'cc archived agent', 'local', $3, now())`, ccAgentArch, ccWS, ccRuntime)
+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id, kind, system_key)
+VALUES ($1, $2, 'cc system agent', 'local', $3, 'system', 'cc_probe')`, ccAgentArch, ccWS, ccRuntime)
exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id)
VALUES ($1, $2, 'cc live agent', 'local', $3)`, ccAgentLive, ccWS, ccRuntime)
- archivedID := seedFullInstallation(t, ctx, pool, ccWS, ccAgentArch, ccAppArchive, ccChatArch, ccTokenArch, ccAuditArch)
+ systemID := seedFullInstallation(t, ctx, pool, ccWS, ccAgentArch, ccAppArchive, ccChatArch, ccTokenArch, ccAuditArch)
liveID := seedFullInstallation(t, ctx, pool, ccWS, ccAgentLive, ccAppLive, ccChatLive, ccTokenLive, ccAuditLive)
- if err := q.DeleteChannelInstallationsByArchivedRuntimeAgents(ctx, util.MustParseUUID(ccRuntime)); err != nil {
- t.Fatalf("DeleteChannelInstallationsByArchivedRuntimeAgents: %v", err)
+ if err := q.DeleteChannelInstallationsBySystemRuntimeAgents(ctx, util.MustParseUUID(ccRuntime)); err != nil {
+ t.Fatalf("DeleteChannelInstallationsBySystemRuntimeAgents: %v", err)
}
- assertInstallationSwept(t, ctx, pool, archivedID, ccChatArch, ccAuditArch)
+ assertInstallationSwept(t, ctx, pool, systemID, ccChatArch, ccAuditArch)
assertInstallationIntact(t, ctx, pool, liveID, ccChatLive, ccAuditLive)
}
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index c4aeaace42..b081416834 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -1267,6 +1267,12 @@ func agentReadinessReasonCode(agent db.Agent) dispatch.ReasonCode {
if agent.ArchivedAt.Valid {
return dispatch.ReasonTargetUnavailable
}
+ // No runtime bound at all is a different user story from a runtime that is
+ // merely offline: nothing will ever pick the work up, and the fix is to bind
+ // the agent to a runtime (MUL-5559).
+ if !agent.RuntimeID.Valid {
+ return dispatch.ReasonAgentRuntimeRequired
+ }
return dispatch.ReasonRuntimeOffline
}
diff --git a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
index ae2884590d..d34142395a 100644
--- a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
@@ -23,6 +23,13 @@ multica agent skills list <agent-id> --output json # current skill bindings
multica agent env get <agent-id> --output json # plaintext env (agent owner or ws owner/admin; agents denied)
```
+An agent can also be **unbound**: `runtime_id` is `NULL` (served as `""` with
+`runtime_bound: false`) after its runtime was deleted, which unbinds instead of
+deleting its agents (MUL-5559). An unbound agent keeps everything it owns and
+stays editable, but no trigger path will run it — they all refuse with
+`agent_runtime_required` — until `agent update <id> --runtime-id <runtime-id>` binds
+it again. Unbound is orthogonal to archived.
+
`agent get` returns the persisted agent including `runtime_id`, `model`,
`thinking_level`, `service_tier`, `custom_args`, `has_custom_env`,
`custom_env_key_count`, and `skills`. It never returns plaintext `custom_env`.
@@ -110,7 +117,7 @@ multica agent copy <source-agent-id> --runtime-id <target> --model <model> # cr
| `description` | `agent.description` | 400 if > 255 code points | catalog/listing only — NOT the runtime prompt |
| `instructions` | `agent.instructions` | none | daemon → provider at claim time |
| `avatar_url` | `agent.avatar_url` | none; an explicit non-empty value is preserved, while omitted/empty creates a random `emoji:<glyph>` avatar | catalog/listing UI only — NOT the runtime prompt |
-| `runtime_id` | `agent.runtime_id` | required (400) + must resolve to a runtime in this workspace | selects runtime/provider |
+| `runtime_id` | `agent.runtime_id` (nullable) | required at create (400) + must resolve to a runtime in this workspace | selects runtime/provider; `NULL` means unbound — see below |
| `model` | `agent.model` (nullable) | none beyond runtime support | daemon reads; empty = runtime default |
| `thinking_level` | `agent.thinking_level` (nullable) | provider-level enum; unknown literal → 400 | daemon; empty = runtime default |
| `service_tier` | `agent.service_tier` (nullable) | Codex-only safe token; other providers reject; exact model/tier pair checked by daemon | daemon → Codex app-server; empty = local Codex config |
diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
index 6d06dcb3de..ba7f556792 100644
--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
@@ -45,7 +45,7 @@ multica repo checkout <url>
multica repo checkout <url> --ref <branch-or-sha>
```
-`runtime update` and `runtime delete` are writes. Starting a runtime update is limited to its owner or a workspace owner/admin; the original initiator may keep polling that specific in-flight request if their admin role changes. `runtime delete` removes a runtime registration; if active agents are still bound, it refuses unless the user explicitly passes `--cascade`, which archives those agents and cancels their queued/running tasks before deleting the runtime. `repo checkout` creates a dedicated branch in the task working directory. Most runtimes use a linked worktree; Linux Codex uses task-local Git metadata so a task can stage and commit without making the shared `.repos` cache writable.
+`runtime update` and `runtime delete` are writes. Starting a runtime update is limited to its owner or a workspace owner/admin; the original initiator may keep polling that specific in-flight request if their admin role changes. `runtime delete` removes a runtime registration; if active agents are still bound, it refuses unless the user explicitly passes `--cascade`, which unbinds those agents and cancels their queued/running tasks before deleting the runtime. Unbinding keeps the agents and everything they own — instructions, skills, chats, labels, channel installations, autopilots and task history — and only clears `agent.runtime_id`; an unbound agent cannot run until it is bound to a runtime again (`multica agent update <id> --runtime-id <runtime-id>`), and every trigger path refuses it with `agent_runtime_required`. `repo checkout` creates a dedicated branch in the task working directory. Most runtimes use a linked worktree; Linux Codex uses task-local Git metadata so a task can stage and commit without making the shared `.repos` cache writable.
`repo checkout` requires `MULTICA_DAEMON_PORT`; it is intended to run inside a daemon task. If absent, you are not in the normal agent checkout path. When a project `github_repo` resource has `resource_ref.ref`, `repo checkout <url>` uses that ref by default for the current task; an explicit `repo checkout <url> --ref <branch-or-sha>` overrides it.
diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
index 98f0d5333f..c6808dc5be 100644
--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
+++ b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
@@ -3,7 +3,7 @@
- `server/cmd/multica/cmd_runtime.go` registers `runtime list`, `usage`, `activity`, `update`, and `delete`.
- `runtime list` reads `/api/runtimes` and prints `id`, `name`, `runtime_mode`, `provider`, `status`, and `last_seen_at`.
- `runtime update` posts to `/api/runtimes/{runtime-id}/update`; with `--wait` it polls update status. Initiation enforces runtime-owner or workspace-owner/admin access through `canEditRuntime`; status polling additionally permits that request's immutable initiator so an in-flight poll survives an admin-role change (`server/internal/handler/runtime_update.go` and `runtime.go`).
-- `runtime delete` deletes `/api/runtimes/{runtime-id}`; with `--cascade`, it first reads the `runtime_has_active_agents` conflict payload and posts those ids to `/api/runtimes/{runtime-id}/archive-agents-and-delete`.
+- `runtime delete` deletes `/api/runtimes/{runtime-id}`; with `--cascade`, it first reads the `runtime_has_active_agents` conflict payload and posts those ids to `/api/runtimes/{runtime-id}/unbind-agents-and-delete` (the older `/archive-agents-and-delete` path still routes to the same handler for installed clients). Both delete paths run `unbindRuntimeForDelete` in `server/internal/handler/runtime.go`: user agents are unbound (`runtime_id = NULL`, MUL-5559), their task history is detached so deleting the runtime cannot cascade it away, active tasks are cancelled, and only `kind='system'` agents are hard-deleted.
- `server/cmd/multica/cmd_repo.go` registers `repo checkout <url> [--ref]`.
- `repo checkout` requires `MULTICA_DAEMON_PORT`, sends `workspace_id`, `workdir`, `ref`, `agent_name`, `task_id`, and the daemon-managed optional `checkout_mode` to local daemon `/repo/checkout`, then prints the checked-out path.
- `server/internal/daemon/health.go` resolves the checkout ref: request `ref` wins; otherwise it asks `server/internal/daemon/daemon.go` for the current task's project repo default ref. It forwards the validated isolated-checkout mode into `repocache.WorktreeParams`.
diff --git a/server/internal/service/reason_code_test.go b/server/internal/service/reason_code_test.go
index 05b0c3afdf..4e3aea88cd 100644
--- a/server/internal/service/reason_code_test.go
+++ b/server/internal/service/reason_code_test.go
@@ -30,17 +30,19 @@ func TestDispatchFailReasonCode(t *testing.T) {
}
// TestAgentReadinessReasonCode is the regression for Elon must-fix 2, case 2: a
-// runtime-availability failure (no runtime bound, or a bound-but-offline
-// runtime) must map to runtime_offline, and an archived agent to
-// target_unavailable — decided from the agent's own state, not the reason text.
+// runtime-availability failure must be classified from the agent's own state,
+// not from the reason text. Since MUL-5559 the two runtime failures are
+// deliberately distinct: an agent with NO runtime needs to be bound to one
+// (agent_runtime_required), while a bound-but-offline runtime needs the machine
+// back (runtime_offline). Collapsing them sends the user looking for a computer
+// that does not exist.
func TestAgentReadinessReasonCode(t *testing.T) {
validRuntime := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}
archivedAt := pgtype.Timestamptz{Valid: true}
- // No runtime bound (the "agent has no runtime bound" case that previously
- // fell through the substring classifier to generic).
- if got := agentReadinessReasonCode(db.Agent{}); got != dispatch.ReasonRuntimeOffline {
- t.Errorf("no runtime bound: got %q, want runtime_offline", got)
+ // No runtime bound — the state an agent lands in when its runtime is deleted.
+ if got := agentReadinessReasonCode(db.Agent{}); got != dispatch.ReasonAgentRuntimeRequired {
+ t.Errorf("no runtime bound: got %q, want agent_runtime_required", got)
}
// Bound runtime that is offline at dispatch time.
if got := agentReadinessReasonCode(db.Agent{RuntimeID: validRuntime}); got != dispatch.ReasonRuntimeOffline {
diff --git a/server/migrations/251_agent_runtime_unbind.down.sql b/server/migrations/251_agent_runtime_unbind.down.sql
new file mode 100644
index 0000000000..1dc9b3e2cb
--- /dev/null
+++ b/server/migrations/251_agent_runtime_unbind.down.sql
@@ -0,0 +1,30 @@
+-- Reverts 251_agent_runtime_unbind.up.sql.
+--
+-- Restoring NOT NULL requires that no unbound row exists. This down migration
+-- deliberately does NOT delete unbound agents to make itself succeed: deleting
+-- them is precisely the data loss the up migration removes, and an operator
+-- rolling a schema back is not asking to destroy every agent whose machine was
+-- retired.
+--
+-- So this fails loudly while unbound rows are present. To roll back, first
+-- rebind the affected agents (PATCH /api/agents/:id with a runtime_id) and
+-- re-point or accept the loss of history rows whose runtime is gone:
+--
+-- SELECT id, name FROM agent WHERE runtime_id IS NULL;
+-- SELECT count(*) FROM agent_task_queue WHERE runtime_id IS NULL;
+--
+-- Note that a rolled-back application binary still contains the old
+-- archive-then-hard-delete runtime teardown, so runtime deletion must not be
+-- exercised during a rollback window.
+
+ALTER TABLE autopilot
+ DROP COLUMN IF EXISTS pause_reason;
+
+ALTER TABLE agent_task_queue
+ DROP CONSTRAINT IF EXISTS agent_task_queue_active_requires_runtime;
+
+ALTER TABLE agent_task_queue
+ ALTER COLUMN runtime_id SET NOT NULL;
+
+ALTER TABLE agent
+ ALTER COLUMN runtime_id SET NOT NULL;
diff --git a/server/migrations/251_agent_runtime_unbind.up.sql b/server/migrations/251_agent_runtime_unbind.up.sql
new file mode 100644
index 0000000000..9a3661bea7
--- /dev/null
+++ b/server/migrations/251_agent_runtime_unbind.up.sql
@@ -0,0 +1,68 @@
+-- Migration 251 (MUL-5559): deleting a runtime unbinds its agents instead of
+-- destroying them.
+--
+-- Before this migration an agent physically could not exist without a runtime
+-- (agent.runtime_id NOT NULL), so the runtime-delete flow had no third option:
+-- it archived the runtime's agents and then hard-deleted the rows, taking their
+-- chat sessions with them. The confirmation dialog called that "archive", which
+-- is not what the user got — the agents and every conversation with them were
+-- gone. Retiring a laptop is an ordinary action; losing the agents configured
+-- on it is not an ordinary consequence.
+--
+-- Two columns become nullable, not one:
+--
+-- 1. agent.runtime_id — NULL now means "unbound": the agent, its
+-- instructions, skills, chats, labels, channel installations and
+-- autopilot config all survive, it simply cannot run until it is bound to
+-- a runtime again. Unbound is orthogonal to archived.
+-- AgentReadiness already refuses an agent with no runtime, so the
+-- scheduling safety gate needs no change.
+--
+-- 2. agent_task_queue.runtime_id — without this, unbinding the agent would
+-- still lose its whole task history: that column is NOT NULL with an
+-- ON DELETE CASCADE FK, which cascades further into task_message,
+-- task_usage and task_token. ReassignTasksToRuntime already documents the
+-- same trap for the legacy-daemon merge path ("Required before deleting
+-- the old runtime row because agent_task_queue has an ON DELETE CASCADE
+-- FK that would otherwise drop historical tasks"). The delete transaction
+-- now nulls these rows explicitly, so the cascade never fires.
+--
+-- No new foreign keys or cascading actions are introduced (repository rule):
+-- the unbind itself is an explicit application-layer UPDATE inside the same
+-- transaction as the runtime delete. The pre-existing CASCADE on
+-- agent_task_queue.runtime_id is left in place but is now inert on this path —
+-- it stays as the last-resort guarantee that no row can reference a runtime
+-- that no longer exists.
+--
+-- The CHECK is the invariant that keeps NULL confined to history: an ACTIVE
+-- task must always have a runtime, so claim / dispatch / delivery-CAS paths can
+-- never observe runtime_id IS NULL. It is expressed with completed_at rather
+-- than a status list because every terminal transition stamps completed_at
+-- (CompleteAgentTask / FailAgentTask / the five cancel queries), and because
+-- naming enumerable status values in a constraint would force a migration for
+-- each new status. A future non-terminal status therefore fails closed — it
+-- must carry a runtime — instead of silently slipping through.
+--
+-- NOT VALID keeps this a metadata-only add on a hot table (no ACCESS EXCLUSIVE
+-- full-table scan); PostgreSQL still enforces it on every INSERT and UPDATE
+-- from this point on, which is exactly what the invariant needs. Existing rows
+-- all satisfy it (runtime_id was NOT NULL until now), so there is nothing to
+-- back-fill; a later migration can VALIDATE it during a quiet window.
+
+ALTER TABLE agent
+ ALTER COLUMN runtime_id DROP NOT NULL;
+
+ALTER TABLE agent_task_queue
+ ALTER COLUMN runtime_id DROP NOT NULL;
+
+ALTER TABLE agent_task_queue
+ ADD CONSTRAINT agent_task_queue_active_requires_runtime
+ CHECK (runtime_id IS NOT NULL OR completed_at IS NOT NULL)
+ NOT VALID;
+
+-- Runtime deletion pauses affected automations so a schedule cannot append one
+-- identical skipped run on every tick forever. The reason is persisted
+-- separately from status: clients can explain the recoverable condition, and a
+-- user can rebind the agent then resume the unchanged automation.
+ALTER TABLE autopilot
+ ADD COLUMN pause_reason TEXT;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index d53fa62678..469abe7bfe 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -3343,7 +3343,7 @@ ORDER BY name ASC
// Returns every non-archived agent bound to a runtime. Backs the cascade
// delete dialog: when DELETE /api/runtimes/:id refuses with
// runtime_has_active_agents, the response carries this list so the front-end
-// can render exactly the agents that will be archived if the user confirms,
+// can render exactly the agents that will be unbound if the user confirms,
// and so the cascade endpoint's expected_active_agent_ids check has a stable
// snapshot to compare against. Ordered by name for a deterministic display.
func (q *Queries) ListActiveAgentsByRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]Agent, error) {
@@ -3408,8 +3408,7 @@ FOR UPDATE
// LockAgentRuntime, which holds the runtime row exclusively to also
// block FK-validated INSERTs / runtime_id updates that would otherwise
// add a new agent to the runtime mid-cascade. Together they guarantee
-// that the set we compared against expected_active_agent_ids is exactly
-// the set ArchiveAgentsByIDs will operate on — no race window.
+// that the set we compared against expected_active_agent_ids is stable.
func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtimeID pgtype.UUID) ([]Agent, error) {
rows, err := q.db.Query(ctx, listActiveAgentsByRuntimeForUpdate, runtimeID)
if err != nil {
@@ -4213,6 +4212,67 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
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 FROM agent
+WHERE runtime_id = $1 AND kind = 'user'
+ORDER BY id
+FOR UPDATE
+`
+
+// 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
+// after confirmation and then be silently unbound. Runtime/profile delete
+// locks the parent runtime first (blocking new FK references), then calls this
+// in stable ID order (blocking restore/archive/move on existing rows).
+func (q *Queries) ListUserAgentsByRuntimeForUpdate(ctx context.Context, runtimeID pgtype.UUID) ([]Agent, error) {
+ rows, err := q.db.Query(ctx, listUserAgentsByRuntimeForUpdate, runtimeID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Agent{}
+ for rows.Next() {
+ var i Agent
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.AvatarUrl,
+ &i.RuntimeMode,
+ &i.RuntimeConfig,
+ &i.Visibility,
+ &i.Status,
+ &i.MaxConcurrentTasks,
+ &i.OwnerID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Description,
+ &i.RuntimeID,
+ &i.Instructions,
+ &i.ArchivedAt,
+ &i.ArchivedBy,
+ &i.CustomEnv,
+ &i.CustomArgs,
+ &i.McpConfig,
+ &i.Model,
+ &i.ThinkingLevel,
+ &i.ComposioToolkitAllowlist,
+ &i.PermissionMode,
+ &i.Kind,
+ &i.SystemKey,
+ &i.DisabledRuntimeSkills,
+ &i.ServiceTier,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
@@ -4506,6 +4566,62 @@ func (q *Queries) ListWorkspaceWorkingAgents(ctx context.Context, arg ListWorksp
return items, nil
}
+const lockAgentForAutopilotAssignment = `-- name: LockAgentForAutopilotAssignment :one
+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 FROM agent
+WHERE id = $1 AND workspace_id = $2 AND kind = 'user'
+FOR SHARE
+`
+
+type LockAgentForAutopilotAssignmentParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Serializes creating, retargeting, or resuming an active Autopilot with
+// Runtime teardown. Teardown takes FOR UPDATE on this same Agent row before it
+// clears runtime_id and pauses matching Autopilots. FOR SHARE also stabilizes
+// runtime_id and archived_at against concurrent ordinary Agent updates. The
+// shared lock makes the
+// two outcomes exhaustive:
+// - assignment commits first, then teardown sees and pauses it; or
+// - teardown commits first, then assignment re-reads runtime_id=NULL and
+// rejects the active Autopilot.
+func (q *Queries) LockAgentForAutopilotAssignment(ctx context.Context, arg LockAgentForAutopilotAssignmentParams) (Agent, error) {
+ row := q.db.QueryRow(ctx, lockAgentForAutopilotAssignment, arg.ID, arg.WorkspaceID)
+ var i Agent
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.AvatarUrl,
+ &i.RuntimeMode,
+ &i.RuntimeConfig,
+ &i.Visibility,
+ &i.Status,
+ &i.MaxConcurrentTasks,
+ &i.OwnerID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Description,
+ &i.RuntimeID,
+ &i.Instructions,
+ &i.ArchivedAt,
+ &i.ArchivedBy,
+ &i.CustomEnv,
+ &i.CustomArgs,
+ &i.McpConfig,
+ &i.Model,
+ &i.ThinkingLevel,
+ &i.ComposioToolkitAllowlist,
+ &i.PermissionMode,
+ &i.Kind,
+ &i.SystemKey,
+ &i.DisabledRuntimeSkills,
+ &i.ServiceTier,
+ )
+ return i, err
+}
+
const markAgentTaskWaitingLocalDirectory = `-- name: MarkAgentTaskWaitingLocalDirectory :one
UPDATE agent_task_queue
SET status = 'waiting_local_directory',
diff --git a/server/pkg/db/generated/agent_invocation_target.sql.go b/server/pkg/db/generated/agent_invocation_target.sql.go
index 24ff307775..6a10c22040 100644
--- a/server/pkg/db/generated/agent_invocation_target.sql.go
+++ b/server/pkg/db/generated/agent_invocation_target.sql.go
@@ -53,23 +53,6 @@ func (q *Queries) DeleteAgentInvocationTargets(ctx context.Context, agentID pgty
return err
}
-const deleteAgentInvocationTargetsByArchivedRuntimeAgents = `-- name: DeleteAgentInvocationTargetsByArchivedRuntimeAgents :exec
-DELETE FROM agent_invocation_target
-WHERE agent_id IN (
- SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL
-)
-`
-
-// Application-layer replacement for the (deliberately absent) agent_id ON
-// DELETE CASCADE: removes invocation targets for the archived agents a runtime
-// delete is about to hard-delete. MUST run in the same tx as, and BEFORE,
-// DeleteArchivedAgentsByRuntime so no orphan target rows survive the agent
-// rows they belonged to. Mirrors the agent hard-delete predicate exactly.
-func (q *Queries) DeleteAgentInvocationTargetsByArchivedRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
- _, err := q.db.Exec(ctx, deleteAgentInvocationTargetsByArchivedRuntimeAgents, runtimeID)
- return err
-}
-
const deleteAgentInvocationTargetsByMember = `-- name: DeleteAgentInvocationTargetsByMember :exec
DELETE FROM agent_invocation_target ait
USING agent a
@@ -94,6 +77,28 @@ func (q *Queries) DeleteAgentInvocationTargetsByMember(ctx context.Context, arg
return err
}
+const deleteAgentInvocationTargetsBySystemRuntimeAgents = `-- name: DeleteAgentInvocationTargetsBySystemRuntimeAgents :exec
+DELETE FROM agent_invocation_target
+WHERE agent_id IN (
+ SELECT id FROM agent WHERE runtime_id = $1 AND kind = 'system'
+)
+`
+
+// Application-layer replacement for the (deliberately absent) agent_id ON
+// DELETE CASCADE: removes invocation targets for the system agents a runtime
+// delete is about to hard-delete. MUST run in the same tx as, and BEFORE,
+// DeleteSystemAgentsByRuntime so no orphan target rows survive the agent rows
+// they belonged to. Mirrors the agent hard-delete predicate exactly.
+//
+// Scoped to kind = 'system' since MUL-5559: user agents are no longer deleted
+// with their runtime (they are unbound and keep their configuration), so
+// clearing THEIR invocation targets here would silently strip a surviving
+// agent's allow-list.
+func (q *Queries) DeleteAgentInvocationTargetsBySystemRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteAgentInvocationTargetsBySystemRuntimeAgents, runtimeID)
+ return err
+}
+
const listAgentInvocationTargets = `-- name: ListAgentInvocationTargets :many
SELECT id, agent_id, target_type, target_id, created_by, created_at FROM agent_invocation_target
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 1cf3147050..f5d3593259 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -83,7 +83,7 @@ func (q *Queries) AdvanceTriggerNextRun(ctx context.Context, arg AdvanceTriggerN
const archiveAutopilot = `-- name: ArchiveAutopilot :exec
UPDATE autopilot
-SET status = 'archived', updated_at = now()
+SET status = 'archived', pause_reason = NULL, updated_at = now()
WHERE id = $1
`
@@ -101,7 +101,7 @@ INSERT INTO autopilot (
$1, $2, $9, $3, $4,
$5, $6, $10, $11,
$7, $8
-) RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id
+) RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id, pause_reason
`
type CreateAutopilotParams struct {
@@ -149,6 +149,7 @@ func (q *Queries) CreateAutopilot(ctx context.Context, arg CreateAutopilotParams
&i.UpdatedAt,
&i.AssigneeType,
&i.ProjectID,
+ &i.PauseReason,
)
return i, err
}
@@ -550,7 +551,7 @@ func (q *Queries) GetActiveAutopilotRuleVersion(ctx context.Context, arg GetActi
}
const getAutopilot = `-- name: GetAutopilot :one
-SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id FROM autopilot
+SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id, pause_reason FROM autopilot
WHERE id = $1
`
@@ -573,12 +574,13 @@ func (q *Queries) GetAutopilot(ctx context.Context, id pgtype.UUID) (Autopilot,
&i.UpdatedAt,
&i.AssigneeType,
&i.ProjectID,
+ &i.PauseReason,
)
return i, err
}
const getAutopilotInWorkspace = `-- name: GetAutopilotInWorkspace :one
-SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id FROM autopilot
+SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id, pause_reason FROM autopilot
WHERE id = $1 AND workspace_id = $2
`
@@ -606,6 +608,7 @@ func (q *Queries) GetAutopilotInWorkspace(ctx context.Context, arg GetAutopilotI
&i.UpdatedAt,
&i.AssigneeType,
&i.ProjectID,
+ &i.PauseReason,
)
return i, err
}
@@ -1124,7 +1127,7 @@ func (q *Queries) ListAutopilotTriggers(ctx context.Context, autopilotID pgtype.
const listAutopilots = `-- name: ListAutopilots :many
SELECT
- a.id, a.workspace_id, a.title, a.description, a.assignee_id, a.status, a.execution_mode, a.issue_title_template, a.created_by_type, a.created_by_id, a.last_run_at, a.created_at, a.updated_at, a.assignee_type, a.project_id,
+ a.id, a.workspace_id, a.title, a.description, a.assignee_id, a.status, a.execution_mode, a.issue_title_template, a.created_by_type, a.created_by_id, a.last_run_at, a.created_at, a.updated_at, a.assignee_type, a.project_id, a.pause_reason,
(
SELECT array_agg(DISTINCT t.kind ORDER BY t.kind)
FROM autopilot_trigger t
@@ -1197,6 +1200,7 @@ func (q *Queries) ListAutopilots(ctx context.Context, arg ListAutopilotsParams)
&i.Autopilot.UpdatedAt,
&i.Autopilot.AssigneeType,
&i.Autopilot.ProjectID,
+ &i.Autopilot.PauseReason,
&i.TriggerKinds,
&i.NextRunAt,
&i.LastRunStatus,
@@ -1283,6 +1287,157 @@ func (q *Queries) ListSchedulableAutopilotTriggers(ctx context.Context) ([]ListS
return items, nil
}
+const lockAutopilotForUpdate = `-- name: LockAutopilotForUpdate :one
+SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id, pause_reason FROM autopilot
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE
+`
+
+type LockAutopilotForUpdateParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// UpdateAutopilot is a patch assembled from a pre-transaction snapshot. Lock
+// and compare that row before applying the patch so a concurrent retarget or
+// Runtime teardown cannot be overwritten by stale assignee/status fields.
+func (q *Queries) LockAutopilotForUpdate(ctx context.Context, arg LockAutopilotForUpdateParams) (Autopilot, error) {
+ row := q.db.QueryRow(ctx, lockAutopilotForUpdate, arg.ID, arg.WorkspaceID)
+ var i Autopilot
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.AssigneeID,
+ &i.Status,
+ &i.ExecutionMode,
+ &i.IssueTitleTemplate,
+ &i.CreatedByType,
+ &i.CreatedByID,
+ &i.LastRunAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.AssigneeType,
+ &i.ProjectID,
+ &i.PauseReason,
+ )
+ return i, err
+}
+
+const pauseAutopilotsByUnboundAgents = `-- name: PauseAutopilotsByUnboundAgents :many
+UPDATE autopilot a
+SET status = 'paused',
+ pause_reason = 'agent_runtime_required',
+ updated_at = now()
+WHERE a.status = 'active'
+ AND (
+ (a.assignee_type = 'agent' AND a.assignee_id = ANY($1::uuid[]))
+ OR (
+ a.assignee_type = 'squad'
+ AND EXISTS (
+ SELECT 1
+ FROM squad s
+ WHERE s.id = a.assignee_id
+ AND s.leader_id = ANY($1::uuid[])
+ )
+ )
+ )
+RETURNING a.id, a.workspace_id, a.title, a.description, a.assignee_id, a.status, a.execution_mode, a.issue_title_template, a.created_by_type, a.created_by_id, a.last_run_at, a.created_at, a.updated_at, a.assignee_type, a.project_id, a.pause_reason
+`
+
+// A runtime delete is a persistent admission failure, not a per-tick event.
+// Pause direct-agent automations and squad automations whose leader was
+// unbound, preserving the full configuration for an explicit resume after
+// rebind. Restrict to active so repeated teardown/retry is idempotent.
+func (q *Queries) PauseAutopilotsByUnboundAgents(ctx context.Context, agentIds []pgtype.UUID) ([]Autopilot, error) {
+ rows, err := q.db.Query(ctx, pauseAutopilotsByUnboundAgents, agentIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Autopilot{}
+ for rows.Next() {
+ var i Autopilot
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.AssigneeID,
+ &i.Status,
+ &i.ExecutionMode,
+ &i.IssueTitleTemplate,
+ &i.CreatedByType,
+ &i.CreatedByID,
+ &i.LastRunAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.AssigneeType,
+ &i.ProjectID,
+ &i.PauseReason,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const pauseAutopilotsByUnrunnableSquad = `-- name: PauseAutopilotsByUnrunnableSquad :many
+UPDATE autopilot
+SET status = 'paused',
+ pause_reason = 'agent_runtime_required',
+ updated_at = now()
+WHERE status = 'active'
+ AND assignee_type = 'squad'
+ AND assignee_id = $1
+RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id, pause_reason
+`
+
+// Rotating a squad to an already-unbound leader has the same persistent
+// admission failure as Runtime teardown. Pause only automations assigned to
+// this squad; direct automations targeting that Agent are unrelated.
+func (q *Queries) PauseAutopilotsByUnrunnableSquad(ctx context.Context, squadID pgtype.UUID) ([]Autopilot, error) {
+ rows, err := q.db.Query(ctx, pauseAutopilotsByUnrunnableSquad, squadID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Autopilot{}
+ for rows.Next() {
+ var i Autopilot
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.AssigneeID,
+ &i.Status,
+ &i.ExecutionMode,
+ &i.IssueTitleTemplate,
+ &i.CreatedByType,
+ &i.CreatedByID,
+ &i.LastRunAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.AssigneeType,
+ &i.ProjectID,
+ &i.PauseReason,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const recoverPartialAutopilotRun = `-- name: RecoverPartialAutopilotRun :exec
UPDATE autopilot_run
SET status = 'failed',
@@ -1562,9 +1717,9 @@ func (q *Queries) SetAutopilotTriggerWebhookToken(ctx context.Context, arg SetAu
const systemPauseAutopilot = `-- name: SystemPauseAutopilot :one
UPDATE autopilot
-SET status = 'paused', updated_at = now()
+SET status = 'paused', pause_reason = NULL, updated_at = now()
WHERE id = $1 AND status = 'active'
-RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id
+RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id, pause_reason
`
// Atomically pauses an autopilot only if it is currently active. Returns no
@@ -1590,6 +1745,7 @@ func (q *Queries) SystemPauseAutopilot(ctx context.Context, id pgtype.UUID) (Aut
&i.UpdatedAt,
&i.AssigneeType,
&i.ProjectID,
+ &i.PauseReason,
)
return i, err
}
@@ -1617,12 +1773,16 @@ UPDATE autopilot SET
assignee_type = COALESCE($4, assignee_type),
assignee_id = COALESCE($5::uuid, assignee_id),
status = COALESCE($6, status),
+ pause_reason = CASE
+ WHEN $6::text IS NOT NULL THEN NULL
+ ELSE pause_reason
+ END,
execution_mode = COALESCE($7, execution_mode),
issue_title_template = $8,
project_id = $9,
updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id
+RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id, pause_reason
`
type UpdateAutopilotParams struct {
@@ -1666,6 +1826,7 @@ func (q *Queries) UpdateAutopilot(ctx context.Context, arg UpdateAutopilotParams
&i.UpdatedAt,
&i.AssigneeType,
&i.ProjectID,
+ &i.PauseReason,
)
return i, err
}
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index d41843d319..72c774bd2c 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -556,11 +556,11 @@ func (q *Queries) DeleteChannelChatSessionBindingsByInstallation(ctx context.Con
return err
}
-const deleteChannelInstallationsByArchivedRuntimeAgents = `-- name: DeleteChannelInstallationsByArchivedRuntimeAgents :exec
+const deleteChannelInstallationsBySystemRuntimeAgents = `-- name: DeleteChannelInstallationsBySystemRuntimeAgents :exec
WITH doomed AS (
SELECT id FROM channel_installation
WHERE agent_id IN (
- SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL
+ SELECT id FROM agent WHERE runtime_id = $1 AND kind = 'system'
)
),
cleared_chat_sessions AS (
@@ -591,15 +591,18 @@ DELETE FROM channel_installation WHERE id IN (SELECT id FROM doomed)
`
// Application-layer replacement for the (deliberately absent, MUL-3515 §4)
-// workspace/agent ON DELETE CASCADE: on runtime teardown, before the archived
+// workspace/agent ON DELETE CASCADE: on runtime teardown, before the system
// agents are hard-deleted, remove every channel installation they own — plus all
// of each installation's dependent rows — so no orphaned installation keeps
// occupying its bot's (channel_type, app_id) routing slot after its agent is gone
-// (#4810). MUST run in the same tx as, and BEFORE, DeleteArchivedAgentsByRuntime.
-// Mirrors the agent hard-delete predicate (runtime_id, archived_at IS NOT NULL)
-// exactly.
-func (q *Queries) DeleteChannelInstallationsByArchivedRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
- _, err := q.db.Exec(ctx, deleteChannelInstallationsByArchivedRuntimeAgents, runtimeID)
+// (#4810). MUST run in the same tx as, and BEFORE, DeleteSystemAgentsByRuntime.
+// Mirrors the agent hard-delete predicate (runtime_id, kind = 'system') exactly.
+//
+// Scoped to kind = 'system' since MUL-5559: a user agent now survives its
+// runtime's deletion as an unbound agent, so tearing down its installations
+// here would take a working bot away from an agent that is still there.
+func (q *Queries) DeleteChannelInstallationsBySystemRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteChannelInstallationsBySystemRuntimeAgents, runtimeID)
return err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 89d83e33c6..9dcc23250f 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -472,25 +472,6 @@ func (q *Queries) DeleteChatDraftRestore(ctx context.Context, arg DeleteChatDraf
return result.RowsAffected(), nil
}
-const deleteChatDraftRestoresByArchivedRuntimeAgents = `-- name: DeleteChatDraftRestoresByArchivedRuntimeAgents :exec
-DELETE FROM chat_draft_restore
-WHERE chat_session_id IN (
- SELECT cs.id FROM chat_session cs
- JOIN agent a ON a.id = cs.agent_id
- WHERE a.runtime_id = $1 AND a.archived_at IS NOT NULL
-)
-`
-
-// chat_session cascades from agent, so hard-deleting a runtime's archived agents
-// silently drops their sessions — and, without an FK, would strand the pending
-// restores (which still hold the user's prompt text) forever. Prune them in the
-// same tx, BEFORE the agent rows go: the join below needs them. Mirrors
-// DeleteChannelInstallationsByArchivedRuntimeAgents.
-func (q *Queries) DeleteChatDraftRestoresByArchivedRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
- _, err := q.db.Exec(ctx, deleteChatDraftRestoresByArchivedRuntimeAgents, runtimeID)
- return err
-}
-
const deleteChatDraftRestoresBySession = `-- name: DeleteChatDraftRestoresBySession :exec
DELETE FROM chat_draft_restore
WHERE chat_session_id = $1
@@ -512,10 +493,14 @@ WHERE chat_session_id IN (
)
`
-// Same cascade, for the system agents a runtime teardown also hard-deletes
-// (DeleteSystemAgentsByRuntime). Split from the archived-agent prune because the
-// runtime-profile teardown deletes only archived agents: pruning system-agent
-// sessions there would destroy restores whose session survives.
+// chat_session cascades from agent, so hard-deleting a runtime's system agents
+// silently drops their sessions — and, without an FK, would strand the pending
+// restores (which still hold the user's prompt text) forever. Prune them in the
+// same tx, BEFORE the agent rows go: the join below needs them. Mirrors
+// DeleteChannelInstallationsBySystemRuntimeAgents.
+//
+// Only system agents are hard-deleted on runtime teardown since MUL-5559; user
+// agents (archived or not) are unbound and keep their sessions and restores.
func (q *Queries) DeleteChatDraftRestoresBySystemRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteChatDraftRestoresBySystemRuntimeAgents, runtimeID)
return err
@@ -1506,34 +1491,6 @@ func (q *Queries) LockChatSessionForTask(ctx context.Context, id pgtype.UUID) (p
return id_2, err
}
-const lockChatSessionsByArchivedRuntimeAgents = `-- name: LockChatSessionsByArchivedRuntimeAgents :many
-SELECT cs.id FROM chat_session cs
-JOIN agent a ON a.id = cs.agent_id
-WHERE a.runtime_id = $1 AND a.archived_at IS NOT NULL
-ORDER BY cs.id
-FOR UPDATE OF cs
-`
-
-func (q *Queries) LockChatSessionsByArchivedRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) ([]pgtype.UUID, error) {
- rows, err := q.db.Query(ctx, lockChatSessionsByArchivedRuntimeAgents, 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 lockChatSessionsBySystemRuntimeAgents = `-- name: LockChatSessionsBySystemRuntimeAgents :many
SELECT cs.id FROM chat_session cs
JOIN agent a ON a.id = cs.agent_id
diff --git a/server/pkg/db/generated/chat_pinned_agent.sql.go b/server/pkg/db/generated/chat_pinned_agent.sql.go
index 20eebc08b1..dceb4c564d 100644
--- a/server/pkg/db/generated/chat_pinned_agent.sql.go
+++ b/server/pkg/db/generated/chat_pinned_agent.sql.go
@@ -63,15 +63,17 @@ func (q *Queries) DeleteChatPinnedAgent(ctx context.Context, arg DeleteChatPinne
return err
}
-const deleteChatPinnedAgentsByArchivedRuntimeAgents = `-- name: DeleteChatPinnedAgentsByArchivedRuntimeAgents :exec
+const deleteChatPinnedAgentsBySystemRuntimeAgents = `-- name: DeleteChatPinnedAgentsBySystemRuntimeAgents :exec
DELETE FROM chat_pinned_agent
WHERE agent_id IN (
- SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL
+ SELECT id FROM agent WHERE runtime_id = $1 AND kind = 'system'
)
`
-func (q *Queries) DeleteChatPinnedAgentsByArchivedRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
- _, err := q.db.Exec(ctx, deleteChatPinnedAgentsByArchivedRuntimeAgents, runtimeID)
+// Scoped to the system agents a runtime delete hard-deletes. User agents keep
+// their pins: since MUL-5559 they survive their runtime as unbound agents.
+func (q *Queries) DeleteChatPinnedAgentsBySystemRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteChatPinnedAgentsBySystemRuntimeAgents, runtimeID)
return err
}
diff --git a/server/pkg/db/generated/issue_label.sql.go b/server/pkg/db/generated/issue_label.sql.go
index 6cb58c49f3..ba851e20f5 100644
--- a/server/pkg/db/generated/issue_label.sql.go
+++ b/server/pkg/db/generated/issue_label.sql.go
@@ -152,10 +152,10 @@ func (q *Queries) DeleteAgentLabelAssignmentsByLabel(ctx context.Context, labelI
return err
}
-const deleteAgentLabelAssignmentsByRuntime = `-- name: DeleteAgentLabelAssignmentsByRuntime :exec
+const deleteAgentLabelAssignmentsBySystemRuntimeAgents = `-- name: DeleteAgentLabelAssignmentsBySystemRuntimeAgents :exec
DELETE FROM agent_to_label
-WHERE agent_id IN (SELECT id FROM agent WHERE runtime_id = $1)
+WHERE agent_id IN (SELECT id FROM agent WHERE runtime_id = $1 AND kind = 'system')
`
// The single-entity cleanups above cover one agent/skill at a time. The runtime
@@ -163,11 +163,12 @@ WHERE agent_id IN (SELECT id FROM agent WHERE runtime_id = $1)
// owning agents disappear without passing through a per-entity delete.
// Workspace-wide cleanup lives in DeleteWorkspace so it is atomic with that
// workspace's existing multi-table teardown.
-// Runtime teardown hard-deletes every agent bound to the runtime (archived and
-// system; active agents are refused by a 409 guard). Clear their label links by
-// runtime so none survive the agent hard-delete.
-func (q *Queries) DeleteAgentLabelAssignmentsByRuntime(ctx context.Context, runtimeID pgtype.UUID) error {
- _, err := q.db.Exec(ctx, deleteAgentLabelAssignmentsByRuntime, runtimeID)
+// Runtime teardown hard-deletes the system agents bound to the runtime (user
+// agents are unbound and kept since MUL-5559). Clear only those agents' label
+// links so none survive the agent hard-delete — a surviving unbound agent must
+// keep its labels.
+func (q *Queries) DeleteAgentLabelAssignmentsBySystemRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteAgentLabelAssignmentsBySystemRuntimeAgents, runtimeID)
return err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index e332a30f4b..6a56381d34 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -195,6 +195,7 @@ type Autopilot struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
AssigneeType string `json:"assignee_type"`
ProjectID pgtype.UUID `json:"project_id"`
+ PauseReason pgtype.Text `json:"pause_reason"`
}
type AutopilotCollaborator struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 59652ee2f1..ef720f14a5 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -15,7 +15,7 @@ const cancelAgentTasksByRuntimeOrAgent = `-- name: CancelAgentTasksByRuntimeOrAg
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
- AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
@@ -38,6 +38,14 @@ type CancelAgentTasksByRuntimeOrAgentParams struct {
// poller (watchTaskCancellation) interrupts the running agent gracefully.
// Returns the affected rows so the caller can broadcast task:cancelled and
// reconcile per-agent status.
+//
+// The status list must cover EVERY non-terminal status, not just the ones the
+// daemon is actively working: 'deferred' (migration 128, comment-routing
+// escalation) was missing here and only went unnoticed because the runtime
+// delete used to cascade those rows away. Since MUL-5559 the runtime delete
+// unbinds history rows instead, and agent_task_queue_active_requires_runtime
+// rejects an active row without a runtime — so a missed status now surfaces as
+// a failed delete (runtime_delete_not_drained) instead of silent data loss.
func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg CancelAgentTasksByRuntimeOrAgentParams) ([]AgentTaskQueue, error) {
rows, err := q.db.Query(ctx, cancelAgentTasksByRuntimeOrAgent, arg.RuntimeIds, arg.AgentIds)
if err != nil {
@@ -121,17 +129,27 @@ func (q *Queries) CountActiveAgentsByRuntime(ctx context.Context, runtimeID pgty
return count, err
}
-const countActiveSquadsWithArchivedLeadersByRuntime = `-- name: CountActiveSquadsWithArchivedLeadersByRuntime :one
-SELECT count(*)
-FROM squad
-WHERE archived_at IS NULL
- AND leader_id IN (
- SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL
- )
+const countUndrainedTasksByRuntimeOrAgent = `-- name: CountUndrainedTasksByRuntimeOrAgent :one
+SELECT count(*) FROM agent_task_queue
+WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
+ AND completed_at IS NULL
`
-func (q *Queries) CountActiveSquadsWithArchivedLeadersByRuntime(ctx context.Context, runtimeID pgtype.UUID) (int64, error) {
- row := q.db.QueryRow(ctx, countActiveSquadsWithArchivedLeadersByRuntime, runtimeID)
+type CountUndrainedTasksByRuntimeOrAgentParams struct {
+ RuntimeIds []pgtype.UUID `json:"runtime_ids"`
+ AgentIds []pgtype.UUID `json:"agent_ids"`
+}
+
+// Belt-and-braces gate for the runtime-delete transaction: after cancelling,
+// every task on this runtime OR owned by an agent being unbound must be terminal
+// (completed_at IS NOT NULL) before the unbind UPDATE runs. The agent-side
+// predicate must mirror CancelAgentTasksByRuntimeOrAgent: a task can remain
+// pinned to another runtime after its agent moves. Non-zero means some
+// non-terminal status escaped the cancel query — the handler aborts with 409
+// runtime_delete_not_drained rather than letting the CHECK constraint turn it
+// into an opaque 500, and rather than deleting rows to make it go away.
+func (q *Queries) CountUndrainedTasksByRuntimeOrAgent(ctx context.Context, arg CountUndrainedTasksByRuntimeOrAgentParams) (int64, error) {
+ row := q.db.QueryRow(ctx, countUndrainedTasksByRuntimeOrAgent, arg.RuntimeIds, arg.AgentIds)
var count int64
err := row.Scan(&count)
return count, err
@@ -146,38 +164,15 @@ func (q *Queries) DeleteAgentRuntime(ctx context.Context, id pgtype.UUID) error
return err
}
-const deleteArchivedAgentsByRuntime = `-- name: DeleteArchivedAgentsByRuntime :exec
-DELETE FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL
-`
-
-func (q *Queries) DeleteArchivedAgentsByRuntime(ctx context.Context, runtimeID pgtype.UUID) error {
- _, err := q.db.Exec(ctx, deleteArchivedAgentsByRuntime, runtimeID)
- return err
-}
-
-const deleteSquadsByArchivedAgentsOnRuntime = `-- name: DeleteSquadsByArchivedAgentsOnRuntime :exec
-DELETE FROM squad
-WHERE leader_id IN (
- SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL
-)
- AND archived_at IS NOT NULL
-`
-
-// Removes archived squads whose leader_id references an archived agent on the
-// given runtime. Must run before DeleteArchivedAgentsByRuntime so the RESTRICT
-// FK on squad.leader_id does not block the agent deletion. Active squads are
-// handled separately by CountActiveSquadsWithArchivedLeadersByRuntime, which
-// returns a 409 until the caller archives them or assigns a new leader.
-func (q *Queries) DeleteSquadsByArchivedAgentsOnRuntime(ctx context.Context, runtimeID pgtype.UUID) error {
- _, err := q.db.Exec(ctx, deleteSquadsByArchivedAgentsOnRuntime, runtimeID)
- return err
-}
-
const deleteStaleOfflineRuntimes = `-- name: DeleteStaleOfflineRuntimes :many
DELETE FROM agent_runtime
WHERE status = 'offline'
AND last_seen_at < now() - make_interval(secs => $1::double precision)
- AND id NOT IN (SELECT DISTINCT runtime_id FROM agent)
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent
+ WHERE agent.runtime_id = agent_runtime.id
+ )
RETURNING id, workspace_id
`
@@ -627,33 +622,6 @@ func (q *Queries) ListAgentRuntimesByOwner(ctx context.Context, arg ListAgentRun
return items, nil
}
-const listArchivedAgentIDsByRuntime = `-- name: ListArchivedAgentIDsByRuntime :many
-SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL
-`
-
-// Companion to DeleteArchivedAgentsByRuntime: enumerates the archived agents
-// about to be hard-deleted so the runtime teardown can pause autopilots that
-// still point at them. Returns ids only — the caller only needs the set.
-func (q *Queries) ListArchivedAgentIDsByRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]pgtype.UUID, error) {
- rows, err := q.db.Query(ctx, listArchivedAgentIDsByRuntime, 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 listDaemonCustomNames = `-- name: ListDaemonCustomNames :many
SELECT custom_name FROM agent_runtime
WHERE workspace_id = $1
@@ -710,10 +678,9 @@ FOR UPDATE
// 2. concurrent UPDATE/DELETE of the runtime row itself (e.g. another
// delete attempt) waits for us to commit.
//
-// Combined with ListActiveAgentsByRuntimeForUpdate (which row-locks the
-// existing active set) this closes the plan-compare → archive race that
-// was possible at read-committed isolation between the snapshot and the
-// bulk archive.
+// Combined with ListUserAgentsByRuntimeForUpdate (which row-locks active and
+// archived user agents) this closes both plan drift and archived-agent restore
+// races under read-committed isolation.
func (q *Queries) LockAgentRuntime(ctx context.Context, id pgtype.UUID) (AgentRuntime, error) {
row := q.db.QueryRow(ctx, lockAgentRuntime, id)
var i AgentRuntime
@@ -833,25 +800,6 @@ func (q *Queries) MarkRuntimesOfflineByIDs(ctx context.Context, arg MarkRuntimes
return items, nil
}
-const pauseAutopilotsByAgentAssignees = `-- name: PauseAutopilotsByAgentAssignees :exec
-UPDATE autopilot
-SET status = 'paused', updated_at = now()
-WHERE status = 'active'
- AND assignee_type = 'agent'
- AND assignee_id = ANY($1::uuid[])
-`
-
-// Pauses every active autopilot whose agent assignee is in the supplied list.
-// Called before hard-deleting archived agents on runtime teardown so the rows
-// do not become dangling (autopilot.assignee_id no longer has an agent FK
-// since migration 096). Status='paused' makes the breakage visible in the UI
-// — operators can re-point the autopilot at a live agent or delete it —
-// rather than silently piling skipped runs.
-func (q *Queries) PauseAutopilotsByAgentAssignees(ctx context.Context, assigneeIds []pgtype.UUID) error {
- _, err := q.db.Exec(ctx, pauseAutopilotsByAgentAssignees, assigneeIds)
- return err
-}
-
const reassignAgentsToRuntime = `-- name: ReassignAgentsToRuntime :execrows
UPDATE agent
SET runtime_id = $1
@@ -1018,6 +966,94 @@ func (q *Queries) TouchAgentRuntimesLastSeenBatch(ctx context.Context, ids []pgt
return result.RowsAffected(), nil
}
+const unbindTasksFromRuntime = `-- name: UnbindTasksFromRuntime :execrows
+UPDATE agent_task_queue
+SET runtime_id = NULL
+WHERE runtime_id = $1 AND completed_at IS NOT NULL
+`
+
+// Detaches this runtime's task history so deleting the runtime row cannot
+// cascade it away (agent_task_queue.runtime_id is ON DELETE CASCADE, and
+// task_message / task_usage / task_token cascade from the task in turn).
+// Restricted to terminal rows: an active task must keep its runtime, per
+// agent_task_queue_active_requires_runtime. The caller runs
+// CancelAgentTasksByRuntimeOrAgent +
+// CountUndrainedTasksByRuntimeOrAgent first, so at this point "terminal" is
+// every row on the runtime.
+func (q *Queries) UnbindTasksFromRuntime(ctx context.Context, runtimeID pgtype.UUID) (int64, error) {
+ result, err := q.db.Exec(ctx, unbindTasksFromRuntime, runtimeID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const unbindUserAgentsFromRuntime = `-- name: UnbindUserAgentsFromRuntime :many
+UPDATE agent
+SET runtime_id = NULL, updated_at = now()
+WHERE runtime_id = $1 AND kind = 'user'
+RETURNING 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
+`
+
+// MUL-5559: the runtime-delete replacement for archive-then-hard-delete. Every
+// user agent bound to this runtime becomes unbound (runtime_id IS NULL) and
+// keeps its row, chats, labels, channel installations and autopilot config.
+//
+// Deliberately NOT filtered on archived_at: an agent archived earlier is just
+// as much the user's data as an active one, and hard-deleting it was the same
+// bug. Deliberately restricted to kind = 'user': system agents are invisible
+// execution infrastructure with no UI to rebind them (see
+// DeleteSystemAgentsByRuntime), so leaving them unbound would strand rows no
+// one can repair.
+func (q *Queries) UnbindUserAgentsFromRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]Agent, error) {
+ rows, err := q.db.Query(ctx, unbindUserAgentsFromRuntime, runtimeID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Agent{}
+ for rows.Next() {
+ var i Agent
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.AvatarUrl,
+ &i.RuntimeMode,
+ &i.RuntimeConfig,
+ &i.Visibility,
+ &i.Status,
+ &i.MaxConcurrentTasks,
+ &i.OwnerID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Description,
+ &i.RuntimeID,
+ &i.Instructions,
+ &i.ArchivedAt,
+ &i.ArchivedBy,
+ &i.CustomEnv,
+ &i.CustomArgs,
+ &i.McpConfig,
+ &i.Model,
+ &i.ThinkingLevel,
+ &i.ComposioToolkitAllowlist,
+ &i.PermissionMode,
+ &i.Kind,
+ &i.SystemKey,
+ &i.DisabledRuntimeSkills,
+ &i.ServiceTier,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const updateAgentRuntimeCustomName = `-- name: UpdateAgentRuntimeCustomName :one
UPDATE agent_runtime
SET custom_name = $1, updated_at = now()
diff --git a/server/pkg/db/generated/runtime_profile.sql.go b/server/pkg/db/generated/runtime_profile.sql.go
index 30cdb7f5ff..12cf9cd540 100644
--- a/server/pkg/db/generated/runtime_profile.sql.go
+++ b/server/pkg/db/generated/runtime_profile.sql.go
@@ -215,6 +215,8 @@ func (q *Queries) GetRuntimeProfileForWorkspace(ctx context.Context, arg GetRunt
const listAgentRuntimeIDsByProfile = `-- name: ListAgentRuntimeIDsByProfile :many
SELECT id FROM agent_runtime
WHERE profile_id = $1 AND workspace_id = $2
+ORDER BY id
+FOR UPDATE
`
type ListAgentRuntimeIDsByProfileParams struct {
@@ -327,6 +329,74 @@ func (q *Queries) ListRuntimeProfiles(ctx context.Context, workspaceID pgtype.UU
return items, nil
}
+const lockRuntimeProfileForDelete = `-- name: LockRuntimeProfileForDelete :one
+SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at FROM runtime_profile
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE
+`
+
+type LockRuntimeProfileForDeleteParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// See LockRuntimeProfileForRegistration. The stronger lock prevents a daemon
+// from registering another instance between the delete plan and commit.
+func (q *Queries) LockRuntimeProfileForDelete(ctx context.Context, arg LockRuntimeProfileForDeleteParams) (RuntimeProfile, error) {
+ row := q.db.QueryRow(ctx, lockRuntimeProfileForDelete, arg.ID, arg.WorkspaceID)
+ var i RuntimeProfile
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.DisplayName,
+ &i.ProtocolFamily,
+ &i.CommandName,
+ &i.Description,
+ &i.FixedArgs,
+ &i.Visibility,
+ &i.CreatedBy,
+ &i.Enabled,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const lockRuntimeProfileForRegistration = `-- name: LockRuntimeProfileForRegistration :one
+SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at FROM runtime_profile
+WHERE id = $1 AND workspace_id = $2
+FOR KEY SHARE
+`
+
+type LockRuntimeProfileForRegistrationParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Serializes daemon registration with profile deletion. Registration holds a
+// KEY SHARE lock until its runtime row is committed; profile deletion takes an
+// UPDATE lock, then locks the profile's runtime rows. Whichever starts first
+// wins, so deletion cannot miss a runtime inserted from a stale profile read.
+func (q *Queries) LockRuntimeProfileForRegistration(ctx context.Context, arg LockRuntimeProfileForRegistrationParams) (RuntimeProfile, error) {
+ row := q.db.QueryRow(ctx, lockRuntimeProfileForRegistration, arg.ID, arg.WorkspaceID)
+ var i RuntimeProfile
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.DisplayName,
+ &i.ProtocolFamily,
+ &i.CommandName,
+ &i.Description,
+ &i.FixedArgs,
+ &i.Visibility,
+ &i.CreatedBy,
+ &i.Enabled,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
const updateRuntimeProfile = `-- name: UpdateRuntimeProfile :one
UPDATE runtime_profile
SET display_name = COALESCE($1, display_name),
diff --git a/server/pkg/db/generated/squad.sql.go b/server/pkg/db/generated/squad.sql.go
index ecb4f0bd70..620a9f4264 100644
--- a/server/pkg/db/generated/squad.sql.go
+++ b/server/pkg/db/generated/squad.sql.go
@@ -563,6 +563,75 @@ func (q *Queries) ListSquadsByMember(ctx context.Context, arg ListSquadsByMember
return items, nil
}
+const lockSquadForAutopilotAssignment = `-- name: LockSquadForAutopilotAssignment :one
+SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions FROM squad
+WHERE id = $1 AND workspace_id = $2
+FOR SHARE
+`
+
+type LockSquadForAutopilotAssignmentParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Stabilizes the squad-to-leader resolution while an active Autopilot is
+// created, retargeted, or resumed. FOR SHARE conflicts with an ordinary
+// leader_id update, so the caller subsequently locks the same leader Agent
+// whose row Runtime teardown serializes against.
+func (q *Queries) LockSquadForAutopilotAssignment(ctx context.Context, arg LockSquadForAutopilotAssignmentParams) (Squad, error) {
+ row := q.db.QueryRow(ctx, lockSquadForAutopilotAssignment, arg.ID, arg.WorkspaceID)
+ var i Squad
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.LeaderID,
+ &i.CreatorID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.ArchivedAt,
+ &i.ArchivedBy,
+ &i.AvatarUrl,
+ &i.Instructions,
+ )
+ return i, err
+}
+
+const lockSquadForUpdate = `-- name: LockSquadForUpdate :one
+SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions FROM squad
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE
+`
+
+type LockSquadForUpdateParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Squad leader changes take the exclusive side of the same lock used by
+// Autopilot assignment. The handler then locks the proposed leader Agent and
+// pauses active squad Autopilots when that Agent is unbound.
+func (q *Queries) LockSquadForUpdate(ctx context.Context, arg LockSquadForUpdateParams) (Squad, error) {
+ row := q.db.QueryRow(ctx, lockSquadForUpdate, arg.ID, arg.WorkspaceID)
+ var i Squad
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.LeaderID,
+ &i.CreatorID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.ArchivedAt,
+ &i.ArchivedBy,
+ &i.AvatarUrl,
+ &i.Instructions,
+ )
+ return i, err
+}
+
const removeSquadMember = `-- name: RemoveSquadMember :execrows
DELETE FROM squad_member
WHERE squad_id = $1 AND member_type = $2 AND member_id = $3
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 5967c0c4f2..752fea39f5 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -38,6 +38,20 @@ FOR UPDATE;
SELECT * FROM agent
WHERE id = $1 AND workspace_id = $2 AND kind = 'user';
+-- name: LockAgentForAutopilotAssignment :one
+-- Serializes creating, retargeting, or resuming an active Autopilot with
+-- Runtime teardown. Teardown takes FOR UPDATE on this same Agent row before it
+-- clears runtime_id and pauses matching Autopilots. FOR SHARE also stabilizes
+-- runtime_id and archived_at against concurrent ordinary Agent updates. The
+-- shared lock makes the
+-- two outcomes exhaustive:
+-- * assignment commits first, then teardown sees and pauses it; or
+-- * teardown commits first, then assignment re-reads runtime_id=NULL and
+-- rejects the active Autopilot.
+SELECT * FROM agent
+WHERE id = $1 AND workspace_id = $2 AND kind = 'user'
+FOR SHARE;
+
-- name: CreateAgent :one
INSERT INTO agent (
workspace_id, name, description, avatar_url, runtime_mode,
@@ -214,7 +228,7 @@ RETURNING *;
-- Returns every non-archived agent bound to a runtime. Backs the cascade
-- delete dialog: when DELETE /api/runtimes/:id refuses with
-- runtime_has_active_agents, the response carries this list so the front-end
--- can render exactly the agents that will be archived if the user confirms,
+-- can render exactly the agents that will be unbound if the user confirms,
-- and so the cascade endpoint's expected_active_agent_ids check has a stable
-- snapshot to compare against. Ordered by name for a deterministic display.
SELECT * FROM agent
@@ -228,13 +242,23 @@ ORDER BY name ASC;
-- LockAgentRuntime, which holds the runtime row exclusively to also
-- block FK-validated INSERTs / runtime_id updates that would otherwise
-- add a new agent to the runtime mid-cascade. Together they guarantee
--- that the set we compared against expected_active_agent_ids is exactly
--- the set ArchiveAgentsByIDs will operate on — no race window.
+-- that the set we compared against expected_active_agent_ids is stable.
SELECT * FROM agent
WHERE runtime_id = $1 AND archived_at IS NULL AND kind = 'user'
ORDER BY name ASC
FOR UPDATE;
+-- 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
+-- after confirmation and then be silently unbound. Runtime/profile delete
+-- locks the parent runtime first (blocking new FK references), then calls this
+-- in stable ID order (blocking restore/archive/move on existing rows).
+SELECT * FROM agent
+WHERE runtime_id = $1 AND kind = 'user'
+ORDER BY id
+FOR UPDATE;
+
-- name: RestoreAgent :one
UPDATE agent SET archived_at = NULL, archived_by = NULL, updated_at = now()
WHERE id = $1
diff --git a/server/pkg/db/queries/agent_invocation_target.sql b/server/pkg/db/queries/agent_invocation_target.sql
index 0b4114e7a6..fbddb734db 100644
--- a/server/pkg/db/queries/agent_invocation_target.sql
+++ b/server/pkg/db/queries/agent_invocation_target.sql
@@ -43,13 +43,18 @@ WHERE ait.agent_id = a.id
AND ait.target_type = 'member'
AND ait.target_id = @target_id;
--- name: DeleteAgentInvocationTargetsByArchivedRuntimeAgents :exec
+-- name: DeleteAgentInvocationTargetsBySystemRuntimeAgents :exec
-- Application-layer replacement for the (deliberately absent) agent_id ON
--- DELETE CASCADE: removes invocation targets for the archived agents a runtime
+-- DELETE CASCADE: removes invocation targets for the system agents a runtime
-- delete is about to hard-delete. MUST run in the same tx as, and BEFORE,
--- DeleteArchivedAgentsByRuntime so no orphan target rows survive the agent
--- rows they belonged to. Mirrors the agent hard-delete predicate exactly.
+-- DeleteSystemAgentsByRuntime so no orphan target rows survive the agent rows
+-- they belonged to. Mirrors the agent hard-delete predicate exactly.
+--
+-- Scoped to kind = 'system' since MUL-5559: user agents are no longer deleted
+-- with their runtime (they are unbound and keep their configuration), so
+-- clearing THEIR invocation targets here would silently strip a surviving
+-- agent's allow-list.
DELETE FROM agent_invocation_target
WHERE agent_id IN (
- SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL
+ SELECT id FROM agent WHERE runtime_id = $1 AND kind = 'system'
);
diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sql
index 141591b5f6..57c5bcab15 100644
--- a/server/pkg/db/queries/autopilot.sql
+++ b/server/pkg/db/queries/autopilot.sql
@@ -44,6 +44,14 @@ WHERE id = $1;
SELECT * FROM autopilot
WHERE id = $1 AND workspace_id = $2;
+-- name: LockAutopilotForUpdate :one
+-- UpdateAutopilot is a patch assembled from a pre-transaction snapshot. Lock
+-- and compare that row before applying the patch so a concurrent retarget or
+-- Runtime teardown cannot be overwritten by stale assignee/status fields.
+SELECT * FROM autopilot
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE;
+
-- name: CreateAutopilot :one
INSERT INTO autopilot (
workspace_id, title, description, assignee_type, assignee_id,
@@ -62,6 +70,10 @@ UPDATE autopilot SET
assignee_type = COALESCE(sqlc.narg('assignee_type'), assignee_type),
assignee_id = COALESCE(sqlc.narg('assignee_id')::uuid, assignee_id),
status = COALESCE(sqlc.narg('status'), status),
+ pause_reason = CASE
+ WHEN sqlc.narg('status')::text IS NOT NULL THEN NULL
+ ELSE pause_reason
+ END,
execution_mode = COALESCE(sqlc.narg('execution_mode'), execution_mode),
issue_title_template = sqlc.narg('issue_title_template'),
project_id = sqlc.narg('project_id'),
@@ -71,9 +83,46 @@ RETURNING *;
-- name: ArchiveAutopilot :exec
UPDATE autopilot
-SET status = 'archived', updated_at = now()
+SET status = 'archived', pause_reason = NULL, updated_at = now()
WHERE id = $1;
+-- name: PauseAutopilotsByUnboundAgents :many
+-- A runtime delete is a persistent admission failure, not a per-tick event.
+-- Pause direct-agent automations and squad automations whose leader was
+-- unbound, preserving the full configuration for an explicit resume after
+-- rebind. Restrict to active so repeated teardown/retry is idempotent.
+UPDATE autopilot a
+SET status = 'paused',
+ pause_reason = 'agent_runtime_required',
+ updated_at = now()
+WHERE a.status = 'active'
+ AND (
+ (a.assignee_type = 'agent' AND a.assignee_id = ANY(@agent_ids::uuid[]))
+ OR (
+ a.assignee_type = 'squad'
+ AND EXISTS (
+ SELECT 1
+ FROM squad s
+ WHERE s.id = a.assignee_id
+ AND s.leader_id = ANY(@agent_ids::uuid[])
+ )
+ )
+ )
+RETURNING a.*;
+
+-- name: PauseAutopilotsByUnrunnableSquad :many
+-- Rotating a squad to an already-unbound leader has the same persistent
+-- admission failure as Runtime teardown. Pause only automations assigned to
+-- this squad; direct automations targeting that Agent are unrelated.
+UPDATE autopilot
+SET status = 'paused',
+ pause_reason = 'agent_runtime_required',
+ updated_at = now()
+WHERE status = 'active'
+ AND assignee_type = 'squad'
+ AND assignee_id = @squad_id
+RETURNING *;
+
-- name: UpdateAutopilotLastRunAt :exec
UPDATE autopilot SET last_run_at = now(), updated_at = now()
WHERE id = $1;
@@ -480,7 +529,7 @@ ORDER BY s.failed DESC, a.id ASC;
-- raced first), letting the caller treat that as a benign no-op rather than
-- an error.
UPDATE autopilot
-SET status = 'paused', updated_at = now()
+SET status = 'paused', pause_reason = NULL, updated_at = now()
WHERE id = $1 AND status = 'active'
RETURNING *;
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index ad1270060e..bac93e83fc 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -197,19 +197,22 @@ detached_audit AS (
)
SELECT id FROM dead;
--- name: DeleteChannelInstallationsByArchivedRuntimeAgents :exec
+-- name: DeleteChannelInstallationsBySystemRuntimeAgents :exec
-- Application-layer replacement for the (deliberately absent, MUL-3515 §4)
--- workspace/agent ON DELETE CASCADE: on runtime teardown, before the archived
+-- workspace/agent ON DELETE CASCADE: on runtime teardown, before the system
-- agents are hard-deleted, remove every channel installation they own — plus all
-- of each installation's dependent rows — so no orphaned installation keeps
-- occupying its bot's (channel_type, app_id) routing slot after its agent is gone
--- (#4810). MUST run in the same tx as, and BEFORE, DeleteArchivedAgentsByRuntime.
--- Mirrors the agent hard-delete predicate (runtime_id, archived_at IS NOT NULL)
--- exactly.
+-- (#4810). MUST run in the same tx as, and BEFORE, DeleteSystemAgentsByRuntime.
+-- Mirrors the agent hard-delete predicate (runtime_id, kind = 'system') exactly.
+--
+-- Scoped to kind = 'system' since MUL-5559: a user agent now survives its
+-- runtime's deletion as an unbound agent, so tearing down its installations
+-- here would take a working bot away from an agent that is still there.
WITH doomed AS (
SELECT id FROM channel_installation
WHERE agent_id IN (
- SELECT id FROM agent WHERE runtime_id = sqlc.arg('runtime_id') AND archived_at IS NOT NULL
+ SELECT id FROM agent WHERE runtime_id = sqlc.arg('runtime_id') AND kind = 'system'
)
),
cleared_chat_sessions AS (
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 9700680f23..a96e41cb2e 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -632,13 +632,6 @@ WHERE workspace_id = $1
ORDER BY id
FOR UPDATE;
--- name: LockChatSessionsByArchivedRuntimeAgents :many
-SELECT cs.id FROM chat_session cs
-JOIN agent a ON a.id = cs.agent_id
-WHERE a.runtime_id = $1 AND a.archived_at IS NOT NULL
-ORDER BY cs.id
-FOR UPDATE OF cs;
-
-- name: LockChatSessionsBySystemRuntimeAgents :many
SELECT cs.id FROM chat_session cs
JOIN agent a ON a.id = cs.agent_id
@@ -646,24 +639,15 @@ WHERE a.runtime_id = $1 AND a.kind = 'system'
ORDER BY cs.id
FOR UPDATE OF cs;
--- name: DeleteChatDraftRestoresByArchivedRuntimeAgents :exec
--- chat_session cascades from agent, so hard-deleting a runtime's archived agents
+-- name: DeleteChatDraftRestoresBySystemRuntimeAgents :exec
+-- chat_session cascades from agent, so hard-deleting a runtime's system agents
-- silently drops their sessions — and, without an FK, would strand the pending
-- restores (which still hold the user's prompt text) forever. Prune them in the
-- same tx, BEFORE the agent rows go: the join below needs them. Mirrors
--- DeleteChannelInstallationsByArchivedRuntimeAgents.
-DELETE FROM chat_draft_restore
-WHERE chat_session_id IN (
- SELECT cs.id FROM chat_session cs
- JOIN agent a ON a.id = cs.agent_id
- WHERE a.runtime_id = $1 AND a.archived_at IS NOT NULL
-);
-
--- name: DeleteChatDraftRestoresBySystemRuntimeAgents :exec
--- Same cascade, for the system agents a runtime teardown also hard-deletes
--- (DeleteSystemAgentsByRuntime). Split from the archived-agent prune because the
--- runtime-profile teardown deletes only archived agents: pruning system-agent
--- sessions there would destroy restores whose session survives.
+-- DeleteChannelInstallationsBySystemRuntimeAgents.
+--
+-- Only system agents are hard-deleted on runtime teardown since MUL-5559; user
+-- agents (archived or not) are unbound and keep their sessions and restores.
DELETE FROM chat_draft_restore
WHERE chat_session_id IN (
SELECT cs.id FROM chat_session cs
diff --git a/server/pkg/db/queries/chat_pinned_agent.sql b/server/pkg/db/queries/chat_pinned_agent.sql
index 7b86a7207b..29224ef286 100644
--- a/server/pkg/db/queries/chat_pinned_agent.sql
+++ b/server/pkg/db/queries/chat_pinned_agent.sql
@@ -20,10 +20,12 @@ WHERE workspace_id = $1 AND user_id = $2 AND agent_id = $3;
DELETE FROM chat_pinned_agent
WHERE workspace_id = $1;
--- name: DeleteChatPinnedAgentsByArchivedRuntimeAgents :exec
+-- name: DeleteChatPinnedAgentsBySystemRuntimeAgents :exec
+-- Scoped to the system agents a runtime delete hard-deletes. User agents keep
+-- their pins: since MUL-5559 they survive their runtime as unbound agents.
DELETE FROM chat_pinned_agent
WHERE agent_id IN (
- SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL
+ SELECT id FROM agent WHERE runtime_id = $1 AND kind = 'system'
);
-- name: GetMaxChatPinnedAgentPosition :one
diff --git a/server/pkg/db/queries/issue_label.sql b/server/pkg/db/queries/issue_label.sql
index 7a2b29da01..a69cc23130 100644
--- a/server/pkg/db/queries/issue_label.sql
+++ b/server/pkg/db/queries/issue_label.sql
@@ -61,12 +61,13 @@ DELETE FROM skill_to_label WHERE skill_id = $1;
-- Workspace-wide cleanup lives in DeleteWorkspace so it is atomic with that
-- workspace's existing multi-table teardown.
--- name: DeleteAgentLabelAssignmentsByRuntime :exec
--- Runtime teardown hard-deletes every agent bound to the runtime (archived and
--- system; active agents are refused by a 409 guard). Clear their label links by
--- runtime so none survive the agent hard-delete.
+-- name: DeleteAgentLabelAssignmentsBySystemRuntimeAgents :exec
+-- Runtime teardown hard-deletes the system agents bound to the runtime (user
+-- agents are unbound and kept since MUL-5559). Clear only those agents' label
+-- links so none survive the agent hard-delete — a surviving unbound agent must
+-- keep its labels.
DELETE FROM agent_to_label
-WHERE agent_id IN (SELECT id FROM agent WHERE runtime_id = $1);
+WHERE agent_id IN (SELECT id FROM agent WHERE runtime_id = $1 AND kind = 'system');
-- name: AttachLabelToIssue :exec
-- Workspace-guarded INSERT: the WHERE EXISTS clauses ensure both the issue
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index 6daf95f347..007639ed18 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -26,10 +26,9 @@ WHERE id = ANY(@ids::uuid[]);
-- our transaction finishes; and
-- 2. concurrent UPDATE/DELETE of the runtime row itself (e.g. another
-- delete attempt) waits for us to commit.
--- Combined with ListActiveAgentsByRuntimeForUpdate (which row-locks the
--- existing active set) this closes the plan-compare → archive race that
--- was possible at read-committed isolation between the snapshot and the
--- bulk archive.
+-- Combined with ListUserAgentsByRuntimeForUpdate (which row-locks active and
+-- archived user agents) this closes both plan drift and archived-agent restore
+-- races under read-committed isolation.
SELECT * FROM agent_runtime
WHERE id = $1
FOR UPDATE;
@@ -272,10 +271,60 @@ RETURNING id, workspace_id, owner_id, daemon_id, provider;
-- poller (watchTaskCancellation) interrupts the running agent gracefully.
-- Returns the affected rows so the caller can broadcast task:cancelled and
-- reconcile per-agent status.
+--
+-- The status list must cover EVERY non-terminal status, not just the ones the
+-- daemon is actively working: 'deferred' (migration 128, comment-routing
+-- escalation) was missing here and only went unnoticed because the runtime
+-- delete used to cascade those rows away. Since MUL-5559 the runtime delete
+-- unbinds history rows instead, and agent_task_queue_active_requires_runtime
+-- rejects an active row without a runtime — so a missed status now surfaces as
+-- a failed delete (runtime_delete_not_drained) instead of silent data loss.
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY(@runtime_ids::uuid[]) OR agent_id = ANY(@agent_ids::uuid[]))
- AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+RETURNING *;
+
+-- name: CountUndrainedTasksByRuntimeOrAgent :one
+-- Belt-and-braces gate for the runtime-delete transaction: after cancelling,
+-- every task on this runtime OR owned by an agent being unbound must be terminal
+-- (completed_at IS NOT NULL) before the unbind UPDATE runs. The agent-side
+-- predicate must mirror CancelAgentTasksByRuntimeOrAgent: a task can remain
+-- pinned to another runtime after its agent moves. Non-zero means some
+-- non-terminal status escaped the cancel query — the handler aborts with 409
+-- runtime_delete_not_drained rather than letting the CHECK constraint turn it
+-- into an opaque 500, and rather than deleting rows to make it go away.
+SELECT count(*) FROM agent_task_queue
+WHERE (runtime_id = ANY(@runtime_ids::uuid[]) OR agent_id = ANY(@agent_ids::uuid[]))
+ AND completed_at IS NULL;
+
+-- name: UnbindTasksFromRuntime :execrows
+-- Detaches this runtime's task history so deleting the runtime row cannot
+-- cascade it away (agent_task_queue.runtime_id is ON DELETE CASCADE, and
+-- task_message / task_usage / task_token cascade from the task in turn).
+-- Restricted to terminal rows: an active task must keep its runtime, per
+-- agent_task_queue_active_requires_runtime. The caller runs
+-- CancelAgentTasksByRuntimeOrAgent +
+-- CountUndrainedTasksByRuntimeOrAgent first, so at this point "terminal" is
+-- every row on the runtime.
+UPDATE agent_task_queue
+SET runtime_id = NULL
+WHERE runtime_id = $1 AND completed_at IS NOT NULL;
+
+-- name: UnbindUserAgentsFromRuntime :many
+-- MUL-5559: the runtime-delete replacement for archive-then-hard-delete. Every
+-- user agent bound to this runtime becomes unbound (runtime_id IS NULL) and
+-- keeps its row, chats, labels, channel installations and autopilot config.
+--
+-- Deliberately NOT filtered on archived_at: an agent archived earlier is just
+-- as much the user's data as an active one, and hard-deleting it was the same
+-- bug. Deliberately restricted to kind = 'user': system agents are invisible
+-- execution infrastructure with no UI to rebind them (see
+-- DeleteSystemAgentsByRuntime), so leaving them unbound would strand rows no
+-- one can repair.
+UPDATE agent
+SET runtime_id = NULL, updated_at = now()
+WHERE runtime_id = $1 AND kind = 'user'
RETURNING *;
-- name: DeleteAgentRuntime :exec
@@ -290,48 +339,6 @@ DELETE FROM agent WHERE runtime_id = $1 AND kind = 'system';
-- name: CountActiveAgentsByRuntime :one
SELECT count(*) FROM agent WHERE runtime_id = $1 AND archived_at IS NULL;
--- name: CountActiveSquadsWithArchivedLeadersByRuntime :one
-SELECT count(*)
-FROM squad
-WHERE archived_at IS NULL
- AND leader_id IN (
- SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL
- );
-
--- name: DeleteArchivedAgentsByRuntime :exec
-DELETE FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL;
-
--- name: PauseAutopilotsByAgentAssignees :exec
--- Pauses every active autopilot whose agent assignee is in the supplied list.
--- Called before hard-deleting archived agents on runtime teardown so the rows
--- do not become dangling (autopilot.assignee_id no longer has an agent FK
--- since migration 096). Status='paused' makes the breakage visible in the UI
--- — operators can re-point the autopilot at a live agent or delete it —
--- rather than silently piling skipped runs.
-UPDATE autopilot
-SET status = 'paused', updated_at = now()
-WHERE status = 'active'
- AND assignee_type = 'agent'
- AND assignee_id = ANY(@assignee_ids::uuid[]);
-
--- name: ListArchivedAgentIDsByRuntime :many
--- Companion to DeleteArchivedAgentsByRuntime: enumerates the archived agents
--- about to be hard-deleted so the runtime teardown can pause autopilots that
--- still point at them. Returns ids only — the caller only needs the set.
-SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL;
-
--- name: DeleteSquadsByArchivedAgentsOnRuntime :exec
--- Removes archived squads whose leader_id references an archived agent on the
--- given runtime. Must run before DeleteArchivedAgentsByRuntime so the RESTRICT
--- FK on squad.leader_id does not block the agent deletion. Active squads are
--- handled separately by CountActiveSquadsWithArchivedLeadersByRuntime, which
--- returns a 409 until the caller archives them or assigns a new leader.
-DELETE FROM squad
-WHERE leader_id IN (
- SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL
-)
- AND archived_at IS NOT NULL;
-
-- name: FindLegacyRuntimesByDaemonID :many
-- Looks up runtime rows keyed on a prior (hostname-derived) daemon_id. Used
-- at register-time to find rows owned by the same machine under its old
@@ -383,5 +390,9 @@ WHERE id = $1;
DELETE FROM agent_runtime
WHERE status = 'offline'
AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision)
- AND id NOT IN (SELECT DISTINCT runtime_id FROM agent)
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent
+ WHERE agent.runtime_id = agent_runtime.id
+ )
RETURNING id, workspace_id;
diff --git a/server/pkg/db/queries/runtime_profile.sql b/server/pkg/db/queries/runtime_profile.sql
index a51e352cc5..c7ab935b63 100644
--- a/server/pkg/db/queries/runtime_profile.sql
+++ b/server/pkg/db/queries/runtime_profile.sql
@@ -24,6 +24,22 @@ WHERE id = $1;
SELECT * FROM runtime_profile
WHERE id = $1 AND workspace_id = $2;
+-- name: LockRuntimeProfileForRegistration :one
+-- Serializes daemon registration with profile deletion. Registration holds a
+-- KEY SHARE lock until its runtime row is committed; profile deletion takes an
+-- UPDATE lock, then locks the profile's runtime rows. Whichever starts first
+-- wins, so deletion cannot miss a runtime inserted from a stale profile read.
+SELECT * FROM runtime_profile
+WHERE id = $1 AND workspace_id = $2
+FOR KEY SHARE;
+
+-- name: LockRuntimeProfileForDelete :one
+-- See LockRuntimeProfileForRegistration. The stronger lock prevents a daemon
+-- from registering another instance between the delete plan and commit.
+SELECT * FROM runtime_profile
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE;
+
-- name: ListRuntimeProfiles :many
SELECT * FROM runtime_profile
WHERE workspace_id = $1
@@ -80,4 +96,6 @@ WHERE ar.profile_id = $1 AND ar.workspace_id = $2 AND a.archived_at IS NULL;
-- removing each runtime row — agent.runtime_id is ON DELETE RESTRICT, so a
-- bare delete would 500 whenever an archived agent still references the row.
SELECT id FROM agent_runtime
-WHERE profile_id = $1 AND workspace_id = $2;
+WHERE profile_id = $1 AND workspace_id = $2
+ORDER BY id
+FOR UPDATE;
diff --git a/server/pkg/db/queries/squad.sql b/server/pkg/db/queries/squad.sql
index edc7aa36ac..b89f9cf701 100644
--- a/server/pkg/db/queries/squad.sql
+++ b/server/pkg/db/queries/squad.sql
@@ -9,6 +9,23 @@ SELECT * FROM squad WHERE id = $1;
-- name: GetSquadInWorkspace :one
SELECT * FROM squad WHERE id = $1 AND workspace_id = $2;
+-- name: LockSquadForAutopilotAssignment :one
+-- Stabilizes the squad-to-leader resolution while an active Autopilot is
+-- created, retargeted, or resumed. FOR SHARE conflicts with an ordinary
+-- leader_id update, so the caller subsequently locks the same leader Agent
+-- whose row Runtime teardown serializes against.
+SELECT * FROM squad
+WHERE id = $1 AND workspace_id = $2
+FOR SHARE;
+
+-- name: LockSquadForUpdate :one
+-- Squad leader changes take the exclusive side of the same lock used by
+-- Autopilot assignment. The handler then locks the proposed leader Agent and
+-- pauses active squad Autopilots when that Agent is unbound.
+SELECT * FROM squad
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE;
+
-- name: ListSquads :many
SELECT * FROM squad WHERE workspace_id = $1 AND archived_at IS NULL ORDER BY created_at ASC;