Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(codex): use ChatGPT Sign in device auth on Control UI
Alfredo Lopez8d421237ef8f
diff --git a/control-api/src/services/codexSubscriptionOAuth.ts b/control-api/src/services/codexSubscriptionOAuth.tsindex 2cdc3478c..243eb4ad5 100644--- a/control-api/src/services/codexSubscriptionOAuth.ts+++ b/control-api/src/services/codexSubscriptionOAuth.ts@@ -26,9 +26,15 @@ const log = rootLogger.child({ module: 'codex-subscription-oauth' })export const CODEX_OAUTH_AUTHORIZE_URL = 'https://auth.openai.com/oauth/authorize'export const CODEX_OAUTH_TOKEN_URL = 'https://auth.openai.com/oauth/token'+/** Prefix shared by the Codex CLI device-auth routes. */export const CODEX_OAUTH_DEVICE_URL = 'https://auth.openai.com/api/accounts/deviceauth'+export const CODEX_OAUTH_DEVICE_USERCODE_URL = `${CODEX_OAUTH_DEVICE_URL}/usercode`+export const CODEX_OAUTH_DEVICE_TOKEN_URL = `${CODEX_OAUTH_DEVICE_URL}/token`+export const CODEX_OAUTH_DEVICE_VERIFICATION_URI = 'https://auth.openai.com/codex/device'+export const CODEX_OAUTH_DEVICE_CALLBACK_URI = 'https://auth.openai.com/deviceauth/callback'export const CODEX_OAUTH_REVOKE_URL = 'https://auth.openai.com/oauth/revoke'export const CODEX_OAUTH_SCOPES = ['openid', 'profile', 'email', 'offline_access'] as const+const DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60const TOKEN_TIMEOUT_MS = 15_000const REFRESH_LOCK_TTL_MS = 30_000@@ -140,37 +146,30 @@ export async function startCodexDeviceConnect(intent: CodexSubscriptionOAuthIntent = 'connect'): Promise<CodexDeviceStartResult> {requireEnabled(deps)- const started = await postJson(deps, CODEX_OAUTH_DEVICE_URL, {+ const started = await postJson(deps, CODEX_OAUTH_DEVICE_USERCODE_URL, {client_id: deps.clientId,- scope: CODEX_OAUTH_SCOPES.join(' '),})if (!started.ok) {throw new CodexSubscriptionOAuthError('provider_unavailable', 'device authorization failed')}- const body = started.body as Record<string, unknown>- const deviceCode = requiredString(body.device_code, 'device_code')- const userCode = requiredString(body.user_code, 'user_code')- const verificationUri = requiredString(- body.verification_uri ?? body.verification_uri_complete,- 'verification_uri'- )- const intervalSeconds = positiveNumber(body.interval, 5)- const expiresIn = positiveNumber(body.expires_in, 600)- const expiresAt = new Date(Date.now() + expiresIn * 1000)+ const body = started.body+ const deviceAuthId = requiredString(body.device_auth_id, 'device_auth_id')+ const userCode = requiredString(body.user_code ?? body.usercode, 'user_code')+ const intervalSeconds = parsePositiveNumber(body.interval, 5)+ const expiresAt = parseDeviceExpiry(body)const state = randomBytes(24).toString('base64url')const safe = await insertCodexSubscriptionOAuthState(deps.db, deps.encryptionKey, {state,flow: 'device',intent,- deviceCode,+ deviceCode: encodeDeviceAuthHandle({ deviceAuthId, userCode }),expiresAt,})log.info({ event: 'codex_oauth_device_start', intent: safe.intent }, 'device OAuth start')return {userCode,- verificationUri,- verificationUriComplete:- typeof body.verification_uri_complete === 'string' ? body.verification_uri_complete : null,+ verificationUri: CODEX_OAUTH_DEVICE_VERIFICATION_URI,+ verificationUriComplete: null,intervalSeconds,expiresAt: safe.expiresAt,state,@@ -214,13 +213,14 @@ export async function pollCodexDevice(await expireCodexSubscriptionOAuthState(deps.db, state)return { status: 'expired' }}- if (!pending.deviceCode) {+ const handle = decodeDeviceAuthHandle(pending.deviceCode)+ if (!handle) {throw new CodexSubscriptionOAuthError('invalid_callback',- 'device state is missing a device code'+ 'device state is missing a device auth handle')}- const tokenResult = await exchangeDeviceCode(deps, pending.deviceCode)+ const tokenResult = await pollDeviceAuthorization(deps, handle)if (tokenResult.kind === 'pending') {return { status: 'pending', intervalSeconds: tokenResult.intervalSeconds, state: pending.safe }}@@ -375,12 +375,13 @@ type ParsedCodexToken = {async function exchangeAuthorizationCode(deps: CodexOAuthDeps,code: string,- pkceVerifier: string+ pkceVerifier: string,+ redirectUri = deps.redirectUri): Promise<ParsedCodexToken> {const result = await postForm(deps, CODEX_OAUTH_TOKEN_URL, {grant_type: 'authorization_code',code,- redirect_uri: deps.redirectUri,+ redirect_uri: redirectUri,client_id: deps.clientId,code_verifier: pkceVerifier,})@@ -408,9 +409,49 @@ async function exchangeRefreshToken(return parseTokenResponse(result.body)}-async function exchangeDeviceCode(+type CodexDeviceAuthHandle = {+ deviceAuthId: string+ userCode: string+}++function encodeDeviceAuthHandle(handle: CodexDeviceAuthHandle): string {+ return JSON.stringify(handle)+}++function decodeDeviceAuthHandle(value: string | undefined): CodexDeviceAuthHandle | null {+ if (!value) return null+ try {+ const parsed = JSON.parse(value) as { deviceAuthId?: unknown; userCode?: unknown }+ if (+ typeof parsed.deviceAuthId === 'string' &&+ parsed.deviceAuthId.length > 0 &&+ typeof parsed.userCode === 'string' &&+ parsed.userCode.length > 0+ ) {+ return { deviceAuthId: parsed.deviceAuthId, userCode: parsed.userCode }+ }+ } catch {+ return null+ }+ return null+}++function readUpstreamErrorCode(body: Record<string, unknown>): string {+ const error = body.error+ if (typeof error === 'string') return error+ if (+ error &&+ typeof error === 'object' &&+ typeof (error as { code?: unknown }).code === 'string'+ ) {+ return (error as { code: string }).code+ }+ return ''+}++async function pollDeviceAuthorization(deps: CodexOAuthDeps,- deviceCode: string+ handle: CodexDeviceAuthHandle): Promise<| { kind: 'ok'; parsed: ParsedCodexToken }| { kind: 'pending'; intervalSeconds: number }@@ -418,22 +459,35 @@ async function exchangeDeviceCode(| { kind: 'expired' }| { kind: 'denied' }> {- const result = await postForm(deps, CODEX_OAUTH_TOKEN_URL, {- grant_type: 'urn:ietf:params:oauth:grant-type:device_code',- device_code: deviceCode,- client_id: deps.clientId,+ const result = await postJson(deps, CODEX_OAUTH_DEVICE_TOKEN_URL, {+ device_auth_id: handle.deviceAuthId,+ user_code: handle.userCode,})if (result.ok) {+ const authorizationCode = requiredString(result.body.authorization_code, 'authorization_code')+ const codeVerifier = requiredString(result.body.code_verifier, 'code_verifier')return {kind: 'ok',- parsed: parseTokenResponse(result.body),+ parsed: await exchangeAuthorizationCode(+ deps,+ authorizationCode,+ codeVerifier,+ CODEX_OAUTH_DEVICE_CALLBACK_URI+ ),}}- const error = typeof result.body.error === 'string' ? result.body.error : ''- if (error === 'authorization_pending') return { kind: 'pending', intervalSeconds: 5 }- if (error === 'slow_down') return { kind: 'slow_down', intervalSeconds: 10 }- if (error === 'expired_token') return { kind: 'expired' }- if (error === 'access_denied') return { kind: 'denied' }+ if (result.status === 403 || result.status === 404) {+ return { kind: 'pending', intervalSeconds: parsePositiveNumber(result.body.interval, 5) }+ }+ const error = readUpstreamErrorCode(result.body)+ if (error === 'authorization_pending' || error === 'deviceauth_authorization_pending') {+ return { kind: 'pending', intervalSeconds: parsePositiveNumber(result.body.interval, 5) }+ }+ if (error === 'slow_down') {+ return { kind: 'slow_down', intervalSeconds: parsePositiveNumber(result.body.interval, 10) }+ }+ if (error === 'expired_token' || error === 'deviceauth_expired') return { kind: 'expired' }+ if (error === 'access_denied' || error === 'deviceauth_denied') return { kind: 'denied' }throw new CodexSubscriptionOAuthError('provider_unavailable', 'device token poll failed')}@@ -479,7 +533,7 @@ async function postForm(deps: CodexOAuthDeps,url: string,params: Record<string, string>-): Promise<{ ok: boolean; body: Record<string, unknown> }> {+): Promise<{ ok: boolean; status: number; body: Record<string, unknown> }> {return post(deps,url,@@ -492,7 +546,7 @@ async function postJson(deps: CodexOAuthDeps,url: string,payload: Record<string, string>-): Promise<{ ok: boolean; body: Record<string, unknown> }> {+): Promise<{ ok: boolean; status: number; body: Record<string, unknown> }> {return post(deps, url, 'application/json', JSON.stringify(payload))}@@ -501,7 +555,7 @@ async function post(url: string,contentType: string,body: string-): Promise<{ ok: boolean; body: Record<string, unknown> }> {+): Promise<{ ok: boolean; status: number; body: Record<string, unknown> }> {let response: Responsetry {response = await deps.fetchFn(url, {@@ -518,7 +572,7 @@ async function post()}const json = (await response.json().catch(() => ({}))) as Record<string, unknown>- return { ok: response.ok, body: json }+ return { ok: response.ok, status: response.status, body: json }}function requiredString(value: unknown, field: string): string {@@ -528,6 +582,20 @@ function requiredString(value: unknown, field: string): string {return value}-function positiveNumber(value: unknown, fallback: number): number {- return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback+function parsePositiveNumber(value: unknown, fallback: number): number {+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value+ if (typeof value === 'string') {+ const parsed = Number(value.trim())+ if (Number.isFinite(parsed) && parsed > 0) return parsed+ }+ return fallback+}++function parseDeviceExpiry(body: Record<string, unknown>): Date {+ if (typeof body.expires_at === 'string') {+ const parsed = new Date(body.expires_at)+ if (!Number.isNaN(parsed.getTime())) return parsed+ }+ const expiresIn = parsePositiveNumber(body.expires_in, DEVICE_CODE_TIMEOUT_SECONDS)+ return new Date(Date.now() + expiresIn * 1000)}diff --git a/control-api/src/services/codexSubscriptionOAuthState.ts b/control-api/src/services/codexSubscriptionOAuthState.tsindex afeab0ed6..23173f4f4 100644--- a/control-api/src/services/codexSubscriptionOAuthState.ts+++ b/control-api/src/services/codexSubscriptionOAuthState.ts@@ -21,6 +21,7 @@ export type CodexSubscriptionOAuthStateWrite = {flow: CodexSubscriptionOAuthFlowintent: CodexSubscriptionOAuthIntentpkceVerifier?: string+ /** Encrypted Codex device handle JSON: { deviceAuthId, userCode }. */deviceCode?: stringexpiresAt: Date}diff --git a/control-api/test/services.codexSubscriptionOAuth.test.ts b/control-api/test/services.codexSubscriptionOAuth.test.tsindex 3eec7da5d..59bce0744 100644--- a/control-api/test/services.codexSubscriptionOAuth.test.ts+++ b/control-api/test/services.codexSubscriptionOAuth.test.ts@@ -47,6 +47,10 @@ vi.mock('../src/services/codexSubscriptionConnection.js', async () => {const {CodexSubscriptionOAuthError,CODEX_OAUTH_AUTHORIZE_URL,+ CODEX_OAUTH_DEVICE_CALLBACK_URI,+ CODEX_OAUTH_DEVICE_TOKEN_URL,+ CODEX_OAUTH_DEVICE_USERCODE_URL,+ CODEX_OAUTH_DEVICE_VERIFICATION_URI,handleCodexBrowserCallback,pollCodexDevice,refreshCodexSubscriptionConnection,@@ -252,6 +256,7 @@ describe('codex subscription OAuth broker', () => {})it('polls device authorization with expiry and backoff', async () => {+ const handle = JSON.stringify({ deviceAuthId: 'deviceauth_secret', userCode: 'ABCD-EFGH' })repos.peekState.mockResolvedValue({safe: {state: 'dev-1',@@ -263,22 +268,25 @@ describe('codex subscription OAuth broker', () => {cancelledAt: null,createdAt: new Date(),},- deviceCode: 'device-secret',+ deviceCode: handle,})const fetchFn = vi.fn().mockResolvedValueOnce({ok: false,- json: async () => ({ error: 'authorization_pending' }),+ status: 403,+ json: async () => ({}),}).mockResolvedValueOnce({ok: false,- json: async () => ({ error: 'slow_down' }),+ status: 400,+ json: async () => ({ error: { code: 'slow_down' }, interval: '10' }),})await expect(pollCodexDevice(deps(fetchFn), 'dev-1')).resolves.toMatchObject({status: 'pending',intervalSeconds: 5,})+ expect(fetchFn.mock.calls[0]?.[0]).toBe(CODEX_OAUTH_DEVICE_TOKEN_URL)await expect(pollCodexDevice(deps(fetchFn), 'dev-1')).resolves.toMatchObject({status: 'slow_down',intervalSeconds: 10,@@ -295,12 +303,78 @@ describe('codex subscription OAuth broker', () => {cancelledAt: null,createdAt: new Date(),},- deviceCode: 'device-secret',+ deviceCode: handle,})await expect(pollCodexDevice(deps(fetchFn), 'dev-exp')).resolves.toEqual({ status: 'expired' })expect(repos.expireState).toHaveBeenCalled()})+ it('exchanges a completed device poll through the Codex device callback', async () => {+ const handle = JSON.stringify({ deviceAuthId: 'deviceauth_secret', userCode: 'ABCD-EFGH' })+ repos.peekState.mockResolvedValue({+ safe: {+ state: 'dev-ok',+ flow: 'device',+ intent: 'connect',+ status: 'pending',+ expiresAt: new Date(Date.now() + 60_000),+ consumedAt: null,+ cancelledAt: null,+ createdAt: new Date(),+ },+ deviceCode: handle,+ })+ repos.consumeState.mockResolvedValue({+ safe: {+ state: 'dev-ok',+ flow: 'device',+ intent: 'connect',+ status: 'consumed',+ expiresAt: new Date(Date.now() + 60_000),+ consumedAt: new Date(),+ cancelledAt: null,+ createdAt: new Date(),+ },+ deviceCode: handle,+ })+ repos.getSafe.mockResolvedValue(null)+ repos.insertInitial.mockResolvedValue({+ connectionKey: 'deployment-default',+ status: 'connected',+ credentialRevision: 1,+ accountFingerprint: fingerprint('acct_raw_123'),+ })+ const fetchFn = vi+ .fn()+ .mockResolvedValueOnce({+ ok: true,+ status: 200,+ json: async () => ({+ authorization_code: 'authz-code',+ code_verifier: 'pkce-from-poll',+ }),+ })+ .mockResolvedValueOnce({+ ok: true,+ status: 200,+ json: async () => ({+ access_token: 'access-secret',+ refresh_token: 'refresh-secret',+ expires_in: 60,+ id_token: idTokenFor('acct_raw_123'),+ }),+ })+ const connected = await pollCodexDevice(deps(fetchFn), 'dev-ok')+ expect(connected.status).toBe('connected')+ expect(fetchFn.mock.calls[1]?.[0]).toContain('/oauth/token')+ expect(String(fetchFn.mock.calls[1]?.[1]?.body)).toContain(+ encodeURIComponent(CODEX_OAUTH_DEVICE_CALLBACK_URI)+ )+ expect(String(fetchFn.mock.calls[1]?.[1]?.body)).toContain('code_verifier=pkce-from-poll')+ assertNoLeak(connected)+ expect(JSON.stringify(connected)).not.toContain('deviceauth_secret')+ })+it('rejects a stale refresh and persists a rotated refresh token', async () => {repos.getSafe.mockResolvedValue({connectionKey: 'deployment-default',@@ -360,19 +434,19 @@ describe('codex subscription OAuth broker', () => {assertNoLeak(revoked)})- it('starts device flow without returning the device code', async () => {+ it('starts device flow without returning the device auth handle', async () => {const fetchFn = vi.fn().mockResolvedValue({ok: true,+ status: 200,json: async () => ({- device_code: 'device-secret',+ device_auth_id: 'deviceauth_secret',user_code: 'ABCD-EFGH',- verification_uri: 'https://auth.openai.com/codex/device',- expires_in: 600,- interval: 5,+ interval: '5',+ expires_at: new Date(Date.now() + 600_000).toISOString(),}),})repos.insertState.mockImplementation(- async (_db: unknown, _key: Buffer, input: { state: string }) => ({+ async (_db: unknown, _key: Buffer, input: { state: string; deviceCode?: string }) => ({state: input.state,flow: 'device',intent: 'connect',@@ -384,9 +458,16 @@ describe('codex subscription OAuth broker', () => {}))const started = await startCodexDeviceConnect(deps(fetchFn), 'connect')+ expect(fetchFn.mock.calls[0]?.[0]).toBe(CODEX_OAUTH_DEVICE_USERCODE_URL)+ expect(JSON.parse(String(fetchFn.mock.calls[0]?.[1]?.body))).toEqual({+ client_id: 'app_test_client',+ })expect(started.userCode).toBe('ABCD-EFGH')+ expect(started.verificationUri).toBe(CODEX_OAUTH_DEVICE_VERIFICATION_URI)+ expect(started.intervalSeconds).toBe(5)+ expect(repos.insertState.mock.calls[0]?.[2].deviceCode).toContain('deviceauth_secret')assertNoLeak(started)- expect(JSON.stringify(started)).not.toContain('device-secret')+ expect(JSON.stringify(started)).not.toContain('deviceauth_secret')})it('exposes only bounded error classes', () => {diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex 03ba7d836..98f07e1f8 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -7853,8 +7853,7 @@ textarea.cu-input {.cu-filter-select__icon,.cu-chip,.cu-px-provider,- .cu-codex-subscription-entry,- .cu-codex-subscription-header-icon+).cu-llm-provider-icon:is([data-provider='openai'], [data-provider='codex-subscription'])img {@@ -10409,77 +10408,9 @@ textarea.cu-input {flex: 0 0 auto;}-.cu-codex-subscription-entry {- display: flex;- align-items: center;- gap: var(--cu-space-3);- padding: var(--cu-space-3) var(--cu-space-4);- border: 1px solid var(--cu-border);- border-radius: var(--cu-radius-sm);- background: var(--cu-bg-elevated);- color: inherit;- text-decoration: none;- transition:- border-color 0.15s ease,- background 0.15s ease;-}--.cu-codex-subscription-entry:hover {- border-color: var(--cu-border-strong);- background: var(--cu-bg-panel);-}--.cu-codex-subscription-entry:focus-visible {- outline: 2px solid rgba(var(--cu-focus-rgb), 0.8);- outline-offset: 2px;-}--.cu-codex-subscription-entry__brand {- display: inline-flex;- align-items: center;- gap: var(--cu-space-2);- flex: none;-}--.cu-codex-subscription-entry__brand .cu-llm-provider-icon {- width: 2rem;- height: 2rem;- flex: 0 0 2rem;-}--.cu-codex-subscription-entry__copy {- display: grid;- gap: 0.15rem;- flex: 1;- min-width: 0;-}--.cu-codex-subscription-entry__title {- color: var(--cu-text);- font-weight: 600;-}--.cu-codex-subscription-entry__subtitle {- color: var(--cu-text-soft);- font-size: 0.8125rem;- line-height: 1.45;-}--.cu-codex-subscription-entry__chevron {- flex: none;- color: var(--cu-text-muted);-}--.cu-codex-subscription-header-icon {- display: inline-flex;- align-items: center;- gap: 0.2rem;-}--.cu-codex-subscription-header-icon .cu-llm-provider-icon {- width: 1.35rem;- height: 1.35rem;- flex: 0 0 1.35rem;+.cu-agent-create-panel__header > .cu-tabs {+ margin: 0;+ padding: 0 var(--cu-space-4) var(--cu-space-3);}.cu-codex-subscription-panel {diff --git a/control-ui/components/CodexSubscriptionConnection/index.tsx b/control-ui/components/CodexSubscriptionConnection/index.tsxindex cd0eb9d43..57a1fa6fd 100644--- a/control-ui/components/CodexSubscriptionConnection/index.tsx+++ b/control-ui/components/CodexSubscriptionConnection/index.tsx@@ -5,21 +5,20 @@ import { useRouter, useSearchParams } from 'next/navigation'import { useConfirmDialog } from '@components/ConfirmDialog'import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreatePageHeader } from '@components/CreatePageHeader'+import { LlmModelsTabBar } from '@components/LlmModelsSurface/LlmModelsTabBar'import { LlmProviderIcon } from '@components/LlmProviderIcon'import { useToast } from '@components/Toast'import { Button, FormSection } from '@components/ui'import { CONTROL_ROUTES } from '@constants/routes'-import { isSilentApiError } from '@lib/api'+import { type LlmAllowedModel, getLlmModels, isSilentApiError } from '@lib/api'import {type CodexOAuthIntent,type CodexSubscriptionConnectionView,getCodexSubscriptionConnection,- isCodexBrowserOAuthUnavailableError,pollCodexDevice,readCodexOAuthQueryParam,refreshCodexSubscriptionConnection,revokeCodexSubscription,- startCodexBrowserConnect,startCodexDeviceConnect,syncCodexSubscriptionCatalog,} from '@lib/codexSubscription'@@ -47,12 +46,7 @@ function failureClass(error: unknown): string {}function CodexHeaderIcon() {- return (- <span className="cu-codex-subscription-header-icon" aria-hidden="true">- <LlmProviderIcon provider="openai" label="OpenAI" />- <LlmProviderIcon provider="codex-subscription" label="Codex subscription" />- </span>- )+ return <LlmProviderIcon provider="codex-subscription" label="Codex subscription" />}function ConnectionDetailRow({@@ -93,6 +87,14 @@ export function CodexSubscriptionConnection() {const [errorClass, setErrorClass] = useState<string | null>(null)const [browserOAuthBlocked, setBrowserOAuthBlocked] = useState(false)const [busy, setBusy] = useState(false)+ const [tabModels, setTabModels] = useState<LlmAllowedModel[]>([])++ const discoveryReviewCount = useMemo(+ () =>+ tabModels.filter(model => model.source === 'discovery' && !model.enabled && !model.stale)+ .length,+ [tabModels]+ )function applyConnection(next: CodexSubscriptionConnectionView) {setConnection(next)@@ -111,6 +113,36 @@ export function CodexSubscriptionConnection() {}}+ useEffect(() => {+ if (!enabled) {+ setTabModels([])+ return+ }+ let cancelled = false+ void getLlmModels()+ .then(result => {+ if (!cancelled) setTabModels(result.rows ?? [])+ })+ .catch(error => {+ if (!cancelled && !isSilentApiError(error)) setTabModels([])+ })+ return () => {+ cancelled = true+ }+ }, [enabled])++ function renderSectionTabs() {+ if (!enabled) return null+ return (+ <LlmModelsTabBar+ activeTab="codex-subscription"+ catalogCount={tabModels.length}+ codexEnabled+ discoveryReviewCount={discoveryReviewCount}+ />+ )+ }+useEffect(() => {let cancelled = falsevoid loadCodexSubscriptionCapability().then(capability => {@@ -180,38 +212,6 @@ export function CodexSubscriptionConnection() {[connection?.accountFingerprint])- async function startBrowser(intent: CodexOAuthIntent) {- setBusy(true)- setErrorClass(null)- setBrowserOAuthBlocked(false)- setUiStatus('connecting')- try {- const started = await startCodexBrowserConnect(intent)- window.location.assign(started.authorizeUrl)- } catch (error) {- if (isSilentApiError(error)) return- if (isCodexBrowserOAuthUnavailableError(error)) {- setBrowserOAuthBlocked(true)- setErrorClass('browser_oauth_unregistered')- setUiStatus(connection ? mapConnectionStatus(connection.status) : 'disconnected')- 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)@@ -222,6 +222,9 @@ export function CodexSubscriptionConnection() {setDeviceState(started.state)setPollMs(started.intervalSeconds * 1000)setUiStatus('device-pending')+ if (started.verificationUri) {+ window.open(started.verificationUri, '_blank', 'noopener,noreferrer')+ }} catch (error) {if (isSilentApiError(error)) returnsetUiStatus('unavailable')@@ -240,7 +243,7 @@ export function CodexSubscriptionConnection() {tone: 'danger',})if (!approved) return- await startBrowser('replace')+ await startDevice('replace')}async function handleRevoke() {@@ -297,10 +300,6 @@ export function CodexSubscriptionConnection() {}}- function backToModels() {- router.push(CONTROL_ROUTES.llmModels.root)- }-if (!capabilityReady) {return <p className="cu-subtitle">Checking Codex subscription availability.</p>}@@ -314,7 +313,7 @@ export function CodexSubscriptionConnection() {title="Codex subscription"subtitle="This provider is not enabled on the control plane."backLabel="Back to models"- onBack={backToModels}+ onBack={() => router.push(CONTROL_ROUTES.llmModels.root)}/>}>@@ -328,20 +327,20 @@ export function CodexSubscriptionConnection() {return (<CreateFlowPanelheader={- <CreatePageHeader- icon={<CodexHeaderIcon />}- title="Codex subscription"- subtitle="Connect OpenAI Codex through the OAuth broker without storing tokens in the browser."- backLabel="Back to models"- onBack={backToModels}- backDisabled={busy}- />+ <>+ <CreatePageHeader+ icon={<CodexHeaderIcon />}+ title="Codex subscription"+ subtitle="Sign in with ChatGPT to use included Codex usage. Tokens stay on the control plane."+ />+ {renderSectionTabs()}+ </>}><div className="cu-create-content cu-px-form cu-codex-subscription-panel"><FormSectiontitle="Connection"- description="Authorize OpenAI Codex once for this deployment. Tokens stay on the control plane."+ description="Sign in with ChatGPT once for this deployment. This uses your ChatGPT account, not a platform API key."><div className="cu-codex-subscription-panel__status-row"><span className="cu-settings-row__label">Status</span>@@ -372,7 +371,7 @@ export function CodexSubscriptionConnection() {role="status"data-testid="codex-device-code">- Enter device code <strong>{deviceUserCode}</strong>+ Sign in with ChatGPT using code <strong>{deviceUserCode}</strong>{deviceVerificationUri ? (<>{' '}@@ -403,9 +402,8 @@ export function CodexSubscriptionConnection() {role="status"data-testid="codex-browser-oauth-blocked">- Browser sign-in needs a deployment-registered OpenAI OAuth client for this- cluster's control-ui callback URL. Use device code to connect with the default- Codex client.+ Browser redirect sign-in is not registered for this cluster. Use Sign in with ChatGPT+ — the same account login path used by Codex, Pi, and OpenCode.</div>) : null}@@ -414,23 +412,15 @@ export function CodexSubscriptionConnection() {variant="primary"size="sm"disabled={busy}- onClick={() => void startBrowser('connect')}- >- Connect in browser- </Button>- <Button- size="sm"- variant="ghost"- disabled={busy}onClick={() => void startDevice('connect')}>- Use device code+ Sign in with ChatGPT</Button><Buttonsize="sm"variant="ghost"disabled={busy || !connection}- onClick={() => void startBrowser('reconnect')}+ onClick={() => void startDevice('reconnect')}>Reconnect</Button>diff --git a/control-ui/components/CreatePageHeader/index.tsx b/control-ui/components/CreatePageHeader/index.tsxindex a7d263e51..394251ba5 100644--- a/control-ui/components/CreatePageHeader/index.tsx+++ b/control-ui/components/CreatePageHeader/index.tsx@@ -31,14 +31,16 @@ export function CreatePageHeader({</div><div className="cu-create-top__controls">{actions ? <div className="cu-create-top__actions">{actions}</div> : null}- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm cu-create-back-btn"- onClick={onBack}- disabled={backDisabled}- >- {backLabel}- </button>+ {backLabel && onBack ? (+ <button+ type="button"+ className="cu-btn cu-btn--ghost cu-btn--sm cu-create-back-btn"+ onClick={onBack}+ disabled={backDisabled}+ >+ {backLabel}+ </button>+ ) : null}</div></div>)diff --git a/control-ui/components/CreatePageHeader/types.ts b/control-ui/components/CreatePageHeader/types.tsindex 6f17a5f30..b8e096087 100644--- a/control-ui/components/CreatePageHeader/types.ts+++ b/control-ui/components/CreatePageHeader/types.ts@@ -3,10 +3,10 @@ import type { ReactNode } from 'react'export type CreatePageHeaderProps = {actions?: ReactNodebackDisabled?: boolean- backLabel: string+ backLabel?: stringeyebrow?: ReactNodeicon: ReactNode- onBack: () => void+ onBack?: () => voidsubtitle?: ReactNodetitle: stringtitleActions?: ReactNodediff --git a/control-ui/components/LlmModelsSurface/CodexSubscriptionCatalogLink.tsx b/control-ui/components/LlmModelsSurface/CodexSubscriptionCatalogLink.tsxdeleted file mode 100644index 4f99101ad..000000000--- a/control-ui/components/LlmModelsSurface/CodexSubscriptionCatalogLink.tsx+++ /dev/null@@ -1,38 +0,0 @@-'use client'--import React from 'react'-import { LlmProviderIcon } from '@components/LlmProviderIcon'-import { IconChevronRight } from '@components/icons'-import { CONTROL_ROUTES } from '@constants/routes'--/**- * Catalog entry for the broker-backed Codex subscription provider. Shown on the- * LLM Models catalog tab only after Control API proves the feature flag.- */-export function CodexSubscriptionCatalogLink() {- return (- <a- href={CONTROL_ROUTES.llmModels.codexSubscription}- className="cu-codex-subscription-entry"- aria-label="Codex subscription"- data-testid="codex-subscription-catalog-link"- >- <span className="cu-codex-subscription-entry__brand" aria-hidden="true">- <LlmProviderIcon provider="openai" label="OpenAI" />- <LlmProviderIcon provider="codex-subscription" label="Codex subscription" />- </span>- <span className="cu-codex-subscription-entry__copy">- <span className="cu-codex-subscription-entry__title">Codex subscription</span>- <span className="cu-codex-subscription-entry__subtitle">- Connect OpenAI Codex through the OAuth broker — no API keys in the browser.- </span>- </span>- <IconChevronRight- className="cu-codex-subscription-entry__chevron"- width={18}- height={18}- aria-hidden- />- </a>- )-}diff --git a/control-ui/components/LlmModelsSurface/LlmModelsTabBar.tsx b/control-ui/components/LlmModelsSurface/LlmModelsTabBar.tsxnew file mode 100644index 000000000..6894d053f--- /dev/null+++ b/control-ui/components/LlmModelsSurface/LlmModelsTabBar.tsx@@ -0,0 +1,59 @@+'use client'++import React from 'react'+import { TabBar } from '@components/TabBar'+import type { TabBarOption } from '@components/TabBar/types'+import { CONTROL_ROUTES } from '@constants/routes'++export type LlmModelsTabValue = 'catalog' | 'discovery' | 'codex-subscription'++export type LlmModelsTabBarProps = {+ activeTab: LlmModelsTabValue+ catalogCount?: number+ codexEnabled?: boolean+ discoveryReviewCount?: number+}++/**+ * Shared LLM Models section tabs. Subscriptions are broker-backed OAuth flows,+ * not API-key catalog rows, so Codex appears as its own tab beside Catalog.+ */+export function LlmModelsTabBar({+ activeTab,+ catalogCount,+ codexEnabled = false,+ discoveryReviewCount = 0,+}: LlmModelsTabBarProps) {+ const options: TabBarOption<LlmModelsTabValue>[] = [+ {+ value: 'catalog' as const,+ href: CONTROL_ROUTES.llmModels.root,+ label:+ catalogCount !== undefined && catalogCount > 0 ? `Catalog (${catalogCount})` : 'Catalog',+ },+ {+ value: 'discovery' as const,+ href: CONTROL_ROUTES.llmModels.discovery,+ label:+ discoveryReviewCount > 0+ ? `Discovery review (${discoveryReviewCount})`+ : 'Discovery review',+ },+ ]++ if (codexEnabled) {+ options.push({+ value: 'codex-subscription' as const,+ href: CONTROL_ROUTES.llmModels.codexSubscription,+ label: 'Codex subscription',+ })+ }++ return (+ <TabBar<LlmModelsTabValue>+ activeValue={activeTab}+ ariaLabel="LLM model management"+ options={options}+ />+ )+}diff --git a/control-ui/components/LlmModelsSurface/index.tsx b/control-ui/components/LlmModelsSurface/index.tsxindex d9f15af83..a9af9b4c3 100644--- a/control-ui/components/LlmModelsSurface/index.tsx+++ b/control-ui/components/LlmModelsSurface/index.tsx@@ -9,7 +9,6 @@ import { DashboardLayout } from '@components/DashboardLayout'import { LlmDiscoveryPanel } from '@components/LlmDiscoveryPanel'import { LlmModelTable } from '@components/LlmModelTable'import { ModelReferences } from '@components/ModelReferences'-import { TabBar } from '@components/TabBar'import { useToast } from '@components/Toast'import { CONTROL_ROUTES } from '@constants/routes'import {@@ -29,7 +28,7 @@ import {import { getProviderDisplayLabel } from '@lib/llm'import { buildUnpricedKeys } from '@lib/llmModelUnpriced'import { CatalogAttentionBanner } from './CatalogAttentionBanner'-import { CodexSubscriptionCatalogLink } from './CodexSubscriptionCatalogLink'+import { LlmModelsTabBar } from './LlmModelsTabBar'import type { LlmModelsSurfaceProps, LlmModelsTab } from './types'const CONFIGMAP_DEFERRED_WARNING =@@ -157,23 +156,13 @@ function LlmModelsContent({ activeTab }: LlmModelsSurfaceProps) {[models])- const tabs = [- {- value: 'catalog' as const,- href: CONTROL_ROUTES.llmModels.root,- label: models.length > 0 ? `Catalog (${models.length})` : 'Catalog',- },- {- value: 'discovery' as const,- href: CONTROL_ROUTES.llmModels.discovery,- label:- discoveryReviewCount > 0- ? `Discovery review (${discoveryReviewCount})`- : 'Discovery review',- },- ]const navigation = (- <TabBar<LlmModelsTab> activeValue={activeTab} ariaLabel="LLM model management" options={tabs} />+ <LlmModelsTabBar+ activeTab={activeTab}+ catalogCount={models.length}+ codexEnabled={codexEnabled}+ discoveryReviewCount={discoveryReviewCount}+ />)return (@@ -186,7 +175,6 @@ function LlmModelsContent({ activeTab }: LlmModelsSurfaceProps) {{activeTab === 'catalog' ? (<CatalogAttentionBanner refreshSignal={attentionRefreshKey} />) : null}- {activeTab === 'catalog' && codexEnabled ? <CodexSubscriptionCatalogLink /> : null}{activeTab === 'catalog' ? (<LlmModelTableitems={models}diff --git a/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx b/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsxindex fbcb2c871..6823280c7 100644--- a/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx+++ b/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx@@ -118,7 +118,7 @@ describe('CodexSubscriptionConnection', () => {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()+ expect(screen.queryByRole('button', { name: 'Sign in with ChatGPT' })).not.toBeInTheDocument()})it('renders connected status without tokens or account ids', async () => {@@ -138,28 +138,35 @@ describe('CodexSubscriptionConnection', () => {expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent(label)})- it('starts a browser connect in the same tab without rendering secrets', async () => {- vi.mocked(startCodexBrowserConnect).mockResolvedValue({- authorizeUrl: 'https://auth.openai.com/oauth/authorize?state=abc',- state: 'abc',+ it('starts Sign in with ChatGPT through the device flow without rendering secrets', async () => {+ const openMock = vi.fn()+ vi.stubGlobal('open', openMock)+ vi.mocked(startCodexDeviceConnect).mockResolvedValue({+ userCode: 'ABCD-EFGH',+ verificationUri: 'https://auth.openai.com/codex/device',+ intervalSeconds: 5,+ state: 'dev',intent: 'connect',- expiresAt: '2026-08-20T00:01:00.000Z',})renderSurface()- fireEvent.click(await screen.findByRole('button', { name: 'Connect in browser' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Sign in with ChatGPT' }))await waitFor(() => {- expect(startCodexBrowserConnect).toHaveBeenCalledWith('connect')+ expect(startCodexDeviceConnect).toHaveBeenCalledWith('connect')})- expect(assignMock).toHaveBeenCalledWith('https://auth.openai.com/oauth/authorize?state=abc')+ expect(openMock).toHaveBeenCalledWith(+ 'https://auth.openai.com/codex/device',+ '_blank',+ 'noopener,noreferrer'+ )+ expect(assignMock).not.toHaveBeenCalled()expect(document.body.textContent).not.toMatch(/sk-|deviceCode|accessToken/i)})- it('shows a device-code fallback banner when browser OAuth is unregistered', async () => {- vi.mocked(startCodexBrowserConnect).mockRejectedValue(browserOAuthUnavailableError())+ it('shows the ChatGPT sign-in banner when a leftover browser callback is unregistered', async () => {+ searchParams = new URLSearchParams('codex_oauth=browser_oauth_unregistered')renderSurface()- fireEvent.click(await screen.findByRole('button', { name: 'Connect in browser' }))expect(await screen.findByTestId('codex-browser-oauth-blocked')).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Use device code' })).toBeVisible()+ expect(screen.getByRole('button', { name: 'Sign in with ChatGPT' })).toBeVisible()expect(assignMock).not.toHaveBeenCalled()})@@ -181,7 +188,7 @@ describe('CodexSubscriptionConnection', () => {intent: 'connect',})renderSurface()- fireEvent.click(await screen.findByRole('button', { name: 'Use device code' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Sign in with ChatGPT' }))expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent('Device code pending')@@ -190,11 +197,12 @@ describe('CodexSubscriptionConnection', () => {})it('confirms replacement impact before starting a replace flow', async () => {- vi.mocked(startCodexBrowserConnect).mockResolvedValue({- authorizeUrl: 'https://auth.openai.com/oauth/authorize?state=rep',+ vi.mocked(startCodexDeviceConnect).mockResolvedValue({+ userCode: 'REPL-CODE',+ verificationUri: 'https://auth.openai.com/codex/device',+ intervalSeconds: 5,state: 'rep',intent: 'replace',- expiresAt: '2026-08-20T00:01:00.000Z',})renderSurface()fireEvent.click(await screen.findByRole('button', { name: 'Replace account' }))@@ -203,7 +211,7 @@ describe('CodexSubscriptionConnection', () => {})expect(String(confirmMock.mock.calls[0]?.[0]?.message)).toMatch(/lose the current grant/i)await waitFor(() => {- expect(startCodexBrowserConnect).toHaveBeenCalledWith('replace')+ expect(startCodexDeviceConnect).toHaveBeenCalledWith('replace')})})diff --git a/control-ui/components/__tests__/LlmModelsSurface.test.tsx b/control-ui/components/__tests__/LlmModelsSurface.test.tsxindex d4e5190b3..0a23e4be7 100644--- a/control-ui/components/__tests__/LlmModelsSurface.test.tsx+++ b/control-ui/components/__tests__/LlmModelsSurface.test.tsx@@ -23,7 +23,12 @@ vi.mock('@components/LlmDiscoveryPanel', () => ({),}))vi.mock('@components/LlmModelTable', () => ({- LlmModelTable: () => <div>Model catalog</div>,+ LlmModelTable: ({ navigation }: { navigation?: ReactNode }) => (+ <div>+ {navigation}+ Model catalog+ </div>+ ),}))vi.mock('@lib/api', async importOriginal => {const actual = await importOriginal<typeof import('@lib/api')>()@@ -75,7 +80,7 @@ describe('LlmModelsSurface', () => {expect(await screen.findByText('Discovery models: 1')).toBeInTheDocument()expect(getUnpricedModels).not.toHaveBeenCalled()- expect(screen.queryByRole('link', { name: 'Codex subscription' })).not.toBeInTheDocument()+ expect(screen.queryByRole('tab', { name: 'Codex subscription' })).not.toBeInTheDocument()})it('hides the Codex subscription deep link when Control API capability is absent', async () => {@@ -86,10 +91,10 @@ describe('LlmModelsSurface', () => {)expect(await screen.findByText('Model catalog')).toBeInTheDocument()- expect(screen.queryByRole('link', { name: 'Codex subscription' })).not.toBeInTheDocument()+ expect(screen.queryByRole('tab', { name: 'Codex subscription' })).not.toBeInTheDocument()})- it('shows the Codex subscription deep link only after Control API proves the flag', async () => {+ it('shows the Codex subscription tab only after Control API proves the flag', async () => {vi.mocked(loadCodexSubscriptionCapability).mockResolvedValue({ enabled: true })render(<ToastProvider>@@ -97,8 +102,8 @@ describe('LlmModelsSurface', () => {</ToastProvider>)- const link = await screen.findByRole('link', { name: 'Codex subscription' })- expect(link).toHaveAttribute('href', '/llm-models/providers/codex-subscription')- expect(screen.getByTestId('codex-subscription-catalog-link')).toBeInTheDocument()+ const tab = await screen.findByRole('tab', { name: 'Codex subscription' })+ expect(tab).toHaveAttribute('href', '/llm-models/providers/codex-subscription')+ expect(screen.queryByTestId('codex-subscription-catalog-link')).not.toBeInTheDocument()})})diff --git a/docs/architecture/codex-subscription-transport-contract.md b/docs/architecture/codex-subscription-transport-contract.mdindex 52961c1d3..a013a4c52 100644--- a/docs/architecture/codex-subscription-transport-contract.md+++ b/docs/architecture/codex-subscription-transport-contract.md@@ -19,7 +19,11 @@ Exact HTTPS origins (no caller-supplied URL or header):- OAuth authorize: `https://auth.openai.com/oauth/authorize`- OAuth token: `https://auth.openai.com/oauth/token`-- OAuth device: `https://auth.openai.com/api/accounts/deviceauth`+- OAuth device prefix: `https://auth.openai.com/api/accounts/deviceauth`+- OAuth device usercode: `https://auth.openai.com/api/accounts/deviceauth/usercode`+- OAuth device token poll: `https://auth.openai.com/api/accounts/deviceauth/token`+- OAuth device callback: `https://auth.openai.com/deviceauth/callback`+- OAuth device verification: `https://auth.openai.com/codex/device`- OAuth revoke: `https://auth.openai.com/oauth/revoke`- Catalog: `https://chatgpt.com/backend-api/codex/models`- Completions: `https://chatgpt.com/backend-api/codex/responses`diff --git a/tests/e2e/fixtures/codex-subscription/sanitized-upstream-contract.json b/tests/e2e/fixtures/codex-subscription/sanitized-upstream-contract.jsonindex dbf765b9b..b31df1f18 100644--- a/tests/e2e/fixtures/codex-subscription/sanitized-upstream-contract.json+++ b/tests/e2e/fixtures/codex-subscription/sanitized-upstream-contract.json@@ -18,6 +18,10 @@"oauthAuthorize": "https://auth.openai.com/oauth/authorize","oauthToken": "https://auth.openai.com/oauth/token","oauthDevice": "https://auth.openai.com/api/accounts/deviceauth",+ "oauthDeviceUsercode": "https://auth.openai.com/api/accounts/deviceauth/usercode",+ "oauthDeviceToken": "https://auth.openai.com/api/accounts/deviceauth/token",+ "oauthDeviceCallback": "https://auth.openai.com/deviceauth/callback",+ "oauthDeviceVerification": "https://auth.openai.com/codex/device","oauthRevoke": "https://auth.openai.com/oauth/revoke","catalog": "https://chatgpt.com/backend-api/codex/models","completions": "https://chatgpt.com/backend-api/codex/responses"diff --git a/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs b/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjsindex 86ac07ded..8288d7e50 100755--- a/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs+++ b/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs@@ -60,16 +60,27 @@ const server = createServer({ cert, key }, async (request, response) => {response.writeHead(302, { location: '/oauth/consent-complete' })return response.end()}- if (request.method === 'POST' && url.pathname === '/api/accounts/deviceauth') {+ if (request.method === 'POST' && url.pathname === '/api/accounts/deviceauth/usercode') {counters.consent += 1- const deviceCode = `dev-${randomBytes(6).toString('hex')}`- devices.set(deviceCode, { approved: true })+ const deviceAuthId = `deviceauth_${randomBytes(6).toString('hex')}`+ devices.set(deviceAuthId, { approved: true, userCode: 'TEST-CODE' })return json(response, 200, {- device_code: deviceCode,+ device_auth_id: deviceAuthId,user_code: 'TEST-CODE',- verification_uri: 'https://codex-test-upstream.local/device',- expires_in: 300,- interval: 1,+ interval: '1',+ expires_at: new Date(Date.now() + 300_000).toISOString(),+ })+ }+ if (request.method === 'POST' && url.pathname === '/api/accounts/deviceauth/token') {+ const body = JSON.parse((await readBody(request)) || '{}')+ const pending = devices.get(body.device_auth_id)+ if (!pending || pending.userCode !== body.user_code) {+ return json(response, 403, { error: { code: 'deviceauth_authorization_pending' } })+ }+ return json(response, 200, {+ authorization_code: `authz-${randomBytes(6).toString('hex')}`,+ code_challenge: 'test-challenge',+ code_verifier: 'test-verifier',})}if (request.method === 'POST' && url.pathname === '/oauth/token') {diff --git a/tests/e2e/fixtures/package-lock.json b/tests/e2e/fixtures/package-lock.jsonindex 44962f81c..95cd2e2e5 100644--- a/tests/e2e/fixtures/package-lock.json+++ b/tests/e2e/fixtures/package-lock.json@@ -1,12 +1,12 @@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.64",+ "version": "1.0.65","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@clerum/e2e-test-fixtures",- "version": "1.0.64",+ "version": "1.0.65","dependencies": {"@kubernetes/client-node": "^1.0.0"},diff --git a/tests/e2e/fixtures/package.json b/tests/e2e/fixtures/package.jsonindex 64d309861..ca73415bc 100644--- a/tests/e2e/fixtures/package.json+++ b/tests/e2e/fixtures/package.json@@ -1,6 +1,6 @@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.64",+ "version": "1.0.65","description": "E2E test fixtures and utilities for Clerum testing","type": "module","main": "index.ts",diff --git a/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.tsindex 7dd3273d1..c398f46d5 100644--- a/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts+++ b/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts@@ -16,7 +16,7 @@ test.describe('Codex subscription admission', () => {await page.goto('/llm-models/providers/codex-subscription')await expect(page.getByLabel('Username or email')).toBeVisible({ timeout: 20_000 })await expect(page.getByTestId('codex-connection-status')).toHaveCount(0)- await expect(page.getByRole('button', { name: 'Connect in browser' })).toHaveCount(0)+ await expect(page.getByRole('button', { name: 'Sign in with ChatGPT' })).toHaveCount(0)})test('catalog surface exposes Codex subscription only after capability is proven', async ({@@ -42,6 +42,6 @@ test.describe('Codex subscription admission', () => {const body = (await capabilityResponse.json()) as { status?: string }expect(body.status).toBe('disconnected')- await expect(page.getByRole('link', { name: 'Codex subscription' })).toBeVisible()+ await expect(page.getByRole('tab', { name: 'Codex subscription' })).toBeVisible()})})diff --git a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.tsindex cf0e796f8..9c5a21646 100644--- a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts+++ b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts@@ -27,7 +27,7 @@ test.describe('Codex subscription connection', () => {response.url().includes('/api/v1/admin/llm/providers/codex-subscription/connection') &&response.request().method() === 'GET')- await page.getByRole('link', { name: 'Codex subscription' }).click()+ await page.getByRole('tab', { name: 'Codex subscription' }).click()const response = await connectionexpect(response.ok(), `connection read must succeed, got ${response.status()}`).toBe(true)const body = (await response.json()) as { status?: string }@@ -35,32 +35,32 @@ test.describe('Codex subscription connection', () => {await expect(page).toHaveURL(/\/llm-models\/providers\/codex-subscription/)await expect(page.getByRole('heading', { name: 'Codex subscription' })).toBeVisible()await expect(page.getByTestId('codex-connection-status')).toContainText(/Disconnected/)- await expect(page.getByRole('button', { name: 'Connect in browser' })).toBeVisible()- await expect(page.getByRole('button', { name: 'Use device code' })).toBeVisible()+ await expect(page.getByRole('button', { name: 'Sign in with ChatGPT' })).toBeVisible()await expect(page.getByText(/sk-|access token|account id/i)).toHaveCount(0)})- test('browser connect fails loud with the default CLI client and keeps device code available', async ({+ test('Sign in with ChatGPT starts the ChatGPT device login and stays on control-ui', async ({page,}) => {await page.goto('/')await loginControlUiVisible(page)await page.getByRole('link', { name: 'LLM Models' }).click()- await page.getByRole('link', { name: 'Codex subscription' }).click()+ await page.getByRole('tab', { name: 'Codex subscription' }).click()await expect(page).toHaveURL(/\/llm-models\/providers\/codex-subscription/)- const browserStart = page.waitForResponse(+ const deviceStart = page.waitForResponse(response =>- response.url().includes('/api/v1/admin/llm/providers/codex-subscription/browser/start') &&+ response.url().includes('/api/v1/admin/llm/providers/codex-subscription/device/start') &&response.request().method() === 'POST')- await page.getByRole('button', { name: 'Connect in browser' }).click()- const response = await browserStart- expect(response.status(), 'default CLI client must not open browser OAuth').toBe(400)- const body = (await response.json()) as { error?: string }- expect(body.error).toBe('browser_oauth_unregistered')- await expect(page.getByTestId('codex-browser-oauth-blocked')).toBeVisible()- await expect(page.getByRole('button', { name: 'Use device code' })).toBeVisible()- await expect(page).not.toHaveURL(/auth\.openai\.com/)+ await page.getByRole('button', { name: 'Sign in with ChatGPT' }).click()+ const response = await deviceStart+ expect(response.ok(), `device start must succeed, got ${response.status()}`).toBe(true)+ const body = (await response.json()) as { userCode?: string; verificationUri?: string }+ expect(body.userCode, 'ChatGPT sign-in must return a user code').toEqual(expect.any(String))+ expect(body.verificationUri).toMatch(/^https:\/\/auth\.openai\.com\/codex\/device/)+ await expect(page.getByTestId('codex-device-code')).toContainText(String(body.userCode))+ await expect(page).toHaveURL(/\/llm-models\/providers\/codex-subscription/)+ await expect(page).not.toHaveURL(/oauth\/authorize/)})})diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.jsonindex 7dfdb1655..d42a06d2f 100644--- a/tests/e2e/playwright/package-lock.json+++ b/tests/e2e/playwright/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-playwright-tests",- "version": "0.1.26",+ "version": "0.1.27","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-playwright-tests",- "version": "0.1.26",+ "version": "0.1.27","devDependencies": {"@playwright/test": "^1.50.0","@types/node": "^22.0.0"diff --git a/tests/e2e/playwright/package.json b/tests/e2e/playwright/package.jsonindex cf4da438d..54f627fc8 100644--- a/tests/e2e/playwright/package.json+++ b/tests/e2e/playwright/package.json@@ -1,6 +1,6 @@{"name": "clerum-playwright-tests",- "version": "0.1.26",+ "version": "0.1.27","private": true,"description": "Playwright E2E tests for Control UI and Desktop App","scripts": {