Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-ui): restore agent LLM secret editing and full-screen secret updates
Miguelon Peluchon97137d6fceec
diff --git a/control-ui/app/constants/routes.ts b/control-ui/app/constants/routes.tsindex 660d6cf4a..8528a930b 100644--- a/control-ui/app/constants/routes.ts+++ b/control-ui/app/constants/routes.ts@@ -124,6 +124,8 @@ export const CONTROL_ROUTES = {new: (query?: ControlRouteQuery) => withQuery('/secrets/new', query),editRecipe: (name: string, query?: ControlRouteQuery) =>withQuery(`/secrets/recipe/${segment(name)}/edit`, query),+ editLlm: (name: string, query?: ControlRouteQuery) =>+ withQuery(`/secrets/llm/${segment(name)}/edit`, query),},settings: {root: '/settings',diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsxindex 70bca45c8..7db25cb74 100644--- a/control-ui/app/hosts/[name]/page.tsx+++ b/control-ui/app/hosts/[name]/page.tsx@@ -22,7 +22,6 @@ import { HostOverviewTab } from '../../../components/HostOverviewTab'import { LlmProviderConfig } from '../../../components/LlmProviderConfig'import { LlmProviderSummary } from '../../../components/LlmProviderSummary'import { LlmSecretSelect, type LlmSecretSelectOption } from '../../../components/LlmSecretSelect'-import { LlmSecretUpdateModal } from '../../../components/LlmSecretUpdateModal'import { RowActionsMenu } from '../../../components/RowActionsMenu'import { IconRobot } from '../../../components/Sidebar/icons'import { IconMoreHorizontal, IconPencil, IconX } from '../../../components/icons'@@ -202,7 +201,6 @@ export default function HostDetailsPage() {const [initialLoading, setInitialLoading] = useState(true)const [editingModel, setEditingModel] = useState(false)- const [llmSecretModalOpen, setLlmSecretModalOpen] = useState(false)const [showDeleteAgentConfirm, setShowDeleteAgentConfirm] = useState(false)const [deletingAgent, setDeletingAgent] = useState(false)const [deleteAgentDialogError, setDeleteAgentDialogError] = useState('')@@ -280,10 +278,6 @@ export default function HostDetailsPage() {const [availableLlmSecrets, setAvailableLlmSecrets] = useState<HostSecretResource[]>([])// Fallback policy (spec §3-R5). `undefined` = the Host has no llmPolicy.const [llmPolicyDraft, setLlmPolicyDraft] = useState<LlmPolicy | undefined>(undefined)- // Keep the last server-backed policy separate from the editable draft. A- // model edit may contain an unsaved fallback slot, but Secret retirement- // must be guarded by the policy that is actually active on the Host.- const [persistedLlmPolicy, setPersistedLlmPolicy] = useState<LlmPolicy | undefined>(undefined)// Per-host model allowlist subset (spec.allowedModels, Topic 3a). Empty = the// host offers the full global allowlist per provider (back-compat default).const [allowedModelsDraft, setAllowedModelsDraft] = useState<HostAllowedModel[]>([])@@ -336,17 +330,6 @@ export default function HostDetailsPage() {allowedCatalog)}, [allowedModelsDraft, allowedCatalog, providerDraft, llmPolicyDraft])- const protectedCredentialSlots = useMemo(- () =>- Array.from(- new Set(- (persistedLlmPolicy?.fallbacks ?? [])- .map(fallback => String(fallback.credentialSlot || '').trim())- .filter(Boolean)- )- ),- [persistedLlmPolicy]- )// Mount race: if the host loaded before the allowlist and it had NO saved// model, loadData resolved the draft to '' — seed the default once the// catalog arrives. Never overrides a non-empty draft (a saved model that@@ -507,8 +490,6 @@ export default function HostDetailsPage() {const { host, contexts: contextsList, secrets: secretsList, agentUsers, agentTeams } = detailif (!mountedRef.current) returnconst spec = host.spec || {}- const nextPersistedLlmPolicy = normalizeLlmPolicy(spec.llmPolicy)- setPersistedLlmPolicy(nextPersistedLlmPolicy)// AP-6: remember the version of THIS read — the edit drafts below are// built from it, so it is the correct precondition for the eventual save.formResourceVersionRef.current = String(host.metadata?.resourceVersion || '')@@ -598,7 +579,7 @@ export default function HostDetailsPage() {(spec.model as { connectionRef?: string } | undefined)?.connectionRef || '').trim() || CODEX_UNASSIGNED_CONNECTION_KEY)- setLlmPolicyDraft(nextPersistedLlmPolicy)+ setLlmPolicyDraft(normalizeLlmPolicy(spec.llmPolicy))// 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))@@ -945,7 +926,30 @@ export default function HostDetailsPage() {setCodexModels([])setGrokModels([])setGrantCatalogError('')- if (isOauthBrokerProvider(providerDraft)) {+ // Secret → provider sync (mirrors HostWizard.handleExistingSecretChange and+ // an explicit provider switch): when the picked secret carries provider+ // credentials (the same metadata that renders the option's provider icons),+ // align the primary provider — and its default model — with it so the+ // pair stays coherent. A secret that already serves the current provider+ // keeps it (multi-provider secrets never clobber a coherent choice), and a+ // provider-less/custom secret never touches the operator's provider.+ const pickedProviders = (+ llmSecretOptions.find(option => option.value === parsed.name)?.providers ?? []+ )+ .map(provider => normalizeProvider(provider.id))+ .filter(provider => !isOauthBrokerProvider(provider))+ if (pickedProviders.length > 0) {+ if (!pickedProviders.includes(providerDraft)) {+ const nextProvider = pickedProviders[0]+ setProviderDraft(nextProvider)+ setModelNameDraft(+ resolveDefaultModel(+ nextProvider,+ constrainModelOptions(allowedCatalog, allowedModelsDraft, nextProvider)+ )+ )+ }+ } else if (isOauthBrokerProvider(providerDraft)) {setProviderDraft('openai')setModelNameDraft(resolveDefaultModel('openai', getModelOptions(allowedCatalog, 'openai')))}@@ -1087,57 +1091,78 @@ export default function HostDetailsPage() {await loadData('model')}- function renderModelCredentialFields(idPrefix: string, selectDisabled: boolean) {+ function renderModelCredentialFields(idPrefix: string, variant: 'summary' | 'editor') {+ const isEditor = variant === 'editor'+ // Static surfaces must not read as broken dropdowns: the summary renders a+ // read-only value display (no chrome, chevron, hover, or pointer cursor)+ // and no pencil — every editing affordance lives in the editor dialog.+ const assignmentValue = credentialSelectValue(+ showFallbackSecretField ? '' : secretRefDraft,+ connectionRefDraft,+ providerDraft === GROK_SUBSCRIPTION_PROVIDER+ ? GROK_SUBSCRIPTION_PROVIDER+ : 'codex-subscription'+ )+ const assignmentEditorPlaceholder = isBrokerAssignment+ ? isBrokerUnassigned+ ? 'No credential assigned'+ : assignedBrokerLabel+ : apiKeySecretOptions.length === 0+ ? 'No LLM Secret available'+ : 'Select an LLM Secret...'+ const assignmentSummaryPlaceholder = isBrokerAssignment+ ? isBrokerUnassigned+ ? 'No credential assigned'+ : assignedBrokerLabel+ : 'No LLM Secret assigned'+ const secretEditorPlaceholder =+ apiKeySecretOptions.length === 0 ? 'No LLM Secret available' : 'Select an LLM Secret...'+ function handleFallbackSecretChange(value: string) {+ const parsed = parseCredentialSelect(value)+ setSecretRefDraft(parsed.kind === 'secret' ? parsed.name : '')+ }+ // The pencil leaves this page for the full-screen secret editor. `from`+ // brings the operator back to this tab when the edit completes or is+ // cancelled — the editor dialog itself unmounts with the navigation.+ const renderPencil = () => (+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--toolbar"+ onClick={() =>+ router.push(+ CONTROL_ROUTES.secrets.editLlm(secretRefDraft.trim(), { from: hostTabHref('model') })+ )+ }+ disabled={busy || !secretRefDraft.trim()}+ aria-label="Edit LLM Secret credentials"+ title="Edit LLM Secret credentials"+ >+ <IconPencil width={16} height={16} />+ </button>+ )return (<><div className="cu-field">- <label htmlFor={`${idPrefix}-assignment`}>{credentialFieldLabel}</label>+ {isEditor ? (+ <label htmlFor={`${idPrefix}-assignment`}>{credentialFieldLabel}</label>+ ) : (+ <span className="cu-llm-summary__label">{credentialFieldLabel}</span>+ )}<div className="cu-llm-secret-control"><LlmSecretSelectid={`${idPrefix}-assignment`}- value={- showFallbackSecretField- ? credentialSelectValue(- '',- connectionRefDraft,- providerDraft === GROK_SUBSCRIPTION_PROVIDER- ? GROK_SUBSCRIPTION_PROVIDER- : 'codex-subscription'- )- : credentialSelectValue(- secretRefDraft,- connectionRefDraft,- providerDraft === GROK_SUBSCRIPTION_PROVIDER- ? GROK_SUBSCRIPTION_PROVIDER- : 'codex-subscription'- )- }+ value={assignmentValue}ariaLabel={credentialFieldLabel}- onChange={handleCredentialChange}options={llmSecretOptions}- placeholder={- isBrokerAssignment- ? isBrokerUnassigned- ? 'No credential assigned'- : assignedBrokerLabel- : apiKeySecretOptions.length === 0- ? 'No LLM Secret available'- : 'Select an LLM Secret...'- }- disabled={selectDisabled}+ {...(isEditor+ ? {+ onChange: handleCredentialChange,+ disabled: busy,+ placeholder: assignmentEditorPlaceholder,+ }+ : { readOnly: true, placeholder: assignmentSummaryPlaceholder })}/>- {showFallbackSecretField ? null : (- <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>- )}+ {isEditor && !showFallbackSecretField ? renderPencil() : null}</div><span className="cu-field__hint">{showFallbackSecretField@@ -1149,34 +1174,26 @@ export default function HostDetailsPage() {</div>{showFallbackSecretField ? (<div className="cu-field">- <label htmlFor={`${idPrefix}-fallback`}>LLM Secret</label>+ {isEditor ? (+ <label htmlFor={`${idPrefix}-fallback`}>LLM Secret</label>+ ) : (+ <span className="cu-llm-summary__label">LLM Secret</span>+ )}<div className="cu-llm-secret-control"><LlmSecretSelectid={`${idPrefix}-fallback`}value={secretRefDraft}ariaLabel="LLM Secret"- onChange={value => {- const parsed = parseCredentialSelect(value)- setSecretRefDraft(parsed.kind === 'secret' ? parsed.name : '')- }}options={apiKeySecretOptions}- placeholder={- apiKeySecretOptions.length === 0- ? 'No LLM Secret available'- : 'Select an LLM Secret...'- }- disabled={selectDisabled}+ {...(isEditor+ ? {+ onChange: handleFallbackSecretChange,+ disabled: busy,+ placeholder: secretEditorPlaceholder,+ }+ : { readOnly: true, placeholder: 'No LLM Secret assigned' })}/>- <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>+ {isEditor ? renderPencil() : null}</div><span className="cu-field__hint">Needed for the {fallbackSecretLabels.join(', ') || 'static'} fallback@@ -1408,7 +1425,7 @@ export default function HostDetailsPage() {{!editingModel ? (<div className="cu-form-stack cu-form-stack--wide">- {renderModelCredentialFields('model-secret-summary', true)}+ {renderModelCredentialFields('model-secret-summary', 'summary')}<LlmProviderSummaryprovider={providerDraft}model={modelNameDraft}@@ -1453,10 +1470,10 @@ export default function HostDetailsPage() {}onDismiss={() => void cancelModelEdit()}open={editingModel}- size="default"- title="Edit model configuration"+ title="Edit model & credentials"><div className="cu-form-stack cu-form-stack--wide">+ {renderModelCredentialFields('model-secret-editor', 'editor')}<LlmProviderConfigprovider={providerDraft}model={modelNameDraft}@@ -1483,24 +1500,14 @@ export default function HostDetailsPage() {catalogError={modelsError}modelLabel="Current model"secretKeys={currentSecretKeys}+ // Fallbacks are opt-in: the section starts collapsed so the+ // dialog leads with the primary provider + credentials.+ fallbackProvidersInitiallyCollapseddisabled={busy}grokEnabled={grokEnabled}/></div></DialogShell>-- {llmSecretModalOpen && secretRefDraft.trim() ? (- <LlmSecretUpdateModal- key={secretRefDraft}- secretName={secretRefDraft}- existingKeys={currentSecretKeys}- protectedCredentialSlots={protectedCredentialSlots}- onClose={() => setLlmSecretModalOpen(false)}- onChanged={async () => {- await loadData('none')- }}- />- ) : null}</>)}diff --git a/control-ui/app/secrets/llm/[name]/edit/__tests__/page.test.tsx b/control-ui/app/secrets/llm/[name]/edit/__tests__/page.test.tsxnew file mode 100644index 000000000..ebdb35287--- /dev/null+++ b/control-ui/app/secrets/llm/[name]/edit/__tests__/page.test.tsx@@ -0,0 +1,425 @@+import React from 'react'+import type { ReactNode } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import {+ cleanup,+ fireEvent,+ render as rtlRender,+ screen,+ waitFor,+ within,+} from '@testing-library/react'+import { ToastProvider } from '@components/Toast'+import { apiSend, getHosts, listLlmHostSecrets } from '@lib/api'+import EditLlmSecretPage from '../page'++const navigation = vi.hoisted(() => ({+ params: { name: 'chatllm-api-keys' },+ push: vi.fn(),+ searchParams: new URLSearchParams(),+}))++vi.mock('next/navigation', () => ({+ useParams: () => navigation.params,+ useRouter: () => ({ push: navigation.push }),+ useSearchParams: () => navigation.searchParams,+}))++vi.mock('next/link', () => ({+ default: ({ children, href, ...props }: { children: ReactNode; href: string }) => (+ <a href={href} {...props}>+ {children}+ </a>+ ),+}))++vi.mock('@components/AuthGate', () => ({+ AuthGate: ({ children }: { children: ReactNode }) => <>{children}</>,+}))++vi.mock('@components/DashboardLayout', () => ({+ DashboardLayout: ({ children }: { children: ReactNode }) => <main>{children}</main>,+}))++vi.mock('@lib/api', async () => {+ const actual = await vi.importActual<typeof import('@lib/api')>('@lib/api')+ return {+ ...actual,+ apiSend: vi.fn(),+ getHosts: vi.fn(),+ listLlmHostSecrets: vi.fn(),+ }+})++const apiSendMock = vi.mocked(apiSend)+const getHostsMock = vi.mocked(getHosts)+const listLlmHostSecretsMock = vi.mocked(listLlmHostSecrets)++const SECRET = 'chatllm-api-keys'++function seedSecret(keys: string[]) {+ listLlmHostSecretsMock.mockResolvedValue({ items: [{ name: SECRET, keys }] })+}++function seedHosts(hosts: Array<{ name: string; secretRef?: string; fallbackSlot?: string }> = []) {+ getHostsMock.mockResolvedValue({+ items: hosts.map(host => ({+ metadata: { name: host.name },+ spec: {+ ...(host.secretRef ? { secretRef: host.secretRef } : {}),+ ...(host.fallbackSlot+ ? {+ llmPolicy: {+ fallbacks: [+ {+ provider: 'claude',+ model: 'claude-sonnet-4-6',+ credentialSlot: host.fallbackSlot,+ },+ ],+ },+ }+ : {}),+ },+ })),+ })+}++async function renderEditor() {+ rtlRender(+ <ToastProvider>+ <EditLlmSecretPage />+ </ToastProvider>+ )+ await screen.findByRole('button', { name: 'Update secret' })+}++const sectionFor = (label: string) =>+ screen.getByText(label, { selector: '.cu-llm-cred-group__title' }).closest('section')!++const removeExtraSlotIn = (label: string) =>+ fireEvent.click(+ within(sectionFor(label)).getByRole('button', { name: 'Remove extra credential slot' })+ )++const save = () => fireEvent.click(screen.getByRole('button', { name: 'Update secret' }))++const replaceOpenAiKey = () =>+ fireEvent.click(screen.getByRole('button', { name: 'Replace OpenAI API key' }))++// Retirement is irreversible, so the save goes through a danger confirm.+async function resolveRemovalConfirm(action: 'Remove and save' | 'Cancel') {+ const dialog = await screen.findByRole('alertdialog')+ fireEvent.click(within(dialog).getByRole('button', { name: action }))+}++beforeEach(() => {+ vi.clearAllMocks()+ navigation.params = { name: SECRET }+ navigation.searchParams = new URLSearchParams()+ apiSendMock.mockResolvedValue(undefined as never)+ seedHosts([])+})++afterEach(() => {+ cleanup()+})++describe('Edit LLM secret page — loading', () => {+ it('loads the named secret and renders the full-screen editor', async () => {+ seedSecret(['openai-api-key', 'claude-api-key'])+ await renderEditor()++ expect(screen.getByRole('heading', { name: `Edit LLM secret: ${SECRET}` })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Replace OpenAI API key' })).toBeInTheDocument()+ expect(listLlmHostSecretsMock).toHaveBeenCalled()+ expect(getHostsMock).toHaveBeenCalled()+ })++ it('fails closed with an error banner when the Host read fails', async () => {+ seedSecret(['openai-api-key'])+ getHostsMock.mockRejectedValue(new Error('hosts unavailable'))++ rtlRender(+ <ToastProvider>+ <EditLlmSecretPage />+ </ToastProvider>+ )++ expect(await screen.findByText('hosts unavailable')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Update secret' })).not.toBeInTheDocument()+ expect(apiSendMock).not.toHaveBeenCalled()+ })++ it('reports a secret that no longer exists', async () => {+ seedSecret([])+ listLlmHostSecretsMock.mockResolvedValue({ items: [] })+ seedHosts([])++ rtlRender(+ <ToastProvider>+ <EditLlmSecretPage />+ </ToastProvider>+ )++ expect(await screen.findByText(SECRET, { selector: 'code' })).toBeInTheDocument()+ expect(screen.getByText(/was not found\./)).toBeInTheDocument()+ })+})++describe('Edit LLM secret page — navigation', () => {+ it('returns to the LLM secrets list by default', async () => {+ seedSecret(['openai-api-key'])+ await renderEditor()++ fireEvent.click(screen.getByRole('button', { name: 'Back to secrets' }))++ expect(navigation.push).toHaveBeenCalledWith('/secrets/llm')+ })++ it('honors an internal from path and returns to it', async () => {+ seedSecret(['openai-api-key'])+ navigation.searchParams = new URLSearchParams({ from: '/agents/foo/model' })+ await renderEditor()++ fireEvent.click(screen.getByRole('button', { name: 'Back to secrets' }))++ expect(navigation.push).toHaveBeenCalledWith('/agents/foo/model')+ })++ it('ignores a non-internal from value', async () => {+ seedSecret(['openai-api-key'])+ navigation.searchParams = new URLSearchParams({ from: 'https://evil.example' })+ await renderEditor()++ fireEvent.click(screen.getByRole('button', { name: 'Back to secrets' }))++ expect(navigation.push).toHaveBeenCalledWith('/secrets/llm')+ })++ it('navigates back after a successful save', async () => {+ seedSecret(['openai-api-key'])+ navigation.searchParams = new URLSearchParams({ from: '/agents/foo/model' })+ await renderEditor()++ replaceOpenAiKey()+ fireEvent.change(screen.getByLabelText(/^OpenAI API key/i), { target: { value: 'sk-live' } })+ save()++ await waitFor(() => {+ expect(apiSendMock).toHaveBeenCalledWith('PUT', '/api/v1/admin/secrets', {+ name: SECRET,+ merge: true,+ stringData: { 'openai-api-key': 'sk-live' },+ })+ })+ await waitFor(() => expect(navigation.push).toHaveBeenCalledWith('/agents/foo/model'))+ })+})++// The editor on this page is the only surface that can retire a stored data+// key. These assert the WRITE it produces: without `removeKeys` in the payload+// the key disappears from the editor while surviving in the Secret.+describe('Edit LLM secret page — update payload', () => {+ it('sends removeKeys for a retire-only edit once the removal is confirmed', async () => {+ seedSecret(['claude-api-key-fb1', 'openai-api-key'])+ await renderEditor()+ removeExtraSlotIn('Anthropic')+ save()++ // Nothing is written until the operator confirms.+ await resolveRemovalConfirm('Remove and save')++ await waitFor(() => {+ expect(apiSendMock).toHaveBeenCalledWith('PUT', '/api/v1/admin/secrets', {+ name: SECRET,+ merge: true,+ stringData: {},+ removeKeys: ['claude-api-key-fb1'],+ })+ })+ // Retiring a key IS an edit: the "provide at least one API key" gate must+ // not swallow it.+ expect(screen.queryAllByText(/Provide at least one API key/i)).toHaveLength(0)+ })++ it('writes nothing when the removal confirmation is cancelled', async () => {+ seedSecret(['claude-api-key-fb1', 'openai-api-key'])+ await renderEditor()+ removeExtraSlotIn('Anthropic')+ save()++ await resolveRemovalConfirm('Cancel')++ await waitFor(() => {+ expect(screen.queryByRole('alertdialog')).toBeNull()+ })+ expect(apiSendMock).not.toHaveBeenCalled()+ // The edit is still open and still queued — cancelling the confirm is not+ // cancelling the edit.+ expect(screen.getByRole('button', { name: 'Update secret' })).toBeInTheDocument()+ })++ it('sends written values and retired keys in the same merge write', async () => {+ seedSecret(['claude-api-key-fb1', 'openai-api-key'])+ await renderEditor()+ replaceOpenAiKey()+ fireEvent.change(screen.getByLabelText(/^OpenAI API key/i), { target: { value: 'sk-live' } })+ removeExtraSlotIn('Anthropic')+ save()+ await resolveRemovalConfirm('Remove and save')++ await waitFor(() => {+ expect(apiSendMock).toHaveBeenCalledWith('PUT', '/api/v1/admin/secrets', {+ name: SECRET,+ merge: true,+ stringData: { 'openai-api-key': 'sk-live' },+ removeKeys: ['claude-api-key-fb1'],+ })+ })+ })++ it('omits removeKeys — and the confirm — when nothing was retired', async () => {+ seedSecret(['openai-api-key'])+ await renderEditor()+ replaceOpenAiKey()+ fireEvent.change(screen.getByLabelText(/^OpenAI API key/i), { target: { value: 'sk-live' } })+ save()++ await waitFor(() => {+ expect(apiSendMock).toHaveBeenCalledWith('PUT', '/api/v1/admin/secrets', {+ name: SECRET,+ merge: true,+ stringData: { 'openai-api-key': 'sk-live' },+ })+ })+ expect(screen.queryByRole('alertdialog')).toBeNull()+ })++ it('writes the key instead of retiring it when a removed slot is re-created', async () => {+ // End-to-end of the delete-then-recreate hole: the payload must WRITE+ // claude-api-key-fb1, never retire it — retirement-wins server-side would+ // otherwise delete the key and discard the value typed for it.+ seedSecret(['claude-api-key-fb1', 'openai-api-key'])+ await renderEditor()+ removeExtraSlotIn('Anthropic')+ fireEvent.click(+ within(sectionFor('Anthropic')).getByRole('button', { name: /Add credential slot/i })+ )+ const anthropic = sectionFor('Anthropic')+ fireEvent.change(within(anthropic).getByLabelText(/Extra credential slot key name/i), {+ target: { value: 'claude-api-key-fb1' },+ })+ fireEvent.change(within(anthropic).getByLabelText(/Extra credential slot value/i), {+ target: { value: 'sk-ant-new' },+ })+ save()++ await waitFor(() => {+ expect(apiSendMock).toHaveBeenCalledWith('PUT', '/api/v1/admin/secrets', {+ name: SECRET,+ merge: true,+ stringData: { 'claude-api-key-fb1': 'sk-ant-new' },+ })+ })+ // No retirement left to confirm.+ expect(screen.queryByRole('alertdialog')).toBeNull()+ })++ it('blocks retiring every stored key instead of letting the server 400', async () => {+ seedSecret(['claude-api-key-fb1'])+ await renderEditor()+ removeExtraSlotIn('Anthropic')+ save()++ await waitFor(() => {+ expect(+ screen.getAllByText(/Removing every key would leave the secret empty/i).length+ ).toBeGreaterThan(0)+ })+ // Refused before the confirm — no point asking about a write that cannot+ // succeed.+ expect(screen.queryByRole('alertdialog')).toBeNull()+ expect(apiSendMock).not.toHaveBeenCalled()+ })++ it('still blocks a save that neither writes nor retires anything', async () => {+ seedSecret(['openai-api-key'])+ await renderEditor()+ save()++ expect(screen.getAllByText(/Provide at least one API key/i).length).toBeGreaterThan(0)+ expect(apiSendMock).not.toHaveBeenCalled()+ })++ it('starts from a clean draft on a fresh visit to the route', async () => {+ // Regression guard (route edition): a stale `removedKeys` from a previous+ // visit must not delete keys on the next one. Each navigation remounts the+ // page, so the second visit begins empty.+ seedSecret(['claude-api-key-fb1', 'openai-api-key'])+ const first = rtlRender(+ <ToastProvider>+ <EditLlmSecretPage />+ </ToastProvider>+ )+ await screen.findByRole('button', { name: 'Update secret' })+ removeExtraSlotIn('Anthropic')+ first.unmount()+ cleanup()++ await renderEditor()+ replaceOpenAiKey()+ fireEvent.change(screen.getByLabelText(/^OpenAI API key/i), { target: { value: 'sk-live' } })+ save()++ await waitFor(() => {+ expect(apiSendMock).toHaveBeenCalledWith('PUT', '/api/v1/admin/secrets', {+ name: SECRET,+ merge: true,+ stringData: { 'openai-api-key': 'sk-live' },+ })+ })+ expect(screen.queryByRole('alertdialog')).toBeNull()+ })+})++describe('Edit LLM secret page — fallback credential slot guard', () => {+ it('blocks removing a stored slot still referenced by a Host fallback policy', async () => {+ const fallbackSlot = 'claude-api-key-fb1'+ seedSecret(['openai-api-key', fallbackSlot])+ // The guard scans every Host, not just the linking surface's: any Host+ // whose secretRef points at this Secret contributes protected slots.+ seedHosts([+ { name: 'foo', secretRef: SECRET, fallbackSlot },+ { name: 'unrelated', secretRef: 'another-secret' },+ ])++ await renderEditor()+ removeExtraSlotIn('Anthropic')+ save()++ expect(+ await screen.findByText(+ new RegExp(`Cannot remove "${fallbackSlot}".*active fallback.*credential slot`)+ )+ ).toBeInTheDocument()+ expect(+ apiSendMock.mock.calls.some(args => args[0] === 'PUT' && args[1] === '/api/v1/admin/secrets')+ ).toBe(false)+ })+})++describe('Edit LLM secret page — additional provider credentials', () => {+ it('adds another provider section from the Add provider picker', async () => {+ seedSecret(['openai-api-key'])+ await renderEditor()++ fireEvent.click(screen.getByLabelText('Add provider'))+ fireEvent.click(screen.getByRole('option', { name: 'Anthropic' }))++ expect(+ screen.getByText('Anthropic', { selector: '.cu-llm-cred-group__title' })+ ).toBeInTheDocument()+ expect(screen.getByLabelText(/Claude API key/i)).toBeInTheDocument()+ })+})diff --git a/control-ui/app/secrets/llm/[name]/edit/page.tsx b/control-ui/app/secrets/llm/[name]/edit/page.tsxnew file mode 100644index 000000000..dd65a5e94--- /dev/null+++ b/control-ui/app/secrets/llm/[name]/edit/page.tsx@@ -0,0 +1,162 @@+'use client'++import React, { Suspense, useEffect, useMemo, useState } from 'react'+import { useParams, useRouter, useSearchParams } from 'next/navigation'+import { AuthGate } from '@components/AuthGate'+import { BodyLoadingSkeleton, FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'+import { CreatePageHeader } from '@components/CreatePageHeader'+import { DashboardLayout } from '@components/DashboardLayout'+import { LlmSecretEditor } from '@components/LlmSecretEditor'+import { IconKey } from '@components/Sidebar/icons'+import { CONTROL_ROUTES } from '@constants/routes'+import { getHosts, listLlmHostSecrets } from '@lib/api'+import { normalizeLlmPolicy } from '@lib/llm'++// Credential slots (Secret data-key names) that persisted Host fallback+// policies still reference through this Secret. Retiring one would break a+// live fallback, so the editor refuses the removal upfront. Scanning every+// Host keeps the guard whole regardless of which surface linked here — the+// list flow previously shipped without it because the table had no Host data.+function collectProtectedCredentialSlots(+ hosts: Awaited<ReturnType<typeof getHosts>>['items'],+ secretName: string+): string[] {+ const slots = new Set<string>()+ for (const host of hosts ?? []) {+ const spec = (host.spec ?? {}) as Record<string, unknown>+ if (String(spec.secretRef || '').trim() !== secretName) continue+ for (const fallback of normalizeLlmPolicy(spec.llmPolicy)?.fallbacks ?? []) {+ const slot = String(fallback.credentialSlot || '').trim()+ if (slot) slots.add(slot)+ }+ }+ return Array.from(slots)+}++function EditLlmSecretContent() {+ const router = useRouter()+ const params = useParams<{ name: string }>()+ const searchParams = useSearchParams()+ const secretName = useMemo(() => {+ const raw = params?.name+ const value = Array.isArray(raw) ? raw[0] : raw+ try {+ return decodeURIComponent(value ?? '')+ } catch {+ return value ?? ''+ }+ }, [params])++ // Optional return context for flows that linked here from another surface+ // (the agent Models & creds editor). Only same-app paths are honored so the+ // param can never aim the back action off-site.+ const fromParam = (searchParams.get('from') ?? '').trim()+ const backTarget =+ fromParam.startsWith('/') && !fromParam.startsWith('//')+ ? fromParam+ : CONTROL_ROUTES.secrets.llm++ const [loading, setLoading] = useState(true)+ const [loadError, setLoadError] = useState('')+ const [notFound, setNotFound] = useState(false)+ const [existingKeys, setExistingKeys] = useState<string[]>([])+ const [protectedCredentialSlots, setProtectedCredentialSlots] = useState<string[]>([])++ useEffect(() => {+ let cancelled = false+ if (!secretName) {+ setLoadError('Missing secret name in URL.')+ setLoading(false)+ return+ }+ void (async () => {+ try {+ // Fail closed: the fallback-slot guard is only sound when the Host+ // read succeeds, so a failed listing blocks editing instead of+ // silently shipping an unguarded retirement surface.+ const [secretsRes, hostsRes] = await Promise.all([listLlmHostSecrets(), getHosts()])+ if (cancelled) return+ const match = (secretsRes.items ?? []).find(+ secret => String(secret.name || '').trim() === secretName+ )+ if (!match) {+ setNotFound(true)+ setLoading(false)+ return+ }+ setExistingKeys(Array.isArray(match.keys) ? match.keys : [])+ setProtectedCredentialSlots(collectProtectedCredentialSlots(hostsRes.items, secretName))+ setLoading(false)+ } catch (e) {+ if (cancelled) return+ setLoadError(e instanceof Error ? e.message : 'Failed to load LLM secret')+ setLoading(false)+ }+ })()+ return () => {+ cancelled = true+ }+ }, [secretName])++ function goBack() {+ router.push(backTarget)+ }++ return (+ <AuthGate>+ <DashboardLayout isDetailPage>+ <CreatePageHeader+ icon={<IconKey />}+ title={`Edit LLM secret${secretName ? `: ${secretName}` : ''}`}+ subtitle="Stored values are never returned by the API. Type a new value to overwrite a key, or remove it to delete that key on save."+ backLabel="Back to secrets"+ onBack={goBack}+ />++ <div className="cu-create-panel">+ <div className="cu-create-content">+ {loading ? (+ <FormSectionsSkeleton+ label="LLM secret"+ primaryActionLabel="Update secret"+ sections={2}+ />+ ) : loadError ? (+ <div className="cu-banner cu-banner--error">{loadError}</div>+ ) : notFound ? (+ <div className="cu-banner cu-banner--error">+ LLM secret <code>{secretName}</code> was not found.+ </div>+ ) : (+ <LlmSecretEditor+ secretName={secretName}+ existingKeys={existingKeys}+ protectedCredentialSlots={protectedCredentialSlots}+ onClose={goBack}+ />+ )}+ </div>+ </div>+ </DashboardLayout>+ </AuthGate>+ )+}++export default function EditLlmSecretPage() {+ return (+ <Suspense+ fallback={+ <BodyLoadingSkeleton+ backLabel="Back to secrets"+ icon={<IconKey />}+ primaryActionLabel="Update secret"+ sections={2}+ subtitle="Load the saved key metadata before editing stored values."+ title="Edit LLM secret"+ />+ }+ >+ <EditLlmSecretContent />+ </Suspense>+ )+}diff --git a/control-ui/components/LlmSecretUpdateModal.tsx b/control-ui/components/LlmSecretEditor/index.tsxsimilarity index 53%rename from control-ui/components/LlmSecretUpdateModal.tsxrename to control-ui/components/LlmSecretEditor/index.tsxindex 7fdea3640..21e733984 100644--- a/control-ui/components/LlmSecretUpdateModal.tsx+++ b/control-ui/components/LlmSecretEditor/index.tsx@@ -1,21 +1,15 @@'use client'import { useState } from 'react'-import { apiSend } from '../lib/api'-import { createEmptyLlmKeyDraft, validateLlmSecretData } from '../lib/llm'-import { useConfirmDialog } from './ConfirmDialog'-import { LlmCredentialFields } from './LlmCredentialFields'-import { useToast } from './Toast'-import { IconX } from './icons'+import { Button } from '@components/ui'+import { apiSend } from '@lib/api'+import { createEmptyLlmKeyDraft, validateLlmSecretData } from '@lib/llm'+import { useConfirmDialog } from '../ConfirmDialog'+import { LlmCredentialFields } from '../LlmCredentialFields'+import { useToast } from '../Toast'+import type { LlmSecretEditorProps } from './types'-export type LlmSecretUpdateModalProps = {- secretName: string- existingKeys: string[]- /** Credential slots still referenced by persisted Host fallback policies. */- protectedCredentialSlots?: string[]- onClose: () => void- onChanged: () => Promise<void>-}+export type { LlmSecretEditorProps } from './types'/*** The single update surface for an LLM Secret.@@ -25,13 +19,12 @@ export type LlmSecretUpdateModalProps = {* write and retirement logic here means every entry point gets the same safe* merge semantics and the same provider editor.*/-export function LlmSecretUpdateModal({+export function LlmSecretEditor({secretName,existingKeys,protectedCredentialSlots = [],onClose,- onChanged,-}: LlmSecretUpdateModalProps) {+}: LlmSecretEditorProps) {const { confirm, confirmDialog } = useConfirmDialog()const { showToast } = useToast()const [keyDraft, setKeyDraft] = useState<Record<string, string>>(() => createEmptyLlmKeyDraft())@@ -39,7 +32,7 @@ export function LlmSecretUpdateModal({const [saving, setSaving] = useState(false)const [error, setError] = useState('')- function closeModal() {+ function cancel() {if (!saving) onClose()}@@ -114,7 +107,6 @@ export function LlmSecretUpdateModal({...(removeKeys.length > 0 ? { removeKeys } : {}),})showToast(`Secret ${normalizedSecretName} updated.`, { tone: 'success' })- await onChanged()onClose()} catch (e) {setError(e instanceof Error ? e.message : 'Failed to save secret')@@ -125,83 +117,38 @@ export function LlmSecretUpdateModal({return (<>- <div- style={{- position: 'fixed',- inset: 0,- background: 'var(--cu-overlay)',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- zIndex: 1000,- padding: '1rem',- }}- role="presentation"- onClick={event => {- if (event.target === event.currentTarget) closeModal()- }}- >- <div- className="cu-modal-panel"- role="dialog"- aria-modal="true"- aria-labelledby="llm-secret-title"- onClick={event => event.stopPropagation()}- >- <div className="cu-modal-panel__head">- <strong id="llm-secret-title" style={{ fontSize: '1rem', lineHeight: 1.35 }}>- Update LLM secret {secretName.trim()}- </strong>- <button- type="button"- className="cu-btn cu-btn--icon cu-btn--ghost"- onClick={closeModal}- disabled={saving}- aria-label="Close"- >- <IconX width={18} height={18} />- </button>- </div>-- <div className="cu-form-stack" style={{ maxWidth: '100%' }}>- <p className="cu-field__hint">- Updates the listed keys and deletes the ones you remove here; every other key already- stored in this secret is preserved.- </p>- <LlmCredentialFields- draft={keyDraft}- onChange={(dataKey, value) => setKeyDraft(prev => ({ ...prev, [dataKey]: value }))}- existingKeys={existingKeys}- // The editor reports on every change. Keep the parent state- // identity-stable so it does not cause an unnecessary rerender.- onRemovedKeysChange={next =>- setRemovedKeys(prev => (prev.join('\n') === next.join('\n') ? prev : next))- }- disabled={saving}- pickerInline- />- </div>-- {error ? <div className="cu-banner cu-banner--error">{error}</div> : null}-- <div className="cu-modal-panel__foot">- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- onClick={closeModal}- disabled={saving}- >- Cancel- </button>- <button- type="button"- className="cu-btn cu-btn--primary"- onClick={() => void saveSecret()}- disabled={saving}- >- {saving ? 'Saving…' : 'Update secret'}- </button>- </div>+ <div className="cu-form-stack" style={{ maxWidth: '100%' }}>+ <p className="cu-field__hint">+ Updates the listed keys and deletes the ones you remove here; every other key already+ stored in this secret is preserved.+ </p>+ <LlmCredentialFields+ draft={keyDraft}+ onChange={(dataKey, value) => setKeyDraft(prev => ({ ...prev, [dataKey]: value }))}+ existingKeys={existingKeys}+ // The editor reports on every change. Keep the parent state+ // identity-stable so it does not cause an unnecessary rerender.+ onRemovedKeysChange={next =>+ setRemovedKeys(prev => (prev.join('\n') === next.join('\n') ? prev : next))+ }+ disabled={saving}+ />++ {error ? <div className="cu-banner cu-banner--error">{error}</div> : null}++ <div className="cu-create-actions">+ <Button type="button" variant="ghost" size="sm" onClick={cancel} disabled={saving}>+ Cancel+ </Button>+ <Button+ type="button"+ variant="primary"+ size="sm"+ onClick={() => void saveSecret()}+ disabled={saving}+ >+ {saving ? 'Saving…' : 'Update secret'}+ </Button></div></div>{confirmDialog}diff --git a/control-ui/components/LlmSecretEditor/types.ts b/control-ui/components/LlmSecretEditor/types.tsnew file mode 100644index 000000000..df4fd8c0f--- /dev/null+++ b/control-ui/components/LlmSecretEditor/types.ts@@ -0,0 +1,11 @@+export type LlmSecretEditorProps = {+ secretName: string+ existingKeys: string[]+ /** Credential slots still referenced by persisted Host fallback policies. */+ protectedCredentialSlots?: string[]+ /**+ * Called when the operator cancels or a save completes successfully. The+ * owning surface (route page) owns navigation; the editor owns the write.+ */+ onClose: () => void+}diff --git a/control-ui/components/LlmSecretSelect/index.tsx b/control-ui/components/LlmSecretSelect/index.tsxindex ea5f8304c..5ef715e80 100644--- a/control-ui/components/LlmSecretSelect/index.tsx+++ b/control-ui/components/LlmSecretSelect/index.tsx@@ -42,11 +42,30 @@ export function LlmSecretSelect({onChange,options,placeholder,+ readOnly = false,value,}: LlmSecretSelectProps) {const [open, setOpen] = useState(false)const selectedOption = options.find(option => option.value === value)+ // Read-only presentation: the same selected-option content (label, provider+ // icons or meta) as the picker, rendered as a static value box with no+ // dropdown chrome, hover affordance, or pointer cursor.+ if (readOnly) {+ return (+ <div id={id} className={cn('cu-agent-select cu-agent-select--readonly', className)}>+ <div className="cu-llm-summary__value" aria-label={ariaLabel}>+ <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}+ </div>+ </div>+ )+ }+return (<divclassName={cn('cu-agent-select', className)}@@ -93,7 +112,7 @@ export function LlmSecretSelect({role="option"aria-selected={value === option.value}onClick={() => {- onChange(option.value)+ onChange?.(option.value)setOpen(false)}}>diff --git a/control-ui/components/LlmSecretSelect/types.ts b/control-ui/components/LlmSecretSelect/types.tsindex 2ec6a468c..0f3b6c2fd 100644--- a/control-ui/components/LlmSecretSelect/types.ts+++ b/control-ui/components/LlmSecretSelect/types.ts@@ -18,8 +18,15 @@ export type LlmSecretSelectProps = {className?: stringdisabled?: booleanid?: string- onChange: (value: string) => void+ /** Only used by the interactive variant; ignored when `readOnly` is set. */+ onChange?: (value: string) => voidoptions: LlmSecretSelectOption[]placeholder: string+ /**+ * Static presentation for read-only surfaces: renders the selected option+ * (label + provider icons or meta) as a plain value display — no button,+ * chevron, hover, or menu. Interactive behavior is unchanged when unset.+ */+ readOnly?: booleanvalue: string}diff --git a/control-ui/components/SecretsTable.tsx b/control-ui/components/SecretsTable.tsxindex e71d07150..3c585242b 100644--- a/control-ui/components/SecretsTable.tsx+++ b/control-ui/components/SecretsTable.tsx@@ -23,7 +23,6 @@ import { getProviderLabel, getProvidersWithCompleteCredentials } from '../lib/llimport { collectWorkflowRecipeSecretRefs } from '../lib/workflowRecipeSecretRefs'import { useConfirmDialog } from './ConfirmDialog'import { LlmProviderIcon } from './LlmProviderIcon'-import { LlmSecretUpdateModal } from './LlmSecretUpdateModal'import { RowActionsMenu } from './RowActionsMenu'import { SecretsScopeTabs } from './SecretsScopeTabs'import { SectionSearchInput } from './SectionSearchInput'@@ -103,7 +102,6 @@ export function SecretsTable({}, [activeScope])// LLM secrets state- const [editingName, setEditingName] = useState('')const [deletingName, setDeletingName] = useState<string | null>(null)const [error, setError] = useState('')const [llmSearchQuery, setLlmSearchQuery] = useState('')@@ -129,8 +127,8 @@ export function SecretsTable({.sort((a, b) => a.localeCompare(b)),[items])- // Secret name -> stored data-key names, so the update modal can light up the- // "present" chips for the row being edited (names only, never values).+ // Secret name -> stored data-key names, so the provider chips can report+ // which credentials each secret holds (names only, never values).const keysByName = useMemo(() => {const map = new Map<string, string[]>()for (const item of items) {@@ -205,7 +203,7 @@ export function SecretsTable({})function openUpdate(name: string) {- setEditingName(name)+ router.push(CONTROL_ROUTES.secrets.editLlm(name))}async function loadMcpSecretReferences() {@@ -886,15 +884,6 @@ export function SecretsTable({) : null}</div>- {editingName ? (- <LlmSecretUpdateModal- key={editingName}- secretName={editingName}- existingKeys={keysByName.get(editingName) ?? []}- onClose={() => setEditingName('')}- onChanged={onChanged}- />- ) : null}{confirmDialog}</>)diff --git a/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx b/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsxindex 9055d5b99..6a72e19c0 100644--- a/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx+++ b/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx@@ -314,15 +314,23 @@ describe('HostDetailsPage current model and credential flow', () => {setupApiMocks(formLoadHost, refetchedHost)})- it('opens the linked LLM Secret editor without navigating or saving the Host', async () => {+ it('navigates from the model editor pencil to the full-screen secret editor without saving the Host', async () => {const view = render(<HostDetailsPage />)navigateToTab(view, 'model')expect(await screen.findByText('Current model')).toBeInTheDocument()- fireEvent.click(screen.getByRole('button', { name: 'Edit LLM Secret credentials' }))+ // No pencil on the read-only summary — editing affordances live in the dialog.+ expect(+ screen.queryByRole('button', { name: 'Edit LLM Secret credentials' })+ ).not.toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })+ fireEvent.click(within(dialog).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()+ // The secret editor is a full-screen route; `from` returns to this tab.+ expect(pushMock).toHaveBeenCalledWith(+ '/secrets/llm/openai-secret/edit?from=%2Fagents%2Ffoo%2Fmodel'+ )+ // Nothing is written to the Host by opening the secret editor.expect((api.apiSend as unknown as ReturnType<typeof vi.fn>).mock.calls.some(args => args[0] === 'PUT' && args[1] === '/api/v1/admin/hosts/foo'@@ -334,17 +342,28 @@ describe('HostDetailsPage current model and credential flow', () => {const view = render(<HostDetailsPage />)navigateToTab(view, 'model')expect(await screen.findByText('Current model')).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Edit LLM Secret credentials' })).toBeInTheDocument()+ // Summary = static display: shows the linked secret, no dropdown button, no pencil.+ expect(screen.getByText('openai-secret')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'LLM Secret' })).not.toBeInTheDocument()+ expect(+ screen.queryByRole('button', { name: 'Edit LLM Secret credentials' })+ ).not.toBeInTheDocument()fireEvent.click(screen.getByRole('button', { name: 'Edit' }))- const dialog = await screen.findByRole('dialog', { name: 'Edit model configuration' })- expect(dialog).toHaveClass('eft-dialog--default')+ const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })+ // Compact default shell: the 35rem content stack (.cu-form-stack--wide)+ // fills the base 34rem dialog edge to edge — no large-size dead space.+ expect(dialog).not.toHaveClass('eft-dialog--large')+ expect(dialog).not.toHaveClass('cu-model-creds-dialog')+ expect(dialog).toHaveClass('eft-dialog')expect(within(dialog).getByRole('region', { name: 'LLM configuration' })).toBeInTheDocument()- expect(within(dialog).queryByLabelText('Credential')).not.toBeInTheDocument()+ // The credential picker lives INSIDE the editor and is the enabled way to+ // change the linked LLM Secret (the summary picker stays read-only).+ expect(within(dialog).getByLabelText('LLM Secret')).toBeEnabled()expect(- within(dialog).queryByRole('button', { name: 'Edit LLM Secret credentials' })- ).not.toBeInTheDocument()+ within(dialog).getByRole('button', { name: 'Edit LLM Secret credentials' })+ ).toBeInTheDocument()expect(within(dialog).getByRole('button', { name: 'Save' })).toBeInTheDocument()expect(screen.getByRole('button', { name: 'Edit' })).toBeDisabled()expect(screen.queryByRole('button', { name: 'Update secret' })).not.toBeInTheDocument()@@ -508,9 +527,11 @@ describe('HostDetailsPage current model and credential flow', () => {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.+ it('still navigates to the secret editor when the Host policy references an extra slot', async () => {+ // The retirement guard for a fallback credentialSlot lives in the+ // full-screen secret editor (it scans Hosts); the pencil itself must never+ // pre-block navigation. The blocking journey is covered by the+ // secrets/llm/[name]/edit page suite.const fallbackSlot = 'claude-api-key-fb1'const hostWithFallback = materializeHostResource({@@ -538,34 +559,20 @@ describe('HostDetailsPage current model and credential flow', () => {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' }))+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ const editorDialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })+ const pencil = within(editorDialog).getByRole('button', {+ name: 'Edit LLM Secret credentials',+ })+ expect(pencil).toBeEnabled()+ fireEvent.click(pencil)- expect(- await screen.findByText(- new RegExp(`Cannot remove "${fallbackSlot}".*active fallback.*credential slot`)- )- ).toBeInTheDocument()- expect(screen.getByRole('dialog')).toBeInTheDocument()- expect(- (api.apiSend as unknown as ReturnType<typeof vi.fn>).mock.calls.some(- args => args[0] === 'PUT' && args[1] === '/api/v1/admin/secrets'- )- ).toBe(false)+ expect(pushMock).toHaveBeenCalledWith(+ '/secrets/llm/openai-secret/edit?from=%2Fagents%2Ffoo%2Fmodel'+ )})- it('keeps the linked LLM Secret selector outside the model configuration editor', async () => {+ it('changes the linked LLM Secret from the inline credentials dropdown', async () => {setupApiMocks(formLoadHost, refetchedHost, [{ name: 'openai-secret', keys: ['openai-api-key'] },{ name: 'openai-secret-b', keys: ['openai-api-key'] },@@ -573,39 +580,120 @@ describe('HostDetailsPage current model and credential flow', () => {const view = render(<HostDetailsPage />)navigateToTab(view, 'model')await screen.findByText('Current model')- expect(screen.getByLabelText('LLM Secret')).toBeDisabled()+ // The summary is a static display; the editor owns the change.+ expect(screen.getByText('openai-secret')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'LLM Secret' })).not.toBeInTheDocument()fireEvent.click(screen.getByRole('button', { name: 'Edit' }))- const dialog = await screen.findByRole('dialog', { name: 'Edit model configuration' })- expect(within(dialog).queryByLabelText('LLM Secret')).not.toBeInTheDocument()+ const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })+ const picker = within(dialog).getByRole('button', { name: 'LLM Secret' })+ expect(picker).toBeEnabled()+ fireEvent.click(picker)+ fireEvent.click(screen.getByRole('option', { name: /openai-secret-b/ }))fireEvent.click(within(dialog).getByRole('button', { name: 'Save' }))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('openai-secret')+ expect(payload.spec.secretRef).toBe('openai-secret-b')expect(payload.spec.model).toEqual(baseSpec.model)expect(screen.queryByRole('dialog')).not.toBeInTheDocument()})- it('updates the linked Secret without writing Host model configuration', async () => {+ it('syncs the primary provider when the picked LLM Secret serves another provider', async () => {+ vi.mocked(api.getLlmModels).mockResolvedValue({+ rows: [+ ...modelCatalogRows,+ {+ id: 'zai-glm-5-1',+ provider: 'zai',+ model: 'glm-5.1',+ vendor: 'Z.AI',+ display_name: null,+ context_window_tokens: 128000,+ enabled: true,+ source: 'manual' as const,+ stale: false,+ created_at: '',+ updated_at: '',+ },+ ],+ })+ setupApiMocks(formLoadHost, refetchedHost, [+ { name: 'openai-secret', keys: ['openai-api-key'] },+ { name: 'zai-secret', keys: ['zai-api-key'] },+ ])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' }))++ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })+ fireEvent.click(within(dialog).getByRole('button', { name: 'LLM Secret' }))+ fireEvent.click(screen.getByRole('option', { name: /zai-secret/ }))++ // Provider and current model follow the picked secret's provider.+ expect(+ screen.getByLabelText('Provider', { selector: '#llm-primary-provider' })+ ).toHaveTextContent('Z.AI')+ expect(+ screen.getByLabelText('Current model', { selector: '#llm-primary-model' })+ ).toHaveTextContent('glm-5.1')++ fireEvent.click(within(dialog).getByRole('button', { name: 'Save' }))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).toHaveBeenCalledWith('PUT', '/api/v1/admin/hosts/foo', expect.any(Object))+ )+ const payload = findHostPutPayload() as { spec: Record<string, unknown> }+ expect(payload.spec.model).toEqual({ provider: 'zai', name: 'glm-5.1' })+ expect(payload.spec.secretRef).toBe('zai-secret')+ })++ it('keeps the explicit provider when the picked LLM Secret has no recognized provider', async () => {+ configureModelCatalog()+ setupApiMocks(formLoadHost, refetchedHost, [+ { name: 'openai-secret', keys: ['openai-api-key'] },+ { name: 'custom-secret', keys: ['some-custom-key'] },+ ])+ const view = render(<HostDetailsPage />)+ navigateToTab(view, 'model')+ await screen.findByText('Current model')++ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })+ fireEvent.click(within(dialog).getByRole('button', { name: 'LLM Secret' }))+ fireEvent.click(screen.getByRole('option', { name: /custom-secret/ }))++ // A provider-less secret never clobbers the operator's provider/model pair.+ expect(+ screen.getByLabelText('Provider', { selector: '#llm-primary-provider' })+ ).toHaveTextContent('OpenAI')+ expect(+ screen.getByLabelText('Current model', { selector: '#llm-primary-model' })+ ).toHaveTextContent('gpt-5.4-mini')+ })++ it('routes the secret editor to the credential picked in the dialog, not the saved one', async () => {+ setupApiMocks(formLoadHost, refetchedHost, [+ { name: 'openai-secret', keys: ['openai-api-key'] },+ { name: 'openai-secret-b', keys: ['openai-api-key'] },+ ])+ const view = render(<HostDetailsPage />)+ navigateToTab(view, 'model')+ await screen.findByText('Current model')+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })+ fireEvent.click(within(dialog).getByRole('button', { name: 'LLM Secret' }))+ fireEvent.click(screen.getByRole('option', { name: /openai-secret-b/ }))++ fireEvent.click(within(dialog).getByRole('button', { name: 'Edit LLM Secret credentials' }))++ // The draft pick — not the persisted secretRef — names the edit route, and+ // the Host itself is never written from this surface.+ expect(pushMock).toHaveBeenCalledWith(+ '/secrets/llm/openai-secret-b/edit?from=%2Fagents%2Ffoo%2Fmodel')expect((api.apiSend as unknown as ReturnType<typeof vi.fn>).mock.calls.some(@@ -660,7 +748,7 @@ describe('HostDetailsPage cross-tab draft preservation', () => {expect(await screen.findByText('Current model')).toBeInTheDocument()fireEvent.click(screen.getByRole('button', { name: 'Edit' }))- expect(screen.queryByLabelText('Credential')).not.toBeInTheDocument()+ 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' })).toBeDisabled()diff --git a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsxindex b6eb01efb..fbdb731c9 100644--- a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx+++ b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx@@ -303,7 +303,7 @@ describe('HostDetailsPage identity integration', () => {)})- it('shows the provider model configuration and opens the linked LLM Secret modal inline', async () => {+ it('shows the provider model configuration and routes the pencil to the secret editor page', async () => {mockParams = { name: 'foo', tab: 'model' }const { container } = render(<HostDetailsPage />)@@ -315,22 +315,28 @@ describe('HostDetailsPage identity integration', () => {expect(summary).toHaveTextContent('All enabled models')expect(screen.queryByText('Model name')).not.toBeInTheDocument()expect(screen.getByText('LLM Secret')).toBeInTheDocument()- expect(container.querySelectorAll('.cu-llm-summary__value')).toHaveLength(2)+ // Static summary: the credential display uses the same read-only value box+ // as the provider summary (credential + provider + current model).+ expect(container.querySelectorAll('.cu-llm-summary__value')).toHaveLength(3)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 LLM Secret credentials' }))+ // The secret editor is a full-screen route opened from inside the model+ // editor dialog; nothing stacks on this page.+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ const editorDialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })+ fireEvent.click(+ within(editorDialog).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(pushMock).toHaveBeenCalledWith(+ '/secrets/llm/openai-secret/edit?from=%2Fagents%2Ffoo%2Fmodel'+ )expect(container.querySelector('.cu-agent-detail-card')).toBeNull()})- it('shows the fixed LLM Secret assignment with provider icons outside the model editor', async () => {+ 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,@@ -347,38 +353,49 @@ describe('HostDetailsPage identity integration', () => {render(<HostDetailsPage />)- const picker = await screen.findByRole('button', { name: 'LLM Secret' })- expect(picker).toHaveTextContent('openai-secret')- expect(picker).toBeDisabled()- 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')+ // Summary: static value display with the provider icons — not a dropdown.+ const summaryName = await screen.findByText('openai-secret')+ const staticValue = summaryName.closest('.cu-llm-summary__value') as HTMLElement+ expect(staticValue).not.toBeNull()+ expect(staticValue.querySelectorAll('img')).toHaveLength(2)+ expect(staticValue.querySelector('img')).toHaveAttribute('src', '/provider-icons/openai.svg')+ expect(staticValue.querySelectorAll('img')[1]).toHaveAttribute(+ 'src',+ '/provider-icons/claude.svg'+ )+ expect(screen.queryByRole('button', { name: 'LLM Secret' })).not.toBeInTheDocument()+ expect(+ screen.queryByRole('button', { name: 'Edit LLM Secret credentials' })+ ).not.toBeInTheDocument()expect(screen.queryByRole('combobox')).toBeNull()fireEvent.click(screen.getByRole('button', { name: 'Edit' }))- const dialog = await screen.findByRole('dialog', { name: 'Edit model configuration' })- expect(within(dialog).queryByLabelText('LLM Secret')).not.toBeInTheDocument()- expect(dialog.querySelector('#llm-primary-provider')).toBeInTheDocument()- expect(picker).toBeDisabled()+ const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })+ const editorPicker = within(dialog).getByRole('button', { name: 'LLM Secret' })+ expect(editorPicker).toBeEnabled()+ fireEvent.click(editorPicker)++ const zaiOption = screen.getByRole('option', { name: /zai-secret/ })+ expect(zaiOption).toHaveTextContent('Z.AI')+ expect(zaiOption.querySelector('img')).toHaveAttribute('src', '/provider-icons/zai.svg')})- it('uses the shared LLM Secret editor for additional provider credentials', async () => {+ it('links the pencil to the shared full-screen editor for the linked secret', 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.getByText('Anthropic', { selector: '.cu-llm-cred-group__title' })- ).toBeInTheDocument()- expect(screen.getByLabelText(/Claude API key/i)).toBeInTheDocument()+ fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))+ const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })+ const pencil = within(dialog).getByRole('button', { name: 'Edit LLM Secret credentials' })+ expect(pencil).toBeEnabled()+ fireEvent.click(pencil)++ // The additional-provider credential journey itself lives on the+ // secrets/llm/[name]/edit page suite; this page only hands off.+ expect(pushMock).toHaveBeenCalledWith(+ '/secrets/llm/openai-secret/edit?from=%2Fagents%2Ffoo%2Fmodel'+ )+ expect(screen.queryByText('Update LLM secret openai-secret')).not.toBeInTheDocument()})it('shows a complete ChatGPT assignment without requiring Edit', async () => {@@ -565,8 +582,8 @@ describe('HostDetailsPage identity integration', () => {expect(screen.queryByText('Secret reference')).not.toBeInTheDocument()expect(screen.queryByText('OpenAI Codex Subscription')).not.toBeInTheDocument()fireEvent.click(screen.getByRole('button', { name: 'Edit' }))- const dialog = screen.getByRole('dialog', { name: 'Edit model configuration' })- expect(within(dialog).queryByLabelText('Credential')).not.toBeInTheDocument()+ const dialog = screen.getByRole('dialog', { name: 'Edit model & credentials' })+ expect(within(dialog).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' }))@@ -805,7 +822,7 @@ describe('HostDetailsPage identity integration', () => {expect(screen.queryByText('disabled')).not.toBeInTheDocument()})- it('keeps credential assignment controls out of the model editor with a static fallback', async () => {+ it('keeps a second LLM Secret field in existing control-ui styles when Codex has a static fallback', async () => {mockParams = { name: 'foo', tab: 'model' }vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([{@@ -851,10 +868,39 @@ describe('HostDetailsPage identity integration', () => {render(<HostDetailsPage />)fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))- const dialog = await screen.findByRole('dialog', { name: 'Edit model configuration' })- expect(within(dialog).queryByLabelText('Credential')).not.toBeInTheDocument()- expect(within(dialog).queryByLabelText('LLM Secret')).not.toBeInTheDocument()- expect(dialog.querySelectorAll('.cu-llm-secret-control')).toHaveLength(0)- expect(dialog.querySelector('#llm-primary-provider')).toBeInTheDocument()+ const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })+ expect(within(dialog).getByLabelText('Credential')).toBeInTheDocument()+ expect(within(dialog).getByLabelText('LLM Secret')).toBeInTheDocument()+ expect(within(dialog).getByLabelText('Credential')).toBeEnabled()+ expect(within(dialog).getByLabelText('LLM Secret')).toBeEnabled()+ expect(dialog.querySelectorAll('.cu-llm-secret-control')).toHaveLength(2)+ expect(dialog.querySelectorAll('.cu-field__hint').length).toBeGreaterThanOrEqual(2)+ expect(+ within(dialog).getByRole('button', { name: 'Edit LLM Secret credentials' })+ ).toBeInTheDocument()+ })++ it('collapses the fallback providers section by default in the model editor', async () => {+ mockParams = { name: 'foo', tab: 'model' }+ render(<HostDetailsPage />)++ fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))+ const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })++ // Collapsed by default: the toggle is closed and the policy editor+ // (including its add-fallback affordance) is not rendered.+ const toggle = within(dialog).getByRole('button', { name: /Fallback providers/ })+ expect(toggle).toHaveAttribute('aria-expanded', 'false')+ expect(+ within(dialog).queryByRole('region', { name: 'Fallback policy' })+ ).not.toBeInTheDocument()++ // Expanding still reveals the full editor.+ fireEvent.click(toggle)+ expect(toggle).toHaveAttribute('aria-expanded', 'true')+ expect(within(dialog).getByRole('region', { name: 'Fallback policy' })).toBeInTheDocument()+ expect(+ within(dialog).getByRole('button', { name: 'Add fallback provider' })+ ).toBeInTheDocument()})})diff --git a/control-ui/components/__tests__/SecretsTable.test.tsx b/control-ui/components/__tests__/SecretsTable.test.tsxindex ec63ca92f..b4f913d1b 100644--- a/control-ui/components/__tests__/SecretsTable.test.tsx+++ b/control-ui/components/__tests__/SecretsTable.test.tsx@@ -77,12 +77,18 @@ function renderTable()}-// The LLM update modal is the only surface that can retire a stored data key.-// These assert the WRITE it produces: without `removeKeys` in the payload the-// row disappears from the editor while the key survives in the Secret.-describe('SecretsTable — LLM secret update payload', () => {+describe('SecretsTable — LLM secret update entry point', () => {const SECRET = 'chatllm-api-keys'+ beforeEach(() => {+ mockReplace.mockClear()+ mockPush.mockClear()+ })++ afterEach(() => {+ cleanup()+ })+function renderLlmTable(keys: string[]) {return rtlRender(<ToastProvider>@@ -99,12 +105,6 @@ describe('SecretsTable — LLM secret update payload', () => {)}- function openUpdateModal(keys: string[]) {- renderLlmTable(keys)- fireEvent.click(screen.getByRole('button', { name: `Actions for LLM secret ${SECRET}` }))- fireEvent.click(screen.getByRole('menuitem', { name: 'Update' }))- }-it('shows the providers whose complete credentials are stored in each secret', () => {renderLlmTable(['openai-api-key', 'claude-api-key'])@@ -113,183 +113,15 @@ describe('SecretsTable — LLM secret update payload', () => {expect(within(providers).getByText('Anthropic')).toBeInTheDocument()})- const sectionFor = (label: string) =>- screen.getByText(label, { selector: '.cu-llm-cred-group__title' }).closest('section')!-- const removeExtraSlotIn = (label: string) =>- fireEvent.click(- within(sectionFor(label)).getByRole('button', { name: 'Remove extra credential slot' })- )-- const save = () => fireEvent.click(screen.getByRole('button', { name: 'Update secret' }))-- const replaceOpenAiKey = () =>- fireEvent.click(screen.getByRole('button', { name: 'Replace OpenAI API key' }))-- // Retirement is irreversible, so the save goes through a danger confirm. The- // dialog is scoped by role — the LLM modal has its own "Cancel" button.- async function resolveRemovalConfirm(action: 'Remove and save' | 'Cancel') {- const dialog = await screen.findByRole('alertdialog')- fireEvent.click(within(dialog).getByRole('button', { name: action }))- }-- beforeEach(() => {- mockReplace.mockClear()- mockPush.mockClear()- })-- afterEach(() => {- cleanup()- })-- it('sends removeKeys for a retire-only edit once the removal is confirmed', async () => {- openUpdateModal(['claude-api-key-fb1', 'openai-api-key'])- removeExtraSlotIn('Anthropic')- save()-- // Nothing is written until the operator confirms.- await resolveRemovalConfirm('Remove and save')-- await waitFor(() => {- expect(apiSendMock).toHaveBeenCalledWith('PUT', '/api/v1/admin/secrets', {- name: SECRET,- merge: true,- stringData: {},- removeKeys: ['claude-api-key-fb1'],- })- })- // Retiring a key IS an edit: the "provide at least one API key" gate must- // not swallow it.- expect(screen.queryAllByText(/Provide at least one API key/i)).toHaveLength(0)- })-- it('writes nothing when the removal confirmation is cancelled', async () => {- openUpdateModal(['claude-api-key-fb1', 'openai-api-key'])- removeExtraSlotIn('Anthropic')- save()-- await resolveRemovalConfirm('Cancel')-- await waitFor(() => {- expect(screen.queryByRole('alertdialog')).toBeNull()- })- expect(apiSendMock).not.toHaveBeenCalled()- // The edit is still open and still queued — cancelling the confirm is not- // cancelling the edit.- expect(screen.getByRole('button', { name: 'Update secret' })).toBeInTheDocument()- })-- it('sends written values and retired keys in the same merge write', async () => {- openUpdateModal(['claude-api-key-fb1', 'openai-api-key'])- replaceOpenAiKey()- fireEvent.change(screen.getByLabelText(/^OpenAI API key/i), { target: { value: 'sk-live' } })- removeExtraSlotIn('Anthropic')- save()- await resolveRemovalConfirm('Remove and save')-- await waitFor(() => {- expect(apiSendMock).toHaveBeenCalledWith('PUT', '/api/v1/admin/secrets', {- name: SECRET,- merge: true,- stringData: { 'openai-api-key': 'sk-live' },- removeKeys: ['claude-api-key-fb1'],- })- })- })-- it('omits removeKeys — and the confirm — when nothing was retired', async () => {- openUpdateModal(['openai-api-key'])- replaceOpenAiKey()- fireEvent.change(screen.getByLabelText(/^OpenAI API key/i), { target: { value: 'sk-live' } })- save()-- await waitFor(() => {- expect(apiSendMock).toHaveBeenCalledWith('PUT', '/api/v1/admin/secrets', {- name: SECRET,- merge: true,- stringData: { 'openai-api-key': 'sk-live' },- })- })- expect(screen.queryByRole('alertdialog')).toBeNull()- })-- it('writes the key instead of retiring it when a removed slot is re-created', async () => {- // End-to-end of the delete-then-recreate hole: the payload must WRITE- // claude-api-key-fb1, never retire it — retirement-wins server-side would- // otherwise delete the key and discard the value typed for it.- openUpdateModal(['claude-api-key-fb1', 'openai-api-key'])- removeExtraSlotIn('Anthropic')- fireEvent.click(- within(sectionFor('Anthropic')).getByRole('button', { name: /Add credential slot/i })- )- const anthropic = sectionFor('Anthropic')- fireEvent.change(within(anthropic).getByLabelText(/Extra credential slot key name/i), {- target: { value: 'claude-api-key-fb1' },- })- fireEvent.change(within(anthropic).getByLabelText(/Extra credential slot value/i), {- target: { value: 'sk-ant-new' },- })- save()-- await waitFor(() => {- expect(apiSendMock).toHaveBeenCalledWith('PUT', '/api/v1/admin/secrets', {- name: SECRET,- merge: true,- stringData: { 'claude-api-key-fb1': 'sk-ant-new' },- })- })- // No retirement left to confirm.- expect(screen.queryByRole('alertdialog')).toBeNull()- })-- it('blocks retiring every stored key instead of letting the server 400', async () => {- openUpdateModal(['claude-api-key-fb1'])- removeExtraSlotIn('Anthropic')- save()-- await waitFor(() => {- expect(- screen.getAllByText(/Removing every key would leave the secret empty/i).length- ).toBeGreaterThan(0)- })- // Refused before the confirm — no point asking about a write that cannot- // succeed.- expect(screen.queryByRole('alertdialog')).toBeNull()- expect(apiSendMock).not.toHaveBeenCalled()- })-- it('still blocks a save that neither writes nor retires anything', () => {- openUpdateModal(['openai-api-key'])- save()-- // Surfaced both in the panel strip and inside the modal.- expect(screen.getAllByText(/Provide at least one API key/i).length).toBeGreaterThan(0)- expect(apiSendMock).not.toHaveBeenCalled()- })-- it('drops queued removals when the modal is closed and reopened', async () => {- // Regression guard: a stale `removedKeys` would delete keys belonging to- // whichever secret is edited next.- renderLlmTable(['claude-api-key-fb1', 'openai-api-key'])- fireEvent.click(screen.getByRole('button', { name: `Actions for LLM secret ${SECRET}` }))- fireEvent.click(screen.getByRole('menuitem', { name: 'Update' }))- removeExtraSlotIn('Anthropic')- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ it('navigates from the Update action to the full-screen secret editor', () => {+ renderLlmTable(['openai-api-key'])fireEvent.click(screen.getByRole('button', { name: `Actions for LLM secret ${SECRET}` }))fireEvent.click(screen.getByRole('menuitem', { name: 'Update' }))- replaceOpenAiKey()- fireEvent.change(screen.getByLabelText(/^OpenAI API key/i), { target: { value: 'sk-live' } })- save()- await waitFor(() => {- expect(apiSendMock).toHaveBeenCalledWith('PUT', '/api/v1/admin/secrets', {- name: SECRET,- merge: true,- stringData: { 'openai-api-key': 'sk-live' },- })- })- expect(screen.queryByRole('alertdialog')).toBeNull()+ expect(mockPush).toHaveBeenCalledWith(`/secrets/llm/${SECRET}/edit`)+ // The editor moved to its own route — no stacked modal remains here.+ expect(screen.queryByRole('button', { name: 'Update secret' })).not.toBeInTheDocument()})})diff --git a/control-ui/lib/__tests__/routes.test.ts b/control-ui/lib/__tests__/routes.test.tsindex f8db5cf0d..072642bf0 100644--- a/control-ui/lib/__tests__/routes.test.ts+++ b/control-ui/lib/__tests__/routes.test.ts@@ -38,4 +38,13 @@ describe('CONTROL_ROUTES', () => {expect(CONTROL_ROUTES.secrets.llmSubscriptions).toBe('/secrets/llm/subscriptions')expect(CONTROL_ROUTES.secrets.subscription).toBe('/secrets/llm/subscriptions')})++ it('builds the full-screen LLM secret edit route with optional return context', () => {+ expect(CONTROL_ROUTES.secrets.editLlm('chatllm-api-keys')).toBe(+ '/secrets/llm/chatllm-api-keys/edit'+ )+ expect(CONTROL_ROUTES.secrets.editLlm('chatllm api keys', { from: '/agents/foo/model' })).toBe(+ '/secrets/llm/chatllm%20api%20keys/edit?from=%2Fagents%2Ffoo%2Fmodel'+ )+ })})diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 3af339469..da72f227f 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.709",+ "version": "0.1.710","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.709",+ "version": "0.1.710","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/frontend-components": "file:../packages/frontend-components",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 1eaf4ecc2..6576c8a4f 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.709",+ "version": "0.1.710","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",