Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-ui): stale-model attention banner + model_in_use force gate on llm-models (Pieza C)
Diego Zacarias5d16ecc10086
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex d72d00381..0d0558c4f 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -4440,6 +4440,68 @@ textarea.cu-input {color: var(--cu-text-soft);}+/* Catalog-attention banner (stale-but-referenced models) on /llm-models. */+.cu-model-attention__lede {+ margin: 0 0 var(--cu-space-2);+}++.cu-model-attention__list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: var(--cu-space-3);+}++.cu-model-attention__head {+ display: block;+}++.cu-model-attention__name {+ font-weight: 600;+}++.cu-model-attention__meta {+ color: var(--cu-text-soft);+}++/* Shared Host/grant reference list (attention banner + 409 impact confirm). */+.cu-model-refs {+ display: flex;+ flex-direction: column;+ gap: var(--cu-space-2);+ margin-top: var(--cu-space-2);+}++.cu-model-refs__label {+ display: block;+ font-weight: 600;+ font-size: 0.8125rem;+}++.cu-model-refs__list {+ list-style: none;+ margin: var(--cu-space-1) 0 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: var(--cu-space-1);+}++.cu-model-refs__item {+ font-size: 0.8125rem;+}++.cu-model-refs__meta {+ color: var(--cu-text-soft);+}++/* Rich detail block inside a confirm dialog (e.g. the impact reference list). */+.cu-modal-copy--details {+ margin-top: var(--cu-space-3);+}+.cu-toast-stack {position: fixed;right: 1rem;diff --git a/control-ui/app/llm-models/[id]/edit/page.tsx b/control-ui/app/llm-models/[id]/edit/page.tsxindex 497d0d250..38ce3e607 100644--- a/control-ui/app/llm-models/[id]/edit/page.tsx+++ b/control-ui/app/llm-models/[id]/edit/page.tsx@@ -4,10 +4,12 @@ import React, { useEffect, useState } from 'react'import { useParams, useRouter } from 'next/navigation'import { AuthGate } from '@components/AuthGate'import { FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'+import { useConfirmDialog } from '@components/ConfirmDialog'import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'import { LlmModelForm } from '@components/LlmModelForm'+import { ModelReferences } from '@components/ModelReferences'import { IconModels } from '@components/Sidebar/icons'import { useToast } from '@components/Toast'import { CONTROL_ROUTES } from '@constants/routes'@@ -15,6 +17,7 @@ import {type CreateLlmModelInput,type LlmAllowedModel,getLlmModel,+ getModelInUseImpact,isLlmModelConfigMapDeferred,updateLlmModel,} from '@lib/api'@@ -24,6 +27,7 @@ export default function EditLlmModelPage() {const params = useParams<{ id: string }>()const id = decodeURIComponent(params?.id ?? '')const { showToast } = useToast()+ const { confirm, confirmDialog } = useConfirmDialog()const [model, setModel] = useState<LlmAllowedModel | null>(null)const [loading, setLoading] = useState(true)@@ -57,12 +61,21 @@ export default function EditLlmModelPage() {}, [id])async function handleSubmit(input: CreateLlmModelInput) {+ await saveWithImpactGate(input, false)+ }++ // Disabling a referenced model (enabled→false) is gated by control-api: without+ // `?force` it answers 409 `model_in_use` with the impact. Show it and let the+ // operator confirm a forced retry — never force automatically (spec Fase 3/5).+ async function saveWithImpactGate(input: CreateLlmModelInput, force: boolean) {setSaving(true)setSaveError('')+ let impact: ReturnType<typeof getModelInUseImpact> = nulltry {- await updateLlmModel(id, input)+ await updateLlmModel(id, input, force ? { force: true } : {})showToast(`${input.provider}/${input.model} updated.`, { tone: 'success' })backToList()+ return} catch (e) {// The row was updated; only the runtime ConfigMap write is delayed.if (isLlmModelConfigMapDeferred(e)) {@@ -73,10 +86,28 @@ export default function EditLlmModelPage() {backToList()return}- setSaveError(e instanceof Error ? e.message : 'Failed to update model')+ impact = getModelInUseImpact(e)+ if (!impact) {+ setSaveError(e instanceof Error ? e.message : 'Failed to update model')+ return+ }} finally {setSaving(false)}++ const forceDisable = await confirm({+ title: 'Model still in use',+ message: `${input.provider}/${input.model} is still referenced. Disabling it leaves these references pointing at a disabled model:`,+ details: (+ <ModelReferences+ hostsAffected={impact.hostsAffected}+ grantsAffected={impact.grantsAffected}+ />+ ),+ confirmLabel: 'Disable anyway',+ tone: 'danger',+ })+ if (forceDisable) await saveWithImpactGate(input, true)}return (@@ -118,6 +149,7 @@ export default function EditLlmModelPage() {/>) : null}</CreateFlowPanel>+ {confirmDialog}</DashboardLayout></AuthGate>)diff --git a/control-ui/components/ConfirmDialog/index.tsx b/control-ui/components/ConfirmDialog/index.tsxindex 1a88317c6..656a9f2d1 100644--- a/control-ui/components/ConfirmDialog/index.tsx+++ b/control-ui/components/ConfirmDialog/index.tsx@@ -30,6 +30,7 @@ function ConfirmDialog({ request, onResolve }: ConfirmDialogProps) {const {cancelLabel = 'Cancel',confirmLabel = 'OK',+ details,message,title = 'Confirm action',tone = 'default',@@ -60,6 +61,7 @@ function ConfirmDialog({ request, onResolve }: ConfirmDialogProps) {<p id={messageId} className="cu-modal-copy">{message}</p>+ {details ? <div className="cu-modal-copy cu-modal-copy--details">{details}</div> : null}<div className="cu-modal-panel__foot"><buttonref={cancelButtonRef}diff --git a/control-ui/components/ConfirmDialog/types.ts b/control-ui/components/ConfirmDialog/types.tsindex bf38ba65a..bf0bec60a 100644--- a/control-ui/components/ConfirmDialog/types.ts+++ b/control-ui/components/ConfirmDialog/types.ts@@ -1,8 +1,16 @@+import type { ReactNode } from 'react'+export type ConfirmDialogTone = 'default' | 'danger'export interface ConfirmDialogOptions {title?: stringmessage: string+ /**+ * Optional rich content rendered below the message inside the dialog — used to+ * show structured detail (e.g. the list of Host/grant references a forced+ * action would strand) the operator must see before confirming.+ */+ details?: ReactNodeconfirmLabel?: stringcancelLabel?: stringtone?: ConfirmDialogTonediff --git a/control-ui/components/LlmModelsSurface/CatalogAttentionBanner.tsx b/control-ui/components/LlmModelsSurface/CatalogAttentionBanner.tsxnew file mode 100644index 000000000..e5ef95929--- /dev/null+++ b/control-ui/components/LlmModelsSurface/CatalogAttentionBanner.tsx@@ -0,0 +1,85 @@+'use client'++import React, { useEffect, useState } from 'react'+import { useAuth } from '@components/AuthContext'+import { ModelReferences } from '@components/ModelReferences'+import { type AdminAttentionItem, getAdminAttention, isSilentApiError } from '@lib/api'+import { getProviderDisplayLabel } from '@lib/llm'+import type { CatalogAttentionBannerProps } from './types'++// The only attention kind today; the feed's `kind` is an open union, so the+// banner renders known kinds and ignores anything else (spec Fase 5, Pieza C).+const STALE_MODEL_REFERENCED = 'stale_model_referenced'++/**+ * Self-contained inline alert on the /llm-models catalog surface. Fetches+ * `GET /admin/attention` and lists each `stale` catalog model that is still+ * referenced by a live Host/grant, so the operator disables it (impact-gated+ * PUT) or repoints those references. A fetch failure degrades softly — the+ * banner stays hidden and never tumbles the surface.+ */+export function CatalogAttentionBanner({ refreshSignal }: CatalogAttentionBannerProps = {}) {+ const { authState } = useAuth()+ const [items, setItems] = useState<AdminAttentionItem[]>([])++ // Re-fetches on mount and whenever `refreshSignal` changes — the surface bumps+ // it after a successful mutation so a just-resolved item stops showing. On+ // demand only; there is no polling.+ useEffect(() => {+ if (!(authState.isLoggedIn && !authState.isLoading)) return+ let cancelled = false+ async function load() {+ try {+ const report = await getAdminAttention()+ if (!cancelled) setItems(report.items)+ } catch (err) {+ if (isSilentApiError(err)) return+ // Advisory banner: a failure must never break the models surface.+ if (!cancelled) setItems([])+ }+ }+ void load()+ return () => {+ cancelled = true+ }+ }, [authState.isLoggedIn, authState.isLoading, refreshSignal])++ // Known-kind items only. An unknown `kind` is ignored (never crashes); a feed+ // with no known items renders no banner.+ const staleItems = items.filter(item => item.kind === STALE_MODEL_REFERENCED)+ if (staleItems.length === 0) return null++ const plural = staleItems.length === 1 ? '' : 's'+ return (+ <div className="cu-banner cu-banner--warning cu-model-attention" role="status">+ <p className="cu-model-attention__lede">+ <strong>{staleItems.length}</strong> model{plural} disappeared from the provider catalog but{' '}+ {staleItems.length === 1 ? 'is' : 'are'} still referenced. Disable{' '}+ {staleItems.length === 1 ? 'it' : 'each one'} or update the references pointing at it.+ </p>+ <ul className="cu-model-attention__list">+ {staleItems.map(item => {+ const label = item.displayName ?? item.model+ const hostCount = item.hostsAffected.length+ const grantCount = item.grantsAffected.length+ return (+ <li key={`${item.provider}/${item.model}`} className="cu-model-attention__item">+ <span className="cu-model-attention__head">+ <span className="cu-model-attention__name">{label}</span>{' '}+ <span className="cu-model-attention__meta">+ ({getProviderDisplayLabel(item.provider)})+ </span>{' '}+ — {hostCount} Host{hostCount === 1 ? '' : 's'} / {grantCount} grant+ {grantCount === 1 ? '' : 's'} still use it.+ </span>+ <ModelReferences+ hostsAffected={item.hostsAffected}+ grantsAffected={item.grantsAffected}+ />+ </li>+ )+ })}+ </ul>+ </div>+ )+}diff --git a/control-ui/components/LlmModelsSurface/index.tsx b/control-ui/components/LlmModelsSurface/index.tsxindex 90d874b62..4f5be0785 100644--- a/control-ui/components/LlmModelsSurface/index.tsx+++ b/control-ui/components/LlmModelsSurface/index.tsx@@ -8,6 +8,7 @@ import { useConfirmDialog } from '@components/ConfirmDialog'import { DashboardLayout } from '@components/DashboardLayout'import { LlmDiscoveryPanel } from '@components/LlmDiscoveryPanel'import { LlmModelTable } from '@components/LlmModelTable'+import { ModelReferences } from '@components/ModelReferences'import { TabBar } from '@components/TabBar'import { useToast } from '@components/Toast'import { CONTROL_ROUTES } from '@constants/routes'@@ -16,12 +17,14 @@ import {type UnpricedModel,deleteLlmModel,getLlmModels,+ getModelInUseImpact,getUnpricedModels,isLlmModelConfigMapDeferred,isSilentApiError,} from '@lib/api'import { getProviderDisplayLabel } from '@lib/llm'import { buildUnpricedKeys } from '@lib/llmModelUnpriced'+import { CatalogAttentionBanner } from './CatalogAttentionBanner'import type { LlmModelsSurfaceProps, LlmModelsTab } from './types'const CONFIGMAP_DEFERRED_WARNING =@@ -38,6 +41,9 @@ function LlmModelsContent({ activeTab }: LlmModelsSurfaceProps) {const [loading, setLoading] = useState(false)const [error, setError] = useState('')const [deletingId, setDeletingId] = useState<string | null>(null)+ // Bumped after each successful mutation so the attention banner re-fetches+ // and drops any item the operator just resolved (on demand, no polling).+ const [attentionRefreshKey, setAttentionRefreshKey] = useState(0)const unpricedKeys = useMemo(() => buildUnpricedKeys(unpriced), [unpriced])@@ -82,24 +88,52 @@ function LlmModelsContent({ activeTab }: LlmModelsSurfaceProps) {tone: 'danger',})if (!shouldDelete) return+ await deleteWithImpactGate(model, label, false)+ }+ // A first delete goes without `?force`. If control-api answers 409+ // `model_in_use`, show the impact and let the operator confirm a forced retry+ // — never force automatically (spec Fase 3/5).+ async function deleteWithImpactGate(model: LlmAllowedModel, label: string, force: boolean) {setDeletingId(model.id)setError('')+ let impact: ReturnType<typeof getModelInUseImpact> = nulltry {- await deleteLlmModel(model.id)+ await deleteLlmModel(model.id, force ? { force: true } : {})await loadAll()+ setAttentionRefreshKey(key => key + 1)showToast(`${label} removed from the allowlist.`, { tone: 'success' })+ return} catch (caught) {if (isSilentApiError(caught)) returnif (isLlmModelConfigMapDeferred(caught)) {await loadAll()+ setAttentionRefreshKey(key => key + 1)showToast(`${label} removed. ${CONFIGMAP_DEFERRED_WARNING}`, { tone: 'info' })return}- setError(caught instanceof Error ? caught.message : `Failed to delete ${label}`)+ impact = getModelInUseImpact(caught)+ if (!impact) {+ setError(caught instanceof Error ? caught.message : `Failed to delete ${label}`)+ return+ }} finally {setDeletingId(null)}++ const forceRemove = await confirm({+ title: 'Model still in use',+ message: `${label} is still referenced. Removing it leaves these references pointing at a deleted model:`,+ details: (+ <ModelReferences+ hostsAffected={impact.hostsAffected}+ grantsAffected={impact.grantsAffected}+ />+ ),+ confirmLabel: 'Remove anyway',+ tone: 'danger',+ })+ if (forceRemove) await deleteWithImpactGate(model, label, true)}useEffect(() => {@@ -140,6 +174,9 @@ function LlmModelsContent({ activeTab }: LlmModelsSurfaceProps) {{error}</div>) : null}+ {activeTab === 'catalog' ? (+ <CatalogAttentionBanner refreshSignal={attentionRefreshKey} />+ ) : null}{activeTab === 'catalog' ? (<LlmModelTableitems={models}diff --git a/control-ui/components/LlmModelsSurface/types.ts b/control-ui/components/LlmModelsSurface/types.tsindex 143e11a88..a37303973 100644--- a/control-ui/components/LlmModelsSurface/types.ts+++ b/control-ui/components/LlmModelsSurface/types.ts@@ -3,3 +3,13 @@ export type LlmModelsTab = 'catalog' | 'discovery'export type LlmModelsSurfaceProps = {activeTab: LlmModelsTab}++export type CatalogAttentionBannerProps = {+ /**+ * Bumped by the surface after each successful mutation (disable/force-delete)+ * so the advisory banner re-fetches the attention feed on demand and stops+ * showing an item the operator just resolved. Not a poll — a change of this+ * value is the only extra fetch trigger beyond mount.+ */+ refreshSignal?: number+}diff --git a/control-ui/components/ModelReferences/index.tsx b/control-ui/components/ModelReferences/index.tsxnew file mode 100644index 000000000..a51727bec--- /dev/null+++ b/control-ui/components/ModelReferences/index.tsx@@ -0,0 +1,55 @@+'use client'++import React from 'react'+import type { ModelReferencesProps } from './types'++/**+ * Renders the live Host/grant references to a (provider, model) pair. Shared by+ * the catalog-attention banner (Fase 5, Pieza C) and the 409 `model_in_use`+ * impact confirm (Fase 3) so both surfaces list the references identically.+ * Renders nothing when there are no references.+ */+export function ModelReferences({ hostsAffected, grantsAffected }: ModelReferencesProps) {+ if (hostsAffected.length === 0 && grantsAffected.length === 0) return null++ return (+ <div className="cu-model-refs">+ {hostsAffected.length > 0 ? (+ <div className="cu-model-refs__group">+ <span className="cu-model-refs__label">+ {hostsAffected.length} Host{hostsAffected.length === 1 ? '' : 's'}+ </span>+ <ul className="cu-model-refs__list">+ {hostsAffected.map(host => (+ <li key={`${host.namespace}/${host.name}`} className="cu-model-refs__item">+ <span className="cu-model-refs__ref">+ {host.namespace}/{host.name}+ </span>+ {host.roles.length > 0 ? (+ <span className="cu-model-refs__meta"> ({host.roles.join(', ')})</span>+ ) : null}+ </li>+ ))}+ </ul>+ </div>+ ) : null}+ {grantsAffected.length > 0 ? (+ <div className="cu-model-refs__group">+ <span className="cu-model-refs__label">+ {grantsAffected.length} grant{grantsAffected.length === 1 ? '' : 's'}+ </span>+ <ul className="cu-model-refs__list">+ {grantsAffected.map(grant => (+ <li key={grant.id} className="cu-model-refs__item">+ <span className="cu-model-refs__ref">+ {grant.recipeNamespace}/{grant.recipeName}+ </span>+ <span className="cu-model-refs__meta"> · {grant.capabilityFamily}</span>+ </li>+ ))}+ </ul>+ </div>+ ) : null}+ </div>+ )+}diff --git a/control-ui/components/ModelReferences/types.ts b/control-ui/components/ModelReferences/types.tsnew file mode 100644index 000000000..9f6f998bd--- /dev/null+++ b/control-ui/components/ModelReferences/types.ts@@ -0,0 +1,6 @@+import type { ModelGrantReference, ModelHostReference } from '@lib/api'++export type ModelReferencesProps = {+ hostsAffected: ModelHostReference[]+ grantsAffected: ModelGrantReference[]+}diff --git a/control-ui/components/__tests__/LlmModelEditImpactGate.test.tsx b/control-ui/components/__tests__/LlmModelEditImpactGate.test.tsxnew file mode 100644index 000000000..4c9cc379a--- /dev/null+++ b/control-ui/components/__tests__/LlmModelEditImpactGate.test.tsx@@ -0,0 +1,150 @@+import type React from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import type { CreateLlmModelInput, LlmAllowedModel } from '@lib/api'+import { getLlmModel, updateLlmModel } from '@lib/api'+import EditLlmModelPage from '../../app/llm-models/[id]/edit/page'++const mockPush = vi.fn()+const mockShowToast = vi.fn()++vi.mock('next/navigation', () => ({+ useRouter: () => ({ push: mockPush }),+ useParams: () => ({ id: 'model-1' }),+}))+vi.mock('@components/AuthGate', () => ({+ AuthGate: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}))+vi.mock('@components/DashboardLayout', () => ({+ DashboardLayout: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}))+vi.mock('@components/CreateFlowPanel', () => ({+ CreateFlowPanel: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}))+vi.mock('@components/CreatePageHeader', () => ({ CreatePageHeader: () => null }))+vi.mock('@components/Sidebar/icons', () => ({ IconModels: () => null }))+vi.mock('@components/Toast', () => ({+ useToast: () => ({ showToast: mockShowToast }),+}))+// Trimmed form: exposes a submit trigger that emits a disable (enabled:false)+// payload so the page's saveWithImpactGate runs end to end. A distinctive label+// (not the loading skeleton's own "Save model" button) so the query resolves to+// the loaded form, never the transient skeleton.+const SUBMIT_INPUT: CreateLlmModelInput = {+ provider: 'claude',+ model: 'claude-haiku-4-5',+ enabled: false,+}+const SUBMIT_LABEL = 'Submit model edit'+vi.mock('@components/LlmModelForm', () => ({+ LlmModelForm: ({ onSubmit }: { onSubmit: (input: CreateLlmModelInput) => void }) => (+ <button type="button" onClick={() => onSubmit(SUBMIT_INPUT)}>+ {SUBMIT_LABEL}+ </button>+ ),+}))+vi.mock('@lib/api', async importOriginal => {+ const actual = await importOriginal<typeof import('@lib/api')>()+ return { ...actual, getLlmModel: vi.fn(), updateLlmModel: vi.fn() }+})++// Mirrors the Error shape lib/api.ts formatApiError produces: message plus the+// preserved structured `.status`/`.code`/`.body` the typed helpers read.+function structuredApiError(status: number, body: Record<string, unknown>): Error {+ const error = new Error(`${status} Conflict - ${String(body.error)}`)+ ;(error as Error & { status?: number }).status = status+ ;(error as Error & { code?: string }).code = String(body.error)+ ;(error as Error & { body?: unknown }).body = body+ return error+}++const model: LlmAllowedModel = {+ id: 'model-1',+ provider: 'claude',+ model: 'claude-haiku-4-5',+ vendor: 'Anthropic',+ display_name: 'Claude Haiku',+ context_window_tokens: null,+ enabled: true,+ source: 'discovery',+ stale: true,+ discovered_at: null,+ last_seen_at: null,+ created_at: '2026-01-01T00:00:00.000Z',+ updated_at: '2026-01-01T00:00:00.000Z',+}++function inUseError(): Error {+ return structuredApiError(409, {+ error: 'model_in_use',+ message: 'still referenced',+ impact: {+ provider: 'claude',+ model: 'claude-haiku-4-5',+ hostsAffected: [{ namespace: 'mcp-host', name: 'agent-a', roles: ['primary'] }],+ grantsAffected: [+ {+ id: 'g1',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'nightly-summary',+ capabilityFamily: 'promptBridge',+ },+ ],+ },+ })+}++describe('edit page disable impact gate (409 model_in_use → force)', () => {+ beforeEach(() => {+ mockPush.mockClear()+ mockShowToast.mockClear()+ vi.mocked(getLlmModel).mockResolvedValue(model)+ })++ afterEach(() => {+ cleanup()+ vi.clearAllMocks()+ })++ it('shows the impact and retries with ?force after the operator confirms', async () => {+ vi.mocked(updateLlmModel).mockRejectedValueOnce(inUseError()).mockResolvedValueOnce(model)++ render(<EditLlmModelPage />)++ fireEvent.click(await screen.findByRole('button', { name: SUBMIT_LABEL }))++ // Impact confirm: shows the stranded references before forcing the disable.+ expect(await screen.findByRole('button', { name: 'Disable anyway' })).toBeInTheDocument()+ expect(screen.getByText('mcp-host/agent-a')).toBeInTheDocument()+ expect(screen.getByText(/promptBridge/)).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'Disable anyway' }))++ await waitFor(() => {+ expect(vi.mocked(updateLlmModel)).toHaveBeenCalledTimes(2)+ })+ // First attempt without force, retry with { force: true }.+ expect(vi.mocked(updateLlmModel).mock.calls[0]).toEqual(['model-1', SUBMIT_INPUT, {}])+ expect(vi.mocked(updateLlmModel).mock.calls[1]).toEqual([+ 'model-1',+ SUBMIT_INPUT,+ { force: true },+ ])+ await waitFor(() => expect(mockPush).toHaveBeenCalled())+ })++ it('does not force when the operator cancels the impact confirm', async () => {+ vi.mocked(updateLlmModel).mockRejectedValueOnce(inUseError())++ render(<EditLlmModelPage />)++ fireEvent.click(await screen.findByRole('button', { name: SUBMIT_LABEL }))+ fireEvent.click(await screen.findByRole('button', { name: 'Cancel' }))++ await waitFor(() => {+ expect(screen.queryByRole('button', { name: 'Disable anyway' })).not.toBeInTheDocument()+ })+ expect(vi.mocked(updateLlmModel)).toHaveBeenCalledTimes(1)+ expect(mockPush).not.toHaveBeenCalled()+ })+})diff --git a/control-ui/components/__tests__/LlmModelsCatalogAttention.test.tsx b/control-ui/components/__tests__/LlmModelsCatalogAttention.test.tsxnew file mode 100644index 000000000..b9e268c09--- /dev/null+++ b/control-ui/components/__tests__/LlmModelsCatalogAttention.test.tsx@@ -0,0 +1,267 @@+import type { ReactNode } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import type { LlmAllowedModel } from '@lib/api'+import { deleteLlmModel, getAdminAttention, getLlmModels, getUnpricedModels } from '@lib/api'+import { LlmModelsSurface } from '../LlmModelsSurface'+import { ToastProvider } from '../Toast'++vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }))+vi.mock('@components/AuthContext', () => ({+ useAuth: () => ({ authState: { isLoggedIn: true, isLoading: false } }),+}))+vi.mock('@components/AuthGate', () => ({+ AuthGate: ({ children }: { children: ReactNode }) => <>{children}</>,+}))+vi.mock('@components/DashboardLayout', () => ({+ DashboardLayout: ({ children }: { children: ReactNode }) => <>{children}</>,+}))+vi.mock('@components/LlmDiscoveryPanel', () => ({+ LlmDiscoveryPanel: () => <div>Discovery</div>,+}))+// A trimmed catalog table that just exposes the per-row delete trigger so the+// 409 impact/force flow can be driven end to end through the real surface.+vi.mock('@components/LlmModelTable', () => ({+ LlmModelTable: ({+ items,+ onDelete,+ }: {+ items: LlmAllowedModel[]+ onDelete: (model: LlmAllowedModel) => void+ }) => (+ <div>+ Model catalog+ {items.map(model => (+ <button key={model.id} type="button" onClick={() => onDelete(model)}>+ Delete {model.model}+ </button>+ ))}+ </div>+ ),+}))+vi.mock('@lib/api', async importOriginal => {+ const actual = await importOriginal<typeof import('@lib/api')>()+ return {+ ...actual,+ getLlmModels: vi.fn(),+ getUnpricedModels: vi.fn(),+ getAdminAttention: vi.fn(),+ deleteLlmModel: vi.fn(),+ }+})++// Mirrors the Error shape lib/api.ts formatApiError produces: message plus the+// preserved structured `.status`/`.code`/`.body` the typed helpers read.+function structuredApiError(status: number, body: Record<string, unknown>): Error {+ const error = new Error(`${status} Conflict - ${String(body.error)}`)+ ;(error as Error & { status?: number }).status = status+ ;(error as Error & { code?: string }).code = String(body.error)+ ;(error as Error & { body?: unknown }).body = body+ return error+}++const model: LlmAllowedModel = {+ id: 'model-1',+ provider: 'claude',+ model: 'claude-haiku-4-5',+ vendor: 'Anthropic',+ display_name: 'Claude Haiku',+ context_window_tokens: null,+ enabled: true,+ source: 'discovery',+ stale: true,+ discovered_at: null,+ last_seen_at: null,+ created_at: '2026-01-01T00:00:00.000Z',+ updated_at: '2026-01-01T00:00:00.000Z',+}++function renderSurface() {+ return render(+ <ToastProvider>+ <LlmModelsSurface activeTab="catalog" />+ </ToastProvider>+ )+}++describe('catalog attention banner', () => {+ beforeEach(() => {+ vi.mocked(getLlmModels).mockResolvedValue({ rows: [model] })+ vi.mocked(getUnpricedModels).mockResolvedValue({ rows: [] })+ vi.mocked(deleteLlmModel).mockResolvedValue(undefined)+ })++ afterEach(() => {+ cleanup()+ vi.clearAllMocks()+ })++ it('lists stale-but-referenced items and ignores an unknown kind without crashing', async () => {+ vi.mocked(getAdminAttention).mockResolvedValue({+ items: [+ {+ kind: 'stale_model_referenced',+ provider: 'claude',+ model: 'claude-haiku-4-5',+ displayName: 'Claude Haiku',+ hostsAffected: [{ namespace: 'mcp-host', name: 'agent-a', roles: ['primary'] }],+ grantsAffected: [+ {+ id: 'g1',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'nightly-summary',+ capabilityFamily: 'promptBridge',+ },+ ],+ },+ // Unknown future kind: must be silently ignored, never throw.+ {+ kind: 'future_kind',+ provider: 'openai',+ model: 'gpt-5',+ hostsAffected: [],+ grantsAffected: [],+ },+ ],+ generatedAt: '2026-08-12T00:00:00.000Z',+ })++ renderSurface()++ expect(await screen.findByText('Claude Haiku')).toBeInTheDocument()+ expect(screen.getByText('mcp-host/agent-a')).toBeInTheDocument()+ expect(screen.getByText(/promptBridge/)).toBeInTheDocument()+ expect(screen.getByText('sandbox-recipes/nightly-summary')).toBeInTheDocument()+ // The unknown-kind item contributes nothing to the banner.+ expect(screen.queryByText('gpt-5')).not.toBeInTheDocument()+ })++ it('renders no banner for an empty feed', async () => {+ vi.mocked(getAdminAttention).mockResolvedValue({ items: [], generatedAt: 'x' })++ renderSurface()++ expect(await screen.findByText('Model catalog')).toBeInTheDocument()+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ })++ it('falls back to the model id when displayName is absent', async () => {+ vi.mocked(getAdminAttention).mockResolvedValue({+ items: [+ {+ kind: 'stale_model_referenced',+ provider: 'openai',+ model: 'gpt-5-mini',+ hostsAffected: [{ namespace: 'mcp-host', name: 'agent-b', roles: ['fallback'] }],+ grantsAffected: [],+ },+ ],+ generatedAt: 'x',+ })++ renderSurface()++ expect(await screen.findByText('gpt-5-mini')).toBeInTheDocument()+ })+})++describe('delete impact gate (409 model_in_use → force)', () => {+ beforeEach(() => {+ vi.mocked(getLlmModels).mockResolvedValue({ rows: [model] })+ vi.mocked(getUnpricedModels).mockResolvedValue({ rows: [] })+ vi.mocked(getAdminAttention).mockResolvedValue({ items: [], generatedAt: 'x' })+ })++ afterEach(() => {+ cleanup()+ vi.clearAllMocks()+ })++ it('shows the impact and retries with ?force after the operator confirms', async () => {+ vi.mocked(deleteLlmModel)+ .mockRejectedValueOnce(+ structuredApiError(409, {+ error: 'model_in_use',+ message: 'still referenced',+ impact: {+ provider: 'claude',+ model: 'claude-haiku-4-5',+ hostsAffected: [{ namespace: 'mcp-host', name: 'agent-a', roles: ['primary'] }],+ grantsAffected: [+ {+ id: 'g1',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'nightly-summary',+ capabilityFamily: 'promptBridge',+ },+ ],+ },+ })+ )+ .mockResolvedValueOnce(undefined)++ renderSurface()++ fireEvent.click(await screen.findByRole('button', { name: 'Delete claude-haiku-4-5' }))+ // First confirm: the ordinary delete prompt.+ fireEvent.click(await screen.findByRole('button', { name: 'Delete' }))++ // Impact confirm: shows the stranded references before forcing.+ expect(await screen.findByRole('button', { name: 'Remove anyway' })).toBeInTheDocument()+ expect(screen.getByText('mcp-host/agent-a')).toBeInTheDocument()+ expect(screen.getByText(/promptBridge/)).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'Remove anyway' }))++ await waitFor(() => {+ expect(vi.mocked(deleteLlmModel)).toHaveBeenCalledTimes(2)+ })+ // First attempt without force, retry with { force: true }.+ expect(vi.mocked(deleteLlmModel).mock.calls[0]).toEqual(['model-1', {}])+ expect(vi.mocked(deleteLlmModel).mock.calls[1]).toEqual(['model-1', { force: true }])+ })++ it('does not force when the operator cancels the impact confirm', async () => {+ vi.mocked(deleteLlmModel).mockRejectedValueOnce(+ structuredApiError(409, {+ error: 'model_in_use',+ message: 'still referenced',+ impact: {+ provider: 'claude',+ model: 'claude-haiku-4-5',+ hostsAffected: [{ namespace: 'mcp-host', name: 'agent-a', roles: ['primary'] }],+ grantsAffected: [],+ },+ })+ )++ renderSurface()++ fireEvent.click(await screen.findByRole('button', { name: 'Delete claude-haiku-4-5' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Delete' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Cancel' }))++ await waitFor(() => {+ expect(screen.queryByRole('button', { name: 'Remove anyway' })).not.toBeInTheDocument()+ })+ expect(vi.mocked(deleteLlmModel)).toHaveBeenCalledTimes(1)+ })++ // L1: the advisory banner must not keep showing an item the operator just+ // resolved in-session. A successful mutation bumps refreshSignal → re-fetch.+ it('re-fetches the attention feed after a successful delete', async () => {+ vi.mocked(deleteLlmModel).mockResolvedValue(undefined)++ renderSurface()++ await screen.findByText('Model catalog')+ // One fetch on mount, before any mutation.+ await waitFor(() => expect(vi.mocked(getAdminAttention)).toHaveBeenCalledTimes(1))++ fireEvent.click(screen.getByRole('button', { name: 'Delete claude-haiku-4-5' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Delete' }))++ // The successful delete triggers a second, on-demand fetch (no polling).+ await waitFor(() => expect(vi.mocked(getAdminAttention)).toHaveBeenCalledTimes(2))+ })+})diff --git a/control-ui/lib/__tests__/llmModelsApi.test.ts b/control-ui/lib/__tests__/llmModelsApi.test.tsindex 1bb1aaa2a..22ed12b20 100644--- a/control-ui/lib/__tests__/llmModelsApi.test.ts+++ b/control-ui/lib/__tests__/llmModelsApi.test.ts@@ -2,8 +2,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import {createLlmModel,deleteLlmModel,+ getAdminAttention,getLlmModel,getLlmModels,+ getModelInUseImpact,isLlmModelConfigMapDeferred,updateLlmModel,} from '../api'@@ -124,3 +126,123 @@ describe('llm allowed-models api helpers', () => {}})})++describe('disable/delete impact gate (?force)', () => {+ it('updateLlmModel appends ?force=true only when force is set', async () => {+ // Fresh Response per call — a single mocked body can only be read once.+ const fetchMock = vi+ .spyOn(globalThis, 'fetch')+ .mockImplementation(async () => jsonResponse(SAMPLE))++ await updateLlmModel(SAMPLE.id, { enabled: false }, { force: true })+ const [forcedUrl, forcedInit] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(forcedInit.method).toBe('PUT')+ expect(forcedUrl).toContain('force=true')++ await updateLlmModel(SAMPLE.id, { enabled: false })+ const [plainUrl] = fetchMock.mock.calls[1] as [string, RequestInit]+ expect(plainUrl).not.toContain('force')+ })++ it('deleteLlmModel appends ?force=true only when force is set', async () => {+ const fetchMock = vi+ .spyOn(globalThis, 'fetch')+ .mockImplementation(async () => new Response(null, { status: 204 }))++ await deleteLlmModel(SAMPLE.id, { force: true })+ const [forcedUrl, forcedInit] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(forcedInit.method).toBe('DELETE')+ expect(forcedUrl).toContain('force=true')++ await deleteLlmModel(SAMPLE.id)+ const [plainUrl] = fetchMock.mock.calls[1] as [string, RequestInit]+ expect(plainUrl).not.toContain('force')+ })++ it('getModelInUseImpact extracts the impact from a 409 model_in_use', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ jsonResponse(+ {+ error: 'model_in_use',+ message: 'still referenced',+ impact: {+ provider: 'claude',+ model: 'claude-haiku-4-5',+ hostsAffected: [{ namespace: 'mcp-host', name: 'agent-a', roles: ['primary'] }],+ grantsAffected: [+ {+ id: 'g1',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'nightly-summary',+ capabilityFamily: 'promptBridge',+ },+ ],+ },+ },+ 409+ )+ )+ try {+ await deleteLlmModel(SAMPLE.id)+ expect.unreachable('deleteLlmModel should reject on 409')+ } catch (err) {+ const impact = getModelInUseImpact(err)+ expect(impact).not.toBeNull()+ expect(impact?.hostsAffected).toEqual([+ { namespace: 'mcp-host', name: 'agent-a', roles: ['primary'] },+ ])+ expect(impact?.grantsAffected[0].capabilityFamily).toBe('promptBridge')+ }+ })++ it('getModelInUseImpact returns null for an unrelated 409', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ jsonResponse({ error: 'conflict', message: 'already exists' }, 409)+ )+ try {+ await deleteLlmModel(SAMPLE.id)+ expect.unreachable('deleteLlmModel should reject on 409')+ } catch (err) {+ expect(getModelInUseImpact(err)).toBeNull()+ }+ })+})++describe('getAdminAttention', () => {+ it('GETs the feed and normalizes items, keeping an unknown kind', async () => {+ const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ jsonResponse({+ items: [+ {+ kind: 'stale_model_referenced',+ provider: 'claude',+ model: 'claude-haiku-4-5',+ displayName: 'Claude Haiku',+ hostsAffected: [{ namespace: 'mcp-host', name: 'agent-a', roles: ['primary'] }],+ grantsAffected: [],+ },+ // A kind the current UI does not know: it must survive normalization+ // (the banner decides what to render) and never throw here.+ { kind: 'future_kind', provider: 'openai', model: 'gpt-5' },+ // Malformed item (no model) is dropped rather than tumbling the feed.+ { kind: 'stale_model_referenced', provider: 'openai' },+ ],+ generatedAt: '2026-08-12T00:00:00.000Z',+ })+ )+ const report = await getAdminAttention()+ const [url] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(url).toContain('/api/v1/admin/attention')+ expect(report.items).toHaveLength(2)+ expect(report.items[0].displayName).toBe('Claude Haiku')+ expect(report.items[0].hostsAffected[0].name).toBe('agent-a')+ expect(report.items[1].kind).toBe('future_kind')+ expect(report.generatedAt).toBe('2026-08-12T00:00:00.000Z')+ })++ it('returns an empty feed when items is missing/empty', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse({ generatedAt: 'x' }))+ const report = await getAdminAttention()+ expect(report.items).toEqual([])+ })+})diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex 664044b0e..8333d651a 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -1663,16 +1663,177 @@ export async function createLlmModel(input: CreateLlmModelInput) {return apiSend('POST', '/api/v1/admin/llm-models', input) as Promise<LlmAllowedModel>}-export async function updateLlmModel(id: string, input: UpdateLlmModelInput) {+// A disable (PUT enabled→false) or delete of a referenced model is gated by+// control-api (Fase 3): without `?force` it answers 409 `model_in_use` with the+// impact. Passing `{ force: true }` appends `?force=true`, which the operator+// confirms only after seeing that impact — never automatically.+export async function updateLlmModel(+ id: string,+ input: UpdateLlmModelInput,+ opts: { force?: boolean } = {}+) {return apiSend('PUT',`/api/v1/admin/llm-models/${encodeURIComponent(id)}`,- input+ input,+ opts.force ? { force: 'true' } : {}) as Promise<LlmAllowedModel>}-export async function deleteLlmModel(id: string) {- return apiSend('DELETE', `/api/v1/admin/llm-models/${encodeURIComponent(id)}`)+export async function deleteLlmModel(id: string, opts: { force?: boolean } = {}) {+ return apiSend(+ 'DELETE',+ `/api/v1/admin/llm-models/${encodeURIComponent(id)}`,+ undefined,+ opts.force ? { force: 'true' } : {}+ )+}++// ── Model references, 409 impact + operator attention feed ─────────────────+// See control-api/src/services/llmAttention.ts and llmModelImpact.ts. The 409+// `model_in_use` impact body (Fase 3) and each attention item (Fase 5, Pieza C)+// carry the SAME `hostsAffected`/`grantsAffected` shape, so both surfaces render+// the references identically.++/** A Host CR that references a (provider, model) pair, with the matched roles. */+export type ModelHostReference = {+ namespace: string+ name: string+ // 'primary' | 'allowedModels' | 'fallback' — kept as string[] so an unknown+ // role from a newer backend renders rather than being dropped.+ roles: string[]+}++/** A capability grant that references a (provider, model) pair. */+export type ModelGrantReference = {+ id: string+ recipeNamespace: string+ recipeName: string+ capabilityFamily: string+}++/** Live references to a (provider, model) pair, shared by both surfaces. */+export type ModelReferences = {+ hostsAffected: ModelHostReference[]+ grantsAffected: ModelGrantReference[]+}++/**+ * One actionable operator-attention item. `kind` is an OPEN string union — today+ * only `'stale_model_referenced'`; the banner switches on it and ignores kinds+ * it does not recognize. `displayName` is optional (omitted, not null).+ */+export type AdminAttentionItem = ModelReferences & {+ kind: string+ provider: string+ model: string+ displayName?: string+}++/** The `GET /admin/attention` response contract consumed by the banner. */+export type AdminAttentionReport = {+ items: AdminAttentionItem[]+ generatedAt: string+}++/** The 409 `model_in_use` impact body (Fase 3): the model plus its references. */+export type ModelInUseImpact = ModelReferences & {+ provider: string+ model: string+}++function coerceModelHostReferences(raw: unknown): ModelHostReference[] {+ if (!Array.isArray(raw)) return []+ return raw.flatMap(entry => {+ if (!entry || typeof entry !== 'object') return []+ const rec = entry as Record<string, unknown>+ if (typeof rec.namespace !== 'string' || typeof rec.name !== 'string') return []+ const roles = Array.isArray(rec.roles)+ ? rec.roles.filter((r): r is string => typeof r === 'string')+ : []+ return [{ namespace: rec.namespace, name: rec.name, roles }]+ })+}++function coerceModelGrantReferences(raw: unknown): ModelGrantReference[] {+ if (!Array.isArray(raw)) return []+ return raw.flatMap(entry => {+ if (!entry || typeof entry !== 'object') return []+ const rec = entry as Record<string, unknown>+ if (+ typeof rec.id !== 'string' ||+ typeof rec.recipeNamespace !== 'string' ||+ typeof rec.recipeName !== 'string' ||+ typeof rec.capabilityFamily !== 'string'+ ) {+ return []+ }+ return [+ {+ id: rec.id,+ recipeNamespace: rec.recipeNamespace,+ recipeName: rec.recipeName,+ capabilityFamily: rec.capabilityFamily,+ },+ ]+ })+}++// Keep every item whose (kind, provider, model) are strings — including unknown+// kinds, so the banner (not the fetch layer) decides what to render. Malformed+// items are dropped rather than tumbling the whole feed.+function coerceAttentionItem(raw: unknown): AdminAttentionItem[] {+ if (!raw || typeof raw !== 'object') return []+ const rec = raw as Record<string, unknown>+ if (+ typeof rec.kind !== 'string' ||+ typeof rec.provider !== 'string' ||+ typeof rec.model !== 'string'+ ) {+ return []+ }+ const item: AdminAttentionItem = {+ kind: rec.kind,+ provider: rec.provider,+ model: rec.model,+ hostsAffected: coerceModelHostReferences(rec.hostsAffected),+ grantsAffected: coerceModelGrantReferences(rec.grantsAffected),+ }+ if (typeof rec.displayName === 'string') item.displayName = rec.displayName+ return [item]+}++export async function getAdminAttention(): Promise<AdminAttentionReport> {+ const raw = (await apiGet('/api/v1/admin/attention')) as {+ items?: unknown+ generatedAt?: unknown+ }+ return {+ items: Array.isArray(raw.items) ? raw.items.flatMap(coerceAttentionItem) : [],+ generatedAt: typeof raw.generatedAt === 'string' ? raw.generatedAt : '',+ }+}++/**+ * When a disable (PUT enabled→false) or delete is rejected with 409+ * `model_in_use` — the model is still referenced and `?force` was not sent —+ * returns the impact so the caller can show it and offer a forced retry. Returns+ * null for any other error. Mirrors `getBudgetsUsingPrice`: reads the structured+ * `.body` `formatApiError` preserves.+ */+export function getModelInUseImpact(err: unknown): ModelInUseImpact | null {+ if ((err as { status?: number })?.status !== 409) return null+ const body = apiErrorBody(err)+ if (!body || body.error !== 'model_in_use') return null+ const impact = body.impact+ if (!impact || typeof impact !== 'object') return null+ const rec = impact as Record<string, unknown>+ return {+ provider: typeof rec.provider === 'string' ? rec.provider : '',+ model: typeof rec.model === 'string' ? rec.model : '',+ hostsAffected: coerceModelHostReferences(rec.hostsAffected),+ grantsAffected: coerceModelGrantReferences(rec.grantsAffected),+ }}// ── Catalog discovery (spec 09 §7, F2) ────────────────────────────────────diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 568daba9b..003f1ba51 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.404",+ "version": "0.1.405","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.404",+ "version": "0.1.405","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 16a2a9d7d..796d59291 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.404",+ "version": "0.1.405","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",