Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-ui): preserve connector links and shared context coverage
Miguelon Peluchonc469ee54a558
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex 7c6bd2cad..75251c497 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -8545,6 +8545,151 @@ textarea.cu-input {margin: 0;}+/* Read-only model configuration summary. It mirrors the editor's provider+ blocks so operators can understand the configured model surface without+ opening edit mode. */+.cu-llm-summary {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.cu-llm-summary__field {+ display: flex;+ min-width: 0;+ flex-direction: column;+ gap: 0.45rem;+}++.cu-llm-summary__label {+ color: var(--cu-text-soft);+ font-size: 0.75rem;+ font-weight: 600;+ letter-spacing: 0.035em;+ text-transform: uppercase;+}++.cu-llm-summary__value {+ display: flex;+ min-height: 2.6rem;+ align-items: center;+ gap: 0.5rem;+ padding: 0.65rem 0.85rem;+ border: 1px solid var(--cu-border-subtle);+ border-radius: var(--cu-radius-sm);+ background: var(--cu-bg-elevated);+ color: var(--cu-text);+ font-size: 0.9375rem;+}++.cu-llm-summary__models {+ display: flex;+ min-height: 2.6rem;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.4rem;+ padding: 0.55rem 0.65rem;+ border: 1px solid var(--cu-border-subtle);+ border-radius: var(--cu-radius-sm);+ background: var(--cu-bg-elevated);+}++.cu-llm-summary__model-chip {+ display: inline-flex;+ max-width: 100%;+ align-items: center;+ padding: 0.2rem 0.5rem;+ border: 1px solid rgba(var(--cu-focus-rgb), 0.45);+ border-radius: 6px;+ background: rgba(var(--cu-focus-rgb), 0.12);+ color: var(--cu-text);+ font-size: 0.75rem;+ overflow-wrap: anywhere;+}++.cu-llm-summary__all-models {+ color: var(--cu-text-muted);+ font-size: 0.8125rem;+}++.cu-llm-summary__fallback-list {+ display: flex;+ flex-direction: column;+ gap: var(--cu-space-3);+ margin: 0;+ padding: 0;+ list-style: none;+}++.cu-llm-summary__fallback {+ display: flex;+ flex-direction: column;+ gap: var(--cu-space-2);+ padding: var(--cu-space-3);+ border: 1px solid var(--cu-border-subtle);+ border-radius: var(--cu-radius-sm);+ background: var(--cu-surface);+}++.cu-llm-summary__fallback-head,+.cu-llm-summary__fallback-provider {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: var(--cu-space-2);+}++.cu-llm-summary__fallback-head {+ justify-content: space-between;+}++.cu-llm-summary__fallback-order {+ color: var(--cu-text-soft);+ font-size: 0.75rem;+ font-weight: 600;+ text-transform: uppercase;+}++.cu-llm-summary__credential-slot {+ color: var(--cu-text-soft);+ font-size: 0.75rem;+}++.cu-llm-summary__fallback-provider {+ color: var(--cu-text);+ font-size: 0.9375rem;+}++.cu-llm-summary__separator {+ color: var(--cu-text-soft);+}++.cu-llm-summary__fallback-allowed {+ display: flex;+ flex-direction: column;+ gap: 0.45rem;+}++.cu-llm-summary__empty {+ color: var(--cu-text-soft);+ font-size: 0.8125rem;+}++.cu-llm-secret-control {+ display: flex;+ align-items: center;+ gap: var(--cu-space-2);+}++.cu-llm-secret-control > .cu-input {+ min-width: 0;+ flex: 1;+}++.cu-llm-secret-control > .cu-btn--icon {+ flex: 0 0 auto;+}+.cu-delete-zone {margin-top: 1.5rem;padding-top: 1.25rem;diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsxindex fa562d57e..9671a052a 100644--- a/control-ui/app/hosts/[name]/page.tsx+++ b/control-ui/app/hosts/[name]/page.tsx@@ -13,10 +13,13 @@ import { HostAdvancedTab } from '../../../components/HostAdvancedTab'import type { HostGuardrails } from '../../../components/HostGuardrailsSection/types'import { HostIdentityTab } from '../../../components/HostIdentityTab'import { HostOverviewTab } from '../../../components/HostOverviewTab'+import { LlmProviderConfig } from '../../../components/LlmProviderConfig'+import { LlmProviderSummary } from '../../../components/LlmProviderSummary'import { LlmSecretUpdateModal } from '../../../components/LlmSecretUpdateModal'import { RowActionsMenu } from '../../../components/RowActionsMenu'import { IconRobot } from '../../../components/Sidebar/icons'import { IconCheck, IconMoreHorizontal, IconPencil, IconX } from '../../../components/icons'+import { SelectInput } from '../../../components/ui'import {apiSend,getHost,@@ -24,21 +27,24 @@ import {getMcpServers,updateContext,} from '../../../lib/api'-import type { ContextResource, ContextSpec } from '../../../lib/api'+import type { ContextResource, ContextSpec, HostSecretResource } from '../../../lib/api'import { buildContextUpdatePayload, contextMutationError } from '../../../lib/contextMutation'import { useLlmAllowedModels } from '../../../lib/hooks/useLlmAllowedModels'import { FIRST_PARTY_CHANNEL_WORKFLOW_CONTROL_SCOPES } from '../../../lib/hostWorkflowControl'import {type HostAllowedModel,+ LLM_EMPTY_TRIGGER_ERROR,type LlmPolicy,type LlmProvider,buildAllowedModelsSpec,getModelOptions,getProviderLabel,+ isProviderUsable,normalizeAllowedModels,normalizeLlmPolicy,normalizeProvider,resolveDefaultModel,+ validateLlmPolicy,} from '../../../lib/llm'import type { HostTab } from './types'@@ -174,6 +180,7 @@ export default function HostDetailsPage() {const [error, setError] = useState('')const [initialLoading, setInitialLoading] = useState(true)+ const [editingModel, setEditingModel] = useState(false)const [llmSecretModalOpen, setLlmSecretModalOpen] = useState(false)const [editingContext, setEditingContext] = useState(false)const [showDeleteAgentConfirm, setShowDeleteAgentConfirm] = useState(false)@@ -188,9 +195,14 @@ export default function HostDetailsPage() {// Model options are the operator allowlist (enabled only). The host's saved// model is always kept selectable even if it fell out of the allowlist// (preexisting resources are not interrupted — spec R3.7).- const { models: allowedCatalog } = useLlmAllowedModels()+ const {+ models: allowedCatalog,+ loading: modelsLoading,+ error: modelsError,+ } = useLlmAllowedModels()const [modelNameDraft, setModelNameDraft] = useState('')const [secretRefDraft, setSecretRefDraft] = useState('')+ const [availableLlmSecrets, setAvailableLlmSecrets] = useState<HostSecretResource[]>([])// Fallback policy (spec §3-R5). `undefined` = the Host has no llmPolicy.const [llmPolicyDraft, setLlmPolicyDraft] = useState<LlmPolicy | undefined>(undefined)// Per-host model allowlist subset (spec.allowedModels, Topic 3a). Empty = the@@ -250,18 +262,6 @@ export default function HostDetailsPage() {allowedCatalog)}, [allowedModelsDraft, allowedCatalog, providerDraft, llmPolicyDraft])- // The effective subset grouped by provider, for the read-only Overview summary.- // Empty = the host is unrestricted (offers the full global allowlist).- const allowedModelsSummary = useMemo(() => {- const byProvider = new Map<string, string[]>()- for (const entry of effectiveAllowedModelsSpec) {- const list = byProvider.get(entry.provider) ?? []- if (!list.includes(entry.model)) list.push(entry.model)- byProvider.set(entry.provider, list)- }- return Array.from(byProvider.entries()).map(([provider, models]) => ({ provider, models }))- }, [effectiveAllowedModelsSpec])-// 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@@ -417,11 +417,16 @@ export default function HostDetailsPage() {// the detail bundle. Feeds the fallback credentialSlot dropdown's extra// keys (e.g. `claude-api-key-fb1`, spec R4.5.6) without a second fetch.const keysMap: Record<string, string[]> = {}+ const secretOptions: HostSecretResource[] = []for (const item of secretsList || []) {const name = item.name.trim()- if (name) keysMap[name] = Array.isArray(item.keys) ? item.keys : []+ if (!name) continue+ const keys = Array.isArray(item.keys) ? item.keys : []+ keysMap[name] = keys+ secretOptions.push({ name, keys })}setSecretKeysByName(keysMap)+ setAvailableLlmSecrets(secretOptions)} catch (e) {if (!mountedRef.current) returnsetError(e instanceof Error ? e.message : 'Failed to load agent details')@@ -529,6 +534,22 @@ export default function HostDetailsPage() {[secretKeysByName, secretRefDraft])+ const llmSecretOptions = useMemo(() => {+ const options = availableLlmSecrets.map(secret => ({+ name: secret.name,+ keys: Array.isArray(secret.keys) ? secret.keys : [],+ }))+ if (secretRefDraft.trim() && !options.some(secret => secret.name === secretRefDraft.trim())) {+ options.unshift({ name: secretRefDraft.trim(), keys: currentSecretKeys })+ }+ return options+ }, [availableLlmSecrets, currentSecretKeys, secretRefDraft])++ const linkedSecretProviderMismatch =+ secretRefDraft.trim().length > 0 &&+ currentSecretKeys.length > 0 &&+ !isProviderUsable(providerDraft, key => currentSecretKeys.includes(key))+const connectorOptions = useMemo(() =>availableConnectorNames@@ -609,6 +630,137 @@ export default function HostDetailsPage() {}}+ async function saveSecretRef(nextSecretRef: string): Promise<void> {+ const normalizedSecretRef = nextSecretRef.trim()+ if (!normalizedSecretRef) throw new Error('Select an LLM Secret.')++ setBusy(true)+ setError('')+ try {+ const currentHost = await getHost(routeName)+ const nextSpec = {+ ...currentHost.spec,+ secretRef: normalizedSecretRef,+ }+ const formResourceVersion = formResourceVersionRef.current+ await apiSend('PUT', `/api/v1/admin/hosts/${encodeURIComponent(routeName)}`, {+ ...(formResourceVersion ? { metadata: { resourceVersion: formResourceVersion } } : {}),+ spec: nextSpec,+ })+ setSecretRefDraft(normalizedSecretRef)+ await loadData('none')+ showToast('LLM Secret link updated.', { tone: 'success' })+ } catch (e) {+ const status = (e as { status?: number } | null)?.status+ const code = (e as { code?: string } | null)?.code+ const message =+ status === 409 && code === 'conflict'+ ? 'This agent changed since you opened the form. Reload to see the latest, then re-apply your change.'+ : e instanceof Error+ ? e.message+ : 'Failed to change the linked LLM Secret'+ setError(message)+ throw new Error(message)+ } finally {+ setBusy(false)+ }+ }++ async function handleSecretRefChange(nextSecretRef: string): Promise<void> {+ if (nextSecretRef === secretRefDraft) return+ try {+ await saveSecretRef(nextSecretRef)+ } catch {+ // saveSecretRef surfaces the server error in the page banner. Keep the+ // controlled select on the previously saved value when the write fails.+ }+ }++ async function saveModelConfiguration(): Promise<boolean> {+ if (!modelNameDraft.trim()) {+ setError('Choose a current model before saving.')+ return false+ }+ if (llmPolicyDraft && allowedCatalog.length > 0) {+ const policyErrors = validateLlmPolicy(llmPolicyDraft, allowedCatalog)+ if (policyErrors.length > 0) {+ setError(policyErrors[0])+ return false+ }+ }+ if (+ llmPolicyDraft &&+ llmPolicyDraft.fallbacks.length > 0 &&+ Array.isArray(llmPolicyDraft.triggerOn) &&+ llmPolicyDraft.triggerOn.length === 0+ ) {+ setError(LLM_EMPTY_TRIGGER_ERROR)+ return false+ }+ if (+ secretRefDraft.trim() &&+ currentSecretKeys.length > 0 &&+ !isProviderUsable(providerDraft, key => currentSecretKeys.includes(key))+ ) {+ setError(+ `The linked LLM Secret does not contain a usable ${getProviderLabel(providerDraft)} credential. Update the linked credentials or choose another secret.`+ )+ return false+ }++ setBusy(true)+ setError('')+ try {+ const currentHost = await getHost(routeName)+ const nextSpec: Record<string, unknown> = {+ ...currentHost.spec,+ model: {+ provider: providerDraft,+ name: modelNameDraft.trim(),+ },+ }+ // These fields are owned by this editor. Delete them first so removing+ // the last fallback or clearing an allowlist is persisted as an actual+ // field removal under the facade's full-replace semantics.+ delete nextSpec.llmPolicy+ delete nextSpec.allowedModels+ if (llmPolicyDraft && llmPolicyDraft.fallbacks.length > 0) {+ nextSpec.llmPolicy = llmPolicyDraft+ }+ if (effectiveAllowedModelsSpec.length > 0) {+ nextSpec.allowedModels = effectiveAllowedModelsSpec+ }++ const formResourceVersion = formResourceVersionRef.current+ await apiSend('PUT', `/api/v1/admin/hosts/${encodeURIComponent(routeName)}`, {+ ...(formResourceVersion ? { metadata: { resourceVersion: formResourceVersion } } : {}),+ spec: nextSpec,+ })+ await loadData('model')+ setEditingModel(false)+ showToast('Model configuration saved.', { tone: 'success' })+ return true+ } catch (e) {+ const status = (e as { status?: number } | null)?.status+ const code = (e as { code?: string } | null)?.code+ if (status === 409 && code === 'conflict') {+ setError(+ "This agent changed since you opened the form (another edit, or the agent's own lifecycle state updated). Reload to see the latest, then re-apply your change."+ )+ } else {+ setError(e instanceof Error ? e.message : 'Failed to save model configuration')+ }+ return false+ } finally {+ setBusy(false)+ }+ }++ async function cancelModelEdit() {+ setEditingModel(false)+ await loadData('model')+ }+const persistApprovalTools = useCallback(async (tools: Record<string, boolean>) => {setBusy(true)@@ -768,69 +920,115 @@ export default function HostDetailsPage() {agent.</p><div className="cu-agent-detail-heading__actions">- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- onClick={() => setLlmSecretModalOpen(true)}- disabled={busy || !secretRefDraft.trim()}- >- Edit- </button>+ {!editingModel ? (+ <button+ type="button"+ className="cu-btn cu-btn--ghost cu-btn--sm"+ onClick={() => {+ setError('')+ setEditingModel(true)+ }}+ disabled={busy}+ >+ Edit+ </button>+ ) : null}</div></div><div className="cu-form-stack"><div className="cu-field"><label htmlFor="model-secret">LLM Secret</label>- <div id="model-secret" className="cu-field__readonly">- {secretRefDraft || '-'}- </div>- </div>- <div className="cu-field">- <label htmlFor="model-current">Current model</label>- <div id="model-current" className="cu-field__readonly">- {modelNameDraft || '-'}+ <div className="cu-llm-secret-control">+ <SelectInput+ id="model-secret"+ value={secretRefDraft}+ onChange={event => void handleSecretRefChange(event.target.value)}+ disabled={busy || llmSecretOptions.length === 0}+ >+ {llmSecretOptions.length === 0 ? (+ <option value="">No LLM Secret available</option>+ ) : (+ <>+ <option value="">Select an LLM Secret…</option>+ {llmSecretOptions.map(secret => (+ <option key={secret.name} value={secret.name}>+ {secret.name}+ </option>+ ))}+ </>+ )}+ </SelectInput>+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--toolbar"+ onClick={() => setLlmSecretModalOpen(true)}+ disabled={busy || !secretRefDraft.trim()}+ aria-label="Edit LLM Secret credentials"+ title="Edit LLM Secret credentials"+ >+ <IconPencil width={16} height={16} />+ </button></div>- </div>- <div className="cu-field">- <label htmlFor="model-provider">Model provider</label>- <div id="model-provider" className="cu-field__readonly">- {getProviderLabel(providerDraft)}- </div>- </div>- <div className="cu-field">- <label htmlFor="model-allowed">Allowed models</label>- {allowedModelsSummary.length > 0 ? (- <ul className="cu-llm-policy__summary">- {allowedModelsSummary.map(entry => (- <li key={entry.provider} className="cu-field__readonly">- {getProviderLabel(entry.provider)} · {entry.models.join(', ')}- </li>- ))}- </ul>- ) : (- <div id="model-allowed" className="cu-field__readonly">- All models — this agent offers every enabled model for its provider(s).+ <span className="cu-field__hint">+ Select the LLM Secret linked to this agent. Use the pencil to edit its stored+ credentials.+ </span>+ {linkedSecretProviderMismatch ? (+ <div className="cu-banner cu-banner--warning">+ The linked secret does not contain a usable {getProviderLabel(providerDraft)}{' '}+ credential. Choose another secret or edit its credentials before saving model+ configuration.</div>- )}+ ) : null}</div>- <div className="cu-field">- <label htmlFor="model-fallback">Fallback policy</label>- {llmPolicyDraft && llmPolicyDraft.fallbacks.length > 0 ? (- <ol className="cu-llm-policy__summary">- {llmPolicyDraft.fallbacks.map((entry, index) => (- <li key={index} className="cu-field__readonly">- {getProviderLabel(entry.provider)} · {entry.model || '-'}- {entry.credentialSlot ? ` · ${entry.credentialSlot}` : ''}- </li>- ))}- </ol>- ) : (- <div id="model-fallback" className="cu-field__readonly">- No fallback configured.+ {editingModel ? (+ <>+ <LlmProviderConfig+ provider={providerDraft}+ model={modelNameDraft}+ onPrimaryChange={next => {+ setProviderDraft(next.provider)+ setModelNameDraft(next.model)+ }}+ policy={llmPolicyDraft}+ onPolicyChange={setLlmPolicyDraft}+ allowedModels={allowedModelsDraft}+ onAllowedModelsChange={setAllowedModelsDraft}+ catalog={allowedCatalog}+ catalogLoading={modelsLoading}+ catalogError={modelsError}+ modelLabel="Current model"+ secretKeys={currentSecretKeys}+ disabled={busy}+ />+ <div className="cu-create-actions">+ <button+ type="button"+ className="cu-btn cu-btn--ghost cu-btn--sm"+ onClick={() => void cancelModelEdit()}+ disabled={busy}+ >+ Cancel model changes+ </button>+ <button+ type="button"+ className="cu-btn cu-btn--primary"+ onClick={() => void saveModelConfiguration()}+ disabled={busy}+ >+ {busy ? 'Saving…' : 'Save model configuration'}+ </button></div>- )}- </div>+ </>+ ) : (+ <LlmProviderSummary+ provider={providerDraft}+ model={modelNameDraft}+ allowedModels={effectiveAllowedModelsSpec}+ policy={llmPolicyDraft}+ />+ )}</div>{llmSecretModalOpen && secretRefDraft.trim() ? (diff --git a/control-ui/components/LlmProviderSummary/index.tsx b/control-ui/components/LlmProviderSummary/index.tsxnew file mode 100644index 000000000..f8d7c36a5--- /dev/null+++ b/control-ui/components/LlmProviderSummary/index.tsx@@ -0,0 +1,140 @@+import { LlmProviderIcon } from '@/components/LlmProviderIcon'+import {+ type HostAllowedModel,+ type LlmPolicy,+ type LlmProvider,+ allowedModelsForProvider,+ getProviderLabel,+} from '@/lib/llm'++export type LlmProviderSummaryProps = {+ provider: LlmProvider+ model: string+ allowedModels: HostAllowedModel[]+ policy?: LlmPolicy+}++function ModelChips({ models, allModelsLabel }: { models: string[]; allModelsLabel: string }) {+ return (+ <div+ className="cu-llm-summary__models"+ aria-label={models.length > 0 ? 'Allowed models' : allModelsLabel}+ >+ {models.length > 0 ? (+ models.map(model => (+ <span key={model} className="cu-llm-summary__model-chip">+ {model}+ </span>+ ))+ ) : (+ <span className="cu-llm-summary__all-models">{allModelsLabel}</span>+ )}+ </div>+ )+}++export function LlmProviderSummary({+ provider,+ model,+ allowedModels,+ policy,+}: LlmProviderSummaryProps) {+ const providerLabel = getProviderLabel(provider)+ const primaryAllowedModels = allowedModelsForProvider(allowedModels, provider)+ const fallbacks = policy?.fallbacks ?? []++ return (+ <div className="cu-llm-summary" role="region" aria-label="LLM configuration summary">+ <section className="cu-llm-config__block cu-llm-config__block--primary">+ <div className="cu-llm-config__block-head">+ <span className="cu-llm-config__block-title">Primary provider</span>+ <span className="cu-llm-config__block-tag">Required</span>+ </div>++ <div className="cu-llm-config__model-row">+ <div className="cu-llm-summary__field">+ <span className="cu-llm-summary__label">Provider</span>+ <div className="cu-llm-summary__value">+ <LlmProviderIcon provider={provider} label={providerLabel} />+ <span>{providerLabel}</span>+ </div>+ </div>++ <div className="cu-llm-summary__field">+ <span className="cu-llm-summary__label">Current model</span>+ <div className="cu-llm-summary__value">+ <LlmProviderIcon provider={provider} label={providerLabel} />+ <span>{model || 'No model configured'}</span>+ </div>+ </div>+ </div>++ <div className="cu-llm-summary__field">+ <span className="cu-llm-summary__label">Allowed models · {providerLabel}</span>+ <ModelChips models={primaryAllowedModels} allModelsLabel="All enabled models" />+ <span className="cu-field__hint">+ {primaryAllowedModels.length > 0+ ? `This agent offers only the ${primaryAllowedModels.length} selected ${providerLabel} model${primaryAllowedModels.length === 1 ? '' : 's'}; end users can pick from these per chat.`+ : `This agent offers every enabled ${providerLabel} model; end users can pick one per chat.`}+ </span>+ </div>+ </section>++ <section className="cu-llm-config__block" aria-labelledby="llm-summary-fallback-title">+ <div className="cu-llm-config__block-head">+ <span id="llm-summary-fallback-title" className="cu-llm-config__block-title">+ Fallback providers+ </span>+ <span className="cu-llm-config__block-tag cu-llm-config__block-tag--muted">Optional</span>+ </div>++ {fallbacks.length > 0 ? (+ <ol className="cu-llm-summary__fallback-list">+ {fallbacks.map((fallback, index) => {+ const fallbackLabel = getProviderLabel(fallback.provider)+ const fallbackAllowedModels = allowedModelsForProvider(+ allowedModels,+ fallback.provider+ )++ return (+ <li+ key={`${fallback.provider}-${fallback.model}-${index}`}+ className="cu-llm-summary__fallback"+ >+ <div className="cu-llm-summary__fallback-head">+ <span className="cu-llm-summary__fallback-order">Fallback #{index + 1}</span>+ {fallback.credentialSlot ? (+ <span className="cu-llm-summary__credential-slot">+ Credential slot: {fallback.credentialSlot}+ </span>+ ) : null}+ </div>+ <div className="cu-llm-summary__fallback-provider">+ <LlmProviderIcon provider={fallback.provider} label={fallbackLabel} />+ <strong>{fallbackLabel}</strong>+ <span className="cu-llm-summary__separator">·</span>+ <span>{fallback.model || 'No model configured'}</span>+ </div>+ {fallbackAllowedModels.length > 0 ? (+ <div className="cu-llm-summary__fallback-allowed">+ <span className="cu-llm-summary__label">+ Allowed models · {fallbackLabel}+ </span>+ <ModelChips+ models={fallbackAllowedModels}+ allModelsLabel="All enabled models"+ />+ </div>+ ) : null}+ </li>+ )+ })}+ </ol>+ ) : (+ <div className="cu-llm-summary__empty">No fallback configured.</div>+ )}+ </section>+ </div>+ )+}diff --git a/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx b/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsxindex e773431d0..14d45f4be 100644--- a/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx+++ b/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx@@ -87,7 +87,10 @@ function setupApiMocks(bundleHost: TestHost, refetchHost: TestHost = bundleHost);(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({host: bundleHost,contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],- secrets: [{ name: 'openai-secret', keys: ['openai-api-key'] }],+ secrets: [+ { name: 'openai-secret', keys: ['openai-api-key'] },+ { name: 'anthropic-secret', keys: ['claude-api-key'] },+ ],users: [],teams: [],agentUsers: [],@@ -245,7 +248,7 @@ describe('HostDetailsPage current model and credential flow', () => {const view = render(<HostDetailsPage />)navigateToTab(view, 'model')expect(await screen.findByText('Current model')).toBeInTheDocument()- fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ fireEvent.click(screen.getByRole('button', { name: 'Edit LLM Secret credentials' }))expect(screen.getByRole('dialog')).toBeInTheDocument()expect(screen.getByText('Update LLM secret openai-secret')).toBeInTheDocument()@@ -257,11 +260,51 @@ describe('HostDetailsPage current model and credential flow', () => {).toBe(false)})+ it('opens the model configuration editor separately from credential editing', async () => {+ const view = render(<HostDetailsPage />)+ navigateToTab(view, 'model')+ expect(await screen.findByText('Current model')).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))++ expect(screen.getByRole('region', { name: 'LLM configuration' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Save model configuration' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Update secret' })).not.toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'Save model configuration' }))++ await waitFor(() =>+ expect(api.apiSend).toHaveBeenCalledWith('PUT', '/api/v1/admin/hosts/foo', expect.any(Object))+ )+ const payload = findHostPutPayload() as { spec: Record<string, unknown> }+ expect(payload.spec.model).toEqual(baseSpec.model)+ expect(payload.spec.secretRef).toBe('openai-secret')+ expect(await screen.findByText('Model configuration saved.')).toBeInTheDocument()+ })++ it('changes the linked LLM Secret from the inline credentials dropdown', async () => {+ const view = render(<HostDetailsPage />)+ navigateToTab(view, 'model')+ await screen.findByText('Current model')++ fireEvent.change(screen.getByRole('combobox', { name: 'LLM Secret' }), {+ target: { value: 'anthropic-secret' },+ })++ await waitFor(() =>+ expect(api.apiSend).toHaveBeenCalledWith('PUT', '/api/v1/admin/hosts/foo', expect.any(Object))+ )+ const payload = findHostPutPayload() as { spec: Record<string, unknown> }+ expect(payload.spec.secretRef).toBe('anthropic-secret')+ expect(payload.spec.model).toEqual(baseSpec.model)+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ })+it('updates the linked Secret without writing Host model configuration', async () => {const view = render(<HostDetailsPage />)navigateToTab(view, 'model')await screen.findByText('Current model')- fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ fireEvent.click(screen.getByRole('button', { name: 'Edit LLM Secret credentials' }))fireEvent.click(screen.getByRole('button', { name: 'Replace OpenAI API key' }))fireEvent.change(screen.getByLabelText(/^OpenAI API key/i), {target: { value: 'sk-live' },diff --git a/control-ui/components/__tests__/HostDetailsPage.connectors.test.tsx b/control-ui/components/__tests__/HostDetailsPage.connectors.test.tsxindex 4e9d79dc4..2d75001fd 100644--- a/control-ui/components/__tests__/HostDetailsPage.connectors.test.tsx+++ b/control-ui/components/__tests__/HostDetailsPage.connectors.test.tsx@@ -10,14 +10,19 @@ import {} from '@testing-library/react'import HostDetailsPage from '../../app/hosts/[name]/page'import * as api from '../../lib/api'+import {+ buildContextResource,+ buildSharedContextScenario,+} from '../../test/fixtures/contextResource'import { ToastProvider } from '../Toast'const replaceMock = vi.fn()const pushMock = vi.fn()+let activeHostName = 'foo'vi.mock('next/navigation', () => ({- useParams: () => ({ name: 'foo', tab: 'connectors' }),- usePathname: () => '/agents/foo/connectors',+ useParams: () => ({ name: activeHostName, tab: 'connectors' }),+ usePathname: () => `/agents/${activeHostName}/connectors`,useRouter: () => ({ push: pushMock, replace: replaceMock }),useSearchParams: () => new URLSearchParams(),}))@@ -49,19 +54,19 @@ vi.mock('../../lib/api', () => ({}))const contextName = 'foo-12345'-const baseContext = {+const baseContext = buildContextResource({metadata: { name: contextName, resourceVersion: 'rv-context-1' },spec: {contextId: contextName,description: 'Connector context for agent foo',mcpServers: ['mcp-existing'],},-}+})function setupApiMocks() {;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({host: {- metadata: { name: 'foo', resourceVersion: 'rv-host-1' },+ metadata: { name: activeHostName, resourceVersion: 'rv-host-1' },spec: {contextRef: contextName,host: 'Foo',@@ -76,7 +81,7 @@ function setupApiMocks() {agentTeams: [],});(api.getHost as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- metadata: { name: 'foo' },+ metadata: { name: activeHostName },spec: {},});(api.getMcpServers as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({@@ -105,6 +110,7 @@ function renderPage() {afterEach(() => {cleanup()+ activeHostName = 'foo'})describe('HostDetailsPage connectors', () => {@@ -164,4 +170,91 @@ describe('HostDetailsPage connectors', () => {).toBeNull())})++ it('keeps connector membership shared for two Hosts backed by one producer Context (R1-H1)', async () => {+ const scenario = buildSharedContextScenario({+ contextName: 'shared-connectors',+ description: 'Shared connector context for two agents',+ mcpServers: ['mcp-existing'],+ hostNames: ['foo', 'bar'],+ })+ 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)+ ;(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: [],+ })+ )+ ;(api.getHost as unknown as ReturnType<typeof vi.fn>).mockImplementation(+ async (name: string) => ({ ...scenario.hosts[name as 'foo' | 'bar'] })+ )+ ;(api.updateContext as unknown as ReturnType<typeof vi.fn>).mockImplementation(+ async (+ _name: string,+ payload: { metadata: { resourceVersion: string }; spec: Record<string, unknown> }+ ) => {+ persistedContext = buildContextResource({+ metadata: {+ ...persistedContext.metadata,+ resourceVersion: 'rv-context-shared-2',+ },+ spec: {+ ...persistedContext.spec,+ ...payload.spec,+ contextId: persistedContext.spec.contextId,+ mcpServers: Array.isArray(payload.spec.mcpServers)+ ? payload.spec.mcpServers.map(String)+ : [],+ },+ })+ return persistedContext+ }+ )++ 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' }))+ fireEvent.click(+ within(screen.getByRole('dialog')).getByRole('button', { name: 'Add connector' })+ )+ await waitFor(() =>+ expect(api.updateContext).toHaveBeenCalledWith(+ 'shared-connectors',+ expect.objectContaining({+ metadata: { resourceVersion: 'rv-context-shared-1' },+ spec: expect.objectContaining({+ contextId: 'shared-connectors',+ mcpServers: ['mcp-existing', 'mcp-new'],+ }),+ })+ )+ )++ cleanup()+ activeHostName = 'bar'+ renderPage()++ // Regression assertion: a second Host referencing the same Context sees+ // the membership written through the first Host, without exposing the+ // implementation Context name in the Connectors UI.+ expect(await screen.findByText('mcp-new')).toBeInTheDocument()+ expect(screen.queryByText('shared-connectors')).not.toBeInTheDocument()+ expect(api.getHostDetailBundle).toHaveBeenLastCalledWith('bar')+ })})diff --git a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsxindex 6ef9f3fba..911cfc348 100644--- a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx+++ b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx@@ -132,29 +132,24 @@ describe('HostDetailsPage identity integration', () => {)})- it('shows the current model and opens the linked LLM Secret modal inline', async () => {+ it('shows the provider model configuration and opens the linked LLM Secret modal inline', async () => {mockParams = { name: 'foo', tab: 'model' }const { container } = render(<HostDetailsPage />)- expect(await screen.findByText('Allowed models')).toBeInTheDocument()+ const summary = await screen.findByRole('region', { name: 'LLM configuration summary' })+ expect(summary).toHaveTextContent('Primary provider')+ expect(summary).toHaveTextContent('OpenAI')+ expect(summary).toHaveTextContent('gpt-5.4')+ expect(summary).toHaveTextContent('Allowed models · OpenAI')+ expect(summary).toHaveTextContent('All enabled models')expect(screen.queryByText('Model name')).not.toBeInTheDocument()expect(screen.getByText('LLM Secret')).toBeInTheDocument()- expect(- Array.from(container.querySelectorAll('.cu-form-stack > .cu-field label')).map(label =>- label.textContent?.trim()- )- ).toEqual([- 'LLM Secret',- 'Current model',- 'Model provider',- 'Allowed models',- 'Fallback policy',- ])+ expect(container.querySelectorAll('.cu-llm-summary__value')).toHaveLength(2)expect(container.querySelector('.cu-agent-detail-card')).toBeNull()expect(container.querySelector('.cu-agent-detail-heading')).not.toBeNull()expect(container.querySelector('.cu-agent-detail-toolbar')).toBeNull()- fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ fireEvent.click(screen.getByRole('button', { name: 'Edit LLM Secret credentials' }))expect(screen.getByRole('dialog')).toBeInTheDocument()expect(screen.getByText('Update LLM secret openai-secret')).toBeInTheDocument()@@ -168,7 +163,7 @@ describe('HostDetailsPage identity integration', () => {mockParams = { name: 'foo', tab: 'model' }render(<HostDetailsPage />)- fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Edit LLM Secret credentials' }))expect(screen.getByText('Update LLM secret openai-secret')).toBeInTheDocument()expect(screen.queryByRole('link', { name: 'Manage LLM Secrets' })).toBeNull()diff --git a/control-ui/components/__tests__/HostWizard.test.tsx b/control-ui/components/__tests__/HostWizard.test.tsxindex 9aec09900..453f52408 100644--- a/control-ui/components/__tests__/HostWizard.test.tsx+++ b/control-ui/components/__tests__/HostWizard.test.tsx@@ -2,6 +2,10 @@ 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 {+ buildHostReferencesForContext,+ materializeContextResource,+} from '../../test/fixtures/contextResource'import { buildSecretSummary } from '../../test/fixtures/secretSummary'import { HostWizard } from '../HostWizard'import { ToastProvider } from '../Toast'@@ -366,13 +370,24 @@ describe('HostWizard — connector selection and automatic context creation', ()const hostCall = vi.mocked(api.apiSend).mock.calls.find(call => call[0] === 'POST' && call[1] === '/api/v1/admin/hosts')- const contextPayload = contextCall![2] as {- metadata: { name: string }- spec: { mcpServers: string[] }- }+ const contextPayload = contextCall![2] as Parameters<typeof materializeContextResource>[0]const hostPayload = hostCall![2] as { spec: { contextRef: string } }+ const persistedContext = materializeContextResource(contextPayload)- expect(contextPayload.spec.mcpServers).toEqual(['mcp-a'])+ expect(persistedContext).toMatchObject({+ metadata: {+ name: contextPayload.metadata.name,+ namespace: 'mcp-server',+ resourceVersion: 'rv-context-read',+ },+ spec: {+ contextId: contextPayload.metadata.name,+ description: 'Connector context for agent connector-agent',+ mcpServers: ['mcp-a'],+ sharedFileSystems: [],+ },+ status: { sharedFileSystems: [] },+ })expect(hostPayload.spec.contextRef).toBe(contextPayload.metadata.name)})@@ -396,12 +411,11 @@ describe('HostWizard — connector selection and automatic context creation', ()const contextCall = vi.mocked(api.apiSend).mock.calls.find(call => call[0] === 'POST' && call[1] === '/api/v1/admin/contexts')- const contextPayload = contextCall![2] as {- metadata: { name: string }- spec: { contextId: string; mcpServers: string[] }- }- expect(contextPayload.spec.contextId).toBe(contextPayload.metadata.name)- expect(contextPayload.spec.mcpServers).toEqual([])+ const contextPayload = contextCall![2] as Parameters<typeof materializeContextResource>[0]+ const persistedContext = materializeContextResource(contextPayload)+ expect(persistedContext.spec.contextId).toBe(persistedContext.metadata.name)+ expect(persistedContext.spec.mcpServers).toEqual([])+ expect(persistedContext.spec.sharedFileSystems).toEqual([])const hostCall = vi.mocked(api.apiSend)@@ -410,6 +424,44 @@ describe('HostWizard — connector selection and automatic context creation', ()contextPayload.metadata.name)})++ it('creates a producer-shaped Context that can be referenced by two Hosts (R1-H1)', async () => {+ // Previous-head reproduction (43e0d17cc): the test only inspected a+ // hand-cast POST body. Materializing the real producer response here keeps+ // the generated Context contract explicit before checking shared references.+ await renderWizard()+ await walkToAccessStep({ agentName: 'shared-context-agent' })+ continueToConnectorsStep()+ fireEvent.click(screen.getByRole('checkbox', { name: /mcp-a/i }))+ submitFromConnectorsStep()++ await waitFor(() =>+ expect(api.apiSend).toHaveBeenCalledWith('POST', '/api/v1/admin/hosts', expect.any(Object))+ )+ const contextCall = vi+ .mocked(api.apiSend)+ .mock.calls.find(call => call[0] === 'POST' && call[1] === '/api/v1/admin/contexts')+ const hostCall = vi+ .mocked(api.apiSend)+ .mock.calls.find(call => call[0] === 'POST' && call[1] === '/api/v1/admin/hosts')+ expect(contextCall).toBeDefined()+ expect(hostCall).toBeDefined()++ 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',+ ])++ 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])+ )+ })})describe("HostWizard — 'Access' empty state", () => {diff --git a/control-ui/lib/__tests__/routeResolution.test.ts b/control-ui/lib/__tests__/routeResolution.test.tsindex 253866c05..f65ed0658 100644--- a/control-ui/lib/__tests__/routeResolution.test.ts+++ b/control-ui/lib/__tests__/routeResolution.test.ts@@ -28,7 +28,22 @@ function applyRule(pathname: string, rule: RouteRule): string | null {return rule.destination.replace(':path*', rest).replace(/\/$/, '') || '/'}- return pathname === rule.source ? rule.destination : null+ const sourceParts = rule.source.split('/')+ const pathnameParts = pathname.split('/')+ if (sourceParts.length !== pathnameParts.length) return null++ const params: Record<string, string> = {}+ for (let index = 0; index < sourceParts.length; index += 1) {+ const sourcePart = sourceParts[index]+ const pathnamePart = pathnameParts[index]+ if (sourcePart.startsWith(':')) {+ params[sourcePart.slice(1)] = pathnamePart+ } else if (sourcePart !== pathnamePart) {+ return null+ }+ }++ return rule.destination.replace(/:([^/]+)/g, (match, name: string) => params[name] ?? match)}function appRoutePatterns(): RegExp[] {@@ -150,6 +165,11 @@ describe('CONTROL_ROUTES App Router resolution', () => {destination: '/agents/:name/advanced',permanent: true,},+ {+ source: '/agents/:name/contexts',+ destination: '/agents/:name/connectors',+ permanent: true,+ },]))})@@ -158,11 +178,33 @@ describe('CONTROL_ROUTES App Router resolution', () => {const redirects = ((await nextConfig.redirects?.()) ?? []) as RouteRule[]const rewrites = ((await nextConfig.rewrites?.()) ?? []) as RouteRule[]const appRoutes = appRoutePatterns()- const legacySlugs = ['member-access', 'team-access', 'approvals', 'env-vars']+ const legacySlugs = ['member-access', 'team-access', 'approvals', 'env-vars', 'contexts']for (const slug of legacySlugs) {const pathname = `/agents/foo/${slug}`expect(resolvesToAppRoute(pathname, redirects, rewrites, appRoutes)).toBe(true)}})++ it('redirects the legacy agent Contexts deep link to the Connectors experience', async () => {+ const redirects = ((await nextConfig.redirects?.()) ?? []) as RouteRule[]+ const rewrites = ((await nextConfig.rewrites?.()) ?? []) as RouteRule[]+ const appRoutes = appRoutePatterns()++ // Direct-route regression: before this compatibility rule, the /agents+ // rewrite reached hosts/[name]/[tab] with tab="contexts", which called+ // notFound() because the renamed tab only accepted "connectors".+ expect(resolvesToAppRoute('/agents/demo-agent/contexts', redirects, rewrites, appRoutes)).toBe(+ true+ )+ expect(redirects).toEqual(+ expect.arrayContaining([+ {+ source: '/agents/:name/contexts',+ destination: '/agents/:name/connectors',+ permanent: true,+ },+ ])+ )+ })})diff --git a/control-ui/next.config.js b/control-ui/next.config.jsindex 8be20d4e7..cd656fe70 100644--- a/control-ui/next.config.js+++ b/control-ui/next.config.js@@ -125,6 +125,14 @@ const nextConfig = {{ source: '/agents/:name/team-access', destination: '/agents/:name/access', permanent: true },{ source: '/agents/:name/approvals', destination: '/agents/:name/advanced', permanent: true },{ source: '/agents/:name/env-vars', destination: '/agents/:name/advanced', permanent: true },+ // The agent-scoped Contexts tab was renamed to Connectors. Keep old+ // bookmarks and shared links working before the /agents -> /hosts+ // rewrite reaches the physical tab route.+ {+ source: '/agents/:name/contexts',+ destination: '/agents/:name/connectors',+ permanent: true,+ },{ source: '/marketplace', destination: '/marketplace/connectors', permanent: true },{ source: '/cost-and-usage', destination: '/cost-and-usage/usage', permanent: true },{diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 4ac83d4a1..accdf57c0 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.450",+ "version": "0.1.451","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.450",+ "version": "0.1.451","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 5fef329e3..1efd79c00 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.450",+ "version": "0.1.451","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.tsindex d8886a0dd..26caa9aad 100644--- a/control-ui/test/fixtures/contextResource.ts+++ b/control-ui/test/fixtures/contextResource.ts@@ -19,6 +19,16 @@ export type ProducerContextResource = {}}+/** The create payload emitted by HostWizard before Kubernetes adds metadata/status. */+export type ProducerContextCreatePayload = {+ metadata: { name: string }+ spec: {+ contextId: string+ description: string+ mcpServers: string[]+ }+}+export type ContextResourceOverrides = {metadata?: Partial<ProducerContextResource['metadata']>spec?: Partial<ProducerContextResource['spec']>@@ -53,3 +63,75 @@ export function buildContextResource(export function buildContextList(items: readonly ProducerContextResource[] = []) {return { items: [...items] }}++/**+ * Materialize the persisted Context shape from the exact HostWizard POST body.+ * This keeps UI tests anchored to the producer's request/response boundary:+ * the wizard supplies the spec, while Kubernetes supplies namespace, version,+ * and status fields.+ */+export function materializeContextResource(+ payload: ProducerContextCreatePayload,+ overrides: ContextResourceOverrides = {}+): ProducerContextResource {+ return buildContextResource({+ metadata: {+ name: payload.metadata.name,+ ...overrides.metadata,+ },+ spec: {+ contextId: payload.spec.contextId,+ description: payload.spec.description,+ mcpServers: [...payload.spec.mcpServers],+ ...overrides.spec,+ },+ status: overrides.status,+ })+}++export function buildHostReferencesForContext(+ contextName: string,+ hostNames: readonly string[] = ['foo', 'bar']+) {+ return Object.fromEntries(+ hostNames.map(name => [+ name,+ {+ metadata: { name, namespace: 'mcp-host', resourceVersion: `rv-host-${name}` },+ spec: { host: name, contextRef: contextName },+ },+ ])+ )+}++/**+ * Build the producer-shaped resources needed to exercise a shared Context.+ * Multiple Hosts intentionally carry the same `spec.contextRef`; connector+ * membership belongs to that Context, not to either Host.+ */+export function buildSharedContextScenario(+ input: {+ contextName?: string+ description?: string+ mcpServers?: readonly string[]+ hostNames?: readonly string[]+ } = {}+) {+ 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 hostNames = input.hostNames ?? ['foo', 'bar']+ const hosts = buildHostReferencesForContext(contextName, hostNames)++ return { context, hosts }+}