Skip to content

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

TypeScript

fix(control-ui): actually retire removed/renamed stored extra credential slots

Diego Zacariasa365351e13d7
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.css
index dfe8eb39b..d4d402914 100644
--- a/control-ui/app/globals.css
+++ b/control-ui/app/globals.css
@@ -6852,6 +6852,30 @@ textarea.cu-input {
margin: 0;
}
+/* Stored keys queued for retirement. The deletion lands on SAVE, so this is
+ the only signal between the click and the write — warning tone, not the
+ muted hint color it inherits from .cu-field__hint. The element stays mounted
+ as a live region even with nothing queued, so :empty (never whitespace — it
+ renders no children at all) takes it out of the flow instead of leaving the
+ editor's column gap around a blank line. */
+.cu-llm-cred-removed {
+ margin: 0;
+ color: var(--cu-warning);
+}
+
+.cu-llm-cred-removed:empty {
+ display: none;
+}
+
+/* Match the monospace key-name inputs the listed keys were typed into (same
+ stack as .cu-input--monospace — the codebase has no mono font token). */
+.cu-llm-cred-removed code {
+ font-family:
+ ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New',
+ monospace;
+ font-size: 0.95em;
+}
+
/* The "Add provider" picker of the additive editor (a SelectionDropdown, so
the width cap lands on its root element, not on a native <select>). The cap
also bounds the popover menu, so it stays wide enough for the longest
diff --git a/control-ui/components/LlmCredentialFields/index.tsx b/control-ui/components/LlmCredentialFields/index.tsx
index 56421a39a..1ca819d92 100644
--- a/control-ui/components/LlmCredentialFields/index.tsx
+++ b/control-ui/components/LlmCredentialFields/index.tsx
@@ -1,6 +1,6 @@
'use client'
-import React, { useMemo, useRef, useState } from 'react'
+import React, { useEffect, useMemo, useRef, useState } from 'react'
import Link from 'next/link'
import { CONTROL_ROUTES } from '@constants/routes'
import { LlmProviderIcon } from '@/components/LlmProviderIcon'
@@ -92,11 +92,17 @@ export function LlmCredentialFields({
onChange,
disabled = false,
existingKeys,
+ onRemovedKeysChange,
pickerInline = false,
}: LlmCredentialFieldsProps) {
const [extraSlots, setExtraSlots] = useState<ExtraSlot[]>(() =>
seedExistingExtraSlots(existingKeys)
)
+ // Stored keys whose seeded ROW was deleted with the X. Rename-driven
+ // retirement is NOT tracked here — it is derived from `extraSlots` below, so
+ // renaming back to the original name un-retires the key without any undo
+ // bookkeeping (one source of truth per retirement cause).
+ const [removedSeededKeys, setRemovedSeededKeys] = useState<ReadonlySet<string>>(() => new Set())
// Providers the operator surfaced with "+ Add provider" this session. Resets
// with the mount (the update modal mounts fresh per row; the create flow
// remounts per step) — a remount is auto-cured by the draft term below.
@@ -154,13 +160,56 @@ export function LlmCredentialFields({
return keys
}, [existingKeySet])
+ // Stored keys pending retirement on save. Two causes, one derivation:
+ // - REMOVED: the seeded row was deleted with its X (`removedSeededKeys`).
+ // - RENAMED: a seeded row still on screen whose committed key differs from
+ // the stored one AND carries a typed value. The value term matters — a
+ // rename with no value writes nothing, so retiring the old key would
+ // delete the credential outright instead of replacing it. Renaming back
+ // to `existingKey` naturally drops out of this set.
+ // Finally, a key the draft is currently writing is never retired: the server
+ // resolves "in data AND in removeKeys" as retirement-wins, which would throw
+ // away the value the operator just typed.
+ const removedKeys = useMemo(() => {
+ const keys = new Set<string>(removedSeededKeys)
+ for (const slot of extraSlots) {
+ if (!slot.existingKey) continue
+ if (!slot.committedKey || slot.committedKey === slot.existingKey) continue
+ if (slot.value.trim().length === 0) continue
+ keys.add(slot.existingKey)
+ }
+ return Array.from(keys)
+ .filter(key => (draft[key] ?? '').trim().length === 0)
+ .sort((a, b) => a.localeCompare(b))
+ }, [draft, extraSlots, removedSeededKeys])
+
+ // Report only on real change. `removedKeys` is a fresh array every render, so
+ // the SIGNATURE is the effect's dependency (a k8s data key cannot contain a
+ // newline, so the join is unambiguous). The callback reaches the effect
+ // through a ref latch rather than the dependency array: parents pass an
+ // inline closure, and depending on that identity would re-fire the effect on
+ // every render the report itself causes.
+ const notifyRemovedKeys = useRef(onRemovedKeysChange)
+ notifyRemovedKeys.current = onRemovedKeysChange
+ const removedKeysSignature = removedKeys.join('\n')
+ useEffect(() => {
+ notifyRemovedKeys.current?.(
+ removedKeysSignature.length > 0 ? removedKeysSignature.split('\n') : []
+ )
+ }, [removedKeysSignature])
+
function extraSlotError(slot: ExtraSlot, nameInput: string): string | null {
const trimmed = nameInput.trim()
if (!trimmed) return 'Key name is required.'
if (!DATA_KEY_PATTERN.test(trimmed)) return 'Use lowercase letters, numbers, and - . _'
// A slot seeded from a stored key may keep (and rewrite) its own name; any
- // OTHER known key is still a collision.
- if (knownKeys.has(trimmed) && trimmed !== slot.existingKey) {
+ // OTHER known key is still a collision — EXCEPT one queued for retirement.
+ // That key is on its way out, so re-typing it is not a collision, it is the
+ // operator taking the removal back (see commitExtraSlot). Without this
+ // exemption the name would never commit, the value would never reach the
+ // draft, and the save would still carry the retirement — deleting the key
+ // and silently discarding the credential just typed under it.
+ if (knownKeys.has(trimmed) && trimmed !== slot.existingKey && !removedSeededKeys.has(trimmed)) {
return 'This key already exists as a provider slot.'
}
if (extraSlots.some(item => item.id !== slot.id && item.nameInput.trim() === trimmed)) {
@@ -178,10 +227,30 @@ export function LlmCredentialFields({
onChange(slot.committedKey, '')
}
if (nextCommitted) onChange(nextCommitted, nextValue)
+ // Committing a key that was queued for retirement takes the removal back:
+ // this row is once again the editor's representation of that STORED key, so
+ // it re-adopts it as `existingKey` (becoming an ordinary seeded row) and the
+ // key leaves the removal set. With no value typed the key simply survives
+ // untouched; with a value it is rewritten through the normal merge.
+ const unretiredKey =
+ nextCommitted !== null && removedSeededKeys.has(nextCommitted) ? nextCommitted : null
+ if (unretiredKey) {
+ setRemovedSeededKeys(prev => {
+ const next = new Set(prev)
+ next.delete(unretiredKey)
+ return next
+ })
+ }
setExtraSlots(prev =>
prev.map(item =>
item.id === slot.id
- ? { ...item, nameInput: nextName, value: nextValue, committedKey: nextCommitted }
+ ? {
+ ...item,
+ nameInput: nextName,
+ value: nextValue,
+ committedKey: nextCommitted,
+ existingKey: unretiredKey ?? item.existingKey,
+ }
: item
)
)
@@ -207,6 +276,14 @@ export function LlmCredentialFields({
const slot = extraSlots.find(item => item.id === id)
if (!slot) return
if (slot.committedKey) onChange(slot.committedKey, '')
+ // A slot seeded from the Secret leaves a STORED key behind: dropping the
+ // row only hides it, so the key is queued for retirement on save. A slot
+ // created in this session has nothing stored — clearing the draft above is
+ // the whole removal.
+ if (slot.existingKey) {
+ const retired = slot.existingKey
+ setRemovedSeededKeys(prev => new Set(prev).add(retired))
+ }
setExtraSlots(prev => prev.filter(item => item.id !== id))
}
@@ -225,8 +302,9 @@ export function LlmCredentialFields({
// `team1.key`) commits to the draft under a key providerForDataKey can't
// attribute, so the slot's own committedKey/value must gate too.
// A provider with a stored key never reaches `manuallyAdded` — it is already
- // visible, so "+ Add provider" never offers it. Deleting a stored key stays
- // on removeSecretKey, not here.
+ // visible, so "+ Add provider" never offers it. Retiring a stored key is the
+ // per-slot X (which queues it into `removedKeys`), never this section-level
+ // control.
function isProviderRemovable(provider: LlmProvider): boolean {
if (!manuallyAdded.has(provider)) return false
const hasDraftValue = Object.entries(draft).some(
@@ -255,6 +333,28 @@ export function LlmCredentialFields({
return (
<div className="cu-llm-cred-groups">
+ {/* Retirement is applied on SAVE, not on click — a row vanishing is not by
+ itself proof anything will be deleted, so the queued keys are named.
+ First child, above the provider sections: in the scroll-clipped update
+ modal anything after them lands below the fold. Always mounted (empty
+ when nothing is queued, and hidden by :empty) so the live region is
+ present before the first announcement — a region inserted together
+ with its text is not reliably announced. */}
+ <p className="cu-field__hint cu-llm-cred-removed" role="status">
+ {removedKeys.length > 0 ? (
+ <>
+ Will be removed from the stored secret on save:{' '}
+ {removedKeys.map((key, index) => (
+ <React.Fragment key={key}>
+ {index > 0 ? ', ' : null}
+ <code>{key}</code>
+ </React.Fragment>
+ ))}
+ .
+ </>
+ ) : null}
+ </p>
+
{visibleGroups.length === 0 ? (
<p className="cu-field__hint cu-llm-cred-empty">
No providers added yet — add a provider below to enter its credentials.
@@ -352,11 +452,26 @@ export function LlmCredentialFields({
{providerExtras.map(slot => {
const inputId = `${ID_PREFIX}-extra-${slot.id}`
const error = extraSlotError(slot, slot.nameInput)
+ // A seeded slot renamed but left valueless is a MUTE state: the
+ // rename writes nothing, so the old key is deliberately not
+ // retired (see `removedKeys`) and saving does nothing at all to
+ // this row. Say so, instead of letting the operator believe the
+ // rename landed.
+ const renameNeedsValue =
+ slot.existingKey !== null &&
+ slot.committedKey !== null &&
+ slot.committedKey !== slot.existingKey &&
+ slot.value.trim().length === 0
return (
<Field
key={slot.id}
htmlFor={inputId}
label={`Additional credential slot`}
+ description={
+ renameNeedsValue
+ ? `Type a value to complete the rename — the stored key keeps its old name (${slot.existingKey}) until then.`
+ : undefined
+ }
error={error ?? undefined}
>
<div className="cu-llm-cred-extra">
diff --git a/control-ui/components/LlmCredentialFields/types.ts b/control-ui/components/LlmCredentialFields/types.ts
index 163f89e4d..bd7796259 100644
--- a/control-ui/components/LlmCredentialFields/types.ts
+++ b/control-ui/components/LlmCredentialFields/types.ts
@@ -27,6 +27,13 @@ export type LlmCredentialFieldsProps = {
// Keys already stored in the Secret (edit mode) — light up the present chips
// without ever exposing a value. Create flows omit it.
existingKeys?: string[]
+ // Stored keys (a subset of `existingKeys`) the operator retired in this
+ // session: removed with the slot's X, or renamed away with a valid
+ // replacement typed under the new name. Reported on every change so the
+ // parent can send them as `removeKeys` on save — without this channel the
+ // draft alone can never express a deletion (it is write-only, and blanking a
+ // value is explicitly NOT deletion server-side). Create flows omit it.
+ onRemovedKeysChange?: (keys: string[]) => void
// Render the "Add provider" picker as an always-open inline list instead of a
// popover. Scroll-clipped surfaces (the update modal) must set it — an
// absolute-positioned menu would open below the modal's visible fold.
diff --git a/control-ui/components/SecretsTable.tsx b/control-ui/components/SecretsTable.tsx
index 8e765802b..3a9067a0e 100644
--- a/control-ui/components/SecretsTable.tsx
+++ b/control-ui/components/SecretsTable.tsx
@@ -94,6 +94,10 @@ export function SecretsTable({
const [editingKeys, setEditingKeys] = useState<string[]>([])
const [isLlmModalOpen, setIsLlmModalOpen] = useState(false)
const [keyDraft, setKeyDraft] = useState<Record<string, string>>(createEmptyLlmKeyDraft)
+ // Stored data keys the editor queued for retirement (removed or renamed-away
+ // extra slots). Sent as `removeKeys` on save — the draft is write-only and a
+ // blank value is explicitly NOT a deletion server-side.
+ const [removedKeys, setRemovedKeys] = useState<string[]>([])
const [saving, setSaving] = useState(false)
const [deletingName, setDeletingName] = useState<string | null>(null)
const [error, setError] = useState('')
@@ -163,6 +167,7 @@ export function SecretsTable({
setEditingName('')
setEditingKeys([])
setKeyDraft(createEmptyLlmKeyDraft())
+ setRemovedKeys([])
setError('')
}
@@ -170,6 +175,7 @@ export function SecretsTable({
setEditingName(name)
setEditingKeys(keysByName.get(name) ?? [])
setKeyDraft(createEmptyLlmKeyDraft())
+ setRemovedKeys([])
setError('')
setIsLlmModalOpen(true)
}
@@ -186,27 +192,61 @@ export function SecretsTable({
.map(([key, value]) => [key, value.trim()])
.filter(([, value]) => value.length > 0)
)
- if (Object.keys(stringData).length === 0) {
+ // Defense in depth: the editor owns this invariant (it never reports a key
+ // the draft is writing), and the server resolves "in data AND in
+ // removeKeys" as retirement-wins, which would drop the value just typed.
+ // The filter stays as a backstop for any future parent wiring the channel.
+ const removeKeys = removedKeys.filter(key => !(key in stringData))
+ // A retire-only edit is a real edit: `merge: true` accepts `removeKeys`
+ // with no data at all, so only an empty-and-nothing-retired save is a
+ // no-op worth blocking.
+ if (Object.keys(stringData).length === 0 && removeKeys.length === 0) {
setError('Provide at least one API key.')
return
}
+ // Retiring every stored key without writing one 400s server-side with
+ // "secret must retain at least one key" — a cryptic answer to a question
+ // the client can answer itself from the keys it already knows.
+ const survivingKeys = new Set([
+ ...editingKeys.filter(key => !removeKeys.includes(key)),
+ ...Object.keys(stringData),
+ ])
+ if (survivingKeys.size === 0) {
+ setError('Removing every key would leave the secret empty — delete the secret instead.')
+ return
+ }
// Slot-aware validation (spec R4.5.3), mirrored server-side in control-api.
const slotErrors = validateLlmSecretData(stringData)
if (slotErrors.length > 0) {
setError(slotErrors[0])
return
}
+ // Retirement is irreversible — the values are write-only, so a key deleted
+ // by mistake cannot be restored from anything the UI holds. Confirm before
+ // the write, naming exactly what goes.
+ if (removeKeys.length > 0) {
+ const confirmed = await confirm({
+ title: 'Remove stored keys',
+ message: `Permanently remove ${removeKeys.join(', ')} from secret ${secretName}? Their values cannot be recovered.`,
+ confirmLabel: 'Remove and save',
+ tone: 'danger',
+ })
+ if (!confirmed) return
+ }
setSaving(true)
setError('')
try {
// merge:true → server-side read-then-replace that preserves the keys of
// other providers stored in this shared LLM secret (spec R4 FIX 2b).
- // Individual key removal has its own path (removeSecretKey).
+ // `removeKeys` (merge-only) is the deletion half of the same write: keys
+ // the editor retired are dropped from the merged data. Omitted entirely
+ // when nothing is retired so a plain update stays a pure overlay.
await apiSend('PUT', '/api/v1/admin/secrets', {
name: secretName,
merge: true,
stringData,
+ ...(removeKeys.length > 0 ? { removeKeys } : {}),
})
showToast(`Secret ${secretName} updated.`, { tone: 'success' })
await onChanged()
@@ -913,12 +953,19 @@ export function SecretsTable({
<div className="cu-form-stack" style={{ maxWidth: '100%' }}>
<p className="cu-field__hint">
- Updates the listed keys; other keys already stored in this secret are preserved.
+ 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={editingKeys}
+ // Identity-stable update: the editor re-reports on every change,
+ // and a fresh array each time would re-render the modal for no
+ // reason (and on mount, for an empty set).
+ onRemovedKeysChange={next =>
+ setRemovedKeys(prev => (prev.join('\n') === next.join('\n') ? prev : next))
+ }
disabled={saving}
pickerInline
/>
diff --git a/control-ui/components/__tests__/LlmCredentialFields.test.tsx b/control-ui/components/__tests__/LlmCredentialFields.test.tsx
index d2677ada8..49e655f1a 100644
--- a/control-ui/components/__tests__/LlmCredentialFields.test.tsx
+++ b/control-ui/components/__tests__/LlmCredentialFields.test.tsx
@@ -12,9 +12,11 @@ afterEach(cleanup)
function Harness({
existingKeys,
onDraftChange,
+ onRemovedKeysChange,
}: {
existingKeys?: string[]
onDraftChange?: (dataKey: string, value: string) => void
+ onRemovedKeysChange?: (keys: string[]) => void
}) {
const [draft, setDraft] = useState<Record<string, string>>({})
return (
@@ -25,6 +27,7 @@ function Harness({
setDraft(prev => ({ ...prev, [dataKey]: value }))
}}
existingKeys={existingKeys}
+ onRemovedKeysChange={onRemovedKeysChange}
/>
)
}
@@ -184,7 +187,8 @@ describe('LlmCredentialFields (additive provider editor)', () => {
it('offers no remove control for a stored provider or one holding a typed value', () => {
render(<Harness existingKeys={['zai-api-key']} />)
- // Stored in the Secret → deletion stays on removeSecretKey, never here.
+ // Stored in the Secret → retiring it is the per-slot X, never the
+ // section-level remove control.
expect(screen.queryByRole('button', { name: 'Remove Z.AI provider' })).toBeNull()
addProvider('openai')
@@ -300,6 +304,211 @@ describe('LlmCredentialFields (additive provider editor)', () => {
})
})
+// Removing or renaming a STORED extra slot has to travel out of the component
+// as an explicit retirement: the draft is write-only, and a blank value is not
+// a deletion server-side, so without this channel the row would disappear from
+// the form while the key stayed in the Kubernetes Secret forever.
+describe('LlmCredentialFields — retiring stored extra slots', () => {
+ const removeSlotButton = (group: HTMLElement) =>
+ within(group).getByRole('button', { name: 'Remove extra credential slot' })
+
+ // The queued-removal hint is a permanently mounted live region (empty when
+ // nothing is queued), and its keys are wrapped in <code>, so it is read as
+ // one element's text rather than matched with getByText.
+ const removalHint = () => document.querySelector('.cu-llm-cred-removed') as HTMLElement
+
+ it('reports the stored key when its seeded slot is removed', () => {
+ const onRemovedKeysChange = vi.fn()
+ render(
+ <Harness existingKeys={['claude-api-key-fb1']} onRemovedKeysChange={onRemovedKeysChange} />
+ )
+ // Nothing is pending until the operator acts, but the live region is
+ // already mounted so its first announcement is not missed.
+ expect(onRemovedKeysChange).toHaveBeenLastCalledWith([])
+ expect(removalHint()).toBeEmptyDOMElement()
+
+ fireEvent.click(removeSlotButton(sectionOf('Anthropic')))
+
+ expect(onRemovedKeysChange).toHaveBeenLastCalledWith(['claude-api-key-fb1'])
+ // The row is gone, exactly as before — the hint is what makes the queued
+ // deletion visible before it is written.
+ expect(screen.queryByLabelText(/Extra credential slot key name/i)).toBeNull()
+ expect(removalHint()).toHaveTextContent(
+ 'Will be removed from the stored secret on save: claude-api-key-fb1.'
+ )
+ })
+
+ it('reports the original key when a seeded slot is renamed with a value', () => {
+ const onRemovedKeysChange = vi.fn()
+ render(
+ <Harness existingKeys={['claude-api-key-fb1']} onRemovedKeysChange={onRemovedKeysChange} />
+ )
+ const group = sectionOf('Anthropic')
+ const name = within(group).getByLabelText(/Extra credential slot key name/i)
+ const value = within(group).getByLabelText(/Extra credential slot value/i)
+
+ fireEvent.change(name, { target: { value: 'claude-api-key-fb2' } })
+ // Renamed but nothing typed yet: the rename writes no replacement, so
+ // retiring the stored key would delete the credential instead of moving it.
+ expect(onRemovedKeysChange).toHaveBeenLastCalledWith([])
+
+ fireEvent.change(value, { target: { value: 'sk-ant-new' } })
+ expect(onRemovedKeysChange).toHaveBeenLastCalledWith(['claude-api-key-fb1'])
+
+ // Renaming back to the stored name un-queues it — the write now targets the
+ // very key that was pending retirement, and "retirement wins" server-side
+ // would have dropped the new value.
+ fireEvent.change(name, { target: { value: 'claude-api-key-fb1' } })
+ expect(onRemovedKeysChange).toHaveBeenLastCalledWith([])
+ expect(removalHint()).toBeEmptyDOMElement()
+ })
+
+ it('reports nothing when an invalid rename never commits a replacement', () => {
+ const onRemovedKeysChange = vi.fn()
+ render(
+ <Harness existingKeys={['claude-api-key-fb1']} onRemovedKeysChange={onRemovedKeysChange} />
+ )
+ const group = sectionOf('Anthropic')
+ fireEvent.change(within(group).getByLabelText(/Extra credential slot key name/i), {
+ target: { value: 'claude-api-key' },
+ })
+ fireEvent.change(within(group).getByLabelText(/Extra credential slot value/i), {
+ target: { value: 'sk-ant-new' },
+ })
+ // The name collides with the canonical Anthropic slot, so nothing is
+ // committed — and an uncommitted rename must not retire anything.
+ expect(within(group).getByText(/already exists as a provider slot/i)).toBeInTheDocument()
+ expect(onRemovedKeysChange).toHaveBeenLastCalledWith([])
+ })
+
+ it('reports nothing when a slot created in this session is removed', () => {
+ const onRemovedKeysChange = vi.fn()
+ render(<Harness onRemovedKeysChange={onRemovedKeysChange} />)
+ addProvider('zai')
+ const group = sectionOf('Z.AI')
+ fireEvent.click(within(group).getByRole('button', { name: /Add credential slot/i }))
+ fireEvent.change(within(group).getByLabelText(/Extra credential slot value/i), {
+ target: { value: 'zai-fallback' },
+ })
+ fireEvent.click(removeSlotButton(group))
+
+ // No stored key was ever behind this row — clearing the draft is the whole
+ // removal.
+ expect(onRemovedKeysChange).toHaveBeenLastCalledWith([])
+ expect(removalHint()).toBeEmptyDOMElement()
+ })
+
+ it('un-retires a stored key re-created under the same name (no silent delete)', () => {
+ // Repro of the delete-then-recreate hole: X the seeded row, add a fresh
+ // slot, type the SAME key name back with a value. If the name kept
+ // colliding with `knownKeys` it would never commit, the value would never
+ // reach the draft, and the queued retirement would still ship — deleting
+ // the key and throwing away the credential typed for it.
+ const onDraftChange = vi.fn()
+ const onRemovedKeysChange = vi.fn()
+ render(
+ <Harness
+ existingKeys={['claude-api-key-fb1']}
+ onDraftChange={onDraftChange}
+ onRemovedKeysChange={onRemovedKeysChange}
+ />
+ )
+ fireEvent.click(removeSlotButton(sectionOf('Anthropic')))
+ expect(onRemovedKeysChange).toHaveBeenLastCalledWith(['claude-api-key-fb1'])
+
+ const group = sectionOf('Anthropic')
+ fireEvent.click(within(group).getByRole('button', { name: /Add credential slot/i }))
+ fireEvent.change(within(group).getByLabelText(/Extra credential slot key name/i), {
+ target: { value: 'claude-api-key-fb1' },
+ })
+
+ // A key on its way out is not a collision — re-typing it takes the removal
+ // back, and the row becomes an ordinary seeded row again.
+ expect(within(group).queryByText(/already exists as a provider slot/i)).toBeNull()
+ expect(onRemovedKeysChange).toHaveBeenLastCalledWith([])
+ expect(removalHint()).toBeEmptyDOMElement()
+
+ fireEvent.change(within(group).getByLabelText(/Extra credential slot value/i), {
+ target: { value: 'sk-ant-new' },
+ })
+ expect(onDraftChange).toHaveBeenLastCalledWith('claude-api-key-fb1', 'sk-ant-new')
+ expect(onRemovedKeysChange).toHaveBeenLastCalledWith([])
+ })
+
+ it('re-creating a retired key with no value neither writes nor retires it', () => {
+ const onRemovedKeysChange = vi.fn()
+ render(
+ <Harness existingKeys={['claude-api-key-fb1']} onRemovedKeysChange={onRemovedKeysChange} />
+ )
+ fireEvent.click(removeSlotButton(sectionOf('Anthropic')))
+ const group = sectionOf('Anthropic')
+ fireEvent.click(within(group).getByRole('button', { name: /Add credential slot/i }))
+ fireEvent.change(within(group).getByLabelText(/Extra credential slot key name/i), {
+ target: { value: 'claude-api-key-fb1' },
+ })
+
+ // Nothing queued: the stored key simply survives untouched.
+ expect(onRemovedKeysChange).toHaveBeenLastCalledWith([])
+ // And the row is a seeded row again, so it is not flagged as an incomplete
+ // rename either.
+ expect(within(group).queryByText(/Type a value to complete the rename/i)).toBeNull()
+ })
+
+ it('flags a seeded slot renamed without a value as an incomplete rename', () => {
+ render(<Harness existingKeys={['claude-api-key-fb1']} />)
+ const group = sectionOf('Anthropic')
+ const name = within(group).getByLabelText(/Extra credential slot key name/i)
+
+ expect(within(group).queryByText(/Type a value to complete the rename/i)).toBeNull()
+ fireEvent.change(name, { target: { value: 'claude-api-key-fb2' } })
+ // Mute state made audible: the rename writes nothing, so the stored key
+ // keeps its old name and saving does nothing to this row.
+ expect(
+ within(group).getByText(/Type a value to complete the rename.*claude-api-key-fb1/i)
+ ).toBeInTheDocument()
+
+ fireEvent.change(within(group).getByLabelText(/Extra credential slot value/i), {
+ target: { value: 'sk-ant-new' },
+ })
+ expect(within(group).queryByText(/Type a value to complete the rename/i)).toBeNull()
+ })
+
+ it('does not re-report while unrelated canonical slots are typed', () => {
+ const onRemovedKeysChange = vi.fn()
+ render(<Harness existingKeys={['openai-api-key']} onRemovedKeysChange={onRemovedKeysChange} />)
+ // One report on mount, establishing the (empty) live region.
+ expect(onRemovedKeysChange.mock.calls).toHaveLength(1)
+
+ const input = screen.getByLabelText(/^OpenAI API key/i)
+ for (const value of ['s', 'sk', 'sk-', 'sk-l']) {
+ fireEvent.change(input, { target: { value } })
+ }
+ // The effect keys off the retirement signature, not the draft — keystrokes
+ // that retire nothing must not churn the parent's state.
+ expect(onRemovedKeysChange.mock.calls).toHaveLength(1)
+ })
+
+ it('lists every queued key in one hint, deduplicated and ordered', () => {
+ const onRemovedKeysChange = vi.fn()
+ render(
+ <Harness
+ existingKeys={['openai-api-key-fb2', 'claude-api-key-fb1']}
+ onRemovedKeysChange={onRemovedKeysChange}
+ />
+ )
+ fireEvent.click(removeSlotButton(sectionOf('OpenAI')))
+ fireEvent.click(removeSlotButton(sectionOf('Anthropic')))
+
+ expect(onRemovedKeysChange).toHaveBeenLastCalledWith([
+ 'claude-api-key-fb1',
+ 'openai-api-key-fb2',
+ ])
+ expect(removalHint()).toHaveTextContent(
+ 'Will be removed from the stored secret on save: claude-api-key-fb1, openai-api-key-fb2.'
+ )
+ })
+})
+
describe('providerForDataKey (B1, prefix-aware)', () => {
it('resolves canonical slot keys to their provider', () => {
expect(providerForDataKey('openai-api-key')).toBe('openai')
diff --git a/control-ui/components/__tests__/SecretsTable.test.tsx b/control-ui/components/__tests__/SecretsTable.test.tsx
index f0b101e4c..bebf8a32b 100644
--- a/control-ui/components/__tests__/SecretsTable.test.tsx
+++ b/control-ui/components/__tests__/SecretsTable.test.tsx
@@ -1,7 +1,14 @@
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
-import { getMcpServers, getRecipeSecrets, getRecipes } from '../../lib/api'
+import {
+ cleanup,
+ fireEvent,
+ render as rtlRender,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react'
+import { apiSend, getMcpServers, getRecipeSecrets, getRecipes } from '../../lib/api'
import { SecretsTable } from '../SecretsTable'
import { ToastProvider } from '../Toast'
@@ -16,16 +23,25 @@ vi.mock('../../lib/api', async () => {
const actual = await vi.importActual<typeof import('../../lib/api')>('../../lib/api')
return {
...actual,
+ apiSend: vi.fn(),
getMcpServers: vi.fn(),
getRecipeSecrets: vi.fn(),
getRecipes: vi.fn(),
}
})
+const apiSendMock = vi.mocked(apiSend)
const getMcpServersMock = vi.mocked(getMcpServers)
const getRecipeSecretsMock = vi.mocked(getRecipeSecrets)
const getRecipesMock = vi.mocked(getRecipes)
+// apiSend is the shared write path for every scope in this table, so its state
+// is reset for the whole file rather than per describe.
+beforeEach(() => {
+ apiSendMock.mockReset()
+ apiSendMock.mockResolvedValue(undefined as never)
+})
+
function renderTable(
activeScope: 'mcp' | 'recipe' = 'mcp',
onCreateRecipeSecretFor: (
@@ -50,6 +66,205 @@ 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', () => {
+ const SECRET = 'chatllm-api-keys'
+
+ function renderLlmTable(keys: string[]) {
+ return rtlRender(
+ <ToastProvider>
+ <SecretsTable
+ activeScope="llm"
+ items={[{ name: SECRET, keys }]}
+ onChanged={async () => {}}
+ onCreateLlmSecret={() => {}}
+ onCreateMcpSecret={() => {}}
+ onCreateRecipeSecret={() => {}}
+ onCreateRecipeSecretFor={() => {}}
+ />
+ </ToastProvider>
+ )
+ }
+
+ function openUpdateModal(keys: string[]) {
+ renderLlmTable(keys)
+ fireEvent.click(screen.getByRole('button', { name: `Update LLM secret ${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' }))
+
+ // 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'])
+ 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'])
+ 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: `Update LLM secret ${SECRET}` }))
+ removeExtraSlotIn('Anthropic')
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+
+ fireEvent.click(screen.getByRole('button', { name: `Update LLM secret ${SECRET}` }))
+ 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('SecretsTable — connector marketplace source', () => {
beforeEach(() => {
getMcpServersMock.mockReset()