Skip to content

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

Go

fix: delete custom runtime profiles from runtime rows (#4456)

Bohan Jiang294953ba379d
diff --git a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
index 906435c0f0..48fcdcdaad 100644
--- a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
+++ b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
@@ -3,7 +3,7 @@
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 { AgentRuntime } from "@multica/core/types";
+import type { AgentRuntime, RuntimeProfile } 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";
@@ -14,6 +14,11 @@ const TEST_RESOURCES = {
};
const mockUpdateRuntime = vi.hoisted(() => vi.fn());
+const mockDeleteRuntimeProfile = vi.hoisted(() => vi.fn());
+const mockQueryData = vi.hoisted(() => ({
+ members: [] as Array<Record<string, unknown>>,
+ profiles: [] as RuntimeProfile[],
+}));
vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-1",
@@ -24,6 +29,8 @@ vi.mock("@multica/core/api", () => ({
updateRuntime: (...args: unknown[]) => mockUpdateRuntime(...args),
deleteRuntime: vi.fn(),
archiveAgentsAndDeleteRuntime: vi.fn(),
+ deleteRuntimeProfile: (...args: unknown[]) =>
+ mockDeleteRuntimeProfile(...args),
},
ApiError: class ApiError extends Error {},
}));
@@ -48,7 +55,16 @@ vi.mock("@tanstack/react-query", async () => {
);
return {
...actual,
- useQuery: vi.fn(() => ({ data: [], isLoading: false })),
+ useQuery: vi.fn((options: { queryKey?: readonly unknown[] }) => {
+ const key = options?.queryKey;
+ if (key?.[0] === "runtime-profiles") {
+ return { data: mockQueryData.profiles, isLoading: false };
+ }
+ if (key?.[0] === "workspaces" && key?.[2] === "members") {
+ return { data: mockQueryData.members, isLoading: false };
+ }
+ return { data: [], isLoading: false };
+ }),
};
});
@@ -59,6 +75,15 @@ vi.mock("@multica/core/auth", () => ({
vi.mock("@multica/core/runtimes", () => ({
deriveRuntimeHealth: () => "online",
+ runtimeProfileListOptions: (wsId: string) => ({
+ queryKey: ["runtime-profiles", wsId],
+ }),
+ parseRuntimeProfileBoundConflict: () => null,
+ useDeleteRuntimeProfile: () => ({
+ mutate: vi.fn(),
+ isPending: false,
+ mutateAsync: (...args: unknown[]) => mockDeleteRuntimeProfile(...args),
+ }),
}));
vi.mock("@multica/core/agents", () => ({
@@ -130,6 +155,24 @@ function makeRuntime(overrides: Partial<AgentRuntime>): AgentRuntime {
};
}
+function makeProfile(overrides: Partial<RuntimeProfile> = {}): RuntimeProfile {
+ return {
+ id: "profile-1",
+ workspace_id: "ws-1",
+ display_name: "Custom Codex",
+ protocol_family: "codex",
+ command_name: "custom-codex",
+ description: null,
+ fixed_args: [],
+ visibility: "workspace",
+ created_by: "user-me",
+ enabled: true,
+ created_at: "2026-04-01T00:00:00Z",
+ updated_at: "2026-04-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
function renderDetail(runtime: AgentRuntime) {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
@@ -142,7 +185,12 @@ function renderDetail(runtime: AgentRuntime) {
}
describe("RuntimeDetail visibility section", () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockQueryData.members = [];
+ mockQueryData.profiles = [];
+ mockDeleteRuntimeProfile.mockResolvedValue(undefined);
+ });
it("shows owner-editable visibility choices when the caller owns the runtime", () => {
renderDetail(makeRuntime({ owner_id: "user-me" }));
@@ -196,4 +244,43 @@ describe("RuntimeDetail visibility section", () => {
screen.queryByRole("button", { name: /Delete runtime/i }),
).not.toBeInTheDocument();
});
+
+ it("routes custom runtime deletion through the profile delete dialog for admins", async () => {
+ const profile = makeProfile();
+ mockQueryData.members = [
+ { user_id: "user-me", role: "owner", name: "Me" },
+ ];
+ mockQueryData.profiles = [profile];
+
+ renderDetail(
+ makeRuntime({
+ owner_id: "someone-else",
+ profile_id: profile.id,
+ }),
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /Delete runtime/i }));
+ expect(screen.getByText("Delete custom runtime?")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Delete" }));
+ await waitFor(() =>
+ expect(mockDeleteRuntimeProfile).toHaveBeenCalledWith(profile.id),
+ );
+ });
+
+ it("hides custom runtime delete for non-admin runtime owners", () => {
+ const profile = makeProfile();
+ mockQueryData.profiles = [profile];
+
+ renderDetail(
+ makeRuntime({
+ owner_id: "user-me",
+ profile_id: profile.id,
+ }),
+ );
+
+ expect(
+ screen.queryByRole("button", { name: /Delete runtime/i }),
+ ).not.toBeInTheDocument();
+ });
});
diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsx
index 6f688570e0..2bd2a6aa39 100644
--- a/packages/views/runtimes/components/runtime-detail.tsx
+++ b/packages/views/runtimes/components/runtime-detail.tsx
@@ -10,12 +10,20 @@ import {
} from "lucide-react";
import { toast } from "sonner";
import { useQuery } from "@tanstack/react-query";
-import type { AgentRuntime, Agent, MemberWithUser } from "@multica/core/types";
+import type {
+ AgentRuntime,
+ Agent,
+ MemberWithUser,
+ RuntimeProfile,
+} 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 { useUpdateRuntime } from "@multica/core/runtimes/mutations";
-import { deriveRuntimeHealth } from "@multica/core/runtimes";
+import {
+ deriveRuntimeHealth,
+ runtimeProfileListOptions,
+} from "@multica/core/runtimes";
import {
type AgentPresenceDetail,
useWorkspacePresenceMap,
@@ -37,6 +45,7 @@ import { ProviderLogo } from "./provider-logo";
import { UpdateSection } from "./update-section";
import { UsageSection } from "./usage-section";
import { DeleteRuntimeDialog } from "./delete-runtime-dialog";
+import { DeleteRuntimeProfileDialog } from "./delete-runtime-profile-dialog";
import { useT } from "../../i18n";
function getCliVersion(metadata: Record<string, unknown>): string | null {
@@ -94,6 +103,7 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
const navigation = useNavigation();
const { data: members = [] } = useQuery(memberListOptions(wsId));
const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const { data: profiles = [] } = useQuery(runtimeProfileListOptions(wsId));
const { byAgent: presenceMap } = useWorkspacePresenceMap(wsId);
const now = useNowTick();
@@ -111,7 +121,14 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
? currentMember.role === "owner" || currentMember.role === "admin"
: false;
const isRuntimeOwner = user && runtime.owner_id === user.id;
- const canDelete = isAdmin || isRuntimeOwner;
+ const canEditRuntime = isAdmin || isRuntimeOwner;
+ const runtimeProfile: RuntimeProfile | null = runtime.profile_id
+ ? profiles.find((p) => p.id === runtime.profile_id) ?? null
+ : null;
+ const isCustomRuntime = !!runtime.profile_id;
+ const canDelete = isCustomRuntime
+ ? isAdmin && !!runtimeProfile
+ : canEditRuntime;
const servingAgents = agents.filter(
(a) => a.runtime_id === runtime.id && !a.archived_at,
@@ -120,12 +137,17 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
// 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 = () => {
+ const handleRuntimeDeleted = () => {
setDeleteOpen(false);
navigation.replace(paths.runtimes());
toast.success(t(($) => $.detail.toast_deleted));
};
+ const handleProfileDeleted = () => {
+ setDeleteOpen(false);
+ navigation.replace(paths.runtimes());
+ };
+
const daemonShort = shortDaemonId(runtime.daemon_id);
const lastSeen = formatLastSeen(runtime.last_seen_at);
@@ -139,7 +161,7 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
</span>
}
actions={
- !canDelete ? (
+ !canEditRuntime ? (
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
<Lock className="h-3 w-3" />
{t(($) => $.detail.read_only)}
@@ -178,6 +200,7 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
runtime={runtime}
cliVersion={cliVersion}
launchedBy={launchedBy}
+ canEdit={!!canEditRuntime}
canDelete={!!canDelete}
onDelete={() => setDeleteOpen(true)}
/>
@@ -185,16 +208,23 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
</div>
</div>
- {/* 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}
- />
+ {isCustomRuntime && runtimeProfile ? (
+ <DeleteRuntimeProfileDialog
+ open={deleteOpen}
+ onOpenChange={setDeleteOpen}
+ profile={runtimeProfile}
+ wsId={wsId}
+ onDeleted={handleProfileDeleted}
+ />
+ ) : (
+ <DeleteRuntimeDialog
+ open={deleteOpen}
+ onOpenChange={setDeleteOpen}
+ runtime={runtime}
+ wsId={wsId}
+ onDeleted={handleRuntimeDeleted}
+ />
+ )}
</div>
);
}
@@ -439,20 +469,19 @@ function DiagnosticsCard({
runtime,
cliVersion,
launchedBy,
+ canEdit,
canDelete,
onDelete,
}: {
runtime: AgentRuntime;
cliVersion: string | null;
launchedBy: string | null;
+ canEdit: boolean;
canDelete: boolean;
onDelete: () => void;
}) {
const { t } = useT("runtimes");
const isLocal = runtime.runtime_mode === "local";
- // canDelete here doubles as the "can edit runtime" predicate — it already
- // means "workspace owner/admin OR runtime owner", which is the same gate
- // the server enforces for the visibility PATCH.
return (
<div className="rounded-lg border">
<div className="border-b px-4 py-2.5">
@@ -463,7 +492,7 @@ function DiagnosticsCard({
<div className="mb-1.5 text-[11px] uppercase tracking-wide text-muted-foreground">
{t(($) => $.detail.diagnostics_visibility)}
</div>
- {canDelete ? (
+ {canEdit ? (
<VisibilityEditor runtime={runtime} />
) : (
<VisibilityReadout runtime={runtime} />
diff --git a/packages/views/runtimes/components/runtime-list.tsx b/packages/views/runtimes/components/runtime-list.tsx
index 5cdfe4e803..f69fac3887 100644
--- a/packages/views/runtimes/components/runtime-list.tsx
+++ b/packages/views/runtimes/components/runtime-list.tsx
@@ -15,6 +15,7 @@ import type {
AgentRuntime,
AgentTask,
MemberWithUser,
+ RuntimeProfile,
} from "@multica/core/types";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
@@ -25,6 +26,7 @@ import {
import { agentTaskSnapshotOptions } from "@multica/core/agents";
import {
deriveRuntimeHealth,
+ runtimeProfileListOptions,
runtimeUsageOptions,
} from "@multica/core/runtimes";
import { useWorkspacePaths } from "@multica/core/paths";
@@ -52,6 +54,7 @@ import { useViewingTimezone } from "../../common/use-viewing-timezone";
import { ProviderLogo } from "./provider-logo";
import { HealthIcon, useHealthLabel } from "./shared";
import { DeleteRuntimeDialog } from "./delete-runtime-dialog";
+import { DeleteRuntimeProfileDialog } from "./delete-runtime-profile-dialog";
import {
computeCostInWindow,
formatLastSeen,
@@ -134,6 +137,7 @@ const EMPTY_WORKLOAD: RuntimeWorkload = {
export interface RuntimeRow {
runtime: AgentRuntime;
+ profile: RuntimeProfile | null;
ownerMember: MemberWithUser | null;
workload: RuntimeWorkload;
canDelete: boolean;
@@ -487,15 +491,18 @@ function AgentStack({ agentIds }: { agentIds: string[] }) {
export function RuntimeRowMenu({
runtime,
+ profile,
wsId,
canDelete,
}: {
runtime: AgentRuntime;
+ profile: RuntimeProfile | null;
wsId: string;
canDelete: boolean;
}) {
const { t } = useT("runtimes");
const [deleteOpen, setDeleteOpen] = useState(false);
+ const isCustomRuntime = !!runtime.profile_id;
// 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. We
// used to also hide it for self-healing runtimes (live local daemon
@@ -533,16 +540,26 @@ export function RuntimeRowMenu({
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
- <DeleteRuntimeDialog
- open={deleteOpen}
- onOpenChange={setDeleteOpen}
- runtime={runtime}
- wsId={wsId}
- onDeleted={() => {
- setDeleteOpen(false);
- toast.success(t(($) => $.detail.toast_deleted));
- }}
- />
+ {isCustomRuntime && profile ? (
+ <DeleteRuntimeProfileDialog
+ open={deleteOpen}
+ onOpenChange={setDeleteOpen}
+ profile={profile}
+ wsId={wsId}
+ onDeleted={() => setDeleteOpen(false)}
+ />
+ ) : (
+ <DeleteRuntimeDialog
+ open={deleteOpen}
+ onOpenChange={setDeleteOpen}
+ runtime={runtime}
+ wsId={wsId}
+ onDeleted={() => {
+ setDeleteOpen(false);
+ toast.success(t(($) => $.detail.toast_deleted));
+ }}
+ />
+ )}
</>
);
}
@@ -576,6 +593,7 @@ export function RuntimeList({
const { data: agents = [] } = useQuery(agentListOptions(wsId));
const { data: members = [] } = useQuery(memberListOptions(wsId));
const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));
+ const { data: profiles = [] } = useQuery(runtimeProfileListOptions(wsId));
const currentMember = user
? members.find((m) => m.user_id === user.id)
@@ -595,6 +613,12 @@ export function RuntimeList({
return map;
}, [members]);
+ const profileById = useMemo(() => {
+ const map = new Map<string, RuntimeProfile>();
+ for (const p of profiles) map.set(p.id, p);
+ return map;
+ }, [profiles]);
+
// Owner column only earns its space when the page actually has multiple
// distinct owners — otherwise it would just be a column of identical
// avatars.
@@ -607,17 +631,26 @@ export function RuntimeList({
}, [runtimes]);
const rows = useMemo<RuntimeRow[]>(() => {
- return runtimes.map((runtime) => ({
- runtime,
- ownerMember: runtime.owner_id
- ? memberById.get(runtime.owner_id) ?? null
- : null,
- workload: workloadIndex.get(runtime.id) ?? EMPTY_WORKLOAD,
- canDelete:
- !isPendingCustomRuntime(runtime) &&
- (isAdmin || (!!user && runtime.owner_id === user.id)),
- }));
- }, [runtimes, memberById, workloadIndex, isAdmin, user]);
+ return runtimes.map((runtime) => {
+ const profile = runtime.profile_id
+ ? profileById.get(runtime.profile_id) ?? null
+ : null;
+ const isCustomRuntime = !!runtime.profile_id;
+ return {
+ runtime,
+ profile,
+ ownerMember: runtime.owner_id
+ ? memberById.get(runtime.owner_id) ?? null
+ : null,
+ workload: workloadIndex.get(runtime.id) ?? EMPTY_WORKLOAD,
+ canDelete:
+ !isPendingCustomRuntime(runtime) &&
+ (isCustomRuntime
+ ? isAdmin && !!profile
+ : isAdmin || (!!user && runtime.owner_id === user.id)),
+ };
+ });
+ }, [runtimes, profileById, memberById, workloadIndex, isAdmin, user]);
// Mirrors RuntimeRowMenu's render guard: the kebab track only earns its
// width when at least one row will actually show the menu.
@@ -710,6 +743,7 @@ export function RuntimeList({
>
<RuntimeRowMenu
runtime={row.runtime}
+ profile={row.profile}
wsId={wsId}
canDelete={row.canDelete}
/>
diff --git a/packages/views/runtimes/components/runtime-row-menu.test.tsx b/packages/views/runtimes/components/runtime-row-menu.test.tsx
index 0aefb031ee..1443458a55 100644
--- a/packages/views/runtimes/components/runtime-row-menu.test.tsx
+++ b/packages/views/runtimes/components/runtime-row-menu.test.tsx
@@ -3,7 +3,7 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, screen } from "@testing-library/react";
-import type { AgentRuntime } from "@multica/core/types";
+import type { AgentRuntime, RuntimeProfile } 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";
@@ -39,6 +39,13 @@ vi.mock("@multica/core/runtimes/mutations", () => ({
vi.mock("@multica/core/runtimes", () => ({
deriveRuntimeHealth: () => "online",
runtimeUsageOptions: () => ({ kind: "usage" }),
+ runtimeProfileListOptions: () => ({ kind: "runtime-profiles" }),
+ parseRuntimeProfileBoundConflict: () => null,
+ useDeleteRuntimeProfile: () => ({
+ mutate: vi.fn(),
+ isPending: false,
+ mutateAsync: vi.fn(),
+ }),
}));
vi.mock("@multica/core/agents", () => ({
@@ -99,9 +106,32 @@ function makeRuntime(overrides: Partial<AgentRuntime>): AgentRuntime {
};
}
-function makeRow(runtime: AgentRuntime, canDelete = true): RuntimeRow {
+function makeProfile(overrides: Partial<RuntimeProfile> = {}): RuntimeProfile {
+ return {
+ id: "profile-1",
+ workspace_id: "ws-1",
+ display_name: "Custom Codex",
+ protocol_family: "codex",
+ command_name: "custom-codex",
+ description: null,
+ fixed_args: [],
+ visibility: "workspace",
+ created_by: "user-1",
+ enabled: true,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+function makeRow(
+ runtime: AgentRuntime,
+ canDelete = true,
+ profile: RuntimeProfile | null = null,
+): RuntimeRow {
return {
runtime,
+ profile,
ownerMember: null,
workload: { agentIds: [], runningCount: 0, queuedCount: 0 },
canDelete,
@@ -118,6 +148,7 @@ function renderActionsCell(row: RuntimeRow) {
<QueryClientProvider client={qc}>
<RuntimeRowMenu
runtime={row.runtime}
+ profile={row.profile}
wsId="ws-1"
canDelete={row.canDelete}
/>
@@ -153,6 +184,18 @@ describe("runtime list row menu", () => {
expect(screen.getByLabelText("Row actions")).toBeInTheDocument();
});
+ it("renders the kebab menu for a custom runtime when the profile is available", () => {
+ const profile = makeProfile();
+ renderActionsCell(
+ makeRow(
+ makeRuntime({ runtime_mode: "local", profile_id: profile.id }),
+ true,
+ profile,
+ ),
+ );
+ expect(screen.getByLabelText("Row actions")).toBeInTheDocument();
+ });
+
it("hides the kebab menu when the caller lacks delete permission", () => {
// Pre-existing behavior — re-asserted so the new self-healing guard
// doesn't accidentally regress it (both paths return the same empty
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index 2b08ddcd69..d115d17a7b 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -32,7 +32,7 @@ type AgentRuntimeResponse struct {
// Visibility is "private" (default — only the owner / workspace admins
// can bind agents) or "public" (any workspace member can). See migration
// 083 and canUseRuntimeForAgent.
- Visibility string `json:"visibility"`
+ Visibility string `json:"visibility"`
// ProfileID is set when this runtime is an instance of a custom
// runtime_profile (MUL-3284); null for built-in runtimes.
ProfileID *string `json:"profile_id"`
@@ -568,6 +568,14 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
}
userID := uuidToString(member.UserID)
+ if rt.ProfileID.Valid {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "cannot delete a custom runtime instance directly; delete its runtime profile instead.",
+ "code": "runtime_profile_instance_delete_unsupported",
+ })
+ return
+ }
+
// Check if any active (non-archived) agents are bound to this runtime.
// Surface them on the 409 so the dialog can render the cascade plan
// directly from this response — saves a second round-trip when the
@@ -746,6 +754,14 @@ func (h *Handler) ArchiveAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.R
}
userID := uuidToString(member.UserID)
+ if rt.ProfileID.Valid {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "cannot delete a custom runtime instance directly; delete its runtime profile instead.",
+ "code": "runtime_profile_instance_delete_unsupported",
+ })
+ return
+ }
+
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to start transaction")
diff --git a/server/internal/handler/runtime_cascade_test.go b/server/internal/handler/runtime_cascade_test.go
index e72c19ff54..0dbc2f8db6 100644
--- a/server/internal/handler/runtime_cascade_test.go
+++ b/server/internal/handler/runtime_cascade_test.go
@@ -168,6 +168,41 @@ func TestDeleteAgentRuntime_StructuredConflict(t *testing.T) {
}
}
+func TestDeleteAgentRuntime_CustomProfileInstanceRefusesDirectDelete(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID, _ := createProfileBackedRuntime(t, ctx, "Custom Instance Delete Guard")
+
+ 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 {
+ Code string `json:"code"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body.Code != "runtime_profile_instance_delete_unsupported" {
+ t.Fatalf("expected runtime_profile_instance_delete_unsupported, got %q", body.Code)
+ }
+
+ 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 custom runtime instance to survive refusal, count=%d", rtRows)
+ }
+}
+
// 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
@@ -209,6 +244,42 @@ func TestArchiveAgentsAndDeleteRuntime_HappyPath(t *testing.T) {
}
}
+func TestArchiveAgentsAndDeleteRuntime_CustomProfileInstanceRefusesDirectDelete(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID, _ := createProfileBackedRuntime(t, ctx, "Custom Instance Cascade Guard")
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/runtimes/"+runtimeID+"/archive-agents-and-delete",
+ map[string]any{"expected_active_agent_ids": []string{}})
+ 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"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body.Code != "runtime_profile_instance_delete_unsupported" {
+ t.Fatalf("expected runtime_profile_instance_delete_unsupported, got %q", body.Code)
+ }
+
+ 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 custom runtime instance to survive refusal, count=%d", rtRows)
+ }
+}
+
// 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
@@ -285,6 +356,40 @@ func createCascadeFixtureRuntime(t *testing.T, ctx context.Context, name string)
return runtimeID
}
+func createProfileBackedRuntime(t *testing.T, ctx context.Context, name string) (string, string) {
+ t.Helper()
+ var profileID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO runtime_profile (
+ workspace_id, display_name, protocol_family, command_name,
+ fixed_args, visibility, created_by, enabled
+ )
+ VALUES ($1, $2, 'codex', 'custom-codex', '[]'::jsonb, 'workspace', $3, true)
+ RETURNING id
+ `, testWorkspaceID, name+" Profile", testUserID).Scan(&profileID); err != nil {
+ t.Fatalf("insert runtime profile: %v", err)
+ }
+
+ 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, profile_id, last_seen_at
+ )
+ VALUES ($1, $2, $3, 'local', 'codex', 'online', $4, '{}'::jsonb, $5, $6, now())
+ RETURNING id
+ `, testWorkspaceID, "daemon-"+profileID, name, name+" device", testUserID, profileID).Scan(&runtimeID); err != nil {
+ t.Fatalf("insert profile-backed runtime: %v", err)
+ }
+
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE runtime_id = $1`, runtimeID)
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)
+ testPool.Exec(context.Background(), `DELETE FROM runtime_profile WHERE id = $1`, profileID)
+ })
+ return runtimeID, profileID
+}
+
func createCascadeFixtureAgent(t *testing.T, ctx context.Context, runtimeID, name string) string {
t.Helper()
var agentID string