Skip to content

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

Go

feat(runtimes): cascade-archive agents on runtime delete (MUL-2667) (#3266)

LinYushenbf8a346cf0c9
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index cb84074e5f..92f9907fce 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -853,6 +853,24 @@ export class ApiClient {
await this.fetch(`/api/runtimes/${runtimeId}`, { method: "DELETE" });
}
+ // Cascade 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(
+ runtimeId: string,
+ expectedActiveAgentIds: string[],
+ ): Promise<{ status: string; agents_archived: number; tasks_cancelled: number }> {
+ return this.fetch(`/api/runtimes/${runtimeId}/archive-agents-and-delete`, {
+ method: "POST",
+ body: JSON.stringify({ expected_active_agent_ids: expectedActiveAgentIds }),
+ });
+ }
+
async updateRuntime(
runtimeId: string,
patch: { visibility?: "private" | "public" },
diff --git a/packages/core/runtimes/mutations.ts b/packages/core/runtimes/mutations.ts
index ee3af2a0b8..2c41777c88 100644
--- a/packages/core/runtimes/mutations.ts
+++ b/packages/core/runtimes/mutations.ts
@@ -1,6 +1,8 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "../api";
import { runtimeKeys } from "./queries";
+import { workspaceKeys } from "../workspace/queries";
+import { agentTaskSnapshotKeys } from "../agents/queries";
export function useDeleteRuntime(wsId: string) {
const qc = useQueryClient();
@@ -12,6 +14,34 @@ export function useDeleteRuntime(wsId: string) {
});
}
+// Cascade-mode 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) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: ({
+ runtimeId,
+ expectedActiveAgentIds,
+ }: {
+ runtimeId: string;
+ expectedActiveAgentIds: string[];
+ }) => api.archiveAgentsAndDeleteRuntime(runtimeId, expectedActiveAgentIds),
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ qc.invalidateQueries({ queryKey: agentTaskSnapshotKeys.all(wsId) });
+ },
+ });
+}
+
// useUpdateRuntime patches editable fields on a runtime (visibility).
// Invalidates the runtime list so the picker disabled-state recomputes.
export function useUpdateRuntime(wsId: string) {
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.json
index 287181259b..0f36a49839 100644
--- a/packages/views/locales/en/runtimes.json
+++ b/packages/views/locales/en/runtimes.json
@@ -111,11 +111,45 @@
"visibility_toast_updated": "Visibility set to {{visibility}}",
"visibility_toast_failed": "Failed to update visibility",
"delete_dialog": {
- "title": "Delete Runtime",
- "description": "Are you sure you want to delete \"{{name}}\"? This action cannot be undone.",
- "cancel": "Cancel",
- "confirm": "Delete",
- "deleting": "Deleting..."
+ "light": {
+ "title": "Delete Runtime?",
+ "description": "Are you sure you want to delete \"{{name}}\"? This action cannot be undone.",
+ "cancel": "Cancel",
+ "confirm": "Delete runtime",
+ "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.",
+ "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.",
+ "cancel": "Cancel",
+ "confirm_one": "Archive {{count}} agent and delete runtime",
+ "confirm_other": "Archive {{count}} agents and delete runtime",
+ "submitting": "Archiving and deleting...",
+ "self_healing_blocked_toast": "This runtime is managed by a running local daemon and will re-register itself.",
+ "delete_failed_toast": "Failed to delete runtime",
+ "table": {
+ "header_agent": "Agent",
+ "header_owner": "Owner",
+ "header_status": "Status",
+ "header_visibility": "Visibility",
+ "header_model": "Model",
+ "owner_self": "You",
+ "owner_unassigned": "—",
+ "model_unset": "—",
+ "presence_unknown": "—",
+ "workload_idle": "Idle",
+ "workload_working": "Working",
+ "workload_queued": "Queued",
+ "visibility_workspace": "Workspace",
+ "visibility_private": "Private"
+ }
+ }
},
"toast_deleted": "Runtime deleted",
"toast_delete_failed": "Failed to delete runtime",
diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.json
index 9139c97004..c84ef12ac4 100644
--- a/packages/views/locales/zh-Hans/runtimes.json
+++ b/packages/views/locales/zh-Hans/runtimes.json
@@ -106,11 +106,42 @@
"visibility_toast_updated": "可见性已设为「{{visibility}}」",
"visibility_toast_failed": "更新可见性失败",
"delete_dialog": {
- "title": "删除运行时",
- "description": "确定要删除\"{{name}}\"吗?此操作不可撤销。",
- "cancel": "取消",
- "confirm": "删除",
- "deleting": "删除中..."
+ "light": {
+ "title": "删除运行时?",
+ "description": "确定要删除「{{name}}」吗?此操作无法撤销。",
+ "cancel": "取消",
+ "confirm": "删除运行时",
+ "submitting": "删除中..."
+ },
+ "cascade": {
+ "title_other": "归档 {{count}} 个智能体并删除该运行时?",
+ "description": "删除「{{name}}」。下列智能体将被归档并从可用工作流中移除,其排队中或运行中的 task 会被取消,随后运行时本身会被删除。",
+ "warning": "此操作具有破坏性。归档的智能体将从可用工作流中移除,其排队中或运行中的 task 会被取消。",
+ "notice_runtime_has_active_agents": "自打开此弹窗后,又有新的活动智能体加入。请确认新方案后继续。",
+ "notice_runtime_delete_plan_changed": "在弹窗打开期间,活动智能体集合发生了变化。请确认新方案后继续。",
+ "checkbox_other": "我已了解:这 {{count}} 个智能体将被归档,其排队中或运行中的 task 会被取消。",
+ "cancel": "取消",
+ "confirm_other": "归档 {{count}} 个智能体并删除运行时",
+ "submitting": "正在归档并删除...",
+ "self_healing_blocked_toast": "该运行时由正在运行的本地守护进程托管,删除后会自动重新注册。",
+ "delete_failed_toast": "删除运行时失败",
+ "table": {
+ "header_agent": "智能体",
+ "header_owner": "所有者",
+ "header_status": "状态",
+ "header_visibility": "可见性",
+ "header_model": "模型",
+ "owner_self": "你",
+ "owner_unassigned": "—",
+ "model_unset": "—",
+ "presence_unknown": "—",
+ "workload_idle": "空闲",
+ "workload_working": "运行中",
+ "workload_queued": "排队中",
+ "visibility_workspace": "工作区",
+ "visibility_private": "私有"
+ }
+ }
},
"toast_deleted": "已删除运行时",
"toast_delete_failed": "删除运行时失败",
diff --git a/packages/views/runtimes/components/delete-runtime-dialog.test.tsx b/packages/views/runtimes/components/delete-runtime-dialog.test.tsx
new file mode 100644
index 0000000000..40907fdf88
--- /dev/null
+++ b/packages/views/runtimes/components/delete-runtime-dialog.test.tsx
@@ -0,0 +1,321 @@
+// @vitest-environment jsdom
+
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import type { Agent, AgentRuntime } from "@multica/core/types";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../../locales/en/common.json";
+import enRuntimes from "../../locales/en/runtimes.json";
+import enAgents from "../../locales/en/agents.json";
+
+const TEST_RESOURCES = {
+ en: { common: enCommon, runtimes: enRuntimes, agents: enAgents },
+};
+
+// ApiError mirrors the production export. The dialog's parseActiveAgentsConflict
+// uses an `instanceof` check, so the class identity must match the one the
+// 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(() => {
+ class ApiError extends Error {
+ status: number;
+ body: unknown;
+ constructor(message: string, status: number, body: unknown) {
+ super(message);
+ this.status = status;
+ this.body = body;
+ }
+ }
+ return {
+ ApiError,
+ apiDeleteRuntime: vi.fn(),
+ apiArchiveAgentsAndDeleteRuntime: vi.fn(),
+ };
+});
+
+vi.mock("@multica/core/api", () => ({
+ api: {
+ deleteRuntime: (...args: unknown[]) => apiDeleteRuntime(...args),
+ archiveAgentsAndDeleteRuntime: (...args: unknown[]) =>
+ apiArchiveAgentsAndDeleteRuntime(...args),
+ listAgents: vi.fn(),
+ listMembers: vi.fn(),
+ },
+ ApiError,
+}));
+
+// The mutations file imports api lazily via the mock above; the mocked
+// hooks below thread directly to the api stubs so the dialog's mode
+// transitions are deterministic in this test.
+vi.mock("@multica/core/runtimes/mutations", () => ({
+ useDeleteRuntime: () => ({
+ isPending: false,
+ mutate: vi.fn(),
+ mutateAsync: (...args: unknown[]) => apiDeleteRuntime(...args),
+ }),
+ useArchiveAgentsAndDeleteRuntime: () => ({
+ isPending: false,
+ mutate: vi.fn(),
+ mutateAsync: (vars: { runtimeId: string; expectedActiveAgentIds: string[] }) =>
+ apiArchiveAgentsAndDeleteRuntime(vars.runtimeId, vars.expectedActiveAgentIds),
+ }),
+}));
+
+vi.mock("@tanstack/react-query", async () => {
+ const actual =
+ await vi.importActual<typeof import("@tanstack/react-query")>(
+ "@tanstack/react-query",
+ );
+ return {
+ ...actual,
+ // The dialog reads agentListOptions / memberListOptions through useQuery.
+ // The default returns an empty list — individual tests override
+ // mockUseQuery to return populated agents when they want cascade-from-cache.
+ useQuery: vi.fn(() => ({ data: [], isLoading: false })),
+ };
+});
+
+vi.mock("@multica/core/agents", () => ({
+ // Empty presence map keeps the cell renderers honest without dragging in
+ // the full presence pipeline.
+ useWorkspacePresenceMap: () => ({ byAgent: new Map(), loading: false }),
+}));
+
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (sel: (s: { user: { id: string } }) => unknown) =>
+ sel({ user: { id: "user-me" } }),
+}));
+
+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
+vi.mock("../../agents/presence", () => ({
+ availabilityConfig: {
+ online: { dotClass: "", textClass: "" },
+ unstable: { dotClass: "", textClass: "" },
+ offline: { dotClass: "", textClass: "" },
+ },
+ workloadConfig: {
+ working: { icon: () => null, textClass: "" },
+ queued: { icon: () => null, textClass: "" },
+ idle: { icon: () => null, textClass: "" },
+ },
+}));
+
+vi.mock("sonner", () => ({
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+
+import { useQuery } from "@tanstack/react-query";
+import { DeleteRuntimeDialog } from "./delete-runtime-dialog";
+
+const mockedUseQuery = vi.mocked(useQuery);
+
+function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
+ return {
+ id: "rt-1",
+ workspace_id: "ws-1",
+ daemon_id: null,
+ name: "Cloud Runtime",
+ runtime_mode: "cloud",
+ provider: "claude",
+ launch_header: "",
+ status: "online",
+ device_info: "",
+ metadata: {},
+ owner_id: "user-me",
+ visibility: "private",
+ last_seen_at: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+function makeAgent(id: string, overrides: Partial<Agent> = {}): Agent {
+ return {
+ id,
+ workspace_id: "ws-1",
+ runtime_id: "rt-1",
+ name: `Agent ${id}`,
+ description: "",
+ instructions: "",
+ avatar_url: null,
+ runtime_mode: "cloud",
+ runtime_config: {},
+ custom_args: [],
+ visibility: "private",
+ status: "idle",
+ max_concurrent_tasks: 1,
+ model: "claude-sonnet-4-5",
+ owner_id: "user-me",
+ skills: [],
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ archived_at: null,
+ archived_by: null,
+ ...overrides,
+ };
+}
+
+function renderDialog(opts: {
+ runtime?: AgentRuntime;
+ cachedAgents?: Agent[];
+ onDeleted?: () => void;
+} = {}) {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const onOpenChange = vi.fn();
+ const onDeleted = opts.onDeleted ?? vi.fn();
+
+ // Wire useQuery mock: agentListOptions returns the cached agents,
+ // memberListOptions returns an empty list (Owner cell renders the dash).
+ mockedUseQuery.mockImplementation(((queryArg: unknown) => {
+ const q = queryArg as { queryKey?: readonly unknown[] };
+ const key = q?.queryKey ?? [];
+ const tail = key[key.length - 1];
+ if (tail === "agents") {
+ return { data: opts.cachedAgents ?? [], isLoading: false } as unknown as ReturnType<typeof useQuery>;
+ }
+ return { data: [], isLoading: false } as unknown as ReturnType<typeof useQuery>;
+ }) as unknown as typeof useQuery);
+
+ const utils = render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={qc}>
+ <DeleteRuntimeDialog
+ open
+ onOpenChange={onOpenChange}
+ runtime={opts.runtime ?? makeRuntime()}
+ wsId="ws-1"
+ onDeleted={onDeleted}
+ />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+ return { ...utils, onOpenChange, onDeleted };
+}
+
+describe("DeleteRuntimeDialog", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("renders the light-mode prompt when no agents are bound", () => {
+ renderDialog({ cachedAgents: [] });
+
+ expect(screen.getByText("Delete Runtime?")).toBeInTheDocument();
+ 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();
+ });
+
+ it("opens directly in cascade mode when local cache shows bound agents, with the destructive button gated by the checkbox", async () => {
+ renderDialog({
+ cachedAgents: [
+ makeAgent("a-1", { name: "Alpha" }),
+ makeAgent("a-2", { name: "Beta" }),
+ ],
+ });
+
+ expect(
+ screen.getByText(/Archive 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/,
+ }) as HTMLButtonElement;
+ expect(confirm.disabled).toBe(true);
+
+ const checkbox = screen.getByRole("checkbox") as HTMLInputElement;
+ fireEvent.click(checkbox);
+ await waitFor(() => expect(confirm.disabled).toBe(false));
+
+ apiArchiveAgentsAndDeleteRuntime.mockResolvedValueOnce({
+ status: "ok",
+ agents_archived: 2,
+ tasks_cancelled: 0,
+ });
+ fireEvent.click(confirm);
+ await waitFor(() =>
+ expect(apiArchiveAgentsAndDeleteRuntime).toHaveBeenCalledWith("rt-1", [
+ "a-1",
+ "a-2",
+ ]),
+ );
+ });
+
+ it("pivots from light to cascade mode when the strict DELETE returns runtime_has_active_agents", async () => {
+ const fresh = makeAgent("a-9", { name: "FreshAgent" });
+ apiDeleteRuntime.mockRejectedValueOnce(
+ new ApiError("conflict", 409, {
+ code: "runtime_has_active_agents",
+ active_agents: [fresh],
+ }),
+ );
+
+ renderDialog({ cachedAgents: [] });
+
+ // We open in light mode, hit Delete, and expect the dialog to pivot to
+ // cascade mode using the server-supplied agent list.
+ const lightConfirm = screen.getByRole("button", { name: "Delete runtime" });
+ fireEvent.click(lightConfirm);
+
+ await waitFor(() =>
+ expect(
+ screen.getByText(/Archive 1 agent and delete this Runtime/),
+ ).toBeInTheDocument(),
+ );
+ expect(screen.getByText("FreshAgent")).toBeInTheDocument();
+ // Notice should be visible explaining the pivot.
+ expect(
+ screen.getByText(/Active agents were added since you opened this dialog/),
+ ).toBeInTheDocument();
+ });
+
+ it("re-prompts when the cascade returns runtime_delete_plan_changed", async () => {
+ apiArchiveAgentsAndDeleteRuntime.mockRejectedValueOnce(
+ new ApiError("plan changed", 409, {
+ code: "runtime_delete_plan_changed",
+ active_agents: [
+ makeAgent("a-1", { name: "Alpha" }),
+ makeAgent("a-2", { name: "Beta" }),
+ makeAgent("a-3", { name: "Gamma" }),
+ ],
+ }),
+ );
+
+ renderDialog({
+ cachedAgents: [
+ makeAgent("a-1", { name: "Alpha" }),
+ makeAgent("a-2", { name: "Beta" }),
+ ],
+ });
+
+ // Tick the checkbox and confirm.
+ fireEvent.click(screen.getByRole("checkbox"));
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: /Archive 2 agents and delete runtime/,
+ }),
+ );
+
+ await waitFor(() =>
+ expect(
+ screen.getByText(/Archive 3 agents and delete this Runtime/),
+ ).toBeInTheDocument(),
+ );
+ // The new third agent shows in the plan.
+ expect(screen.getByText("Gamma")).toBeInTheDocument();
+ // Checkbox is unchecked again so the user must re-confirm. The base-ui
+ // Checkbox renders as a <button role="checkbox"> with aria-checked, so
+ // we read that attribute rather than `.checked`.
+ expect(screen.getByRole("checkbox").getAttribute("aria-checked")).toBe(
+ "false",
+ );
+ // Notice copy explains why the dialog re-prompted.
+ expect(
+ screen.getByText(/active agent set changed/i),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/runtimes/components/delete-runtime-dialog.tsx b/packages/views/runtimes/components/delete-runtime-dialog.tsx
new file mode 100644
index 0000000000..32c2b39619
--- /dev/null
+++ b/packages/views/runtimes/components/delete-runtime-dialog.tsx
@@ -0,0 +1,602 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { AlertTriangle, Globe, Lock } from "lucide-react";
+import { toast } from "sonner";
+import { useQuery } from "@tanstack/react-query";
+import { ApiError } from "@multica/core/api";
+import type { Agent, AgentRuntime, MemberWithUser } from "@multica/core/types";
+import {
+ useDeleteRuntime,
+ useArchiveAgentsAndDeleteRuntime,
+} from "@multica/core/runtimes/mutations";
+import {
+ agentListOptions,
+ memberListOptions,
+} from "@multica/core/workspace/queries";
+import {
+ type AgentPresenceDetail,
+ useWorkspacePresenceMap,
+} from "@multica/core/agents";
+import { useAuthStore } from "@multica/core/auth";
+import {
+ AlertDialog,
+ AlertDialogContent,
+} from "@multica/ui/components/ui/alert-dialog";
+import { Button } from "@multica/ui/components/ui/button";
+import { Checkbox } from "@multica/ui/components/ui/checkbox";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { availabilityConfig, workloadConfig } from "../../agents/presence";
+import { useT } from "../../i18n";
+import { isSelfHealingRuntime } from "../utils";
+
+// DeleteRuntimeDialog is the single confirmation surface for runtime
+// 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.
+//
+// Mode is decided dynamically:
+// 1. Initial: peek at the cached agent list and pick light vs cascade
+// based on whether any active agent.runtime_id === runtime.id. This
+// lets the dialog open in the right state without an extra request.
+// 2. After the strict DELETE: if the server refuses with
+// `runtime_has_active_agents` (the local data was stale), switch to
+// cascade mode using the server's authoritative agent list.
+// 3. After the cascade endpoint: if it refuses with
+// `runtime_delete_plan_changed`, refresh the displayed list with the
+// server snapshot and force the user to re-confirm the checkbox.
+//
+// Self-healing local runtimes (online local daemons that re-register
+// themselves seconds after deletion — see isSelfHealingRuntime) are
+// gated at the affordance level by the row-menu and Diagnostics card,
+// so this dialog never opens for them. We re-check at confirm time as
+// defence in depth in case the runtime flips while the dialog is open.
+export interface DeleteRuntimeDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ runtime: AgentRuntime;
+ wsId: string;
+ // Called after a successful delete. List page closes the dialog and
+ // toasts; detail page additionally navigates back to /runtimes.
+ onDeleted: () => void;
+}
+
+export function DeleteRuntimeDialog({
+ open,
+ onOpenChange,
+ runtime,
+ wsId,
+ onDeleted,
+}: DeleteRuntimeDialogProps) {
+ const { t } = useT("runtimes");
+ // Pull cached workspace data — every consumer page already has these
+ // mounted, so this dialog adds zero new fetches when opened.
+ const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const { byAgent: presenceMap } = useWorkspacePresenceMap(wsId);
+ const user = useAuthStore((s) => s.user);
+
+ // The displayed plan starts from the cached agent list and is replaced by
+ // server snapshots when the backend returns a structured 409 (either on
+ // the initial DELETE or on a plan-changed cascade refusal). We hold it in
+ // state so renders are deterministic even after invalidation flickers.
+ const cachedActiveAgents = useMemo(
+ () => agents.filter((a) => a.runtime_id === runtime.id && !a.archived_at),
+ [agents, runtime.id],
+ );
+ const [planAgents, setPlanAgents] = useState<Agent[]>(cachedActiveAgents);
+ // `cascade` is true when the visible plan has at least one agent. Mode is
+ // a derived value, not user-controlled — the user always confirms the
+ // current plan; switching is the consequence of a server response, not a
+ // toggle.
+ const cascade = planAgents.length > 0;
+
+ const [confirmed, setConfirmed] = useState(false);
+ const [submitting, setSubmitting] = useState(false);
+ // Server-issued message shown above the agent table on plan-changed —
+ // tells the user "the list refreshed because something moved" without
+ // re-stating it in the title. Stored as a localized string (already
+ // translated) so the consumer can just render it.
+ const [planChangedNotice, setPlanChangedNotice] = useState<string | null>(null);
+
+ // Reset transient state every time the dialog opens. Without this a
+ // previous plan-changed notice or a stale checkbox could survive across
+ // open/close cycles and confuse the next attempt.
+ useEffect(() => {
+ if (open) {
+ setPlanAgents(cachedActiveAgents);
+ setConfirmed(false);
+ setSubmitting(false);
+ setPlanChangedNotice(null);
+ }
+ }, [open, cachedActiveAgents]);
+
+ const lightMutation = useDeleteRuntime(wsId);
+ const cascadeMutation = useArchiveAgentsAndDeleteRuntime(wsId);
+
+ const handleConfirm = async () => {
+ // Defensive re-check of the self-healing rule — the affordance is
+ // gated upstream, but a local daemon that came online while the
+ // dialog was open should still block the action.
+ if (isSelfHealingRuntime(runtime)) {
+ toast.error(
+ t(($) => $.detail.delete_dialog.cascade.self_healing_blocked_toast),
+ );
+ return;
+ }
+
+ setSubmitting(true);
+ setPlanChangedNotice(null);
+
+ try {
+ if (cascade) {
+ await cascadeMutation.mutateAsync({
+ runtimeId: runtime.id,
+ expectedActiveAgentIds: planAgents.map((a) => a.id),
+ });
+ onDeleted();
+ } else {
+ try {
+ await lightMutation.mutateAsync(runtime.id);
+ onDeleted();
+ } catch (err) {
+ // The strict DELETE returns a structured 409 when active
+ // agents were created between dialog-open and confirm. Pivot
+ // into cascade mode using the server's authoritative list,
+ // unset the checkbox, and surface a notice so the user knows
+ // why the dialog suddenly grew an agent table.
+ const conflict = parseActiveAgentsConflict(err);
+ if (conflict?.code === "runtime_has_active_agents") {
+ setPlanAgents(conflict.activeAgents);
+ setConfirmed(false);
+ setPlanChangedNotice(
+ t(
+ ($) =>
+ $.detail.delete_dialog.cascade.notice_runtime_has_active_agents,
+ ),
+ );
+ return;
+ }
+ throw err;
+ }
+ }
+ } catch (err) {
+ // Cascade-side plan-changed: the user confirmed plan A but the live
+ // set is now plan B. Refresh the displayed list with the server
+ // snapshot, force the user to re-tick the checkbox.
+ const conflict = parseActiveAgentsConflict(err);
+ if (conflict?.code === "runtime_delete_plan_changed") {
+ setPlanAgents(conflict.activeAgents);
+ setConfirmed(false);
+ setPlanChangedNotice(
+ t(
+ ($) =>
+ $.detail.delete_dialog.cascade.notice_runtime_delete_plan_changed,
+ ),
+ );
+ return;
+ }
+ const message =
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.detail.delete_dialog.cascade.delete_failed_toast);
+ toast.error(message);
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ // Permission to act — `false` blocks the close while submitting, prevents
+ // an accidental click on the underlying page from cancelling mid-write.
+ const handleOpenChange = (next: boolean) => {
+ if (submitting) return;
+ onOpenChange(next);
+ };
+
+ // Light mode keeps the legacy short copy. Cascade mode mirrors the plan
+ // 赵刚 wrote: destructive title with the count, a destructive warning
+ // banner, the agent table, then a checkbox confirm whose label restates
+ // the consequences in the same words as the warning.
+ return (
+ <AlertDialog open={open} onOpenChange={handleOpenChange}>
+ <AlertDialogContent
+ className={
+ cascade
+ ? "w-[calc(100vw-2rem)] !max-w-[640px] gap-0 overflow-hidden rounded-lg p-0"
+ : "w-[calc(100vw-2rem)] !max-w-[440px] gap-0 overflow-hidden rounded-lg p-0"
+ }
+ onClick={(e) => e.stopPropagation()}
+ >
+ {cascade ? (
+ <CascadeBody
+ runtime={runtime}
+ agents={planAgents}
+ members={members}
+ presenceMap={presenceMap}
+ currentUserId={user?.id ?? null}
+ confirmed={confirmed}
+ onConfirmedChange={setConfirmed}
+ planChangedNotice={planChangedNotice}
+ submitting={submitting}
+ onCancel={() => handleOpenChange(false)}
+ onConfirm={handleConfirm}
+ />
+ ) : (
+ <LightBody
+ runtime={runtime}
+ submitting={submitting}
+ onCancel={() => handleOpenChange(false)}
+ onConfirm={handleConfirm}
+ />
+ )}
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Light mode — no active agents, classic "are you sure" prompt. Title and
+// description match the legacy AlertDialog so existing screenshots / muscle
+// memory still apply.
+// ---------------------------------------------------------------------------
+
+function LightBody({
+ runtime,
+ submitting,
+ onCancel,
+ onConfirm,
+}: {
+ runtime: AgentRuntime;
+ submitting: boolean;
+ onCancel: () => void;
+ onConfirm: () => void;
+}) {
+ const { t } = useT("runtimes");
+ return (
+ <>
+ <div className="px-5 pb-4 pt-5">
+ <h2 className="text-base font-semibold">
+ {t(($) => $.detail.delete_dialog.light.title)}
+ </h2>
+ <p className="mt-1 text-sm leading-5 text-muted-foreground">
+ {t(($) => $.detail.delete_dialog.light.description, {
+ name: runtime.name,
+ })}
+ </p>
+ </div>
+ <div className="border-t bg-muted/25 px-5 py-3">
+ <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
+ <Button
+ type="button"
+ variant="outline"
+ className="w-full sm:w-auto"
+ onClick={onCancel}
+ disabled={submitting}
+ >
+ {t(($) => $.detail.delete_dialog.light.cancel)}
+ </Button>
+ <Button
+ type="button"
+ variant="destructive"
+ className="w-full sm:w-auto"
+ onClick={onConfirm}
+ disabled={submitting}
+ >
+ {submitting
+ ? t(($) => $.detail.delete_dialog.light.submitting)
+ : t(($) => $.detail.delete_dialog.light.confirm)}
+ </Button>
+ </div>
+ </div>
+ </>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Cascade mode — destructive warning, agent table, checkbox-confirmed
+// destructive button. Copy follows 赵刚's English text verbatim per the
+// squad lead's directive.
+// ---------------------------------------------------------------------------
+
+function CascadeBody({
+ runtime,
+ agents,
+ members,
+ presenceMap,
+ currentUserId,
+ confirmed,
+ onConfirmedChange,
+ planChangedNotice,
+ submitting,
+ onCancel,
+ onConfirm,
+}: {
+ runtime: AgentRuntime;
+ agents: Agent[];
+ members: MemberWithUser[];
+ presenceMap: Map<string, AgentPresenceDetail>;
+ currentUserId: string | null;
+ confirmed: boolean;
+ onConfirmedChange: (next: boolean) => void;
+ planChangedNotice: string | null;
+ submitting: boolean;
+ onCancel: () => void;
+ onConfirm: () => void;
+}) {
+ const { t } = useT("runtimes");
+ const count = agents.length;
+
+ return (
+ <>
+ <div className="px-5 pb-4 pt-5">
+ <h2 className="text-base font-semibold">
+ {t(($) => $.detail.delete_dialog.cascade.title, { count })}
+ </h2>
+ <p className="mt-1 text-sm leading-5 text-muted-foreground">
+ {t(($) => $.detail.delete_dialog.cascade.description, {
+ name: runtime.name,
+ })}
+ </p>
+
+ {/* Destructive banner — keep the user's eye on the irreversible
+ half before they scan the agent table. */}
+ <div
+ role="alert"
+ className="mt-3 flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive"
+ >
+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
+ <span>{t(($) => $.detail.delete_dialog.cascade.warning)}</span>
+ </div>
+
+ {planChangedNotice && (
+ <div
+ role="status"
+ className="mt-2 rounded-md border bg-muted/40 px-3 py-2 text-xs text-foreground"
+ >
+ {planChangedNotice}
+ </div>
+ )}
+
+ <AgentPlanTable
+ agents={agents}
+ members={members}
+ presenceMap={presenceMap}
+ currentUserId={currentUserId}
+ />
+ </div>
+
+ <div className="border-t bg-muted/25 px-5 py-4">
+ <label className="flex cursor-pointer items-start gap-2 text-sm text-foreground">
+ <Checkbox
+ className="mt-0.5"
+ checked={confirmed}
+ onCheckedChange={(next) => onConfirmedChange(next === true)}
+ disabled={submitting}
+ />
+ <span className="leading-5">
+ {t(($) => $.detail.delete_dialog.cascade.checkbox, { count })}
+ </span>
+ </label>
+ <div className="mt-3 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
+ <Button
+ type="button"
+ variant="outline"
+ className="w-full sm:w-auto"
+ onClick={onCancel}
+ disabled={submitting}
+ >
+ {t(($) => $.detail.delete_dialog.cascade.cancel)}
+ </Button>
+ <Button
+ type="button"
+ variant="destructive"
+ className="w-full sm:w-auto"
+ onClick={onConfirm}
+ disabled={!confirmed || submitting}
+ >
+ {submitting
+ ? t(($) => $.detail.delete_dialog.cascade.submitting)
+ : t(($) => $.detail.delete_dialog.cascade.confirm, { count })}
+ </Button>
+ </div>
+ </div>
+ </>
+ );
+}
+
+// AgentPlanTable renders the cascade plan: one row per agent showing the
+// fields 赵刚 specified. Header + scroll body live in a fixed-height
+// container so a runtime with many agents doesn't push the destructive
+// confirm out of view; the body scrolls instead.
+function AgentPlanTable({
+ agents,
+ members,
+ presenceMap,
+ currentUserId,
+}: {
+ agents: Agent[];
+ members: MemberWithUser[];
+ presenceMap: Map<string, AgentPresenceDetail>;
+ currentUserId: string | null;
+}) {
+ const { t } = useT("runtimes");
+ const memberById = useMemo(() => {
+ const map = new Map<string, MemberWithUser>();
+ for (const m of members) map.set(m.user_id, m);
+ return map;
+ }, [members]);
+
+ return (
+ <div className="mt-3 overflow-hidden rounded-md border">
+ <div className="grid grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)_minmax(0,1.2fr)_minmax(0,0.8fr)_minmax(0,1fr)] gap-3 border-b bg-muted/40 px-3 py-2 text-[11px] uppercase tracking-wide text-muted-foreground">
+ <span>{t(($) => $.detail.delete_dialog.cascade.table.header_agent)}</span>
+ <span>{t(($) => $.detail.delete_dialog.cascade.table.header_owner)}</span>
+ <span>{t(($) => $.detail.delete_dialog.cascade.table.header_status)}</span>
+ <span>
+ {t(($) => $.detail.delete_dialog.cascade.table.header_visibility)}
+ </span>
+ <span>{t(($) => $.detail.delete_dialog.cascade.table.header_model)}</span>
+ </div>
+ <div className="max-h-[240px] overflow-y-auto divide-y">
+ {agents.map((agent) => {
+ const ownerMember = agent.owner_id
+ ? memberById.get(agent.owner_id) ?? null
+ : null;
+ const ownerLabel = ownerMember
+ ? ownerMember.user_id === currentUserId
+ ? t(($) => $.detail.delete_dialog.cascade.table.owner_self)
+ : ownerMember.name
+ : t(($) => $.detail.delete_dialog.cascade.table.owner_unassigned);
+ const presence = presenceMap.get(agent.id);
+ return (
+ <div
+ key={agent.id}
+ className="grid grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)_minmax(0,1.2fr)_minmax(0,0.8fr)_minmax(0,1fr)] items-center gap-3 px-3 py-2 text-xs"
+ >
+ <span className="inline-flex min-w-0 items-center gap-2">
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ size={20}
+ enableHoverCard
+ />
+ <span className="truncate font-medium text-foreground">
+ {agent.name}
+ </span>
+ </span>
+ <span className="inline-flex min-w-0 items-center gap-1.5">
+ {ownerMember ? (
+ <ActorAvatar
+ actorType="member"
+ actorId={ownerMember.user_id}
+ size={16}
+ />
+ ) : null}
+ <span className="truncate text-muted-foreground">
+ {ownerLabel}
+ </span>
+ </span>
+ <PresenceCell presence={presence} />
+ <VisibilityCell visibility={agent.visibility} />
+ <span className="truncate text-muted-foreground">
+ {agent.model ||
+ t(($) => $.detail.delete_dialog.cascade.table.model_unset)}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+function PresenceCell({ presence }: { presence: AgentPresenceDetail | undefined }) {
+ const { t } = useT("runtimes");
+ if (!presence) {
+ return (
+ <span className="text-muted-foreground/60">
+ {t(($) => $.detail.delete_dialog.cascade.table.presence_unknown)}
+ </span>
+ );
+ }
+ const av = availabilityConfig[presence.availability];
+ const wl = workloadConfig[presence.workload];
+ const counts =
+ presence.workload === "working"
+ ? presence.queuedCount > 0
+ ? `${presence.runningCount} +${presence.queuedCount}q`
+ : `${presence.runningCount}`
+ : presence.workload === "queued"
+ ? `${presence.queuedCount}`
+ : null;
+ return (
+ <span className="inline-flex min-w-0 items-center gap-1.5">
+ <span className={`size-1.5 shrink-0 rounded-full ${av.dotClass}`} />
+ <span className={av.textClass}>
+ {presence.workload === "idle"
+ ? t(($) => $.detail.delete_dialog.cascade.table.workload_idle)
+ : null}
+ {presence.workload === "working" && (
+ <wl.icon className={`mr-1 inline size-3 align-[-2px] animate-spin ${wl.textClass}`} />
+ )}
+ {presence.workload === "queued" && (
+ <wl.icon className={`mr-1 inline size-3 align-[-2px] ${wl.textClass}`} />
+ )}
+ {presence.workload === "working" &&
+ t(($) => $.detail.delete_dialog.cascade.table.workload_working)}
+ {presence.workload === "queued" &&
+ t(($) => $.detail.delete_dialog.cascade.table.workload_queued)}
+ </span>
+ {counts && (
+ <span className="font-mono tabular-nums text-muted-foreground/80">
+ {counts}
+ </span>
+ )}
+ </span>
+ );
+}
+
+function VisibilityCell({ visibility }: { visibility: string }) {
+ const { t } = useT("runtimes");
+ if (visibility === "public" || visibility === "workspace") {
+ return (
+ <span className="inline-flex items-center gap-1 text-muted-foreground">
+ <Globe className="size-3" />
+ <span>
+ {t(($) => $.detail.delete_dialog.cascade.table.visibility_workspace)}
+ </span>
+ </span>
+ );
+ }
+ return (
+ <span className="inline-flex items-center gap-1 text-muted-foreground">
+ <Lock className="size-3" />
+ <span>
+ {t(($) => $.detail.delete_dialog.cascade.table.visibility_private)}
+ </span>
+ </span>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Server response parsing
+// ---------------------------------------------------------------------------
+
+interface ActiveAgentsConflict {
+ code: "runtime_has_active_agents" | "runtime_delete_plan_changed";
+ activeAgents: Agent[];
+}
+
+// parseActiveAgentsConflict pulls the structured 409 fields off an ApiError.
+// Non-409s, non-active-agents codes, and missing bodies all collapse to
+// `null` so callers can fall through to the generic error toast.
+function parseActiveAgentsConflict(err: unknown): ActiveAgentsConflict | null {
+ if (!(err instanceof ApiError)) return null;
+ if (err.status !== 409) return null;
+ const body = err.body;
+ if (!body || typeof body !== "object") return null;
+ const code = (body as Record<string, unknown>).code;
+ if (
+ code !== "runtime_has_active_agents" &&
+ code !== "runtime_delete_plan_changed"
+ ) {
+ return null;
+ }
+ const rawAgents = (body as Record<string, unknown>).active_agents;
+ if (!Array.isArray(rawAgents)) {
+ return { code, activeAgents: [] };
+ }
+ // We trust the server contract here — the response is the same
+ // AgentResponse shape that the agent list endpoint returns. Light
+ // runtime checks (id, runtime_id, name) catch genuinely malformed
+ // payloads without re-typing every field.
+ const activeAgents = rawAgents.filter(
+ (a): a is Agent =>
+ typeof a === "object" &&
+ a !== null &&
+ typeof (a as Record<string, unknown>).id === "string" &&
+ typeof (a as Record<string, unknown>).name === "string",
+ );
+ return { code, activeAgents };
+}
diff --git a/packages/views/runtimes/components/runtime-columns.tsx b/packages/views/runtimes/components/runtime-columns.tsx
index 87c141d7c3..8afb7b3257 100644
--- a/packages/views/runtimes/components/runtime-columns.tsx
+++ b/packages/views/runtimes/components/runtime-columns.tsx
@@ -16,17 +16,6 @@ import {
deriveRuntimeHealth,
runtimeUsageOptions,
} from "@multica/core/runtimes";
-import { useDeleteRuntime } from "@multica/core/runtimes/mutations";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@multica/ui/components/ui/alert-dialog";
import { Button } from "@multica/ui/components/ui/button";
import {
DropdownMenu,
@@ -44,6 +33,7 @@ import { useViewingTimezone } from "../../common/use-viewing-timezone";
import { workloadConfig } from "../../agents/presence";
import { ProviderLogo } from "./provider-logo";
import { HealthIcon, useHealthLabel } from "./shared";
+import { DeleteRuntimeDialog } from "./delete-runtime-dialog";
import {
computeCostInWindow,
formatLastSeen,
@@ -484,7 +474,6 @@ function RowMenu({
canDelete: boolean;
}) {
const { t } = useT("runtimes");
- const deleteMutation = useDeleteRuntime(wsId);
const [deleteOpen, setDeleteOpen] = useState(false);
// Delete is currently the only row action; if the row can't run it, drop
// the kebab entirely so the column doesn't render an empty popover. The
@@ -496,20 +485,6 @@ function RowMenu({
return <span aria-hidden />;
}
- const handleDelete = () => {
- deleteMutation.mutate(runtime.id, {
- onSuccess: () => {
- toast.success(t(($) => $.detail.toast_deleted));
- setDeleteOpen(false);
- },
- onError: (e) => {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.detail.toast_delete_failed),
- );
- },
- });
- };
-
return (
<>
<DropdownMenu>
@@ -541,35 +516,16 @@ function RowMenu({
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
- <AlertDialog
+ <DeleteRuntimeDialog
open={deleteOpen}
- onOpenChange={(v) => {
- if (deleteMutation.isPending) return;
- setDeleteOpen(v);
+ onOpenChange={setDeleteOpen}
+ runtime={runtime}
+ wsId={wsId}
+ onDeleted={() => {
+ setDeleteOpen(false);
+ toast.success(t(($) => $.detail.toast_deleted));
}}
- >
- <AlertDialogContent onClick={(e) => e.stopPropagation()}>
- <AlertDialogHeader>
- <AlertDialogTitle>{t(($) => $.detail.delete_dialog.title)}</AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.detail.delete_dialog.description, { name: runtime.name })}
- <span className="mt-2 block text-xs text-muted-foreground/80">
- {t(($) => $.list.delete_admin_hint)}
- </span>
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>{t(($) => $.detail.delete_dialog.cancel)}</AlertDialogCancel>
- <AlertDialogAction
- variant="destructive"
- onClick={handleDelete}
- disabled={deleteMutation.isPending}
- >
- {deleteMutation.isPending ? t(($) => $.detail.delete_dialog.deleting) : t(($) => $.detail.delete_dialog.confirm)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
+ />
</>
);
}
diff --git a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
index b8d1297316..9d19c13dd9 100644
--- a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
+++ b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
@@ -22,7 +22,10 @@ vi.mock("@multica/core/hooks", () => ({
vi.mock("@multica/core/api", () => ({
api: {
updateRuntime: (...args: unknown[]) => mockUpdateRuntime(...args),
+ deleteRuntime: vi.fn(),
+ archiveAgentsAndDeleteRuntime: vi.fn(),
},
+ ApiError: class ApiError extends Error {},
}));
vi.mock("sonner", () => ({
@@ -80,7 +83,12 @@ vi.mock("@multica/core/runtimes/mutations", () => ({
},
isPending: false,
}),
- useDeleteRuntime: () => ({ mutate: vi.fn(), isPending: false }),
+ useDeleteRuntime: () => ({ mutate: vi.fn(), isPending: false, mutateAsync: vi.fn() }),
+ useArchiveAgentsAndDeleteRuntime: () => ({
+ mutate: vi.fn(),
+ isPending: false,
+ mutateAsync: vi.fn(),
+ }),
}));
// Stubbing ProviderLogo / UsageSection / UpdateSection avoids dragging in
diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsx
index ee5287504e..9b50cb1e19 100644
--- a/packages/views/runtimes/components/runtime-detail.tsx
+++ b/packages/views/runtimes/components/runtime-detail.tsx
@@ -15,7 +15,7 @@ import type { AgentRuntime, Agent, MemberWithUser } from "@multica/core/types";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";
-import { useDeleteRuntime, useUpdateRuntime } from "@multica/core/runtimes/mutations";
+import { useUpdateRuntime } from "@multica/core/runtimes/mutations";
import { deriveRuntimeHealth } from "@multica/core/runtimes";
import {
type AgentPresenceDetail,
@@ -23,16 +23,6 @@ import {
} from "@multica/core/agents";
import { useWorkspacePaths } from "@multica/core/paths";
import { Button } from "@multica/ui/components/ui/button";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@multica/ui/components/ui/alert-dialog";
import {
Tooltip,
TooltipContent,
@@ -46,6 +36,7 @@ import { HealthBadge } from "./shared";
import { ProviderLogo } from "./provider-logo";
import { UpdateSection } from "./update-section";
import { UsageSection } from "./usage-section";
+import { DeleteRuntimeDialog } from "./delete-runtime-dialog";
import { useT } from "../../i18n";
function getCliVersion(metadata: Record<string, unknown>): string | null {
@@ -104,7 +95,6 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
const { data: members = [] } = useQuery(memberListOptions(wsId));
const { data: agents = [] } = useQuery(agentListOptions(wsId));
const { byAgent: presenceMap } = useWorkspacePresenceMap(wsId);
- const deleteMutation = useDeleteRuntime(wsId);
const now = useNowTick();
const [deleteOpen, setDeleteOpen] = useState(false);
@@ -127,17 +117,13 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
(a) => a.runtime_id === runtime.id && !a.archived_at,
);
- const handleDelete = () => {
- deleteMutation.mutate(runtime.id, {
- onSuccess: () => {
- setDeleteOpen(false);
- navigation.replace(paths.runtimes());
- toast.success(t(($) => $.detail.toast_deleted));
- },
- onError: (e) => {
- toast.error(e instanceof Error ? e.message : t(($) => $.detail.toast_delete_failed));
- },
- });
+ // Successful delete (light or cascade) closes the dialog and navigates
+ // back to the runtimes list. Toast lives here so the cascade-mode count
+ // and the light-mode "Runtime deleted" share one entry point.
+ const handleDeleted = () => {
+ setDeleteOpen(false);
+ navigation.replace(paths.runtimes());
+ toast.success(t(($) => $.detail.toast_deleted));
};
const daemonShort = shortDaemonId(runtime.daemon_id);
@@ -208,27 +194,16 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
</div>
</div>
- {/* Delete confirmation */}
- <AlertDialog open={deleteOpen} onOpenChange={(v) => { if (!v) setDeleteOpen(false); }}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>{t(($) => $.detail.delete_dialog.title)}</AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.detail.delete_dialog.description, { name: runtime.name })}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>{t(($) => $.detail.delete_dialog.cancel)}</AlertDialogCancel>
- <AlertDialogAction
- variant="destructive"
- onClick={handleDelete}
- disabled={deleteMutation.isPending}
- >
- {deleteMutation.isPending ? t(($) => $.detail.delete_dialog.deleting) : t(($) => $.detail.delete_dialog.confirm)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
+ {/* Delete confirmation — unified light/cascade dialog. Shared across
+ this page and the runtime list kebab so the two entry points stay
+ in lockstep on copy and behaviour. */}
+ <DeleteRuntimeDialog
+ open={deleteOpen}
+ onOpenChange={setDeleteOpen}
+ runtime={runtime}
+ wsId={wsId}
+ onDeleted={handleDeleted}
+ />
</div>
);
}
diff --git a/packages/views/runtimes/components/runtime-row-menu.test.tsx b/packages/views/runtimes/components/runtime-row-menu.test.tsx
index 8a4ae6d579..3a9a4d2fd4 100644
--- a/packages/views/runtimes/components/runtime-row-menu.test.tsx
+++ b/packages/views/runtimes/components/runtime-row-menu.test.tsx
@@ -28,7 +28,12 @@ vi.mock("@tanstack/react-query", async () => {
});
vi.mock("@multica/core/runtimes/mutations", () => ({
- useDeleteRuntime: () => ({ mutate: vi.fn(), isPending: false }),
+ useDeleteRuntime: () => ({ mutate: vi.fn(), isPending: false, mutateAsync: vi.fn() }),
+ useArchiveAgentsAndDeleteRuntime: () => ({
+ mutate: vi.fn(),
+ isPending: false,
+ mutateAsync: vi.fn(),
+ }),
}));
vi.mock("@multica/core/runtimes", () => ({
@@ -38,6 +43,27 @@ vi.mock("@multica/core/runtimes", () => ({
vi.mock("@multica/core/agents", () => ({
deriveWorkload: () => "idle",
+ useWorkspacePresenceMap: () => ({ byAgent: new Map(), loading: false }),
+}));
+
+// The unified DeleteRuntimeDialog the kebab now opens reaches into auth +
+// the api singleton. The dialog never renders in these tests (`open=false`
+// throughout) but its hooks still mount; stub them so module init is clean.
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (sel: (s: { user: { id: string } }) => unknown) =>
+ sel({ user: { id: "user-me" } }),
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: {
+ deleteRuntime: vi.fn(),
+ archiveAgentsAndDeleteRuntime: vi.fn(),
+ },
+ ApiError: class ApiError extends Error {},
+}));
+
+vi.mock("sonner", () => ({
+ toast: { error: vi.fn(), success: vi.fn() },
}));
vi.mock("../../common/use-viewing-timezone", () => ({
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 7503ee4b34..f4953d5c92 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -597,6 +597,13 @@ 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)
})
})
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index 27d78293ae..2ad91b9916 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -528,6 +528,13 @@ func (h *Handler) ListAgentRuntimes(w http.ResponseWriter, r *http.Request) {
}
// DeleteAgentRuntime deletes a runtime after permission and dependency checks.
+//
+// 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
+// below) and runs the multi-write teardown inside a single transaction.
func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
@@ -555,13 +562,16 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
userID := uuidToString(member.UserID)
// Check if any active (non-archived) agents are bound to this runtime.
- activeCount, err := h.Queries.CountActiveAgentsByRuntime(r.Context(), rt.ID)
+ // Surface them on the 409 so the dialog can render the cascade plan
+ // directly from this response — saves a second round-trip when the
+ // user clicked Delete from a stale list page.
+ activeAgents, err := h.Queries.ListActiveAgentsByRuntime(r.Context(), rt.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to check runtime dependencies")
return
}
- if activeCount > 0 {
- writeError(w, http.StatusConflict, "cannot delete runtime: it has active agents bound to it. Archive or reassign the agents first.")
+ if len(activeAgents) > 0 {
+ writeJSON(w, http.StatusConflict, runtimeHasActiveAgentsResponse(activeAgents))
return
}
@@ -604,3 +614,278 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
+
+// runtimeHasActiveAgentsResponse builds the structured 409 body shared by
+// DeleteAgentRuntime (light-mode block) and ArchiveAgentsAndDeleteRuntime
+// (cascade-plan-changed). The shape is:
+//
+// {
+// "error": "...",
+// "code": "runtime_has_active_agents" | "runtime_delete_plan_changed",
+// "active_agents": [AgentResponse, ...]
+// }
+//
+// Front-end branches on `code`. The caller picks which code to send; this
+// helper just normalises the agent serialisation and the error string.
+func runtimeHasActiveAgentsResponse(agents []db.Agent) map[string]any {
+ resp := make([]AgentResponse, len(agents))
+ for i, a := range agents {
+ resp[i] = agentToResponse(a)
+ }
+ return map[string]any{
+ "error": "cannot delete runtime: it has active agents bound to it. Archive or reassign the agents 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
+// 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 {
+ 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.
+//
+// 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.
+//
+// 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
+// the user a checkbox confirmation; if a teammate adds or archives an agent
+// 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) {
+ runtimeID := chi.URLParam(r, "runtimeId")
+ runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
+ if !ok {
+ return
+ }
+
+ var req archiveAgentsAndDeleteRuntimeRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ expected, ok := parseExpectedActiveAgentIDs(req.ExpectedActiveAgentIDs)
+ if !ok {
+ writeError(w, http.StatusBadRequest, "expected_active_agent_ids must be a list of valid UUIDs")
+ return
+ }
+
+ rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
+ if err != nil {
+ writeError(w, http.StatusNotFound, "runtime not found")
+ return
+ }
+
+ wsID := uuidToString(rt.WorkspaceID)
+ member, ok := h.requireWorkspaceMember(w, r, wsID, "runtime not found")
+ if !ok {
+ return
+ }
+ if !canEditRuntime(member, rt) {
+ writeError(w, http.StatusForbidden, "you can only delete your own runtimes")
+ return
+ }
+ userID := uuidToString(member.UserID)
+
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to start transaction")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ // Lock the runtime row first. PostgreSQL's FK validation on
+ // agent.runtime_id requires FOR KEY SHARE on the parent runtime row,
+ // 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.
+ if _, err := qtx.LockAgentRuntime(r.Context(), rt.ID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to lock runtime")
+ return
+ }
+
+ // Re-list active agents inside the transaction, with FOR UPDATE on
+ // each row so a concurrent archive/move of one of those existing
+ // agents also blocks until we commit. Comparing against the expected
+ // 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.
+ currentActive, err := qtx.ListActiveAgentsByRuntimeForUpdate(r.Context(), rt.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to enumerate active agents")
+ return
+ }
+ if !activeAgentSetMatches(currentActive, expected) {
+ // Refuse with the latest snapshot so the front-end can re-render
+ // the dialog and force a fresh user confirmation. Reuses the
+ // shared response helper but overrides the code to a planning
+ // signal so the dialog can distinguish "you opened from a stale
+ // page" from "the plan you confirmed just changed under you".
+ body := runtimeHasActiveAgentsResponse(currentActive)
+ body["code"] = "runtime_delete_plan_changed"
+ body["error"] = "the active agent set changed; please review and confirm again."
+ writeJSON(w, http.StatusConflict, body)
+ 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)
+ 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")
+ 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.DeleteArchivedAgentsByRuntime(r.Context(), rt.ID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to clean up archived agents")
+ return
+ }
+
+ // 5. 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
+ }
+
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to commit transaction")
+ 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": agentToResponse(a),
+ })
+ }
+ h.publish(protocol.EventDaemonRegister, wsID, "member", userID, map[string]any{
+ "action": "delete",
+ })
+
+ slog.Info("runtime deleted via cascade",
+ "runtime_id", uuidToString(rt.ID),
+ "deleted_by", userID,
+ "agents_archived", len(archivedAgents),
+ "tasks_cancelled", len(cancelledTasks),
+ )
+
+ writeJSON(w, http.StatusOK, map[string]any{
+ "status": "ok",
+ "agents_archived": len(archivedAgents),
+ "tasks_cancelled": len(cancelledTasks),
+ })
+}
+
+// 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
+// any malformed UUID so the handler responds 400 instead of silently
+// matching a different set.
+func parseExpectedActiveAgentIDs(raw []string) (map[string]struct{}, bool) {
+ out := make(map[string]struct{}, len(raw))
+ for _, s := range raw {
+ u, err := util.ParseUUID(s)
+ if err != nil || !u.Valid {
+ return nil, false
+ }
+ out[uuidToString(u)] = struct{}{}
+ }
+ return out, true
+}
+
+// activeAgentSetMatches reports whether the live set of active agents on the
+// runtime matches the snapshot the front-end confirmed. Order-insensitive
+// because the front-end may render in any order; size + membership is what
+// matters for "did the plan change?".
+func activeAgentSetMatches(current []db.Agent, expected map[string]struct{}) bool {
+ if len(current) != len(expected) {
+ return false
+ }
+ for _, a := range current {
+ if _, ok := expected[uuidToString(a.ID)]; !ok {
+ return false
+ }
+ }
+ return true
+}
diff --git a/server/internal/handler/runtime_cascade_test.go b/server/internal/handler/runtime_cascade_test.go
new file mode 100644
index 0000000000..e72c19ff54
--- /dev/null
+++ b/server/internal/handler/runtime_cascade_test.go
@@ -0,0 +1,305 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// parseExpectedActiveAgentIDs is the cascade endpoint's input validator.
+// Empty list is a valid plan ("no active agents" — cascade just deletes the
+// runtime); malformed UUIDs must surface as 400 so a bug in the front-end
+// can't silently dilute the plan check.
+func TestParseExpectedActiveAgentIDs(t *testing.T) {
+ t.Run("empty list returns empty set, ok", func(t *testing.T) {
+ got, ok := parseExpectedActiveAgentIDs(nil)
+ if !ok {
+ t.Fatalf("expected ok for nil input")
+ }
+ if len(got) != 0 {
+ t.Fatalf("expected empty set, got %d entries", len(got))
+ }
+ })
+
+ t.Run("valid uuids are accepted and deduplicated by set semantics", func(t *testing.T) {
+ ids := []string{
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ "11111111-1111-1111-1111-111111111111", // dup is intentional
+ }
+ got, ok := parseExpectedActiveAgentIDs(ids)
+ if !ok {
+ t.Fatalf("expected ok for valid uuid list")
+ }
+ if len(got) != 2 {
+ t.Fatalf("expected dedup set of 2, got %d", len(got))
+ }
+ for _, want := range []string{
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ } {
+ if _, ok := got[want]; !ok {
+ t.Fatalf("expected %s in set", want)
+ }
+ }
+ })
+
+ t.Run("any malformed entry fails the whole list", func(t *testing.T) {
+ ids := []string{
+ "11111111-1111-1111-1111-111111111111",
+ "not-a-uuid",
+ }
+ _, ok := parseExpectedActiveAgentIDs(ids)
+ if ok {
+ t.Fatal("expected !ok for list containing malformed uuid")
+ }
+ })
+}
+
+// activeAgentSetMatches drives the runtime_delete_plan_changed branch: it
+// must report mismatch for any divergence — extra agent, missing agent, or
+// substituted agent — and accept order-insensitive set equality.
+func TestActiveAgentSetMatches(t *testing.T) {
+ mkAgent := func(id string) db.Agent {
+ u, err := uuidFromString(id)
+ if err != nil {
+ t.Fatalf("uuidFromString: %v", err)
+ }
+ return db.Agent{ID: u}
+ }
+ a1 := mkAgent("11111111-1111-1111-1111-111111111111")
+ a2 := mkAgent("22222222-2222-2222-2222-222222222222")
+ a3 := mkAgent("33333333-3333-3333-3333-333333333333")
+
+ t.Run("equal sets match regardless of order", func(t *testing.T) {
+ expected := map[string]struct{}{
+ "11111111-1111-1111-1111-111111111111": {},
+ "22222222-2222-2222-2222-222222222222": {},
+ }
+ if !activeAgentSetMatches([]db.Agent{a2, a1}, expected) {
+ t.Fatal("expected match for set-equal inputs")
+ }
+ })
+
+ t.Run("missing agent is a mismatch", func(t *testing.T) {
+ expected := map[string]struct{}{
+ "11111111-1111-1111-1111-111111111111": {},
+ "22222222-2222-2222-2222-222222222222": {},
+ }
+ if activeAgentSetMatches([]db.Agent{a1}, expected) {
+ t.Fatal("expected mismatch when an agent disappeared")
+ }
+ })
+
+ t.Run("extra agent is a mismatch", func(t *testing.T) {
+ expected := map[string]struct{}{
+ "11111111-1111-1111-1111-111111111111": {},
+ }
+ if activeAgentSetMatches([]db.Agent{a1, a2}, expected) {
+ t.Fatal("expected mismatch when a new agent appeared")
+ }
+ })
+
+ t.Run("substituted agent is a mismatch", func(t *testing.T) {
+ expected := map[string]struct{}{
+ "11111111-1111-1111-1111-111111111111": {},
+ "22222222-2222-2222-2222-222222222222": {},
+ }
+ if activeAgentSetMatches([]db.Agent{a1, a3}, expected) {
+ t.Fatal("expected mismatch when one agent was swapped for another")
+ }
+ })
+
+ t.Run("both empty matches", func(t *testing.T) {
+ if !activeAgentSetMatches(nil, map[string]struct{}{}) {
+ t.Fatal("expected empty/empty to match")
+ }
+ })
+}
+
+func uuidFromString(s string) (pgtype.UUID, error) {
+ var u pgtype.UUID
+ if err := u.Scan(s); err != nil {
+ return pgtype.UUID{}, err
+ }
+ return u, nil
+}
+
+// TestDeleteAgentRuntime_StructuredConflict covers the new 409 shape: the
+// strict DELETE refuses with `runtime_has_active_agents` and the body carries
+// the live active-agent list so the front-end can pivot to the cascade dialog
+// without a second round-trip.
+func TestDeleteAgentRuntime_StructuredConflict(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Cascade 409 Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Cascade 409 Agent")
+ _ = agentID
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.DeleteAgentRuntime(w, req)
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var body struct {
+ Error string `json:"error"`
+ Code string `json:"code"`
+ ActiveAgents []AgentResponse `json:"active_agents"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body.Code != "runtime_has_active_agents" {
+ t.Fatalf("expected code runtime_has_active_agents, got %q", body.Code)
+ }
+ if len(body.ActiveAgents) != 1 || body.ActiveAgents[0].ID != agentID {
+ t.Fatalf("expected one active agent %s, got %+v", agentID, body.ActiveAgents)
+ }
+}
+
+// TestArchiveAgentsAndDeleteRuntime_HappyPath exercises the cascade 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
+// counts.
+func TestArchiveAgentsAndDeleteRuntime_HappyPath(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Cascade Happy Runtime")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Cascade Happy 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.ArchiveAgentsAndDeleteRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Runtime row must be gone.
+ 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("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 {
+ t.Fatalf("count agent rows: %v", err)
+ }
+ if agentRows != 0 {
+ t.Fatalf("expected archived agent to be hard-deleted with runtime, found %d", agentRows)
+ }
+}
+
+// TestArchiveAgentsAndDeleteRuntime_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) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Cascade Drift Runtime")
+ agent1 := createCascadeFixtureAgent(t, ctx, runtimeID, "Cascade Drift Agent A")
+ agent2 := createCascadeFixtureAgent(t, ctx, runtimeID, "Cascade Drift Agent B")
+
+ // User confirmed only agent1 — but the live set is {agent1, agent2}.
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/runtimes/"+runtimeID+"/archive-agents-and-delete",
+ map[string]any{"expected_active_agent_ids": []string{agent1}})
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.ArchiveAgentsAndDeleteRuntime(w, req)
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var body struct {
+ Code string `json:"code"`
+ ActiveAgents []AgentResponse `json:"active_agents"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body.Code != "runtime_delete_plan_changed" {
+ t.Fatalf("expected code runtime_delete_plan_changed, got %q", body.Code)
+ }
+ if len(body.ActiveAgents) != 2 {
+ t.Fatalf("expected 2 active agents in fresh snapshot, got %d", len(body.ActiveAgents))
+ }
+ // Runtime must still exist — the plan-changed branch is non-destructive.
+ 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 != 1 {
+ t.Fatalf("expected runtime to survive plan-changed refusal, count=%d", rtRows)
+ }
+
+ _ = agent2
+}
+
+// createCascadeFixtureRuntime creates a fresh runtime owned by testUserID
+// inside testWorkspaceID and registers cleanup. Each cascade test uses its
+// own runtime so the destructive paths don't trample the shared fixture.
+func createCascadeFixtureRuntime(t *testing.T, ctx context.Context, name string) string {
+ t.Helper()
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status,
+ device_info, metadata, owner_id, last_seen_at
+ )
+ VALUES ($1, NULL, $2, 'cloud', 'cascade-test', 'online', $3, '{}'::jsonb, $4, now())
+ RETURNING id
+ `, testWorkspaceID, name, name+" device", testUserID).Scan(&runtimeID); err != nil {
+ t.Fatalf("insert cascade fixture runtime: %v", err)
+ }
+ t.Cleanup(func() {
+ // Best-effort cleanup. The cascade endpoint deletes the runtime;
+ // these statements only matter when the test failed before the
+ // cascade ran.
+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE runtime_id = $1`, runtimeID)
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)
+ })
+ return runtimeID
+}
+
+func createCascadeFixtureAgent(t *testing.T, ctx context.Context, runtimeID, name string) string {
+ t.Helper()
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, max_concurrent_tasks, owner_id
+ )
+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'private', 1, $4)
+ RETURNING id
+ `, testWorkspaceID, name, runtimeID, testUserID).Scan(&agentID); err != nil {
+ t.Fatalf("insert cascade fixture agent: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID)
+ })
+ return agentID
+}
diff --git a/server/internal/handler/runtime_test.go b/server/internal/handler/runtime_test.go
index c33a35a0e7..30ff3af4ee 100644
--- a/server/internal/handler/runtime_test.go
+++ b/server/internal/handler/runtime_test.go
@@ -36,6 +36,12 @@ func TestRuntimeHandlersRejectMalformedRuntimeID(t *testing.T) {
path: "/api/runtimes/not-a-uuid",
handle: testHandler.DeleteAgentRuntime,
},
+ {
+ name: "archive-agents-and-delete",
+ method: "POST",
+ path: "/api/runtimes/not-a-uuid/archive-agents-and-delete",
+ handle: testHandler.ArchiveAgentsAndDeleteRuntime,
+ },
{
name: "models",
method: "POST",
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 1c78a47e05..b191481c9f 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -53,6 +53,70 @@ func (q *Queries) ArchiveAgent(ctx context.Context, arg ArchiveAgentParams) (Age
return i, err
}
+const archiveAgentsByIDs = `-- name: ArchiveAgentsByIDs :many
+UPDATE agent
+SET archived_at = now(), archived_by = $1, updated_at = now()
+WHERE id = ANY($2::uuid[]) AND archived_at IS NULL
+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, skills_local
+`
+
+type ArchiveAgentsByIDsParams struct {
+ ArchivedBy pgtype.UUID `json:"archived_by"`
+ AgentIds []pgtype.UUID `json:"agent_ids"`
+}
+
+// Narrow archive that only touches the explicit ID list. Used by the
+// cascade-delete endpoint so the user's expected_active_agent_ids list
+// is the authoritative bound on what gets archived: any agent that
+// appeared on the runtime after the user opened the dialog is filtered
+// out here so it can't be silently archived even in the (vanishingly
+// rare) case where a row-level race slips past the runtime FOR UPDATE
+// lock. Returns the affected rows so the caller can broadcast
+// agent:archived per agent.
+func (q *Queries) ArchiveAgentsByIDs(ctx context.Context, arg ArchiveAgentsByIDsParams) ([]Agent, error) {
+ rows, err := q.db.Query(ctx, archiveAgentsByIDs, arg.ArchivedBy, arg.AgentIds)
+ 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.SkillsLocal,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const archiveAgentsByRuntime = `-- name: ArchiveAgentsByRuntime :many
UPDATE agent
SET archived_at = now(), archived_by = $1, updated_at = now()
@@ -1525,6 +1589,121 @@ func (q *Queries) LinkTaskToIssue(ctx context.Context, arg LinkTaskToIssueParams
return err
}
+const listActiveAgentsByRuntime = `-- name: ListActiveAgentsByRuntime :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, skills_local FROM agent
+WHERE runtime_id = $1 AND archived_at IS NULL
+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,
+// 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) {
+ rows, err := q.db.Query(ctx, listActiveAgentsByRuntime, 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.SkillsLocal,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listActiveAgentsByRuntimeForUpdate = `-- name: ListActiveAgentsByRuntimeForUpdate :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, skills_local FROM agent
+WHERE runtime_id = $1 AND archived_at IS NULL
+ORDER BY name ASC
+FOR UPDATE
+`
+
+// FOR UPDATE variant used inside the cascade-delete transaction. Locks
+// each currently-active agent row so a concurrent archive/move of one
+// of those rows blocks until our transaction commits. Pair with
+// 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.
+func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtimeID pgtype.UUID) ([]Agent, error) {
+ rows, err := q.db.Query(ctx, listActiveAgentsByRuntimeForUpdate, 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.SkillsLocal,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many
SELECT 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 FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running')
@@ -2314,7 +2493,7 @@ const updateAgentCustomEnv = `-- name: UpdateAgentCustomEnv :one
UPDATE agent
SET custom_env = $2, updated_at = now()
WHERE id = $1
-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
+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, skills_local
`
type UpdateAgentCustomEnvParams struct {
@@ -2353,6 +2532,7 @@ func (q *Queries) UpdateAgentCustomEnv(ctx context.Context, arg UpdateAgentCusto
&i.McpConfig,
&i.Model,
&i.ThinkingLevel,
+ &i.SkillsLocal,
)
return i, err
}
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index c297aee1fa..1aad412992 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -496,6 +496,49 @@ func (q *Queries) ListArchivedAgentIDsByRuntime(ctx context.Context, runtimeID p
return items, nil
}
+const lockAgentRuntime = `-- name: LockAgentRuntime :one
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility FROM agent_runtime
+WHERE id = $1
+FOR UPDATE
+`
+
+// Acquires a row-level exclusive lock on the runtime row. Used at the
+// top of the cascade-delete transaction so that:
+// 1. PostgreSQL's FK validation on agent.runtime_id (FK ... ON DELETE
+// RESTRICT) needs FOR KEY SHARE on the parent runtime row, which
+// conflicts with FOR UPDATE — so any concurrent INSERT or UPDATE
+// that would point a new/moved agent at this runtime blocks until
+// 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.
+func (q *Queries) LockAgentRuntime(ctx context.Context, id pgtype.UUID) (AgentRuntime, error) {
+ row := q.db.QueryRow(ctx, lockAgentRuntime, id)
+ var i AgentRuntime
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.DaemonID,
+ &i.Name,
+ &i.RuntimeMode,
+ &i.Provider,
+ &i.Status,
+ &i.DeviceInfo,
+ &i.Metadata,
+ &i.LastSeenAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.OwnerID,
+ &i.LegacyDaemonID,
+ &i.Visibility,
+ )
+ return i, err
+}
+
const markAgentRuntimeOnline = `-- name: MarkAgentRuntimeOnline :one
UPDATE agent_runtime
SET status = 'online', last_seen_at = now(), updated_at = now()
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 0335326a21..b7a34e8882 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -86,6 +86,45 @@ SET archived_at = now(), archived_by = @archived_by, updated_at = now()
WHERE runtime_id = ANY(@runtime_ids::uuid[]) AND archived_at IS NULL
RETURNING *;
+-- name: ArchiveAgentsByIDs :many
+-- Narrow archive that only touches the explicit ID list. Used by the
+-- cascade-delete endpoint so the user's expected_active_agent_ids list
+-- is the authoritative bound on what gets archived: any agent that
+-- appeared on the runtime after the user opened the dialog is filtered
+-- out here so it can't be silently archived even in the (vanishingly
+-- rare) case where a row-level race slips past the runtime FOR UPDATE
+-- lock. Returns the affected rows so the caller can broadcast
+-- agent:archived per agent.
+UPDATE agent
+SET archived_at = now(), archived_by = @archived_by, updated_at = now()
+WHERE id = ANY(@agent_ids::uuid[]) AND archived_at IS NULL
+RETURNING *;
+
+-- name: ListActiveAgentsByRuntime :many
+-- 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,
+-- 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
+WHERE runtime_id = $1 AND archived_at IS NULL
+ORDER BY name ASC;
+
+-- name: ListActiveAgentsByRuntimeForUpdate :many
+-- FOR UPDATE variant used inside the cascade-delete transaction. Locks
+-- each currently-active agent row so a concurrent archive/move of one
+-- of those rows blocks until our transaction commits. Pair with
+-- 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.
+SELECT * FROM agent
+WHERE runtime_id = $1 AND archived_at IS NULL
+ORDER BY name ASC
+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/runtime.sql b/server/pkg/db/queries/runtime.sql
index 8096706779..9054badd1c 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -7,6 +7,24 @@ ORDER BY created_at ASC;
SELECT * FROM agent_runtime
WHERE id = $1;
+-- name: LockAgentRuntime :one
+-- Acquires a row-level exclusive lock on the runtime row. Used at the
+-- top of the cascade-delete transaction so that:
+-- 1. PostgreSQL's FK validation on agent.runtime_id (FK ... ON DELETE
+-- RESTRICT) needs FOR KEY SHARE on the parent runtime row, which
+-- conflicts with FOR UPDATE — so any concurrent INSERT or UPDATE
+-- that would point a new/moved agent at this runtime blocks until
+-- 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.
+SELECT * FROM agent_runtime
+WHERE id = $1
+FOR UPDATE;
+
-- name: GetAgentRuntimeForWorkspace :one
SELECT * FROM agent_runtime
WHERE id = $1 AND workspace_id = $2;