Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
Merge origin/dev into feat/codex-subscription-multi-connection
Alfredo Lopez0389ea7d61c1
diff --cc control-api/package-lock.jsonindex 6f783af21,7c4508c9e..ceccfd02a--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-control-api",- "version": "0.1.507",- "version": "0.1.498",++ "version": "0.1.508","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.507",- "version": "0.1.498",++ "version": "0.1.508","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/image-policy": "file:../packages/image-policy",diff --cc control-api/package.jsonindex 2f4609c3a,994945d9e..6bc362f53--- a/control-api/package.json+++ b/control-api/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-control-api",- "version": "0.1.507",- "version": "0.1.498",++ "version": "0.1.508","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --cc control-api/test/workflows.shared.rateLimit.test.tsindex df31632b9,47a55851e..d7e59ac03--- a/control-api/test/workflows.shared.rateLimit.test.ts+++ b/control-api/test/workflows.shared.rateLimit.test.ts@@@ -7,8 -5,8 +7,10 @@@ importadminOutputsReadRateLimits,adminWorkflowRateLimitCredential,adminWorkflowTriggerRateLimit,+ codexOAuthCallbackRateLimits,+ llmProviderAttemptAuthorizeRateLimits,+ mcpHostWorkflowTriggerRateLimit,+ mcpHostWorkflowTriggerRateLimitCredential,shouldSkipWorkflowGrantEdgeRateLimit,verifiedAdminRateLimitSubject,workflowAdminReadRateLimits,diff --cc control-ui/app/hosts/[name]/page.tsxindex 3c021a0ac,b3b1c29b8..a562ad1b8--- a/control-ui/app/hosts/[name]/page.tsx+++ b/control-ui/app/hosts/[name]/page.tsx@@@ -11,16 -12,23 +12,29 @@@ import { HostAccessTab } from '../../..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 { LlmSecretSelect } from '../../../components/LlmSecretSelect'+ import { LlmSecretUpdateModal } from '../../../components/LlmSecretUpdateModal'+ import { RowActionsMenu } from '../../../components/RowActionsMenu'import { IconRobot } from '../../../components/Sidebar/icons'- import { IconCheck, IconPencil, IconX } from '../../../components/icons'- import { apiSend, getHost, getHostDetailBundle } from '../../../lib/api'+ import { IconCheck, IconMoreHorizontal, IconPencil, IconX } from '../../../components/icons'+ import {+ apiSend,+ getHost,+ getHostDetailBundle,+ getMcpServers,+ updateContext,+ } from '../../../lib/api'+ import type { ContextResource, ContextSpec, HostSecretResource } from '../../../lib/api'+import {+ CODEX_UNASSIGNED_CONNECTION_KEY,+ type CodexSubscriptionConnectionView,+ listCodexConnectionModels,+ listCodexSubscriptionConnections,+} from '../../../lib/codexSubscription'+ import { buildContextUpdatePayload, contextMutationError } from '../../../lib/contextMutation'import { useLlmAllowedModels } from '../../../lib/hooks/useLlmAllowedModels'import { FIRST_PARTY_CHANNEL_WORKFLOW_CONTROL_SCOPES } from '../../../lib/hostWorkflowControl'import {@@@ -29,24 -37,16 +43,22 @@@type LlmPolicy,type LlmProvider,buildAllowedModelsSpec,+ constrainModelOptions,- getActiveCredentialKeys,getModelOptions,getProviderLabel,+ getProvidersWithCompleteCredentials,+ hostModelNameError,isProviderUsable,+ llmChainRequiresSecret,normalizeAllowedModels,normalizeLlmPolicy,normalizeProvider,+ offeredCodexModelNames,- projectCredentialDraft,+ resolveCodexGrantModel,resolveDefaultModel,validateLlmPolicy,- validateLlmSecretData,} from '../../../lib/llm'+import { credentialSelectValue, parseCredentialSelect } from '../../../lib/llmCredentialSelect'import type { HostTab } from './types'const TAB_LABELS: Record<HostTab, string> = {@@@ -142,32 -202,14 +214,37 @@@ export default function HostDetailsPageerror: modelsError,} = useLlmAllowedModels()const [modelNameDraft, setModelNameDraft] = useState('')+ const [connectionRefDraft, setConnectionRefDraft] = useState(CODEX_UNASSIGNED_CONNECTION_KEY)+ const [codexModels, setCodexModels] = useState<string[]>([])+ const [codexConnections, setCodexConnections] = useState<CodexSubscriptionConnectionView[]>([])+ const [grantCatalogError, setGrantCatalogError] = useState('')+ const catalogForEditor = useMemo(() => {+ if (providerDraft !== 'codex-subscription') return allowedCatalog+ const others = allowedCatalog.filter(row => row.provider !== 'codex-subscription')+ if (codexModels.length === 0) return others+ return [+ ...others,+ ...codexModels.map(model => ({+ id: `codex:${model}`,- provider: 'codex-subscription',++ provider: 'codex-subscription' as const,+ model,+ vendor: 'OpenAI',+ display_name: model,+ context_window_tokens: null,+ enabled: true,+ source: 'discovery' as const,+ stale: false,+ })),+ ]+ }, [allowedCatalog, providerDraft, codexModels])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)+ // 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[]>([])@@@ -193,12 -247,9 +282,9 @@@const [lifecycleReason, setLifecycleReason] = useState('')const [statelessRejectionMessage, setStatelessRejectionMessage] = useState('')- const [availableContexts, setAvailableContexts] = useState<string[]>([])- const [availableSecrets, setAvailableSecrets] = useState<string[]>([])-const providerModelOptions = useMemo(- () => getModelOptions(allowedCatalog, providerDraft),- [allowedCatalog, providerDraft]+ () => getModelOptions(catalogForEditor, providerDraft),+ [catalogForEditor, providerDraft])// The EFFECTIVE per-host subset to persist (Topic 3a): the raw draft pruned to// the providers actually in this host's domain (primary + fallbacks — so a@@@ -249,50 -287,7 +334,58 @@@if (modelNameDraft === '' && providerModelOptions.length > 0) {setModelNameDraft(resolveDefaultModel(providerDraft, providerModelOptions))}- }, [allowedModelsDraft, catalogForEditor, modelNameDraft, providerDraft, providerModelOptions])- }, [modelNameDraft, providerDraft, providerModelOptions])++ }, [++ allowedModelsDraft,++ catalogForEditor,++ codexConnections,++ connectionRefDraft,++ modelNameDraft,++ providerDraft,++ providerModelOptions,++ ])++ useEffect(() => {+ let cancelled = false+ void listCodexSubscriptionConnections()+ .then(rows => {+ if (!cancelled) setCodexConnections(rows)+ })+ .catch(err => {+ if (!cancelled) {+ setCodexConnections([])+ setError(err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions')+ }+ })+ return () => {+ cancelled = true+ }+ }, [])++ useEffect(() => {+ if (!connectionRefDraft.trim() || connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY) {+ setCodexModels([])+ setGrantCatalogError('')+ return+ }+ let cancelled = false+ setGrantCatalogError('')+ void listCodexConnectionModels(connectionRefDraft)+ .then(models => {+ if (cancelled) return+ setCodexModels(offeredCodexModelNames(models))+ })+ .catch(err => {+ if (cancelled) return+ setCodexModels([])+ setModelNameDraft('')+ setGrantCatalogError(+ err instanceof Error ? err.message : 'Could not load ChatGPT grant models'+ )+ })+ return () => {+ cancelled = true+ }+ }, [connectionRefDraft])useEffect(() => {setActiveTab(parseHostTab(params.tab))@@@ -356,13 -402,8 +500,13 @@@currentModel ||resolveDefaultModel(nextProvider, getModelOptions(allowedCatalog, nextProvider)))+ setSecretRefDraft(String(spec.secretRef || ''))+ setConnectionRefDraft(+ String(+ (spec.model as { connectionRef?: string } | undefined)?.connectionRef || ''+ ).trim() || CODEX_UNASSIGNED_CONNECTION_KEY+ )- 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))@@@ -584,38 -663,57 +766,104 @@@}}- // Scoped save for the "Model & credentials" tab. Owns provider/model,- // secretRef, the opt-in fallback policy, the per-host model allowlist, and- // write-only credential rotations/retirements. All other spec fields- // (identity, context, channels, lifecycle) are preserved via the- // `...currentHost.spec` spread (full-replace semantics).- async function saveModelAndCredentials(): Promise<boolean> {+ 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.+ }+ }+++ function handleCredentialChange(value: string) {++ const parsed = parseCredentialSelect(value)++ if (parsed.kind === 'empty') {++ setSecretRefDraft('')++ setConnectionRefDraft(CODEX_UNASSIGNED_CONNECTION_KEY)++ setCodexModels([])++ setGrantCatalogError('')++ return++ }++ if (parsed.kind === 'subscription') {++ setSecretRefDraft('')++ setConnectionRefDraft(parsed.connectionKey)++ setProviderDraft('codex-subscription')++ setModelNameDraft('')++ return++ }++ setSecretRefDraft(parsed.name)++ setConnectionRefDraft(CODEX_UNASSIGNED_CONNECTION_KEY)++ setCodexModels([])++ setGrantCatalogError('')++ if (providerDraft === 'codex-subscription') {++ setProviderDraft('openai')++ setModelNameDraft(resolveDefaultModel('openai', getModelOptions(allowedCatalog, 'openai')))++ }++ }+++ async function saveModelConfiguration(): Promise<boolean> {+ const modelNameProblem = hostModelNameError(modelNameDraft)+ if (modelNameProblem) {+ setError(modelNameProblem)+ return false+ }+ if (providerDraft === 'codex-subscription') {+ if (!connectionRefDraft.trim() || connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY) {+ setError('Choose a ChatGPT subscription before saving.')+ return false+ }+ if (grantCatalogError) {+ setError(grantCatalogError)+ return false+ }+ if (!codexModels.includes(modelNameDraft.trim())) {+ setError(+ 'This subscription has no offered models yet. Sign in and sync the catalog before assigning agents.'+ )+ return false+ }+ }- // Client-side mirror of control-api's write gate (spec R5.3): block a save- // with an out-of-allowlist fallback model before the round-trip. Skip the- // check when the allowlist failed to load (`allowedCatalog` empty) — every- // model would falsely flag as "not enabled"; the backend 422 stays the- // source of truth for that case (matching how spec.model has no client gate).+ 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) {@@@ -640,47 -730,14 +880,20 @@@setError(LLM_EMPTY_TRIGGER_ERROR)return false}-- // Asymmetric usable gate (spec Topic 1b): block save when the PRIMARY- // provider isn't usable. "Usable" counts both a stored key (existingKeys)- // and a freshly typed rotation, so switching to a provider whose key is- // already stored stays allowed. Enforced only when we have real key signal —- // the Secret listed at least one key OR the operator typed a rotation. An- // empty/unlisted key set is treated as unknown (the backend stays the source- // of truth), so the save is never blocked by stale listing.+ const chainRequiresSecret = llmChainRequiresSecret(providerDraft, llmPolicyDraft?.fallbacks)+ if (chainRequiresSecret && !secretRefDraft.trim()) {+ setError('Select an LLM secret for the static-credentials provider in this chain.')+ return false+ }- const primaryPresent = (dataKey: string): boolean =>- (llmKeyDraft[dataKey] ?? '').trim().length > 0 || currentSecretKeys.includes(dataKey)- const typedAnyCredential = Object.values(llmKeyDraft).some(value => value.trim().length > 0)if (+ chainRequiresSecret &&secretRefDraft.trim() &&- (currentSecretKeys.length > 0 || typedAnyCredential) &&- !isProviderUsable(providerDraft, primaryPresent)+ currentSecretKeys.length > 0 &&+ !isProviderUsable(providerDraft, key => currentSecretKeys.includes(key))) {- setError(`Add the ${getProviderLabel(providerDraft)} credential for the primary model.`)- return false- }-- // Write-only credential rotations + slot retirement (merge PUT, never a- // full replace — a full replace of this shared Secret would drop fallback- // keys the operator didn't re-type). The draft is PROJECTED onto the active- // domain first, so a value typed for a since-unmounted provider (primary- // switched, or a fallback removed) is neither validated nor written — no- // stale block, no orphan key. Then validate cross-slot shape up front.- const activeCredentialKeys = getActiveCredentialKeys(providerDraft, llmPolicyDraft)- const rotatedData = projectCredentialDraft(llmKeyDraft, activeCredentialKeys)- const removeKeys = retireCandidates.filter(key => !(key in rotatedData))- // Cross-slot shape check on the rotated keys only. Note: rotating one half of- // the Bedrock pair fails this (both must be written together) — matching the- // server contract; the operator re-enters both to rotate either.- const credentialSlotErrors = validateLlmSecretData(rotatedData)- if (credentialSlotErrors.length > 0) {- setError(credentialSlotErrors[0])+ setError(+ `The linked LLM Secret does not contain a usable ${getProviderLabel(providerDraft)} credential. Update the linked credentials or choose another secret.`+ )return false}@@@ -694,37 -750,18 +906,28 @@@model: {provider: providerDraft,name: modelNameDraft.trim(),+ ...(providerDraft === 'codex-subscription'+ ? {+ connectionRef: connectionRefDraft.trim() || CODEX_UNASSIGNED_CONNECTION_KEY,+ }+ : {}),},}- // Host identity is metadata.name / the route slug. Never persist- // hostRef/userId as execution authority on this write.- delete nextSpec.hostRef- delete nextSpec.userId+ // 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 (chainRequiresSecret) {+ nextSpec.secretRef = secretRefDraft.trim()+ } else {+ delete nextSpec.secretRef+ }- // Opt-in fallback policy: set it when configured, otherwise drop it so a- // Host with no policy stays exactly as today (full-replace semantics).if (llmPolicyDraft && llmPolicyDraft.fallbacks.length > 0) {nextSpec.llmPolicy = llmPolicyDraft- } else {- delete nextSpec.llmPolicy}- // Per-host model allowlist subset (Topic 3a): emit only genuine subsets- // (providers the operator restricted); drop the field entirely when every- // provider is unrestricted so absent=all-global holds (full-replace- // semantics — a Host that restricts nothing saves exactly as today).if (effectiveAllowedModelsSpec.length > 0) {nextSpec.allowedModels = effectiveAllowedModelsSpec- } else {- delete nextSpec.allowedModels}const formResourceVersion = formResourceVersionRef.current@@@ -1117,216 -969,107 +1135,163 @@@</div></div>- {!editingModel ? (- <div className="cu-form-stack">- <div className="cu-field">- <label htmlFor="model-provider">Model provider</label>- <div className="cu-field__readonly">{getProviderLabel(providerDraft)}</div>- </div>- <div className="cu-field">- <label htmlFor="model-credential">Credential</label>- <div className="cu-field__readonly" id="model-credential">- {providerDraft === 'codex-subscription'- ? connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY- ? 'No credential assigned'- : codexConnections.find(row => row.connectionKey === connectionRefDraft)- ?.displayName || connectionRefDraft- : secretRefDraft || '-'}- </div>- </div>- <div className="cu-field">- <label htmlFor="model-name">Default model</label>- <div className="cu-field__readonly" id="model-name">- {modelNameDraft || 'Not set'}- </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 className="cu-field__readonly">- All models — this agent offers every enabled model for its provider(s).- </div>- )}- </div>- {providerDraft === 'codex-subscription' &&- llmChainRequiresSecret(providerDraft, llmPolicyDraft?.fallbacks) ? (- <div className="cu-field">- <label htmlFor="model-secret">Secret reference</label>- <div className="cu-field__readonly">{secretRefDraft || '-'}</div>- </div>- ) : null}- <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 className="cu-field__readonly">No fallback configured.</div>- )}- </div>- </div>- ) : (- <>- {retireCandidates.length > 0 ? (- <div className="cu-banner cu-banner--warning" style={{ marginBottom: '0.75rem' }}>- <span>- Removed fallback left stored key(s): {retireCandidates.join(', ')}. They will- be deleted from the Secret when you save.- </span>- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- onClick={() => setRetireCandidates([])}- disabled={busy}- >- Keep them- </button>- </div>- ) : null}- <div className="cu-form-stack" style={{ marginBottom: '1rem' }}>- <div className="cu-field">- <label htmlFor="host-secret">Credential</label>+ <div className="cu-form-stack">+ <div className="cu-field">- <label htmlFor="model-secret">LLM Secret</label>++ <label htmlFor="model-secret">Credential</label>+ <div className="cu-llm-secret-control">- <LlmSecretSelect- id="model-secret"- value={secretRefDraft}- ariaLabel="LLM Secret"- onChange={value => void handleSecretRefChange(value)}- options={llmSecretOptions}- placeholder={- llmSecretOptions.length === 0- ? 'No LLM Secret available'- : 'Select an LLM Secret...'- }- disabled={busy || llmSecretOptions.length === 0}- />++ {editingModel ? (+ <select- id="host-secret"++ id="model-secret"++ className="cu-select"++ aria-label="Credential"+ value={credentialSelectValue(secretRefDraft, connectionRefDraft)}- onChange={e => handleCredentialChange(e.target.value)}++ onChange={event => handleCredentialChange(event.target.value)}+ disabled={busy}+ >- <option value="">Select credential</option>- {availableSecrets.length > 0 ? (- <optgroup label="API keys">- {availableSecrets.map(secretName => (- <option key={secretName} value={secretName}>- {secretName}- </option>- ))}- {secretRefDraft &&- parseCredentialSelect(secretRefDraft).kind === 'secret' &&- !availableSecrets.includes(secretRefDraft) ? (- <option value={secretRefDraft}>{secretRefDraft} (custom)</option>- ) : null}- </optgroup>- ) : secretRefDraft &&- parseCredentialSelect(secretRefDraft).kind === 'secret' ? (- <optgroup label="API keys">- <option value={secretRefDraft}>{secretRefDraft} (custom)</option>- </optgroup>- ) : null}++ <option value="">Select a credential…</option>++ {llmSecretOptions.map(option => (++ <option key={option.value} value={credentialSelectValue(option.value, '')}>++ {option.label}++ </option>++ ))}+ {codexConnections.some(row => row.status !== 'revoked') ||+ (connectionRefDraft &&+ connectionRefDraft !== CODEX_UNASSIGNED_CONNECTION_KEY) ? (- <optgroup label="Subscriptions">++ <optgroup label="ChatGPT subscriptions">+ {codexConnections+ .filter(row => row.status !== 'revoked')+ .map(row => (+ <option+ key={row.connectionKey}+ value={credentialSelectValue('', row.connectionKey)}+ >+ {row.displayName || row.connectionKey}+ </option>+ ))}+ {connectionRefDraft &&+ connectionRefDraft !== CODEX_UNASSIGNED_CONNECTION_KEY &&+ !codexConnections.some(+ row =>+ row.connectionKey === connectionRefDraft && row.status !== 'revoked'+ ) ? (+ <option value={credentialSelectValue('', connectionRefDraft)}>+ {connectionRefDraft} (unavailable)+ </option>+ ) : null}+ </optgroup>+ ) : null}+ </select>- <p className="cu-muted" style={{ marginTop: '0.35rem' }}>- <a- href={- providerDraft === 'codex-subscription'- ? CONTROL_ROUTES.secrets.llmSubscriptions- : CONTROL_ROUTES.secrets.llm- }- >- Manage credentials in Secrets- </a>- </p>- </div>- {providerDraft === 'codex-subscription' &&- llmChainRequiresSecret(providerDraft, llmPolicyDraft?.fallbacks) ? (- <div className="cu-field">- <label htmlFor="host-fallback-secret">Secret reference</label>- <select- id="host-fallback-secret"- value={secretRefDraft}- onChange={e => setSecretRefDraft(e.target.value)}- disabled={busy}- >- <option value="">Select LLM secret</option>- {availableSecrets.map(secretName => (- <option key={secretName} value={secretName}>- {secretName}- </option>- ))}- {secretRefDraft && !availableSecrets.includes(secretRefDraft) ? (- <option value={secretRefDraft}>{secretRefDraft} (custom)</option>- ) : null}- </select>- </div>- ) : null}++ ) : (++ <LlmSecretSelect++ id="model-secret"++ value={secretRefDraft}++ ariaLabel="Credential"++ onChange={value => void handleSecretRefChange(value)}++ options={llmSecretOptions}++ placeholder={++ providerDraft === 'codex-subscription'++ ? connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY++ ? 'No ChatGPT subscription assigned'++ : codexConnections.find(row => row.connectionKey === connectionRefDraft)++ ?.displayName || connectionRefDraft++ : llmSecretOptions.length === 0++ ? 'No LLM Secret available'++ : 'Select an LLM Secret...'++ }++ disabled={busy || providerDraft === 'codex-subscription'}++ />++ )}+ <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>- <LlmProviderConfig+ <span className="cu-field__hint">- Select the LLM Secret linked to this agent. Use the pencil to edit its stored- credentials.++ Choose an API-key secret or a ChatGPT subscription. Agents only choose; Secrets++ creates grants.+ </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>+ {editingModel ? (+ <>+ <LlmProviderConfig+ provider={providerDraft}+ model={modelNameDraft}+ onPrimaryChange={next => {+ setProviderDraft(next.provider)+ setModelNameDraft(next.model)+ }}+ policy={llmPolicyDraft}+ onPolicyChange={setLlmPolicyDraft}+ allowedModels={allowedModelsDraft}+ onAllowedModelsChange={setAllowedModelsDraft}- catalog={allowedCatalog}++ catalog={catalogForEditor}+ 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}++ disabled={++ busy ||++ Boolean(hostModelNameError(modelNameDraft)) ||++ (providerDraft === 'codex-subscription' &&++ (connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY ||++ Boolean(grantCatalogError) ||++ !codexModels.includes(modelNameDraft.trim())))++ }+ >+ {busy ? 'Saving…' : 'Save model configuration'}+ </button>+ </div>+ </>+ ) : (+ <LlmProviderSummaryprovider={providerDraft}model={modelNameDraft}- modelLabel="Default model"- onPrimaryChange={next => {- setProviderDraft(next.provider)- setModelNameDraft(next.model)- if (next.provider !== 'codex-subscription') {- setConnectionRefDraft(CODEX_UNASSIGNED_CONNECTION_KEY)- setCodexModels([])- }- }}+ allowedModels={effectiveAllowedModelsSpec}policy={llmPolicyDraft}- onPolicyChange={handlePolicyChange}- allowedModels={allowedModelsDraft}- onAllowedModelsChange={setAllowedModelsDraft}- catalog={catalogForEditor}- catalogLoading={modelsLoading}- catalogError={modelsError}- replacePrimaryModelWithAllowedModels={providerDraft !== 'codex-subscription'}- credentials={- llmChainRequiresSecret(providerDraft, llmPolicyDraft?.fallbacks)- ? {- draft: llmKeyDraft,- onChange: (dataKey, value) =>- setLlmKeyDraft(prev => ({ ...prev, [dataKey]: value })),- existingKeys: currentSecretKeys,- }- : undefined- }- secretKeys={- llmChainRequiresSecret(providerDraft, llmPolicyDraft?.fallbacks)- ? currentSecretKeys- : []- }- disabled={busy}/>- </>- )}+ )}+ </div>++ {llmSecretModalOpen && secretRefDraft.trim() ? (+ <LlmSecretUpdateModal+ key={secretRefDraft}+ secretName={secretRefDraft}+ existingKeys={currentSecretKeys}+ protectedCredentialSlots={protectedCredentialSlots}+ onClose={() => setLlmSecretModalOpen(false)}+ onChanged={async () => {+ await loadData('none')+ }}+ />+ ) : null}</>)}diff --cc control-ui/components/HostWizard/types.tsindex b4ec0c763,419378670..42b94250f--- a/control-ui/components/HostWizard/types.ts+++ b/control-ui/components/HostWizard/types.ts@@@ -48,19 -38,13 +49,33 @@@ export type HostWizardProps =pageHeader?: ReactNode}+export type WizardSelectOption = {+ group?: string+ label: ReactNode+ meta?: ReactNode+ providers?: { id: string; label: string }[]+ value: string+}++export type WizardSelectProps = {+ className?: string+ disabled?: boolean+ onChange: (value: string) => void+ options: WizardSelectOption[]+ placeholder: string+ value: string+}+++ export type HostWizardValidationState = {+ hostName: string+ secretMode: 'existing' | 'new'+ existingSecret: string++ existingLlmSecret: string+ newSecretName: string+ llmKeyDraft: Record<string, string>+ llmPolicy: LlmPolicy | undefined+ provider: LlmProvider+ modelName: string++ connectionRef: string++ codexModels: string[]+ }diff --cc control-ui/components/LlmCredentialFields/index.tsxindex eb7638cb4,dec6990ab..718e4c996--- a/control-ui/components/LlmCredentialFields/index.tsx+++ b/control-ui/components/LlmCredentialFields/index.tsx@@@ -138,11 -145,9 +146,11 @@@ export function LlmCredentialFields(// Filtering LLM_CREDENTIAL_GROUPS (instead of iterating the sets) keeps the// canonical package order regardless of the order providers were added.- const visibleGroups = LLM_CREDENTIAL_GROUPS.filter(group => visibleProviders.has(group.provider))- const addableGroups = LLM_CREDENTIAL_GROUPS.filter(+ const visibleGroups = LLM_SECRET_EDITOR_GROUPS.filter(group =>+ visibleProviders.has(group.provider)+ )+ const addableGroups = LLM_SECRET_EDITOR_GROUPS.filter(- group => !visibleProviders.has(group.provider)+ group => !visibleProviders.has(group.provider) && !excludedProviderSet.has(group.provider))// The picker is a MENU, not a selection: it never holds a value (see thediff --cc control-ui/components/LlmSecretSelect/index.tsxindex 000000000,ee99532ca..663d2b393mode 000000,100644..100644--- a/control-ui/components/LlmSecretSelect/index.tsx+++ b/control-ui/components/LlmSecretSelect/index.tsx@@@ -1,0 -1,113 +1,117 @@@+ 'use client'++ import React, { Fragment, useState } from 'react'+ import { LlmProviderIcon } from '@/components/LlmProviderIcon'+ import { cn } from '@/lib/cn'+ import type { LlmSecretSelectOption, LlmSecretSelectProps } from './types'++ export type { LlmSecretSelectOption, LlmSecretSelectProps } from './types'++ function ProviderSummary({+ providers,+ }: {+ providers: NonNullable<LlmSecretSelectOption['providers']>+ }) {+ if (providers.length === 0) return null++ return (+ <span className="cu-agent-select__providers">+ <span className="cu-agent-select__providers-label">Providers: </span>+ {providers.map((provider, index) => (+ <Fragment key={provider.id}>+ {index > 0 ? ', ' : null}+ <span className="cu-agent-select__provider">+ <LlmProviderIcon provider={provider.id} label={provider.label} />+ <span>{provider.label}</span>+ </span>+ </Fragment>+ ))}+ </span>+ )+ }++ /**+ * The shared custom picker for linking an agent to an LLM Secret. The provider+ * list is derived from Secret data-key names, so each option can show the same+ * enabled-provider SVGs as the LLM Secrets table without exposing values.+ */+ export function LlmSecretSelect({+ ariaLabel,+ className,+ disabled = false,+ id,+ onChange,+ options,+ placeholder,+ value,+ }: LlmSecretSelectProps) {+ const [open, setOpen] = useState(false)+ const selectedOption = options.find(option => option.value === value)++ return (+ <div+ className={cn('cu-agent-select', className)}+ onBlur={event => {+ if (!event.currentTarget.contains(event.relatedTarget)) {+ setOpen(false)+ }+ }}+ >+ <button+ id={id}+ type="button"+ className="cu-agent-select__button"+ aria-label={ariaLabel}+ aria-expanded={open}+ aria-haspopup="listbox"+ disabled={disabled}+ onClick={() => setOpen(previous => !previous)}+ >+ <span className="cu-agent-select__button-copy">+ <span>{selectedOption?.label || placeholder}</span>+ {selectedOption?.providers && selectedOption.providers.length > 0 ? (+ <ProviderSummary providers={selectedOption.providers} />+ ) : selectedOption?.meta ? (+ <span className="cu-agent-select__button-meta">{selectedOption.meta}</span>+ ) : null}+ </span>+ <span className="cu-agent-select__chevron" aria-hidden="true" />+ </button>+ {open ? (+ <div className="cu-agent-select__menu" role="listbox" aria-label={ariaLabel}>+ {options.length === 0 ? (+ <span className="cu-agent-select__empty">No options available.</span>+ ) : (- options.map(option => (- <button- key={option.value}- type="button"- className="cu-agent-select__option"- data-active={value === option.value ? 'true' : 'false'}- role="option"- aria-selected={value === option.value}- onClick={() => {- onChange(option.value)- setOpen(false)- }}- >- <span className="cu-agent-select__option-copy">- <span className="cu-agent-select__option-name">{option.label}</span>- {option.providers && option.providers.length > 0 ? (- <ProviderSummary providers={option.providers} />- ) : option.meta ? (- <span className="cu-agent-select__option-meta">{option.meta}</span>- ) : null}- </span>- </button>++ options.map((option, index) => (++ <Fragment key={option.value}>++ {option.group && option.group !== options[index - 1]?.group ? (++ <span className="cu-agent-select__empty">{option.group}</span>++ ) : null}++ <button++ type="button"++ className="cu-agent-select__option"++ data-active={value === option.value ? 'true' : 'false'}++ role="option"++ aria-selected={value === option.value}++ onClick={() => {++ onChange(option.value)++ setOpen(false)++ }}++ >++ <span className="cu-agent-select__option-copy">++ <span className="cu-agent-select__option-name">{option.label}</span>++ {option.providers && option.providers.length > 0 ? (++ <ProviderSummary providers={option.providers} />++ ) : option.meta ? (++ <span className="cu-agent-select__option-meta">{option.meta}</span>++ ) : null}++ </span>++ </button>++ </Fragment>+ ))+ )}+ </div>+ ) : null}+ </div>+ )+ }diff --cc control-ui/components/LlmSecretSelect/types.tsindex 000000000,05d2f0733..2ec6a468cmode 000000,100644..100644--- a/control-ui/components/LlmSecretSelect/types.ts+++ b/control-ui/components/LlmSecretSelect/types.ts@@@ -1,0 -1,24 +1,25 @@@+ import type { ReactNode } from 'react'++ export type LlmSecretSelectProvider = {+ id: string+ label: string+ }++ export type LlmSecretSelectOption = {++ group?: string+ value: string+ label: string+ meta?: ReactNode+ providers?: LlmSecretSelectProvider[]+ }++ export type LlmSecretSelectProps = {+ ariaLabel?: string+ className?: string+ disabled?: boolean+ id?: string+ onChange: (value: string) => void+ options: LlmSecretSelectOption[]+ placeholder: string+ value: string+ }diff --cc control-ui/components/RecipeSecretsPanel/index.tsxindex 676a354aa,b0c435dfb..6252fa410--- a/control-ui/components/RecipeSecretsPanel/index.tsx+++ b/control-ui/components/RecipeSecretsPanel/index.tsx@@@ -9,12 -9,12 +9,13 @@@ importgetRecipe,getRecipeSecrets,} from '../../lib/api'+import { llmChainRequiresSecret } from '../../lib/llm'import { collectWorkflowRecipeSecretRefs } from '../../lib/workflowRecipeSecretRefs'import { useConfirmDialog } from '../ConfirmDialog'+ import { RowActionsMenu } from '../RowActionsMenu'import { TablePanelHeader } from '../TablePanelHeader'import { useToast } from '../Toast'- import { IconPencil, IconRefresh, IconX } from '../icons'+ import { IconRefresh } from '../icons'type RecipeSecretStatus = 'provisioned' | 'missing'diff --cc control-ui/components/SecretsTable.tsxindex 779975d3f,f47db7407..9ff31854c--- a/control-ui/components/SecretsTable.tsx+++ b/control-ui/components/SecretsTable.tsx@@@ -11,23 -11,18 +11,19 @@@ importgetRecipeSecrets,getRecipes,} from '../lib/api'- import {- createEmptyLlmKeyDraft,- getProviderLabel,- getProvidersWithCompleteCredentials,- validateLlmSecretData,- } from '../lib/llm'+ import { getProviderLabel, getProvidersWithCompleteCredentials } from '../lib/llm'import { collectWorkflowRecipeSecretRefs } from '../lib/workflowRecipeSecretRefs'import { useConfirmDialog } from './ConfirmDialog'- import { LlmCredentialFields } from './LlmCredentialFields'import { LlmProviderIcon } from './LlmProviderIcon'+ import { LlmSecretUpdateModal } from './LlmSecretUpdateModal'+import { LlmSecretsSubTabs } from './LlmSecretsSubTabs'+ import { RowActionsMenu } from './RowActionsMenu'+import { SecretsScopeTabs } from './SecretsScopeTabs'import { SectionSearchInput } from './SectionSearchInput'import { IconKey } from './Sidebar/icons'-import { TabBar } from './TabBar'import { TablePanelHeader } from './TablePanelHeader'import { useToast } from './Toast'- import { IconPencil, IconRefresh, IconX } from './icons'+ import { IconRefresh } from './icons'type SecretItem = {name?: stringdiff --cc control-ui/components/__tests__/HostDetailsPage.conflict.test.tsxindex 1bf78cf73,6df3dd47d..f0373f5ec--- a/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx+++ b/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx@@@ -239,50 -311,292 +311,355 @@@ describe('HostDetailsPage current modesetupApiMocks(formLoadHost, refetchedHost)})- it('preserves an open Overview draft when Model & credentials is saved', async () => {+ it('opens the linked LLM Secret editor without navigating or saving the Host', async () => {const view = render(<HostDetailsPage />)- await openOverviewEdit()- fireEvent.change(screen.getByLabelText('Display name'), {- target: { value: 'unsaved-overview-name' },- })+ navigateToTab(view, 'model')+ expect(await screen.findByText('Current model')).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Edit LLM Secret credentials' }))++ expect(screen.getByRole('dialog')).toBeInTheDocument()+ expect(screen.getByText('Update LLM secret openai-secret')).toBeInTheDocument()+ expect(pushMock).not.toHaveBeenCalled()+ 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('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('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(- await screen.findByText(- 'Provider, allowed models, fallback policy, and credentials for this agent.'+ 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')- ).toBeInTheDocument()+ ).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' }))- // Keep the existing static-credentials secret. Emptying it now fails- // closed (Codex broker chains omit secretRef; OpenAI still requires one).- fireEvent.click(screen.getByRole('button', { name: 'Save' }))- expect(await screen.findByText('Model & credentials saved.')).toBeInTheDocument()+ 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' }))- navigateToTab(view, 'overview')- expect(await screen.findByDisplayValue('unsaved-overview-name')).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument()+ 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('preserves an open Model & credentials draft when Overview is saved', async () => {+ 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(- 'Provider, allowed models, fallback policy, and credentials for this agent.'+ 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')+ await screen.findByText('Current model')++ fireEvent.click(screen.getByRole('button', { name: 'LLM Secret' }))+ fireEvent.click(screen.getByRole('option', { name: /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 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' },+ })+ fireEvent.click(screen.getByRole('button', { name: 'Update secret' }))++ await waitFor(() =>+ expect(api.apiSend).toHaveBeenCalledWith('PUT', '/api/v1/admin/secrets', {+ name: 'openai-secret',+ merge: true,+ stringData: { 'openai-api-key': 'sk-live' },+ })+ )+ 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)+ })+ })++++describe('HostDetailsPage cross-tab draft preservation', () => {++ beforeEach(() => {++ vi.clearAllMocks()++ mockParams = { name: 'foo' }++ vi.mocked(api.getLlmModels).mockResolvedValue({ rows: [] })++ setupApiMocks(formLoadHost, refetchedHost)++ })++++ it('preserves an open Overview draft when model configuration is saved', async () => {++ const view = render(<HostDetailsPage />)++ await openOverviewEdit()++ fireEvent.change(screen.getByLabelText('Agent name'), {++ target: { value: 'unsaved-overview-name' },++ })++++ navigateToTab(view, 'model')++ expect(await screen.findByText('Current model')).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))- fireEvent.change(screen.getByLabelText('Credential'), { target: { value: '' } })++ // Keep the existing static-credentials secret. Emptying it now fails++ // closed (Codex broker chains omit secretRef; OpenAI still requires one).++ fireEvent.click(screen.getByRole('button', { name: 'Save model configuration' }))++ expect(await screen.findByText('Model configuration saved.')).toBeInTheDocument()++ navigateToTab(view, 'overview')- await openOverviewEdit()- fireEvent.click(screen.getByRole('button', { name: 'Save' }))- expect(await screen.findByText('Agent configuration saved.')).toBeInTheDocument()++ expect(await screen.findByDisplayValue('unsaved-overview-name')).toBeInTheDocument()++ expect(screen.getByRole('button', { name: 'Save agent name' })).toBeInTheDocument()++ })++++ it('fails closed instead of writing an unassigned Codex connectionRef', async () => {++ const { secretRef: _omit, ...specWithoutSecret } = baseSpec++ void _omit++ const codexHost: TestHost = {++ metadata: { name: 'foo', resourceVersion: 'rv-form-load' },++ spec: {++ ...specWithoutSecret,++ model: { provider: 'codex-subscription', name: 'gpt-5.1' },++ },++ }++ setupApiMocks(codexHost, codexHost)+++ const view = render(<HostDetailsPage />)+ navigateToTab(view, 'model')- await waitFor(() =>- expect((screen.getByLabelText('Credential') as HTMLSelectElement).value).toBe('')++ expect(await screen.findByText('Current model')).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))++++ expect(screen.getByLabelText('Credential')).toBeInTheDocument()++ expect(screen.queryByText('Secret reference')).not.toBeInTheDocument()++ expect(screen.queryByRole('radio', { name: /ChatGPT subscription/i })).not.toBeInTheDocument()++ expect(screen.getByRole('button', { name: 'Save model configuration' })).toBeDisabled()++ fireEvent.click(screen.getByRole('button', { name: 'Save model configuration' }))++++ expect(api.apiSend).not.toHaveBeenCalledWith(++ 'PUT',++ '/api/v1/admin/hosts/foo',++ expect.objectContaining({++ spec: expect.objectContaining({++ model: expect.objectContaining({ connectionRef: 'unassigned' }),++ }),++ })+ )- expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument()+ })+})diff --cc control-ui/components/__tests__/HostDetailsPage.identity.test.tsxindex 98dc331c1,ff48e987f..097eaf35d--- a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx+++ b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx@@@ -150,73 -149,66 +162,124 @@@ describe('HostDetailsPage identity inteexpect(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()+ expect(screen.getByRole('button', { name: 'Replace OpenAI API key' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Update secret' })).toBeInTheDocument()+ expect(pushMock).not.toHaveBeenCalled()+ expect(container.querySelector('.cu-agent-detail-card')).toBeNull()+ })++ it('uses a custom LLM Secret picker with the enabled provider icons', async () => {+ mockParams = { name: 'foo', tab: 'model' }+ ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({+ host,+ contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],+ secrets: [+ { name: 'openai-secret', keys: ['openai-api-key', 'claude-api-key'] },+ { name: 'zai-secret', keys: ['zai-api-key'] },+ ],+ users: [],+ teams: [],+ agentUsers: [],+ agentTeams: [],+ })++ render(<HostDetailsPage />)++ const picker = await screen.findByRole('button', { name: 'LLM Secret' })+ expect(picker).toHaveTextContent('openai-secret')+ expect(picker.querySelectorAll('img')).toHaveLength(2)+ expect(picker.querySelector('img')).toHaveAttribute('src', '/provider-icons/openai.svg')+ expect(picker.querySelectorAll('img')[1]).toHaveAttribute('src', '/provider-icons/claude.svg')+ expect(screen.queryByRole('combobox')).toBeNull()++ fireEvent.click(picker)++ const zaiOption = screen.getByRole('option', { name: /zai-secret/ })+ expect(zaiOption).toHaveTextContent('Providers: Z.AI')+ expect(zaiOption.querySelector('img')).toHaveAttribute('src', '/provider-icons/zai.svg')+ })++ it('uses the shared LLM Secret editor for additional provider credentials', async () => {+ mockParams = { name: 'foo', tab: 'model' }+ render(<HostDetailsPage />)++ 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()+ expect(screen.getByRole('button', { name: 'Replace OpenAI API key' })).toBeInTheDocument()++ fireEvent.click(screen.getByLabelText('Add provider'))+ fireEvent.click(screen.getByRole('option', { name: 'Anthropic' }))expect(- screen.getByLabelText('Allowed models · OpenAI', { selector: '#llm-allowed-openai' })+ screen.getByText('Anthropic', { selector: '.cu-llm-cred-group__title' })).toBeInTheDocument()- expect(screen.queryByLabelText('Model', { selector: '#llm-primary-model' })).toBeNull()- expect(screen.getByLabelText('Credential')).toBeInTheDocument()- expect(- screen.getByRole('button', { name: 'Save' }).closest('.cu-agent-detail-toolbar')- ).not.toBeNull()- expect(container.querySelector('.cu-agent-detail-card .cu-agent-detail-scroll')).not.toBeNull()+ expect(screen.getByLabelText(/Claude API key/i)).toBeInTheDocument()})+ it('shows a complete ChatGPT assignment without requiring Edit', async () => {+ mockParams = { name: 'foo', tab: 'model' }+ vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([+ {+ connectionKey: 'codex-aaa',+ displayName: 'Team A',+ status: 'connected',+ credentialRevision: 1,+ catalogRevision: 1,+ accountFingerprint: 'fp',+ catalogStatus: 'ready',+ catalogSyncedAt: '2026-08-20T00:00:00.000Z',+ lastRefreshAt: '2026-08-20T00:00:00.000Z',+ lastAuthAt: '2026-08-20T00:00:00.000Z',+ refreshLockHeld: false,+ defaultModel: 'gpt-5.1',+ },+ ])+ vi.mocked(listCodexConnectionModels).mockResolvedValue([+ { model: 'gpt-5.1', enabled: true, stale: false },+ ])+ const codexHost = {+ ...host,+ spec: {+ ...host.spec,+ secretRef: undefined,+ model: {+ provider: 'codex-subscription',+ name: 'gpt-5.1',+ connectionRef: 'codex-aaa',+ },+ },+ }+ ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({+ host: codexHost,+ contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],+ secrets: [],+ users: [],+ teams: [],+ agentUsers: [],+ agentTeams: [],+ })+ render(<HostDetailsPage />)+- expect(await screen.findByText('Default model')).toBeInTheDocument()- expect(screen.getByText('gpt-5.1')).toBeInTheDocument()++ const summary = await screen.findByRole('region', { name: 'LLM configuration summary' })++ expect(summary).toHaveTextContent('Current model')++ expect(summary).toHaveTextContent('gpt-5.1')+ expect(screen.getByText('Team A')).toBeInTheDocument()+ expect(screen.queryByText('codex-aaa')).not.toBeInTheDocument()- expect(screen.getByText('Team A')).toBeInTheDocument()+ expect(screen.getByText('Credential')).toBeInTheDocument()++ expect(screen.queryByText('Secret reference')).not.toBeInTheDocument()+ expect(screen.queryByText('Broker-backed — no LLM secret required')).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()++ expect(++ screen.queryByRole('button', { name: 'Save model configuration' })++ ).not.toBeInTheDocument()+ })+it('opens Advanced on the Hooks sub-tab', async () => {mockParams = { name: 'foo', tab: 'advanced' }render(<HostDetailsPage />)@@@ -316,152 -276,17 +347,77 @@@expect(pushMock).not.toHaveBeenCalledWith('/agents/Product Agents')})- // Regression: Cancel must DISCARD the Display-name edit, not carry the stale- // draft into the read-only view and the next save. Before the resetOverview- // fix, a cancelled "Display name" edit silently persisted on the following- // Save (spec.host written to the abandoned value).- it('discards a cancelled Display name edit — read-only reverts and a later save keeps the saved value', async () => {+ it('cancels an inline agent name edit without persisting the draft', async () => {render(<HostDetailsPage />)- const [overviewEditButton] = await screen.findAllByRole('button', { name: 'Edit' })- await waitFor(() => expect(overviewEditButton).toBeEnabled())- fireEvent.click(overviewEditButton)-- // Type a Display name the operator then abandons.- fireEvent.change(screen.getByLabelText('Display name'), {+ fireEvent.click(await screen.findByRole('button', { name: 'Edit agent name' }))+ fireEvent.change(screen.getByLabelText('Agent name'), {target: { value: 'Discarded Draft' },})- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ fireEvent.click(screen.getByRole('button', { name: 'Cancel editing agent name' }))- // Observable #1 (T4): the read-only view shows the last-SAVED value, not the- // abandoned draft.expect(screen.getByText('foo-display')).toBeInTheDocument()expect(screen.queryByText('Discarded Draft')).not.toBeInTheDocument()-- // Re-open Edit and Save without touching Display name again.- const [overviewEditButton2] = await screen.findAllByRole('button', { name: 'Edit' })- fireEvent.click(overviewEditButton2)- fireEvent.click(screen.getByRole('button', { name: 'Save' }))-- await waitFor(() =>- expect(api.apiSend).toHaveBeenCalledWith('PUT', '/api/v1/admin/hosts/foo', expect.any(Object))- )-- // Observable #2 (T4, PINNING): the persisted spec.host is the saved value,- // NOT the discarded draft. This assertion goes red pre-fix.- const putCall = (api.apiSend as unknown as ReturnType<typeof vi.fn>).mock.calls.find(- c => c[0] === 'PUT' && c[1] === '/api/v1/admin/hosts/foo'- )- expect(putCall![2].spec.host).toBe('foo-display')- })-- // Collateral regression: resetOverviewDrafts must NOT clobber a LIVE Context-tab- // edit. contextRefDraft is written by both saveHost (Overview) and the Context- // tab's own editingContext session; reverting it on Overview Edit-open/Cancel- // while that session is open silently discards the operator's in-progress pick.- it('preserves a live Context-tab selection across an Overview Edit-open/Cancel', async () => {- // Two contexts so the Context tab can switch selection; saved = ctx-a.- ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- host: { ...host, spec: { ...host.spec, contextRef: 'ctx-a' } },- contexts: [- { metadata: { name: 'ctx-a' }, spec: { contextId: 'ctx-a' } },- { metadata: { name: 'ctx-b' }, spec: { contextId: 'ctx-b' } },- ],- secrets: [{ name: 'openai-secret' }],- users: [],- teams: [],- agentUsers: [],- agentTeams: [],- })-- // Land on the Context tab, open its edit session, pick a DIFFERENT context.- mockParams = { name: 'foo', tab: 'contexts' }- const view = render(<HostDetailsPage />)- fireEvent.click(await screen.findByRole('button', { name: 'Edit context' }))- fireEvent.change(screen.getByRole('combobox'), { target: { value: 'ctx-b' } })- expect((screen.getByRole('combobox') as HTMLSelectElement).value).toBe('ctx-b')-- // Switch to Overview and fire BOTH resetOverviewDrafts sites: Edit-open, Cancel.- mockParams = { name: 'foo' }- view.rerender(- <ToastProvider>- <HostDetailsPage />- </ToastProvider>- )- const [overviewEditButton] = await screen.findAllByRole('button', { name: 'Edit' })- await waitFor(() => expect(overviewEditButton).toBeEnabled())- fireEvent.click(overviewEditButton)- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))-- // Back on the Context tab (still editing): the in-progress ctx-b must survive.- mockParams = { name: 'foo', tab: 'contexts' }- view.rerender(- <ToastProvider>- <HostDetailsPage />- </ToastProvider>- )-- // PINNING (T4): the Context select still shows the unsaved ctx-b, not the- // reverted saved ctx-a. Pre-collateral-fix this reads 'ctx-a'.- expect((screen.getByRole('combobox') as HTMLSelectElement).value).toBe('ctx-b')+ expect(api.apiSend).not.toHaveBeenCalled()})++ it('saves a Codex-only Host without secretRef and keeps metadata.name as identity', async () => {+ const { secretRef: _omit, ...specWithoutSecret } = host.spec+ void _omit+ const codexHost = {+ ...host,+ spec: {+ ...specWithoutSecret,+ model: { provider: 'codex-subscription', name: 'gpt-5.1' },+ },+ }+ ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({+ host: codexHost,+ contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],+ secrets: [{ name: 'openai-secret' }],+ users: [],+ teams: [],+ agentUsers: [],+ agentTeams: [],+ })+ ;(api.getHost as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(codexHost)+ ;(api.getLlmModels as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({+ rows: [+ {+ id: 'm-codex',+ provider: 'codex-subscription',+ model: 'gpt-5.1',+ vendor: 'OpenAI',+ display_name: null,+ context_window_tokens: null,+ enabled: true,+ stale: false,+ created_at: '',+ updated_at: '',+ },+ ],+ })+ mockParams = { name: 'foo', tab: 'model' }+ render(<HostDetailsPage />)++ expect(await screen.findByText('No credential assigned')).toBeInTheDocument()+ expect(screen.getByText('Credential')).toBeInTheDocument()++ expect(screen.queryByText('Secret reference')).not.toBeInTheDocument()+ expect(screen.queryByText('OpenAI Codex Subscription')).not.toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ expect(screen.getByLabelText('Credential')).toBeInTheDocument()+ expect(screen.queryByRole('radio', { name: /ChatGPT subscription/i })).not.toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()- fireEvent.click(screen.getByRole('button', { name: 'Save' }))++ expect(screen.getByRole('button', { name: 'Save model configuration' })).toBeDisabled()++ fireEvent.click(screen.getByRole('button', { name: 'Save model configuration' }))+ expect(api.apiSend).not.toHaveBeenCalledWith(+ 'PUT',+ '/api/v1/admin/hosts/foo',+ expect.objectContaining({+ spec: expect.objectContaining({+ model: expect.objectContaining({ connectionRef: 'unassigned' }),+ }),+ })+ )+ expect(screen.queryByText('OpenAI Codex Subscription')).not.toBeInTheDocument()+ })})diff --cc control-ui/components/__tests__/HostWizard.test.tsxindex be388f6a8,d3af99092..384384b07--- a/control-ui/components/__tests__/HostWizard.test.tsx+++ b/control-ui/components/__tests__/HostWizard.test.tsx@@@ -22,35 -26,8 +26,34 @@@ import { ToastProvider } from '../Toast* These tests lock the new behavior so it cannot regress.*/+vi.mock('../../lib/codexSubscription', async importOriginal => {+ const actual = await importOriginal<typeof import('../../lib/codexSubscription')>()+ return {+ ...actual,+ listCodexSubscriptionConnections: vi.fn().mockResolvedValue([+ {+ connectionKey: 'codex-aaa',+ displayName: 'Team A',+ status: 'connected',+ defaultModel: 'gpt-5.1',+ credentialRevision: 1,+ catalogRevision: 1,+ accountFingerprint: 'fp',+ catalogStatus: 'ready',+ catalogSyncedAt: '2026-08-20T00:00:00.000Z',+ lastRefreshAt: '2026-08-20T00:00:00.000Z',+ lastAuthAt: '2026-08-20T00:00:00.000Z',+ refreshLockHeld: false,+ },+ ]),+ listCodexConnectionModels: vi+ .fn()+ .mockResolvedValue([{ model: 'gpt-5.1', enabled: true, stale: false }]),+ }+})+// Mock lib/api BEFORE importing the component. vi.mock is hoisted.vi.mock('../../lib/api', () => ({- apiGet: vi.fn().mockResolvedValue({ items: [] }),apiSend: vi.fn().mockResolvedValue({}),getAdminUsers: vi.fn().mockResolvedValue({items: [@@@ -175,20 -128,9 +178,11 @@@ async function walkToAccessStep(opts?:})fireEvent.click(screen.getByRole('button', { name: 'Next' }))- // Step 1: Context — create a new context. MCP attachments are optional,- // but this helper selects one to keep existing submit payload coverage.- fireEvent.click(screen.getByLabelText(/Create new context/i))- fireEvent.change(screen.getByPlaceholderText(/context-name/i), {- target: { value: 'ctx1' },- })- // Select the first connector checkbox- const mcpCheckbox = screen.getByRole('checkbox', { name: /mcp-a/i }) as HTMLInputElement- fireEvent.click(mcpCheckbox)- fireEvent.click(screen.getByRole('button', { name: 'Next' }))-- // Step 2: Model & Credentials — default model is valid; reuse the secret we provided.- fireEvent.click(screen.getByLabelText(/Use an existing Secret/i))- fireEvent.click(screen.getByRole('button', { name: /Select credential/i }))+ // Step 1: Model & Credentials — default model is valid; reuse the secret we provided.++ // Context/connectors moved after Access (origin/dev UX). Codex subscriptions++ // appear in the same LlmSecretSelect as API-key secrets.+ fireEvent.click(screen.getByLabelText(/Use an existing LLM Secret/i))+ fireEvent.click(screen.getByRole('button', { name: /Select LLM Secret/i }))fireEvent.click(screen.getByRole('option', { name: /secret-a/i }))fireEvent.click(screen.getByRole('button', { name: 'Next' }))@@@ -791,119 -856,3 +910,117 @@@ describe('HostWizard — create-only seexpect(api.apiSend).toHaveBeenCalledWith('DELETE', '/api/v1/admin/secrets/crd-agent-llm')})})++async function walkToModelStep(opts?: { agentName?: string }) {+ const name = opts?.agentName ?? 'codex-agent'+ await waitFor(() => {+ expect(api.getAdminUsers).toHaveBeenCalled()+ })+ fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: name } })+ fireEvent.click(screen.getByRole('button', { name: 'Next' }))- fireEvent.click(screen.getByLabelText(/Create new context/i))- fireEvent.change(screen.getByPlaceholderText(/context-name/i), { target: { value: 'ctx1' } })- fireEvent.click(screen.getByRole('button', { name: 'Next' }))+ await waitFor(() => {+ expect(+ screen.getByLabelText('Provider', { selector: '#llm-primary-provider' })+ ).toBeInTheDocument()+ })+}++async function selectCodexSubscription(model = 'gpt-5.1') {- fireEvent.click(screen.getByRole('button', { name: /Select credential/i }))++ fireEvent.click(screen.getByRole('button', { name: /Select LLM Secret/i }))+ fireEvent.click(screen.getByRole('option', { name: /Team A/i }))+ await waitFor(() => {+ expect(+ screen.getByLabelText('Default model', { selector: '#llm-primary-model' })+ ).toHaveTextContent(model)+ })+ expect(screen.queryByRole('radio', { name: /^ChatGPT subscription$/i })).not.toBeInTheDocument()+}++describe('HostWizard — broker-backed Codex authoring', () => {+ it('creates a Codex-only Host without secretRef or a Secret POST', async () => {+ await renderWizard()+ await walkToModelStep({ agentName: 'codex-only' })+ await selectCodexSubscription()+ expect(screen.queryByLabelText(/OpenAI API key/i)).not.toBeInTheDocument()+ fireEvent.click(screen.getByLabelText('Default model', { selector: '#llm-primary-model' }))+ expect(screen.queryByRole('option', { name: 'old-codex' })).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Next' })).toBeEnabled()+ fireEvent.click(screen.getByRole('button', { name: 'Next' }))- fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))++ continueToConnectorsStep()++ submitFromConnectorsStep()++ await waitFor(() => {+ expect(api.apiSend).toHaveBeenCalledWith(+ 'POST',+ '/api/v1/admin/hosts',+ expect.objectContaining({+ metadata: { name: 'codex-only' },+ spec: expect.objectContaining({+ model: {+ provider: 'codex-subscription',+ name: 'gpt-5.1',+ connectionRef: 'codex-aaa',+ },+ }),+ })+ )+ })+ const hostCall = vi+ .mocked(api.apiSend)+ .mock.calls.find(call => call[0] === 'POST' && call[1] === '/api/v1/admin/hosts')+ expect(hostCall?.[2]).not.toHaveProperty('spec.secretRef')+ expect((hostCall?.[2] as { spec: Record<string, unknown> }).spec.secretRef).toBeUndefined()+ expect(+ vi+ .mocked(api.apiSend)+ .mock.calls.some(call => call[0] === 'POST' && call[1] === '/api/v1/admin/secrets')+ ).toBe(false)+ }, 15_000)++ it('blocks Next until a ChatGPT subscription is chosen', async () => {+ await renderWizard()+ await walkToModelStep({ agentName: 'codex-needs-grant' })+ expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()- expect(screen.getByText('Select an existing secret.')).toBeInTheDocument()++ expect(screen.getByText('Select an existing LLM Secret.')).toBeInTheDocument()+ await selectCodexSubscription()+ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'Next' })).toBeEnabled()+ })- expect(screen.queryByText('Select an existing secret.')).not.toBeInTheDocument()++ expect(screen.queryByText('Select an existing LLM Secret.')).not.toBeInTheDocument()+ }, 15_000)++ it('seeds the grant default model when a ChatGPT subscription is chosen', async () => {+ await renderWizard()+ await walkToModelStep({ agentName: 'codex-keep-model' })+ await waitFor(() => {+ expect(+ screen.getByLabelText('Default model', { selector: '#llm-primary-model' })+ ).toHaveTextContent(/\S/)+ })+ await selectCodexSubscription()+ expect(+ screen.getByLabelText('Default model', { selector: '#llm-primary-model' })+ ).toHaveTextContent('gpt-5.1')- expect(screen.getByText(/Use an existing secret/i)).toBeInTheDocument()++ expect(screen.getByText(/Use an existing LLM Secret/i)).toBeInTheDocument()+ }, 15_000)++ it('requires exact credential slots when a static fallback joins a Codex primary', async () => {+ await renderWizard()+ await walkToModelStep({ agentName: 'codex-mixed' })+ await selectCodexSubscription()+ fireEvent.click(screen.getByRole('button', { name: /Fallback providers/i }))+ fireEvent.click(screen.getByRole('button', { name: /Add fallback provider/i }))+ fireEvent.change(screen.getByLabelText('Provider', { selector: '#llm-fallback-0-provider' }), {+ target: { value: 'openai' },+ })+ await waitFor(() => {+ expect(screen.getByRole('button', { name: /Select secret/i })).toBeInTheDocument()+ })+ expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()+ fireEvent.click(screen.getByRole('button', { name: /Select secret/i }))+ fireEvent.click(screen.getByRole('option', { name: /secret-a/i }))+ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'Next' })).not.toBeDisabled()+ })+ }, 15_000)+})diff --cc control-ui/package-lock.jsonindex f5980bc64,22ebfb978..4f7c2c87d--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-control-ui",- "version": "0.1.464",- "version": "0.1.457",++ "version": "0.1.465","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.464",- "version": "0.1.457",++ "version": "0.1.465","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/llm-providers": "file:../packages/llm-providers",diff --cc control-ui/package.jsonindex b078d5cde,2c1ef70e0..ea1b74a25--- a/control-ui/package.json+++ b/control-ui/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-control-ui",- "version": "0.1.464",- "version": "0.1.457",++ "version": "0.1.465","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --cc deploy/scripts/apply-inter-service-tokens.shindex 262d550d0,0b4a18fce..79253e248--- a/deploy/scripts/apply-inter-service-tokens.sh+++ b/deploy/scripts/apply-inter-service-tokens.sh@@@ -308,9 -309,14 +321,15 @@@ WA_READER_PATCH="$(jq -cnkctl -n channels patch secret workflow-approval-request-reader-credentials --type=merge -p "$WA_READER_PATCH"# Roll the consumers so they pick up the fresh tokens on first deploy. Safe- # no-ops if the Deployments do not yet exist.- for pair in "control-plane:control-api" \+ # no-ops if the Deployments do not yet exist. HCC is Recreate + replicas:1+ # and reloads HMAC only at process start, so skip that extra rollout when the+ # HCC key this run writes equals the key already in the Secret (image/spec+ # applies still roll HCC themselves). This is not "the running pod env matches+ # the Secret": an out-of-band kubectl patch of the HCC key, then a re-run that+ # preserve-or-generates from the Secret, will skip. Heal that with+ # FORCE_CONSUMER_RESTART=true.+ for pair in "control-plane:control-api" \+ "control-plane:codex-llm-proxy" \"control-plane:workflow-recipes" \"control-plane:host-context-controller" \"profiles:external-rest-api" \diff --cc mcp-host/package-lock.jsonindex 2e6a745ba,7f6e1cb32..13925ccfa--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-mcp-host",- "version": "0.1.288",- "version": "0.1.277",++ "version": "0.1.289","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.288",- "version": "0.1.277",++ "version": "0.1.289","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --cc mcp-host/package.jsonindex 23fe2b6f4,1908c8523..45e4d0aef--- a/mcp-host/package.json+++ b/mcp-host/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-mcp-host",- "version": "0.1.288",- "version": "0.1.277",++ "version": "0.1.289","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --cc tests/e2e/playwright/package-lock.jsonindex 0429aa18d,6c6c236b5..fcdb6cfb6--- a/tests/e2e/playwright/package-lock.json+++ b/tests/e2e/playwright/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-playwright-tests",- "version": "0.1.34",- "version": "0.1.21",++ "version": "0.1.35","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-playwright-tests",- "version": "0.1.34",- "version": "0.1.21",++ "version": "0.1.35","devDependencies": {"@playwright/test": "^1.50.0","@types/node": "^22.0.0"diff --cc tests/e2e/playwright/package.jsonindex 234fd06e7,23fc8d8a9..0d5b0dba7--- a/tests/e2e/playwright/package.json+++ b/tests/e2e/playwright/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-playwright-tests",- "version": "0.1.34",- "version": "0.1.21",++ "version": "0.1.35","private": true,"description": "Playwright E2E tests for Control UI and Desktop App","scripts": {