Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

adapt(control-ui): graft create-only seam onto dev's channel-less HostWizard

Diego Zacarias20b5203200ac
diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsx
index 72e00f6ca..32674e2cc 100644
--- a/control-ui/components/HostWizard/index.tsx
+++ b/control-ui/components/HostWizard/index.tsx
@@ -41,7 +41,7 @@ import {
STEPS,
STEP_DETAILS,
} from './constants'
-import type { ContextOption, HostWizardProps, WizardSelectProps } from './types'
+import type { ContextOption, CreatedResource, HostWizardProps, WizardSelectProps } from './types'
// Stateless lifecycle support remains intact in the API and existing-agent UI;
// only creation through this wizard is temporarily unavailable.
@@ -123,6 +123,79 @@ function WizardSelect({
)
}
+// 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`) 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: {
@@ -527,19 +600,6 @@ export function HostWizard({
selectedTeamIds,
])
- 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('')
@@ -586,6 +646,13 @@ export function HostWizard({
async function submitAll() {
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. Declared outside the try so the
+ // catch can read it.
+ const created: CreatedResource[] = []
+ let hostCreated = false
try {
const normalizedHostName = toKebabCase(hostName)
const normalizedContextName = toKebabCase(contextName)
@@ -607,20 +674,31 @@ 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.
+ 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: {
@@ -629,14 +707,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 })
}
// Effective per-host model subset (Topic 3a): prune the draft to the
@@ -670,21 +743,26 @@ export function HostWizard({
...(stateless ? { lifecycle: { stateless: true } } : {}),
}
- 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)
}
@@ -698,6 +776,20 @@ export function HostWizard({
if (!mountedRef.current) return
onClose()
} 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`) — whose messages formatApiError
+ // already produced; masking them as "already in use" 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/__tests__/HostWizard.create-seam.test.tsx b/control-ui/components/__tests__/HostWizard.create-seam.test.tsx
deleted file mode 100644
index 196be93d0..000000000
--- a/control-ui/components/__tests__/HostWizard.create-seam.test.tsx
+++ /dev/null
@@ -1,397 +0,0 @@
-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.display-preflight.test.tsx b/control-ui/components/__tests__/HostWizard.display-preflight.test.tsx
deleted file mode 100644
index 7f4625ca7..000000000
--- a/control-ui/components/__tests__/HostWizard.display-preflight.test.tsx
+++ /dev/null
@@ -1,183 +0,0 @@
-import React from 'react'
-import { afterEach, 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'
-
-/**
- * Regression guard for R5-H1: the step-0 gate validates the DERIVED slug
- * (toKebabCase), but toKebabCase STRIPS control/bidi characters and truncates
- * nothing about the free-text display value. So a name like "agent‮name"
- * (a Right-to-Left-Override bidi char) derives a clean, valid slug ("agentname")
- * that sails through the slug gate — yet the RAW display value the server stores
- * as spec.host is rejected (422). Because the secret/context are created BEFORE
- * the host in submitAll, that late rejection orphans the siblings.
- *
- * The fix validates the free-text spec.host display value with the shared
- * @clerum/display-field rule (the SAME rule the server applies), both in the
- * step-0 gate (live feedback) and as a hard check at the top of submitAll
- * (defense in depth) BEFORE any write.
- *
- * These tests FAIL against the pre-fix head, where nothing validated the raw
- * display value: the bidi name enabled Next and the whole wizard reached Create,
- * POSTing the secret before the host create failed.
- */
-
-vi.mock('../../lib/api', () => ({
- apiGet: vi.fn().mockResolvedValue({ items: [] }),
- apiSend: vi.fn().mockResolvedValue({}),
- getAdminUsers: vi.fn().mockResolvedValue({ items: [] }),
- 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 = () => {}
-}
-
-// A Right-to-Left-Override (U+202E) bidi character: the canonical Trojan-Source
-// vector. toKebabCase strips it, so the derived slug is clean ("agentname").
-const BIDI_NAME = 'agent‮name'
-
-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 }
-}
-
-// Drive the wizard from step 0 toward the final Create/Skip action, filling the
-// minimal valid values each step needs. Pre-fix, a bidi name slips past step 0
-// and this reaches "Skip channel setup" (which submits). Post-fix, the step-0
-// gate keeps Next disabled and this bails harmlessly on the first iteration —
-// so it never throws on absent later-step controls in either version.
-async function driveTowardCreate() {
- for (let i = 0; i < 10; i += 1) {
- // Last step: submit via "Skip channel setup" so channel fields aren't needed.
- const skipBtn = screen.queryByRole('button', { name: /Skip channel setup/i })
- if (skipBtn) {
- fireEvent.click(skipBtn)
- return
- }
-
- // Step 1: pick a new context with a valid name so its gate can pass.
- const newCtx = screen.queryByLabelText(/Create new context/i) as HTMLInputElement | null
- if (newCtx) {
- if (!newCtx.checked) fireEvent.click(newCtx)
- const ctxInput = screen.queryByPlaceholderText(/context-name/i) as HTMLInputElement | null
- if (ctxInput && !ctxInput.value) fireEvent.change(ctxInput, { target: { value: 'ctx1' } })
- }
-
- // Step 2: make the OpenAI primary usable, then wait for the model to seed
- // (async, once the allowlist loads) so Next isn't transiently disabled.
- const openAiKey = screen.queryByLabelText(/OpenAI API key/i) as HTMLInputElement | null
- if (openAiKey && !openAiKey.value) {
- fireEvent.change(openAiKey, { target: { value: 'sk-openai' } })
- await waitFor(() => {
- const n = screen.queryByRole('button', { name: 'Next' }) as HTMLButtonElement | null
- expect(Boolean(n && !n.disabled)).toBe(true)
- })
- }
-
- const nextBtn = screen.queryByRole('button', { name: 'Next' }) as HTMLButtonElement | null
- if (!nextBtn || nextBtn.disabled) return
- fireEvent.click(nextBtn)
- }
-}
-
-afterEach(() => {
- cleanup()
- vi.clearAllMocks()
-})
-
-describe('HostWizard — step 0 gates the free-text spec.host display value (R5-H1)', () => {
- it('INV-1: keeps Next DISABLED for a name whose slug is valid but display carries a bidi char', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: BIDI_NAME } })
-
- // The derived slug is clean and valid, so the slug/identifier hint reports no
- // error — only the display-value gate blocks.
- expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()
- expect(screen.getByText(/control or formatting characters/i)).toBeInTheDocument()
- })
-
- it('INV-1 baseline: enables Next for an ordinary display name', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: 'My Agent' } })
-
- expect(screen.getByRole('button', { name: 'Next' })).not.toBeDisabled()
- expect(screen.queryByText(/control or formatting characters/i)).not.toBeInTheDocument()
- })
-
- it('INV-3: keeps Next DISABLED when the display value exceeds the max length but the slug is valid', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- // "ab" + 130 dots: toKebabCase strips the dots → slug "ab" (valid, ≤63),
- // but the raw display value is 132 chars — over the 120 display max the
- // server enforces. The slug gate alone would let this through.
- const longDisplay = `ab${'.'.repeat(130)}`
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: longDisplay } })
-
- expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()
- expect(screen.getByText(/too long \(max 120 characters\)/i)).toBeInTheDocument()
- })
-})
-
-describe('HostWizard — an invalid display value never reaches the server as a side-effect (R5-H1)', () => {
- it('INV-2: fires NO create apiSend when the display value is invalid (bidi char)', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: BIDI_NAME } })
-
- // Pre-fix: the bidi name slips through, the flow reaches Create, and the
- // secret is POSTed before the host create fails — apiSend IS called (bug).
- // Post-fix: the step-0 gate blocks before any step advances.
- await driveTowardCreate()
- await act(async () => {
- await Promise.resolve()
- })
-
- // The observable invariant (T4): no create request escaped for an invalid
- // display value, so no orphaned sibling can exist.
- expect(api.apiSend).not.toHaveBeenCalled()
- // And the operator sees why.
- expect(screen.getByText(/control or formatting characters/i)).toBeInTheDocument()
- })
-})
diff --git a/control-ui/components/__tests__/HostWizard.slug-gate.test.tsx b/control-ui/components/__tests__/HostWizard.slug-gate.test.tsx
deleted file mode 100644
index 9f7dce87f..000000000
--- a/control-ui/components/__tests__/HostWizard.slug-gate.test.tsx
+++ /dev/null
@@ -1,302 +0,0 @@
-import React from 'react'
-import { afterEach, 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'
-
-/**
- * Regression guard for R1-B1 (and its class sibling in step 1): the step gates
- * must validate the DERIVED slug (toKebabCase), not the raw trimmed text. A name
- * with no ASCII alphanumerics ("!!!", whitespace, "---") trims to a non-empty
- * string but toKebabCase()s to "" — which would send metadata.name: "" and, since
- * the secret/context are POSTed BEFORE the host create in submit(), orphan those
- * siblings when the host create fails.
- *
- * These tests FAIL against the pre-fix head (c3ac3e40), where the gates read
- * `state.hostName.trim().length > 0` / `state.contextName.trim().length > 0`.
- */
-
-vi.mock('../../lib/api', () => ({
- apiGet: vi.fn().mockResolvedValue({ items: [] }),
- apiSend: vi.fn().mockResolvedValue({}),
- getAdminUsers: vi.fn().mockResolvedValue({ items: [] }),
- 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 = () => {}
-}
-
-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 }
-}
-
-afterEach(() => {
- cleanup()
- vi.clearAllMocks()
-})
-
-describe('HostWizard — step 0 gates on the derived slug (R1-B1)', () => {
- it('keeps Next DISABLED when the agent name has no alphanumerics', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: '!!!' } })
-
- expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()
- expect(screen.getByText(/Agent name must contain letters or numbers/i)).toBeInTheDocument()
- })
-
- it('keeps Next DISABLED for a whitespace-only name', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: ' ' } })
-
- expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()
- })
-
- it('enables Next for a name that derives a valid identifier', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: 'My Agent' } })
-
- expect(screen.getByRole('button', { name: 'Next' })).not.toBeDisabled()
- })
-})
-
-describe('HostWizard — step 1 new-context gate on the derived slug (R1-B1 sibling)', () => {
- it('keeps Next DISABLED when the new context name has no alphanumerics', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- // Step 0: valid name, advance.
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: 'agent-1' } })
- fireEvent.click(screen.getByRole('button', { name: 'Next' }))
-
- // Step 1: new context with a symbols-only name.
- fireEvent.click(screen.getByLabelText(/Create new context/i))
- fireEvent.change(screen.getByPlaceholderText(/context-name/i), { target: { value: '!!!' } })
-
- expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()
- expect(screen.getByText(/Context name must contain letters or numbers/i)).toBeInTheDocument()
- })
-
- it('enables Next when the new context name derives a valid identifier', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: 'agent-1' } })
- fireEvent.click(screen.getByRole('button', { name: 'Next' }))
-
- fireEvent.click(screen.getByLabelText(/Create new context/i))
- fireEvent.change(screen.getByPlaceholderText(/context-name/i), { target: { value: 'My Ctx' } })
-
- expect(screen.getByRole('button', { name: 'Next' })).not.toBeDisabled()
- })
-})
-
-/**
- * Regression guard for R4-H1: the step-0 gate must mirror the SERVER validation
- * (RFC1123 DNS-label ≤63 chars), not just "derives a non-empty slug". A 64-char
- * name derives a valid-but-too-long slug that passes `toKebabCase(x).length > 0`
- * yet is rejected server-side (`invalid_name`), orphaning the siblings created
- * before the host. FAILS against the pre-fix head where the gate was
- * `toKebabCase(state.hostName).length > 0`.
- */
-describe('HostWizard — step 0 gates on the RFC1123 length limit (R4-H1)', () => {
- it('keeps Next DISABLED when the derived slug exceeds 63 characters', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), {
- target: { value: 'a'.repeat(64) },
- })
-
- expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()
- expect(screen.getAllByText(/at most 63 characters/i).length).toBeGreaterThan(0)
- })
-
- it('enables Next for a 63-character derived slug (boundary)', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), {
- target: { value: 'a'.repeat(63) },
- })
-
- expect(screen.getByRole('button', { name: 'Next' })).not.toBeDisabled()
- })
-})
-
-/**
- * Regression guard for R4-B1: create is a PUT-first upsert, so a slug that
- * collides with an existing host would silently OVERWRITE that agent's spec and
- * report "created". The step-0 gate must block a colliding derived slug BEFORE
- * any sibling (secret/context/channel) is created — no create request escapes.
- * FAILS against the pre-fix head, which never loaded the host directory.
- */
-describe('HostWizard — step 0 blocks a slug colliding with an existing host (R4-B1)', () => {
- it('keeps Next DISABLED and fires no create request when the slug matches an existing host', async () => {
- ;(api.apiGet as unknown as ReturnType<typeof vi.fn>).mockImplementation((path: string) => {
- if (path === '/api/v1/admin/hosts') {
- return Promise.resolve({ items: [{ metadata: { name: 'my-agent' } }] })
- }
- return Promise.resolve({ items: [] })
- })
-
- await renderWizard()
- await waitFor(() => expect(api.apiGet).toHaveBeenCalledWith('/api/v1/admin/hosts'))
-
- // "My Agent" derives to the slug "my-agent", which already exists.
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: 'My Agent' } })
-
- expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()
- expect(screen.getByText(/Identifier already in use/i)).toBeInTheDocument()
- // No create request (POST/PUT via apiSend) escapes for a colliding slug.
- expect(api.apiSend).not.toHaveBeenCalled()
-
- // Restore the default apiGet stub so no implementation leaks past this test.
- ;(api.apiGet as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({ items: [] })
- })
-})
-
-/**
- * Regression guard for R4-M5: the step-2 SECRET gate must mirror the SERVER,
- * which validates a K8s Secret name as an RFC1123 DNS SUBDOMAIN (≤253 chars,
- * `isValidDNSSubdomain`), NOT the stricter ≤63 DNS label used for
- * host/context/channel names. R4-H1's fix wrongly applied the ≤63-label
- * validator (`isValidResourceSlug`) to the secret, making the client STRICTER
- * than the server: a 60-char host name auto-derives a `${slug}-llm` secret of 64
- * chars, which the server accepts (≤253) but the ≤63 gate blocked — freezing
- * step 2 before the user ever touched the secret field.
- *
- * FAILS against the R4-H1 head (11d5beee), where the secret gate read
- * `isValidResourceSlug(state.newSecretName)` / `slugConstraintMessage`.
- */
-describe('HostWizard — step 2 secret gate mirrors the server DNS-subdomain limit (R4-M5)', () => {
- it('enables Next on a 64-char derived secret name the server (≤253) accepts', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- // 60-char host name → 60-char slug (valid ≤63). The auto-derived secret
- // default is `${slug}-llm` = 64 chars, a valid DNS subdomain the server
- // accepts. The operator never touches the secret field.
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), {
- target: { value: 'a'.repeat(60) },
- })
- fireEvent.click(screen.getByRole('button', { name: 'Next' }))
-
- // Step 1: a new context with just a valid name, advance to step 2.
- fireEvent.click(screen.getByLabelText(/Create new context/i))
- fireEvent.change(screen.getByPlaceholderText(/context-name/i), { target: { value: 'ctx1' } })
- fireEvent.click(screen.getByRole('button', { name: 'Next' }))
-
- // Step 2: fill the primary OpenAI key so the ONLY thing that could still
- // block Next is the secret name length. Post-fix (subdomain ≤253), the
- // 64-char default is valid → Next enabled and no length error shown.
- fireEvent.change(screen.getByLabelText(/OpenAI API key/i), { target: { value: 'sk-openai' } })
-
- expect(screen.queryByText(/at most 63 characters/i)).not.toBeInTheDocument()
- await waitFor(() => expect(screen.getByRole('button', { name: 'Next' })).not.toBeDisabled())
- })
-
- it('still blocks a secret name longer than 253 characters', async () => {
- await renderWizard()
- await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: 'agent-1' } })
- fireEvent.click(screen.getByRole('button', { name: 'Next' }))
-
- fireEvent.click(screen.getByLabelText(/Create new context/i))
- fireEvent.change(screen.getByPlaceholderText(/context-name/i), { target: { value: 'ctx1' } })
- fireEvent.click(screen.getByRole('button', { name: 'Next' }))
-
- // Step 2: make the primary credential valid so the secret length is the
- // sole blocker, then overtype the secret with a 254-char name (> subdomain
- // max). The gate must still block — the fix loosens the ceiling, not removes
- // it.
- fireEvent.change(screen.getByLabelText(/OpenAI API key/i), { target: { value: 'sk-openai' } })
- fireEvent.change(screen.getByPlaceholderText(/secret-name/i), {
- target: { value: 'a'.repeat(254) },
- })
-
- expect(screen.getByText(/at most 253 characters/i)).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()
- })
-})
-
-/**
- * Regression guard for R4-M6: R4-B1's fix added GET /admin/hosts INTO the same
- * `Promise.all` as users/teams/contexts/channels. `Promise.all` rejects if ANY
- * input rejects, so a 403/timeout/500 on the hosts fetch discarded every other
- * selector and dropped the wizard into `directoryLoadError` — even though hosts
- * only feeds a best-effort collision guard. The hosts fetch must be isolated so
- * its failure leaves the rest of the directory loaded and `existingHostNames`
- * empty (collision guard degrades fail-open, the pre-fix behavior).
- *
- * FAILS against the R4-B1 head (11d5beee), where the hosts fetch sat unguarded
- * inside the `Promise.all`.
- */
-describe('HostWizard — a failed GET /admin/hosts does not sink the directory load (R4-M6)', () => {
- it('loads the wizard and degrades the collision guard fail-open when hosts fetch rejects', async () => {
- ;(api.apiGet as unknown as ReturnType<typeof vi.fn>).mockImplementation((path: string) => {
- if (path === '/api/v1/admin/hosts') {
- return Promise.reject(new Error('403 forbidden'))
- }
- return Promise.resolve({ items: [] })
- })
-
- await renderWizard()
- await waitFor(() => expect(api.apiGet).toHaveBeenCalledWith('/api/v1/admin/hosts'))
-
- // The whole directory load did NOT fail: no error banner from Promise.all.
- expect(screen.queryByText(/Failed to load users\/teams\/contexts/i)).not.toBeInTheDocument()
-
- // Collision guard degraded fail-open: existingHostNames is empty, so a name
- // that would collide had the directory loaded is NOT blocked, and no
- // "already in use" message appears.
- fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: 'My Agent' } })
- expect(screen.getByRole('button', { name: 'Next' })).not.toBeDisabled()
- expect(screen.queryByText(/Identifier already in use/i)).not.toBeInTheDocument()
-
- // Restore the default apiGet stub so no implementation leaks past this test.
- ;(api.apiGet as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({ items: [] })
- })
-})
diff --git a/control-ui/components/__tests__/HostWizard.test.tsx b/control-ui/components/__tests__/HostWizard.test.tsx
index 3fc83fa88..50a7bcc05 100644
--- a/control-ui/components/__tests__/HostWizard.test.tsx
+++ b/control-ui/components/__tests__/HostWizard.test.tsx
@@ -149,6 +149,53 @@ function openTeamsAccessTab() {
fireEvent.click(screen.getByRole('tab', { name: /Teams/i }))
}
+/**
+ * Walk to the Access step choosing "New credential" so a Secret is actually
+ * created (secretMode='new'). This is the vehicle the create-only/compensation
+ * tests need: an already-POSTed secret that a later failure must roll back. The
+ * new Secret name is auto-derived from the agent name as `${slug}-llm`.
+ */
+async function walkToAccessStepNewSecret(opts?: { agentName?: string; contextName?: string }) {
+ const name = opts?.agentName ?? 'newsecretagent'
+ const ctx = opts?.contextName ?? 'ctx1'
+
+ await waitFor(() => {
+ expect(api.getAdminUsers).toHaveBeenCalled()
+ })
+
+ // Step 0: Agent name
+ fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: name } })
+ fireEvent.click(screen.getByRole('button', { name: 'Next' }))
+
+ // Step 1: new context
+ fireEvent.click(screen.getByLabelText(/Create new context/i))
+ fireEvent.change(screen.getByPlaceholderText(/context-name/i), { target: { value: ctx } })
+ fireEvent.click(screen.getByRole('button', { name: 'Next' }))
+
+ // Step 2: New credential → make the OpenAI primary usable; secret name auto-derives.
+ fireEvent.click(screen.getByLabelText(/New credential/i))
+ 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' }))
+
+ // Now at the "Access" step.
+}
+
+/**
+ * Build the exact Error object the client's fetch layer would surface for a 409,
+ * derived from the REAL formatApiError (importActual, T1) — never hand-shaped —
+ * so `error.status`, `error.code`, and `error.body` carry precisely what the
+ * producer emits. `bodyObj` stands in for the server's JSON response body.
+ */
+async function build409(bodyObj: Record<string, unknown>): Promise<Error> {
+ const actual = await vi.importActual<typeof import('../../lib/api')>('../../lib/api')
+ const text = JSON.stringify(bodyObj)
+ const res = new Response(text, { status: 409, statusText: 'Conflict' })
+ return actual.formatApiError(res, text)
+}
+
afterEach(() => {
cleanup()
vi.clearAllMocks()
@@ -413,10 +460,15 @@ 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.objectContaining({ spec: expect.objectContaining({ channels: [] }) })
+ 'POST',
+ '/api/v1/admin/hosts',
+ expect.objectContaining({
+ metadata: { name: 'empty-access-test' },
+ spec: expect.objectContaining({ channels: [] }),
+ })
)
})
@@ -564,18 +616,127 @@ describe('HostWizard — Agent type (stateless lifecycle)', () => {
fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))
await waitFor(() => {
- expect(api.apiSend).toHaveBeenCalledWith(
- 'PUT',
- '/api/v1/admin/hosts/stateful-agent',
- expect.any(Object)
- )
+ // Create-only contract (R5-C1/R5-B1): POST to the collection, not PUT to a name.
+ expect(api.apiSend).toHaveBeenCalledWith('POST', '/api/v1/admin/hosts', expect.any(Object))
})
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)
expect('workflowControl' in payload.spec).toBe(false)
})
})
+
+describe('HostWizard — create-only seam + compensation (R5-C1/R5-B1, V-1, V-7)', () => {
+ it('surfaces the friendly collision message and rolls back the created secret when the context POST 409s WITHOUT a body code', async () => {
+ // Code-less 409 from a create-only POST = unambiguous AlreadyExists collision.
+ const collision = await build409({
+ error: 'contexts.mcp.evenfire.io "ctx1" already exists',
+ })
+ vi.mocked(api.apiSend).mockImplementation(async (method: string, path: string) => {
+ if (method === 'POST' && path === '/api/v1/admin/contexts') throw collision
+ return {}
+ })
+
+ await renderWizard()
+ await walkToAccessStepNewSecret({ agentName: 'coll-agent', contextName: 'ctx1' })
+ fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))
+
+ // Observable (T4): the friendly per-resource collision message is shown —
+ // NOT the raw K8s AlreadyExists text.
+ await waitFor(() => {
+ expect(screen.getByText(/A context named "ctx1" already exists/i)).toBeInTheDocument()
+ })
+ // Observable (T4): the already-created secret is compensated with an inverse DELETE.
+ expect(api.apiSend).toHaveBeenCalledWith('DELETE', '/api/v1/admin/secrets/coll-agent-llm')
+ // The Host was never POSTed (the seam aborted before the boundary).
+ expect(
+ vi
+ .mocked(api.apiSend)
+ .mock.calls.some(c => c[0] === 'POST' && c[1] === '/api/v1/admin/hosts')
+ ).toBe(false)
+ })
+
+ it('rolls back the created secret AND context in inverse order when the HOST create fails', async () => {
+ const hostErr = await build409({
+ error: 'hosts.mcp.evenfire.io "hostfail" already exists',
+ })
+ vi.mocked(api.apiSend).mockImplementation(async (method: string, path: string) => {
+ if (method === 'POST' && path === '/api/v1/admin/hosts') throw hostErr
+ return {}
+ })
+
+ await renderWizard()
+ await walkToAccessStepNewSecret({ agentName: 'hostfail', contextName: 'ctx1' })
+ fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))
+
+ await waitFor(() => {
+ expect(screen.getByText(/That agent name is already in use/i)).toBeInTheDocument()
+ })
+ // Inverse order: created = [secret, context] → compensate context THEN secret.
+ const deletePaths = vi
+ .mocked(api.apiSend)
+ .mock.calls.filter(c => c[0] === 'DELETE')
+ .map(c => c[1])
+ expect(deletePaths).toEqual([
+ '/api/v1/admin/contexts/ctx1',
+ '/api/v1/admin/secrets/hostfail-llm',
+ ])
+ })
+
+ it('rolls back NOTHING when a GRANT fails after the host is created (V-7)', async () => {
+ // The grant runs AFTER hostCreated=true; its failure must not trigger any
+ // sibling rollback — the host + siblings stay and grants retry from detail.
+ // vi.clearAllMocks() resets call history but NOT implementations, so pin a
+ // clean all-resolving apiSend for this test (prior tests set throwing ones).
+ vi.mocked(api.apiSend).mockImplementation(async () => ({}))
+ vi.mocked(api.updateAgentUsers).mockRejectedValueOnce(new Error('grant boom'))
+
+ await renderWizard()
+ await walkToAccessStepNewSecret({ agentName: 'grantfail', contextName: 'ctx1' })
+ // Select a user so updateAgentUsers is invoked.
+ fireEvent.click(screen.getByLabelText(/alice/i))
+ fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))
+
+ // The grant error is surfaced verbatim (no 409 remap at the top level).
+ await waitFor(() => {
+ expect(screen.getByText(/grant boom/i)).toBeInTheDocument()
+ })
+ // The host WAS created...
+ expect(
+ vi
+ .mocked(api.apiSend)
+ .mock.calls.some(c => c[0] === 'POST' && c[1] === '/api/v1/admin/hosts')
+ ).toBe(true)
+ // ...so NO compensation DELETE runs.
+ expect(vi.mocked(api.apiSend).mock.calls.some(c => c[0] === 'DELETE')).toBe(false)
+ })
+
+ it('re-throws the server message untouched on a CODED 409 (CRD-outdated) — no collision remap', async () => {
+ // 409 WITH a body `code` = CRD-outdated, NOT a collision: keep the server's
+ // human message, do not remap to the friendly "already exists" text.
+ const crdErr = await build409({
+ error: 'context CRD is outdated; apply the latest CRDs and retry',
+ code: 'context_crd_outdated',
+ })
+ vi.mocked(api.apiSend).mockImplementation(async (method: string, path: string) => {
+ if (method === 'POST' && path === '/api/v1/admin/contexts') throw crdErr
+ return {}
+ })
+
+ await renderWizard()
+ await walkToAccessStepNewSecret({ agentName: 'crd-agent', contextName: 'ctx1' })
+ fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))
+
+ await waitFor(() => {
+ expect(screen.getByText(/context CRD is outdated/i)).toBeInTheDocument()
+ })
+ // The friendly collision text must NOT appear (coded 409 is not a collision).
+ expect(screen.queryByText(/A context named .* already exists/i)).not.toBeInTheDocument()
+ // Boundary rule still applies: the secret created before the failing context
+ // is compensated (host never created), but nothing beyond that.
+ expect(api.apiSend).toHaveBeenCalledWith('DELETE', '/api/v1/admin/secrets/crd-agent-llm')
+ })
+})