From fc09f094aae9cffa059c5ef6fa94e1693a7f0837 Mon Sep 17 00:00:00 2001 From: Michel Blaauw Date: Wed, 25 Nov 2026 17:40:36 +0100 Subject: [PATCH] fix(api): refuse to delete providers, connections and agents that are still used (#434) Providers, connections and agents are referenced from JSON (agent specs, team definitions, environment mappings, worker profiles), so no foreign key stopped a delete: it returned 204 and the dependants failed later at run time with an unrelated-looking error. Skills and worker profiles already refused. - Store: new `in_use` module with "used by" queries. `delete_provider`, `delete_connection` and `delete_agent` lock the row, refuse with the new `StoreError::InUse` while anything refers to it, then delete in the same transaction. Providers: agent model, team and step/node model overrides, worker profiles. Connections: agent connector bindings, team connectionIds and work source, environment mappings, worker profile env mappings. Agents: team steps and workflow nodes, worker profile agent scopes (team run history is still protected by the team_steps key). The bulk agent delete uses the same path, so its preview reports the same conflicts. - API: `InUse` becomes a 409 envelope whose `details` name each dependant (path `usedBy`). A permanent agent delete records what went with it (executions, triggers, tool policies, memory, runtimes, outputs deleted or detached) in the audit entry. New `GET /api/v1/agents/{id}/delete-impact` returns `usedBy` and `removes` for the confirmation dialog. - Web: the agent delete dialogs load the impact first; an agent still in use is not offered for deletion (a message names the dependants), otherwise the dialog lists what is removed. Provider and connection deletes name the dependants when refused. - Docs: agents, connections and providers guides; UI test plan. Co-Authored-By: Claude Opus 5.5 --- apps/web/app/agents/[id]/page.tsx | 13 +- apps/web/app/agents/page.tsx | 16 +- apps/web/app/connections/[id]/page.tsx | 5 +- apps/web/app/models/[id]/page.tsx | 5 +- .../agents/use-confirm-agent-delete.tsx | 59 +++++ apps/web/lib/delete-impact.test.ts | 34 +++ apps/web/lib/delete-impact.ts | 27 ++ changelog.d/434.fixed.md | 6 + crates/orbit-api/src/error.rs | 8 + crates/orbit-api/src/handlers/agents.rs | 25 +- crates/orbit-api/src/handlers/catalog.rs | 4 +- crates/orbit-api/src/openapi.rs | 1 + crates/orbit-api/src/routes.rs | 4 + crates/orbit-api/tests/api_integration.rs | 182 ++++++++++++++ crates/orbit-store/src/agents.rs | 55 ++-- crates/orbit-store/src/catalog.rs | 46 +++- crates/orbit-store/src/in_use.rs | 237 ++++++++++++++++++ crates/orbit-store/src/lib.rs | 32 +++ docs/development/ui-test-plan.md | 2 + docs/guide/agents.md | 7 +- docs/guide/connections.md | 4 +- docs/guide/providers.md | 4 +- packages/api-client/openapi.json | 91 ++++++- packages/api-client/src/schema.d.ts | 78 ++++++ 24 files changed, 881 insertions(+), 64 deletions(-) create mode 100644 apps/web/components/agents/use-confirm-agent-delete.tsx create mode 100644 apps/web/lib/delete-impact.test.ts create mode 100644 apps/web/lib/delete-impact.ts create mode 100644 changelog.d/434.fixed.md create mode 100644 crates/orbit-store/src/in_use.rs diff --git a/apps/web/app/agents/[id]/page.tsx b/apps/web/app/agents/[id]/page.tsx index 82c5818d..7fe37312 100644 --- a/apps/web/app/agents/[id]/page.tsx +++ b/apps/web/app/agents/[id]/page.tsx @@ -48,6 +48,8 @@ import { copyText } from "@/lib/browser"; import { agentSpecSchema } from "@orbit/contracts"; import { queryKeys, unwrap, useAgent, useAgentVersions, useExecutions, useOutputs, useSkills } from "@/lib/queries"; import { errorMessage } from "@orbit/api-client"; +import { useConfirmAgentDelete } from "@/components/agents/use-confirm-agent-delete"; +import { deleteFailureMessage } from "@/lib/delete-impact"; import { formatDateTime, relativeTime, titleCase } from "@/lib/utils"; import { autonomyName, brandName, capabilityLabel, cronDescription } from "@/lib/presentation"; @@ -60,6 +62,7 @@ export default function AgentDetailPage() { const router = useRouter(); const queryClient = useQueryClient(); const confirm = useConfirm(); + const confirmAgentDelete = useConfirmAgentDelete(); const agent = useAgent(agentId); const skillList = useSkills(); const outputs = useOutputs(); @@ -152,7 +155,7 @@ export default function AgentDetailPage() { void queryClient.invalidateQueries({ queryKey: queryKeys.agents() }); router.push("/agents"); }, - onError: (error) => toast.error(errorMessage(error)), + onError: (error) => toast.error(deleteFailureMessage("agent", error, errorMessage(error))), }); if (agent.isLoading) { @@ -234,13 +237,7 @@ export default function AgentDetailPage() { } async function deleteAgent() { - const confirmed = await confirm({ - title: `Delete ${data.name} permanently?`, - description: "This removes the agent and its whole execution history. It cannot be undone.", - confirmLabel: "Delete agent", - destructive: true, - }); - if (confirmed) remove.mutate(true); + if (await confirmAgentDelete({ id: agentId, name: data.name })) remove.mutate(true); } return ( diff --git a/apps/web/app/agents/page.tsx b/apps/web/app/agents/page.tsx index 19c12367..21940933 100644 --- a/apps/web/app/agents/page.tsx +++ b/apps/web/app/agents/page.tsx @@ -10,7 +10,6 @@ import { Button } from "@/components/ui/button"; import { BulkActionsBar } from "@/components/bulk-actions-bar"; import { BulkAccessDialog } from "@/components/bulk-access-dialog"; import { Callout } from "@/components/ui/callout"; -import { useConfirm } from "@/components/ui/confirm"; import { EmptyState } from "@/components/ui/empty-state"; import { PageHeader } from "@/components/ui/page-header"; import { ImportPortableButton } from "@/components/import-portable-dialog"; @@ -25,9 +24,11 @@ import { toggleId, } from "@/components/ui/resource-list"; import { AgentRow } from "@/components/agents/agent-row"; +import { useConfirmAgentDelete } from "@/components/agents/use-confirm-agent-delete"; import { api } from "@/lib/api"; import { queryKeys, unwrap, useAllAgents } from "@/lib/queries"; import { errorMessage } from "@orbit/api-client"; +import { deleteFailureMessage } from "@/lib/delete-impact"; import type { AgentSummary } from "@/lib/types"; type Filter = "current" | "active" | "draft" | "paused" | "archived"; @@ -54,7 +55,7 @@ export default function AgentsPage() { const [bulkOpen, setBulkOpen] = useState(false); const agents = useAllAgents(); const queryClient = useQueryClient(); - const confirm = useConfirm(); + const confirmAgentDelete = useConfirmAgentDelete(); const invalidateAgents = () => queryClient.invalidateQueries({ queryKey: queryKeys.agents() }); @@ -69,7 +70,7 @@ export default function AgentsPage() { toast.success("Agent deleted"); void invalidateAgents(); }, - onError: (error) => toast.error(errorMessage(error)), + onError: (error) => toast.error(deleteFailureMessage("agent", error, errorMessage(error))), }); const restore = useMutation({ @@ -210,14 +211,7 @@ export default function AgentsPage() { onSelect={(checked) => setSelected((current) => toggleId(current, agent.id, checked))} onRestore={(target) => restore.mutate(target.id)} onDelete={async (target) => { - const confirmed = await confirm({ - title: `Delete ${target.name} permanently?`, - description: - "This removes the agent and its whole execution history. It cannot be undone.", - confirmLabel: "Delete agent", - destructive: true, - }); - if (confirmed) hardDelete.mutate(target.id); + if (await confirmAgentDelete(target)) hardDelete.mutate(target.id); }} /> ))} diff --git a/apps/web/app/connections/[id]/page.tsx b/apps/web/app/connections/[id]/page.tsx index 06b2f65b..87f14f18 100644 --- a/apps/web/app/connections/[id]/page.tsx +++ b/apps/web/app/connections/[id]/page.tsx @@ -31,6 +31,7 @@ import { capabilityLabel, effectLabel, effectTone, humanizeIdentifier } from "@/ import { queryKeys, unwrap, useConnectors } from "@/lib/queries"; import { formatDateTime, relativeTime } from "@/lib/utils"; import { errorMessage } from "@orbit/api-client"; +import { deleteFailureMessage } from "@/lib/delete-impact"; function configValue(value: unknown): string { if (value === null || value === undefined || value === "") return "—"; @@ -70,7 +71,7 @@ export default function ConnectionPage() { await queryClient.invalidateQueries({ queryKey: queryKeys.connections }); router.push("/connections"); }, - onError: (error) => toast.error(errorMessage(error)), + onError: (error) => toast.error(deleteFailureMessage("connection", error, errorMessage(error))), }); if (connection.isLoading) { @@ -105,7 +106,7 @@ export default function ConnectionPage() { async function confirmRemove() { const ok = await confirm({ title: `Remove connection ${data.name}?`, - description: "Its stored credential is deleted and agents lose access through it. This cannot be undone.", + description: "Its stored credential is deleted. This cannot be undone. A connection that agents, agent teams, environment mappings or worker profiles still use is not removed; you are told which ones.", confirmLabel: "Remove connection", destructive: true, }); diff --git a/apps/web/app/models/[id]/page.tsx b/apps/web/app/models/[id]/page.tsx index e752a941..bae07ba1 100644 --- a/apps/web/app/models/[id]/page.tsx +++ b/apps/web/app/models/[id]/page.tsx @@ -34,6 +34,7 @@ import { plural, providerState, } from "@/lib/provider-meta"; +import { deleteFailureMessage } from "@/lib/delete-impact"; import { deleteProvider, setProviderEnabled, useProvider, useProviderTests, useTestProvider } from "@/lib/providers"; import { queryKeys } from "@/lib/queries"; import { formatDateTime, relativeTime } from "@/lib/utils"; @@ -65,7 +66,7 @@ export default function ProviderPage() { await queryClient.invalidateQueries({ queryKey: queryKeys.providers }); router.push("/models"); }, - onError: (error) => toast.error(errorMessage(error)), + onError: (error) => toast.error(deleteFailureMessage("provider", error, errorMessage(error))), }); if (provider.isLoading) { @@ -113,7 +114,7 @@ export default function ProviderPage() { const ok = await confirm({ title: `Delete provider ${data.name}?`, description: - "Agents and worker profiles that use it cannot run until you pick another provider. Its stored credential is deleted. This cannot be undone.", + "Its stored credential is deleted. This cannot be undone. A provider that agents, agent teams or worker profiles still use is not deleted; you are told which ones.", confirmLabel: "Delete provider", destructive: true, }); diff --git a/apps/web/components/agents/use-confirm-agent-delete.tsx b/apps/web/components/agents/use-confirm-agent-delete.tsx new file mode 100644 index 00000000..08fe7158 --- /dev/null +++ b/apps/web/components/agents/use-confirm-agent-delete.tsx @@ -0,0 +1,59 @@ +"use client"; + +import { toast } from "sonner"; +import { errorMessage } from "@orbit/api-client"; + +import { useConfirm } from "@/components/ui/confirm"; +import { api } from "@/lib/api"; +import { stillUsedMessage } from "@/lib/delete-impact"; +import { unwrap } from "@/lib/queries"; + +/** + * Ask before permanently deleting an agent (#434). Loads what the delete would be refused + * for and what it removes: an agent still used by a team or worker profile is not offered + * for deletion; otherwise the dialog lists the executions, triggers and outputs that go too. + */ +export function useConfirmAgentDelete() { + const confirm = useConfirm(); + return async (agent: { id: string; name: string }): Promise => { + let impact: { usedBy: string[]; removes: string[] }; + try { + impact = unwrap( + await api.GET("/api/v1/agents/{agent_id}/delete-impact", { + params: { path: { agent_id: agent.id } }, + }), + ); + } catch (error) { + toast.error(errorMessage(error)); + return false; + } + if (impact.usedBy.length) { + toast.error(stillUsedMessage("agent", impact.usedBy)); + return false; + } + return confirm({ + title: `Delete ${agent.name} permanently?`, + description: ( + + + {impact.removes.length + ? "This removes the agent together with:" + : "This removes the agent. It has no history, triggers or outputs."} + + {impact.removes.length ? ( + + {impact.removes.map((line) => ( + + • {line} + + ))} + + ) : null} + It cannot be undone. + + ), + confirmLabel: "Delete agent", + destructive: true, + }); + }; +} diff --git a/apps/web/lib/delete-impact.test.ts b/apps/web/lib/delete-impact.test.ts new file mode 100644 index 00000000..44787e13 --- /dev/null +++ b/apps/web/lib/delete-impact.test.ts @@ -0,0 +1,34 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { ApiError } from "./api-error.ts"; +import { deleteFailureMessage, stillUsedMessage, usedByFromError } from "./delete-impact.ts"; + +test("usedByFromError reads only usedBy details of a 409", () => { + const conflict = new ApiError(409, "provider is still used by agent Triage", { + code: "conflict", + details: [ + { path: "usedBy", message: "agent Triage" }, + { path: "usedBy", message: "worker profile ci" }, + { path: "other", message: "ignored" }, + ], + }); + assert.deepEqual(usedByFromError(conflict), ["agent Triage", "worker profile ci"]); + assert.deepEqual( + usedByFromError(new ApiError(422, "bad", { details: [{ path: "usedBy", message: "x" }] })), + [], + ); + assert.deepEqual(usedByFromError(new Error("plain")), []); +}); + +test("deleteFailureMessage names the dependants or falls back", () => { + const conflict = new ApiError(409, "in use", { + details: [{ path: "usedBy", message: "agent team Release" }], + }); + assert.equal( + deleteFailureMessage("connection", conflict, "fallback"), + "This connection is still used by agent team Release. Remove it there first.", + ); + assert.equal(deleteFailureMessage("connection", new Error("boom"), "boom"), "boom"); + assert.equal(stillUsedMessage("agent", ["a", "b"]), "This agent is still used by a, b. Remove it there first."); +}); diff --git a/apps/web/lib/delete-impact.ts b/apps/web/lib/delete-impact.ts new file mode 100644 index 00000000..e7ba9bd2 --- /dev/null +++ b/apps/web/lib/delete-impact.ts @@ -0,0 +1,27 @@ +import { ApiError } from "./api-error.ts"; + +/** What a permanent agent delete would be refused for and what it would remove (#434). */ +export interface DeleteImpact { + usedBy: string[]; + removes: string[]; +} + +/** + * The dependants named by a 409 "still used by" refusal (`details` with path `usedBy`), or an + * empty list for any other error. + */ +export function usedByFromError(error: unknown): string[] { + if (!(error instanceof ApiError) || error.status !== 409) return []; + return (error.details ?? []).filter((detail) => detail.path === "usedBy").map((detail) => detail.message); +} + +/** One sentence naming what still uses an item, for a toast after a refused delete. */ +export function stillUsedMessage(noun: string, usedBy: string[]): string { + return `This ${noun} is still used by ${usedBy.join(", ")}. Remove it there first.`; +} + +/** The message for a failed delete: the dependants when the API listed them, else `fallback`. */ +export function deleteFailureMessage(noun: string, error: unknown, fallback: string): string { + const usedBy = usedByFromError(error); + return usedBy.length ? stillUsedMessage(noun, usedBy) : fallback; +} diff --git a/changelog.d/434.fixed.md b/changelog.d/434.fixed.md new file mode 100644 index 00000000..2a51e050 --- /dev/null +++ b/changelog.d/434.fixed.md @@ -0,0 +1,6 @@ +- Deleting a provider, connection or agent that is still in use is refused with `409` + naming what uses it (in `details`, path `usedBy`), instead of leaving agents, agent + teams, environment mappings and worker profiles pointing at nothing (#434). The agent + delete dialog lists what is removed with the agent (executions, triggers, tool + policies, memory, outputs), the audit entry records it, and + `GET /api/v1/agents/{id}/delete-impact` returns both lists. diff --git a/crates/orbit-api/src/error.rs b/crates/orbit-api/src/error.rs index 4cf7018f..5966af72 100644 --- a/crates/orbit-api/src/error.rs +++ b/crates/orbit-api/src/error.rs @@ -125,6 +125,14 @@ impl From for ApiError { match err { StoreError::NotFound(what) => ApiError::not_found(what), StoreError::Conflict(message) => ApiError::conflict(message), + StoreError::InUse { resource, used_by } => { + let mut error = ApiError::conflict(StoreError::in_use_message(&resource, &used_by)); + error.details = used_by + .into_iter() + .map(|dependant| ValidationIssue::new("usedBy", dependant)) + .collect(); + error + } StoreError::Invalid(message) => ApiError::bad_request(message), StoreError::Database(err) => { if let Some(db) = err.as_database_error() { diff --git a/crates/orbit-api/src/handlers/agents.rs b/crates/orbit-api/src/handlers/agents.rs index 97abd107..70f718b9 100644 --- a/crates/orbit-api/src/handlers/agents.rs +++ b/crates/orbit-api/src/handlers/agents.rs @@ -311,7 +311,7 @@ pub struct DeleteAgentQuery { pub hard: Option, } -#[utoipa::path(delete, path = "/api/v1/agents/{agent_id}", tag = "agents", params(DeleteAgentQuery), responses((status = 200, body = AgentDetail), (status = 204)))] +#[utoipa::path(delete, path = "/api/v1/agents/{agent_id}", tag = "agents", params(DeleteAgentQuery), responses((status = 200, body = AgentDetail), (status = 204), (status = 409, description = "A permanent delete is refused while agent teams or worker profiles use the agent; `details` lists them (path `usedBy`)", body = crate::error::ErrorEnvelope)))] pub async fn delete_agent( State(state): State, Extension(auth): Extension, @@ -321,14 +321,15 @@ pub async fn delete_agent( auth.require(Permission::AgentsWrite)?; require_agent_manage(&state, &auth, agent_id).await?; if query.hard.unwrap_or(false) { - state.store.delete_agent(auth.org_id, agent_id).await?; + let agent = state.store.get_agent(auth.org_id, agent_id).await?; + let removed = state.store.delete_agent(auth.org_id, agent_id).await?; audit::record( &state, &auth, "agent.deleted", Some("agent"), Some(agent_id), - serde_json::json!({ "hard": true }), + serde_json::json!({ "hard": true, "name": agent.name, "removed": removed }), ) .await; return Ok(StatusCode::NO_CONTENT.into_response()); @@ -349,6 +350,24 @@ pub async fn delete_agent( Ok(Json(load_agent_detail(&state, &auth, agent_id).await?).into_response()) } +/// What a permanent delete of the agent would be refused for (`usedBy`) and what it would +/// remove with it (`removes`), for the confirmation dialog (#434). +#[utoipa::path(get, path = "/api/v1/agents/{agent_id}/delete-impact", tag = "agents", responses((status = 200, body = orbit_store::in_use::AgentDeleteImpact)))] +pub async fn agent_delete_impact( + State(state): State, + Extension(auth): Extension, + Path(agent_id): Path, +) -> Result, ApiError> { + auth.require(Permission::AgentsWrite)?; + require_agent_manage(&state, &auth, agent_id).await?; + Ok(Json( + state + .store + .agent_delete_impact(auth.org_id, agent_id) + .await?, + )) +} + #[utoipa::path(post, path = "/api/v1/agents/{agent_id}/activate", tag = "agents", responses((status = 200, body = AgentDetail)))] pub async fn activate_agent( State(state): State, diff --git a/crates/orbit-api/src/handlers/catalog.rs b/crates/orbit-api/src/handlers/catalog.rs index 5b39a8da..a59f6697 100644 --- a/crates/orbit-api/src/handlers/catalog.rs +++ b/crates/orbit-api/src/handlers/catalog.rs @@ -273,7 +273,7 @@ pub async fn update_provider( Ok(Json(ProviderView::from_record(provider))) } -#[utoipa::path(delete, path = "/api/v1/providers/{provider_id}", tag = "providers", responses((status = 204)))] +#[utoipa::path(delete, path = "/api/v1/providers/{provider_id}", tag = "providers", responses((status = 204), (status = 409, description = "Refused while agents, agent teams or worker profiles use the provider; `details` lists them (path `usedBy`)", body = crate::error::ErrorEnvelope)))] pub async fn delete_provider( State(state): State, Extension(auth): Extension, @@ -783,7 +783,7 @@ fn changed_url_field( .find(|field| normalized(before, field) != normalized(after, field)) } -#[utoipa::path(delete, path = "/api/v1/connections/{connection_id}", tag = "connectors", responses((status = 204)))] +#[utoipa::path(delete, path = "/api/v1/connections/{connection_id}", tag = "connectors", responses((status = 204), (status = 409, description = "Refused while agents, agent teams, environment mappings or worker profiles use the connection; `details` lists them (path `usedBy`)", body = crate::error::ErrorEnvelope)))] pub async fn delete_connection( State(state): State, Extension(auth): Extension, diff --git a/crates/orbit-api/src/openapi.rs b/crates/orbit-api/src/openapi.rs index 52660d20..60f67de2 100644 --- a/crates/orbit-api/src/openapi.rs +++ b/crates/orbit-api/src/openapi.rs @@ -38,6 +38,7 @@ use crate::handlers; handlers::bulk_lifecycle::bulk_archive_agents, handlers::bulk_lifecycle::bulk_delete_agents, handlers::agents::activate_agent, + handlers::agents::agent_delete_impact, handlers::agents::pause_agent, handlers::agents::list_versions, handlers::agents::export_agent, diff --git a/crates/orbit-api/src/routes.rs b/crates/orbit-api/src/routes.rs index ac2a454d..4d664e5b 100644 --- a/crates/orbit-api/src/routes.rs +++ b/crates/orbit-api/src/routes.rs @@ -62,6 +62,10 @@ pub fn build_router(state: AppState) -> Router { "/api/v1/agents/{agent_id}/activate", post(handlers::agents::activate_agent), ) + .route( + "/api/v1/agents/{agent_id}/delete-impact", + get(handlers::agents::agent_delete_impact), + ) .route( "/api/v1/agents/{agent_id}/pause", post(handlers::agents::pause_agent), diff --git a/crates/orbit-api/tests/api_integration.rs b/crates/orbit-api/tests/api_integration.rs index 97176072..6ad74cad 100644 --- a/crates/orbit-api/tests/api_integration.rs +++ b/crates/orbit-api/tests/api_integration.rs @@ -15087,3 +15087,185 @@ async fn a_workflow_run_is_started_once_by_whoever_gets_there_first() { .unwrap(); assert_eq!(executions, 2); } + +fn delete_req(path: &str) -> Request { + Request::builder() + .method("DELETE") + .uri(path) + .body(Body::empty()) + .unwrap() +} + +fn used_by(body: &Value) -> Vec { + body["error"]["details"] + .as_array() + .into_iter() + .flatten() + .filter(|detail| detail["path"] == "usedBy") + .filter_map(|detail| detail["message"].as_str().map(str::to_owned)) + .collect() +} + +/// #434: providers, connections and agents that are still used cannot be deleted; the 409 +/// names what uses them, and a permanent agent delete records what went with it. +#[tokio::test] +async fn in_use_providers_connections_and_agents_refuse_delete() { + let Some(app) = test_app(true).await else { + return; + }; + let suffix = Uuid::now_v7().simple().to_string(); + + // Provider named by an agent's model. + let provider_name = format!("in-use-{suffix}"); + let (status, provider) = send( + &app.router, + post( + "/api/v1/providers", + json!({ "name": provider_name, "kind": "openai_compatible", + "config": { "baseUrl": "http://localhost:9999/v1", "model": "qwen" } }), + ), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{provider}"); + let provider_id = provider["id"].as_str().unwrap().to_string(); + let mut agent = definition(); + agent["metadata"]["name"] = json!(format!("Uses provider {suffix}")); + agent["spec"]["model"] = + json!({ "management": "platform", "provider": provider_name, "model": "qwen" }); + let (status, body) = send(&app.router, post("/api/v1/agents", agent)).await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + let provider_agent = body["id"].as_str().unwrap().to_string(); + + let (status, body) = send( + &app.router, + delete_req(&format!("/api/v1/providers/{provider_id}")), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "{body}"); + assert_eq!(body["error"]["code"], "conflict"); + assert_eq!(used_by(&body), [format!("agent Uses provider {suffix}")]); + + // Connection used by an environment mapping. + let (status, connection) = send( + &app.router, + post( + "/api/v1/connections", + json!({ "connectorSlug": "telegram", "name": format!("Bot {suffix}"), + "credential": "123456:bot-secret" }), + ), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{connection}"); + let connection_id = connection["id"].as_str().unwrap().to_string(); + let (status, mapping) = send( + &app.router, + post( + "/api/v1/env-mappings", + json!({ "name": format!("map-{suffix}"), + "mappings": [{ "envVar": "TOKEN", "connectionId": connection_id }] }), + ), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{mapping}"); + let (status, body) = send( + &app.router, + delete_req(&format!("/api/v1/connections/{connection_id}")), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "{body}"); + assert_eq!( + used_by(&body), + [format!("environment mapping map-{suffix}")] + ); + + // Agent listed in a team. + let team_name = format!("Uses agent {suffix}"); + let (status, team) = send( + &app.router, + post( + "/api/v1/agent-teams", + json!({ "name": team_name, "mode": "pipeline", + "steps": [{ "agentId": app.agent_id }] }), + ), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{team}"); + let team_id = team["id"].as_str().unwrap().to_string(); + let agent_path = format!("/api/v1/agents/{}", app.agent_id); + let (status, impact) = send(&app.router, get(&format!("{agent_path}/delete-impact"))).await; + assert_eq!(status, StatusCode::OK, "{impact}"); + assert_eq!(impact["usedBy"], json!([format!("agent team {team_name}")])); + assert!( + impact["removes"] + .as_array() + .unwrap() + .contains(&json!("1 trigger")), + "{impact}" + ); + let (status, body) = send(&app.router, delete_req(&format!("{agent_path}?hard=true"))).await; + assert_eq!(status, StatusCode::CONFLICT, "{body}"); + assert_eq!(used_by(&body), [format!("agent team {team_name}")]); + // The bulk delete applies the same rule. + let (status, body) = send( + &app.router, + post( + "/api/v1/agents/bulk/delete", + json!({ "ids": [app.agent_id], "dryRun": true }), + ), + ) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(body["failed"][0]["code"], "conflict", "{body}"); + + // Once the dependants are gone the deletes go through. + let (status, _) = send( + &app.router, + delete_req(&format!("/api/v1/agent-teams/{team_id}")), + ) + .await; + assert!(status.is_success(), "{status}"); + let (status, body) = send(&app.router, delete_req(&format!("{agent_path}?hard=true"))).await; + assert_eq!(status, StatusCode::NO_CONTENT, "{body}"); + let (entries, _) = app + .store + .list_audit_logs(app.org_id, 10, None, Some("agent.deleted")) + .await + .unwrap(); + let entry = entries.into_iter().next().expect("audit entry"); + assert!( + entry.metadata["removed"] + .as_array() + .unwrap() + .contains(&json!("1 trigger")), + "{:?}", + entry.metadata + ); + + let (status, _) = send( + &app.router, + delete_req(&format!("/api/v1/agents/{provider_agent}?hard=true")), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + let (status, body) = send( + &app.router, + delete_req(&format!("/api/v1/providers/{provider_id}")), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT, "{body}"); + let (status, _) = send( + &app.router, + delete_req(&format!( + "/api/v1/env-mappings/{}", + mapping["id"].as_str().unwrap() + )), + ) + .await; + assert!(status.is_success(), "{status}"); + let (status, body) = send( + &app.router, + delete_req(&format!("/api/v1/connections/{connection_id}")), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT, "{body}"); +} diff --git a/crates/orbit-store/src/agents.rs b/crates/orbit-store/src/agents.rs index 45da3491..24997368 100644 --- a/crates/orbit-store/src/agents.rs +++ b/crates/orbit-store/src/agents.rs @@ -405,19 +405,16 @@ impl Store { } /// Permanently delete an agent together with its versions, executions and other - /// agent-owned history. Refused with a `Conflict` while team run steps still reference - /// the agent: that history belongs to the team, not to the agent. - pub async fn delete_agent(&self, org_id: Uuid, agent_id: Uuid) -> StoreResult<()> { - let result = sqlx::query("DELETE FROM agents WHERE org_id = $1 AND id = $2") - .bind(org_id) - .bind(agent_id) - .execute(&self.pool) - .await - .map_err(agent_delete_error)?; - if result.rows_affected() == 0 { - return Err(StoreError::NotFound("agent".into())); - } - Ok(()) + /// agent-owned history, and return what went with it (for the audit entry). + /// + /// Refused with [`StoreError::InUse`] while an agent team or worker profile still lists + /// the agent (#434), and with a `Conflict` while team run steps reference it: that + /// history belongs to the team, not to the agent. + pub async fn delete_agent(&self, org_id: Uuid, agent_id: Uuid) -> StoreResult> { + let mut tx = self.begin().await?; + let removes = Self::delete_agent_in(&mut tx, org_id, agent_id).await?; + tx.commit().await?; + Ok(removes) } /// Check delete eligibility using the same SQL (and therefore the same FK rules) as @@ -425,17 +422,35 @@ impl Store { /// deleted" reflects the real database constraints, not a hand-maintained copy. pub async fn check_delete_agent(&self, org_id: Uuid, agent_id: Uuid) -> StoreResult<()> { let mut tx = self.begin().await?; - let result = sqlx::query("DELETE FROM agents WHERE org_id = $1 AND id = $2") + Self::delete_agent_in(&mut tx, org_id, agent_id).await?; + tx.rollback().await?; + Ok(()) + } + + async fn delete_agent_in( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + org_id: Uuid, + agent_id: Uuid, + ) -> StoreResult> { + let found: Option = + sqlx::query_scalar("SELECT id FROM agents WHERE org_id = $1 AND id = $2 FOR UPDATE") + .bind(org_id) + .bind(agent_id) + .fetch_optional(&mut **tx) + .await?; + if found.is_none() { + return Err(StoreError::NotFound("agent".into())); + } + let used_by = crate::in_use::agent_used_by(tx, org_id, agent_id).await?; + StoreError::refuse_in_use("agent", used_by)?; + let removes = Self::agent_cascade_in(tx, org_id, agent_id).await?; + sqlx::query("DELETE FROM agents WHERE org_id = $1 AND id = $2") .bind(org_id) .bind(agent_id) - .execute(&mut *tx) + .execute(&mut **tx) .await .map_err(agent_delete_error)?; - if result.rows_affected() == 0 { - return Err(StoreError::NotFound("agent".into())); - } - tx.rollback().await?; - Ok(()) + Ok(removes) } /// Validation report combining domain rules with store-level checks (provider and diff --git a/crates/orbit-store/src/catalog.rs b/crates/orbit-store/src/catalog.rs index 975b596e..95d29f22 100644 --- a/crates/orbit-store/src/catalog.rs +++ b/crates/orbit-store/src/catalog.rs @@ -202,15 +202,28 @@ impl Store { .ok_or_else(|| StoreError::NotFound("provider".into())) } + /// Delete a provider. Refused with [`StoreError::InUse`] while an agent, agent team or + /// worker profile still names it (#434). pub async fn delete_provider(&self, org_id: Uuid, provider_id: Uuid) -> StoreResult<()> { - let result = sqlx::query("DELETE FROM providers WHERE org_id = $1 AND id = $2") + let mut tx = self.begin().await?; + // Lock the row first so a concurrent save that starts using it waits or fails. + let found: Option = + sqlx::query_scalar("SELECT id FROM providers WHERE org_id = $1 AND id = $2 FOR UPDATE") + .bind(org_id) + .bind(provider_id) + .fetch_optional(&mut *tx) + .await?; + if found.is_none() { + return Err(StoreError::NotFound("provider".into())); + } + let used_by = crate::in_use::provider_used_by(&mut tx, org_id, provider_id).await?; + StoreError::refuse_in_use("provider", used_by)?; + sqlx::query("DELETE FROM providers WHERE org_id = $1 AND id = $2") .bind(org_id) .bind(provider_id) - .execute(&self.pool) + .execute(&mut *tx) .await?; - if result.rows_affected() == 0 { - return Err(StoreError::NotFound("provider".into())); - } + tx.commit().await?; Ok(()) } @@ -422,15 +435,28 @@ impl Store { .ok_or_else(|| StoreError::NotFound("connection".into())) } + /// Delete a connection. Refused with [`StoreError::InUse`] while an agent binding, agent + /// team, environment mapping or worker profile still points at it (#434). pub async fn delete_connection(&self, org_id: Uuid, connection_id: Uuid) -> StoreResult<()> { - let result = sqlx::query("DELETE FROM connections WHERE org_id = $1 AND id = $2") + let mut tx = self.begin().await?; + let found: Option = sqlx::query_scalar( + "SELECT id FROM connections WHERE org_id = $1 AND id = $2 FOR UPDATE", + ) + .bind(org_id) + .bind(connection_id) + .fetch_optional(&mut *tx) + .await?; + if found.is_none() { + return Err(StoreError::NotFound("connection".into())); + } + let used_by = crate::in_use::connection_used_by(&mut tx, org_id, connection_id).await?; + StoreError::refuse_in_use("connection", used_by)?; + sqlx::query("DELETE FROM connections WHERE org_id = $1 AND id = $2") .bind(org_id) .bind(connection_id) - .execute(&self.pool) + .execute(&mut *tx) .await?; - if result.rows_affected() == 0 { - return Err(StoreError::NotFound("connection".into())); - } + tx.commit().await?; Ok(()) } } diff --git a/crates/orbit-store/src/in_use.rs b/crates/orbit-store/src/in_use.rs new file mode 100644 index 00000000..2b60020d --- /dev/null +++ b/crates/orbit-store/src/in_use.rs @@ -0,0 +1,237 @@ +//! "Used by" lookups for deletes (#434). Providers, connections and agents are referenced +//! from JSON (agent specs, team definitions, env mappings), so no foreign key stops a delete +//! that leaves the dependant pointing at nothing. Each delete runs these queries in its own +//! transaction and refuses with [`StoreError::InUse`] while anything still refers to the item. + +use serde::Serialize; +use sqlx::{Postgres, Transaction}; +use uuid::Uuid; + +use crate::{Store, StoreError, StoreResult, IN_USE_LIMIT}; + +/// What permanently deleting an agent would do: what blocks it, and what goes with it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct AgentDeleteImpact { + /// Records that still use the agent. While any are listed, the delete is refused. + pub used_by: Vec, + /// Records the delete removes or changes with the agent, such as "3 executions" or + /// "output Slack alerts (deleted)". + pub removes: Vec, +} + +pub(crate) async fn provider_used_by( + tx: &mut Transaction<'_, Postgres>, + org_id: Uuid, + provider_id: Uuid, +) -> StoreResult> { + let query = r#" + WITH target AS (SELECT name FROM providers WHERE org_id = $1 AND id = $2) + SELECT label FROM ( + SELECT 'agent ' || a.name AS label + FROM agents a + JOIN agent_versions v ON v.agent_id = a.id AND v.version = a.current_version + JOIN target t ON v.spec -> 'model' ->> 'provider' = t.name + WHERE a.org_id = $1 + UNION + SELECT 'agent team ' || tm.name + FROM agent_teams tm, target t + WHERE tm.org_id = $1 + AND (tm.definition -> 'model' ->> 'provider' = t.name + OR EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tm.definition -> 'steps') = 'array' THEN tm.definition -> 'steps' ELSE '[]'::jsonb END) s WHERE s -> 'model' ->> 'provider' = t.name) + OR EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tm.definition -> 'workflow' -> 'nodes') = 'array' THEN tm.definition -> 'workflow' -> 'nodes' ELSE '[]'::jsonb END) n WHERE n -> 'model' ->> 'provider' = t.name)) + UNION + SELECT 'worker profile ' || p.name + FROM worker_profiles p, target t + WHERE p.org_id = $1 AND p.provider = t.name + ) used + ORDER BY label + LIMIT $3 + "#; + Ok(sqlx::query_scalar(query) + .bind(org_id) + .bind(provider_id) + .bind(IN_USE_LIMIT) + .fetch_all(&mut **tx) + .await?) +} + +pub(crate) async fn connection_used_by( + tx: &mut Transaction<'_, Postgres>, + org_id: Uuid, + connection_id: Uuid, +) -> StoreResult> { + let query = r#" + SELECT label FROM ( + SELECT 'agent ' || a.name AS label + FROM agents a + JOIN agent_versions v ON v.agent_id = a.id AND v.version = a.current_version + WHERE a.org_id = $1 + AND EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(v.spec -> 'connectors') = 'array' THEN v.spec -> 'connectors' ELSE '[]'::jsonb END) c WHERE c ->> 'connectionId' = $2::text) + UNION + SELECT 'agent team ' || tm.name + FROM agent_teams tm + WHERE tm.org_id = $1 + AND (tm.definition -> 'connectionIds' ? $2::text + OR tm.definition -> 'workSource' ->> 'connectionId' = $2::text) + UNION + SELECT 'environment mapping ' || e.name + FROM env_mappings e + WHERE e.org_id = $1 + AND EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(e.mappings) = 'array' THEN e.mappings ELSE '[]'::jsonb END) m WHERE m ->> 'connectionId' = $2::text) + UNION + SELECT 'worker profile ' || p.name + FROM worker_profiles p + WHERE p.org_id = $1 + AND EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(p.env_mappings) = 'array' THEN p.env_mappings ELSE '[]'::jsonb END) m WHERE m ->> 'connectionId' = $2::text) + ) used + ORDER BY label + LIMIT $3 + "#; + Ok(sqlx::query_scalar(query) + .bind(org_id) + .bind(connection_id) + .bind(IN_USE_LIMIT) + .fetch_all(&mut **tx) + .await?) +} + +/// Agent teams (pipeline steps or workflow nodes) and worker profiles scoped to the agent. +/// Team run history is protected separately by the `team_steps` foreign key. +pub(crate) async fn agent_used_by( + tx: &mut Transaction<'_, Postgres>, + org_id: Uuid, + agent_id: Uuid, +) -> StoreResult> { + let query = r#" + SELECT label FROM ( + SELECT 'agent team ' || tm.name AS label + FROM agent_teams tm + WHERE tm.org_id = $1 + AND (EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tm.definition -> 'steps') = 'array' THEN tm.definition -> 'steps' ELSE '[]'::jsonb END) s WHERE s ->> 'agentId' = $2::text) + OR EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tm.definition -> 'workflow' -> 'nodes') = 'array' THEN tm.definition -> 'workflow' -> 'nodes' ELSE '[]'::jsonb END) n WHERE n ->> 'agentId' = $2::text)) + UNION + SELECT 'worker profile ' || p.name + FROM worker_profiles p + WHERE p.org_id = $1 AND $2 = ANY(p.agent_ids) + ) used + ORDER BY label + LIMIT $3 + "#; + Ok(sqlx::query_scalar(query) + .bind(org_id) + .bind(agent_id) + .bind(IN_USE_LIMIT) + .fetch_all(&mut **tx) + .await?) +} + +/// What the `ON DELETE CASCADE` keys and the output trigger remove with the agent. +async fn agent_cascade( + tx: &mut Transaction<'_, Postgres>, + org_id: Uuid, + agent_id: Uuid, +) -> StoreResult> { + let (executions, triggers, policies, memories, runtimes): (i64, i64, i64, i64, i64) = + sqlx::query_as( + r#" + SELECT + (SELECT count(*) FROM executions WHERE org_id = $1 AND agent_id = $2), + (SELECT count(*) FROM triggers WHERE org_id = $1 AND agent_id = $2), + (SELECT count(*) FROM tool_policies WHERE org_id = $1 AND agent_id = $2), + (SELECT count(*) FROM agent_memory WHERE agent_id = $2), + (SELECT count(*) FROM agent_runtimes WHERE agent_id = $2) + "#, + ) + .bind(org_id) + .bind(agent_id) + .fetch_one(&mut **tx) + .await?; + let mut removes = Vec::new(); + for (count, singular, plural) in [ + (executions, "execution", "executions"), + (triggers, "trigger", "triggers"), + (policies, "tool policy", "tool policies"), + (memories, "memory entry", "memory entries"), + (runtimes, "runtime", "runtimes"), + ] { + if count > 0 { + removes.push(format!( + "{count} {}", + if count == 1 { singular } else { plural } + )); + } + } + // Same rule as `orbit_remove_agent_from_outputs` (migration 0062) and the legacy + // `outputs.agent_id` cascade. + let outputs: Vec<(String, bool)> = sqlx::query_as( + r#" + SELECT name, + agent_id = $2 + OR (team_id IS NULL AND cardinality(array_remove(agent_ids, $2)) = 0) + FROM outputs + WHERE org_id = $1 AND (agent_id = $2 OR $2 = ANY(agent_ids)) + ORDER BY name + "#, + ) + .bind(org_id) + .bind(agent_id) + .fetch_all(&mut **tx) + .await?; + for (name, deleted) in outputs { + removes.push(if deleted { + format!("output {name} (deleted)") + } else { + format!("output {name} (no longer sent for this agent)") + }); + } + Ok(removes) +} + +impl Store { + /// What a permanent delete of the agent would be refused for, and what it would remove. + pub async fn agent_delete_impact( + &self, + org_id: Uuid, + agent_id: Uuid, + ) -> StoreResult { + let mut tx = self.begin().await?; + let exists: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM agents WHERE org_id = $1 AND id = $2)", + ) + .bind(org_id) + .bind(agent_id) + .fetch_one(&mut *tx) + .await?; + if !exists { + return Err(StoreError::NotFound("agent".into())); + } + let mut used_by = agent_used_by(&mut tx, org_id, agent_id).await?; + let team_runs: i64 = sqlx::query_scalar( + "SELECT count(DISTINCT run_id) FROM team_steps WHERE org_id = $1 AND agent_id = $2", + ) + .bind(org_id) + .bind(agent_id) + .fetch_one(&mut *tx) + .await?; + if team_runs > 0 { + used_by.push(format!( + "{team_runs} agent team {}", + if team_runs == 1 { "run" } else { "runs" } + )); + } + let removes = agent_cascade(&mut tx, org_id, agent_id).await?; + tx.rollback().await?; + Ok(AgentDeleteImpact { used_by, removes }) + } + + /// The cascade of a permanent agent delete, read inside the deleting transaction so the + /// audit entry lists exactly what went. + pub(crate) async fn agent_cascade_in( + tx: &mut Transaction<'_, Postgres>, + org_id: Uuid, + agent_id: Uuid, + ) -> StoreResult> { + agent_cascade(tx, org_id, agent_id).await + } +} diff --git a/crates/orbit-store/src/lib.rs b/crates/orbit-store/src/lib.rs index 77bb92ea..1678f415 100644 --- a/crates/orbit-store/src/lib.rs +++ b/crates/orbit-store/src/lib.rs @@ -42,6 +42,7 @@ pub mod dashboard; pub mod env_mappings; pub mod executions; pub mod identity; +pub mod in_use; pub mod metrics; pub mod models; pub mod observe; @@ -67,6 +68,13 @@ pub enum StoreError { NotFound(String), #[error("conflict: {0}")] Conflict(String), + /// A delete was refused because other records still use the item. `used_by` names + /// them ("agent Triage", "worker profile ci"), at most [`IN_USE_LIMIT`] entries. + #[error("conflict: {} is still used by {}; remove it there first", .resource, .used_by.join(", "))] + InUse { + resource: String, + used_by: Vec, + }, #[error("invalid: {0}")] Invalid(String), #[error("database error: {0}")] @@ -105,6 +113,30 @@ impl StoreError { pub type StoreResult = Result; +/// How many dependants an [`StoreError::InUse`] names at most. +pub const IN_USE_LIMIT: i64 = 20; + +impl StoreError { + /// `Err(InUse)` when `used_by` is not empty. + pub fn refuse_in_use(resource: &str, used_by: Vec) -> StoreResult<()> { + if used_by.is_empty() { + return Ok(()); + } + Err(StoreError::InUse { + resource: resource.to_string(), + used_by, + }) + } + + /// The human message of an [`StoreError::InUse`] without the `conflict:` prefix. + pub fn in_use_message(resource: &str, used_by: &[String]) -> String { + format!( + "{resource} is still used by {}; remove it there first", + used_by.join(", ") + ) + } +} + const LICENSE_LOCK_RETRY_BASE: Duration = Duration::from_millis(2); const LICENSE_LOCK_RETRY_MAX: Duration = Duration::from_millis(25); const LICENSE_LOCK_WAIT: Duration = Duration::from_secs(10); diff --git a/docs/development/ui-test-plan.md b/docs/development/ui-test-plan.md index 53ee1117..2d4c8f10 100644 --- a/docs/development/ui-test-plan.md +++ b/docs/development/ui-test-plan.md @@ -319,6 +319,8 @@ licence messages instead. | **Archived** filter → **Restore agent** on the agent page | The agent returns as before | | **Delete permanently** | Names the agents and says execution history is kept; a partial failure leaves the failed ids selected | | Skills list → select a skill an agent uses → delete | The confirmation names the agents and teams that use it | +| Archived agent in an agent team → **Delete permanently** on its page | A message names the team; nothing is deleted. Remove it from the team, retry: the confirmation lists executions, triggers and outputs that go with it | +| Provider or connection an agent uses → **Delete** / **Remove connection** | The refusal names the agent (and team, environment mapping or worker profile); the item stays | | Change the filter or search with rows ticked | Only ticked rows that are still on screen are counted and acted on | --- diff --git a/docs/guide/agents.md b/docs/guide/agents.md index 1bce7d40..8adb322f 100644 --- a/docs/guide/agents.md +++ b/docs/guide/agents.md @@ -75,7 +75,12 @@ its triggers only fire once it is Active. Use **Pause** and **Resume** on the ag stop and restart triggers. **Archive agent** stops triggers and means the agent can no longer run or be edited; its versions and execution history are kept. **Restore agent** (also offered in the Archived filter of the Agents list) activates an archived agent again. -**Delete permanently** is offered only for archived agents. +**Delete permanently** is offered only for archived agents. The confirmation lists what goes +with the agent (executions, triggers, tool policies, memory, and outputs that are deleted or +no longer sent for it), and the audit entry records the same list. An agent that an agent +team or a worker profile still lists, or that agent team runs used, cannot be deleted: the +page names them so you can remove it there first (the API answers `409` with them in +`details`, path `usedBy`; `GET /api/v1/agents/{id}/delete-impact` returns both lists). Editing creates a new immutable version; executions pin the version they started with. Undoing a change (returning to an earlier configuration) is saved as a new version too; diff --git a/docs/guide/connections.md b/docs/guide/connections.md index 6b9c77fe..07b4fc4d 100644 --- a/docs/guide/connections.md +++ b/docs/guide/connections.md @@ -70,7 +70,9 @@ Agent teams can also attach connections for all their steps ## Test a connection A connection page (`/connections/`) has **Test**, **Edit**, **Export as YAML** and -**Remove connection**. **Test** contacts the service with the stored credential: +**Remove connection**. A connection that an agent, agent team, environment mapping or worker +profile still uses cannot be removed: the page names them (the API answers `409` with them in +`details`, path `usedBy`). **Test** contacts the service with the stored credential: - GitHub and GitLab: a request to `/user`. - Generic webhook: a `HEAD` request to the URL. diff --git a/docs/guide/providers.md b/docs/guide/providers.md index ba826ea9..4d5c61e2 100644 --- a/docs/guide/providers.md +++ b/docs/guide/providers.md @@ -37,7 +37,9 @@ you know your provider endpoint expects it. model, a filter by type with counts, status (**Enabled**, **Disabled**, or **Test failed** after a failed test in this session), the default model and catalog size, and row checkboxes for **Change access**. Each provider has a page with **Test**, **Edit**, and **Disable**, -**Export as YAML** and **Delete** under ⋯. +**Export as YAML** and **Delete** under ⋯. A provider that an agent, agent team or worker +profile still names cannot be deleted: the page lists them (the API answers `409` with them in +`details`, path `usedBy`). **Add provider** and **Edit** open Provider Studio, one section at a time: diff --git a/packages/api-client/openapi.json b/packages/api-client/openapi.json index 1e600a80..08c79799 100644 --- a/packages/api-client/openapi.json +++ b/packages/api-client/openapi.json @@ -670,7 +670,17 @@ } } }, - "204": {} + "204": {}, + "409": { + "description": "A permanent delete is refused while agent teams or worker profiles use the agent; `details` lists them (path `usedBy`)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + } + } } }, "patch": { @@ -742,6 +752,37 @@ } } }, + "/api/v1/agents/{agent_id}/delete-impact": { + "get": { + "tags": [ + "agents" + ], + "summary": "What a permanent delete of the agent would be refused for (`usedBy`) and what it would\nremove with it (`removes`), for the confirmation dialog (#434).", + "operationId": "agent_delete_impact", + "parameters": [ + { + "name": "agent_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentDeleteImpact" + } + } + } + } + } + } + }, "/api/v1/agents/{agent_id}/executions": { "get": { "tags": [ @@ -1429,7 +1470,17 @@ } ], "responses": { - "204": {} + "204": {}, + "409": { + "description": "Refused while agents, agent teams, environment mappings or worker profiles use the connection; `details` lists them (path `usedBy`)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + } + } } }, "patch": { @@ -2520,7 +2571,17 @@ } ], "responses": { - "204": {} + "204": {}, + "409": { + "description": "Refused while agents, agent teams or worker profiles use the provider; `details` lists them (path `usedBy`)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + } + } } }, "patch": { @@ -4677,6 +4738,30 @@ }, "additionalProperties": false }, + "AgentDeleteImpact": { + "type": "object", + "description": "What permanently deleting an agent would do: what blocks it, and what goes with it.", + "required": [ + "usedBy", + "removes" + ], + "properties": { + "removes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Records the delete removes or changes with the agent, such as \"3 executions\" or\n\"output Slack alerts (deleted)\"." + }, + "usedBy": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Records that still use the agent. While any are listed, the delete is refused." + } + } + }, "AgentDetail": { "type": "object", "required": [ diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 65c261f5..f6af0ad3 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -217,6 +217,26 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/agents/{agent_id}/delete-impact": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * What a permanent delete of the agent would be refused for (`usedBy`) and what it would + * remove with it (`removes`), for the confirmation dialog (#434). + */ + get: operations["agent_delete_impact"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/agents/{agent_id}/executions": { parameters: { query?: never; @@ -1747,6 +1767,16 @@ export interface components { metadata: components["schemas"]["AgentMetadata"]; spec: components["schemas"]["AgentSpec"]; }; + /** @description What permanently deleting an agent would do: what blocks it, and what goes with it. */ + AgentDeleteImpact: { + /** + * @description Records the delete removes or changes with the agent, such as "3 executions" or + * "output Slack alerts (deleted)". + */ + removes: string[]; + /** @description Records that still use the agent. While any are listed, the delete is refused. */ + usedBy: string[]; + }; AgentDetail: { /** Format: date-time */ createdAt: string; @@ -4197,6 +4227,15 @@ export interface operations { }; content?: never; }; + /** @description A permanent delete is refused while agent teams or worker profiles use the agent; `details` lists them (path `usedBy`) */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorEnvelope"]; + }; + }; }; }; update_agent: { @@ -4245,6 +4284,27 @@ export interface operations { }; }; }; + agent_delete_impact: { + parameters: { + query?: never; + header?: never; + path: { + agent_id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AgentDeleteImpact"]; + }; + }; + }; + }; list_agent_executions: { parameters: { query?: { @@ -4721,6 +4781,15 @@ export interface operations { }; content?: never; }; + /** @description Refused while agents, agent teams, environment mappings or worker profiles use the connection; `details` lists them (path `usedBy`) */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorEnvelope"]; + }; + }; }; }; update_connection: { @@ -5515,6 +5584,15 @@ export interface operations { }; content?: never; }; + /** @description Refused while agents, agent teams or worker profiles use the provider; `details` lists them (path `usedBy`) */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorEnvelope"]; + }; + }; }; }; update_provider: {