Skip to content

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

TypeScript

fix(control-ui): close host UX review gaps

Miguelon Peluchoneae69376fc15
diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsx
index 9671a052a..ecb085924 100644
--- a/control-ui/app/hosts/[name]/page.tsx
+++ b/control-ui/app/hosts/[name]/page.tsx
@@ -205,6 +205,10 @@ export default function HostDetailsPage() {
const [availableLlmSecrets, setAvailableLlmSecrets] = useState<HostSecretResource[]>([])
// Fallback policy (spec §3-R5). `undefined` = the Host has no llmPolicy.
const [llmPolicyDraft, setLlmPolicyDraft] = useState<LlmPolicy | undefined>(undefined)
+ // Keep the last server-backed policy separate from the editable draft. A
+ // model edit may contain an unsaved fallback slot, but Secret retirement
+ // must be guarded by the policy that is actually active on the Host.
+ const [persistedLlmPolicy, setPersistedLlmPolicy] = useState<LlmPolicy | undefined>(undefined)
// Per-host model allowlist subset (spec.allowedModels, Topic 3a). Empty = the
// host offers the full global allowlist per provider (back-compat default).
const [allowedModelsDraft, setAllowedModelsDraft] = useState<HostAllowedModel[]>([])
@@ -262,6 +266,17 @@ export default function HostDetailsPage() {
allowedCatalog
)
}, [allowedModelsDraft, allowedCatalog, providerDraft, llmPolicyDraft])
+ const protectedCredentialSlots = useMemo(
+ () =>
+ Array.from(
+ new Set(
+ (persistedLlmPolicy?.fallbacks ?? [])
+ .map(fallback => String(fallback.credentialSlot || '').trim())
+ .filter(Boolean)
+ )
+ ),
+ [persistedLlmPolicy]
+ )
// Mount race: if the host loaded before the allowlist and it had NO saved
// model, loadData resolved the draft to '' — seed the default once the
// catalog arrives. Never overrides a non-empty draft (a saved model that
@@ -302,6 +317,8 @@ export default function HostDetailsPage() {
const { host, contexts: contextsList, secrets: secretsList, agentUsers, agentTeams } = detail
if (!mountedRef.current) return
const spec = host.spec || {}
+ const nextPersistedLlmPolicy = normalizeLlmPolicy(spec.llmPolicy)
+ setPersistedLlmPolicy(nextPersistedLlmPolicy)
// AP-6: remember the version of THIS read — the edit drafts below are
// built from it, so it is the correct precondition for the eventual save.
formResourceVersionRef.current = String(host.metadata?.resourceVersion || '')
@@ -385,7 +402,7 @@ export default function HostDetailsPage() {
resolveDefaultModel(nextProvider, getModelOptions(allowedCatalog, nextProvider))
)
setSecretRefDraft(String(spec.secretRef || ''))
- setLlmPolicyDraft(normalizeLlmPolicy(spec.llmPolicy))
+ setLlmPolicyDraft(nextPersistedLlmPolicy)
// Hydrate the per-host model subset from the saved spec (Topic 3a); absent
// → [] = unrestricted (offers the full global allowlist per provider).
setAllowedModelsDraft(normalizeAllowedModels(spec.allowedModels))
@@ -1036,6 +1053,7 @@ export default function HostDetailsPage() {
key={secretRefDraft}
secretName={secretRefDraft}
existingKeys={currentSecretKeys}
+ protectedCredentialSlots={protectedCredentialSlots}
onClose={() => setLlmSecretModalOpen(false)}
onChanged={async () => {
await loadData('none')
diff --git a/control-ui/app/hosts/page.tsx b/control-ui/app/hosts/page.tsx
index 817e22e33..a1a96e45f 100644
--- a/control-ui/app/hosts/page.tsx
+++ b/control-ui/app/hosts/page.tsx
@@ -27,11 +27,23 @@ export default function HostsPage() {
setLoading(true)
setError('')
try {
- // Fetch hosts and contexts in parallel. The context payload powers the
- // hover card on the Context column (shows the same MCP-server list the
- // create wizard shows), so any failure to load it surfaces here too.
- const [hostsResponse, contextsResponse] = await Promise.all([getHosts(), getContexts()])
+ // Hosts are the primary resource for this page. Contexts only enrich the
+ // connector hover card, so an optional enrichment failure must not hide
+ // the table or its primary actions.
+ const hostsResponse = await getHosts()
setHosts(hostsResponse.items || [])
+ // Clear stale enrichment before refreshing it. If the optional request
+ // fails, rows still render with their raw context reference and a
+ // degraded connector count/hover card.
+ setContextsByRef({})
+
+ let contextsResponse
+ try {
+ contextsResponse = await getContexts()
+ } catch {
+ return
+ }
+
const map: Record<string, string[]> = {}
for (const ctx of contextsResponse.items || []) {
const ref = String(ctx.spec?.contextId || ctx.metadata?.name || '').trim()
diff --git a/control-ui/components/LlmSecretUpdateModal.tsx b/control-ui/components/LlmSecretUpdateModal.tsx
index 4c28b6891..7fdea3640 100644
--- a/control-ui/components/LlmSecretUpdateModal.tsx
+++ b/control-ui/components/LlmSecretUpdateModal.tsx
@@ -11,6 +11,8 @@ import { IconX } from './icons'
export type LlmSecretUpdateModalProps = {
secretName: string
existingKeys: string[]
+ /** Credential slots still referenced by persisted Host fallback policies. */
+ protectedCredentialSlots?: string[]
onClose: () => void
onChanged: () => Promise<void>
}
@@ -26,6 +28,7 @@ export type LlmSecretUpdateModalProps = {
export function LlmSecretUpdateModal({
secretName,
existingKeys,
+ protectedCredentialSlots = [],
onClose,
onChanged,
}: LlmSecretUpdateModalProps) {
@@ -61,6 +64,21 @@ export function LlmSecretUpdateModal({
return
}
+ // A fallback credentialSlot is a live reference into this Secret. Refuse
+ // the retirement before the empty-secret check and confirmation dialog so
+ // the operator gets the actionable reason even when this is the Secret's
+ // last stored key. Re-adding the key above intentionally removes it from
+ // removeKeys, so replacing a protected slot remains allowed.
+ const protectedSlotSet = new Set(protectedCredentialSlots)
+ const blockedRemovals = removeKeys.filter(key => protectedSlotSet.has(key))
+ if (blockedRemovals.length > 0) {
+ const quotedSlots = blockedRemovals.map(key => `"${key}"`).join(', ')
+ setError(
+ `Cannot remove ${quotedSlots}: an active fallback still references ${blockedRemovals.length === 1 ? 'this credential slot' : 'these credential slots'}. Update the fallback configuration first.`
+ )
+ return
+ }
+
const survivingKeys = new Set([
...existingKeys.filter(key => !removeKeys.includes(key)),
...Object.keys(stringData),
diff --git a/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx b/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx
index 14d45f4be..d64fca271 100644
--- a/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx
+++ b/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx
@@ -1,9 +1,17 @@
import React from 'react'
import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
+import {
+ cleanup,
+ fireEvent,
+ render as rtlRender,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react'
import HostDetailsPage from '../../app/hosts/[name]/page'
import * as api from '../../lib/api'
+import { materializeHostResource } from '../../test/fixtures/contextResource'
import { ToastProvider } from '../Toast'
const replaceMock = vi.fn()
@@ -83,18 +91,72 @@ const refetchedHost: TestHost = {
spec: { ...baseSpec },
}
-function setupApiMocks(bundleHost: TestHost, refetchHost: TestHost = bundleHost) {
- ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
+const modelCatalogRows = [
+ {
+ id: 'openai-gpt-5-4-mini',
+ provider: 'openai',
+ model: 'gpt-5.4-mini',
+ vendor: 'OpenAI',
+ display_name: null,
+ context_window_tokens: 400000,
+ enabled: true,
+ source: 'manual' as const,
+ stale: false,
+ created_at: '',
+ updated_at: '',
+ },
+ {
+ id: 'openai-gpt-5-4',
+ provider: 'openai',
+ model: 'gpt-5.4',
+ vendor: 'OpenAI',
+ display_name: null,
+ context_window_tokens: 400000,
+ enabled: true,
+ source: 'manual' as const,
+ stale: false,
+ created_at: '',
+ updated_at: '',
+ },
+ {
+ id: 'openai-gpt-4-1',
+ provider: 'openai',
+ model: 'gpt-4.1',
+ vendor: 'OpenAI',
+ display_name: null,
+ context_window_tokens: 1047576,
+ enabled: true,
+ source: 'manual' as const,
+ stale: false,
+ created_at: '',
+ updated_at: '',
+ },
+]
+
+const defaultSecretResources = [
+ { name: 'openai-secret', keys: ['openai-api-key'] },
+ { name: 'anthropic-secret', keys: ['claude-api-key'] },
+]
+
+function detailBundle(bundleHost: TestHost, secrets = defaultSecretResources) {
+ return {
host: bundleHost,
- contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],
- secrets: [
- { name: 'openai-secret', keys: ['openai-api-key'] },
- { name: 'anthropic-secret', keys: ['claude-api-key'] },
- ],
+ contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx', mcpServers: [] } }],
+ secrets,
users: [],
teams: [],
agentUsers: [],
agentTeams: [],
+ }
+}
+
+function setupApiMocks(
+ bundleHost: TestHost,
+ refetchHost: TestHost = bundleHost,
+ secrets = defaultSecretResources
+) {
+ ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
+ ...detailBundle(bundleHost, secrets),
})
;(api.getHost as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(refetchHost)
;(api.apiSend as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({})
@@ -127,6 +189,10 @@ function findHostPutPayload(): Record<string, unknown> {
return call![2] as Record<string, unknown>
}
+function configureModelCatalog() {
+ vi.mocked(api.getLlmModels).mockResolvedValue({ rows: modelCatalogRows })
+}
+
// Shape produced by lib/api formatApiError for the facade's AP-6 response
// body {error:'conflict', reason:'resource_changed'}.
function makeConflictError(): Error {
@@ -241,6 +307,7 @@ describe('HostDetailsPage current model and credential flow', () => {
beforeEach(() => {
vi.clearAllMocks()
mockParams = { name: 'foo' }
+ vi.mocked(api.getLlmModels).mockResolvedValue({ rows: [] })
setupApiMocks(formLoadHost, refetchedHost)
})
@@ -282,6 +349,215 @@ describe('HostDetailsPage current model and credential flow', () => {
expect(await screen.findByText('Model configuration saved.')).toBeInTheDocument()
})
+ it('cancels model changes, reloads the Host, and restores authoritative server state', async () => {
+ configureModelCatalog()
+ const authoritativeHost: TestHost = {
+ metadata: { name: 'foo', resourceVersion: 'rv-authoritative-cancel' },
+ spec: {
+ ...baseSpec,
+ model: { name: 'gpt-4.1', provider: 'openai' },
+ },
+ }
+ vi.mocked(api.getHostDetailBundle)
+ .mockResolvedValueOnce(detailBundle(formLoadHost))
+ .mockResolvedValue(detailBundle(authoritativeHost))
+
+ const view = render(<HostDetailsPage />)
+ navigateToTab(view, 'model')
+ await screen.findByText('Current model')
+
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
+ fireEvent.click(screen.getByLabelText('Current model', { selector: '#llm-primary-model' }))
+ fireEvent.click(await screen.findByRole('option', { name: 'gpt-5.4' }))
+ expect(
+ screen.getByLabelText('Current model', { selector: '#llm-primary-model' })
+ ).toHaveTextContent('gpt-5.4')
+
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel model changes' }))
+
+ expect(await screen.findByText('gpt-4.1')).toBeInTheDocument()
+ await waitFor(() => expect(api.getHostDetailBundle).toHaveBeenCalledTimes(2))
+ expect(
+ screen.queryByRole('button', { name: 'Save model configuration' })
+ ).not.toBeInTheDocument()
+ expect(
+ (api.apiSend as unknown as ReturnType<typeof vi.fn>).mock.calls.some(
+ args => args[0] === 'PUT' && args[1] === '/api/v1/admin/hosts/foo'
+ )
+ ).toBe(false)
+ })
+
+ it('keeps the model draft and displays the error when the Host save fails', async () => {
+ configureModelCatalog()
+ const formSpec = {
+ ...baseSpec,
+ description: 'Preserve this unrelated field',
+ channels: ['slack'],
+ approval: { tools: { shell_exec: true, web_search: false } },
+ workflowControl: { scopes: ['chat'] },
+ customField: { keep: true },
+ }
+ const formHost: TestHost = {
+ metadata: { name: 'foo', resourceVersion: 'rv-model-form' },
+ spec: formSpec,
+ }
+ setupApiMocks(formHost, formHost)
+ ;(api.apiSend as unknown as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
+ new Error('model save failed')
+ )
+
+ const view = render(<HostDetailsPage />)
+ navigateToTab(view, 'model')
+ await screen.findByText('Current model')
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
+ fireEvent.click(screen.getByLabelText('Current model', { selector: '#llm-primary-model' }))
+ fireEvent.click(await screen.findByRole('option', { name: 'gpt-5.4' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Save model configuration' }))
+
+ expect(await screen.findByText('model save failed')).toBeInTheDocument()
+ expect(
+ screen.getByLabelText('Current model', { selector: '#llm-primary-model' })
+ ).toHaveTextContent('gpt-5.4')
+ expect(screen.getByRole('button', { name: 'Save model configuration' })).toBeInTheDocument()
+ expect(screen.queryByText('Model configuration saved.')).not.toBeInTheDocument()
+
+ const payload = findHostPutPayload() as {
+ metadata?: { resourceVersion?: string }
+ spec: Record<string, unknown>
+ }
+ expect(payload.metadata?.resourceVersion).toBe('rv-model-form')
+ expect(payload.spec).toMatchObject({
+ description: 'Preserve this unrelated field',
+ channels: ['slack'],
+ approval: { tools: { shell_exec: true, web_search: false } },
+ workflowControl: { scopes: ['chat'] },
+ customField: { keep: true },
+ model: { provider: 'openai', name: 'gpt-5.4' },
+ secretRef: 'openai-secret',
+ })
+ })
+
+ it('renders the authoritative Host state after a successful model save', async () => {
+ configureModelCatalog()
+ const formSpec = {
+ ...baseSpec,
+ description: 'Keep this description',
+ channels: ['telegram'],
+ approval: { tools: { shell_exec: true } },
+ lifecycle: { stateless: false },
+ customField: 'keep-me',
+ }
+ const formHost: TestHost = {
+ metadata: { name: 'foo', resourceVersion: 'rv-model-form' },
+ spec: formSpec,
+ }
+ const preSaveHost: TestHost = {
+ metadata: { name: 'foo', resourceVersion: 'rv-model-refetch' },
+ spec: formSpec,
+ }
+ const authoritativeHost: TestHost = {
+ metadata: { name: 'foo', resourceVersion: 'rv-model-after-save' },
+ spec: {
+ ...formSpec,
+ // The refresh is authoritative even if the server normalizes the
+ // selected model or another writer changes it during the save.
+ model: { provider: 'openai', name: 'gpt-4.1' },
+ },
+ }
+ setupApiMocks(formHost, preSaveHost)
+ vi.mocked(api.getHostDetailBundle)
+ .mockResolvedValueOnce(detailBundle(formHost))
+ .mockResolvedValue(detailBundle(authoritativeHost))
+
+ const view = render(<HostDetailsPage />)
+ navigateToTab(view, 'model')
+ await screen.findByText('Current model')
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
+ fireEvent.click(screen.getByLabelText('Current model', { selector: '#llm-primary-model' }))
+ fireEvent.click(await screen.findByRole('option', { name: 'gpt-5.4' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Save model configuration' }))
+
+ expect(await screen.findByText('Model configuration saved.')).toBeInTheDocument()
+ expect(await screen.findByText('gpt-4.1')).toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'Save model configuration' })
+ ).not.toBeInTheDocument()
+
+ const payload = findHostPutPayload() as {
+ metadata?: { resourceVersion?: string }
+ spec: Record<string, unknown>
+ }
+ expect(payload.metadata?.resourceVersion).toBe('rv-model-form')
+ expect(payload.spec).toMatchObject({
+ description: 'Keep this description',
+ channels: ['telegram'],
+ approval: { tools: { shell_exec: true } },
+ lifecycle: { stateless: false },
+ customField: 'keep-me',
+ model: { provider: 'openai', name: 'gpt-5.4' },
+ secretRef: 'openai-secret',
+ })
+ expect(api.getHost).toHaveBeenCalledWith('foo')
+ expect(api.getHostDetailBundle).toHaveBeenCalledTimes(2)
+ })
+
+ it('blocks removing a stored fallback credential slot still referenced by the Host policy', async () => {
+ // Producer-valid Host data: the custom Secret key is referenced by an
+ // active fallback, not merely shown as an arbitrary extra Secret key.
+ const fallbackSlot = 'claude-api-key-fb1'
+ const hostWithFallback = materializeHostResource(
+ {
+ metadata: { name: 'foo' },
+ spec: {
+ ...baseSpec,
+ llmPolicy: {
+ fallbacks: [
+ {
+ provider: 'claude',
+ model: 'claude-sonnet-4-6',
+ credentialSlot: fallbackSlot,
+ },
+ ],
+ },
+ },
+ },
+ { metadata: { resourceVersion: 'rv-fallback-policy' } }
+ )
+ setupApiMocks(hostWithFallback, hostWithFallback, [
+ { name: 'openai-secret', keys: ['openai-api-key', fallbackSlot] },
+ { name: 'anthropic-secret', keys: ['claude-api-key'] },
+ ])
+
+ const view = render(<HostDetailsPage />)
+ navigateToTab(view, 'model')
+ await screen.findByText('Current model')
+ fireEvent.click(screen.getByRole('button', { name: 'Edit LLM Secret credentials' }))
+
+ const anthropicGroup = screen
+ .getByText('Anthropic', { selector: '.cu-llm-cred-group__title' })
+ .closest('section')
+ expect(anthropicGroup).not.toBeNull()
+ fireEvent.click(
+ within(anthropicGroup as HTMLElement).getByRole('button', {
+ name: 'Remove extra credential slot',
+ })
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'Update secret' }))
+
+ expect(
+ await screen.findByText(
+ new RegExp(`Cannot remove "${fallbackSlot}".*active fallback.*credential slot`)
+ )
+ ).toBeInTheDocument()
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ expect(
+ (api.apiSend as unknown as ReturnType<typeof vi.fn>).mock.calls.some(
+ args => args[0] === 'PUT' && args[1] === '/api/v1/admin/secrets'
+ )
+ ).toBe(false)
+ })
+
it('changes the linked LLM Secret from the inline credentials dropdown', async () => {
const view = render(<HostDetailsPage />)
navigateToTab(view, 'model')
diff --git a/control-ui/components/__tests__/HostDetailsPage.connectors.test.tsx b/control-ui/components/__tests__/HostDetailsPage.connectors.test.tsx
index 2d75001fd..feb104582 100644
--- a/control-ui/components/__tests__/HostDetailsPage.connectors.test.tsx
+++ b/control-ui/components/__tests__/HostDetailsPage.connectors.test.tsx
@@ -13,6 +13,7 @@ import * as api from '../../lib/api'
import {
buildContextResource,
buildSharedContextScenario,
+ materializeContextResource,
} from '../../test/fixtures/contextResource'
import { ToastProvider } from '../Toast'
@@ -180,22 +181,30 @@ describe('HostDetailsPage connectors', () => {
})
let persistedContext = scenario.context
- // Previous-head reproduction (43e0d17cc): the old test mounted only one
- // Host and supplied a partial hand-built Context. That fixture could pass
- // even if the page accidentally treated connector membership as Host-local.
- // Both producer-shaped Hosts below point at the same persisted Context, so
- // the second mount must observe the first Host's Context update.
- expect(scenario.hosts.foo.spec.contextRef).toBe(scenario.hosts.bar.spec.contextRef)
+ // Previous-head reproduction (8c9e129a7ad4e7252bf8dae5a3820c08cb32ed5b):
+ // the reviewed coverage mounted one Host with a partial hand-built Context.
+ // That setup could pass without proving that two producer Hosts consume the
+ // same persisted Context. Each response below is a fresh producer-shaped
+ // Host + Context read, so a Host-local connector list cannot satisfy the
+ // observable assertions.
;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockImplementation(
- async (name: string) => ({
- host: scenario.hosts[name as 'foo' | 'bar'],
- contexts: [persistedContext],
- secrets: [],
- users: [],
- teams: [],
- agentUsers: [],
- agentTeams: [],
- })
+ async (name: string) => {
+ const host = scenario.hosts[name as 'foo' | 'bar']
+ // Model the producer's detail response: Contexts are resolved from the
+ // Host's persisted reference, rather than injected into every Host
+ // response regardless of its binding.
+ const contexts =
+ persistedContext.metadata.name === host.spec.contextRef ? [persistedContext] : []
+ return {
+ host,
+ contexts,
+ secrets: [],
+ users: [],
+ teams: [],
+ agentUsers: [],
+ agentTeams: [],
+ }
+ }
)
;(api.getHost as unknown as ReturnType<typeof vi.fn>).mockImplementation(
async (name: string) => ({ ...scenario.hosts[name as 'foo' | 'bar'] })
@@ -205,28 +214,44 @@ describe('HostDetailsPage connectors', () => {
_name: string,
payload: { metadata: { resourceVersion: string }; spec: Record<string, unknown> }
) => {
- persistedContext = buildContextResource({
- metadata: {
- ...persistedContext.metadata,
- resourceVersion: 'rv-context-shared-2',
+ persistedContext = materializeContextResource(
+ {
+ metadata: { name: 'shared-connectors' },
+ spec: {
+ contextId: String(payload.spec.contextId || 'shared-connectors'),
+ description: String(payload.spec.description || ''),
+ mcpServers: Array.isArray(payload.spec.mcpServers)
+ ? payload.spec.mcpServers.map(String)
+ : [],
+ },
},
- spec: {
- ...persistedContext.spec,
- ...payload.spec,
- contextId: persistedContext.spec.contextId,
- mcpServers: Array.isArray(payload.spec.mcpServers)
- ? payload.spec.mcpServers.map(String)
- : [],
- },
- })
+ {
+ metadata: {
+ ...persistedContext.metadata,
+ resourceVersion: 'rv-context-shared-2',
+ },
+ spec: payload.spec,
+ }
+ )
return persistedContext
}
)
+ // Both Hosts render the same producer Context before any mutation. This
+ // is deliberately checked through the UI, not by inspecting contextRef.
activeHostName = 'foo'
renderPage()
expect(await screen.findByText('mcp-existing')).toBeInTheDocument()
+ cleanup()
+ activeHostName = 'bar'
+ renderPage()
+ expect(await screen.findByText('mcp-existing')).toBeInTheDocument()
+
+ cleanup()
+ activeHostName = 'foo'
+ renderPage()
+ expect(await screen.findByText('mcp-existing')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Add connector' }))
await waitFor(() => expect(api.getMcpServers).toHaveBeenCalledTimes(1))
fireEvent.click(await screen.findByRole('option', { name: 'mcp-new' }))
diff --git a/control-ui/components/__tests__/HostWizard.test.tsx b/control-ui/components/__tests__/HostWizard.test.tsx
index 453f52408..d3af99092 100644
--- a/control-ui/components/__tests__/HostWizard.test.tsx
+++ b/control-ui/components/__tests__/HostWizard.test.tsx
@@ -5,6 +5,7 @@ import * as api from '../../lib/api'
import {
buildHostReferencesForContext,
materializeContextResource,
+ materializeHostResource,
} from '../../test/fixtures/contextResource'
import { buildSecretSummary } from '../../test/fixtures/secretSummary'
import { HostWizard } from '../HostWizard'
@@ -450,17 +451,19 @@ describe('HostWizard — connector selection and automatic context creation', ()
const context = materializeContextResource(
contextCall![2] as Parameters<typeof materializeContextResource>[0]
)
- const contextRef = (hostCall![2] as { spec: { contextRef: string } }).spec.contextRef
- const twoHosts = buildHostReferencesForContext(contextRef, [
- 'shared-context-agent',
- 'second-agent',
- ])
+ const createdHost = materializeHostResource(
+ hostCall![2] as Parameters<typeof materializeHostResource>[0],
+ { metadata: { resourceVersion: 'rv-host-created' } }
+ )
+ const secondHost = buildHostReferencesForContext(createdHost.spec.contextRef, ['second-agent'])[
+ 'second-agent'
+ ]
+ const twoHosts = [createdHost, secondHost]
expect(context.spec.mcpServers).toEqual(['mcp-a'])
- expect(context.metadata.name).toBe(contextRef)
- expect(new Set(Object.values(twoHosts).map(host => host.spec.contextRef))).toEqual(
- new Set([contextRef])
- )
+ expect(createdHost.spec.contextRef).toBe(context.metadata.name)
+ expect(twoHosts).toHaveLength(2)
+ expect(twoHosts.every(host => host.spec.contextRef === context.metadata.name)).toBe(true)
})
})
diff --git a/control-ui/components/__tests__/HostsPage.test.tsx b/control-ui/components/__tests__/HostsPage.test.tsx
new file mode 100644
index 000000000..1afc1afca
--- /dev/null
+++ b/control-ui/components/__tests__/HostsPage.test.tsx
@@ -0,0 +1,78 @@
+import type { ReactNode } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, render, screen } from '@testing-library/react'
+import HostsPage from '../../app/hosts/page'
+import * as api from '../../lib/api'
+import { materializeHostResource } from '../../test/fixtures/contextResource'
+
+const pushMock = vi.fn()
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: pushMock, replace: vi.fn() }),
+ usePathname: () => '/agents',
+}))
+
+vi.mock('@components/AuthGate', () => ({
+ AuthGate: ({ children }: { children: ReactNode }) => children,
+}))
+
+vi.mock('@components/DashboardLayout', () => ({
+ DashboardLayout: ({ children }: { children: ReactNode }) => children,
+}))
+
+vi.mock('@components/ConfirmDialog', () => ({
+ useConfirmDialog: () => ({ confirm: vi.fn(), confirmDialog: null }),
+}))
+
+vi.mock('@components/Toast', () => ({
+ useToast: () => ({ showToast: vi.fn() }),
+}))
+
+vi.mock('../../lib/api', () => ({
+ apiSend: vi.fn(),
+ getContexts: vi.fn(),
+ getHosts: vi.fn(),
+ isSilentApiError: vi.fn().mockReturnValue(false),
+}))
+
+afterEach(() => {
+ cleanup()
+})
+
+describe('HostsPage optional Context enrichment', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('keeps the Hosts table and primary actions available when Context enrichment fails', async () => {
+ const host = materializeHostResource({
+ metadata: { name: 'agent-a' },
+ spec: {
+ host: 'Agent A',
+ contextRef: 'agent-a-context',
+ secretRef: 'openai-secret',
+ channels: [],
+ model: { provider: 'openai', name: 'gpt-5.4-mini' },
+ },
+ })
+ vi.mocked(api.getHosts).mockResolvedValue({
+ items: [host],
+ })
+ vi.mocked(api.getContexts).mockRejectedValue(new Error('Context service unavailable'))
+
+ render(<HostsPage />)
+
+ expect(await screen.findByText('Agent A')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Create agent' })).toBeEnabled()
+ expect(screen.getByRole('button', { name: 'Reload agents' })).toBeEnabled()
+
+ // The row remains usable with only the non-critical connector enrichment
+ // degraded: a raw Context reference renders as a zero count with no hover
+ // card, while the rest of the Host row remains present.
+ expect(screen.getByText('0')).toBeInTheDocument()
+ expect(screen.queryByRole('tooltip')).not.toBeInTheDocument()
+ expect(screen.queryByText('Context service unavailable')).not.toBeInTheDocument()
+ expect(api.getHosts).toHaveBeenCalledTimes(1)
+ expect(api.getContexts).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index accdf57c0..2c6910463 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.451",
+ "version": "0.1.452",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.451",
+ "version": "0.1.452",
"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.json
index 1efd79c00..24b4ddf96 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.451",
+ "version": "0.1.452",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/control-ui/test/fixtures/contextResource.ts b/control-ui/test/fixtures/contextResource.ts
index 26caa9aad..7a365e1a5 100644
--- a/control-ui/test/fixtures/contextResource.ts
+++ b/control-ui/test/fixtures/contextResource.ts
@@ -29,6 +29,36 @@ export type ProducerContextCreatePayload = {
}
}
+/** The create payload emitted by HostWizard before Kubernetes adds metadata/status. */
+export type ProducerHostCreatePayload = {
+ metadata: { name: string }
+ spec: {
+ host: string
+ contextRef: string
+ secretRef: string
+ channels: string[]
+ model: { provider: string; name: string }
+ [key: string]: unknown
+ }
+}
+
+/** The Host shape returned by the producer after Kubernetes materializes it. */
+export type ProducerHostResource = {
+ metadata: {
+ name: string
+ namespace: string
+ resourceVersion: string
+ }
+ spec: {
+ host: string
+ contextRef: string
+ secretRef: string
+ channels: string[]
+ model: { provider: string; name: string }
+ [key: string]: unknown
+ }
+}
+
export type ContextResourceOverrides = {
metadata?: Partial<ProducerContextResource['metadata']>
spec?: Partial<ProducerContextResource['spec']>
@@ -89,16 +119,51 @@ export function materializeContextResource(
})
}
+/**
+ * Materialize the persisted Host shape from the exact HostWizard POST body.
+ * The defaults model the producer/Kubernetes response fields that are
+ * relevant to a Host consuming a Context; the payload's remaining spec fields
+ * are retained so tests cannot accidentally discard unrelated Host settings.
+ */
+export function materializeHostResource(
+ payload: ProducerHostCreatePayload,
+ overrides: {
+ metadata?: Partial<ProducerHostResource['metadata']>
+ spec?: Partial<ProducerHostResource['spec']>
+ } = {}
+): ProducerHostResource {
+ return {
+ metadata: {
+ name: payload.metadata.name,
+ namespace: 'mcp-host',
+ resourceVersion: 'rv-host-read',
+ ...overrides.metadata,
+ },
+ spec: {
+ ...payload.spec,
+ channels: [...payload.spec.channels],
+ model: { ...payload.spec.model },
+ ...overrides.spec,
+ },
+ }
+}
+
export function buildHostReferencesForContext(
contextName: string,
hostNames: readonly string[] = ['foo', 'bar']
-) {
+): Record<string, ProducerHostResource> {
return Object.fromEntries(
hostNames.map(name => [
name,
{
metadata: { name, namespace: 'mcp-host', resourceVersion: `rv-host-${name}` },
- spec: { host: name, contextRef: contextName },
+ spec: {
+ host: name,
+ contextRef: contextName,
+ secretRef: 'shared-llm-secret',
+ channels: [],
+ model: { provider: 'openai', name: 'gpt-5.4-mini' },
+ },
},
])
)
@@ -118,18 +183,22 @@ export function buildSharedContextScenario(
} = {}
) {
const contextName = input.contextName ?? 'shared-connectors'
- const context = buildContextResource({
- metadata: {
- name: contextName,
- namespace: 'mcp-server',
- resourceVersion: 'rv-context-shared-1',
- },
- spec: {
- contextId: contextName,
- description: input.description ?? 'Shared connector context',
- mcpServers: [...(input.mcpServers ?? [])],
+ const context = materializeContextResource(
+ {
+ metadata: { name: contextName },
+ spec: {
+ contextId: contextName,
+ description: input.description ?? 'Shared connector context',
+ mcpServers: [...(input.mcpServers ?? [])],
+ },
},
- })
+ {
+ metadata: {
+ namespace: 'mcp-server',
+ resourceVersion: 'rv-context-shared-1',
+ },
+ }
+ )
const hostNames = input.hostNames ?? ['foo', 'bar']
const hosts = buildHostReferencesForContext(contextName, hostNames)