Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 5 additions & 8 deletions apps/web/app/agents/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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();
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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 (
Expand Down
16 changes: 5 additions & 11 deletions apps/web/app/agents/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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";
Expand All @@ -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() });

Expand All @@ -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({
Expand Down Expand Up @@ -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);
}}
/>
))}
Expand Down
5 changes: 3 additions & 2 deletions apps/web/app/connections/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 "—";
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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,
});
Expand Down
5 changes: 3 additions & 2 deletions apps/web/app/models/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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,
});
Expand Down
59 changes: 59 additions & 0 deletions apps/web/components/agents/use-confirm-agent-delete.tsx
Original file line number Diff line number Diff line change
@@ -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<boolean> => {
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: (
<span className="block space-y-2">
<span className="block">
{impact.removes.length
? "This removes the agent together with:"
: "This removes the agent. It has no history, triggers or outputs."}
</span>
{impact.removes.length ? (
<span className="block">
{impact.removes.map((line) => (
<span key={line} className="block">
• {line}
</span>
))}
</span>
) : null}
<span className="block">It cannot be undone.</span>
</span>
),
confirmLabel: "Delete agent",
destructive: true,
});
};
}
34 changes: 34 additions & 0 deletions apps/web/lib/delete-impact.test.ts
Original file line number Diff line number Diff line change
@@ -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.");
});
27 changes: 27 additions & 0 deletions apps/web/lib/delete-impact.ts
Original file line number Diff line number Diff line change
@@ -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;
}
6 changes: 6 additions & 0 deletions changelog.d/434.fixed.md
Original file line number Diff line number Diff line change
@@ -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.
8 changes: 8 additions & 0 deletions crates/orbit-api/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,14 @@ impl From<StoreError> 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() {
Expand Down
25 changes: 22 additions & 3 deletions crates/orbit-api/src/handlers/agents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ pub struct DeleteAgentQuery {
pub hard: Option<bool>,
}

#[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<AppState>,
Extension(auth): Extension<AuthContext>,
Expand All @@ -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());
Expand All @@ -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<AppState>,
Extension(auth): Extension<AuthContext>,
Path(agent_id): Path<Uuid>,
) -> Result<Json<orbit_store::in_use::AgentDeleteImpact>, 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<AppState>,
Expand Down
4 changes: 2 additions & 2 deletions crates/orbit-api/src/handlers/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AppState>,
Extension(auth): Extension<AuthContext>,
Expand Down Expand Up @@ -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<AppState>,
Extension(auth): Extension<AuthContext>,
Expand Down
1 change: 1 addition & 0 deletions crates/orbit-api/src/openapi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 4 additions & 0 deletions crates/orbit-api/src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading