Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-ui): preserve credential set mode after sync
Josué682ce9bc4171
diff --git a/control-ui/components/UpdateConnectorCredentials/index.tsx b/control-ui/components/UpdateConnectorCredentials/index.tsxindex 0d548492e..781fdac88 100644--- a/control-ui/components/UpdateConnectorCredentials/index.tsx+++ b/control-ui/components/UpdateConnectorCredentials/index.tsx@@ -5,7 +5,13 @@ import { DataTable } from '@clerum/frontend-components'import { useConfirmDialog } from '@components/ConfirmDialog'import { useToast } from '@components/Toast'import { Button, Field, FormSection, TextInput } from '@components/ui'-import { getMcpServer, getMcpServers, getRegistryCredentialSchema, updateMcpSecret } from '@lib/api'+import {+ createMcpSecret,+ getMcpServer,+ getMcpServers,+ getRegistryCredentialSchema,+ updateMcpSecret,+} from '@lib/api'import type { McpServerCondition } from '@lib/api'import type { RotationPhase, UpdateConnectorCredentialsProps } from './types'@@ -52,6 +58,45 @@ export const ROLLOUT_INCOMPLETE_REASON = 'RolloutIncomplete'// excluded. 5s comfortably covers ordinary NTP drift.export const CLOCK_SKEW_TOLERANCE_MS = 5_000+// The aggregate validation alert's id. Rejected inputs point at it through+// `aria-describedby`, so a screen reader announces WHY a field is invalid from+// the field itself instead of only when the operator happens to reach the+// banner at the bottom of the form.+const VALIDATION_ERROR_ID = 'mcp-cred-validation-error'++// Kubernetes permits Secret keys that overlap Object.prototype, including+// __proto__, constructor, and toString. Credential drafts and request payloads+// therefore cannot be ordinary objects: reading an untouched key must mean+// "absent", never an inherited method or prototype value.+type CredentialMap = Record<string, string>++function emptyCredentialMap(): CredentialMap {+ return Object.create(null) as CredentialMap+}++function ownCredentialValue(credentials: CredentialMap, secretKey: string): string | undefined {+ return Object.hasOwn(credentials, secretKey) ? credentials[secretKey] : undefined+}++function withCredentialValue(+ credentials: CredentialMap,+ secretKey: string,+ value: string+): CredentialMap {+ const next = emptyCredentialMap()+ for (const key of Object.keys(credentials)) {+ next[key] = credentials[key]+ }+ next[secretKey] = value+ return next+}++/** Stable per-key input id, shared by the label's `htmlFor` and the+ * post-submit focus lookup. */+function inputId(secretKey: string): string {+ return `mcp-cred-${secretKey}`+}+function buildConfirmMessage(secretName: string, affected: string[] | null): string {if (affected === null) {return `This rotates the credential value(s) you entered in Secret "${secretName}" and restarts any connector that references it.`@@ -83,13 +128,20 @@ function findFreshDeploymentReady(export function UpdateConnectorCredentials({serverName,envSecret,+ surface = 'rotate',+ recipeOwned = false,registryCredentialSource,}: UpdateConnectorCredentialsProps) {const { showToast } = useToast()const { confirm, confirmDialog } = useConfirmDialog()- const [draft, setDraft] = useState<Record<string, string>>({})+ const [draft, setDraft] = useState<CredentialMap>(emptyCredentialMap)const [validationError, setValidationError] = useState('')+ // The secretKeys the last submit rejected. Drives per-input `aria-invalid` /+ // `aria-describedby`, so the aggregate alert is not the ONLY way to learn+ // which fields are wrong — assistive technology gets the association on the+ // control itself.+ const [invalidKeys, setInvalidKeys] = useState<string[]>([])// Best-effort preview of "who restarts", shown in the pre-save confirm// dialog (requisito 5). The authoritative list only exists after the PUT// (Fase 1 regla 9) — this mirrors the server's own@@ -101,7 +153,18 @@ export function UpdateConnectorCredentials({const [phaseMessage, setPhaseMessage] = useState('')const [rotationCutoff, setRotationCutoff] = useState<string | null>(null)const [rotationAffected, setRotationAffected] = useState<string[]>([])- const [credentialLabels, setCredentialLabels] = useState<Record<string, string>>({})+ // Labels use the same Kubernetes-valid key namespace as drafts. Keep this+ // map prototype-safe as well, because Marketplace schemas may contain keys+ // such as `constructor` or `__proto__`.+ const [credentialLabels, setCredentialLabels] = useState<CredentialMap>(emptyCredentialMap)+ // Latches the form onto rotate semantics after a successful create, so a+ // stale `surface` prop cannot leave "set" copy on a Secret that now exists.+ const [secretCreated, setSecretCreated] = useState(false)+ // Latches the form onto set semantics when a rotate PUT 404s.+ const [recreateRequired, setRecreateRequired] = useState(false)+ // Which operation is actually in flight / just completed. Captured at submit+ // time and used for the in-flight and success banners.+ const [submittedMode, setSubmittedMode] = useState<'set' | 'rotate'>('rotate')// The HCC's most recent RolloutIncomplete diagnostic, kept across polls (a// ref, not state: it only matters at the timeout boundary, so it must not// re-render or re-fire the poll effect). Seeing RolloutIncomplete never@@ -140,7 +203,7 @@ export function UpdateConnectorCredentials({useEffect(() => {if (!registryCredentialSource) {- setCredentialLabels({})+ setCredentialLabels(emptyCredentialMap())return}@@ -151,12 +214,12 @@ export function UpdateConnectorCredentials({).then(schema => {if (cancelled) return- setCredentialLabels(- Object.fromEntries(schema.keys.map(key => [key.name, key.label || key.name]))- )+ const labels = emptyCredentialMap()+ for (const key of schema.keys) labels[key.name] = key.label || key.name+ setCredentialLabels(labels)}).catch(() => {- if (!cancelled) setCredentialLabels({})+ if (!cancelled) setCredentialLabels(emptyCredentialMap())})return () => {@@ -238,10 +301,12 @@ export function UpdateConnectorCredentials({// No verdict either way inside the budget — an inconclusive// timeout, distinct from a diagnosed failure.setPhase('timeout')+ // Diagnostic only. The "what to try next" sentence is mode-specific+ // and is appended by the timeout banner from `submittedMode`.setPhaseMessage(`The rollout did not finish within ${Math.round(POLL_TIMEOUT_MS / 1000)}s. Run ` +`"kubectl get mcpserver ${serverName} -o yaml" to see the current DeploymentReady ` +- 'condition, or try the rotation again.'+ 'condition.')}}@@ -256,6 +321,16 @@ export function UpdateConnectorCredentials({}}, [phase, rotationCutoff, serverName])+ // "The Secret is missing and this screen would have to create it." Two+ // sources feed it, and `secretCreated` gates BOTH — not just the `surface`+ // prop. That latch flips the moment a create succeeds, and the Secret it+ // created exists from then on, whether the form got here from a stale+ // `surface` prop or from a rotate PUT that 404'd (`recreateRequired`).+ const secretMissing = !secretCreated && (recreateRequired || surface === 'set')+ // Ownership is the can-create invariant, and it is NOT derived from the+ // observed condition — see the `recipeOwned` prop doc.+ const mode: 'set' | 'rotate' = secretMissing && !recipeOwned ? 'set' : 'rotate'+if (!envSecret) {return (<FormSection title="Update credentials">@@ -267,32 +342,85 @@ export function UpdateConnectorCredentials({)}+ // A WorkflowRecipe-owned connector whose Secret is missing: the Secret name+ // belongs to the recipe, and HCC never creates a Deployment for+ // managed:false, so a create here would both cross an ownership boundary and+ // never converge.+ if (surface === 'recipe-owned' || (recipeOwned && secretMissing)) {+ return (+ <FormSection title="Update credentials">+ <p className="cu-muted">+ This connector's credentials are managed by its WorkflowRecipe. Add the Secret+ through the recipe's secrets, not here.+ </p>+ </FormSection>+ )+ }+function updateField(secretKey: string, value: string) {- setDraft(prev => ({ ...prev, [secretKey]: value }))+ setDraft(prev => withCredentialValue(prev, secretKey, value))if (validationError) setValidationError('')+ // The alert the inputs point at is about to disappear, so the association+ // has to go with it — a dangling aria-describedby is worse than none.+ if (invalidKeys.length > 0) setInvalidKeys([])+ }++ /** Rejects a submit: shows the aggregate alert, marks the offending inputs,+ * and moves focus to the first one so the repair is reachable without+ * hunting for it. `keys` may be empty (rotate mode's "at least one" rule+ * blames no single field); focus then lands on the first input. */+ function rejectSubmit(message: string, keys: string[]) {+ setValidationError(message)+ setInvalidKeys(keys)+ const focusKey = keys[0] ?? envSecret!.keys[0]?.secretKey+ if (!focusKey) return+ const target = document.getElementById(inputId(focusKey))+ if (target instanceof HTMLElement) target.focus()}async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {event.preventDefault()if (phase === 'saving' || phase === 'rotating') return- const data: Record<string, string> = {}+ const data = emptyCredentialMap()for (const key of envSecret!.keys) {- const value = draft[key.secretKey]- if (value && value.trim() !== '') data[key.secretKey] = value+ const value = ownCredentialValue(draft, key.secretKey)+ if (typeof value === 'string' && value.trim() !== '') data[key.secretKey] = value}- if (Object.keys(data).length === 0) {- setValidationError('Enter at least one credential value to rotate.')+ if (mode === 'set') {+ // Every declared key is required. HCC validates each key and answers+ // SecretMissingKey if any is absent, so a partial create would just swap+ // one broken state for another while this screen reported success.+ const missing = envSecret!.keys+ .map(k => k.secretKey)+ .filter(secretKey => !(data[secretKey] && data[secretKey].trim()))+ if (missing.length > 0) {+ rejectSubmit(`Enter every credential value. Missing: ${missing.join(', ')}.`, missing)+ return+ }+ } else if (Object.keys(data).length === 0) {+ // No single field is at fault here — the rule is "at least one" — so+ // nothing is marked invalid; focus just returns to the top of the form.+ rejectSubmit('Enter at least one credential value to rotate.', [])return}setValidationError('')-- const confirmed = await confirm({- title: 'Rotate credentials',- message: buildConfirmMessage(envSecret!.name, previewAffected),- confirmLabel: 'Rotate & restart',- tone: 'danger',- })+ setInvalidKeys([])++ const confirmed = await confirm(+ mode === 'set'+ ? {+ title: 'Set credentials',+ message: `This creates Secret "${envSecret!.name}" and starts ${serverName}.`,+ confirmLabel: 'Set & start',+ }+ : {+ title: 'Rotate credentials',+ message: buildConfirmMessage(envSecret!.name, previewAffected),+ confirmLabel: 'Rotate & restart',+ tone: 'danger',+ }+ )if (!confirmed) return// Captured BEFORE the PUT fires — the correlation anchor the poll below@@ -303,22 +431,55 @@ export function UpdateConnectorCredentials({// the server (ordinary NTP skew), a genuinely fresh condition could carry a// timestamp just *before* this cutoff and be wrongly discarded, wedging the// UI until the 180s timeout. Back the anchor off by a small tolerance so- // clock skew can't hide the rotation's own outcome. The window we widen is- // harmless: a truly stale condition predates the PUT by the full rollout,- // far more than this margin.+ // clock skew can't hide the rotation's own outcome.const cutoff = new Date(Date.now() - CLOCK_SKEW_TOLERANCE_MS).toISOString()setPhase('saving')setPhaseMessage('')+ setSubmittedMode(mode)try {- const result = await updateMcpSecret(envSecret!.name, data)- setDraft({})- setRotationAffected(result.affectedConnectors)+ if (mode === 'set') {+ try {+ await createMcpSecret(envSecret!.name, data)+ } catch (postError) {+ // The Secret may have appeared between page load and submit. Retry as+ // a merge-patch without inspecting status: control-api answers a bare+ // 500 for AlreadyExists, not reliably 409.+ try {+ await updateMcpSecret(envSecret!.name, data)+ } catch (putError) {+ throw (putError as { status?: number })?.status === 404 ? postError : putError+ }+ }+ setSecretCreated(true)+ // POST returns no affectedConnectors, so fall back to the best-effort+ // preview for the "who else restarts" note.+ setRotationAffected(previewAffected ?? [])+ } else {+ try {+ const result = await updateMcpSecret(envSecret!.name, data)+ setRotationAffected(result.affectedConnectors)+ } catch (putError) {+ // The Secret is gone. Do NOT silently POST: rotate mode may hold only+ // one of several declared keys. Demand every key instead.+ if ((putError as { status?: number })?.status === 404) {+ setRecreateRequired(true)+ setSecretCreated(false)+ setPhase('idle')+ setValidationError('This Secret no longer exists. Enter every key to recreate it.')+ return+ }+ throw putError+ }+ }+ setDraft(emptyCredentialMap())setRotationCutoff(cutoff)setPhase('rotating')} catch (e) {setPhase('failed')- setPhaseMessage(e instanceof Error ? e.message : 'Failed to rotate credentials')- showToast('Failed to rotate credentials.', { tone: 'error' })+ setPhaseMessage(e instanceof Error ? e.message : 'Failed to save credentials')+ showToast(mode === 'set' ? 'Failed to set credentials.' : 'Failed to rotate credentials.', {+ tone: 'error',+ })}}@@ -348,104 +509,143 @@ export function UpdateConnectorCredentials({return (<FormSection- title="Update credentials"+ title={mode === 'set' ? 'Set credentials' : 'Update credentials'}description={- <>- Rotate values stored in Secret <code>{envSecret.name}</code>. Values are write-only — this- screen never shows a stored credential, only key names.- </>+ mode === 'set' ? (+ <>+ This connector needs credentials before it can start. Values are write-only — this+ screen never shows a stored credential, only key names.+ </>+ ) : (+ <>+ Rotate values stored in Secret <code>{envSecret.name}</code>. Values are write-only —+ this screen never shows a stored credential, only key names.+ </>+ )}>{confirmDialog}- <form className="cu-connector-credentials-form" onSubmit={handleSubmit}>- <div className="cu-form-stack">- <div className="eft-table-viewport cu-table-wrap">- <DataTable className="eft-table cu-table">- <thead>- <tr>- <th>Secret key</th>- <th>Env var</th>- </tr>- </thead>- <tbody>- {envSecret.keys.map(k => (- <tr key={k.secretKey}>- <td>- <code>{k.secretKey}</code>- </td>- <td>- <code>{k.envVar}</code>- </td>- </tr>- ))}- </tbody>- </DataTable>- </div>-- {envSecret.keys.map(k => (+ <div className="eft-table-viewport cu-table-wrap">+ <DataTable className="eft-table cu-table">+ <thead>+ <tr>+ <th>Secret key</th>+ <th>Env var</th>+ </tr>+ </thead>+ <tbody>+ {envSecret.keys.map(k => (+ <tr key={k.secretKey}>+ <td>+ <code>{k.secretKey}</code>+ </td>+ <td>+ <code>{k.envVar}</code>+ </td>+ </tr>+ ))}+ </tbody>+ </DataTable>+ </div>++ {/* `noValidate`: the browser's own required-field bubble would fire+ before handleSubmit and replace the aggregate message that actually+ NAMES the missing keys. The `required` attributes below are kept for+ their programmatic semantics. */}+ <form+ className="cu-connector-credentials-form cu-form-stack"+ onSubmit={handleSubmit}+ noValidate+ >+ {envSecret.keys.map(k => {+ const isInvalid = invalidKeys.includes(k.secretKey)+ return (<Fieldkey={k.secretKey}- htmlFor={`mcp-cred-${k.secretKey}`}- label={credentialLabels[k.secretKey] || k.secretKey}+ htmlFor={inputId(k.secretKey)}+ label={ownCredentialValue(credentialLabels, k.secretKey) ?? k.secretKey}+ required={mode === 'set'}><TextInput- id={`mcp-cred-${k.secretKey}`}+ id={inputId(k.secretKey)}type="password"autoComplete="new-password"- placeholder="Leave blank to keep current value"- value={draft[k.secretKey] || ''}+ placeholder={mode === 'set' ? 'Required' : 'Leave blank to keep current value'}+ value={ownCredentialValue(draft, k.secretKey) ?? ''}onChange={e => updateField(k.secretKey, e.target.value)}disabled={busy}+ required={mode === 'set'}+ aria-required={mode === 'set' || undefined}+ invalid={isInvalid}+ aria-invalid={isInvalid || undefined}+ aria-describedby={isInvalid ? VALIDATION_ERROR_ID : undefined}/></Field>- ))}-- {validationError ? (- <div className="cu-banner cu-banner--error" role="alert">- {validationError}- </div>- ) : null}-- {phase === 'rotating' ? (- <div className="cu-banner cu-banner--info" role="status">- Rotating credentials — waiting for {serverName} to restart with the new value.- {phaseMessage ? ` ${phaseMessage}` : ''}- </div>- ) : null}-- {phase === 'success' ? (- <div className="cu-banner cu-banner--ok" role="status">- Credentials rotated. {serverName} restarted and is serving the new credential.- {otherAffectedNote}- </div>- ) : null}-- {phase === 'failed' ? (- <div className="cu-banner cu-banner--error" role="alert">- Rotation failed: {phaseMessage}- </div>- ) : null}-- {phase === 'timeout' ? (- <div className="cu-banner cu-banner--warning" role="alert">- {phaseMessage}- </div>- ) : null}- </div>+ )+ })}++ {validationError ? (+ <div className="cu-banner cu-banner--error" role="alert" id={VALIDATION_ERROR_ID}>+ {validationError}+ </div>+ ) : null}++ {phase === 'rotating' ? (+ <div className="cu-banner cu-banner--info" role="status">+ {submittedMode === 'set'+ ? `Setting credentials — waiting for ${serverName} to start.`+ : `Rotating credentials — waiting for ${serverName} to restart with the new value.`}+ {phaseMessage ? ` ${phaseMessage}` : ''}+ </div>+ ) : null}++ {phase === 'success' ? (+ <div className="cu-banner cu-banner--ok" role="status">+ {submittedMode === 'set'+ ? `Credentials set. ${serverName} started and is serving the new credential.`+ : `Credentials rotated. ${serverName} restarted and is serving the new credential.`}+ {otherAffectedNote}+ </div>+ ) : null}++ {phase === 'failed' ? (+ <div className="cu-banner cu-banner--error" role="alert">+ {submittedMode === 'set'+ ? `Could not set credentials: ${phaseMessage}`+ : `Rotation failed: ${phaseMessage}`}+ </div>+ ) : null}++ {phase === 'timeout' ? (+ <div className="cu-banner cu-banner--warning" role="alert">+ {phaseMessage}{' '}+ {submittedMode === 'set'+ ? 'You can also try setting the credentials again.'+ : 'You can also try the rotation again.'}+ </div>+ ) : null}<div className="cu-create-actions">{phase === 'success' || phase === 'failed' || phase === 'timeout' ? (<Button type="button" onClick={resetToIdle}>- {phase === 'success' ? 'Done' : 'Rotate again'}+ {phase === 'success'+ ? 'Done'+ : submittedMode === 'set'+ ? 'Try again'+ : 'Rotate again'}</Button>) : (<Button type="submit" variant="primary" disabled={busy}>{phase === 'saving'? 'Saving…': phase === 'rotating'- ? 'Rotating…'- : 'Rotate credentials'}+ ? submittedMode === 'set'+ ? 'Starting…'+ : 'Rotating…'+ : mode === 'set'+ ? 'Set credentials'+ : 'Rotate credentials'}</Button>)}</div>diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 278a1675a..3bbc8d3ac 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.544",+ "version": "0.1.545","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.544",+ "version": "0.1.545","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 62b7f4db8..24917aa5a 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.544",+ "version": "0.1.545","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",