Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-ui): replace wizard create-as-upsert with create-only + sibling rollback (R5-C1, R5-B1)
Diego Zacariascd2727f47088
diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsxindex 7be53fdab..dbd2730c1 100644--- a/control-ui/components/HostWizard/index.tsx+++ b/control-ui/components/HostWizard/index.tsx@@ -53,6 +53,7 @@ import type {ChannelOption,ChannelProvider,ContextOption,+ CreatedResource,HostWizardProps,NewChannelDraft,WizardSelectProps,@@ -266,6 +267,80 @@ function displayHostPreflightMessage(rawHostName: string): string | null {return null}+// The DELETE path for one tracked sibling. The server fixes each resource's+// namespace (secrets → config.secretsNamespace; hosts/contexts/channels →+// their configured namespace), so — exactly like the SecretsTable /+// CommunicationChannelsTable / deleteContext call-sites — no namespace query is+// sent. Deleting a communicationchannel also removes its credentials Secret+// server-side, so a channel's credential Secret is never tracked or deleted+// separately here.+function compensationPath(entry: CreatedResource): string {+ const encoded = encodeURIComponent(entry.name)+ switch (entry.kind) {+ case 'secret':+ return `/api/v1/admin/secrets/${encoded}`+ case 'context':+ return `/api/v1/admin/contexts/${encoded}`+ case 'communication-channel':+ return `/api/v1/admin/communication-channels/${encoded}`+ }+}++// Inverse-order (channel → context → secret) best-effort rollback of the+// siblings THIS run created before the Host create failed, so a failed create+// never leaves an orphaned secret/context/channel behind. Best-effort: each+// DELETE is independent, a 404 is success (idempotent — the resource is already+// gone), and NO failure is re-thrown — a rollback error must never mask the+// original create error the caller is about to surface. The server performs a+// direct delete with no referential-integrity/finalizer coupling between the+// siblings, so inverse order is for tidiness, not correctness.+async function compensateCreated(created: CreatedResource[]): Promise<void> {+ for (let i = created.length - 1; i >= 0; i -= 1) {+ const entry = created[i]+ try {+ await apiSend('DELETE', compensationPath(entry))+ } catch (err) {+ console.warn(+ `HostWizard: best-effort rollback of ${entry.kind} "${entry.name}" failed after a create error`,+ err+ )+ }+ }+}++// A create-only POST, with the 409 disambiguation done HERE — at the create+// site — never in the shared submitAll catch. This is deliberate: only a POST to+// a create-only /admin/{secrets,contexts,communication-channels,hosts} endpoint+// can turn a code-less 409 into an UNAMBIGUOUS AlreadyExists name collision. The+// grant endpoints (409 `deleted_agent_history_limit_exceeded`) and the+// `mode=existing` channel PUT (409 `conflict`/`resource_changed`) share the+// top-level catch but can NEVER reach here, so their messages are preserved.+//+// The two 409 shapes from THESE endpoints (V-1):+// - WITH a body `code` (context_crd_outdated / communication_channel_crd_outdated)+// → a CRD-outdated response, NOT a collision. formatApiError already set+// e.message to the server's human `error` text, so re-throw e untouched.+// - WITHOUT a body `code` → apiserver AlreadyExists. The create-only POST+// refused to overwrite a foreign resource; replace the raw K8s text with the+// friendly, per-resource `collisionMessage`.+// Discriminate on `body.code` (the field INSIDE the JSON body), never on the+// client's `.code` (which formatApiError sets from `body.error`, the message).+// Any non-409 error is re-thrown verbatim.+async function createOrThrow(path: string, body: unknown, collisionMessage: string): Promise<void> {+ try {+ await apiSend('POST', path, body)+ } catch (e) {+ if (e instanceof Error && (e as Error & { status?: number }).status === 409) {+ const errBody = (e as Error & { body?: { code?: unknown } }).body+ const hasCode = typeof errBody?.code === 'string' && errBody.code.length > 0+ // Code-less 409 from a create-only POST = unambiguous name collision.+ if (!hasCode) throw new Error(collisionMessage)+ // Coded 409 (CRD-outdated) keeps the server's own message (e.message).+ }+ throw e+ }+}+function isStepValid(stepIndex: number,state: {@@ -301,10 +376,10 @@ function isStepValid(// those siblings. isValidResourceSlug mirrors the server rule client-side.if (stepIndex === 0) {if (!isValidResourceSlug(state.hostName)) return false- // Block a slug that collides with an existing host: create's PUT-first- // upsert (submitAll → upsertResource('admin/hosts', …)) would otherwise- // overwrite that agent's entire spec and still report "created". Gating here- // stops the collision BEFORE any sibling (secret/context/channel) is created.+ // Block a slug that collides with an existing host. The submit path is now+ // create-only (POST), so the server 409s AlreadyExists on a collision rather+ // than overwriting — this client gate is an early-UX layer that stops the+ // collision BEFORE any sibling (secret/context/channel) is created.if (state.existingHostNames.includes(toKebabCase(state.hostName))) return false// Gate the free-text display value (spec.host) too: toKebabCase strips// control/bidi chars, so a name like "agentname" derives a clean slug@@ -315,8 +390,8 @@ function isStepValid(}if (stepIndex === 1) {if (state.contextMode === 'existing') return state.selectedExistingContext.trim().length > 0- // Same slug-derivation gate: the new context upsert runs before the host- // create, so an invalid/over-long derived name here has the same orphan risk.+ // Same slug-derivation gate: the new context is created before the host, so+ // an invalid/over-long derived name here has the same orphan risk.return isValidResourceSlug(state.contextName)}if (stepIndex === 2) {@@ -392,8 +467,8 @@ export function HostWizard({const [hostName, setHostName] = useState('')const hostNamespace = HOST_NAMESPACE// Existing host slugs (metadata.name), loaded up front so the step-0 gate can- // block a colliding name BEFORE any sibling is created. Without this, create's- // PUT-first upsert would silently overwrite an existing agent's whole spec.+ // block a colliding name BEFORE any sibling is created — early UX ahead of the+ // create-only POST, whose 409 AlreadyExists is the real backstop.const [existingHostNames, setExistingHostNames] = useState<string[]>([])const [contextName, setContextName] = useState('')@@ -619,9 +694,9 @@ export function HostWizard({// Promise.all and blank the context/channel/member/team selectors. On// failure existingHostNames stays [] and the step-0 collision gate// degrades FAIL-OPEN (permits create) — the pre-fix behavior (the wizard- // never loaded hosts at all), not worse. The submit-time upsert is still- // PUT-first, so a true collision could overwrite a spec when the- // directory is down; that exposure predates this guard and is unchanged.+ // never loaded hosts at all), not worse. Even with the directory down a+ // true collision can NOT overwrite a foreign spec: submit is create-only+ // (POST), so the server 409s AlreadyExists. This gate is only early UX.// Do NOT make this fail-closed: blocking every create when hosts can't// load is a strictly worse UX.(@@ -824,19 +899,6 @@ export function HostWizard({existingHostNames,])- async function upsertResource(- pluralPath: string,- name: string,- createBody: unknown,- updateBody: unknown- ) {- try {- await apiSend('PUT', `/api/v1/${pluralPath}/${encodeURIComponent(name)}`, updateBody)- } catch {- await apiSend('POST', `/api/v1/${pluralPath}`, createBody)- }- }-function resetForm() {setStep(0)setError('')@@ -901,20 +963,29 @@ export function HostWizard({async function submitAll(options: { skipChannels?: boolean } = {}) {setBusy(true)setError('')+ // Rollback ledger for the create-only seam: every sibling THIS run POSTs+ // successfully is appended here so a later failure (before the Host exists)+ // can inverse-compensate it. Only successful POSTs of this execution are+ // tracked — never inferred from slug/label — and the `mode=existing` channel+ // PUT is an edit, so it is deliberately NOT recorded (deleting it would+ // destroy a foreign resource). Declared outside the try so catch can read it.+ const created: CreatedResource[] = []+ let hostCreated = falsetry {const shouldSkipChannels = options.skipChannels || channelMode === 'skip'const normalizedHostName = toKebabCase(hostName)- // Collision guard, mirrored from the step-0 gate: create's PUT-first- // upsert would overwrite an existing agent's spec. Throw BEFORE creating- // any sibling (secret/context/channel) so a collision never orphans them.+ // Collision guard, mirrored from the step-0 gate. Throw BEFORE creating any+ // sibling so a collision never orphans one; the server-side create-only+ // POST is the real backstop (409 AlreadyExists), this is just early UX.if (existingHostNames.includes(normalizedHostName)) {throw new Error('Identifier already in use — choose another name.')}// Hard preflight — defense in depth for the step gates (R5-H1). Everything// the server validates is checked HERE, before the first apiSend, so a// value the server would reject can never leave an orphaned sibling- // (secret/context/channel) ahead of the failing host create. This is- // purely additive: no write ordering or upsert behavior changes.+ // (secret/context/channel) ahead of the failing host create. Additive to+ // the create-only seam: it fails fast before any write, and if a write+ // still fails past this point, compensateCreated rolls the siblings back.const displayHostIssue = validateDisplayField(displayHostValue(hostName), 'spec.host')if (displayHostIssue) {throw new Error(displayHostPreflightMessage(hostName) || 'Agent name is not valid.')@@ -954,20 +1025,32 @@ export function HostWizard({if (slotErrors.length > 0) {throw new Error(slotErrors[0])}- await apiSend('POST', '/api/v1/admin/secrets', {- name: normalizedSecretName,- namespace: hostNamespace,- labels: {- [HOST_SECRET_LABEL_KEY]: HOST_SECRET_LABEL_VALUE,+ // Create-only POST (R5-C1/R5-B1): a name collision must 409 AlreadyExists+ // server-side, never silently overwrite a foreign Secret via a PUT. The+ // 409 → friendly message translation is scoped to createOrThrow.+ await createOrThrow(+ '/api/v1/admin/secrets',+ {+ name: normalizedSecretName,+ namespace: hostNamespace,+ labels: {+ [HOST_SECRET_LABEL_KEY]: HOST_SECRET_LABEL_VALUE,+ },+ stringData,},- stringData,- })+ `A credential secret named "${normalizedSecretName}" already exists — choose another name.`+ )+ // The host's own LLM Secret (${slug}-llm). Tracked so a later failure+ // rolls it back explicitly by name (a channel's credential Secret is+ // NOT tracked — the channel DELETE removes it server-side).+ created.push({ kind: 'secret', name: normalizedSecretName })}if (contextMode === 'new') {- await upsertResource(- 'admin/contexts',- normalizedContextName,+ // Create-only POST (R5-C1/R5-B1): a name collision must 409 AlreadyExists+ // server-side, never silently overwrite a foreign context via a PUT.+ await createOrThrow(+ '/api/v1/admin/contexts',{metadata: { name: normalizedContextName },spec: {@@ -976,14 +1059,9 @@ export function HostWizard({mcpServers: Array.from(new Set(selectedMcp)),},},- {- spec: {- contextId: normalizedContextName,- description: `Context for agent ${normalizedHostName}`,- mcpServers: Array.from(new Set(selectedMcp)),- },- }+ `A context named "${normalizedContextName}" already exists — choose another name.`)+ created.push({ kind: 'context', name: normalizedContextName })}if (!shouldSkipChannels && channelMode === 'new') {@@ -1004,19 +1082,23 @@ export function HostWizard({...providerSettings(channelProvider, newChannelDraft),}- await upsertResource(- 'admin/communication-channels',- normalizedChannelName,+ // Create-only POST (R5-C1/R5-B1): a name collision must 409 AlreadyExists+ // server-side, never overwrite a foreign channel via a PUT.+ await createOrThrow(+ '/api/v1/admin/communication-channels',{metadata: { name: normalizedChannelName },spec: channelSpec,credentials: cleanedCredentials,},- {- spec: channelSpec,- }+ `A channel named "${normalizedChannelName}" already exists — choose another name.`)+ created.push({ kind: 'communication-channel', name: normalizedChannelName })} else if (!shouldSkipChannels && channelMode === 'existing' && selectedChannelOption) {+ // Deliberate edit of a channel the operator SELECTED: attach this host ++ // its access to a resource that already exists. This is the ONE surviving+ // PUT (not a create) and is intentionally NOT tracked in `created` —+ // compensating it would delete a foreign resource we did not create.await apiSend('PUT',`/api/v1/admin/communication-channels/${encodeURIComponent(selectedChannelOption.name)}`,@@ -1069,21 +1151,26 @@ export function HostWizard({: {}),}- await upsertResource(- 'admin/hosts',- normalizedHostName,+ // Create-only POST (R5-C1/R5-B1): the Host is the seam boundary. A name+ // collision must 409 AlreadyExists rather than overwrite a foreign agent's+ // entire spec. Once this resolves, hostCreated flips the compensation off:+ // the siblings now belong to a real Host and must NOT be rolled back.+ await createOrThrow(+ '/api/v1/admin/hosts',{metadata: { name: normalizedHostName },spec: hostSpec,},- {- spec: hostSpec,- }+ `That agent name is already in use — choose another name.`)+ hostCreated = true// Associate authorized users and teams with the new agent in a single// atomic call each, rather than looping N×(GET+PUT) per selection.// Uses the agent-centric endpoints PUT /admin/agents/:name/users|teams.+ // These run AFTER hostCreated=true: if a grant fails, the Host + siblings+ // stay (V-7) — the operator retries grants from the agent detail page — so+ // no compensation runs for a grant failure.if (selectedUserIds.length > 0) {await updateAgentUsers(normalizedHostName, selectedUserIds)}@@ -1097,6 +1184,21 @@ export function HostWizard({if (!mountedRef.current) returnonClose()} catch (e) {+ // The Host is the compensation boundary (V-7): if it never got created, the+ // siblings created before it are orphans — inverse-compensate them+ // best-effort. If it DID get created, leave everything (a grant failure is+ // recoverable from the agent detail page). Always await the rollback before+ // surfacing the error so a caller/test observes the terminal state.+ if (!hostCreated) {+ await compensateCreated(created)+ }+ // NO 409 remap here: each create-only POST already translated its OWN+ // collision inside createOrThrow. This catch also sees errors from paths+ // that run AFTER the Host — the grant calls (409+ // `deleted_agent_history_limit_exceeded`) and the `mode=existing` channel+ // PUT (409 `conflict`) — whose messages formatApiError already produced;+ // masking them as "already in use" (the prior top-level remap) told the+ // operator a collision that never happened. Preserve e.message verbatim.if (mountedRef.current) {setError(e instanceof Error ? e.message : 'Failed to create agent resources')}diff --git a/control-ui/components/HostWizard/types.ts b/control-ui/components/HostWizard/types.tsindex d09878af1..cf3760257 100644--- a/control-ui/components/HostWizard/types.ts+++ b/control-ui/components/HostWizard/types.ts@@ -36,6 +36,16 @@ export type ChannelOption = {spec: Record<string, unknown>}+// A sibling resource this wizard run created via a create-only POST, tracked so+// a later failure (before the Host exists) can compensate it with an inverse+// DELETE. ONLY POSTs succeeded by THIS submit are recorded — never inferred from+// slug or label ownership. The channel `mode=existing` PUT is an edit of a+// pre-existing resource and is NEVER tracked here.+export type CreatedResource = {+ kind: 'secret' | 'context' | 'communication-channel'+ name: string+}+export type HostWizardProps = {existingSecrets: SecretMeta[]mcpServers: McpServer[]diff --git a/control-ui/components/__tests__/HostWizard.create-seam.test.tsx b/control-ui/components/__tests__/HostWizard.create-seam.test.tsxnew file mode 100644index 000000000..196be93d0--- /dev/null+++ b/control-ui/components/__tests__/HostWizard.create-seam.test.tsx@@ -0,0 +1,397 @@+import React from 'react'+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import * as api from '../../lib/api'+import { HostWizard } from '../HostWizard'+import { ToastProvider } from '../Toast'++/**+ * Fase 3 — HostWizard create seam moves from "create-as-upsert (PUT-first)" to+ * "create-only (POST) + inverse compensation" (closes R5-C1 upsert overwrites a+ * foreign context/channel/host, and R5-B1 no real server-side create control).+ *+ * These invariants assert the OBSERVABLE apiSend traffic (T4) — the POST/PUT/+ * DELETE calls — never internal effects:+ *+ * - INV-A a successful create is POST-only (no PUT to hosts/contexts/channels).+ * - INV-B a Host name collision (409, no body code) shows "already in use",+ * overwrites nothing (no PUT), and rolls back the created siblings.+ * - INV-C for every failure boundary before the Host (context POST, channel+ * POST, host POST), the siblings created BEFORE it are DELETEd by name+ * and no orphan survives.+ * - INV-D a grant failure AFTER the Host exists compensates nothing (V-7).+ * - INV-E a `mode=existing` channel is edited via PUT and is NEVER tracked, so+ * a later failure does not delete that foreign channel.+ *+ * INV-A/B/C FAIL against the pre-fix head, where create was a PUT-first upsert:+ * the PUT to hosts/contexts fired (INV-A), a colliding PUT silently "succeeded"+ * so no error/rollback surfaced (INV-B), and a rejected POST never ran because+ * the PUT resolved first, so no sibling DELETE occurred (INV-C).+ */++vi.mock('../../lib/api', () => ({+ apiGet: vi.fn().mockResolvedValue({ items: [] }),+ apiSend: vi.fn().mockResolvedValue({}),+ getAdminUsers: vi.fn().mockResolvedValue({+ items: [{ id: 'user-a', email: '[email protected]', name: 'Alice', displayName: null }],+ }),+ getAdminTeams: vi.fn().mockResolvedValue({ items: [] }),+ updateAgentUsers: vi.fn().mockResolvedValue({ agentName: '', userIds: [] }),+ updateAgentTeams: vi.fn().mockResolvedValue({ agentName: '', teamIds: [] }),+ getLlmModels: vi.fn().mockResolvedValue({+ rows: [+ {+ id: 'm1',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ vendor: 'OpenAI',+ display_name: null,+ context_window_tokens: null,+ enabled: true,+ created_at: '',+ updated_at: '',+ },+ ],+ }),+ isSilentApiError: vi.fn().mockReturnValue(false),+}))++if (!Element.prototype.scrollIntoView) {+ Element.prototype.scrollIntoView = () => {}+}++type ApiSendMock = ReturnType<typeof vi.fn>++// T1 (derive fixtures from the real producer): the error shape createOrThrow /+// the submitAll catch discriminate on (`.status`, `.body`, `.code`, `.message`)+// is produced by lib/api's formatApiError. We build every rejection by calling+// the REAL formatApiError (via importActual, bypassing the module mock) against+// a synthetic 4xx Response — so if formatApiError's shape ever drifts, these+// tests break instead of quietly certifying a stale hand-built shape.+let formatApiError!: (typeof import('../../lib/api'))['formatApiError']+beforeAll(async () => {+ ;({ formatApiError } = await vi.importActual<typeof import('../../lib/api')>('../../lib/api'))+})++/** A real formatApiError-derived Error for an HTTP status + JSON body. */+function makeApiError(status: number, body: Record<string, unknown>): Error {+ const text = JSON.stringify(body)+ const statusText = status === 409 ? 'Conflict' : 'Internal Server Error'+ return formatApiError(new Response(text, { status, statusText }), text)+}++/** apiSend calls to a specific method — `[method, url, body]` tuples. */+function callsFor(method: 'POST' | 'PUT' | 'DELETE'): unknown[][] {+ return (api.apiSend as unknown as ApiSendMock).mock.calls.filter(call => call[0] === method)+}++function urlsFor(method: 'POST' | 'PUT' | 'DELETE'): string[] {+ return callsFor(method).map(call => String(call[1]))+}++async function renderWizard() {+ const onCreated = vi.fn().mockResolvedValue(undefined)+ const onClose = vi.fn()+ const utils = render(+ <ToastProvider>+ <HostWizard+ mcpServers={[{ metadata: { name: 'mcp-a' } }]}+ existingSecrets={[{ name: 'secret-a' }]}+ onCreated={onCreated}+ onClose={onClose}+ />+ </ToastProvider>+ )+ await act(async () => {+ await Promise.resolve()+ await Promise.resolve()+ })+ return { ...utils, onCreated, onClose }+}++/**+ * Fill steps 0→3 with a NEW context + NEW (auto-named) secret and land on the+ * Channels step. Leaves the Access selection empty unless `selectUser` is set.+ * The auto-derived secret name is `${agentName}-llm`.+ */+async function fillToChannels(agentName: string, opts: { selectUser?: boolean } = {}) {+ await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())++ // Step 0: agent name.+ fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: agentName } })+ fireEvent.click(screen.getByRole('button', { name: 'Next' }))++ // Step 1: a new context named "ctx-a".+ fireEvent.click(screen.getByLabelText(/Create new context/i))+ fireEvent.change(screen.getByPlaceholderText(/context-name/i), { target: { value: 'ctx-a' } })+ fireEvent.click(screen.getByRole('button', { name: 'Next' }))++ // Step 2: default "new secret" (auto-named) + a usable OpenAI primary key.+ fireEvent.change(screen.getByLabelText(/OpenAI API key/i), { target: { value: 'sk-openai' } })+ await waitFor(() => expect(screen.getByRole('button', { name: 'Next' })).not.toBeDisabled())+ fireEvent.click(screen.getByRole('button', { name: 'Next' }))++ // Step 3: Access.+ if (opts.selectUser) {+ fireEvent.click(screen.getByLabelText(/alice/i))+ }+ fireEvent.click(screen.getByRole('button', { name: 'Next' }))++ // Now on Step 4: Channels.+ await waitFor(() =>+ expect(screen.getByRole('button', { name: /Skip channel setup/i })).toBeInTheDocument()+ )+}++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+ // Restore the default resolved stubs so a per-test implementation never leaks.+ ;(api.apiSend as unknown as ApiSendMock).mockResolvedValue({})+ ;(api.apiGet as unknown as ApiSendMock).mockResolvedValue({ items: [] })+})++describe('HostWizard create seam — INV-A: a successful create is POST-only', () => {+ it('POSTs secret/context/host and never PUTs any of them (R5-C1/R5-B1)', async () => {+ await renderWizard()+ await fillToChannels('agent-a')++ fireEvent.click(screen.getByRole('button', { name: /Skip channel setup/i }))++ await waitFor(() => {+ expect(api.apiSend).toHaveBeenCalledWith(+ 'POST',+ '/api/v1/admin/hosts',+ expect.objectContaining({ metadata: { name: 'agent-a' } })+ )+ })++ // Create-only: the three resources are POSTed to their collections.+ const posted = urlsFor('POST')+ expect(posted).toContain('/api/v1/admin/secrets')+ expect(posted).toContain('/api/v1/admin/contexts')+ expect(posted).toContain('/api/v1/admin/hosts')++ // Nothing was upsert-overwritten: no PUT fired at all in the skip-channels+ // path (the only surviving PUT is the mode=existing channel edit, unused).+ expect(callsFor('PUT')).toHaveLength(0)+ // No rollback on the happy path.+ expect(callsFor('DELETE')).toHaveLength(0)+ })+})++describe('HostWizard create seam — INV-B: Host name collision (409) does not overwrite', () => {+ it('shows "already in use", fires no PUT, and rolls back the created siblings', async () => {+ ;(api.apiSend as unknown as ApiSendMock).mockImplementation(+ async (method: string, url: string) => {+ if (method === 'POST' && url === '/api/v1/admin/hosts') {+ // apiserver AlreadyExists: 409 with a message body but NO machine code.+ throw makeApiError(409, { error: 'hosts.clerum.io "agent-b" already exists' })+ }+ return {}+ }+ )++ await renderWizard()+ await fillToChannels('agent-b')+ fireEvent.click(screen.getByRole('button', { name: /Skip channel setup/i }))++ // The operator sees the collision message, mapped from the code-less 409.+ await waitFor(() => {+ expect(screen.getByText(/already in use/i)).toBeInTheDocument()+ })++ // Nothing was overwritten: no PUT anywhere.+ expect(callsFor('PUT')).toHaveLength(0)++ // The siblings created before the Host are rolled back (inverse order).+ const deleted = urlsFor('DELETE')+ expect(deleted).toContain('/api/v1/admin/contexts/ctx-a')+ expect(deleted).toContain('/api/v1/admin/secrets/agent-b-llm')+ })+})++describe('HostWizard create seam — INV-C: zero orphans at every failure boundary', () => {+ it('context POST fails → the already-created secret is DELETEd; the host is never POSTed', async () => {+ ;(api.apiSend as unknown as ApiSendMock).mockImplementation(+ async (method: string, url: string) => {+ if (method === 'POST' && url === '/api/v1/admin/contexts') {+ throw makeApiError(500, { error: 'internal' })+ }+ return {}+ }+ )++ await renderWizard()+ await fillToChannels('agent-c1')+ fireEvent.click(screen.getByRole('button', { name: /Skip channel setup/i }))++ await waitFor(() => {+ expect(urlsFor('DELETE')).toContain('/api/v1/admin/secrets/agent-c1-llm')+ })+ // The context POST failed, so it was never tracked → never DELETEd.+ expect(urlsFor('DELETE')).not.toContain('/api/v1/admin/contexts/ctx-a')+ // The host was never reached, so no orphaned spec.host exists.+ expect(urlsFor('POST')).not.toContain('/api/v1/admin/hosts')+ })++ it('channel POST fails → the created context and secret are both DELETEd; the host is never POSTed', async () => {+ ;(api.apiSend as unknown as ApiSendMock).mockImplementation(+ async (method: string, url: string) => {+ if (method === 'POST' && url === '/api/v1/admin/communication-channels') {+ throw makeApiError(500, { error: 'internal' })+ }+ return {}+ }+ )++ await renderWizard()+ await fillToChannels('agent-c2')++ // Configure a NEW telegram channel so a channel POST is attempted.+ fireEvent.click(screen.getByLabelText(/Create new channel/i))+ fireEvent.change(screen.getByPlaceholderText(/^channel-name$/i), {+ target: { value: 'chan-a' },+ })+ fireEvent.change(screen.getByPlaceholderText(/@your_bot/i), {+ target: { value: '@clerum_test_bot' },+ })+ fireEvent.change(screen.getByLabelText(/Telegram Bot Token/i), { target: { value: '123:ABC' } })++ await waitFor(() =>+ expect(screen.getByRole('button', { name: /Create Agent/i })).not.toBeDisabled()+ )+ fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))++ await waitFor(() => {+ expect(urlsFor('DELETE')).toContain('/api/v1/admin/contexts/ctx-a')+ })+ expect(urlsFor('DELETE')).toContain('/api/v1/admin/secrets/agent-c2-llm')+ // The failed channel was never tracked → never DELETEd.+ expect(urlsFor('DELETE')).not.toContain('/api/v1/admin/communication-channels/chan-a')+ // The host was never reached.+ expect(urlsFor('POST')).not.toContain('/api/v1/admin/hosts')+ })++ it('host POST fails → the created context and secret are both DELETEd', async () => {+ ;(api.apiSend as unknown as ApiSendMock).mockImplementation(+ async (method: string, url: string) => {+ if (method === 'POST' && url === '/api/v1/admin/hosts') {+ throw makeApiError(500, { error: 'internal' })+ }+ return {}+ }+ )++ await renderWizard()+ await fillToChannels('agent-c3')+ fireEvent.click(screen.getByRole('button', { name: /Skip channel setup/i }))++ await waitFor(() => {+ expect(urlsFor('DELETE')).toContain('/api/v1/admin/contexts/ctx-a')+ })+ expect(urlsFor('DELETE')).toContain('/api/v1/admin/secrets/agent-c3-llm')+ })+})++describe('HostWizard create seam — INV-D: a grant failure after the Host does NOT revert (V-7)', () => {+ it('leaves the Host + siblings and fires no DELETE when updateAgentUsers rejects', async () => {+ vi.mocked(api.updateAgentUsers).mockRejectedValueOnce(new Error('grant failed'))++ await renderWizard()+ await fillToChannels('agent-d', { selectUser: true })+ fireEvent.click(screen.getByRole('button', { name: /Skip channel setup/i }))++ // The Host was created, then the grant failed.+ await waitFor(() => {+ expect(urlsFor('POST')).toContain('/api/v1/admin/hosts')+ expect(vi.mocked(api.updateAgentUsers)).toHaveBeenCalled()+ })+ await waitFor(() => {+ expect(screen.getByText(/grant failed/i)).toBeInTheDocument()+ })++ // Nothing rolled back: the Host + siblings stay for a grant retry from detail.+ expect(callsFor('DELETE')).toHaveLength(0)+ })+})++describe('HostWizard create seam — INV-E: a mode=existing channel is edited, never tracked', () => {+ it('PUTs the selected channel and never DELETEs it, even when a later create fails', async () => {+ ;(api.apiGet as unknown as ApiSendMock).mockImplementation(async (path: string) => {+ if (path === '/api/v1/admin/communication-channels') {+ return {+ items: [{ metadata: { name: 'existing-chan', namespace: 'default' }, spec: {} }],+ }+ }+ return { items: [] }+ })+ ;(api.apiSend as unknown as ApiSendMock).mockImplementation(+ async (method: string, url: string) => {+ if (method === 'POST' && url === '/api/v1/admin/hosts') {+ throw makeApiError(500, { error: 'internal' })+ }+ return {}+ }+ )++ await renderWizard()+ await fillToChannels('agent-e')++ // channelMode defaults to "existing": open the dropdown and pick the channel.+ fireEvent.click(screen.getByRole('button', { name: /Select channel/i }))+ fireEvent.click(screen.getByRole('option', { name: /existing-chan/i }))++ await waitFor(() =>+ expect(screen.getByRole('button', { name: /Create Agent/i })).not.toBeDisabled()+ )+ fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))++ // The existing channel is edited via PUT (attach host + access).+ await waitFor(() => {+ expect(urlsFor('PUT')).toContain('/api/v1/admin/communication-channels/existing-chan')+ })++ // The host POST failed → the tracked siblings roll back...+ await waitFor(() => {+ expect(urlsFor('DELETE')).toContain('/api/v1/admin/contexts/ctx-a')+ })+ expect(urlsFor('DELETE')).toContain('/api/v1/admin/secrets/agent-e-llm')+ // ...but the foreign channel we only EDITED is never deleted.+ expect(urlsFor('DELETE')).not.toContain('/api/v1/admin/communication-channels/existing-chan')+ })+})++describe('HostWizard create seam — INV-F: a post-Host grant 409 is NOT masked as a name collision', () => {+ it('surfaces the grant history-limit message (not "already in use") and rolls back nothing', async () => {+ // The Host is created OK; then the grant call rejects with the exact 409 the+ // server sends (agentGrants.ts): { error: 'deleted_agent_history_limit_exceeded' }.+ // formatApiError already remaps that code to an actionable message. The prior+ // top-level 409 remap clobbered it with "already in use" (the HIGH regression):+ // a false collision for an agent that WAS created (no rollback) → the operator+ // recreates → duplicate agent. Derived from the real producer (T1).+ vi.mocked(api.updateAgentUsers).mockRejectedValueOnce(+ makeApiError(409, { error: 'deleted_agent_history_limit_exceeded', deletedHistoryLimit: 5 })+ )++ await renderWizard()+ await fillToChannels('agent-f', { selectUser: true })+ fireEvent.click(screen.getByRole('button', { name: /Skip channel setup/i }))++ // The Host was created (POST hosts) and the grant was attempted.+ await waitFor(() => {+ expect(urlsFor('POST')).toContain('/api/v1/admin/hosts')+ expect(vi.mocked(api.updateAgentUsers)).toHaveBeenCalled()+ })++ // The operator sees the history-limit message formatApiError produced...+ await waitFor(() => {+ expect(screen.getByText(/deleted-agent history limit was reached/i)).toBeInTheDocument()+ })+ // ...NOT a spurious collision message.+ expect(screen.queryByText(/already in use/i)).not.toBeInTheDocument()++ // V-7: the Host + siblings stay — a grant retry lives on the agent detail page.+ expect(callsFor('DELETE')).toHaveLength(0)+ })+})diff --git a/control-ui/components/__tests__/HostWizard.test.tsx b/control-ui/components/__tests__/HostWizard.test.tsxindex dd64995f1..b25684e8a 100644--- a/control-ui/components/__tests__/HostWizard.test.tsx+++ b/control-ui/components/__tests__/HostWizard.test.tsx@@ -281,10 +281,12 @@ describe('HostWizard — submit path uses the atomic agent-centric endpoints', (await waitFor(() => {expect(screen.queryByText(/Failed to create agent resources/i)).not.toBeInTheDocument()+ // Create-only contract (R5-C1/R5-B1): the Host is POSTed to the collection,+ // never PUT to a name (which would upsert-overwrite a foreign agent).expect(api.apiSend).toHaveBeenCalledWith(- 'PUT',- '/api/v1/admin/hosts/empty-access-test',- expect.any(Object)+ 'POST',+ '/api/v1/admin/hosts',+ expect.objectContaining({ metadata: { name: 'empty-access-test' } }))})@@ -356,16 +358,8 @@ describe('HostWizard — submit path uses the atomic agent-centric endpoints', (})it('creates a new Telegram channel with provider settings and access grants', async () => {- vi.mocked(api.apiSend).mockImplementation(async (method, url) => {- if (- method === 'PUT' &&- String(url).includes('/api/v1/admin/communication-channels/new-telegram-channel')- ) {- throw new Error('not found')- }- return {}- })-+ // Create-only contract: the new channel is POSTed directly (no PUT-first+ // upsert), so no per-URL mock trick is needed — every apiSend resolves.await renderWizard()await walkToAccessStep({ agentName: 'agent-with-channel' })@@ -409,9 +403,10 @@ describe('HostWizard — submit path uses the atomic agent-centric endpoints', (})await waitFor(() => {expect(api.apiSend).toHaveBeenCalledWith(- 'PUT',- '/api/v1/admin/hosts/agent-with-channel',+ 'POST',+ '/api/v1/admin/hosts',expect.objectContaining({+ metadata: { name: 'agent-with-channel' },spec: expect.objectContaining({channels: ['new-telegram-channel'],workflowControl: {@@ -506,14 +501,14 @@ describe('HostWizard — Agent type (stateless lifecycle)', () => {await waitFor(() => {expect(api.apiSend).toHaveBeenCalledWith(- 'PUT',- '/api/v1/admin/hosts/stateful-agent',- expect.any(Object)+ 'POST',+ '/api/v1/admin/hosts',+ expect.objectContaining({ metadata: { name: 'stateful-agent' } }))})const hostCall = vi.mocked(api.apiSend)- .mock.calls.find(call => call[1] === '/api/v1/admin/hosts/stateful-agent')+ .mock.calls.find(call => call[0] === 'POST' && call[1] === '/api/v1/admin/hosts')expect(hostCall).toBeDefined()const payload = hostCall![2] as { spec: Record<string, unknown> }expect('lifecycle' in payload.spec).toBe(false)diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex a2acee34f..1a6441a08 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -90,7 +90,7 @@ async function parseJsonResponse(res: Response): Promise<unknown> {return JSON.parse(text)}-function formatApiError(res: Response, text: string): Error {+export function formatApiError(res: Response, text: string): Error {let detail = textlet parsedBody: Record<string, unknown> | null = nulltry {diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 5af96b36f..996b5bad5 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.397",+ "version": "0.1.398","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.397",+ "version": "0.1.398","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-ui/package.json b/control-ui/package.jsonindex cb7490b04..b590a2308 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.397",+ "version": "0.1.398","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",