Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
refactor(control-ui): make LLM secrets editor additive per provider
Diego Zacariaseee7e21c0ff5
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex 66a0029da..8b9754341 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -6698,6 +6698,23 @@ textarea.cu-input {align-items: center;}+/* Chip + optional remove icon-button on the right side of a group head. */+.cu-llm-cred-group__head-actions {+ display: flex;+ align-items: center;+ gap: 0.4rem;+}++/* Empty state of the additive editor (no provider sections mounted yet). */+.cu-llm-cred-empty {+ margin: 0;+}++/* The "+ Add provider" picker of the additive editor. */+select.cu-input.cu-llm-cred-add {+ max-width: 14rem;+}+/* ── Host LLM config surface (spec Topic 1b, jury design C) ───────────────── */.cu-llm-config {display: flex;diff --git a/control-ui/components/LlmCredentialFields/index.tsx b/control-ui/components/LlmCredentialFields/index.tsxindex f65893f9d..84105c7f6 100644--- a/control-ui/components/LlmCredentialFields/index.tsx+++ b/control-ui/components/LlmCredentialFields/index.tsx@@ -4,9 +4,19 @@ import React, { useMemo, useRef, useState } from 'react'import Link from 'next/link'import { CONTROL_ROUTES } from '@constants/routes'import { IconX } from '@/components/icons'-import { Button, Field, TextAreaInput, TextInput } from '@/components/ui'+import { Button, Field, SelectInput, TextAreaInput, TextInput } from '@/components/ui'import { cn } from '@/lib/cn'-import { LLM_CREDENTIAL_GROUPS, type LlmCredentialGroup, getLlmGroupCompleteness } from '@/lib/llm'+import {+ LLM_CREDENTIAL_GROUPS,+ type LlmCredentialGroup,+ type LlmProvider,+ getLlmGroupCompleteness,+ mintFallbackSlot,+ providerForDataKey,+} from '@/lib/llm'+import type { ExtraSlot, LlmCredentialFieldsProps } from './types'++export type { LlmCredentialFieldsProps } from './types'// Where the non-secret per-Host env vars (VERTEX_PROJECT_ID/-LOCATION,// AWS_REGION) are configured — the secrets form only links to it, it never@@ -18,34 +28,39 @@ const HOST_ENV_HREF = CONTROL_ROUTES.agents.root// dataKey", never free-form).const DATA_KEY_PATTERN = /^[a-zA-Z0-9]([a-zA-Z0-9._-]*[a-zA-Z0-9])?$/-// An operator-created extra credential slot (spec R4.5.6). The slot OWNS its-// name draft and value; only a validated, non-colliding key is ever projected-// into the parent `draft` (`committedKey`). This guarantees editing an extra-// slot can never write to — and clobber — a real provider slot, and that an-// invalid/colliding key never reaches submit.-type ExtraSlot = {- id: string- provider: string- nameInput: string- value: string- committedKey: string | null-}--export type LlmCredentialFieldsProps = {- // dataKey -> value. Write-only: existing values are NEVER passed in here (the- // status-only listing returns names only, spec R4.5.3).- draft: Record<string, string>- onChange: (dataKey: string, value: string) => void- disabled?: boolean- // Keys already stored in the Secret (edit mode) — light up the present chips- // without ever exposing a value. Create flows omit it.- existingKeys?: string[]-}-// Input-id prefix. Only one LlmCredentialFields renders per page and every slot// id already ends in a unique dataKey/slot id, so this is a fixed constant.const ID_PREFIX = 'llm-secret'+// Every canonical (registry) slot dataKey across providers. An existing Secret+// key outside this set is an operator-minted extra slot (`claude-api-key-fb1`).+const CANONICAL_SLOT_KEYS: ReadonlySet<string> = new Set(+ LLM_CREDENTIAL_GROUPS.flatMap(group => group.slots.map(slot => slot.dataKey))+)++// Seed one ExtraSlot per stored NON-canonical key so a Secret that only holds+// an extra slot of a provider (e.g. `claude-api-key-fb1` minted by the agents+// flow) still shows that key visible and editable inside its provider section+// (additive editor spec B1). `committedKey` starts null: stored values never+// enter the write-only draft until the operator types a replacement.+function seedExistingExtraSlots(existingKeys: string[] | undefined): ExtraSlot[] {+ const slots: ExtraSlot[] = []+ for (const key of new Set(existingKeys ?? [])) {+ if (CANONICAL_SLOT_KEYS.has(key)) continue+ const provider = providerForDataKey(key)+ if (!provider) continue+ slots.push({+ id: `existing-${key}`,+ provider,+ nameInput: key,+ value: '',+ committedKey: null,+ existingKey: key,+ })+ }+ return slots+}+function completenessChip(group: LlmCredentialGroup, present: (dataKey: string) => boolean) {const { present: filled, total, usable } = getLlmGroupCompleteness(group, present)// Single-slot providers read as present/absent; multi-slot providers show the@@ -71,13 +86,46 @@ export function LlmCredentialFields({disabled = false,existingKeys,}: LlmCredentialFieldsProps) {- const [extraSlots, setExtraSlots] = useState<ExtraSlot[]>([])+ const [extraSlots, setExtraSlots] = useState<ExtraSlot[]>(() =>+ seedExistingExtraSlots(existingKeys)+ )+ // 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.+ const [manuallyAdded, setManuallyAdded] = useState<ReadonlySet<LlmProvider>>(() => new Set())const nextExtraId = useRef(0)const existingKeySet = useMemo(() => new Set(existingKeys ?? []), [existingKeys])const present = (dataKey: string): boolean =>(draft[dataKey] ?? '').trim().length > 0 || existingKeySet.has(dataKey)+ // Additive visibility (spec S1) — a provider section renders only when:+ // - the Secret already stores one of its keys (canonical or extra), or+ // - the draft carries a non-empty value for one of its keys (typed now, or+ // surviving a create-flow step remount — never "key present in draft":+ // createEmptyLlmKeyDraft seeds '' under EVERY canonical key), or+ // - the operator added it this session.+ // Everything else stays hidden behind "+ Add provider".+ const visibleProviders = useMemo(() => {+ const visible = new Set<LlmProvider>()+ for (const key of existingKeySet) {+ const provider = providerForDataKey(key)+ if (provider) visible.add(provider)+ }+ for (const [key, value] of Object.entries(draft)) {+ if (value.trim().length === 0) continue+ const provider = providerForDataKey(key)+ if (provider) visible.add(provider)+ }+ for (const provider of manuallyAdded) visible.add(provider)+ return visible+ }, [draft, existingKeySet, manuallyAdded])++ // Filtering LLM_CREDENTIAL_GROUPS (instead of iterating the sets) keeps the+ // canonical package order regardless of the order providers were added.+ const visibleGroups = LLM_CREDENTIAL_GROUPS.filter(group => visibleProviders.has(group.provider))+ const addableGroups = LLM_CREDENTIAL_GROUPS.filter(group => !visibleProviders.has(group.provider))+// The full set of keys the form already knows (package slots + created extra// slots) — used to flag duplicate extra-slot names.const knownKeys = useMemo(() => {@@ -89,12 +137,16 @@ export function LlmCredentialFields({return keys}, [existingKeySet])- function extraSlotError(id: string, nameInput: string): string | null {+ 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 - . _'- if (knownKeys.has(trimmed)) return 'This key already exists as a provider slot.'- if (extraSlots.some(slot => slot.id !== id && slot.nameInput.trim() === trimmed)) {+ // 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) {+ return 'This key already exists as a provider slot.'+ }+ if (extraSlots.some(item => item.id !== slot.id && item.nameInput.trim() === trimmed)) {return 'Duplicate key name.'}return null@@ -104,7 +156,7 @@ export function LlmCredentialFields({// valid, non-colliding key is committed; the previously-committed key (always// itself a validated key, never a real provider slot) is cleared on change.function commitExtraSlot(slot: ExtraSlot, nextName: string, nextValue: string) {- const nextCommitted = extraSlotError(slot.id, nextName) === null ? nextName.trim() : null+ const nextCommitted = extraSlotError(slot, nextName) === null ? nextName.trim() : nullif (slot.committedKey && slot.committedKey !== nextCommitted) {onChange(slot.committedKey, '')}@@ -118,13 +170,19 @@ export function LlmCredentialFields({)}- function addExtraSlot(provider: string) {- const existingForProvider = extraSlots.filter(slot => slot.provider === provider).length- const suggested = `${provider}-api-key-fb${existingForProvider + 1}`+ function addExtraSlot(provider: LlmProvider) {+ // Suggest the first `${provider}-api-key-fbN` not already claimed by the+ // stored Secret or another slot in the form (mirrors mintFallbackSlot in+ // the agents flow), so a seeded `-fb1` never collides with the suggestion.+ const claimed = new Set<string>([+ ...existingKeySet,+ ...extraSlots.map(slot => slot.nameInput.trim()),+ ])+ const suggested = mintFallbackSlot(provider, claimed)const id = `extra-${provider}-${nextExtraId.current++}`setExtraSlots(prev => [...prev,- { id, provider, nameInput: suggested, value: '', committedKey: null },+ { id, provider, nameInput: suggested, value: '', committedKey: null, existingKey: null },])}@@ -135,21 +193,85 @@ export function LlmCredentialFields({setExtraSlots(prev => prev.filter(item => item.id !== id))}+ function addProvider(value: string) {+ const group = LLM_CREDENTIAL_GROUPS.find(item => item.provider === value)+ if (!group) return+ setManuallyAdded(prev => new Set(prev).add(group.provider))+ }++ // Removable only when hiding the section cannot lose anything (spec S2): the+ // provider was added this session AND no key of it carries a committed value+ // (canonical or extra). Two terms compose the value check:+ // - draft scan via providerForDataKey — canonical slots and extras whose+ // key still carries a recognizable provider prefix;+ // - the extra-slot STATE — an extra slot renamed to a custom key (e.g.+ // `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.+ function isProviderRemovable(provider: LlmProvider): boolean {+ if (!manuallyAdded.has(provider)) return false+ const hasDraftValue = Object.entries(draft).some(+ ([key, value]) => value.trim().length > 0 && providerForDataKey(key) === provider+ )+ if (hasDraftValue) return false+ return !extraSlots.some(+ slot =>+ slot.provider === provider && slot.committedKey !== null && slot.value.trim().length > 0+ )+ }++ function removeProvider(provider: LlmProvider) {+ // Clear the provider's extra slots first so no committedKey stays orphaned+ // in the parent draft (spec §5 — their values are empty per the gate, but+ // the committed keys themselves must not linger).+ for (const slot of extraSlots.filter(item => item.provider === provider)) {+ removeExtraSlot(slot.id)+ }+ setManuallyAdded(prev => {+ const next = new Set(prev)+ next.delete(provider)+ return next+ })+ }+return (<div className="cu-llm-cred-groups">- {LLM_CREDENTIAL_GROUPS.map(group => {+ {visibleGroups.length === 0 ? (+ <p className="cu-field__hint cu-llm-cred-empty">+ No providers added yet — add a provider below to enter its credentials.+ </p>+ ) : null}++ {visibleGroups.map(group => {const chip = completenessChip(group, present)const providerExtras = extraSlots.filter(slot => slot.provider === group.provider)+ const removable = isProviderRemovable(group.provider)return (<section className="cu-llm-cred-group" key={group.provider}><div className="cu-llm-cred-group__head"><span className="cu-llm-cred-group__title">{group.label}</span>- <span- className={cn('cu-slot-chip', `cu-slot-chip--${chip.state}`)}- aria-label={`${group.label} credentials ${chip.text}`}- >- <span aria-hidden="true">{chip.symbol}</span>- {chip.text}+ <span className="cu-llm-cred-group__head-actions">+ <span+ className={cn('cu-slot-chip', `cu-slot-chip--${chip.state}`)}+ aria-label={`${group.label} credentials ${chip.text}`}+ >+ <span aria-hidden="true">{chip.symbol}</span>+ {chip.text}+ </span>+ {removable ? (+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--danger-icon"+ onClick={() => removeProvider(group.provider)}+ disabled={disabled}+ aria-label={`Remove ${group.label} provider`}+ title={`Remove ${group.label} provider`}+ >+ <IconX width={16} height={16} />+ </button>+ ) : null}</span></div>@@ -212,7 +334,7 @@ export function LlmCredentialFields({{providerExtras.map(slot => {const inputId = `${ID_PREFIX}-extra-${slot.id}`- const error = extraSlotError(slot.id, slot.nameInput)+ const error = extraSlotError(slot, slot.nameInput)return (<Fieldkey={slot.id}@@ -267,6 +389,23 @@ export function LlmCredentialFields({</section>)})}++ {addableGroups.length > 0 ? (+ <SelectInput+ className="cu-llm-cred-add"+ value=""+ onChange={event => addProvider(event.target.value)}+ disabled={disabled}+ aria-label="Add provider"+ >+ <option value="">+ Add provider…</option>+ {addableGroups.map(group => (+ <option key={group.provider} value={group.provider}>+ {group.label}+ </option>+ ))}+ </SelectInput>+ ) : null}</div>)}diff --git a/control-ui/components/LlmCredentialFields/types.ts b/control-ui/components/LlmCredentialFields/types.tsnew file mode 100644index 000000000..61284bf98--- /dev/null+++ b/control-ui/components/LlmCredentialFields/types.ts@@ -0,0 +1,30 @@+import type { LlmProvider } from '@/lib/llm'++// An operator-created extra credential slot (spec R4.5.6). The slot OWNS its+// name draft and value; only a validated, non-colliding key is ever projected+// into the parent `draft` (`committedKey`). This guarantees editing an extra+// slot can never write to — and clobber — a real provider slot, and that an+// invalid/colliding key never reaches submit.+export type ExtraSlot = {+ id: string+ provider: LlmProvider+ nameInput: string+ value: string+ committedKey: string | null+ // The stored Secret key this slot was seeded from (edit mode, additive+ // editor spec B1) — exempted from the "already exists" collision check so+ // the operator can keep the name while rewriting the value. Null for slots+ // created in this session.+ existingKey: string | null+}++export type LlmCredentialFieldsProps = {+ // dataKey -> value. Write-only: existing values are NEVER passed in here (the+ // status-only listing returns names only, spec R4.5.3).+ draft: Record<string, string>+ onChange: (dataKey: string, value: string) => void+ disabled?: boolean+ // Keys already stored in the Secret (edit mode) — light up the present chips+ // without ever exposing a value. Create flows omit it.+ existingKeys?: string[]+}diff --git a/control-ui/components/__tests__/LlmCredentialFields.test.tsx b/control-ui/components/__tests__/LlmCredentialFields.test.tsxindex f7ef8194c..9a67141eb 100644--- a/control-ui/components/__tests__/LlmCredentialFields.test.tsx+++ b/control-ui/components/__tests__/LlmCredentialFields.test.tsx@@ -1,40 +1,85 @@import { useState } from 'react'-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'+import { LLM_CREDENTIAL_GROUPS, providerForDataKey } from '@/lib/llm'import { LlmCredentialFields } from '../LlmCredentialFields'afterEach(cleanup)// A tiny controlled host so the component's draft/onChange contract is exercised-// the way the real forms wire it.-function Harness({ existingKeys }: { existingKeys?: string[] }) {+// the way the real forms wire it. `onDraftChange` observes every write for the+// cleanup assertions (the draft itself stays write-only).+function Harness({+ existingKeys,+ onDraftChange,+}: {+ existingKeys?: string[]+ onDraftChange?: (dataKey: string, value: string) => void+}) {const [draft, setDraft] = useState<Record<string, string>>({})return (<LlmCredentialFieldsdraft={draft}- onChange={(dataKey, value) => setDraft(prev => ({ ...prev, [dataKey]: value }))}+ onChange={(dataKey, value) => {+ onDraftChange?.(dataKey, value)+ setDraft(prev => ({ ...prev, [dataKey]: value }))+ }}existingKeys={existingKeys}/>)}-describe('LlmCredentialFields (spec R4.5)', () => {- it('renders a group per provider from the shared package', () => {+const addProviderSelect = () => screen.getByLabelText('Add provider') as HTMLSelectElement++function addProvider(provider: string) {+ fireEvent.change(addProviderSelect(), { target: { value: provider } })+}++// Provider sections are the only elements using this title class; option+// elements inside the "Add provider" picker share the same visible label, so+// plain getByText would be ambiguous.+const sectionTitle = (label: string) =>+ screen.queryByText(label, { selector: '.cu-llm-cred-group__title' })++const sectionOf = (label: string) => sectionTitle(label)!.closest('section') as HTMLElement++describe('LlmCredentialFields (additive provider editor)', () => {+ it('starts with no provider sections in create mode and offers every provider', () => {+ const { container } = render(<Harness />)+ expect(container.querySelectorAll('.cu-llm-cred-group')).toHaveLength(0)+ expect(screen.getByText(/No providers added yet/i)).toBeInTheDocument()+ // Placeholder option + one option per provider in the shared package.+ const options = within(addProviderSelect()).getAllByRole('option')+ expect(options).toHaveLength(LLM_CREDENTIAL_GROUPS.length + 1)+ })++ it('edit mode renders only the providers that already have a stored key', () => {+ render(<Harness existingKeys={['zai-api-key']} />)+ expect(sectionTitle('Z.AI')).toBeInTheDocument()+ expect(sectionTitle('OpenAI')).toBeNull()+ expect(sectionTitle('Anthropic')).toBeNull()+ expect(sectionTitle('Amazon Bedrock')).toBeNull()+ })++ it('adding a provider mounts its section and removes it from the picker', () => {render(<Harness />)- for (const label of [- 'OpenAI',- 'Anthropic',- 'Z.AI',- 'Bailian',- 'Google Vertex AI',- 'Amazon Bedrock',- ]) {- expect(screen.getByText(label)).toBeInTheDocument()- }+ addProvider('openai')+ expect(sectionTitle('OpenAI')).toBeInTheDocument()+ expect(within(addProviderSelect()).queryByRole('option', { name: 'OpenAI' })).toBeNull()+ // The rest stays hidden.+ expect(sectionTitle('Anthropic')).toBeNull()})- it('renders the Bedrock access-key pair and the Vertex JSON textarea', () => {+ it('hides the picker once every provider is visible', () => {render(<Harness />)+ for (const group of LLM_CREDENTIAL_GROUPS) addProvider(group.provider)+ expect(screen.queryByLabelText('Add provider')).toBeNull()+ })++ it('renders the Bedrock access-key pair and the Vertex JSON textarea when added', () => {+ render(<Harness />)+ addProvider('bedrock')+ addProvider('vertex')expect(screen.getByLabelText(/Amazon Bedrock access key ID/i)).toBeInTheDocument()expect(screen.getByLabelText(/Amazon Bedrock secret access key/i)).toBeInTheDocument()const vertex = screen.getByLabelText(/Google Vertex AI service account JSON/i)@@ -43,6 +88,7 @@ describe('LlmCredentialFields (spec R4.5)', () => {it('shows the non-secret env hint pointing at Host → Environment (no editor)', () => {render(<Harness />)+ addProvider('bedrock')expect(screen.getByText(/AWS_REGION/)).toBeInTheDocument()const links = screen.getAllByRole('link', { name: /Host → Environment/i })expect(links.length).toBeGreaterThan(0)@@ -51,6 +97,7 @@ describe('LlmCredentialFields (spec R4.5)', () => {it('flips a slot chip from absent to present as the value is typed', () => {render(<Harness />)+ addProvider('openai')// Anchor to start: a bare substring regex would also hit "Azure OpenAI API// key" (R6). `^` excludes it while tolerating the trailing chip text.const input = screen.getByLabelText(/^OpenAI API key/i)@@ -63,15 +110,129 @@ describe('LlmCredentialFields (spec R4.5)', () => {it('lights up a present chip for a stored key passed via existingKeys (edit mode)', () => {render(<Harness existingKeys={['openai-api-key']} />)- const openaiGroup = screen.getByText('OpenAI').closest('section') as HTMLElement+ const openaiGroup = sectionOf('OpenAI')// The stored key reads "present" even though no value is typed (values are// never returned by the listing).expect(within(openaiGroup).getAllByLabelText('present').length).toBeGreaterThan(0)})+ it('keeps a section visible from a non-empty draft across a remount (create-flow back/forward)', () => {+ // Mirrors /secrets/new: CreateStepFlow unmounts the step on Back, resetting+ // manuallyAdded, while the draft lives in the parent. The draft term of the+ // visibility formula (spec S1) must resurrect the section — otherwise the+ // typed value would be invisible but still submitted.+ function RemountHarness() {+ const [draft, setDraft] = useState<Record<string, string>>({})+ const [mounted, setMounted] = useState(true)+ return (+ <>+ <button type="button" onClick={() => setMounted(current => !current)}>+ toggle-mount+ </button>+ {mounted ? (+ <LlmCredentialFields+ draft={draft}+ onChange={(dataKey, value) => setDraft(prev => ({ ...prev, [dataKey]: value }))}+ />+ ) : null}+ </>+ )+ }+ render(<RemountHarness />)+ addProvider('zai')+ fireEvent.change(screen.getByLabelText(/^Z\.AI API key/i), { target: { value: 'zai-live' } })+ fireEvent.click(screen.getByRole('button', { name: 'toggle-mount' }))+ expect(sectionTitle('Z.AI')).toBeNull()+ fireEvent.click(screen.getByRole('button', { name: 'toggle-mount' }))+ expect(sectionTitle('Z.AI')).toBeInTheDocument()+ expect((screen.getByLabelText(/^Z\.AI API key/i) as HTMLInputElement).value).toBe('zai-live')+ })++ it('a manually added provider without values can be removed and returns to the picker', () => {+ render(<Harness />)+ addProvider('openai')+ fireEvent.click(screen.getByRole('button', { name: 'Remove OpenAI provider' }))+ expect(sectionTitle('OpenAI')).toBeNull()+ expect(within(addProviderSelect()).getByRole('option', { name: 'OpenAI' })).toBeInTheDocument()+ })++ 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.+ expect(screen.queryByRole('button', { name: 'Remove Z.AI provider' })).toBeNull()++ addProvider('openai')+ const input = screen.getByLabelText(/^OpenAI API key/i)+ fireEvent.change(input, { target: { value: 'sk-live' } })+ expect(screen.queryByRole('button', { name: 'Remove OpenAI provider' })).toBeNull()+ // Clearing the value re-arms the gate.+ fireEvent.change(input, { target: { value: '' } })+ expect(screen.getByRole('button', { name: 'Remove OpenAI provider' })).toBeInTheDocument()+ })++ it('removing a provider clears its committed extra-slot keys from the draft', () => {+ const onDraftChange = vi.fn()+ render(<Harness onDraftChange={onDraftChange} />)+ addProvider('zai')+ const group = sectionOf('Z.AI')+ fireEvent.click(within(group).getByRole('button', { name: /Add credential slot/i }))+ const value = within(group).getByLabelText(/Extra credential slot value/i)+ fireEvent.change(value, { target: { value: 'zai-fallback' } })+ // A committed extra-slot value blocks removal (spec S2 gate).+ expect(screen.queryByRole('button', { name: 'Remove Z.AI provider' })).toBeNull()+ fireEvent.change(value, { target: { value: '' } })+ fireEvent.click(screen.getByRole('button', { name: 'Remove Z.AI provider' }))+ expect(sectionTitle('Z.AI')).toBeNull()+ // The committed key was cleared — no orphan stays behind in the draft.+ expect(onDraftChange).toHaveBeenLastCalledWith('zai-api-key-fb1', '')+ })++ it('an extra slot renamed to a custom key with a value still blocks removal (S2)', () => {+ // providerForDataKey cannot attribute `team1.key` to any provider, so the+ // gate must fall back to the extra-slot state itself — otherwise the X+ // would silently discard the typed value in one click.+ const onDraftChange = vi.fn()+ render(<Harness onDraftChange={onDraftChange} />)+ addProvider('openai')+ const group = sectionOf('OpenAI')+ fireEvent.click(within(group).getByRole('button', { name: /Add credential slot/i }))+ 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: 'team1.key' } })+ fireEvent.change(value, { target: { value: 'sk-custom' } })+ expect(onDraftChange).toHaveBeenLastCalledWith('team1.key', 'sk-custom')+ // Committed value under an unattributable key → NOT removable.+ expect(screen.queryByRole('button', { name: 'Remove OpenAI provider' })).toBeNull()+ // Clearing the value re-arms the gate…+ fireEvent.change(value, { target: { value: '' } })+ fireEvent.click(screen.getByRole('button', { name: 'Remove OpenAI provider' }))+ // …and removal cleans the custom committed key out of the draft.+ expect(sectionTitle('OpenAI')).toBeNull()+ expect(onDraftChange).toHaveBeenLastCalledWith('team1.key', '')+ })++ it('a secret holding only an extra slot shows that provider with the slot editable (B1)', () => {+ const onDraftChange = vi.fn()+ render(<Harness existingKeys={['claude-api-key-fb1']} onDraftChange={onDraftChange} />)+ expect(sectionTitle('Anthropic')).toBeInTheDocument()+ const group = sectionOf('Anthropic')+ const name = within(group).getByLabelText(/Extra credential slot key name/i) as HTMLInputElement+ expect(name.value).toBe('claude-api-key-fb1')+ // Its own stored name is not flagged as a collision.+ expect(within(group).queryByText(/already exists as a provider slot/i)).toBeNull()+ // Present in the Secret → never removable from here.+ expect(screen.queryByRole('button', { name: 'Remove Anthropic provider' })).toBeNull()+ // Typing a value rewrites the stored key through the normal commit path.+ 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')+ })+it('adds an extra credential slot with the suggested fallback name (R4.5.6)', () => {render(<Harness />)- const openaiGroup = screen.getByText('OpenAI').closest('section') as HTMLElement+ addProvider('openai')+ const openaiGroup = sectionOf('OpenAI')fireEvent.click(within(openaiGroup).getByRole('button', { name: /Add credential slot/i }))const nameInput = within(openaiGroup).getByLabelText(/Extra credential slot key name/i@@ -79,12 +240,22 @@ describe('LlmCredentialFields (spec R4.5)', () => {expect(nameInput.value).toBe('openai-api-key-fb1')})+ it('suggests the next free fallback name when the Secret already claims fb1', () => {+ render(<Harness existingKeys={['openai-api-key', 'openai-api-key-fb1']} />)+ const openaiGroup = sectionOf('OpenAI')+ fireEvent.click(within(openaiGroup).getByRole('button', { name: /Add credential slot/i }))+ const names = within(openaiGroup).getAllByLabelText(/Extra credential slot key name/i)+ // names[0] is the seeded fb1; the new slot skips to fb2.+ expect((names[1] as HTMLInputElement).value).toBe('openai-api-key-fb2')+ })+it('renaming an extra slot onto a real provider key does not clobber it', () => {render(<Harness />)+ addProvider('openai')const openai = screen.getByLabelText(/^OpenAI API key/i) as HTMLInputElementfireEvent.change(openai, { target: { value: 'sk-real' } })- const openaiGroup = screen.getByText('OpenAI').closest('section') as HTMLElement+ const openaiGroup = sectionOf('OpenAI')fireEvent.click(within(openaiGroup).getByRole('button', { name: /Add credential slot/i }))const extraName = within(openaiGroup).getByLabelText(/Extra credential slot key name/i@@ -102,3 +273,29 @@ describe('LlmCredentialFields (spec R4.5)', () => {expect(within(openaiGroup).getByText(/already exists as a provider slot/i)).toBeInTheDocument()})})++describe('providerForDataKey (B1, prefix-aware)', () => {+ it('resolves canonical slot keys to their provider', () => {+ expect(providerForDataKey('openai-api-key')).toBe('openai')+ expect(providerForDataKey('claude-api-key')).toBe('claude')+ expect(providerForDataKey('aws-access-key-id')).toBe('bedrock')+ expect(providerForDataKey('aws-secret-access-key')).toBe('bedrock')+ expect(providerForDataKey('vertex-service-account-json')).toBe('vertex')+ })++ it('resolves extra-slot keys by provider prefix or canonical-slot prefix', () => {+ expect(providerForDataKey('claude-api-key-fb1')).toBe('claude')+ expect(providerForDataKey('openai-api-key-fb2')).toBe('openai')+ expect(providerForDataKey('zai-secondary-key')).toBe('zai')+ expect(providerForDataKey('bedrock-api-key-fb1')).toBe('bedrock')+ // Bedrock extras minted from the canonical slot name carry no `bedrock-`+ // prefix — the canonical-slot-prefix rule must still claim them.+ expect(providerForDataKey('aws-access-key-id-fb1')).toBe('bedrock')+ })++ it('returns null for keys owned by no provider', () => {+ expect(providerForDataKey('random-key')).toBeNull()+ expect(providerForDataKey('SOME_ENV_VAR')).toBeNull()+ expect(providerForDataKey('')).toBeNull()+ })+})diff --git a/control-ui/lib/llm.ts b/control-ui/lib/llm.tsindex 9554fd687..eae1db576 100644--- a/control-ui/lib/llm.ts+++ b/control-ui/lib/llm.ts@@ -579,6 +579,30 @@ export function getCredentialSlotOptions(return Array.from(new Set([...registrySlots, ...extras]))}+// Derive the provider that owns a Secret dataKey, or null for a stray key+// (additive LLM secrets editor, spec B1). Prefix-aware — matching only+// canonical slots would lose operator-minted EXTRA slots (`claude-api-key-fb1`+// from mintFallbackSlot, or the secrets form's "Add credential slot"), making+// a Secret that holds ONLY an extra slot of a provider render that provider+// as absent. Mirrors the extra-key matching in getCredentialSlotOptions:+// 1. an exact canonical (registry) slot dataKey → its provider;+// 2. otherwise, a key carrying a provider's `${provider}-` prefix or+// extending one of its canonical slot keys (the suggested `<slot>-fbN`+// naming; covers Bedrock's `aws-…` extras) → that provider. A canonical+// key of ANOTHER provider can never fall here — rule 1 already claimed+// every key in ALL_REGISTRY_SLOT_KEYS;+// 3. otherwise → null (the editor ignores the key).+export function providerForDataKey(dataKey: string): LlmProvider | null {+ for (const group of LLM_CREDENTIAL_GROUPS) {+ if (group.slots.some(slot => slot.dataKey === dataKey)) return group.provider+ }+ for (const group of LLM_CREDENTIAL_GROUPS) {+ const prefixes = [...group.slots.map(slot => slot.dataKey), `${group.provider}-`]+ if (prefixes.some(prefix => dataKey.startsWith(prefix))) return group.provider+ }+ return null+}+// Client-side mirror of control-api's write gate (hostSpecValidation.ts): every// fallback entry must name a known provider and a model that is ENABLED in the// operator allowlist for that provider; cooldown must be a non-negative integer;diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 9c97858f2..ebdcfde2b 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.344",+ "version": "0.1.345","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.344",+ "version": "0.1.345","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 925194420..d2e7b9c55 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.344",+ "version": "0.1.345","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",