Skip to content

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

TypeScript

feat(codex): open sync on create and auto-fetch the catalog

Alfredo Lopez3e7b12d16c22
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 5af411a25..bfc68805f 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.520",
+ "version": "0.1.521",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.520",
+ "version": "0.1.521",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index 9c3a25f81..9b045fb78 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.520",
+ "version": "0.1.521",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/admin/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.ts
index 8c52f74fe..145653649 100644
--- a/control-api/src/routes/admin/codexSubscription.ts
+++ b/control-api/src/routes/admin/codexSubscription.ts
@@ -13,7 +13,6 @@ import {
listOfferedCodexModelsForAssignment,
pickCodexGrantModel,
setCodexCatalogModelEnabled,
- syncCodexSubscriptionCatalog,
} from '../../services/codexSubscriptionCatalog.js'
import {
CODEX_UNASSIGNED_CONNECTION_KEY,
@@ -23,18 +22,17 @@ import {
generateCodexConnectionKey,
getSafeCodexSubscriptionConnection,
listSafeCodexSubscriptionConnections,
- loadCodexSubscriptionSecrets,
normalizeCodexConnectionKey,
updateCodexSubscriptionConnectionMetadata,
} from '../../services/codexSubscriptionConnection.js'
import {
type CodexOAuthDeps,
CodexSubscriptionOAuthError,
- ensureFreshCodexAccessToken,
getCodexSubscriptionConnection,
pollCodexDevice,
refreshCodexSubscriptionConnection,
revokeCodexSubscription,
+ runCodexCatalogSync,
startCodexBrowserConnect,
startCodexDeviceConnect,
} from '../../services/codexSubscriptionOAuth.js'
@@ -408,11 +406,20 @@ export function createAdminCodexSubscriptionRouter(
const devicePollHandler = asyncHandler(async (req, res) => {
try {
const state = typeof req.query.state === 'string' ? req.query.state : ''
- const result = await pollCodexDevice(
- oauthDeps(req, resolveBrowserRedirectUri(req), keyFromReq(req)),
- state
- )
- if (result.status === 'connected' && (await publishRuntimeAllowlistOrFail(res))) return
+ const connectionKey = keyFromReq(req)
+ const deps = oauthDeps(req, resolveBrowserRedirectUri(req), connectionKey)
+ let result = await pollCodexDevice(deps, state)
+ if (result.status === 'connected') {
+ const sync = await runCodexCatalogSync(
+ deps,
+ result.connection.connectionKey,
+ catalogTransport
+ )
+ if (sync.connection) {
+ result = { ...result, connection: sync.connection }
+ }
+ if (await publishRuntimeAllowlistOrFail(res)) return
+ }
res.status(200).json(result)
} catch (err) {
sendOAuthError(res, err)
@@ -437,32 +444,16 @@ export function createAdminCodexSubscriptionRouter(
res.status(404).json({ error: 'disabled' })
return
}
- const db = dbClient()
const connectionKey = keyFromReq(req)
- await ensureFreshCodexAccessToken(
- oauthDeps(req, resolveBrowserRedirectUri(req), connectionKey)
- )
- const secrets = await loadCodexSubscriptionSecrets(
- db,
- deriveOAuthEncryptionKey(config.oauthEncryptionKey),
- connectionKey
- )
- if (!secrets?.accessToken) {
- res.status(404).json({ error: 'no_grant' })
- return
- }
- const synced = await syncCodexSubscriptionCatalog(db, catalogTransport, secrets.accessToken, {
+ const synced = await runCodexCatalogSync(
+ oauthDeps(req, resolveBrowserRedirectUri(req), connectionKey),
connectionKey,
- })
- if (!synced.connection) {
- res.status(409).json({ error: 'stale_revision' })
- return
- }
- if (synced.outcome !== 'ready') {
+ catalogTransport
+ )
+ if (synced.ok) {
if (await publishRuntimeAllowlistOrFail(res)) return
- res.status(503).json({
- error: 'catalog_sync_failed',
- outcome: synced.outcome,
+ res.status(200).json({
+ outcome: synced.catalogStatus,
added: synced.added,
refreshed: synced.refreshed,
staled: synced.staled,
@@ -470,13 +461,36 @@ export function createAdminCodexSubscriptionRouter(
})
return
}
+ if (synced.reason === 'no_grant') {
+ res.status(404).json({ error: 'no_grant' })
+ return
+ }
+ if (synced.reason === 'stale_revision') {
+ res.status(409).json({ error: 'stale_revision' })
+ return
+ }
+ if (synced.reason === 'disabled') {
+ res.status(404).json({ error: 'disabled' })
+ return
+ }
+ if (synced.reason !== 'catalog_sync_failed' && synced.reason !== 'unavailable') {
+ sendOAuthError(
+ res,
+ new CodexSubscriptionOAuthError(
+ synced.reason as ConstructorParameters<typeof CodexSubscriptionOAuthError>[0],
+ synced.reason
+ )
+ )
+ return
+ }
if (await publishRuntimeAllowlistOrFail(res)) return
- res.status(200).json({
- outcome: synced.outcome,
- added: synced.added,
- refreshed: synced.refreshed,
- staled: synced.staled,
- connection: synced.connection,
+ res.status(503).json({
+ error: 'catalog_sync_failed',
+ outcome: synced.catalogStatus === 'never_synced' ? 'unavailable' : synced.catalogStatus,
+ added: synced.added ?? 0,
+ refreshed: synced.refreshed ?? 0,
+ staled: synced.staled ?? 0,
+ connection: synced.connection ?? null,
})
} catch (err) {
sendOAuthError(res, err)
diff --git a/control-api/src/routes/auth/codexSubscription.ts b/control-api/src/routes/auth/codexSubscription.ts
index d37eeb4a3..2f974bca5 100644
--- a/control-api/src/routes/auth/codexSubscription.ts
+++ b/control-api/src/routes/auth/codexSubscription.ts
@@ -6,10 +6,15 @@ import type { K8sGateway } from '../../k8s.js'
import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'
import { rootLogger } from '../../observability/logger.js'
import { llmAllowlistConfigMapWriteFailuresTotal } from '../../observability/metrics.js'
+import {
+ type CodexCatalogTransport,
+ createCodexCatalogTransportFromEnv,
+} from '../../services/codexSubscriptionCatalog.js'
import {
type CodexOAuthDeps,
CodexSubscriptionOAuthError,
handleCodexBrowserCallback,
+ runCodexCatalogSync,
} from '../../services/codexSubscriptionOAuth.js'
import {
buildCodexBrowserRedirectUri,
@@ -52,7 +57,10 @@ function redirectToCodexSurface(
res.redirect(303, buildCodexBrowserReturnLocation(outcome))
}
-export function createAuthCodexSubscriptionRouter(gateway?: K8sGateway): Router {
+export function createAuthCodexSubscriptionRouter(
+ gateway?: K8sGateway,
+ catalogTransport: CodexCatalogTransport = createCodexCatalogTransportFromEnv()
+): Router {
const router = Router()
router.get(
@@ -62,7 +70,12 @@ export function createAuthCodexSubscriptionRouter(gateway?: K8sGateway): Router
const code = typeof req.query.code === 'string' ? req.query.code : ''
const state = typeof req.query.state === 'string' ? req.query.state : ''
try {
- await handleCodexBrowserCallback(oauthDeps(req), { code, state })
+ const connection = await handleCodexBrowserCallback(oauthDeps(req), { code, state })
+ await runCodexCatalogSync(
+ { ...oauthDeps(req), connectionKey: connection.connectionKey },
+ connection.connectionKey,
+ catalogTransport
+ )
try {
await publishAllowedModelsConfigMapAfterGrantChange(gateway?.llmAllowedModelsConfigMap())
} catch (err) {
diff --git a/control-api/src/services/codexSubscriptionOAuth.ts b/control-api/src/services/codexSubscriptionOAuth.ts
index fcf2587b5..f92bc9f56 100644
--- a/control-api/src/services/codexSubscriptionOAuth.ts
+++ b/control-api/src/services/codexSubscriptionOAuth.ts
@@ -2,7 +2,12 @@ import { createHash, randomBytes } from 'node:crypto'
import type { DbClient } from '../db.js'
import { rootLogger } from '../observability/logger.js'
import { chatgptAccountIdFromJwt } from './chatgptAccountId.js'
-import { rebuildLiveCodexUnionAllowlist } from './codexSubscriptionCatalog.js'
+import {
+ type CodexCatalogOutcome,
+ type CodexCatalogTransport,
+ rebuildLiveCodexUnionAllowlist,
+ syncCodexSubscriptionCatalog,
+} from './codexSubscriptionCatalog.js'
import {
CodexSubscriptionFingerprintConflictError,
type CodexSubscriptionSafeConnection,
@@ -142,6 +147,26 @@ export type CodexDevicePollResult =
| { status: 'expired' }
| { status: 'denied' }
+/** Fail-soft catalog fetch after a grant is persisted. Never throws. */
+export type CodexCatalogSyncResult =
+ | {
+ ok: true
+ catalogStatus: 'ready'
+ added: number
+ refreshed: number
+ staled: number
+ connection: CodexSubscriptionSafeConnection
+ }
+ | {
+ ok: false
+ catalogStatus: Extract<CodexCatalogOutcome, 'auth-rejected' | 'unavailable'> | 'never_synced'
+ reason: string
+ added?: number
+ refreshed?: number
+ staled?: number
+ connection?: CodexSubscriptionSafeConnection | null
+ }
+
function requireEnabled(deps: CodexOAuthDeps): void {
if (!deps.enabled) {
throw new CodexSubscriptionOAuthError('disabled', 'Codex subscription is disabled')
@@ -559,6 +584,63 @@ export async function ensureFreshCodexAccessToken(deps: CodexOAuthDeps): Promise
}
}
+/**
+ * Fail-soft first catalog fetch after OAuth persist. Never throws: a connected
+ * grant stays connected when ChatGPT catalog is unavailable.
+ */
+export async function runCodexCatalogSync(
+ deps: CodexOAuthDeps,
+ connectionKey: string,
+ transport: CodexCatalogTransport
+): Promise<CodexCatalogSyncResult> {
+ const key = normalizeCodexConnectionKey(connectionKey)
+ try {
+ const keyed = { ...deps, connectionKey: key }
+ await ensureFreshCodexAccessToken(keyed)
+ const secrets = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey, key)
+ if (!secrets?.accessToken) {
+ return { ok: false, catalogStatus: 'never_synced', reason: 'no_grant' }
+ }
+ const synced = await syncCodexSubscriptionCatalog(deps.db, transport, secrets.accessToken, {
+ connectionKey: key,
+ })
+ if (!synced.connection) {
+ return { ok: false, catalogStatus: 'never_synced', reason: 'stale_revision' }
+ }
+ if (synced.outcome !== 'ready') {
+ return {
+ ok: false,
+ catalogStatus: synced.outcome,
+ reason: 'catalog_sync_failed',
+ added: synced.added,
+ refreshed: synced.refreshed,
+ staled: synced.staled,
+ connection: synced.connection,
+ }
+ }
+ return {
+ ok: true,
+ catalogStatus: 'ready',
+ added: synced.added,
+ refreshed: synced.refreshed,
+ staled: synced.staled,
+ connection: synced.connection,
+ }
+ } catch (err) {
+ log.warn(
+ { err, event: 'codex_catalog_auto_sync_failed', connectionKey: key },
+ 'automatic catalog sync after grant failed'
+ )
+ const reason =
+ err instanceof CodexSubscriptionOAuthError
+ ? err.code
+ : err instanceof Error
+ ? err.message
+ : 'catalog_sync_failed'
+ return { ok: false, catalogStatus: 'never_synced', reason }
+ }
+}
+
async function exchangeAuthorizationCode(
deps: CodexOAuthDeps,
code: string,
diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.ts
index aab62a0d2..d9a8a9672 100644
--- a/control-api/test/routes.admin.codexSubscription.test.ts
+++ b/control-api/test/routes.admin.codexSubscription.test.ts
@@ -12,6 +12,7 @@ const oauth = vi.hoisted(() => ({
refresh: vi.fn(),
revoke: vi.fn(),
ensureFresh: vi.fn(),
+ runCatalogSync: vi.fn(),
}))
const catalog = vi.hoisted(() => ({
@@ -31,6 +32,7 @@ vi.mock('../src/services/codexSubscriptionOAuth.js', async () => {
refreshCodexSubscriptionConnection: oauth.refresh,
revokeCodexSubscription: oauth.revoke,
ensureFreshCodexAccessToken: oauth.ensureFresh,
+ runCodexCatalogSync: oauth.runCatalogSync,
}
})
@@ -146,6 +148,14 @@ describe('admin Codex subscription routes', () => {
catalog.listOffered.mockReset()
catalog.listOffered.mockResolvedValue(['gpt-5.1'])
oauth.ensureFresh.mockResolvedValue(undefined)
+ oauth.runCatalogSync.mockResolvedValue({
+ ok: true,
+ catalogStatus: 'ready',
+ added: 0,
+ refreshed: 0,
+ staled: 0,
+ connection: { connectionKey: 'codex-aaa', status: 'connected', catalogStatus: 'ready' },
+ })
vi.mocked(pool.query).mockReset()
})
@@ -336,9 +346,9 @@ describe('admin Codex subscription routes', () => {
it('publishes the runtime ConfigMap after a catalog sync', async () => {
const materialize = vi.fn(async () => {})
- catalog.loadSecrets.mockResolvedValue({ accessToken: 'access-secret' })
- catalog.sync.mockResolvedValue({
- outcome: 'ready',
+ oauth.runCatalogSync.mockResolvedValue({
+ ok: true,
+ catalogStatus: 'ready',
added: 8,
refreshed: 0,
staled: 0,
@@ -349,22 +359,23 @@ describe('admin Codex subscription routes', () => {
)
expect(res.status).toBe(200)
expect(res.body.added).toBe(8)
- expect(oauth.ensureFresh).toHaveBeenCalledTimes(1)
+ expect(oauth.runCatalogSync).toHaveBeenCalledTimes(1)
expect(materialize).toHaveBeenCalledTimes(1)
assertNoLeak(res.body)
})
it('does not publish the runtime ConfigMap when catalog sync cannot refresh the access token', async () => {
const materialize = vi.fn(async () => {})
- oauth.ensureFresh.mockRejectedValueOnce(
- new CodexSubscriptionOAuthError('reauth_required', 'refresh token rejected')
- )
+ oauth.runCatalogSync.mockResolvedValue({
+ ok: false,
+ catalogStatus: 'never_synced',
+ reason: 'reauth_required',
+ })
const res = await request(makeAuthedApp(makeGateway(materialize))).post(
'/admin/llm/providers/codex-subscription/connections/codex-aaa/catalog/sync'
)
expect(res.status).toBe(400)
expect(res.body.error).toBe('reauth_required')
- expect(catalog.sync).not.toHaveBeenCalled()
expect(materialize).not.toHaveBeenCalled()
assertNoLeak(res.body)
})
@@ -373,9 +384,9 @@ describe('admin Codex subscription routes', () => {
const materialize = vi.fn(async () => {
throw new Error('apiserver down')
})
- catalog.loadSecrets.mockResolvedValue({ accessToken: 'access-secret' })
- catalog.sync.mockResolvedValue({
- outcome: 'ready',
+ oauth.runCatalogSync.mockResolvedValue({
+ ok: true,
+ catalogStatus: 'ready',
added: 8,
refreshed: 0,
staled: 0,
@@ -426,9 +437,10 @@ describe('admin Codex subscription routes', () => {
it('publishes the runtime ConfigMap after a recorded non-ready catalog sync', async () => {
const materialize = vi.fn(async () => {})
- catalog.loadSecrets.mockResolvedValue({ accessToken: 'access-secret' })
- catalog.sync.mockResolvedValue({
- outcome: 'auth-rejected',
+ oauth.runCatalogSync.mockResolvedValue({
+ ok: false,
+ catalogStatus: 'auth-rejected',
+ reason: 'catalog_sync_failed',
added: 0,
refreshed: 0,
staled: 0,
@@ -453,9 +465,10 @@ describe('admin Codex subscription routes', () => {
const materialize = vi.fn(async () => {
throw new Error('apiserver down')
})
- catalog.loadSecrets.mockResolvedValue({ accessToken: 'access-secret' })
- catalog.sync.mockResolvedValue({
- outcome: 'unavailable',
+ oauth.runCatalogSync.mockResolvedValue({
+ ok: false,
+ catalogStatus: 'unavailable',
+ reason: 'catalog_sync_failed',
added: 0,
refreshed: 0,
staled: 0,
@@ -511,12 +524,63 @@ describe('admin Codex subscription routes', () => {
it('publishes the runtime ConfigMap after a connected device poll', async () => {
const materialize = vi.fn(async () => {})
- oauth.pollDevice.mockResolvedValue({ status: 'connected', connectionKey: 'codex-aaa' })
+ const callOrder: string[] = []
+ oauth.pollDevice.mockResolvedValue({
+ status: 'connected',
+ connection: {
+ connectionKey: 'codex-aaa',
+ status: 'connected',
+ catalogStatus: 'never_synced',
+ },
+ })
+ oauth.runCatalogSync.mockImplementation(async () => {
+ callOrder.push('sync')
+ return {
+ ok: true,
+ catalogStatus: 'ready',
+ added: 2,
+ refreshed: 0,
+ staled: 0,
+ connection: { connectionKey: 'codex-aaa', status: 'connected', catalogStatus: 'ready' },
+ }
+ })
+ const res = await request(
+ makeAuthedApp({
+ ...makeGateway(async () => {
+ callOrder.push('publish')
+ }),
+ })
+ ).get('/admin/llm/providers/codex-subscription/connections/codex-aaa/device/poll')
+ expect(res.status).toBe(200)
+ expect(res.body.status).toBe('connected')
+ expect(res.body.connection.catalogStatus).toBe('ready')
+ expect(oauth.runCatalogSync).toHaveBeenCalledTimes(1)
+ expect(callOrder).toEqual(['sync', 'publish'])
+ assertNoLeak(res.body)
+ })
+
+ it('keeps a connected device poll at 200 when automatic catalog sync fails', async () => {
+ const materialize = vi.fn(async () => {})
+ oauth.pollDevice.mockResolvedValue({
+ status: 'connected',
+ connection: {
+ connectionKey: 'codex-aaa',
+ status: 'connected',
+ catalogStatus: 'never_synced',
+ },
+ })
+ oauth.runCatalogSync.mockResolvedValue({
+ ok: false,
+ catalogStatus: 'unavailable',
+ reason: 'catalog_sync_failed',
+ connection: { connectionKey: 'codex-aaa', status: 'connected', catalogStatus: 'unavailable' },
+ })
const res = await request(makeAuthedApp(makeGateway(materialize))).get(
'/admin/llm/providers/codex-subscription/connections/codex-aaa/device/poll'
)
expect(res.status).toBe(200)
expect(res.body.status).toBe('connected')
+ expect(res.body.connection.catalogStatus).toBe('unavailable')
expect(materialize).toHaveBeenCalledTimes(1)
assertNoLeak(res.body)
})
@@ -525,7 +589,10 @@ describe('admin Codex subscription routes', () => {
const materialize = vi.fn(async () => {
throw new Error('apiserver down')
})
- oauth.pollDevice.mockResolvedValue({ status: 'connected', connectionKey: 'codex-aaa' })
+ oauth.pollDevice.mockResolvedValue({
+ status: 'connected',
+ connection: { connectionKey: 'codex-aaa', status: 'connected', catalogStatus: 'ready' },
+ })
const res = await request(makeAuthedApp(makeGateway(materialize))).get(
'/admin/llm/providers/codex-subscription/device/poll'
)
@@ -543,6 +610,7 @@ describe('admin Codex subscription routes', () => {
)
expect(res.status).toBe(200)
expect(materialize).not.toHaveBeenCalled()
+ expect(oauth.runCatalogSync).not.toHaveBeenCalled()
assertNoLeak(res.body)
})
diff --git a/control-api/test/routes.auth.codexSubscriptionCallback.test.ts b/control-api/test/routes.auth.codexSubscriptionCallback.test.ts
index ac9262b49..fd3627a85 100644
--- a/control-api/test/routes.auth.codexSubscriptionCallback.test.ts
+++ b/control-api/test/routes.auth.codexSubscriptionCallback.test.ts
@@ -5,6 +5,7 @@ import { CodexSubscriptionOAuthError } from '../src/services/codexSubscriptionOA
const oauth = vi.hoisted(() => ({
callback: vi.fn(),
+ runCatalogSync: vi.fn(),
}))
vi.mock('../src/services/codexSubscriptionOAuth.js', async () => {
@@ -12,6 +13,7 @@ vi.mock('../src/services/codexSubscriptionOAuth.js', async () => {
return {
...actual,
handleCodexBrowserCallback: oauth.callback,
+ runCodexCatalogSync: oauth.runCatalogSync,
}
})
@@ -59,12 +61,22 @@ describe('GET /auth/codex-subscription/callback', () => {
beforeEach(() => {
app = makeApp()
oauth.callback.mockReset()
+ oauth.runCatalogSync.mockReset()
+ oauth.runCatalogSync.mockResolvedValue({
+ ok: true,
+ catalogStatus: 'ready',
+ added: 1,
+ refreshed: 0,
+ staled: 0,
+ connection: { connectionKey: 'codex-aaa', status: 'connected', catalogStatus: 'ready' },
+ })
config.controlUiBaseUrl = 'http://127.0.0.1:3000'
})
it('redirects back to the Codex surface on success without tokens', async () => {
oauth.callback.mockResolvedValue({
status: 'connected',
+ connectionKey: 'codex-aaa',
accountFingerprint: 'fp',
credentialRevision: 1,
refreshToken: 'refresh-secret',
@@ -86,6 +98,7 @@ describe('GET /auth/codex-subscription/callback', () => {
{ code: 'code-1', state: 'state-1' }
)
expect(res.headers['set-cookie']).toBeUndefined()
+ expect(oauth.runCatalogSync).toHaveBeenCalledTimes(1)
assertNoLeak(res.text)
})
@@ -93,6 +106,7 @@ describe('GET /auth/codex-subscription/callback', () => {
const materialize = vi.fn(async () => {})
oauth.callback.mockResolvedValue({
status: 'connected',
+ connectionKey: 'codex-aaa',
accountFingerprint: 'fp',
credentialRevision: 1,
})
@@ -103,6 +117,7 @@ describe('GET /auth/codex-subscription/callback', () => {
expect(res.headers.location).toBe(
'/llm-models/providers/codex-subscription?codex_oauth=connected'
)
+ expect(oauth.runCatalogSync).toHaveBeenCalledTimes(1)
expect(materialize).toHaveBeenCalledTimes(1)
assertNoLeak(res.headers.location)
})
@@ -113,6 +128,7 @@ describe('GET /auth/codex-subscription/callback', () => {
})
oauth.callback.mockResolvedValue({
status: 'connected',
+ connectionKey: 'codex-aaa',
accountFingerprint: 'fp',
credentialRevision: 1,
})
@@ -127,6 +143,29 @@ describe('GET /auth/codex-subscription/callback', () => {
assertNoLeak(res.headers.location)
})
+ it('still redirects when automatic catalog sync fails after a successful callback', async () => {
+ oauth.callback.mockResolvedValue({
+ status: 'connected',
+ connectionKey: 'codex-aaa',
+ accountFingerprint: 'fp',
+ credentialRevision: 1,
+ })
+ oauth.runCatalogSync.mockResolvedValue({
+ ok: false,
+ catalogStatus: 'unavailable',
+ reason: 'catalog_sync_failed',
+ })
+ const res = await request(app)
+ .get('/auth/codex-subscription/callback')
+ .query({ code: 'code-1', state: 'state-1' })
+ expect(res.status).toBe(303)
+ expect(res.headers.location).toBe(
+ '/llm-models/providers/codex-subscription?codex_oauth=connected'
+ )
+ expect(oauth.runCatalogSync).toHaveBeenCalledTimes(1)
+ assertNoLeak(res.headers.location)
+ })
+
it('redirects callback replay errors back to the Codex surface', async () => {
oauth.callback.mockRejectedValue(new CodexSubscriptionOAuthError('state_replayed', 'replay'))
const res = await request(app)
diff --git a/control-api/test/services.codexSubscriptionOAuth.test.ts b/control-api/test/services.codexSubscriptionOAuth.test.ts
index f334c0a57..dee277011 100644
--- a/control-api/test/services.codexSubscriptionOAuth.test.ts
+++ b/control-api/test/services.codexSubscriptionOAuth.test.ts
@@ -48,6 +48,18 @@ vi.mock('../src/services/codexSubscriptionConnection.js', async () => {
}
})
+const catalog = vi.hoisted(() => ({
+ sync: vi.fn(),
+}))
+
+vi.mock('../src/services/codexSubscriptionCatalog.js', async () => {
+ const actual = await vi.importActual('../src/services/codexSubscriptionCatalog.js')
+ return {
+ ...actual,
+ syncCodexSubscriptionCatalog: catalog.sync,
+ }
+})
+
const {
CodexSubscriptionOAuthError,
CODEX_OAUTH_AUTHORIZE_URL,
@@ -62,6 +74,7 @@ const {
revokeCodexSubscription,
startCodexBrowserConnect,
startCodexDeviceConnect,
+ runCodexCatalogSync,
} = await import('../src/services/codexSubscriptionOAuth.js')
const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))
@@ -102,6 +115,7 @@ function deps(fetchFn: typeof fetch) {
describe('codex subscription OAuth broker', () => {
beforeEach(() => {
for (const fn of Object.values(repos)) fn.mockReset()
+ catalog.sync.mockReset()
})
it('starts a browser PKCE flow without leaking secrets', async () => {
@@ -749,4 +763,41 @@ describe('codex subscription OAuth broker', () => {
expect(result).toMatchObject({ status: 'connected' })
expect(repos.insertInitial.mock.calls[0]?.[3]).toBe('team-plus')
})
+
+ it('runs a fail-soft catalog sync after a grant is ready', async () => {
+ repos.loadSecrets.mockResolvedValue({
+ refreshToken: 'refresh-secret',
+ accessToken: 'access-secret',
+ accessTokenExpiresAt: new Date(Date.now() + 60_000),
+ chatgptAccountId: 'acct',
+ credentialRevision: 1,
+ })
+ catalog.sync.mockResolvedValue({
+ outcome: 'ready',
+ added: 3,
+ refreshed: 0,
+ staled: 0,
+ connection: { connectionKey: 'team-plus', status: 'connected', catalogStatus: 'ready' },
+ })
+ const result = await runCodexCatalogSync(deps(vi.fn()), 'team-plus', {
+ listModels: async () => ({ outcome: 'ready', models: [] }),
+ })
+ expect(result).toMatchObject({ ok: true, catalogStatus: 'ready', added: 3 })
+ expect(catalog.sync).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not throw when automatic catalog sync fails', async () => {
+ repos.loadSecrets.mockResolvedValue({
+ refreshToken: 'refresh-secret',
+ accessToken: 'access-secret',
+ accessTokenExpiresAt: new Date(Date.now() + 60_000),
+ chatgptAccountId: 'acct',
+ credentialRevision: 1,
+ })
+ catalog.sync.mockRejectedValue(new Error('proxy down'))
+ const result = await runCodexCatalogSync(deps(vi.fn()), 'team-plus', {
+ listModels: async () => ({ outcome: 'unavailable' }),
+ })
+ expect(result).toEqual({ ok: false, catalogStatus: 'never_synced', reason: 'proxy down' })
+ })
})
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.css
index 447729271..6146dbd60 100644
--- a/control-ui/app/globals.css
+++ b/control-ui/app/globals.css
@@ -11278,6 +11278,25 @@ textarea.cu-input {
gap: var(--cu-space-2);
}
+.cu-codex-device-code {
+ display: grid;
+ gap: var(--cu-space-2);
+}
+
+.cu-codex-device-code__row {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--cu-space-2);
+}
+
+.cu-codex-device-code__value {
+ font-family: var(--cu-font-mono);
+ font-size: var(--cu-font-size-lg);
+ font-weight: var(--cu-font-weight-semibold);
+ letter-spacing: 0.04em;
+}
+
.cu-agent-select.cu-llm-provider-filter {
width: 12rem;
flex: 0 0 12rem;
diff --git a/control-ui/components/CodexSubscriptionHub/index.tsx b/control-ui/components/CodexSubscriptionHub/index.tsx
index 6cc3c56c1..d0cd01b01 100644
--- a/control-ui/components/CodexSubscriptionHub/index.tsx
+++ b/control-ui/components/CodexSubscriptionHub/index.tsx
@@ -1,6 +1,7 @@
'use client'
-import React, { useCallback, useEffect, useMemo, useState } from 'react'
+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { copyTextToClipboard } from '@lib/clipboard'
import {
type CodexSubscriptionConnectionView,
createCodexSubscriptionConnection,
@@ -32,7 +33,7 @@ import { SelectionDropdown } from '../SelectionDropdown'
import { IconKey } from '../Sidebar/icons'
import { TablePanelHeader } from '../TablePanelHeader'
import { useToast } from '../Toast'
-import { IconPencil, IconRefresh, IconX } from '../icons'
+import { IconCopy, IconPencil, IconRefresh, IconX } from '../icons'
function grantLabel(row: CodexSubscriptionConnectionView): string {
return row.displayName || row.connectionKey
@@ -57,6 +58,7 @@ export function CodexSubscriptionHub() {
>([])
const [userCode, setUserCode] = useState<string | null>(null)
const [verificationUri, setVerificationUri] = useState<string | null>(null)
+ const connectEpoch = useRef(0)
const enabled = isCodexSubscriptionUiEnabled(capability)
useEffect(() => {
@@ -107,20 +109,32 @@ export function CodexSubscriptionHub() {
}
setBusyKey('create')
try {
- await createCodexSubscriptionConnection({ displayName })
+ const created = await createCodexSubscriptionConnection({ displayName })
setCreateName('')
setCreating(false)
setError('')
- await load()
+ setEditing(created)
+ setEditName(grantLabel(created))
+ setEditDefault(created.defaultModel ?? '')
+ setEditModels([])
+ setUserCode(null)
+ setVerificationUri(null)
showToast(`Subscription ${displayName} created.`, { tone: 'success' })
+ void startDeviceConnect(created)
+ try {
+ await load()
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load ChatGPT subscriptions')
+ }
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not create subscription')
- } finally {
setBusyKey(null)
}
}
async function openEdit(row: CodexSubscriptionConnectionView) {
+ connectEpoch.current += 1
+ setBusyKey(null)
setEditing(row)
setEditName(grantLabel(row))
setEditDefault(row.defaultModel ?? '')
@@ -141,6 +155,8 @@ export function CodexSubscriptionHub() {
}
function closeEdit() {
+ connectEpoch.current += 1
+ setBusyKey(null)
setEditing(null)
setEditName('')
setEditDefault('')
@@ -168,19 +184,23 @@ export function CodexSubscriptionHub() {
}
}
- async function handleConnect(row: CodexSubscriptionConnectionView) {
+ async function startDeviceConnect(row: CodexSubscriptionConnectionView) {
+ const epoch = ++connectEpoch.current
setBusyKey(row.connectionKey)
try {
const started = await startCodexDeviceConnect(
row.status === 'connected' ? 'reconnect' : 'connect',
row.connectionKey
)
+ if (epoch !== connectEpoch.current) return
setUserCode(started.userCode)
setVerificationUri(started.verificationUri)
const deadline = Date.now() + started.intervalSeconds * 1000 * 40
while (Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, started.intervalSeconds * 1000))
+ if (epoch !== connectEpoch.current) return
const polled = await pollCodexDevice(started.state, row.connectionKey)
+ if (epoch !== connectEpoch.current) return
if (polled.status === 'connected') {
setUserCode(null)
setVerificationUri(null)
@@ -189,6 +209,13 @@ export function CodexSubscriptionHub() {
const models = await listCodexConnectionModels(latest.connectionKey)
setEditModels(models)
await load()
+ if (latest.catalogStatus === 'ready') {
+ showToast('Connected — catalog synced', { tone: 'success' })
+ } else {
+ showToast('Connected, but catalog sync failed — use Sync catalog to retry', {
+ tone: 'error',
+ })
+ }
return
}
if (polled.status === 'expired' || polled.status === 'denied') {
@@ -202,14 +229,25 @@ export function CodexSubscriptionHub() {
setVerificationUri(null)
setError('ChatGPT sign-in timed out. Try again.')
} catch (err) {
+ if (epoch !== connectEpoch.current) return
setUserCode(null)
setVerificationUri(null)
setError(err instanceof Error ? err.message : 'ChatGPT sign-in failed')
} finally {
- setBusyKey(null)
+ if (epoch === connectEpoch.current) setBusyKey(null)
}
}
+ async function handleCopyUserCode() {
+ if (!userCode) return
+ const copied = await copyTextToClipboard(userCode)
+ if (copied) {
+ showToast('Code copied', { tone: 'success' })
+ return
+ }
+ setError('Could not copy the verification code')
+ }
+
async function handleSync(row: CodexSubscriptionConnectionView) {
if (row.status !== 'connected') return
setBusyKey(row.connectionKey)
@@ -512,7 +550,7 @@ export function CodexSubscriptionHub() {
className="cu-modal-overlay"
role="presentation"
onClick={e => {
- if (e.target === e.currentTarget && !busyKey) closeEdit()
+ if (e.target === e.currentTarget) closeEdit()
}}
>
<div
@@ -530,7 +568,6 @@ export function CodexSubscriptionHub() {
type="button"
className="cu-btn cu-btn--icon cu-btn--ghost"
onClick={closeEdit}
- disabled={Boolean(busyKey)}
aria-label="Close"
>
<IconX width={18} height={18} />
@@ -555,7 +592,7 @@ export function CodexSubscriptionHub() {
<button
type="button"
className="cu-btn cu-btn--ghost cu-btn--sm"
- onClick={() => void handleConnect(editing)}
+ onClick={() => void startDeviceConnect(editing)}
disabled={Boolean(busyKey)}
>
Sign in with ChatGPT
@@ -570,10 +607,38 @@ export function CodexSubscriptionHub() {
</button>
</div>
{userCode ? (
- <p data-testid="codex-device-code">
- Enter {userCode}
- {verificationUri ? ` at ${verificationUri}` : ''}
- </p>
+ <div className="cu-codex-device-code">
+ <p className="cu-field__hint">
+ Enter this code at{' '}
+ {verificationUri ? (
+ <a
+ className="cu-link"
+ data-testid="codex-device-verification-link"
+ href={verificationUri}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {verificationUri}
+ </a>
+ ) : (
+ 'the ChatGPT verification page'
+ )}
+ </p>
+ <div className="cu-codex-device-code__row">
+ <code data-testid="codex-device-code" className="cu-codex-device-code__value">
+ {userCode}
+ </code>
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost cu-btn--sm"
+ onClick={() => void handleCopyUserCode()}
+ aria-label="Copy code"
+ >
+ <IconCopy width={15} height={15} />
+ Copy
+ </button>
+ </div>
+ </div>
) : null}
{editModels.length > 0 ? (
<fieldset className="cu-field">
@@ -615,12 +680,7 @@ export function CodexSubscriptionHub() {
</div>
</div>
<div className="cu-modal-panel__foot">
- <button
- type="button"
- className="cu-btn cu-btn--ghost cu-btn--sm"
- onClick={closeEdit}
- disabled={Boolean(busyKey)}
- >
+ <button type="button" className="cu-btn cu-btn--ghost cu-btn--sm" onClick={closeEdit}>
Cancel
</button>
<button
diff --git a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx
index c1c476930..05b819808 100644
--- a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx
+++ b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx
@@ -7,6 +7,7 @@ import {
listCodexSubscriptionConnections,
patchCodexCatalogModel,
patchCodexSubscriptionConnection,
+ pollCodexDevice,
revokeCodexSubscription,
startCodexDeviceConnect,
syncCodexSubscriptionCatalog,
@@ -45,6 +46,24 @@ vi.mock('@lib/codexSubscription', async importOriginal => {
}
})
+type DevicePollView = Awaited<ReturnType<typeof pollCodexDevice>>
+
+const pendingPolls: Array<(value: DevicePollView) => void> = []
+
+function holdDevicePoll() {
+ vi.mocked(pollCodexDevice).mockImplementation(
+ () =>
+ new Promise<DevicePollView>(resolve => {
+ pendingPolls.push(resolve)
+ })
+ )
+}
+
+function releaseDevicePolls(view: DevicePollView = { status: 'expired' }) {
+ const resolvers = pendingPolls.splice(0)
+ for (const resolve of resolvers) resolve(view)
+}
+
function connection(
overrides: Partial<CodexSubscriptionConnectionView> &
Pick<CodexSubscriptionConnectionView, 'connectionKey'>
@@ -75,17 +94,35 @@ describe('CodexSubscriptionHub', () => {
{ model: 'gpt-5.1', enabled: true, stale: false },
{ model: 'gpt-5.3-codex', enabled: false, stale: false },
])
+ vi.mocked(startCodexDeviceConnect).mockResolvedValue({
+ userCode: 'ABCD-1234',
+ verificationUri: 'https://auth.openai.com/codex/device',
+ intervalSeconds: 0.001,
+ state: 'state-1',
+ intent: 'connect',
+ })
+ pendingPolls.length = 0
+ holdDevicePoll()
})
- afterEach(() => {
- cleanup()
- vi.clearAllMocks()
+ afterEach(async () => {
+ try {
+ await new Promise(resolve => setTimeout(resolve, 20))
+ releaseDevicePolls()
+ } finally {
+ cleanup()
+ vi.clearAllMocks()
+ }
})
- it('creates a subscription from the Add modal', async () => {
- vi.mocked(createCodexSubscriptionConnection).mockResolvedValue(
- connection({ connectionKey: 'codex-bbb', displayName: 'New team' })
- )
+ it('opens the sync modal and starts device connect after Create without using the pencil', async () => {
+ const created = connection({
+ connectionKey: 'codex-bbb',
+ displayName: 'New team',
+ status: 'disconnected',
+ catalogStatus: 'never_synced',
+ })
+ vi.mocked(createCodexSubscriptionConnection).mockResolvedValue(created)
render(
<ToastProvider>
<CodexSubscriptionHub />
@@ -100,9 +137,117 @@ describe('CodexSubscriptionHub', () => {
await waitFor(() => {
expect(createCodexSubscriptionConnection).toHaveBeenCalledWith({ displayName: 'New team' })
})
+ expect(await screen.findByRole('button', { name: 'Sign in with ChatGPT' })).toBeInTheDocument()
+ await waitFor(() => {
+ expect(startCodexDeviceConnect).toHaveBeenCalledWith('connect', 'codex-bbb')
+ })
+ expect(syncCodexSubscriptionCatalog).not.toHaveBeenCalled()
expect(revokeCodexSubscription).not.toHaveBeenCalled()
})
+ it('renders a ChatGPT verification link and copies the device code', async () => {
+ const writeText = vi.fn().mockResolvedValue(undefined)
+ Object.assign(navigator, { clipboard: { writeText } })
+ vi.mocked(createCodexSubscriptionConnection).mockResolvedValue(
+ connection({
+ connectionKey: 'codex-bbb',
+ displayName: 'New team',
+ status: 'disconnected',
+ catalogStatus: 'never_synced',
+ })
+ )
+ render(
+ <ToastProvider>
+ <CodexSubscriptionHub />
+ </ToastProvider>
+ )
+ fireEvent.click(await screen.findByRole('button', { name: 'Add subscription' }))
+ fireEvent.change(screen.getByRole('textbox', { name: 'Name' }), {
+ target: { value: 'New team' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))
+ const link = await screen.findByTestId('codex-device-verification-link')
+ expect(link).toHaveAttribute('href', 'https://auth.openai.com/codex/device')
+ expect(link).toHaveAttribute('target', '_blank')
+ expect(link.getAttribute('rel') ?? '').toContain('noopener')
+ expect(screen.getByTestId('codex-device-code')).toHaveTextContent('ABCD-1234')
+ fireEvent.click(screen.getByRole('button', { name: 'Copy code' }))
+ await waitFor(() => {
+ expect(writeText).toHaveBeenCalledWith('ABCD-1234')
+ })
+ expect(await screen.findByText('Code copied')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeEnabled()
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ await waitFor(() => {
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+ })
+
+ it('does not POST catalog/sync after a ready poll', async () => {
+ vi.mocked(createCodexSubscriptionConnection).mockResolvedValue(
+ connection({
+ connectionKey: 'codex-bbb',
+ displayName: 'New team',
+ status: 'disconnected',
+ catalogStatus: 'never_synced',
+ })
+ )
+ vi.mocked(startCodexDeviceConnect).mockResolvedValue({
+ userCode: 'ABCD-1234',
+ verificationUri: 'https://auth.openai.com/codex/device',
+ intervalSeconds: 0.001,
+ state: 'state-1',
+ intent: 'connect',
+ })
+ vi.mocked(pollCodexDevice).mockResolvedValue({
+ status: 'connected',
+ connection: connection({
+ connectionKey: 'codex-bbb',
+ displayName: 'New team',
+ catalogStatus: 'ready',
+ }),
+ })
+ render(
+ <ToastProvider>
+ <CodexSubscriptionHub />
+ </ToastProvider>
+ )
+ fireEvent.click(await screen.findByRole('button', { name: 'Add subscription' }))
+ fireEvent.change(screen.getByRole('textbox', { name: 'Name' }), {
+ target: { value: 'New team' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))
+ await waitFor(() => {
+ expect(pollCodexDevice).toHaveBeenCalled()
+ })
+ expect(await screen.findByText('Connected — catalog synced')).toBeInTheDocument()
+ expect(syncCodexSubscriptionCatalog).not.toHaveBeenCalled()
+ })
+
+ it('keeps the sync modal open with Sign in when device/start fails after Create', async () => {
+ vi.mocked(createCodexSubscriptionConnection).mockResolvedValue(
+ connection({
+ connectionKey: 'codex-ccc',
+ displayName: 'Retry team',
+ status: 'disconnected',
+ catalogStatus: 'never_synced',
+ })
+ )
+ vi.mocked(startCodexDeviceConnect).mockRejectedValue(new Error('device start failed'))
+ render(
+ <ToastProvider>
+ <CodexSubscriptionHub />
+ </ToastProvider>
+ )
+ fireEvent.click(await screen.findByRole('button', { name: 'Add subscription' }))
+ fireEvent.change(screen.getByRole('textbox', { name: 'Name' }), {
+ target: { value: 'Retry team' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))
+ expect(await screen.findByRole('button', { name: 'Sign in with ChatGPT' })).toBeInTheDocument()
+ expect(await screen.findByText('device start failed')).toBeInTheDocument()
+ })
+
it('renders subscriptions as a Secrets table with pencil and delete actions', async () => {
render(
<ToastProvider>
diff --git a/control-ui/lib/__tests__/codexSubscription.sanitize.test.ts b/control-ui/lib/__tests__/codexSubscription.sanitize.test.ts
index bbe12e86e..4b419e82d 100644
--- a/control-ui/lib/__tests__/codexSubscription.sanitize.test.ts
+++ b/control-ui/lib/__tests__/codexSubscription.sanitize.test.ts
@@ -3,6 +3,7 @@ import {
type CodexSubscriptionConnectionView,
isAssignableCodexGrant,
sanitizeCodexConnection,
+ sanitizeCodexDevicePoll,
} from '../codexSubscription'
function connected(
@@ -41,6 +42,27 @@ describe('sanitizeCodexConnection', () => {
})
})
+describe('sanitizeCodexDevicePoll', () => {
+ it('keeps catalogStatus when present and defaults when the backend omits it', () => {
+ const ready = sanitizeCodexDevicePoll({
+ status: 'connected',
+ connection: connected(),
+ })
+ expect(ready.status).toBe('connected')
+ if (ready.status === 'connected') {
+ expect(ready.connection.catalogStatus).toBe('ready')
+ }
+ const omitted = sanitizeCodexDevicePoll({
+ status: 'connected',
+ connection: { ...connected(), catalogStatus: undefined },
+ })
+ expect(omitted.status).toBe('connected')
+ if (omitted.status === 'connected') {
+ expect(omitted.connection.catalogStatus).toBe('never_synced')
+ }
+ })
+})
+
describe('isAssignableCodexGrant', () => {
it('accepts only a connected grant whose catalog is ready', () => {
expect(isAssignableCodexGrant(connected())).toBe(true)
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index d5b00a90d..c6c1e8790 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.475",
+ "version": "0.1.476",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.475",
+ "version": "0.1.476",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-ui/package.json b/control-ui/package.json
index c5a43e394..bcf1f477a 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.475",
+ "version": "0.1.476",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts
index fbd3f5087..87c8381e9 100644
--- a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts
+++ b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts
@@ -89,18 +89,22 @@ test.describe('Codex subscription connection', () => {
await expect(page.getByRole('tab', { name: 'Subscriptions', selected: true })).toBeVisible()
})
- test('J3 Add subscription POSTs 201 and shows the displayName row', async ({ page }) => {
+ test('J3 Create lands on the sync modal, not the table alone', async ({ page }) => {
const shell = new ControlUiShell(page)
const hub = new SecretsLlmSubscriptionsPage(page)
const displayName = `e2e-add-${Date.now().toString(36)}`
await loginFromHome(page)
await shell.openSecretsLlmSubscriptions()
const key = await hub.createGrant(displayName)
+ await expect(page).toHaveURL(/\/secrets\/llm\/subscriptions$/)
+ await hub.expectConnectModal()
const listed = await listConnections()
expect(listed.find(row => row.connectionKey === key)?.displayName).toBe(displayName)
+ await hub.closeConnectModal()
+ await expect(page.getByRole('cell', { name: displayName, exact: true })).toBeVisible()
})
- test('J4 pencil Sign in and Sync live on Secrets, never on the agent', async ({ page }) => {
+ test('J4 Create starts device connect with a usable ChatGPT link and copy', async ({ page }) => {
const shell = new ControlUiShell(page)
const hub = new SecretsLlmSubscriptionsPage(page)
const agents = new AgentListPage(page)
@@ -109,27 +113,37 @@ test.describe('Codex subscription connection', () => {
await loginFromHome(page)
await shell.openSecretsLlmSubscriptions()
- const grantKey = await hub.createGrant(displayName)
- await hub.openGrant(displayName)
-
- const signIn = page.getByRole('button', { name: 'Sign in with ChatGPT' })
- await expect(signIn).toBeEnabled()
+ await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
const deviceStart = page.waitForResponse(
response =>
/\/api\/v1\/admin\/llm\/providers\/codex-subscription\/(connections\/[^/]+\/)?device\/start$/.test(
new URL(response.url()).pathname
) && response.request().method() === 'POST'
)
- await signIn.click()
+ const grantKey = await hub.createGrant(displayName)
const deviceRes = await deviceStart
- expect(deviceRes.ok(), `device start must succeed, got ${deviceRes.status()}`).toBe(true)
- const deviceBody = (await deviceRes.json()) as { userCode?: string }
+ expect(deviceRes.status(), `device start must return 200, got ${deviceRes.status()}`).toBe(200)
+ const deviceBody = (await deviceRes.json()) as {
+ userCode?: string
+ verificationUri?: string
+ }
expect(deviceBody.userCode).toEqual(expect.any(String))
- await expect(page.getByTestId('codex-device-code')).toContainText(String(deviceBody.userCode))
+
+ const link = page.getByTestId('codex-device-verification-link')
+ await expect(link).toHaveAttribute('href', 'https://auth.openai.com/codex/device')
+ await expect(link).toHaveAttribute('target', '_blank')
+ await expect(link).toHaveAttribute('rel', /noopener/)
+ await expect(page.getByTestId('codex-device-code')).toHaveText(String(deviceBody.userCode))
+
+ await page.getByRole('button', { name: 'Copy code' }).click()
+ await expect(page.getByText('Code copied')).toBeVisible()
+ await expect
+ .poll(async () => page.evaluate(() => navigator.clipboard.readText()))
+ .toBe(String(deviceBody.userCode))
const grant = (await listConnections()).find(row => row.connectionKey === grantKey)
expect(grant, 'created grant must be listed').toBeTruthy()
- const sync = page.getByRole('button', { name: 'Sync catalog' })
+ const sync = page.getByRole('dialog').getByRole('button', { name: 'Sync catalog' })
if (grant?.status === 'connected') {
const syncResPromise = page.waitForResponse(
response =>
@@ -139,12 +153,14 @@ test.describe('Codex subscription connection', () => {
)
await sync.click()
const syncRes = await syncResPromise
- expect(syncRes.ok(), `catalog sync must succeed, got ${syncRes.status()}`).toBe(true)
+ expect(syncRes.ok(), `manual catalog sync retry must succeed, got ${syncRes.status()}`).toBe(
+ true
+ )
} else {
await expect(sync, 'Sync stays disabled until the grant is connected').toBeDisabled()
}
- await page.getByRole('button', { name: 'Cancel' }).click()
+ await hub.closeConnectModal()
await shell.openAgents()
await seedCodexAgents(page, 1)
await agents.openNth(0)
@@ -237,6 +253,7 @@ test.describe('Codex subscription connection', () => {
await loginFromHome(page)
await shell.openSecretsLlmSubscriptions()
const grantKey = await hub.createGrant(displayName)
+ await hub.closeConnectModal()
await shell.openAgents()
await seedCodexAgents(page, 1)
const agentName = await agents.openNth(0)
@@ -275,6 +292,7 @@ test.describe('Codex subscription connection', () => {
await loginFromHome(page)
await shell.openSecretsLlmSubscriptions()
await hub.createGrant(displayName)
+ await hub.closeConnectModal()
await shell.openAgents()
await seedCodexAgents(page, 2)
await agents.openNth(0)
@@ -300,6 +318,7 @@ test.describe('Codex subscription connection', () => {
await loginFromHome(page)
await shell.openSecretsLlmSubscriptions()
const grantKey = await hub.createGrant(displayName)
+ await hub.closeConnectModal()
await shell.openAgents()
await seedCodexAgents(page, 1)
const agentName = await agents.openNth(0)
@@ -325,6 +344,7 @@ test.describe('Codex subscription connection', () => {
await loginFromHome(page)
await shell.openSecretsLlmSubscriptions()
const grantKey = await hub.createGrant(displayName)
+ await hub.closeConnectModal()
await shell.openAgents()
await seedCodexAgents(page, 1)
const agentName = await agents.openNth(0)
@@ -370,6 +390,7 @@ test.describe('Codex subscription connection', () => {
expect(grantPatches, 'API-KEY must not PATCH grant metadata').toEqual([])
await shell.openSecretsLlmSubscriptions()
await hub.createGrant(displayName)
+ await hub.closeConnectModal()
expect(secretPuts, 'Subscriptions must not PUT LLM secrets').toEqual([])
})
})
diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.json
index fcdb6cfb6..454f3db77 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.35",
+ "version": "0.1.36",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-playwright-tests",
- "version": "0.1.35",
+ "version": "0.1.36",
"devDependencies": {
"@playwright/test": "^1.50.0",
"@types/node": "^22.0.0"
diff --git a/tests/e2e/playwright/package.json b/tests/e2e/playwright/package.json
index 0d5b0dba7..8bcb11369 100644
--- a/tests/e2e/playwright/package.json
+++ b/tests/e2e/playwright/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-playwright-tests",
- "version": "0.1.35",
+ "version": "0.1.36",
"private": true,
"description": "Playwright E2E tests for Control UI and Desktop App",
"scripts": {
diff --git a/tests/e2e/playwright/pages/codex-subscription.ts b/tests/e2e/playwright/pages/codex-subscription.ts
index 8bf7c1a8b..0f10e3221 100644
--- a/tests/e2e/playwright/pages/codex-subscription.ts
+++ b/tests/e2e/playwright/pages/codex-subscription.ts
@@ -145,6 +145,22 @@ export class SecretsLlmSubscriptionsPage {
return this.page.getByRole('row', { name: new RegExp(displayName) })
}
+ async expectConnectModal() {
+ const dialog = this.page.getByRole('dialog')
+ await expect(dialog).toBeVisible()
+ await expect(dialog.getByRole('button', { name: 'Sign in with ChatGPT' })).toBeVisible()
+ await expect(dialog.getByRole('button', { name: 'Sync catalog' })).toBeVisible()
+ }
+
+ async closeConnectModal() {
+ await this.page.getByRole('dialog').getByRole('button', { name: 'Cancel' }).click()
+ await expect(this.page.getByRole('dialog')).toHaveCount(0)
+ }
+
+ /**
+ * Create a named grant. After the 201 the sync dialog stays open
+ * (Sign in visible). Callers that leave Secrets must closeConnectModal first.
+ */
async createGrant(displayName: string): Promise<string> {
await this.page.getByRole('button', { name: 'Add subscription' }).click()
await this.page.getByLabel('Name', { exact: true }).fill(displayName)
@@ -156,10 +172,10 @@ export class SecretsLlmSubscriptionsPage {
)
await this.page.getByRole('button', { name: 'Create', exact: true }).click()
const response = await created
- expect(response.ok(), `create grant must succeed, got ${response.status()}`).toBe(true)
+ expect(response.status(), `create grant must return 201, got ${response.status()}`).toBe(201)
const body = (await response.json()) as { connectionKey?: string }
expect(body.connectionKey).toEqual(expect.any(String))
- await expect(this.page.getByRole('cell', { name: displayName, exact: true })).toBeVisible()
+ await this.expectConnectModal()
return String(body.connectionKey)
}