Skip to content

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

TypeScript

feat(control-ui): change a connector's assigned Secret

M8c816818652f
diff --git a/control-ui/app/mcp-servers/[name]/edit/page.tsx b/control-ui/app/mcp-servers/[name]/edit/page.tsx
index f88a79638..5457b184f 100644
--- a/control-ui/app/mcp-servers/[name]/edit/page.tsx
+++ b/control-ui/app/mcp-servers/[name]/edit/page.tsx
@@ -1,10 +1,11 @@
'use client'
-import React, { useCallback, useEffect, useMemo, useState } from 'react'
+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { AttachConnectorCredentials } from '@components/AttachConnectorCredentials'
import { AuthGate } from '@components/AuthGate'
import { FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'
+import { ChangeConnectorSecret } from '@components/ChangeConnectorSecret'
import { CreateFlowPanel } from '@components/CreateFlowPanel'
import { CreatePageHeader } from '@components/CreatePageHeader'
import { DashboardLayout } from '@components/DashboardLayout'
@@ -46,7 +47,11 @@ import {
mergeAccessSummaries,
sortAccessPrincipals,
} from '@lib/connectorAccess'
-import { credentialAttachUnavailable, sameCredentialSpec } from '@lib/connectorCredentials'
+import {
+ credentialAttachUnavailable,
+ credentialReferenceChangeUnavailable,
+ sameCredentialSpec,
+} from '@lib/connectorCredentials'
import { buildMcpEgressStatus, deriveEgressEditorInputs } from '@lib/egressModel'
import type { EgressEditorStatus } from '@lib/egressModel'
import { extractOAuthImmutables, oauthClientSecretRefName } from '@lib/oauthInstall'
@@ -70,6 +75,10 @@ const CONTEXT_ACCESS_GROUPS: Array<{ key: keyof ContextAccess; title: string }>
{ key: 'agents', title: 'Agents' },
]
+/** Keyboard focus must survive the credentials-panel swap when the change
+ * flow closes, so the trigger is addressed by a stable element id. */
+const CHANGE_SECRET_TRIGGER_ID = 'change-assigned-secret-trigger'
+
export default function EditMcpServerPage() {
const router = useRouter()
const params = useParams<{ name: string; tab?: string | string[] }>()
@@ -83,6 +92,7 @@ export default function EditMcpServerPage() {
const [loadError, setLoadError] = useState('')
const [saving, setSaving] = useState(false)
const [reloadTick, setReloadTick] = useState(0)
+ const [changeSource, setChangeSource] = useState<McpServerResource | null>(null)
const [attachActive, setAttachActive] = useState(false)
const [attachBusy, setAttachBusy] = useState(false)
const [egressDirty, setEgressDirty] = useState(false)
@@ -303,10 +313,37 @@ export default function EditMcpServerPage() {
}, [])
const onAttachFinished = useCallback(() => {
setAttachActive(false)
+ setChangeSource(null)
setAttachBusy(false)
setReloadTick(tick => tick + 1)
}, [])
+ // The change flow replaces the whole credentials panel; after it closes the
+ // trigger remounts (after a reload when a save happened). Park the return
+ // focus until the panel has settled, then hand focus back to the trigger.
+ const returnFocusState = useRef<'idle' | 'waiting-reload' | 'ready'>('idle')
+ const finishChangeFlow = useCallback(() => {
+ returnFocusState.current = 'waiting-reload'
+ onAttachFinished()
+ }, [onAttachFinished])
+ const cancelChangeFlow = useCallback(() => {
+ returnFocusState.current = 'ready'
+ setChangeSource(null)
+ }, [])
+ useEffect(() => {
+ if (returnFocusState.current === 'waiting-reload') {
+ // A save schedules a reload; focus must wait for it to finish.
+ if (loading) returnFocusState.current = 'ready'
+ return
+ }
+ if (returnFocusState.current !== 'ready') return
+ if (loading || changeSource || attachActive) return
+ const trigger = document.getElementById(CHANGE_SECRET_TRIGGER_ID)
+ if (!trigger) return
+ returnFocusState.current = 'idle'
+ trigger.focus()
+ }, [loading, changeSource, attachActive])
+
return (
<AuthGate>
<DashboardLayout isDetailPage>
@@ -372,7 +409,24 @@ export default function EditMcpServerPage() {
) : server ? (
activeTab === 'credentials' ? (
<div className="cu-connector-edit-form">
- {attachActive || !attachUnavailable ? (
+ {changeSource ? (
+ <ChangeConnectorSecret
+ serverName={name}
+ server={changeSource}
+ reference={resolveEnvSecret(changeSource.spec)!}
+ blockedReason={
+ egressDirty
+ ? 'Save or discard your egress changes before changing the assigned Secret.'
+ : saving
+ ? 'Wait for the egress save to finish.'
+ : undefined
+ }
+ onBusyChange={setAttachBusy}
+ onSpecSaved={setServer}
+ onFinished={finishChangeFlow}
+ onCancel={cancelChangeFlow}
+ />
+ ) : attachActive || !attachUnavailable ? (
<>
<AttachConnectorCredentials
key={name}
@@ -419,17 +473,42 @@ export default function EditMcpServerPage() {
)}
/>
) : envSecret ? (
- <UpdateConnectorCredentials
- serverName={name}
- envSecret={envSecret}
- registryCredentialSource={registryCredentialSource}
- surface={resolveCredentialSurface(
- server.status?.conditions,
- server.spec as { managed?: boolean } | undefined
- )}
- // Ownership is a spec fact, independent of observed status.
- recipeOwned={isRecipeOwned(server.spec as { managed?: boolean } | undefined)}
- />
+ <>
+ {!credentialReferenceChangeUnavailable(server) ? (
+ <FormSection
+ title="Assigned Secret"
+ description="Reuse stored credentials by choosing another Secret or changing its key mappings. Rotate credentials below to update values in the current shared Secret."
+ >
+ <p>
+ Current Secret: <code>{envSecret.name}</code>
+ </p>
+ <Button
+ id={CHANGE_SECRET_TRIGGER_ID}
+ disabled={attachBusy || saving || egressDirty}
+ onClick={() => setChangeSource(server)}
+ >
+ Change assigned Secret
+ </Button>
+ {egressDirty ? (
+ <p role="status">
+ Save or discard your egress changes before changing the assigned Secret.
+ </p>
+ ) : null}
+ </FormSection>
+ ) : null}
+ <UpdateConnectorCredentials
+ onBusyChange={setAttachBusy}
+ serverName={name}
+ envSecret={envSecret}
+ registryCredentialSource={registryCredentialSource}
+ surface={resolveCredentialSurface(
+ server.status?.conditions,
+ server.spec as { managed?: boolean } | undefined
+ )}
+ // Ownership is a spec fact, independent of observed status.
+ recipeOwned={isRecipeOwned(server.spec as { managed?: boolean } | undefined)}
+ />
+ </>
) : (
<FormSection title="Connector credentials">
<p className="cu-muted">{attachUnavailable}</p>
diff --git a/control-ui/components/ChangeConnectorSecret/index.tsx b/control-ui/components/ChangeConnectorSecret/index.tsx
new file mode 100644
index 000000000..cb486af9e
--- /dev/null
+++ b/control-ui/components/ChangeConnectorSecret/index.tsx
@@ -0,0 +1,194 @@
+'use client'
+
+import { useEffect, useRef, useState } from 'react'
+import { useConfirmDialog } from '@components/ConfirmDialog'
+import { ExistingConnectorSecretFields } from '@components/ExistingConnectorSecretFields'
+import { useToast } from '@components/Toast'
+import { useRolloutWait } from '@components/UpdateConnectorCredentials/useRolloutWait'
+import { Button, FormSection } from '@components/ui'
+import {
+ CredentialAttachError,
+ buildAttachPayload,
+ changeConnectorSecretReference,
+ sameCredentialSpec,
+ validateCredentialAttach,
+} from '@lib/connectorCredentials'
+import type {
+ AttachedCredentials,
+ ExistingCredentialSelection,
+} from '@lib/connectorCredentials.types'
+import type { ChangeConnectorSecretProps } from './types'
+
+export function ChangeConnectorSecret({
+ serverName,
+ server,
+ reference,
+ blockedReason,
+ onBusyChange,
+ onSpecSaved,
+ onFinished,
+ onCancel,
+}: ChangeConnectorSecretProps) {
+ const { confirm, confirmDialog } = useConfirmDialog()
+ const { showToast } = useToast()
+ const [selection, setSelection] = useState<ExistingCredentialSelection>({
+ rows: [],
+ ready: false,
+ })
+ const [submitting, setSubmitting] = useState(false)
+ const [saved, setSaved] = useState<AttachedCredentials | null>(null)
+ const [error, setError] = useState('')
+ const [refreshRequired, setRefreshRequired] = useState(false)
+ const lock = useRef(false)
+ const mounted = useRef(true)
+ const completed = useRef(false)
+ const callbacks = useRef({ onBusyChange, onFinished, onSpecSaved })
+ callbacks.current = { onBusyChange, onFinished, onSpecSaved }
+ const { phase, phaseMessage, setPhase, setPhaseMessage } = useRolloutWait({
+ serverName,
+ cutoff: saved?.cutoff ?? null,
+ expectedUid: saved?.server.metadata?.uid,
+ expectedGeneration: saved?.server.metadata?.generation,
+ })
+ const locked = submitting || Boolean(saved) || refreshRequired
+ const valid =
+ selection.ready &&
+ Boolean(selection.secret) &&
+ !validateCredentialAttach(
+ 'use-existing',
+ selection.secret?.name ?? '',
+ selection.rows,
+ server,
+ selection.secret,
+ { storedKeysOnly: true }
+ )
+ const changed =
+ valid &&
+ !sameCredentialSpec(
+ reference,
+ buildAttachPayload(selection.secret!.name, selection.rows).reference
+ )
+
+ useEffect(() => {
+ mounted.current = true
+ return () => {
+ mounted.current = false
+ }
+ }, [])
+ useEffect(() => {
+ callbacks.current.onBusyChange?.(locked)
+ return () => callbacks.current.onBusyChange?.(false)
+ }, [locked])
+ useEffect(() => {
+ if (phase !== 'success' || completed.current) return
+ completed.current = true
+ showToast(`Assigned Secret changed. ${serverName} is ready.`, { tone: 'success' })
+ callbacks.current.onFinished()
+ }, [phase, serverName, showToast])
+
+ async function submit(event: React.FormEvent) {
+ event.preventDefault()
+ if (lock.current || locked || blockedReason || !changed) return
+ lock.current = true
+ setSubmitting(true)
+ setError('')
+ try {
+ const accepted = await confirm({
+ title: 'Change assigned Secret',
+ confirmLabel: 'Assign and restart',
+ message: `Change ${serverName} from Secret "${reference.name}" to "${selection.secret!.name}" and restart it? Secret values stay unchanged. Other connectors keep their current assignments.`,
+ })
+ if (!accepted || !mounted.current) return
+ const result = await changeConnectorSecretReference({ serverName, server, selection })
+ if (!mounted.current) return
+ setSaved(result)
+ callbacks.current.onSpecSaved(result.server)
+ if (!result.server.metadata?.uid || !Number.isInteger(result.server.metadata.generation)) {
+ setPhase('timeout')
+ setPhaseMessage('Rollout identity is unavailable.')
+ } else setPhase('rotating')
+ } catch (error) {
+ if (!mounted.current) return
+ // A known verification/conflict error carries its own recovery message;
+ // anything else stays generic. Either way no shared Secret was touched.
+ const known = error instanceof CredentialAttachError
+ setError(
+ known
+ ? `${error.message} Secret values were not changed.`
+ : 'The assignment could not be completed or verified. Refresh credentials to review the connector before trying again. Secret values were not changed.'
+ )
+ setRefreshRequired(true)
+ } finally {
+ lock.current = false
+ if (mounted.current) setSubmitting(false)
+ }
+ }
+
+ return (
+ <FormSection
+ title="Change assigned Secret"
+ description="Choose reusable credentials and map stored keys. This changes only this connector’s assignment."
+ >
+ {confirmDialog}
+ <form className="cu-connector-credentials-form cu-form-stack--wide" onSubmit={submit}>
+ <p>
+ Currently assigned: <code>{reference.name}</code>
+ </p>
+ {server.spec?.remote ? (
+ <p className="cu-muted">
+ Remote credentials use existing authentication header placeholders. Keep their
+ environment variable names; assigning a Secret does not add headers.
+ </p>
+ ) : null}
+ {blockedReason ? (
+ <p role="status" className="cu-banner cu-banner--warn">
+ {blockedReason}
+ </p>
+ ) : null}
+ <ExistingConnectorSecretFields
+ server={server}
+ initialReference={reference}
+ disabled={locked}
+ onChange={setSelection}
+ />
+ {error ? (
+ <p role="alert" className="cu-banner cu-banner--error">
+ {error}
+ </p>
+ ) : null}
+ {phase === 'rotating' ? (
+ <p role="status">
+ Assignment saved. Waiting for {serverName} to become ready… {phaseMessage}
+ </p>
+ ) : null}
+ {phase === 'failed' || phase === 'timeout' ? (
+ <p role="alert">
+ Assignment saved, but readiness could not be verified. Refresh to check status.{' '}
+ {phaseMessage}
+ </p>
+ ) : null}
+ <div className="cu-create-actions">
+ {saved || refreshRequired ? (
+ <Button onClick={onFinished}>
+ {phase === 'rotating' ? 'Check credentials later' : 'Refresh credentials'}
+ </Button>
+ ) : (
+ <>
+ <Button variant="ghost" disabled={submitting} onClick={onCancel}>
+ Cancel assignment change
+ </Button>
+ <Button
+ type="submit"
+ variant="primary"
+ loading={submitting}
+ disabled={Boolean(blockedReason) || !changed || submitting}
+ >
+ Assign and restart
+ </Button>
+ </>
+ )}
+ </div>
+ </form>
+ </FormSection>
+ )
+}
diff --git a/control-ui/components/ChangeConnectorSecret/types.ts b/control-ui/components/ChangeConnectorSecret/types.ts
new file mode 100644
index 000000000..6953227cc
--- /dev/null
+++ b/control-ui/components/ChangeConnectorSecret/types.ts
@@ -0,0 +1,10 @@
+import type { AttachConnectorCredentialsProps } from '@components/AttachConnectorCredentials/types'
+import type { EnvSecret } from '@lib/api'
+
+export type ChangeConnectorSecretProps = Omit<
+ AttachConnectorCredentialsProps,
+ 'registryCredentialSource'
+> & {
+ reference: EnvSecret
+ onCancel: () => void
+}
diff --git a/control-ui/components/SecretsTable.tsx b/control-ui/components/SecretsTable.tsx
index 4b0fd4180..f06395d8a 100644
--- a/control-ui/components/SecretsTable.tsx
+++ b/control-ui/components/SecretsTable.tsx
@@ -490,7 +490,11 @@ export function SecretsTable({
{activeInitialLoad ? 'Secrets' : `Secrets (${activeCount})`}
</>
}
- subtitle="Manage LLM, connector, and recipe credentials in one place."
+ subtitle={
+ activeScope === 'mcp'
+ ? 'Create reusable connector Secrets here. Assign them when creating a connector or from its Credentials tab using Change assigned Secret.'
+ : 'Manage LLM, connector, and recipe credentials in one place.'
+ }
primaryAction={
<button
type="button"
diff --git a/control-ui/components/UpdateConnectorCredentials/index.tsx b/control-ui/components/UpdateConnectorCredentials/index.tsx
index e52909d70..563752626 100644
--- a/control-ui/components/UpdateConnectorCredentials/index.tsx
+++ b/control-ui/components/UpdateConnectorCredentials/index.tsx
@@ -1,6 +1,6 @@
'use client'
-import React, { useEffect, useState } from 'react'
+import React, { useEffect, useRef, useState } from 'react'
import { DataTable, TableViewport } from '@clerum/frontend-components'
import { useConfirmDialog } from '@components/ConfirmDialog'
import { useToast } from '@components/Toast'
@@ -77,10 +77,15 @@ export function UpdateConnectorCredentials({
surface = 'rotate',
recipeOwned = false,
registryCredentialSource,
+ onBusyChange,
}: UpdateConnectorCredentialsProps) {
const { showToast } = useToast()
const { confirm, confirmDialog } = useConfirmDialog()
+ const busyCallback = useRef(onBusyChange)
+ busyCallback.current = onBusyChange
+ const [confirming, setConfirming] = useState(false)
+ const confirmLock = useRef(false)
const [draft, setDraft] = useState<CredentialMap>(emptyCredentialMap)
const [validationError, setValidationError] = useState('')
// The secretKeys the last submit rejected. Drives per-input `aria-invalid` /
@@ -166,6 +171,11 @@ export function UpdateConnectorCredentials({
}
}, [registryCredentialSource])
+ useEffect(() => {
+ busyCallback.current?.(confirming || phase === 'saving' || phase === 'rotating')
+ return () => busyCallback.current?.(false)
+ }, [confirming, phase])
+
// "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
@@ -225,7 +235,7 @@ export function UpdateConnectorCredentials({
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault()
- if (phase === 'saving' || phase === 'rotating') return
+ if (confirmLock.current || phase === 'saving' || phase === 'rotating') return
const data = emptyCredentialMap()
for (const key of envSecret!.keys) {
@@ -252,6 +262,8 @@ export function UpdateConnectorCredentials({
setValidationError('')
setInvalidKeys([])
+ confirmLock.current = true
+ setConfirming(true)
const confirmed = await confirm(
mode === 'set'
? {
@@ -266,6 +278,8 @@ export function UpdateConnectorCredentials({
tone: 'danger',
}
)
+ confirmLock.current = false
+ setConfirming(false)
if (!confirmed) return
// Captured BEFORE the PUT fires — the correlation anchor the poll below
@@ -335,7 +349,7 @@ export function UpdateConnectorCredentials({
setRotationAffected([])
}
- const busy = phase === 'saving' || phase === 'rotating'
+ const busy = confirming || phase === 'saving' || phase === 'rotating'
// The poll above verifies ONLY this connector's own DeploymentReady, via
// getMcpServer(serverName). A shared Secret can be referenced by other
// connectors too (result.affectedConnectors); the HCC restarts them as well,
diff --git a/control-ui/components/UpdateConnectorCredentials/types.ts b/control-ui/components/UpdateConnectorCredentials/types.ts
index e118cd316..002fa2eb9 100644
--- a/control-ui/components/UpdateConnectorCredentials/types.ts
+++ b/control-ui/components/UpdateConnectorCredentials/types.ts
@@ -45,6 +45,7 @@ export type UpdateConnectorCredentialsProps = {
recipeOwned?: boolean
/** Marketplace source used to resolve operator-friendly credential labels. */
registryCredentialSource?: RegistryCredentialSource
+ onBusyChange?: (busy: boolean) => void
}
/**
diff --git a/control-ui/components/__tests__/ChangeConnectorSecret.test.tsx b/control-ui/components/__tests__/ChangeConnectorSecret.test.tsx
new file mode 100644
index 000000000..2ab2c85d1
--- /dev/null
+++ b/control-ui/components/__tests__/ChangeConnectorSecret.test.tsx
@@ -0,0 +1,349 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
+import { ChangeConnectorSecret } from '@components/ChangeConnectorSecret'
+import { ToastProvider } from '@components/Toast'
+import { POLL_INTERVAL_MS, POLL_TIMEOUT_MS } from '@components/UpdateConnectorCredentials'
+import {
+ createMcpSecret,
+ deleteMcpSecret,
+ getMcpServer,
+ listMcpSecrets,
+ updateMcpSecret,
+ updateMcpServer,
+} from '@lib/api'
+import type { EnvSecret, McpServerResource } from '@lib/api'
+
+vi.mock('@lib/api', () => ({
+ createMcpSecret: vi.fn(),
+ deleteMcpSecret: vi.fn(),
+ getMcpServer: vi.fn(),
+ listMcpSecrets: vi.fn(),
+ updateMcpSecret: vi.fn(),
+ updateMcpServer: vi.fn(),
+}))
+
+const mockGetMcpServer = vi.mocked(getMcpServer)
+const mockListMcpSecrets = vi.mocked(listMcpSecrets)
+const mockUpdateMcpServer = vi.mocked(updateMcpServer)
+
+const SERVER_NAME = 'linear-connector'
+const OLD_REFERENCE: EnvSecret = {
+ name: 'old-secret',
+ keys: [{ secretKey: 'api-key', envVar: 'LINEAR_API_KEY' }],
+}
+const OLD_SECRET = { name: 'old-secret', uid: 'old-uid', keys: ['api-key'] }
+const NEW_SECRET = { name: 'shared-credentials', uid: 'shared-uid', keys: ['api-key'] }
+
+function assignedServer(
+ overrides: {
+ spec?: Record<string, unknown>
+ generation?: number
+ resourceVersion?: string
+ status?: McpServerResource['status']
+ } = {}
+): McpServerResource {
+ return {
+ metadata: {
+ name: SERVER_NAME,
+ uid: 'server-uid',
+ resourceVersion: overrides.resourceVersion ?? '10',
+ generation: overrides.generation ?? 2,
+ },
+ spec: {
+ image: 'example/linear:v1',
+ contextRef: 'private-context',
+ managed: true,
+ enabled: true,
+ envSecret: OLD_REFERENCE,
+ ...(overrides.spec ?? {}),
+ },
+ ...(overrides.status ? { status: overrides.status } : {}),
+ }
+}
+
+/** A DeploymentReady condition shaped like the reconciler writes it. */
+function deploymentReady(
+ status: 'True' | 'False',
+ at: string,
+ generation = 3
+): McpServerResource['status'] {
+ return {
+ conditions: [
+ {
+ type: 'DeploymentReady',
+ status,
+ reason: status === 'True' ? 'RolloutComplete' : 'WaitingForReplicas',
+ message: status === 'True' ? 'ready' : 'rolling out',
+ lastTransitionTime: at,
+ observedGeneration: generation,
+ },
+ ],
+ }
+}
+
+/** Drains chained microtasks without relying on real timers — safe under
+ * `vi.useFakeTimers()`, unlike `waitFor`/`findBy*`. */
+async function flush(ticks = 4) {
+ for (let i = 0; i < ticks; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ await act(async () => {
+ await Promise.resolve()
+ })
+ }
+}
+
+async function renderPanel(
+ options: {
+ server?: McpServerResource
+ reference?: EnvSecret
+ blockedReason?: string
+ list?: Promise<{ items: Array<{ name: string; uid: string; keys: string[] }> }>
+ } = {}
+) {
+ const { server = assignedServer(), reference = OLD_REFERENCE, blockedReason, list } = options
+ mockListMcpSecrets.mockReturnValue(list ?? Promise.resolve({ items: [OLD_SECRET, NEW_SECRET] }))
+ mockGetMcpServer.mockResolvedValue(server)
+ const onFinished = vi.fn()
+ const onCancel = vi.fn()
+ const onBusyChange = vi.fn()
+ const onSpecSaved = vi.fn()
+ render(
+ <ToastProvider>
+ <ChangeConnectorSecret
+ serverName={SERVER_NAME}
+ server={server}
+ reference={reference}
+ onFinished={onFinished}
+ onCancel={onCancel}
+ onBusyChange={onBusyChange}
+ onSpecSaved={onSpecSaved}
+ blockedReason={blockedReason}
+ />
+ </ToastProvider>
+ )
+ await flush(2)
+ return { onFinished, onCancel, onBusyChange, onSpecSaved }
+}
+
+/** Chooses the replacement Secret and drains the state updates that follow. */
+async function chooseReplacement(secretName = NEW_SECRET.name) {
+ fireEvent.change(screen.getByLabelText(/^Existing Secret/), {
+ target: { value: secretName },
+ })
+ await flush(2)
+}
+
+/** The resource `updateMcpServer` answers with after an accepted assignment:
+ * the new reference (destinations preserved), a bumped generation, and a
+ * fresh Ready condition. */
+function savedServer(status?: McpServerResource['status']): McpServerResource {
+ return assignedServer({
+ generation: 3,
+ resourceVersion: '11',
+ spec: {
+ envSecret: {
+ name: NEW_SECRET.name,
+ keys: [{ secretKey: 'api-key', envVar: 'LINEAR_API_KEY' }],
+ },
+ },
+ status: status ?? deploymentReady('True', '2026-01-01T00:00:05.000Z'),
+ })
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'))
+ mockUpdateMcpServer.mockResolvedValue(savedServer())
+})
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+ vi.useRealTimers()
+})
+
+describe('ChangeConnectorSecret — reference-only selection', () => {
+ it('shows the current assignment and never renders a credential value input', async () => {
+ await renderPanel()
+ expect(screen.getByText(/Currently assigned:/)).toHaveTextContent('old-secret')
+ await chooseReplacement()
+ expect(screen.getByRole('button', { name: 'Assign and restart' })).toBeEnabled()
+ expect(document.querySelectorAll('input[type="password"]')).toHaveLength(0)
+ expect(screen.queryByText(/Credential value/i)).not.toBeInTheDocument()
+ })
+
+ it('disables assignment until the metadata list is ready', async () => {
+ await renderPanel({ list: new Promise(() => undefined) })
+ expect(screen.getByRole('status')).toHaveTextContent('Loading Secrets…')
+ expect(screen.getByLabelText(/^Existing Secret/)).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'Assign and restart' })).toBeDisabled()
+ })
+
+ it('offers retry when metadata cannot load and reports the failure inline', async () => {
+ await renderPanel({ list: Promise.reject(new Error('boom')) })
+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load Secrets')
+ expect(screen.getByRole('button', { name: 'Assign and restart' })).toBeDisabled()
+ })
+
+ it('treats an unchanged assignment as a no-op', async () => {
+ await renderPanel()
+ await chooseReplacement(OLD_SECRET.name)
+ expect(screen.getByRole('button', { name: 'Assign and restart' })).toBeDisabled()
+ })
+
+ it('demands an explicit replacement key when the new Secret lacks one, never a value', async () => {
+ const partialReference: EnvSecret = {
+ name: 'old-secret',
+ keys: [
+ { secretKey: 'api-key', envVar: 'LINEAR_API_KEY' },
+ { secretKey: 'workspace-id', envVar: 'LINEAR_WORKSPACE' },
+ ],
+ }
+ await renderPanel({ reference: partialReference })
+ await chooseReplacement()
+
+ // The dropped destination survives as an explicit choice; the error points
+ // at the key selection, not at a credential value.
+ expect(screen.getByLabelText(/^Environment variable 2/)).toHaveValue('LINEAR_WORKSPACE')
+ expect(screen.getByLabelText(/^Secret key 2/)).toHaveValue('')
+ expect(screen.getByRole('alert').textContent).toContain('Choose a stored key')
+ expect(screen.getByRole('alert').textContent?.toLowerCase()).not.toContain(
+ 'enter a credential value'
+ )
+ expect(screen.getByRole('button', { name: 'Assign and restart' })).toBeDisabled()
+ })
+
+ it('surfaces the blocked reason and keeps assignment disabled', async () => {
+ await renderPanel({ blockedReason: 'Wait for the egress save to finish.' })
+ await chooseReplacement()
+ expect(screen.getByRole('status')).toHaveTextContent('Wait for the egress save to finish.')
+ expect(screen.getByRole('button', { name: 'Assign and restart' })).toBeDisabled()
+ })
+
+ it('reports busy once assignment starts and clears it on cancel', async () => {
+ const { onCancel, onBusyChange } = await renderPanel()
+ await chooseReplacement()
+ expect(onBusyChange).toHaveBeenCalledWith(false)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel assignment change' }))
+ await flush(2)
+ expect(onCancel).toHaveBeenCalledOnce()
+ })
+})
+
+describe('ChangeConnectorSecret — assignment save', () => {
+ async function submitThroughConfirm() {
+ fireEvent.click(screen.getByRole('button', { name: 'Assign and restart' }))
+ await flush(2)
+ const dialog = screen.getByRole('alertdialog')
+ expect(dialog.textContent).toContain('old-secret')
+ expect(dialog.textContent).toContain(NEW_SECRET.name)
+ expect(dialog.textContent).toContain('Other connectors keep their current assignments')
+ // The duplicate-submit guard: the form's own button is disabled while the
+ // confirmation is pending, so a second click is inert and no second dialog
+ // can stack.
+ const assignButtons = screen.getAllByRole('button', { name: 'Assign and restart' })
+ expect(assignButtons).toHaveLength(2)
+ const formButton = assignButtons.find(button => button.getAttribute('type') === 'submit')
+ expect(formButton).toBeDisabled()
+ fireEvent.click(formButton!)
+ expect(screen.getAllByRole('alertdialog')).toHaveLength(1)
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Assign and restart' }))
+ // Drain the full verify → save → confirm-read microtask chain.
+ await flush(8)
+ return dialog
+ }
+
+ it('confirms with both Secret names, writes only envSecret, and never touches shared Secret values', async () => {
+ const { onFinished } = await renderPanel()
+ await chooseReplacement()
+ await submitThroughConfirm()
+
+ expect(mockUpdateMcpServer).toHaveBeenCalledOnce()
+ expect(mockUpdateMcpServer).toHaveBeenCalledWith(SERVER_NAME, {
+ metadata: { uid: 'server-uid', resourceVersion: '10' },
+ spec: {
+ ...assignedServer().spec,
+ envSecret: {
+ name: NEW_SECRET.name,
+ // The connector's original destination survives the reassignment.
+ keys: [{ secretKey: 'api-key', envVar: 'LINEAR_API_KEY' }],
+ },
+ },
+ })
+ expect(createMcpSecret).not.toHaveBeenCalled()
+ expect(updateMcpSecret).not.toHaveBeenCalled()
+ expect(deleteMcpSecret).not.toHaveBeenCalled()
+ expect(screen.getByRole('status').textContent).toContain('Assignment saved')
+
+ // Correlated readiness: a fresh True after the save resolves the wait.
+ mockGetMcpServer.mockResolvedValue(
+ savedServer(deploymentReady('True', '2026-01-01T00:00:05.000Z'))
+ )
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS)
+ })
+ expect(onFinished).toHaveBeenCalledOnce()
+ expect(screen.getByText(/Assigned Secret changed/)).toBeInTheDocument()
+ })
+
+ it('rejects a concurrent spec change before writing and locks until refresh', async () => {
+ const { onFinished } = await renderPanel()
+ // Both the pre-write snapshot read and the pre-write re-read see a
+ // connector that no longer matches the displayed snapshot.
+ mockGetMcpServer.mockResolvedValue(assignedServer({ spec: { image: 'example/linear:v2' } }))
+ await chooseReplacement()
+ await submitThroughConfirm()
+
+ expect(screen.getByRole('alert').textContent).toContain('connector changed')
+ expect(mockUpdateMcpServer).not.toHaveBeenCalled()
+ expect(screen.getByRole('button', { name: 'Refresh credentials' })).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Assign and restart' })).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh credentials' }))
+ expect(onFinished).toHaveBeenCalledOnce()
+ })
+
+ it('reports a rejected save without cleanup of either shared Secret', async () => {
+ mockUpdateMcpServer.mockRejectedValue(Object.assign(new Error('409 conflict'), { status: 409 }))
+ const { onFinished } = await renderPanel()
+ await chooseReplacement()
+ await submitThroughConfirm()
+
+ expect(screen.getByRole('alert').textContent).toContain('rejected')
+ expect(deleteMcpSecret).not.toHaveBeenCalled()
+ expect(updateMcpSecret).not.toHaveBeenCalled()
+ expect(onFinished).not.toHaveBeenCalled()
+ })
+
+ it('reports an uncertain outcome when the confirmation read cannot verify the save', async () => {
+ mockUpdateMcpServer.mockRejectedValue(Object.assign(new Error('503'), { status: 503 }))
+ await renderPanel()
+ await chooseReplacement()
+ await submitThroughConfirm()
+
+ expect(screen.getByRole('alert').textContent).toContain('could not be confirmed')
+ expect(deleteMcpSecret).not.toHaveBeenCalled()
+ })
+
+ it('reports the bounded readiness timeout and recovers through the refresh action', async () => {
+ mockUpdateMcpServer.mockResolvedValue(savedServer())
+ // Never fresh or never True: the poll cannot conclude within its budget.
+ mockGetMcpServer.mockResolvedValue(
+ savedServer(deploymentReady('False', '2025-12-31T23:59:00.000Z'))
+ )
+ const { onFinished } = await renderPanel()
+ await chooseReplacement()
+ await submitThroughConfirm()
+ expect(screen.getByRole('status').textContent).toContain('Assignment saved')
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(POLL_TIMEOUT_MS + POLL_INTERVAL_MS)
+ })
+ const timeoutAlert = screen.getByRole('alert')
+ expect(timeoutAlert.textContent).toContain('readiness could not be verified')
+ expect(onFinished).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh credentials' }))
+ expect(onFinished).toHaveBeenCalledOnce()
+ })
+})
diff --git a/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx b/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx
index 63904b80c..1804dc08c 100644
--- a/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx
+++ b/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx
@@ -8,7 +8,9 @@ import {
getContexts,
getMcpServer,
getMcpServers,
+ listMcpSecrets,
updateMcpSecret,
+ updateMcpServer,
} from '../../lib/api'
import type { McpServerCondition, McpServerResource } from '../../lib/api'
import {
@@ -63,6 +65,7 @@ vi.mock('../../lib/api', async () => {
getContexts: vi.fn(),
getMcpServer: vi.fn(),
getMcpServers: vi.fn(),
+ listMcpSecrets: vi.fn(),
updateMcpServer: vi.fn(),
updateMcpSecret: vi.fn(),
createMcpSecret: vi.fn(),
@@ -72,6 +75,8 @@ vi.mock('../../lib/api', async () => {
const mockGetMcpServer = vi.mocked(getMcpServer)
const mockGetMcpServers = vi.mocked(getMcpServers)
const mockGetContexts = vi.mocked(getContexts)
+const mockListMcpSecrets = vi.mocked(listMcpSecrets)
+const mockUpdateMcpServer = vi.mocked(updateMcpServer)
const mockUpdateMcpSecret = vi.mocked(updateMcpSecret)
const mockCreateMcpSecret = vi.mocked(createMcpSecret)
@@ -494,3 +499,144 @@ describe('EditMcpServerPage — credential surface wiring', () => {
expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()
})
})
+
+// ─── Change assigned Secret — page wiring ───────────────────────────────────
+//
+// The component suites cover the form in isolation; these tests pin the wiring
+// the page owns: eligibility gating, the busy navigation interlock, the
+// spec-only write, and keyboard focus surviving the panel swap.
+describe('EditMcpServerPage — Change assigned Secret', () => {
+ const OTHER_SECRET = {
+ name: 'other-credentials',
+ uid: 'other-uid',
+ keys: ['api-key', 'workspace-id'],
+ }
+
+ function eligibleServer(): McpServerResource {
+ return {
+ metadata: {
+ name: SERVER_NAME,
+ namespace: NAMESPACE,
+ uid: 'server-uid',
+ resourceVersion: '10',
+ generation: 2,
+ },
+ spec: {
+ image: CONNECTOR_IMAGE,
+ contextRef: 'default',
+ managed: true,
+ envSecret: {
+ name: SECRET_NAME,
+ keys: [
+ { secretKey: 'api-key', envVar: 'LINEAR_API_KEY' },
+ { secretKey: 'workspace-id', envVar: 'LINEAR_WORKSPACE' },
+ ],
+ },
+ },
+ status: { conditions: [] },
+ }
+ }
+
+ function reassignedServer(): McpServerResource {
+ return {
+ ...eligibleServer(),
+ metadata: { ...eligibleServer().metadata, resourceVersion: '11', generation: 3 },
+ spec: {
+ ...eligibleServer().spec,
+ envSecret: {
+ name: OTHER_SECRET.name,
+ keys: [
+ { secretKey: 'api-key', envVar: 'LINEAR_API_KEY' },
+ { secretKey: 'workspace-id', envVar: 'LINEAR_WORKSPACE' },
+ ],
+ },
+ },
+ }
+ }
+
+ beforeEach(() => {
+ mockListMcpSecrets.mockResolvedValue({
+ items: [
+ { name: SECRET_NAME, uid: 'secret-uid', keys: ['api-key', 'workspace-id'] },
+ OTHER_SECRET,
+ ],
+ })
+ mockUpdateMcpServer.mockResolvedValue(reassignedServer())
+ })
+
+ it('offers reassignment beside rotation for an eligible managed connector', async () => {
+ await renderPage(eligibleServer())
+ expect(screen.getByRole('button', { name: 'Change assigned Secret' })).toBeInTheDocument()
+ // Value rotation keeps its separate surface on the same tab.
+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()
+ })
+
+ it('hides reassignment when the WorkflowRecipe owns the credentials', async () => {
+ await renderPage(mcpServer({ managed: false, status: { conditions: [] } }))
+ expect(screen.queryByRole('button', { name: 'Change assigned Secret' })).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()
+ })
+
+ it('returns focus to the trigger after the change flow is cancelled', async () => {
+ await renderPage(eligibleServer())
+ fireEvent.click(screen.getByRole('button', { name: 'Change assigned Secret' }))
+ await screen.findByLabelText(/^Existing Secret/)
+ fireEvent.change(screen.getByLabelText(/^Existing Secret/), {
+ target: { value: OTHER_SECRET.name },
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel assignment change' }))
+ const trigger = await screen.findByRole('button', { name: 'Change assigned Secret' })
+ expect(trigger).toHaveFocus()
+ // Cancelling never wrote anything.
+ expect(mockUpdateMcpServer).not.toHaveBeenCalled()
+ })
+
+ it('locks navigation during the assignment, writes only envSecret, and reloads', async () => {
+ await renderPage(eligibleServer())
+ fireEvent.click(screen.getByRole('button', { name: 'Change assigned Secret' }))
+ fireEvent.change(await screen.findByLabelText(/^Existing Secret/), {
+ target: { value: OTHER_SECRET.name },
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'Assign and restart' }))
+ const dialog = await screen.findByRole('alertdialog')
+ // The busy interlock: every tab is locked while the mutation is pending.
+ for (const tab of screen.getAllByRole('tab')) {
+ expect(tab).toBeDisabled()
+ }
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Assign and restart' }))
+
+ await waitFor(() => expect(mockUpdateMcpServer).toHaveBeenCalledOnce())
+ expect(mockUpdateMcpServer).toHaveBeenCalledWith(SERVER_NAME, {
+ metadata: { uid: 'server-uid', resourceVersion: '10' },
+ spec: {
+ ...eligibleServer().spec,
+ envSecret: {
+ name: OTHER_SECRET.name,
+ keys: [
+ { secretKey: 'api-key', envVar: 'LINEAR_API_KEY' },
+ { secretKey: 'workspace-id', envVar: 'LINEAR_WORKSPACE' },
+ ],
+ },
+ },
+ })
+ // Reference-only: shared Secret values are never written by this flow.
+ expect(mockUpdateMcpSecret).not.toHaveBeenCalled()
+ expect(mockCreateMcpSecret).not.toHaveBeenCalled()
+ expect(await screen.findByText(/Assignment saved/)).toBeInTheDocument()
+ // Saved is not ready: the operator can leave while the rollout is observed.
+ for (const tab of screen.getAllByRole('tab')) {
+ expect(tab).toBeDisabled()
+ }
+
+ // Leaving releases the panel and reloads the connector's new reference.
+ mockGetMcpServer.mockResolvedValue(reassignedServer())
+ fireEvent.click(screen.getByRole('button', { name: 'Check credentials later' }))
+ const currentAssignment = await screen.findByText(/Current Secret:/)
+ expect(currentAssignment.textContent).toContain(OTHER_SECRET.name)
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'Change assigned Secret' })).toHaveFocus()
+ )
+ })
+})
diff --git a/control-ui/components/__tests__/SecretsTable.test.tsx b/control-ui/components/__tests__/SecretsTable.test.tsx
index 90c85b1da..8cbf91725 100644
--- a/control-ui/components/__tests__/SecretsTable.test.tsx
+++ b/control-ui/components/__tests__/SecretsTable.test.tsx
@@ -747,3 +747,34 @@ describe('SecretsTable — LLM empty state', () => {
expect(screen.queryByRole('tab', { name: 'API-KEY' })).not.toBeInTheDocument()
})
})
+
+// ─── Connector Secret management guidance ───────────────────────────────────
+//
+// Reusable connector Secrets are assigned from a connector's Credentials tab
+// (Change assigned Secret) or during connector creation. The Connectors scope
+// header is where operators look first, so it carries that pointer instead of
+// the generic one-liner.
+describe('SecretsTable — connector Secret management guidance', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('points at assignment from creation and the Credentials tab in the Connectors scope', () => {
+ renderTable('mcp')
+
+ expect(
+ screen.getByText(
+ /Create reusable connector Secrets here\. Assign them when creating a connector or from its Credentials tab using Change assigned Secret\./
+ )
+ ).toBeInTheDocument()
+ })
+
+ it('keeps the generic subtitle outside the Connectors scope', () => {
+ renderTable('recipe')
+
+ expect(
+ screen.getByText('Manage LLM, connector, and recipe credentials in one place.')
+ ).toBeInTheDocument()
+ expect(screen.queryByText(/Change assigned Secret/)).not.toBeInTheDocument()
+ })
+})
diff --git a/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx b/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx
index 810cdc945..65070c3ac 100644
--- a/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx
+++ b/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx
@@ -1454,3 +1454,48 @@ describe('UpdateConnectorCredentials — set mode submit', () => {
expect(banner.textContent).not.toMatch(/rotation/i)
})
})
+
+// ─── Busy interlock during the confirmation ─────────────────────────────────
+//
+// The page drives its navigation lock from `onBusyChange`, and a pending
+// confirmation is a mutation-in-waiting: the submit must be guarded against
+// double activation and the page must be able to block tab/back navigation
+// from the moment the dialog opens, not only from the PUT.
+describe('UpdateConnectorCredentials — busy interlock', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('reports busy while the rotation confirmation is pending and clears it on cancel', async () => {
+ const onBusyChange = vi.fn()
+ render(
+ <ToastProvider>
+ <UpdateConnectorCredentials
+ serverName={SERVER_NAME}
+ envSecret={ENV_SECRET}
+ surface="rotate"
+ onBusyChange={onBusyChange}
+ />
+ </ToastProvider>
+ )
+ await flush(2)
+ expect(onBusyChange).toHaveBeenLastCalledWith(false)
+
+ fireEvent.change(screen.getByLabelText('api-key'), { target: { value: 'next-value' } })
+ fireEvent.click(screen.getByRole('button', { name: 'Rotate credentials' }))
+ await flush(2)
+
+ // Dialog open: busy is reported, the submit is disabled, and a second
+ // activation is inert.
+ expect(onBusyChange).toHaveBeenLastCalledWith(true)
+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeDisabled()
+ fireEvent.click(screen.getByRole('button', { name: 'Rotate credentials' }))
+ expect(mockUpdateMcpSecret).not.toHaveBeenCalled()
+
+ fireEvent.click(within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Cancel' }))
+ await flush(2)
+ expect(onBusyChange).toHaveBeenLastCalledWith(false)
+ expect(mockUpdateMcpSecret).not.toHaveBeenCalled()
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+ })
+})
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index c129ea928..6f440d7b7 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.752",
+ "version": "0.1.753",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.752",
+ "version": "0.1.753",
"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.json
index 8058daf60..06c900a86 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.752",
+ "version": "0.1.753",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",