Skip to content

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

TypeScript

feat(control-ui): manage Codex subscription connection

Alfredo Lopezaa3352cd051f
diff --git a/control-ui/app/constants/routes.ts b/control-ui/app/constants/routes.ts
index 6c0920e00..b2419a3ea 100644
--- a/control-ui/app/constants/routes.ts
+++ b/control-ui/app/constants/routes.ts
@@ -71,6 +71,7 @@ export const CONTROL_ROUTES = {
discovery: '/llm-models/discovery',
new: '/llm-models/new',
edit: (id: string) => `/llm-models/${segment(id)}/edit`,
+ codexSubscription: '/llm-models/providers/codex-subscription',
},
marketplace: {
root: '/marketplace',
diff --git a/control-ui/app/llm-models/providers/codex-subscription/page.tsx b/control-ui/app/llm-models/providers/codex-subscription/page.tsx
new file mode 100644
index 000000000..3e6ae804b
--- /dev/null
+++ b/control-ui/app/llm-models/providers/codex-subscription/page.tsx
@@ -0,0 +1,15 @@
+'use client'
+
+import { AuthGate } from '@components/AuthGate'
+import { CodexSubscriptionConnection } from '@components/CodexSubscriptionConnection'
+import { DashboardLayout } from '@components/DashboardLayout'
+
+export default function CodexSubscriptionProviderPage() {
+ return (
+ <AuthGate>
+ <DashboardLayout isDetailPage>
+ <CodexSubscriptionConnection />
+ </DashboardLayout>
+ </AuthGate>
+ )
+}
diff --git a/control-ui/components/CodexSubscriptionConnection/index.tsx b/control-ui/components/CodexSubscriptionConnection/index.tsx
new file mode 100644
index 000000000..2d3e8369f
--- /dev/null
+++ b/control-ui/components/CodexSubscriptionConnection/index.tsx
@@ -0,0 +1,394 @@
+'use client'
+
+import React, { useEffect, useMemo, useState } from 'react'
+import { useRouter } from 'next/navigation'
+import { useConfirmDialog } from '@components/ConfirmDialog'
+import { CreateFlowPanel } from '@components/CreateFlowPanel'
+import { CreatePageHeader } from '@components/CreatePageHeader'
+import { IconModels } from '@components/Sidebar/icons'
+import { useToast } from '@components/Toast'
+import { CONTROL_ROUTES } from '@constants/routes'
+import { isSilentApiError } from '@lib/api'
+import {
+ type CodexOAuthIntent,
+ type CodexSubscriptionConnectionView,
+ getCodexSubscriptionConnection,
+ pollCodexDevice,
+ refreshCodexSubscriptionConnection,
+ revokeCodexSubscription,
+ startCodexBrowserConnect,
+ startCodexDeviceConnect,
+ syncCodexSubscriptionCatalog,
+} from '@lib/codexSubscription'
+import {
+ isCodexSubscriptionUiEnabled,
+ loadCodexSubscriptionCapability,
+} from '@lib/codexSubscriptionFeature'
+import { type CodexSubscriptionUiStatus, mapConnectionStatus } from './types'
+
+function failureClass(error: unknown): string {
+ if (
+ error &&
+ typeof error === 'object' &&
+ typeof (error as { code?: unknown }).code === 'string'
+ ) {
+ return (error as { code: string }).code
+ }
+ if (error instanceof Error && error.message.trim()) return 'request_failed'
+ return 'unavailable'
+}
+
+function statusLabel(status: CodexSubscriptionUiStatus): string {
+ switch (status) {
+ case 'connected':
+ return 'Connected'
+ case 'connecting':
+ return 'Connecting'
+ case 'device-pending':
+ return 'Device code pending'
+ case 'reauth-required':
+ return 'Reauthorization required'
+ case 'revoking':
+ return 'Revoking'
+ case 'unavailable':
+ return 'Unavailable'
+ default:
+ return 'Disconnected'
+ }
+}
+
+export function CodexSubscriptionConnection() {
+ const router = useRouter()
+ const { showToast } = useToast()
+ const { confirm, confirmDialog } = useConfirmDialog()
+ const [capabilityReady, setCapabilityReady] = useState(false)
+ const [enabled, setEnabled] = useState(false)
+ const [uiStatus, setUiStatus] = useState<CodexSubscriptionUiStatus>('disconnected')
+ const [connection, setConnection] = useState<CodexSubscriptionConnectionView | null>(null)
+ const [deviceUserCode, setDeviceUserCode] = useState<string | null>(null)
+ const [deviceVerificationUri, setDeviceVerificationUri] = useState<string | null>(null)
+ const [deviceState, setDeviceState] = useState<string | null>(null)
+ const [pollMs, setPollMs] = useState(5000)
+ const [syncSummary, setSyncSummary] = useState<string | null>(null)
+ const [errorClass, setErrorClass] = useState<string | null>(null)
+ const [busy, setBusy] = useState(false)
+
+ function applyConnection(next: CodexSubscriptionConnectionView) {
+ setConnection(next)
+ setUiStatus(mapConnectionStatus(next.status))
+ setErrorClass(null)
+ }
+
+ async function loadConnection() {
+ try {
+ applyConnection(await getCodexSubscriptionConnection())
+ } catch (error) {
+ if (isSilentApiError(error)) return
+ setConnection(null)
+ setUiStatus('unavailable')
+ setErrorClass(failureClass(error))
+ }
+ }
+
+ useEffect(() => {
+ let cancelled = false
+ void loadCodexSubscriptionCapability().then(capability => {
+ if (cancelled) return
+ const on = isCodexSubscriptionUiEnabled(capability)
+ setEnabled(on)
+ setCapabilityReady(true)
+ if (on) void loadConnection()
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [])
+
+ useEffect(() => {
+ if (!deviceState || uiStatus !== 'device-pending') return undefined
+ const timer = window.setInterval(() => {
+ void pollCodexDevice(deviceState)
+ .then(result => {
+ if (result.status === 'connected') {
+ setDeviceState(null)
+ setDeviceUserCode(null)
+ setDeviceVerificationUri(null)
+ applyConnection(result.connection)
+ showToast('Codex subscription connected.', { tone: 'success' })
+ return
+ }
+ if (result.status === 'expired' || result.status === 'denied') {
+ setDeviceState(null)
+ setDeviceUserCode(null)
+ setDeviceVerificationUri(null)
+ setUiStatus('disconnected')
+ setErrorClass(result.status)
+ return
+ }
+ if (result.status === 'pending' || result.status === 'slow_down') {
+ setPollMs(result.intervalSeconds * 1000)
+ }
+ })
+ .catch(error => {
+ if (isSilentApiError(error)) return
+ setErrorClass(failureClass(error))
+ })
+ }, pollMs)
+ return () => window.clearInterval(timer)
+ }, [deviceState, pollMs, showToast, uiStatus])
+
+ const fingerprint = useMemo(
+ () => connection?.accountFingerprint ?? 'none',
+ [connection?.accountFingerprint]
+ )
+
+ async function startBrowser(intent: CodexOAuthIntent) {
+ setBusy(true)
+ setErrorClass(null)
+ setUiStatus('connecting')
+ try {
+ const started = await startCodexBrowserConnect(intent)
+ window.open(started.authorizeUrl, '_blank', 'noopener,noreferrer')
+ showToast('Complete Codex sign-in in the browser window.', { tone: 'info' })
+ await loadConnection()
+ } catch (error) {
+ if (isSilentApiError(error)) return
+ if (
+ error &&
+ typeof error === 'object' &&
+ (error as { code?: string }).code === 'replacement_required'
+ ) {
+ setErrorClass('replacement_required')
+ setUiStatus(connection ? mapConnectionStatus(connection.status) : 'disconnected')
+ return
+ }
+ setUiStatus('unavailable')
+ setErrorClass(failureClass(error))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function startDevice(intent: CodexOAuthIntent) {
+ setBusy(true)
+ setErrorClass(null)
+ try {
+ const started = await startCodexDeviceConnect(intent)
+ setDeviceUserCode(started.userCode)
+ setDeviceVerificationUri(started.verificationUri)
+ setDeviceState(started.state)
+ setPollMs(started.intervalSeconds * 1000)
+ setUiStatus('device-pending')
+ } catch (error) {
+ if (isSilentApiError(error)) return
+ setUiStatus('unavailable')
+ setErrorClass(failureClass(error))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function handleReplace() {
+ const approved = await confirm({
+ title: 'Replace Codex account',
+ message:
+ 'This replaces the current Codex grant. Hosts and recipes using Codex subscription lose the current grant and must use the new account after replacement.',
+ confirmLabel: 'Replace account',
+ tone: 'danger',
+ })
+ if (!approved) return
+ await startBrowser('replace')
+ }
+
+ async function handleRevoke() {
+ const approved = await confirm({
+ title: 'Revoke Codex subscription',
+ message:
+ 'Revoke the deployment Codex grant? Catalog models stay visible but become unusable until a new connection.',
+ confirmLabel: 'Revoke',
+ tone: 'danger',
+ })
+ if (!approved) return
+ setBusy(true)
+ setUiStatus('revoking')
+ try {
+ applyConnection(await revokeCodexSubscription())
+ showToast('Codex subscription revoked.', { tone: 'success' })
+ } catch (error) {
+ if (isSilentApiError(error)) return
+ setUiStatus('unavailable')
+ setErrorClass(failureClass(error))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function handleSync() {
+ setBusy(true)
+ try {
+ const synced = await syncCodexSubscriptionCatalog()
+ applyConnection(synced.connection)
+ setSyncSummary(
+ `Catalog ${synced.outcome}: ${synced.added} added, ${synced.refreshed} refreshed, ${synced.staled} stale. New models stay disabled until enabled.`
+ )
+ showToast('Codex catalog synchronized.', { tone: 'success' })
+ } catch (error) {
+ if (isSilentApiError(error)) return
+ setErrorClass(failureClass(error))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function handleTest() {
+ setBusy(true)
+ try {
+ applyConnection(await refreshCodexSubscriptionConnection())
+ showToast('Codex connection test succeeded.', { tone: 'success' })
+ } catch (error) {
+ if (isSilentApiError(error)) return
+ setErrorClass(failureClass(error))
+ if (connection) setUiStatus(mapConnectionStatus(connection.status))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ function backToModels() {
+ router.push(CONTROL_ROUTES.llmModels.root)
+ }
+
+ if (!capabilityReady) {
+ return <p className="cu-subtitle">Checking Codex subscription availability.</p>
+ }
+
+ if (!enabled) {
+ return (
+ <CreateFlowPanel
+ header={
+ <CreatePageHeader
+ icon={<IconModels />}
+ title="Codex subscription"
+ subtitle="This provider is not enabled on the control plane."
+ backLabel="Back to models"
+ onBack={backToModels}
+ />
+ }
+ >
+ <div className="cu-banner" role="status">
+ Codex subscription is unavailable.
+ </div>
+ </CreateFlowPanel>
+ )
+ }
+
+ return (
+ <CreateFlowPanel
+ header={
+ <CreatePageHeader
+ icon={<IconModels />}
+ title="Codex subscription"
+ subtitle="Connect a broker-backed Codex catalog without storing tokens in the browser."
+ backLabel="Back to models"
+ onBack={backToModels}
+ backDisabled={busy}
+ />
+ }
+ >
+ <div className="cu-llm-models-layout">
+ <p data-testid="codex-connection-status">Status: {statusLabel(uiStatus)}</p>
+ {connection ? (
+ <dl>
+ <div>
+ <dt>Fingerprint</dt>
+ <dd data-testid="codex-fingerprint">{fingerprint}</dd>
+ </div>
+ <div>
+ <dt>Credential revision</dt>
+ <dd>{connection.credentialRevision}</dd>
+ </div>
+ <div>
+ <dt>Catalog revision</dt>
+ <dd>{connection.catalogRevision}</dd>
+ </div>
+ <div>
+ <dt>Catalog</dt>
+ <dd>{connection.catalogStatus}</dd>
+ </div>
+ </dl>
+ ) : null}
+ {deviceUserCode ? (
+ <p data-testid="codex-device-code">
+ Enter device code {deviceUserCode}
+ {deviceVerificationUri ? ` at ${deviceVerificationUri}` : ''}
+ </p>
+ ) : null}
+ {syncSummary ? <p data-testid="codex-sync-summary">{syncSummary}</p> : null}
+ {errorClass ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ Connection failed ({errorClass}).
+ </div>
+ ) : null}
+ <div>
+ <button
+ type="button"
+ className="cu-btn cu-btn--primary cu-btn--sm"
+ disabled={busy}
+ onClick={() => void startBrowser('connect')}
+ >
+ Connect in browser
+ </button>
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost cu-btn--sm"
+ disabled={busy}
+ onClick={() => void startDevice('connect')}
+ >
+ Use device code
+ </button>
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost cu-btn--sm"
+ disabled={busy || !connection}
+ onClick={() => void startBrowser('reconnect')}
+ >
+ Reconnect
+ </button>
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost cu-btn--sm"
+ disabled={busy || !connection}
+ onClick={() => void handleReplace()}
+ >
+ Replace account
+ </button>
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost cu-btn--sm"
+ disabled={busy || uiStatus !== 'connected'}
+ onClick={() => void handleSync()}
+ >
+ Sync catalog
+ </button>
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost cu-btn--sm"
+ disabled={busy || uiStatus !== 'connected'}
+ onClick={() => void handleTest()}
+ >
+ Test connection
+ </button>
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost cu-btn--sm"
+ disabled={busy || uiStatus === 'disconnected'}
+ onClick={() => void handleRevoke()}
+ >
+ Revoke
+ </button>
+ </div>
+ </div>
+ {confirmDialog}
+ </CreateFlowPanel>
+ )
+}
diff --git a/control-ui/components/CodexSubscriptionConnection/types.ts b/control-ui/components/CodexSubscriptionConnection/types.ts
new file mode 100644
index 000000000..d46ced913
--- /dev/null
+++ b/control-ui/components/CodexSubscriptionConnection/types.ts
@@ -0,0 +1,35 @@
+import type {
+ CodexCatalogSyncView,
+ CodexConnectionStatus,
+ CodexDeviceStartView,
+ CodexSubscriptionConnectionView,
+} from '@lib/codexSubscription'
+
+export type CodexSubscriptionUiStatus =
+ | 'disconnected'
+ | 'connecting'
+ | 'device-pending'
+ | 'connected'
+ | 'reauth-required'
+ | 'revoking'
+ | 'unavailable'
+
+export type CodexSubscriptionConnectionProps = {
+ initialConnection?: CodexSubscriptionConnectionView | null
+}
+
+export type CodexSubscriptionViewState = {
+ uiStatus: CodexSubscriptionUiStatus
+ connection: CodexSubscriptionConnectionView | null
+ device: CodexDeviceStartView | null
+ sync: CodexCatalogSyncView | null
+ failureClass: string | null
+}
+
+export function mapConnectionStatus(status: CodexConnectionStatus): CodexSubscriptionUiStatus {
+ if (status === 'reauth_required') return 'reauth-required'
+ if (status === 'connecting') return 'connecting'
+ if (status === 'connected') return 'connected'
+ if (status === 'revoked') return 'disconnected'
+ return 'disconnected'
+}
diff --git a/control-ui/components/LlmModelsSurface/index.tsx b/control-ui/components/LlmModelsSurface/index.tsx
index 4f5be0785..4e2cad86e 100644
--- a/control-ui/components/LlmModelsSurface/index.tsx
+++ b/control-ui/components/LlmModelsSurface/index.tsx
@@ -22,6 +22,10 @@ import {
isLlmModelConfigMapDeferred,
isSilentApiError,
} from '@lib/api'
+import {
+ isCodexSubscriptionUiEnabled,
+ loadCodexSubscriptionCapability,
+} from '@lib/codexSubscriptionFeature'
import { getProviderDisplayLabel } from '@lib/llm'
import { buildUnpricedKeys } from '@lib/llmModelUnpriced'
import { CatalogAttentionBanner } from './CatalogAttentionBanner'
@@ -44,6 +48,7 @@ function LlmModelsContent({ activeTab }: LlmModelsSurfaceProps) {
// Bumped after each successful mutation so the attention banner re-fetches
// and drops any item the operator just resolved (on demand, no polling).
const [attentionRefreshKey, setAttentionRefreshKey] = useState(0)
+ const [codexEnabled, setCodexEnabled] = useState(false)
const unpricedKeys = useMemo(() => buildUnpricedKeys(unpriced), [unpriced])
@@ -139,6 +144,9 @@ function LlmModelsContent({ activeTab }: LlmModelsSurfaceProps) {
useEffect(() => {
if (authState.isLoggedIn && !authState.isLoading) {
void loadAll()
+ void loadCodexSubscriptionCapability().then(capability => {
+ setCodexEnabled(isCodexSubscriptionUiEnabled(capability))
+ })
}
}, [activeTab, authState.isLoggedIn, authState.isLoading])
@@ -177,6 +185,11 @@ function LlmModelsContent({ activeTab }: LlmModelsSurfaceProps) {
{activeTab === 'catalog' ? (
<CatalogAttentionBanner refreshSignal={attentionRefreshKey} />
) : null}
+ {activeTab === 'catalog' && codexEnabled ? (
+ <p>
+ <a href={CONTROL_ROUTES.llmModels.codexSubscription}>Codex subscription</a>
+ </p>
+ ) : null}
{activeTab === 'catalog' ? (
<LlmModelTable
items={models}
diff --git a/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx b/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx
new file mode 100644
index 000000000..f703b18c5
--- /dev/null
+++ b/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx
@@ -0,0 +1,221 @@
+import type { ReactNode } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { sanitizeCodexConnection } from '@lib/codexSubscription'
+import type { CodexSubscriptionConnectionView } from '@lib/codexSubscription'
+import {
+ getCodexSubscriptionConnection,
+ refreshCodexSubscriptionConnection,
+ revokeCodexSubscription,
+ startCodexBrowserConnect,
+ startCodexDeviceConnect,
+ syncCodexSubscriptionCatalog,
+} from '@lib/codexSubscription'
+import { loadCodexSubscriptionCapability } from '@lib/codexSubscriptionFeature'
+import { CodexSubscriptionConnection } from '../CodexSubscriptionConnection'
+import { ToastProvider } from '../Toast'
+
+const confirmMock = vi.fn()
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: vi.fn() }),
+}))
+
+vi.mock('@components/ConfirmDialog', () => ({
+ useConfirmDialog: () => ({
+ confirm: confirmMock,
+ confirmDialog: null,
+ }),
+}))
+
+vi.mock('@lib/codexSubscriptionFeature', () => ({
+ loadCodexSubscriptionCapability: vi.fn(),
+ isCodexSubscriptionUiEnabled: (capability: { enabled?: boolean } | null) =>
+ capability?.enabled === true,
+}))
+
+vi.mock('@lib/codexSubscription', async importOriginal => {
+ const actual = await importOriginal<typeof import('@lib/codexSubscription')>()
+ return {
+ ...actual,
+ getCodexSubscriptionConnection: vi.fn(),
+ startCodexBrowserConnect: vi.fn(),
+ startCodexDeviceConnect: vi.fn(),
+ pollCodexDevice: vi.fn(),
+ refreshCodexSubscriptionConnection: vi.fn(),
+ syncCodexSubscriptionCatalog: vi.fn(),
+ revokeCodexSubscription: vi.fn(),
+ }
+})
+
+const connected: CodexSubscriptionConnectionView = {
+ connectionKey: 'deployment-default',
+ status: 'connected',
+ credentialRevision: 2,
+ catalogRevision: 4,
+ accountFingerprint: 'fp-safe',
+ catalogStatus: 'ready',
+ catalogSyncedAt: '2026-08-20T00:00:00.000Z',
+ lastRefreshAt: '2026-08-20T00:00:00.000Z',
+ lastAuthAt: '2026-08-20T00:00:00.000Z',
+ refreshLockHeld: false,
+}
+
+function renderSurface() {
+ return render(
+ <ToastProvider>
+ <CodexSubscriptionConnection />
+ </ToastProvider>
+ )
+}
+
+describe('CodexSubscriptionConnection', () => {
+ beforeEach(() => {
+ confirmMock.mockReset()
+ confirmMock.mockResolvedValue(true)
+ vi.mocked(loadCodexSubscriptionCapability).mockResolvedValue({ enabled: true })
+ vi.mocked(getCodexSubscriptionConnection).mockResolvedValue(connected)
+ vi.stubGlobal('open', vi.fn())
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+ vi.unstubAllGlobals()
+ })
+
+ it('strips tokens from a leaked connection fixture', () => {
+ expect(() =>
+ sanitizeCodexConnection({
+ ...connected,
+ accessToken: 'sk-leaked',
+ })
+ ).toThrow(/accessToken/)
+ })
+
+ it('hides the surface when Control API capability is disabled', async () => {
+ vi.mocked(loadCodexSubscriptionCapability).mockResolvedValue({ enabled: false })
+ renderSurface()
+ expect(await screen.findByText('Codex subscription is unavailable.')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Connect in browser' })).not.toBeInTheDocument()
+ })
+
+ it('renders connected status without tokens or account ids', async () => {
+ renderSurface()
+ expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent('Connected')
+ expect(screen.getByTestId('codex-fingerprint')).toHaveTextContent('fp-safe')
+ expect(document.body.textContent).not.toMatch(/sk-|accessToken|acct_raw|Authorization/i)
+ })
+
+ it.each([
+ ['disconnected', 'Disconnected'],
+ ['connecting', 'Connecting'],
+ ['reauth_required', 'Reauthorization required'],
+ ] as const)('maps backend status %s to %s', async (status, label) => {
+ vi.mocked(getCodexSubscriptionConnection).mockResolvedValue({ ...connected, status })
+ renderSurface()
+ expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent(label)
+ })
+
+ it('starts a browser connect without rendering secrets', async () => {
+ vi.mocked(startCodexBrowserConnect).mockResolvedValue({
+ authorizeUrl: 'https://auth.openai.com/oauth/authorize?state=abc',
+ state: 'abc',
+ intent: 'connect',
+ expiresAt: '2026-08-20T00:01:00.000Z',
+ })
+ renderSurface()
+ fireEvent.click(await screen.findByRole('button', { name: 'Connect in browser' }))
+ await waitFor(() => {
+ expect(startCodexBrowserConnect).toHaveBeenCalledWith('connect')
+ })
+ expect(window.open).toHaveBeenCalledWith(
+ 'https://auth.openai.com/oauth/authorize?state=abc',
+ '_blank',
+ 'noopener,noreferrer'
+ )
+ expect(document.body.textContent).not.toMatch(/sk-|deviceCode|accessToken/i)
+ })
+
+ it('shows device-code progress without the secret device code', async () => {
+ vi.mocked(startCodexDeviceConnect).mockResolvedValue({
+ userCode: 'ABCD-EFGH',
+ verificationUri: 'https://auth.openai.com/codex/device',
+ intervalSeconds: 5,
+ state: 'dev',
+ intent: 'connect',
+ })
+ renderSurface()
+ fireEvent.click(await screen.findByRole('button', { name: 'Use device code' }))
+ expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent(
+ 'Device code pending'
+ )
+ expect(screen.getByTestId('codex-device-code')).toHaveTextContent('ABCD-EFGH')
+ expect(document.body.textContent).not.toContain('device_secret')
+ })
+
+ it('confirms replacement impact before starting a replace flow', async () => {
+ vi.mocked(startCodexBrowserConnect).mockResolvedValue({
+ authorizeUrl: 'https://auth.openai.com/oauth/authorize?state=rep',
+ state: 'rep',
+ intent: 'replace',
+ expiresAt: '2026-08-20T00:01:00.000Z',
+ })
+ renderSurface()
+ fireEvent.click(await screen.findByRole('button', { name: 'Replace account' }))
+ await waitFor(() => {
+ expect(confirmMock).toHaveBeenCalled()
+ })
+ expect(String(confirmMock.mock.calls[0]?.[0]?.message)).toMatch(/lose the current grant/i)
+ await waitFor(() => {
+ expect(startCodexBrowserConnect).toHaveBeenCalledWith('replace')
+ })
+ })
+
+ it('syncs catalog and keeps newly discovered models disabled in the summary', async () => {
+ vi.mocked(syncCodexSubscriptionCatalog).mockResolvedValue({
+ outcome: 'ready',
+ added: 2,
+ refreshed: 1,
+ staled: 1,
+ connection: connected,
+ })
+ renderSurface()
+ fireEvent.click(await screen.findByRole('button', { name: 'Sync catalog' }))
+ expect(await screen.findByTestId('codex-sync-summary')).toHaveTextContent(
+ 'New models stay disabled until enabled'
+ )
+ expect(syncCodexSubscriptionCatalog).toHaveBeenCalled()
+ })
+
+ it('tests and revokes the connection', async () => {
+ vi.mocked(refreshCodexSubscriptionConnection).mockResolvedValue(connected)
+ vi.mocked(revokeCodexSubscription).mockResolvedValue({
+ ...connected,
+ status: 'revoked',
+ })
+ renderSurface()
+ fireEvent.click(await screen.findByRole('button', { name: 'Test connection' }))
+ await waitFor(() => {
+ expect(refreshCodexSubscriptionConnection).toHaveBeenCalled()
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Revoke' }))
+ await waitFor(() => {
+ expect(revokeCodexSubscription).toHaveBeenCalled()
+ })
+ expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent('Disconnected')
+ })
+
+ it('anti-false-positive: a leaked accessToken never reaches the DOM', async () => {
+ vi.mocked(getCodexSubscriptionConnection).mockImplementation(async () =>
+ sanitizeCodexConnection({
+ ...connected,
+ accessToken: 'sk-should-not-render',
+ })
+ )
+ renderSurface()
+ expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent('Unavailable')
+ expect(document.body.textContent).not.toContain('sk-should-not-render')
+ expect(document.body.textContent).not.toContain('accessToken')
+ })
+})
diff --git a/control-ui/components/__tests__/LlmModelsSurface.test.tsx b/control-ui/components/__tests__/LlmModelsSurface.test.tsx
index 9993079f8..d85299092 100644
--- a/control-ui/components/__tests__/LlmModelsSurface.test.tsx
+++ b/control-ui/components/__tests__/LlmModelsSurface.test.tsx
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import type { LlmAllowedModel } from '@lib/api'
import { getLlmModels, getUnpricedModels } from '@lib/api'
+import { loadCodexSubscriptionCapability } from '@lib/codexSubscriptionFeature'
import { LlmModelsSurface } from '../LlmModelsSurface'
import { ToastProvider } from '../Toast'
@@ -29,6 +30,12 @@ vi.mock('@lib/api', async importOriginal => {
return { ...actual, getLlmModels: vi.fn(), getUnpricedModels: vi.fn() }
})
+vi.mock('@lib/codexSubscriptionFeature', () => ({
+ loadCodexSubscriptionCapability: vi.fn(),
+ isCodexSubscriptionUiEnabled: (capability: { enabled?: boolean } | null) =>
+ capability?.enabled === true,
+}))
+
const model: LlmAllowedModel = {
id: 'model-1',
provider: 'openai',
@@ -51,6 +58,7 @@ describe('LlmModelsSurface', () => {
vi.mocked(getUnpricedModels).mockReturnValue(
new Promise<Awaited<ReturnType<typeof getUnpricedModels>>>(() => undefined)
)
+ vi.mocked(loadCodexSubscriptionCapability).mockResolvedValue({ enabled: false })
})
afterEach(() => {
@@ -67,5 +75,31 @@ describe('LlmModelsSurface', () => {
expect(await screen.findByText('Discovery models: 1')).toBeInTheDocument()
expect(getUnpricedModels).not.toHaveBeenCalled()
+ expect(screen.queryByRole('link', { name: 'Codex subscription' })).not.toBeInTheDocument()
+ })
+
+ it('hides the Codex subscription deep link when Control API capability is absent', async () => {
+ render(
+ <ToastProvider>
+ <LlmModelsSurface activeTab="catalog" />
+ </ToastProvider>
+ )
+
+ expect(await screen.findByText('Model catalog')).toBeInTheDocument()
+ expect(screen.queryByRole('link', { name: 'Codex subscription' })).not.toBeInTheDocument()
+ })
+
+ it('shows the Codex subscription deep link only after Control API proves the flag', async () => {
+ vi.mocked(loadCodexSubscriptionCapability).mockResolvedValue({ enabled: true })
+ render(
+ <ToastProvider>
+ <LlmModelsSurface activeTab="catalog" />
+ </ToastProvider>
+ )
+
+ expect(await screen.findByRole('link', { name: 'Codex subscription' })).toHaveAttribute(
+ 'href',
+ '/llm-models/providers/codex-subscription'
+ )
})
})
diff --git a/control-ui/lib/__tests__/routes.test.ts b/control-ui/lib/__tests__/routes.test.ts
index de98de1d7..8eb786baa 100644
--- a/control-ui/lib/__tests__/routes.test.ts
+++ b/control-ui/lib/__tests__/routes.test.ts
@@ -27,4 +27,10 @@ describe('CONTROL_ROUTES', () => {
expect(CONTROL_ROUTES.agentOutputs.root).toBe('/agent-outputs/recipe-artifacts')
expect(CONTROL_ROUTES.globalFileSystem).toBe('/global-file-system')
})
+
+ it('exposes the Codex subscription provider path without query tabs', () => {
+ expect(CONTROL_ROUTES.llmModels.codexSubscription).toBe(
+ '/llm-models/providers/codex-subscription'
+ )
+ })
})
diff --git a/control-ui/lib/codexSubscription.ts b/control-ui/lib/codexSubscription.ts
new file mode 100644
index 000000000..c6e0d6251
--- /dev/null
+++ b/control-ui/lib/codexSubscription.ts
@@ -0,0 +1,236 @@
+import { apiGet, apiSend } from './api'
+
+export const CODEX_SUBSCRIPTION_API_BASE = '/api/v1/admin/llm/providers/codex-subscription'
+
+export type CodexConnectionStatus =
+ | 'disconnected'
+ | 'connecting'
+ | 'connected'
+ | 'reauth_required'
+ | 'revoked'
+
+export type CodexCatalogStatus = 'never_synced' | 'ready' | 'auth-rejected' | 'unavailable'
+
+export type CodexOAuthIntent = 'connect' | 'reconnect' | 'replace'
+
+export type CodexSubscriptionConnectionView = {
+ connectionKey: 'deployment-default'
+ status: CodexConnectionStatus
+ credentialRevision: number
+ catalogRevision: number
+ accountFingerprint: string | null
+ catalogStatus: CodexCatalogStatus
+ catalogSyncedAt: string | null
+ lastRefreshAt: string | null
+ lastAuthAt: string | null
+ refreshLockHeld: boolean
+}
+
+export type CodexBrowserStartView = {
+ authorizeUrl: string
+ state: string
+ intent: CodexOAuthIntent
+ expiresAt: string
+}
+
+export type CodexDeviceStartView = {
+ userCode: string
+ verificationUri: string
+ intervalSeconds: number
+ state: string
+ intent: CodexOAuthIntent
+}
+
+export type CodexDevicePollView =
+ | { status: 'pending' | 'slow_down'; intervalSeconds: number; state: string }
+ | { status: 'connected'; connection: CodexSubscriptionConnectionView }
+ | { status: 'expired' | 'denied' }
+
+export type CodexCatalogSyncView = {
+ outcome: string
+ added: number
+ refreshed: number
+ staled: number
+ connection: CodexSubscriptionConnectionView
+}
+
+const FORBIDDEN_KEY =
+ /accessToken|refreshToken|deviceCode|authorization|set-cookie|cookie|proxyUrl|proxyURL|accountId|rawAccount|subject/i
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
+}
+
+function assertNoForbiddenKeys(value: unknown, path = 'root'): void {
+ if (Array.isArray(value)) {
+ value.forEach((entry, index) => assertNoForbiddenKeys(entry, `${path}[${index}]`))
+ return
+ }
+ if (!isPlainObject(value)) return
+ for (const [key, nested] of Object.entries(value)) {
+ if (FORBIDDEN_KEY.test(key)) {
+ throw new Error(`Codex subscription payload leaked forbidden field "${key}" at ${path}`)
+ }
+ assertNoForbiddenKeys(nested, `${path}.${key}`)
+ }
+}
+
+function pickString(value: unknown): string | null {
+ return typeof value === 'string' && value.trim() ? value : null
+}
+
+function pickNumber(value: unknown, fallback = 0): number {
+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback
+}
+
+function pickBool(value: unknown): boolean {
+ return value === true
+}
+
+export function sanitizeCodexConnection(raw: unknown): CodexSubscriptionConnectionView {
+ assertNoForbiddenKeys(raw)
+ if (!isPlainObject(raw)) {
+ throw new Error('Codex subscription connection is not an object')
+ }
+ const status = raw.status
+ if (
+ status !== 'disconnected' &&
+ status !== 'connecting' &&
+ status !== 'connected' &&
+ status !== 'reauth_required' &&
+ status !== 'revoked'
+ ) {
+ throw new Error('Codex subscription connection status is invalid')
+ }
+ const catalogStatus = raw.catalogStatus
+ const safeCatalog: CodexCatalogStatus =
+ catalogStatus === 'ready' ||
+ catalogStatus === 'auth-rejected' ||
+ catalogStatus === 'unavailable' ||
+ catalogStatus === 'never_synced'
+ ? catalogStatus
+ : 'never_synced'
+ return {
+ connectionKey: 'deployment-default',
+ status,
+ credentialRevision: pickNumber(raw.credentialRevision),
+ catalogRevision: pickNumber(raw.catalogRevision),
+ accountFingerprint: pickString(raw.accountFingerprint),
+ catalogStatus: safeCatalog,
+ catalogSyncedAt: pickString(raw.catalogSyncedAt),
+ lastRefreshAt: pickString(raw.lastRefreshAt),
+ lastAuthAt: pickString(raw.lastAuthAt),
+ refreshLockHeld: pickBool(raw.refreshLockHeld),
+ }
+}
+
+export function sanitizeCodexBrowserStart(raw: unknown): CodexBrowserStartView {
+ assertNoForbiddenKeys(raw)
+ if (!isPlainObject(raw)) throw new Error('Codex browser start is not an object')
+ const authorizeUrl = pickString(raw.authorizeUrl)
+ const state = pickString(raw.state)
+ const expiresAt = pickString(raw.expiresAt)
+ const intent = raw.intent
+ if (!authorizeUrl || !state || !expiresAt) {
+ throw new Error('Codex browser start is incomplete')
+ }
+ if (!authorizeUrl.startsWith('https://')) {
+ throw new Error('Codex browser start authorizeUrl must be https')
+ }
+ return {
+ authorizeUrl,
+ state,
+ intent: intent === 'reconnect' || intent === 'replace' ? intent : 'connect',
+ expiresAt,
+ }
+}
+
+export function sanitizeCodexDeviceStart(raw: unknown): CodexDeviceStartView {
+ assertNoForbiddenKeys(raw)
+ if (!isPlainObject(raw)) throw new Error('Codex device start is not an object')
+ const userCode = pickString(raw.userCode)
+ const verificationUri = pickString(raw.verificationUri)
+ const state = pickString(raw.state)
+ const intent = raw.intent
+ if (!userCode || !verificationUri || !state) {
+ throw new Error('Codex device start is incomplete')
+ }
+ return {
+ userCode,
+ verificationUri,
+ intervalSeconds: Math.max(1, pickNumber(raw.intervalSeconds, 5)),
+ state,
+ intent: intent === 'reconnect' || intent === 'replace' ? intent : 'connect',
+ }
+}
+
+export function sanitizeCodexDevicePoll(raw: unknown): CodexDevicePollView {
+ assertNoForbiddenKeys(raw)
+ if (!isPlainObject(raw)) throw new Error('Codex device poll is not an object')
+ if (raw.status === 'connected') {
+ return { status: 'connected', connection: sanitizeCodexConnection(raw.connection) }
+ }
+ if (raw.status === 'expired' || raw.status === 'denied') {
+ return { status: raw.status }
+ }
+ if (raw.status === 'pending' || raw.status === 'slow_down') {
+ return {
+ status: raw.status,
+ intervalSeconds: Math.max(1, pickNumber(raw.intervalSeconds, 5)),
+ state: pickString(raw.state) ?? '',
+ }
+ }
+ throw new Error('Codex device poll status is invalid')
+}
+
+export function sanitizeCodexCatalogSync(raw: unknown): CodexCatalogSyncView {
+ assertNoForbiddenKeys(raw)
+ if (!isPlainObject(raw)) throw new Error('Codex catalog sync is not an object')
+ return {
+ outcome: pickString(raw.outcome) ?? 'unknown',
+ added: pickNumber(raw.added),
+ refreshed: pickNumber(raw.refreshed),
+ staled: pickNumber(raw.staled),
+ connection: sanitizeCodexConnection(raw.connection),
+ }
+}
+
+export async function getCodexSubscriptionConnection(): Promise<CodexSubscriptionConnectionView> {
+ return sanitizeCodexConnection(await apiGet(`${CODEX_SUBSCRIPTION_API_BASE}/connection`))
+}
+
+export async function startCodexBrowserConnect(
+ intent: CodexOAuthIntent
+): Promise<CodexBrowserStartView> {
+ return sanitizeCodexBrowserStart(
+ await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/browser/start`, { intent })
+ )
+}
+
+export async function startCodexDeviceConnect(
+ intent: CodexOAuthIntent
+): Promise<CodexDeviceStartView> {
+ return sanitizeCodexDeviceStart(
+ await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/device/start`, { intent })
+ )
+}
+
+export async function pollCodexDevice(state: string): Promise<CodexDevicePollView> {
+ return sanitizeCodexDevicePoll(
+ await apiGet(`${CODEX_SUBSCRIPTION_API_BASE}/device/poll`, { state })
+ )
+}
+
+export async function refreshCodexSubscriptionConnection(): Promise<CodexSubscriptionConnectionView> {
+ return sanitizeCodexConnection(await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/refresh`))
+}
+
+export async function syncCodexSubscriptionCatalog(): Promise<CodexCatalogSyncView> {
+ return sanitizeCodexCatalogSync(
+ await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/catalog/sync`)
+ )
+}
+
+export async function revokeCodexSubscription(): Promise<CodexSubscriptionConnectionView> {
+ return sanitizeCodexConnection(await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/revoke`))
+}
diff --git a/control-ui/lib/codexSubscriptionFeature.ts b/control-ui/lib/codexSubscriptionFeature.ts
new file mode 100644
index 000000000..669a1cbe8
--- /dev/null
+++ b/control-ui/lib/codexSubscriptionFeature.ts
@@ -0,0 +1,34 @@
+import { getCodexSubscriptionConnection } from './codexSubscription'
+
+export type CodexSubscriptionCapability = {
+ enabled: boolean
+}
+
+const DISABLED_CAPABILITY: CodexSubscriptionCapability = { enabled: false }
+
+function isDisabledCapabilityError(error: unknown): boolean {
+ if (!error || typeof error !== 'object') return false
+ const status = (error as { status?: unknown }).status
+ const code = (error as { code?: unknown }).code
+ return status === 404 || code === 'disabled'
+}
+
+/**
+ * Control UI default is off. Capability is proven only by a successful
+ * Control API connection read — never by a browser-manipulable env var.
+ */
+export async function loadCodexSubscriptionCapability(): Promise<CodexSubscriptionCapability> {
+ try {
+ await getCodexSubscriptionConnection()
+ return { enabled: true }
+ } catch (error) {
+ if (isDisabledCapabilityError(error)) return DISABLED_CAPABILITY
+ return DISABLED_CAPABILITY
+ }
+}
+
+export function isCodexSubscriptionUiEnabled(
+ capability: CodexSubscriptionCapability | null | undefined
+): boolean {
+ return capability?.enabled === true
+}