Skip to content

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

TypeScript

fix(control-ui): fence session and catalog binding changes

Alfredo Lopez6040b390539e
diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsx
index 11458b412..1639f6246 100644
--- a/control-ui/app/hosts/[name]/page.tsx
+++ b/control-ui/app/hosts/[name]/page.tsx
@@ -244,9 +244,24 @@ export default function HostDetailsPage() {
} = useLlmAllowedModels()
const [modelNameDraft, setModelNameDraft] = useState('')
const [connectionRefDraft, setConnectionRefDraft] = useState(CODEX_UNASSIGNED_CONNECTION_KEY)
- const [codexModels, setCodexModels] = useState<string[]>([])
+ const [grantCatalog, setGrantCatalog] = useState<{
+ provider: LlmProvider
+ connectionRef: string
+ models: string[]
+ } | null>(null)
+ // A retained catalog is display data for its exact broker/connection only;
+ // changing the draft binding cannot make the old models valid for a new grant.
+ const [codexModels, grokModels] = useMemo(() => {
+ const models =
+ grantCatalog?.provider === providerDraft && grantCatalog.connectionRef === connectionRefDraft
+ ? grantCatalog.models
+ : []
+ return [
+ providerDraft === 'codex-subscription' ? models : [],
+ providerDraft === GROK_SUBSCRIPTION_PROVIDER ? models : [],
+ ] as const
+ }, [connectionRefDraft, grantCatalog, providerDraft])
const [codexConnections, setCodexConnections] = useState<CodexSubscriptionConnectionView[]>([])
- const [grokModels, setGrokModels] = useState<string[]>([])
const [grokConnections, setGrokConnections] = useState<GrokSubscriptionConnectionView[]>([])
const [codexInventoryLoaded, setCodexInventoryLoaded] = useState(false)
const [grokInventoryLoaded, setGrokInventoryLoaded] = useState(false)
@@ -468,22 +483,24 @@ export default function HostDetailsPage() {
useEffect(() => {
if (!editingModel) return
if (!connectionRefDraft.trim() || connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY) {
- setCodexModels([])
- setGrokModels([])
+ setGrantCatalog(null)
setGrantCatalogError('')
return
}
const controller = new AbortController()
setGrantCatalogError('')
if (providerDraft === GROK_SUBSCRIPTION_PROVIDER) {
- setCodexModels([])
void listGrokConnectionModels(connectionRefDraft, {
signal: controller.signal,
refresh: inventoryRetryNonce > 0,
})
.then(models => {
if (controller.signal.aborted) return
- setGrokModels(offeredCodexModelNames(models))
+ setGrantCatalog({
+ provider: providerDraft,
+ connectionRef: connectionRefDraft,
+ models: offeredCodexModelNames(models),
+ })
})
.catch(err => {
if (controller.signal.aborted) return
@@ -495,14 +512,17 @@ export default function HostDetailsPage() {
controller.abort()
}
}
- setGrokModels([])
void listCodexConnectionModels(connectionRefDraft, {
signal: controller.signal,
refresh: inventoryRetryNonce > 0,
})
.then(models => {
if (controller.signal.aborted) return
- setCodexModels(offeredCodexModelNames(models))
+ setGrantCatalog({
+ provider: providerDraft,
+ connectionRef: connectionRefDraft,
+ models: offeredCodexModelNames(models),
+ })
})
.catch(err => {
if (controller.signal.aborted) return
@@ -971,7 +991,7 @@ export default function HostDetailsPage() {
if (parsed.kind === 'empty') {
setSecretRefDraft('')
setConnectionRefDraft(CODEX_UNASSIGNED_CONNECTION_KEY)
- setCodexModels([])
+ setGrantCatalog(null)
setGrantCatalogError('')
return
}
@@ -986,8 +1006,7 @@ export default function HostDetailsPage() {
}
setSecretRefDraft(parsed.name)
setConnectionRefDraft(CODEX_UNASSIGNED_CONNECTION_KEY)
- setCodexModels([])
- setGrokModels([])
+ setGrantCatalog(null)
setGrantCatalogError('')
if (isOauthBrokerProvider(providerDraft)) {
setProviderDraft('openai')
@@ -1531,8 +1550,7 @@ export default function HostDetailsPage() {
// another broker's connection key.
if (next.provider !== providerDraft) {
setConnectionRefDraft(CODEX_UNASSIGNED_CONNECTION_KEY)
- setCodexModels([])
- setGrokModels([])
+ setGrantCatalog(null)
setGrantCatalogError('')
}
}}
diff --git a/control-ui/components/AuthContext.tsx b/control-ui/components/AuthContext.tsx
index d03fc3817..3ec634d95 100644
--- a/control-ui/components/AuthContext.tsx
+++ b/control-ui/components/AuthContext.tsx
@@ -55,11 +55,13 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
email: '',
})
const sessionExpiredToastShownRef = useRef(false)
+ const authOperationRef = useRef(0)
// The router and ToastProvider callbacks are stable in normal runtime; keep
// this singleton registration tied to them if either provider is remounted.
useEffect(() => {
const handleAuthError = () => {
+ authOperationRef.current += 1
if (sessionExpiredToastShownRef.current) return
sessionExpiredToastShownRef.current = true
resetPublishScopeCache()
@@ -72,24 +74,31 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
}, [router, showToast])
const checkAuth = useCallback(async () => {
+ const operation = ++authOperationRef.current
try {
const response = await getControlUIAuthMe()
- if (!response.me.id) {
+ if (operation !== authOperationRef.current) return
+ const { id, username, email, role } = response.me
+ if (!id) {
clearAdminAuthToken()
setAuthState({ id: '', isLoggedIn: false, isLoading: false, username: '', email: '' })
return
}
- setControlUIReadPrincipal(response.me.id, response.me.role || 'admin')
+ setControlUIReadPrincipal(id, role || 'admin')
sessionExpiredToastShownRef.current = false
- setAuthState(prev => ({
- ...prev,
- id: response.me.id || prev.id,
- isLoggedIn: true,
- isLoading: false,
- username: response.me.username || prev.username,
- email: response.me.email || prev.email,
- }))
+ setAuthState(prev => {
+ if (operation !== authOperationRef.current) return prev
+ const sameIdentity = prev.id === id
+ return {
+ id,
+ isLoggedIn: true,
+ isLoading: false,
+ username: username ?? (sameIdentity ? prev.username : ''),
+ email: email === undefined ? (sameIdentity ? prev.email : '') : (email ?? ''),
+ }
+ })
} catch (error) {
+ if (operation !== authOperationRef.current) return
// Session-expiry errors are handled by the global toast/redirect path.
if (isSilentApiError(error)) {
setAuthState({ id: '', isLoggedIn: false, isLoading: false, username: '', email: '' })
@@ -104,13 +113,17 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
void checkAuth()
const onRemoteInvalidation = () => void checkAuth()
window.addEventListener(CONTROL_UI_SESSION_INVALIDATION_EVENT, onRemoteInvalidation)
- return () =>
+ return () => {
+ authOperationRef.current += 1
window.removeEventListener(CONTROL_UI_SESSION_INVALIDATION_EVENT, onRemoteInvalidation)
+ }
}, [checkAuth])
const login = useCallback(
async (username: string, password: string): Promise<AdminLoginResponse> => {
+ const operation = ++authOperationRef.current
const result = await loginControlUI(username, password)
+ if (operation !== authOperationRef.current) return result
setControlUIReadPrincipal(result.me.id, 'admin')
resetPublishScopeCache()
invalidateRegistryCapabilityCache()
@@ -128,9 +141,11 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
)
const logout = useCallback(async () => {
+ const operation = ++authOperationRef.current
try {
await logoutControlUI()
} finally {
+ if (operation !== authOperationRef.current) return
resetPublishScopeCache(authState.id)
sessionExpiredToastShownRef.current = false
// Drop the module-level registry-capability cache so a same-tab
diff --git a/control-ui/components/__tests__/AuthContext.test.tsx b/control-ui/components/__tests__/AuthContext.test.tsx
index 0bda4731b..a5e104cba 100644
--- a/control-ui/components/__tests__/AuthContext.test.tsx
+++ b/control-ui/components/__tests__/AuthContext.test.tsx
@@ -74,6 +74,25 @@ function AuthUserProbe() {
return <div data-testid="auth-user">{authState.username || 'signed-out'}</div>
}
+function AuthIdentityProbe() {
+ const { authState } = useAuth()
+ return (
+ <>
+ <div data-testid="auth-id">{authState.id}</div>
+ <div data-testid="auth-username">{authState.username}</div>
+ <div data-testid="auth-email">{authState.email}</div>
+ <div data-testid="auth-logged-in">{String(authState.isLoggedIn)}</div>
+ </>
+ )
+}
+
+function meResponse(me: Record<string, unknown>): Response {
+ return new Response(JSON.stringify({ me }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+}
+
function AuthProbe() {
useAuth()
return <div>Auth mounted</div>
@@ -450,6 +469,153 @@ describe('AuthProvider session expiry handling', () => {
otherTab.close()
})
+ it.each([null, '', undefined])(
+ 'clears the previous identity fields after remote sign-in with email %s',
+ async email => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ meResponse({
+ id: 'admin-a',
+ username: 'username-a',
+ email: '[email protected]',
+ role: 'admin',
+ })
+ )
+ .mockResolvedValueOnce(meResponse({ id: 'admin-b', email, role: 'admin' }))
+ vi.stubGlobal('fetch', fetchMock)
+ render(
+ <ToastProvider>
+ <AuthProvider>
+ <AuthIdentityProbe />
+ </AuthProvider>
+ </ToastProvider>
+ )
+ await waitFor(() => expect(screen.getByTestId('auth-id')).toHaveTextContent('admin-a'))
+ expect(screen.getByTestId('auth-email')).toHaveTextContent('[email protected]')
+ const otherTab = new BroadcastChannel('control-ui-read-metadata-invalidation')
+ try {
+ await act(async () => {
+ otherTab.postMessage({ type: 'session-invalidation' })
+ await new Promise(resolve => setTimeout(resolve, 0))
+ })
+ await waitFor(() => expect(screen.getByTestId('auth-id')).toHaveTextContent('admin-b'))
+ expect(screen.getByTestId('auth-email')).toBeEmptyDOMElement()
+ expect(screen.getByTestId('auth-username')).toBeEmptyDOMElement()
+ expect(screen.queryByText('[email protected]')).toBeNull()
+ expect(getReadRequestPrincipal()?.principalId).toBe('admin-b')
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ } finally {
+ otherTab.close()
+ }
+ }
+ )
+
+ it('preserves omitted fields for the same identity and clears an explicitly null email', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ meResponse({
+ id: 'admin-a',
+ username: 'username-a',
+ email: '[email protected]',
+ role: 'admin',
+ })
+ )
+ .mockResolvedValueOnce(meResponse({ id: 'admin-a', role: 'admin' }))
+ .mockResolvedValueOnce(meResponse({ id: 'admin-a', email: null, role: 'admin' }))
+ vi.stubGlobal('fetch', fetchMock)
+ render(
+ <ToastProvider>
+ <AuthProvider>
+ <AuthIdentityProbe />
+ <CheckAuthButton />
+ </AuthProvider>
+ </ToastProvider>
+ )
+ await waitFor(() =>
+ expect(screen.getByTestId('auth-email')).toHaveTextContent('[email protected]')
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Check auth' }))
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))
+ expect(screen.getByTestId('auth-username')).toHaveTextContent('username-a')
+ expect(screen.getByTestId('auth-email')).toHaveTextContent('[email protected]')
+ fireEvent.click(screen.getByRole('button', { name: 'Check auth' }))
+ await waitFor(() => expect(screen.getByTestId('auth-email')).toBeEmptyDOMElement())
+ expect(screen.getByTestId('auth-username')).toHaveTextContent('username-a')
+ })
+
+ it.each(['response', 'body'] as const)(
+ 'does not let an obsolete %s clear a newer confirmed login, and still honors a current 401',
+ async phase => {
+ let completeOld!: () => void
+ let oldBodyStarted = false
+ const oldResponse = meResponse({
+ id: 'admin-a',
+ username: 'username-a',
+ email: '[email protected]',
+ role: 'admin',
+ })
+ const deferredResponse = new Promise<Response>(resolve => {
+ if (phase === 'response') completeOld = () => resolve(oldResponse)
+ else resolve(oldResponse)
+ })
+ if (phase === 'body') {
+ vi.spyOn(oldResponse, 'text').mockImplementation(() => {
+ oldBodyStarted = true
+ return new Promise((_resolve, reject) => {
+ completeOld = () => reject(new Error('Old body failed'))
+ })
+ })
+ }
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ meResponse({
+ id: 'admin-a',
+ username: 'username-a',
+ email: '[email protected]',
+ role: 'admin',
+ })
+ )
+ // Deliberately ignore AbortSignal at this network/body seam: the UI
+ // operation fence must hold even when a transport completion is late.
+ .mockReturnValueOnce(deferredResponse)
+ .mockResolvedValueOnce(
+ meResponse({ id: 'admin-b', username: 'username-b', email: null, role: 'admin' })
+ )
+ .mockResolvedValueOnce(new Response(JSON.stringify({ error: 'expired' }), { status: 401 }))
+ vi.stubGlobal('fetch', fetchMock)
+ render(
+ <ToastProvider>
+ <AuthProvider>
+ <AuthIdentityProbe />
+ <CheckAuthButton />
+ <LoginButton />
+ </AuthProvider>
+ </ToastProvider>
+ )
+ await waitFor(() => expect(screen.getByTestId('auth-id')).toHaveTextContent('admin-a'))
+ fireEvent.click(screen.getByRole('button', { name: 'Check auth' }))
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))
+ if (phase === 'body') await waitFor(() => expect(oldBodyStarted).toBe(true))
+ fireEvent.click(screen.getByRole('button', { name: 'Log in' }))
+ await waitFor(() => expect(screen.getByTestId('auth-id')).toHaveTextContent('admin-b'))
+ await act(async () => {
+ completeOld()
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+ expect(screen.getByTestId('auth-id')).toHaveTextContent('admin-b')
+ expect(screen.getByTestId('auth-logged-in')).toHaveTextContent('true')
+ expect(getReadRequestPrincipal()?.principalId).toBe('admin-b')
+ expect(screen.queryByText('[email protected]')).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'Check auth' }))
+ await waitFor(() => expect(screen.getByTestId('auth-logged-in')).toHaveTextContent('false'))
+ expect(getReadRequestPrincipal()).toBeNull()
+ }
+ )
+
it('redirects after logout even when token revocation fails', async () => {
window.localStorage.setItem('controlUiAdminToken', 'valid-token')
const fetchMock = vi
diff --git a/control-ui/components/__tests__/HostDetailsPage.rateLimit.test.tsx b/control-ui/components/__tests__/HostDetailsPage.rateLimit.test.tsx
index 3ee9afe6f..ba28a7266 100644
--- a/control-ui/components/__tests__/HostDetailsPage.rateLimit.test.tsx
+++ b/control-ui/components/__tests__/HostDetailsPage.rateLimit.test.tsx
@@ -11,11 +11,12 @@ const navigation = vi.hoisted(() => ({
replace: vi.fn(),
push: vi.fn(),
tab: undefined as string | undefined,
+ name: 'quota-agent',
}))
vi.mock('next/navigation', () => ({
- useParams: () => ({ name: 'quota-agent', tab: navigation.tab }),
- usePathname: () => '/agents/quota-agent',
+ useParams: () => ({ name: navigation.name, tab: navigation.tab }),
+ usePathname: () => `/agents/${navigation.name}`,
useRouter: () => navigation,
useSearchParams: () => new URLSearchParams(),
}))
@@ -141,6 +142,7 @@ describe('HostDetailsPage optional subscription throttling', () => {
beforeEach(() => {
navigation.tab = undefined
+ navigation.name = 'quota-agent'
__resetReadRequestCacheForTests()
api.setControlUIReadPrincipal('unit-test-admin', 'admin')
vi.clearAllMocks()
@@ -195,6 +197,7 @@ describe('HostDetailsPage optional subscription throttling', () => {
__resetReadRequestCacheForTests()
vi.unstubAllGlobals()
vi.restoreAllMocks()
+ vi.useRealTimers()
})
it('makes no subscription GET for ordinary sections and reuses editor metadata across reopening', async () => {
@@ -274,4 +277,149 @@ describe('HostDetailsPage optional subscription throttling', () => {
expect(screen.getByRole('region', { name: 'Identity editor' })).toHaveTextContent('quota-agent')
expect(api.apiSend).not.toHaveBeenCalled()
})
+
+ it.each(['codex-subscription', 'grok-subscription'] as const)(
+ 'does not confirm retained %s models under a different connection that throttles, then recovers only that binding',
+ async provider => {
+ vi.useFakeTimers()
+ const modelA = provider === 'codex-subscription' ? 'gpt-5.1' : 'grok-4.6'
+ const modelB = provider === 'codex-subscription' ? 'gpt-5.4' : 'grok-4.7'
+ vi.mocked(api.getHostDetailBundle).mockImplementation(
+ async name =>
+ ({
+ host: {
+ ...host,
+ metadata: { ...host.metadata, name },
+ spec: {
+ ...host.spec,
+ secretRef: undefined,
+ model: {
+ provider,
+ name: modelA,
+ connectionRef: name === 'quota-agent' ? 'connection-a' : 'connection-b',
+ },
+ },
+ },
+ contexts: [
+ buildContextResource({
+ metadata: { name: 'quota-context' },
+ spec: { contextId: 'quota-context', mcpServers: ['documents-connector'] },
+ }),
+ ],
+ secrets: [],
+ users: [],
+ teams: [],
+ agentUsers: [],
+ agentTeams: [],
+ }) as never
+ )
+ vi.mocked(api.getLlmModels).mockResolvedValue({
+ rows: [modelA, modelB].map((model, index) => ({
+ id: `binding-model-${index}`,
+ provider,
+ model,
+ enabled: true,
+ stale: false,
+ vendor: provider === 'codex-subscription' ? 'OpenAI' : 'xAI',
+ display_name: null,
+ context_window_tokens: null,
+ created_at: '',
+ updated_at: '',
+ })),
+ })
+ let bReads = 0
+ fetchMock.mockImplementation((input: RequestInfo | URL) => {
+ const url = String(input)
+ if (url.endsWith('/capabilities'))
+ return Promise.resolve(
+ json({
+ providers: {
+ 'codex-subscription': { enabled: true },
+ 'grok-subscription': { enabled: true },
+ },
+ })
+ )
+ if (url.endsWith('/connection-a/models'))
+ return Promise.resolve(json({ models: [{ model: modelA, enabled: true, stale: false }] }))
+ if (url.endsWith('/connection-b/models')) {
+ bReads += 1
+ return Promise.resolve(
+ bReads === 1
+ ? throttle()
+ : json({ models: [{ model: modelB, enabled: true, stale: false }] })
+ )
+ }
+ return Promise.resolve(
+ json({
+ connections: ['a', 'b'].map(suffix => ({
+ connectionKey: `connection-${suffix}`,
+ displayName: `Connection ${suffix}`,
+ status: 'connected',
+ credentialRevision: 1,
+ catalogRevision: 1,
+ catalogStatus: 'ready',
+ defaultModel: suffix === 'a' ? modelA : modelB,
+ })),
+ })
+ )
+ })
+ const flush = () =>
+ act(async () => {
+ await vi.advanceTimersByTimeAsync(0)
+ })
+ renderPage()
+ await flush()
+ navigate('Models & creds')
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
+ await flush()
+ let dialog = screen.getByRole('dialog', { name: 'Edit model configuration' })
+ expect(within(dialog).getByRole('button', { name: 'Save' })).toBeEnabled()
+ fireEvent.click(
+ within(dialog).getByLabelText('Current model', { selector: '#llm-primary-model' })
+ )
+ expect(screen.getByRole('option', { name: new RegExp(modelA) })).not.toHaveTextContent(
+ 'out of allowlist'
+ )
+ fireEvent.click(
+ within(dialog).getByLabelText('Current model', { selector: '#llm-primary-model' })
+ )
+
+ // Reuse the page under a new route/detail producer input. Its real HTTP
+ // catalog client must fence A's loaded result as the B binding is hydrated.
+ navigation.name = 'quota-agent-b'
+ rerenderPage()
+ await flush()
+ dialog = screen.getByRole('dialog', { name: 'Edit model configuration' })
+ expect(screen.getByRole('heading', { name: 'Agent: Operations agent' })).toBeInTheDocument()
+ expect(within(dialog).getByRole('alert')).toHaveTextContent('Try again in 12 seconds.')
+ expect(
+ within(dialog).getByLabelText('Current model', { selector: '#llm-primary-model' })
+ ).toHaveTextContent(modelA)
+ expect(within(dialog).getByRole('button', { name: 'Save' })).toBeDisabled()
+ fireEvent.click(
+ within(dialog).getByLabelText('Current model', { selector: '#llm-primary-model' })
+ )
+ expect(screen.getByRole('option', { name: new RegExp(modelA) })).toHaveTextContent(
+ 'out of allowlist'
+ )
+ expect(screen.queryByRole('option', { name: new RegExp(modelB) })).toBeNull()
+ fireEvent.click(
+ within(dialog).getByLabelText('Current model', { selector: '#llm-primary-model' })
+ )
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(12_000)
+ })
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Retry' }))
+ await flush()
+ expect(within(dialog).queryByRole('alert')).toBeNull()
+ fireEvent.click(
+ within(dialog).getByLabelText('Current model', { selector: '#llm-primary-model' })
+ )
+ expect(screen.getByRole('option', { name: new RegExp(modelB) })).not.toHaveTextContent(
+ 'out of allowlist'
+ )
+ expect(screen.queryByRole('option', { name: new RegExp(modelA) })).toBeNull()
+ expect(api.apiSend).not.toHaveBeenCalled()
+ }
+ )
})
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index ace5d18fc..49209391b 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.704",
+ "version": "0.1.705",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.704",
+ "version": "0.1.705",
"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 7b4f7e30a..9380f9917 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.704",
+ "version": "0.1.705",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",