Skip to content

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

TypeScript

feat(llm): declare provider families and reconcile subscription catalogs

Alfredo Lopezb847b0599dd8
diff --git a/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts b/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts
index a06c287f3..97cf9add4 100644
--- a/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts
+++ b/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts
@@ -534,7 +534,10 @@ describe('hermetic per-response tool-call limit', () => {
try {
// The request presents the fixture's tool name, so the upstream serves
// the stream instead of refusing with fixture_tool_not_declared.
- const raw = { ...completionRequest('gpt-5.3-codex'), tools: structuredClone(optionalMcpTools) }
+ const raw = {
+ ...completionRequest('gpt-5.3-codex'),
+ tools: structuredClone(optionalMcpTools),
+ }
const parsed = parseCodexCompletionRequestV1(raw)
if (!parsed.ok) throw new Error(parsed.message)
const requestHash = hashCodexCompletionRequestV1(parsed.value)
@@ -604,7 +607,10 @@ describe('hermetic per-response tool-call limit', () => {
expect(frames[0]).toEqual({ type: 'text', text: 'hello' })
expect(frames.filter(frame => frame.type === 'tool_call')).toHaveLength(0)
expect(frames.filter(frame => frame.type === 'done')).toHaveLength(0)
- expect(frames[frames.length - 1]).toMatchObject({ type: 'error', code: 'tool_call_limit_exceeded' })
+ expect(frames[frames.length - 1]).toMatchObject({
+ type: 'error',
+ code: 'tool_call_limit_exceeded',
+ })
expect(redeems).toHaveLength(1)
expect(finalizes).toHaveLength(1)
expect(finalizes[0]?.receipt).toMatchObject({
@@ -637,3 +643,72 @@ describe('hermetic per-response tool-call limit', () => {
})
})
})
+
+describe('hermetic catalog re-read', () => {
+ // The catalog is read once at sign-in, so a model the vendor publishes later
+ // reaches a grant only through a re-read. This is the one place in the
+ // repository where that re-read can be exercised against an upstream we
+ // control: the catalog origin is frozen to chatgpt.com by originPolicy, and
+ // only the in-process fetch seam below redirects the socket. The lane that
+ // deploys this same fixture into the cluster never points any component at
+ // it, and the Control UI Playwright lane deploys no upstream at all.
+ const CATALOG_UPSTREAM_PORT = UPSTREAM_PORT + 2
+ const PUBLISHED_AFTER_HANDSHAKE = 'gpt-5.3-codex-mini'
+
+ function adminPermit(): string {
+ return sign(
+ { sub: 'admin-hermetic', typ: 'codex-admin-permit', operation: 'catalog_list' },
+ 'codex-llm-proxy-admin'
+ )
+ }
+
+ it('returns a model the upstream published after the grant was connected', async () => {
+ // The fixture reads its model list at startup, so this case owns its
+ // upstream. The grant seeded in CONNECTED_GRANTS carries only
+ // gpt-5.3-codex; the second id exists upstream and nowhere else.
+ const catalogUpstream = await spawnFixtureUpstream(CATALOG_UPSTREAM_PORT, {
+ CODEX_TEST_UPSTREAM_EXTRA_MODEL: PUBLISHED_AFTER_HANDSHAKE,
+ })
+ const base = `https://127.0.0.1:${CATALOG_UPSTREAM_PORT}`
+ const proxy = createProxyApps(config(), {
+ fetchFn: (url, init) => {
+ const parsed = new URL(String(url))
+ expect(parsed.origin).toBe('https://chatgpt.com')
+ expect(parsed.pathname).toBe(new URL(CODEX_CATALOG_ORIGIN).pathname)
+ return trustedLoopbackFetch(new URL(parsed.pathname + parsed.search, base), init)
+ },
+ lookup: async () => [{ address: '104.18.32.47', family: 4 }],
+ })
+ try {
+ const before = (await (
+ await trustedLoopbackFetch(`${base}/internal/counters`)
+ ).json()) as Record<string, number>
+
+ const res = await request(proxy.adminApp)
+ .post('/internal/admin/v1/codex/models')
+ .set('Authorization', `Bearer ${adminPermit()}`)
+ .send({ accessToken: 'test-access-hermetic-catalog' })
+
+ const after = (await (
+ await trustedLoopbackFetch(`${base}/internal/counters`)
+ ).json()) as Record<string, number>
+ // Liveness witness: the route reached the upstream for this call. Without
+ // it, a handler that answered from anything cached would satisfy the
+ // model assertions below.
+ expect(after.models - before.models).toBe(1)
+
+ expect(res.status).toBe(200)
+ // The grant's own model is asserted alongside the new one: a reply that
+ // lost it would be a different failure than one that never gained the
+ // second id, and one assertion reports both.
+ expect(res.body).toEqual({
+ outcome: 'ready',
+ models: [{ model: 'gpt-5.3-codex' }, { model: PUBLISHED_AFTER_HANDSHAKE }],
+ })
+ expect(CONNECTED_GRANTS[RECIPE_HOST_REF]?.models).not.toContain(PUBLISHED_AFTER_HANDSHAKE)
+ } finally {
+ await proxy.close()
+ await stopFixtureUpstream(catalogUpstream)
+ }
+ })
+})
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 461945ecf..fbc5590fc 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.589",
+ "version": "0.1.590",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.589",
+ "version": "0.1.590",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index a518fab2a..c16ca492b 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.589",
+ "version": "0.1.590",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/config.ts b/control-api/src/config.ts
index a953e2c73..41ddda9ca 100644
--- a/control-api/src/config.ts
+++ b/control-api/src/config.ts
@@ -129,6 +129,15 @@ type Config = {
// Public Grok CLI OAuth client id. Not a secret; device-code flow protects
// the grant. Override only to pin a documented registration.
grokOAuthClientId: string
+ // Default OFF. When on, a periodic tick re-runs the SAME catalog sync the
+ // connect flow and the manual Hub action drive, for every live connected
+ // subscription grant of every enabled broker. Without it a grant's catalog is
+ // written once at connect and never refreshed on its own.
+ subscriptionCatalogSyncCronEnabled: boolean
+ // Deliberately conservative: each tick issues one upstream catalog call PER
+ // CONNECTION, and a Grok refresh inside the 5-minute skew rotates the refresh
+ // token. A short interval is an abuse risk, not a freshness win.
+ subscriptionCatalogSyncIntervalMs: number
llmCatalogSyncIntervalMs: number
// How long image-input evidence derived from models.dev stays valid, counted
// from the catalog CAPTURE time (not the wall clock). Past it the shared
@@ -445,6 +454,11 @@ const LLM_CATALOG_SYNC_MIN_INTERVAL_MS = 60_000
// came from. The floor is two sync intervals: anything shorter would expire the
// evidence before the cron could possibly renew it.
const LLM_CATALOG_IMAGE_EVIDENCE_MIN_TTL_MS = 2 * LLM_CATALOG_SYNC_MIN_INTERVAL_MS
+// Unlike the discovery sync (one call to models.dev per tick), a subscription
+// reconciliation tick calls each broker once PER CONNECTED GRANT and can rotate
+// a Grok refresh token on the way. Fifteen minutes is the floor below which the
+// cron stops being a reconciler and becomes traffic against the vendor.
+const SUBSCRIPTION_CATALOG_SYNC_MIN_INTERVAL_MS = 15 * 60_000
const WORKFLOW_MAX_WORKLOADS_PER_RECIPE_CEILING = 25
const WORKFLOW_UI_EGRESS_INTERNAL_MAX_ITEMS_CEILING = 25
const WORKFLOW_MAX_STEPS_CEILING = 100
@@ -854,6 +868,14 @@ export const config: Config = {
codexOAuthClientId:
process.env.CONTROL_API_CODEX_OAUTH_CLIENT_ID || 'app_EMoamEEZ73f0CkXaXp7hrann',
grokSubscriptionEnabled: process.env.CONTROL_API_GROK_SUBSCRIPTION_ENABLED === 'true',
+ // Default OFF, same exact-token idiom as the discovery cron above: the
+ // reconciliation stays dark until an operator turns it on deliberately.
+ subscriptionCatalogSyncCronEnabled: process.env.SUBSCRIPTION_CATALOG_SYNC_CRON_ENABLED === 'true',
+ subscriptionCatalogSyncIntervalMs: intervalMsFromEnv(
+ 'SUBSCRIPTION_CATALOG_SYNC_INTERVAL_MS',
+ 6 * 60 * 60 * 1000,
+ SUBSCRIPTION_CATALOG_SYNC_MIN_INTERVAL_MS
+ ),
// Public native client used by Grok CLI / SuperGrok device-code login.
// This is not a confidential client secret. Same shape as Codex above.
grokOAuthClientId:
diff --git a/control-api/src/main.ts b/control-api/src/main.ts
index c77b9d132..4571932f1 100644
--- a/control-api/src/main.ts
+++ b/control-api/src/main.ts
@@ -24,6 +24,11 @@ import {
reconcileRegistryPullSecret,
startRegistryPullSecretReconcileCron,
} from './services/registryPullSecretReconcileCron.js'
+import {
+ reconcileSubscriptionCatalogsFromEnv,
+ startSubscriptionCatalogSyncCron,
+ stopSubscriptionCatalogSyncCron,
+} from './services/subscriptionCatalogSyncCron.js'
import {
startWorkflowApprovalTraceProjector,
stopWorkflowApprovalTraceProjector,
@@ -116,6 +121,27 @@ async function main(): Promise<void> {
)
}
+ // Subscription catalog reconciliation. A grant's catalog is written once at
+ // connect and never refreshed on its own, so a model the vendor publishes
+ // afterwards stays invisible to the subscription while the API-key provider of
+ // the SAME vendor picks it up from the discovery sync above. The tick re-runs
+ // the identical per-connection sync the Hub's manual action drives, and needs
+ // the gateway for the same reason: it publishes the allowlist ConfigMap when a
+ // connection records an outcome. Per-broker gates still apply inside the tick.
+ if (config.subscriptionCatalogSyncCronEnabled) {
+ startSubscriptionCatalogSyncCron(
+ { sync: () => reconcileSubscriptionCatalogsFromEnv(gateway.llmAllowedModelsConfigMap()) },
+ config.subscriptionCatalogSyncIntervalMs
+ )
+ console.log(
+ `[ControlAPI] Subscription catalog sync cron enabled (interval=${config.subscriptionCatalogSyncIntervalMs}ms)`
+ )
+ } else {
+ console.log(
+ '[ControlAPI] Subscription catalog sync cron disabled (SUBSCRIPTION_CATALOG_SYNC_CRON_ENABLED not "true")'
+ )
+ }
+
// Assert the platform image-pull credential up front and then on a timer. WRC injects
// the reference for ANY WorkflowRecipe, including ones created by `kubectl apply` or the
// `deploy_recipe` tool that control-api never sees — so provisioning cannot only happen
@@ -196,6 +222,7 @@ main().catch(error => {
stopUsageRetentionCron()
stopBudgetReservationSweepCron()
stopLlmCatalogSyncCron()
+ stopSubscriptionCatalogSyncCron()
stopWorkflowApprovalTraceProjector()
void pool.end()
process.exit(1)
diff --git a/control-api/src/routes/admin/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.ts
index cf16c186d..9992f09c1 100644
--- a/control-api/src/routes/admin/codexSubscription.ts
+++ b/control-api/src/routes/admin/codexSubscription.ts
@@ -716,6 +716,14 @@ export function createAdminCodexSubscriptionRouter(
)
return
}
+ // A catalogStatus other than `never_synced` means the sync reached xAI
+ // and the connection row now carries that outcome, so the runtime
+ // snapshot is stale until it is republished — mcp-host and HCC never
+ // read Postgres. `never_synced` persisted nothing and needs no write.
+ // The Codex branch below publishes before its own 503 for this reason.
+ if (synced.catalogStatus !== 'never_synced') {
+ if (await publishRuntimeAllowlistOrFail(res)) return
+ }
res.status(503).json({ error: 'catalog_sync_failed', outcome: synced.catalogStatus })
return
}
diff --git a/control-api/src/services/__tests__/subscriptionCatalogSyncCron.test.ts b/control-api/src/services/__tests__/subscriptionCatalogSyncCron.test.ts
new file mode 100644
index 000000000..83712cdd1
--- /dev/null
+++ b/control-api/src/services/__tests__/subscriptionCatalogSyncCron.test.ts
@@ -0,0 +1,392 @@
+/**
+ * Subscription catalog reconciliation cron.
+ *
+ * The tick reconciles every live, connected subscription grant against its
+ * broker's catalog under a SESSION advisory lock, so replicas dedup instead of
+ * piling up redundant upstream calls. This suite pins the hazards that make the
+ * difference between a reconciler and an abuse vector: the lock lifecycle, the
+ * skip rules (a disabled broker, a grant that is not `connected`), failure
+ * isolation per connection, and the single ConfigMap publish whose rule is
+ * "any RECORDED outcome", not "a ready outcome".
+ *
+ * Deps are injected: no database, no cluster, no upstream. The production
+ * wiring is asserted where it belongs — the route suite for the endpoint and
+ * the real-Postgres suite for the schema.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { AllowedModelsConfigMapMaterializer } from '../llmAllowedModelsConfigMap.js'
+import {
+ type SubscriptionBrokerPort,
+ type SubscriptionCatalogSyncOutcome,
+ filterAddressableGrokConnections,
+ reconcileSubscriptionCatalogs,
+ runSubscriptionCatalogSyncTick,
+ startSubscriptionCatalogSyncCron,
+ stopSubscriptionCatalogSyncCron,
+} from '../subscriptionCatalogSyncCron.js'
+
+vi.mock('../../observability/logger.js', () => ({
+ rootLogger: { child: () => ({ info() {}, warn() {}, error() {}, debug() {} }) },
+}))
+
+const READY: SubscriptionCatalogSyncOutcome = { ok: true, catalogStatus: 'ready' }
+/** Recorded, but not ready: the row now carries `auth-rejected`. */
+const AUTH_REJECTED: SubscriptionCatalogSyncOutcome = { ok: false, catalogStatus: 'auth-rejected' }
+/** Nothing recorded: a concurrent writer won the revision fence. */
+const STALE: SubscriptionCatalogSyncOutcome = {
+ ok: false,
+ catalogStatus: 'never_synced',
+ reason: 'stale_revision',
+}
+
+/**
+ * A fake pool sharing one advisory-lock state across every client it hands out
+ * — the real cross-replica contract. `calls` records the lock lifecycle so a
+ * leaked SESSION lock is visible rather than inferred.
+ */
+function makeLockPool(
+ shared: { held: boolean },
+ calls: string[],
+ opts: { failUnlock?: boolean } = {}
+) {
+ const releaseArgs: Array<Error | boolean | undefined> = []
+ return {
+ releaseArgs,
+ connect: vi.fn(async () => {
+ const query = vi.fn(async (sql: string) => {
+ if (/pg_try_advisory_lock/.test(sql)) {
+ const acquired = !shared.held
+ if (acquired) shared.held = true
+ calls.push(acquired ? 'acquire:ok' : 'acquire:skip')
+ return { rows: [{ acquired }], rowCount: 1 }
+ }
+ if (/pg_advisory_unlock/.test(sql)) {
+ if (opts.failUnlock) {
+ calls.push('unlock:throw')
+ throw new Error('unlock failed')
+ }
+ shared.held = false
+ calls.push('unlock')
+ return { rows: [{ pg_advisory_unlock: true }], rowCount: 1 }
+ }
+ return { rows: [], rowCount: 0 }
+ })
+ const release = vi.fn((destroy?: Error | boolean) => {
+ releaseArgs.push(destroy)
+ if (destroy) {
+ shared.held = false
+ calls.push('release:destroy')
+ } else {
+ calls.push('release')
+ }
+ })
+ return { query, release }
+ }),
+ }
+}
+
+function makePort(
+ broker: SubscriptionBrokerPort['broker'],
+ rows: Array<{ connectionKey: string; status: string }>,
+ sync: (connectionKey: string) => Promise<SubscriptionCatalogSyncOutcome>,
+ enabled = true
+): SubscriptionBrokerPort & {
+ listConnections: ReturnType<typeof vi.fn>
+ syncCatalog: ReturnType<typeof vi.fn>
+} {
+ return {
+ broker,
+ enabled,
+ listConnections: vi.fn(async () => rows),
+ syncCatalog: vi.fn(sync),
+ }
+}
+
+function makeMaterializer(): AllowedModelsConfigMapMaterializer & {
+ materialize: ReturnType<typeof vi.fn>
+} {
+ return { materialize: vi.fn(async () => undefined) }
+}
+
+afterEach(() => {
+ stopSubscriptionCatalogSyncCron()
+ vi.useRealTimers()
+})
+
+describe('subscription catalog sync tick — advisory lock', () => {
+ it('runs the reconciliation and releases the lock when it acquires it', async () => {
+ const shared = { held: false }
+ const calls: string[] = []
+ const connector = makeLockPool(shared, calls)
+ const sync = vi.fn(async () => ({
+ synced: 1,
+ degraded: 0,
+ raced: 0,
+ failed: 0,
+ skipped: 0,
+ published: 'published' as const,
+ }))
+
+ const result = await runSubscriptionCatalogSyncTick({ connector, sync })
+
+ expect(result).toEqual({ skippedLock: false, ran: true, errored: false })
+ expect(sync).toHaveBeenCalledTimes(1)
+ expect(calls).toEqual(['acquire:ok', 'unlock', 'release'])
+ expect(shared.held).toBe(false)
+ })
+
+ it('skips the tick without syncing when another replica holds the lock', async () => {
+ const shared = { held: true }
+ const calls: string[] = []
+ const connector = makeLockPool(shared, calls)
+ const sync = vi.fn()
+
+ const result = await runSubscriptionCatalogSyncTick({ connector, sync })
+
+ expect(result).toEqual({ skippedLock: true, ran: false, errored: false })
+ // Liveness witness: the tick did reach the lock and was refused it, so the
+ // un-called sync is a skip and not an unreached code path.
+ expect(calls).toEqual(['acquire:skip', 'release'])
+ expect(sync).not.toHaveBeenCalled()
+ // The other replica's lock is untouched.
+ expect(shared.held).toBe(true)
+ })
+
+ it('destroys the connection when the unlock itself fails, so the session lock cannot leak', async () => {
+ const shared = { held: false }
+ const calls: string[] = []
+ const connector = makeLockPool(shared, calls, { failUnlock: true })
+ const sync = vi.fn(async () => ({
+ synced: 0,
+ degraded: 0,
+ raced: 0,
+ failed: 0,
+ skipped: 0,
+ published: 'skipped' as const,
+ }))
+
+ await runSubscriptionCatalogSyncTick({ connector, sync })
+
+ expect(calls).toEqual(['acquire:ok', 'unlock:throw', 'release:destroy'])
+ expect(connector.releaseArgs).toHaveLength(1)
+ expect(connector.releaseArgs[0]).toBeInstanceOf(Error)
+ expect(shared.held).toBe(false)
+ })
+
+ it('reports a failing reconciliation without throwing, and still releases the lock', async () => {
+ const shared = { held: false }
+ const calls: string[] = []
+ const connector = makeLockPool(shared, calls)
+ const sync = vi.fn(async () => {
+ throw new Error('reconciliation exploded')
+ })
+
+ const result = await runSubscriptionCatalogSyncTick({ connector, sync })
+
+ expect(result).toEqual({ skippedLock: false, ran: false, errored: true })
+ expect(calls).toEqual(['acquire:ok', 'unlock', 'release'])
+ expect(shared.held).toBe(false)
+ })
+})
+
+describe('subscription catalog reconciliation — skip rules', () => {
+ it('skips a broker whose deployment gate is off without listing its connections', async () => {
+ const codex = makePort(
+ 'codex-subscription',
+ [{ connectionKey: 'a', status: 'connected' }],
+ async () => READY
+ )
+ const grok = makePort(
+ 'grok-subscription',
+ [{ connectionKey: 'b', status: 'connected' }],
+ async () => READY,
+ false
+ )
+ const materializer = makeMaterializer()
+
+ const result = await reconcileSubscriptionCatalogs({ brokers: [codex, grok], materializer })
+
+ // Liveness witness: the enabled broker ran, so the loop was entered and the
+ // disabled broker was skipped by its gate, not by an unreached path.
+ expect(codex.syncCatalog).toHaveBeenCalledWith('a')
+ expect(grok.listConnections).not.toHaveBeenCalled()
+ expect(grok.syncCatalog).not.toHaveBeenCalled()
+ expect(result.synced).toBe(1)
+ })
+
+ it('syncs only grants whose status is connected', async () => {
+ const rows = [
+ { connectionKey: 'disconnected-key', status: 'disconnected' },
+ { connectionKey: 'connecting-key', status: 'connecting' },
+ { connectionKey: 'reauth-key', status: 'reauth_required' },
+ { connectionKey: 'connected-key', status: 'connected' },
+ ]
+ const grok = makePort('grok-subscription', rows, async () => READY)
+ const materializer = makeMaterializer()
+
+ const result = await reconcileSubscriptionCatalogs({ brokers: [grok], materializer })
+
+ // Liveness witness: the connected sibling in the SAME list was synced, so
+ // the three unsynced rows were filtered, not merely never reached.
+ expect(grok.syncCatalog.mock.calls.map(call => call[0])).toEqual(['connected-key'])
+ expect(result.skipped).toBe(3)
+ expect(result.synced).toBe(1)
+ })
+
+ it('drops archived Grok tombstone keys that sit outside the key grammar', () => {
+ // The key grammar is a DNS label (`grokSubscriptionSchema.ts:4`), so the
+ // archive suffix `~revoked~<id>` puts a tombstone outside it by construction.
+ const rows = [
+ { connectionKey: 'grok-primary', status: 'connected' },
+ { connectionKey: 'grok-primary~revoked~91f3', status: 'revoked' },
+ ]
+
+ expect(filterAddressableGrokConnections(rows)).toEqual([
+ { connectionKey: 'grok-primary', status: 'connected' },
+ ])
+ })
+})
+
+describe('subscription catalog reconciliation — isolation and outcomes', () => {
+ it('keeps going after one connection throws, and counts it as failed', async () => {
+ const rows = [
+ { connectionKey: 'first', status: 'connected' },
+ { connectionKey: 'boom', status: 'connected' },
+ { connectionKey: 'last', status: 'connected' },
+ ]
+ const codex = makePort('codex-subscription', rows, async key => {
+ if (key === 'boom') throw new Error('upstream refused the connection')
+ return READY
+ })
+ const materializer = makeMaterializer()
+
+ const result = await reconcileSubscriptionCatalogs({ brokers: [codex], materializer })
+
+ expect(codex.syncCatalog.mock.calls.map(call => call[0])).toEqual(['first', 'boom', 'last'])
+ expect(result).toMatchObject({ synced: 2, failed: 1, raced: 0, degraded: 0 })
+ })
+
+ it('counts a raced revision or a held refresh lock as transient, not as a failure', async () => {
+ const rows = [
+ { connectionKey: 'raced', status: 'connected' },
+ { connectionKey: 'locked', status: 'connected' },
+ ]
+ const grok = makePort('grok-subscription', rows, async key =>
+ key === 'raced'
+ ? STALE
+ : { ok: false, catalogStatus: 'never_synced', reason: 'refresh_in_flight' }
+ )
+ const materializer = makeMaterializer()
+
+ const result = await reconcileSubscriptionCatalogs({ brokers: [grok], materializer })
+
+ expect(result).toMatchObject({ raced: 2, failed: 0, synced: 0, degraded: 0 })
+ })
+})
+
+describe('subscription catalog reconciliation — ConfigMap publish', () => {
+ it('publishes once after the loop, not once per connection', async () => {
+ const rows = [
+ { connectionKey: 'one', status: 'connected' },
+ { connectionKey: 'two', status: 'connected' },
+ ]
+ const codex = makePort('codex-subscription', rows, async () => READY)
+ const grok = makePort(
+ 'grok-subscription',
+ [{ connectionKey: 'three', status: 'connected' }],
+ async () => READY
+ )
+ const materializer = makeMaterializer()
+
+ const result = await reconcileSubscriptionCatalogs({ brokers: [codex, grok], materializer })
+
+ expect(result.synced).toBe(3)
+ expect(materializer.materialize).toHaveBeenCalledTimes(1)
+ expect(result.published).toBe('published')
+ })
+
+ it('publishes a recorded NON-ready outcome, because the row now carries that status', async () => {
+ const codex = makePort(
+ 'codex-subscription',
+ [{ connectionKey: 'rejected', status: 'connected' }],
+ async () => AUTH_REJECTED
+ )
+ const materializer = makeMaterializer()
+
+ const result = await reconcileSubscriptionCatalogs({ brokers: [codex], materializer })
+
+ expect(result).toMatchObject({ synced: 0, degraded: 1, published: 'published' })
+ expect(materializer.materialize).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not publish when nothing recorded an outcome', async () => {
+ const codex = makePort(
+ 'codex-subscription',
+ [
+ { connectionKey: 'skipped', status: 'reauth_required' },
+ { connectionKey: 'raced', status: 'connected' },
+ ],
+ async () => STALE
+ )
+ const materializer = makeMaterializer()
+
+ const result = await reconcileSubscriptionCatalogs({ brokers: [codex], materializer })
+
+ // Liveness witness: the loop ran and reached the broker — one row was
+ // skipped by status and the other really was synced and raced — so the
+ // absent publish is the rule under test, not an unreached path.
+ expect(codex.listConnections).toHaveBeenCalledTimes(1)
+ expect(codex.syncCatalog).toHaveBeenCalledWith('raced')
+ expect(result).toMatchObject({ skipped: 1, raced: 1 })
+ expect(materializer.materialize).not.toHaveBeenCalled()
+ expect(result.published).toBe('skipped')
+ })
+
+ it('records the tick as failed when the publish itself fails, without throwing', async () => {
+ const codex = makePort(
+ 'codex-subscription',
+ [{ connectionKey: 'one', status: 'connected' }],
+ async () => READY
+ )
+ const materializer = makeMaterializer()
+ materializer.materialize.mockRejectedValueOnce(new Error('configmap write failed'))
+
+ await expect(reconcileSubscriptionCatalogs({ brokers: [codex], materializer })).rejects.toThrow(
+ /configmap write failed/
+ )
+
+ // The catalog rows were already written; only the publish failed. The tick
+ // surfaces it (runSubscriptionCatalogSyncTick turns it into errored:true)
+ // instead of reporting a clean reconciliation.
+ expect(codex.syncCatalog).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('subscription catalog cron scheduling', () => {
+ it('runs a first jittered tick and then one per interval, with unref()d handles', async () => {
+ vi.useFakeTimers()
+ const shared = { held: false }
+ const calls: string[] = []
+ const connector = makeLockPool(shared, calls)
+ const sync = vi.fn(async () => ({
+ synced: 0,
+ degraded: 0,
+ raced: 0,
+ failed: 0,
+ skipped: 0,
+ published: 'skipped' as const,
+ }))
+
+ startSubscriptionCatalogSyncCron({ connector, sync }, 60_000)
+
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(sync).toHaveBeenCalledTimes(1)
+
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(sync).toHaveBeenCalledTimes(2)
+
+ stopSubscriptionCatalogSyncCron()
+ await vi.advanceTimersByTimeAsync(120_000)
+ expect(sync).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/control-api/src/services/subscriptionCatalogSyncCron.ts b/control-api/src/services/subscriptionCatalogSyncCron.ts
new file mode 100644
index 000000000..a821ebd92
--- /dev/null
+++ b/control-api/src/services/subscriptionCatalogSyncCron.ts
@@ -0,0 +1,451 @@
+/**
+ * Subscription catalog reconciliation cron.
+ *
+ * A subscription grant's catalog (`codex_catalog_models`, `grok_catalog_models`)
+ * is written during the OAuth handshake and never again on its own. A model the
+ * vendor publishes afterwards therefore stays invisible to that connection —
+ * while the API-key provider of the SAME vendor picks it up from the discovery
+ * sync — until an operator asks for it. This cron closes that gap by re-running
+ * the very same `runCodexCatalogSync` / `runGrokCatalogSync` the connect flow
+ * and the manual `POST .../catalog/sync` endpoint drive. No HTTP hop, no new
+ * auth, no second write path.
+ *
+ * Hazard handling follows `llmCatalogSyncCron.ts`, which is the reference
+ * implementation for every one of them:
+ *
+ * - Cross-replica dedup through a SESSION-scoped
+ * `pg_try_advisory_lock(hashtext('subscription-catalog-sync-cron-v1'))` on a
+ * dedicated client. A session lock is NOT released by COMMIT nor by returning
+ * the connection to the pool, so the `finally` unlocks explicitly and, when
+ * the unlock itself fails, DESTROYS the connection (`release(err)`) — the only
+ * remaining way to end the session and free the lock. A leaked lock would
+ * wedge every future tick.
+ * - First tick after random jitter, then `setInterval`; both handles `unref()`'d,
+ * start is not awaited by boot, and errors are logged but never thrown.
+ * - The reconciliation closure is injected by `main.ts`, because publishing the
+ * allowlist ConfigMap needs the K8s gateway and this module owns none.
+ *
+ * Cost discipline: every tick issues one upstream catalog call PER CONNECTION,
+ * and a Grok refresh inside the 5-minute skew ROTATES the refresh token. A short
+ * interval is an abuse risk, not a freshness win — hence the conservative
+ * default and the floor enforced in `config.ts`.
+ */
+import { config } from '../config.js'
+import { pool } from '../db.js'
+import { deriveOAuthEncryptionKey } from '../oauth/encryption.js'
+import { rootLogger } from '../observability/logger.js'
+import { createCodexCatalogTransportFromEnv } from './codexSubscriptionCatalog.js'
+import { listLiveCodexSubscriptionConnections } from './codexSubscriptionConnection.js'
+import { runCodexCatalogSync } from './codexSubscriptionOAuth.js'
+import {
+ buildCodexBrowserRedirectUri,
+ resolveCodexControlUiBaseUrl,
+} from './codexSubscriptionRedirectUri.js'
+import { createGrokCatalogTransportFromEnv } from './grokSubscriptionCatalog.js'
+import {
+ assertGrokConnectionKey,
+ listLiveGrokSubscriptionConnections,
+} from './grokSubscriptionConnection.js'
+import { runGrokCatalogSync } from './grokSubscriptionOAuth.js'
+import type { AllowedModelsConfigMapMaterializer } from './llmAllowedModelsConfigMap.js'
+import { publishAllowedModelsConfigMapAfterGrantChange } from './llmAllowedModelsConfigMap.js'
+
+const log = rootLogger.child({ service: 'subscription_catalog_sync_cron' })
+
+// Session-scoped advisory lock key, distinct from every other cron's. The `-v1`
+// suffix leaves room to re-key if the tick's semantics ever change.
+const CRON_LOCK_KEY_SQL = "hashtext('subscription-catalog-sync-cron-v1')"
+
+export type SubscriptionBroker = 'codex-subscription' | 'grok-subscription'
+
+/**
+ * What `runCodexCatalogSync` / `runGrokCatalogSync` return, reduced to the two
+ * fields this module decides on. `catalogStatus: 'never_synced'` is the
+ * services' own signal that NOTHING was persisted for the connection; any other
+ * status means the row now carries that outcome.
+ */
+export type SubscriptionCatalogSyncOutcome =
+ | { ok: true; catalogStatus: 'ready' }
+ | { ok: false; catalogStatus: string; reason?: string }
+
+export type SubscriptionConnectionRow = { connectionKey: string; status: string }
+
+/** One broker's side of a tick. Production builds it from config + db + transport. */
+export interface SubscriptionBrokerPort {
+ broker: SubscriptionBroker
+ /** The deployment gate (`config.*SubscriptionEnabled`). Off = the broker is dark. */
+ enabled: boolean
+ listConnections(): Promise<SubscriptionConnectionRow[]>
+ syncCatalog(connectionKey: string): Promise<SubscriptionCatalogSyncOutcome>
+}
+
+export interface SubscriptionCatalogReconcileDeps {
+ brokers: SubscriptionBrokerPort[]
+ /** Undefined = no ConfigMap writer, so the publish is a local no-op (unit tests). */
+ materializer: AllowedModelsConfigMapMaterializer | undefined
+}
+
+export interface SubscriptionCatalogReconcileResult {
+ /** Connections whose catalog is now `ready`. */
+ synced: number
+ /** Connections that RECORDED a non-ready outcome (`auth-rejected`, `unavailable`). */
+ degraded: number
+ /** Raced or lock-held; nothing recorded, resolves on the next tick. */
+ raced: number
+ failed: number
+ /** Gate off, not addressable, or `status !== 'connected'`. */
+ skipped: number
+ published: 'published' | 'skipped'
+}
+
+/**
+ * Transient, not failures. `stale_revision` means a concurrent manual sync won
+ * the `credential_revision AND catalog_revision` fence — its write landed, ours
+ * did not, and the catalog is fresh either way. `refresh_in_flight` means the
+ * per-connection 30s refresh lock was held. Both clear by themselves.
+ */
+const RACED_REASONS = new Set(['stale_revision', 'refresh_in_flight'])
+
+/**
+ * Migration 0113_grok_subscription_terminal_connection_key archives superseded
+ * tombstones as `<key>~revoked~<id>`, outside the key grammar. `listLive*`
+ * filters `revoked_at IS NULL`, but an archived row can still surface here; a
+ * sync call on it would only raise `invalid_connection_key`. The admin router
+ * applies the same filter for the same reason.
+ */
+export function filterAddressableGrokConnections<T extends SubscriptionConnectionRow>(
+ rows: T[]
+): T[] {
+ return rows.filter(row => {
+ try {
+ assertGrokConnectionKey(row.connectionKey)
+ return true
+ } catch {
+ return false
+ }
+ })
+}
+
+/**
+ * Reconcile every live, connected grant of every enabled broker, then publish
+ * the runtime allowlist ONCE.
+ *
+ * A per-connection failure is isolated: one rejected grant must not cost the
+ * others their sync. The publish, in contrast, is not isolated — a catalog that
+ * changed in Postgres but not in the ConfigMap is a divergence the runtime hosts
+ * would serve until the next mutation, so the rejection propagates and the tick
+ * reports `errored`.
+ */
+export async function reconcileSubscriptionCatalogs(
+ deps: SubscriptionCatalogReconcileDeps
+): Promise<SubscriptionCatalogReconcileResult> {
+ let synced = 0
+ let degraded = 0
+ let raced = 0
+ let failed = 0
+ let skipped = 0
+
+ for (const port of deps.brokers) {
+ if (!port.enabled) {
+ log.debug(
+ { event: 'subscription_catalog_sync_broker_disabled', broker: port.broker },
+ `${port.broker} is disabled for this deployment; skipping`
+ )
+ continue
+ }
+ const rows = await port.listConnections()
+ for (const row of rows) {
+ // Every narrower rule is wrong: `disconnected` makes the catalog sync
+ // throw `not_connected`, `connecting` throws `no_grant` inside the
+ // ensure-fresh path, and `reauth_required` needs a human this cron
+ // cannot summon.
+ if (row.status !== 'connected') {
+ skipped += 1
+ continue
+ }
+ try {
+ const outcome = await port.syncCatalog(row.connectionKey)
+ if (outcome.ok) {
+ synced += 1
+ } else if (outcome.catalogStatus !== 'never_synced') {
+ degraded += 1
+ log.info(
+ {
+ event: 'subscription_catalog_sync_degraded',
+ broker: port.broker,
+ connectionKey: row.connectionKey,
+ catalogStatus: outcome.catalogStatus,
+ },
+ `${port.broker} catalog recorded a non-ready outcome`
+ )
+ } else if (outcome.reason && RACED_REASONS.has(outcome.reason)) {
+ raced += 1
+ } else {
+ failed += 1
+ log.warn(
+ {
+ event: 'subscription_catalog_sync_failed',
+ broker: port.broker,
+ connectionKey: row.connectionKey,
+ reason: outcome.reason,
+ },
+ `${port.broker} catalog sync recorded nothing`
+ )
+ }
+ } catch (err) {
+ failed += 1
+ log.warn(
+ {
+ event: 'subscription_catalog_sync_threw',
+ broker: port.broker,
+ connectionKey: row.connectionKey,
+ err: err instanceof Error ? err.message : String(err),
+ },
+ `${port.broker} catalog sync threw; continuing with the remaining connections`
+ )
+ }
+ }
+ }
+
+ // Publish on ANY recorded outcome, ready or not. A tick that moves a grant to
+ // `reauth_required` persists that status, the ConfigMap carries it in its
+ // annotations, and the materializer's own contract requires the publish for
+ // "recorded non-ready outcomes". Publishing only on `ready` would leave the
+ // runtime hosts serving a grant the control plane already knows is broken.
+ const recorded = synced + degraded
+ const published =
+ recorded > 0
+ ? await publishAllowedModelsConfigMapAfterGrantChange(deps.materializer)
+ : 'skipped'
+
+ return { synced, degraded, raced, failed, skipped, published }
+}
+
+function cronDbClient() {
+ return { query: (text: string, values?: unknown[]) => pool.query(text, values) }
+}
+
+/**
+ * Production wiring for both brokers, built at TICK time rather than at module
+ * load or boot.
+ *
+ * The laziness is load-bearing for Codex: `normalizeControlUiOrigin` throws on a
+ * malformed, non-http or path-bearing `CONTROL_API_CONTROL_UI_BASE_URL`, and a
+ * throw at boot would take control-api down instead of failing one tick. The
+ * redirect URI is built only when Codex is enabled, so a bad value cannot cost
+ * Grok its reconciliation either. `runCodexCatalogSync` reaches the refresh path
+ * only — `exchangeRefreshToken` sends no `redirect_uri` — but a real value is
+ * built anyway rather than a placeholder that would be wrong the day the path
+ * changes.
+ */
+export function createSubscriptionBrokerPorts(): SubscriptionBrokerPort[] {
+ const db = cronDbClient()
+ const encryptionKey = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+
+ const codexTransport = createCodexCatalogTransportFromEnv()
+ const codexRedirectUri = config.codexSubscriptionEnabled
+ ? buildCodexBrowserRedirectUri(resolveCodexControlUiBaseUrl(config.controlUiBaseUrl, undefined))
+ : ''
+ const codex: SubscriptionBrokerPort = {
+ broker: 'codex-subscription',
+ enabled: config.codexSubscriptionEnabled,
+ listConnections: () => listLiveCodexSubscriptionConnections(db),
+ syncCatalog: connectionKey =>
+ runCodexCatalogSync(
+ {
+ db,
+ encryptionKey,
+ fetchFn: fetch,
+ clientId: config.codexOAuthClientId,
+ redirectUri: codexRedirectUri,
+ enabled: config.codexSubscriptionEnabled,
+ connectionKey,
+ },
+ connectionKey,
+ codexTransport
+ ),
+ }
+
+ const grokTransport = createGrokCatalogTransportFromEnv()
+ const grok: SubscriptionBrokerPort = {
+ broker: 'grok-subscription',
+ enabled: config.grokSubscriptionEnabled,
+ listConnections: async () =>
+ filterAddressableGrokConnections(await listLiveGrokSubscriptionConnections(db)),
+ syncCatalog: connectionKey =>
+ runGrokCatalogSync(
+ {
+ db,
+ encryptionKey,
+ fetchFn: fetch,
+ clientId: config.grokOAuthClientId,
+ enabled: config.grokSubscriptionEnabled,
+ connectionKey,
+ },
+ connectionKey,
+ grokTransport
+ ),
+ }
+
+ return [codex, grok]
+}
+
+/**
+ * The closure `main.ts` hands to the cron. It owns no gateway, so the caller
+ * passes the materializer the admin routes already use.
+ */
+export function reconcileSubscriptionCatalogsFromEnv(
+ materializer: AllowedModelsConfigMapMaterializer | undefined
+): Promise<SubscriptionCatalogReconcileResult> {
+ return reconcileSubscriptionCatalogs({ brokers: createSubscriptionBrokerPorts(), materializer })
+}
+
+/**
+ * Minimal client shape for the advisory-lock session. pg's PoolClient satisfies
+ * it. `release` takes pg's optional destroy argument: a truthy value (an Error)
+ * DESTROYS the connection instead of returning it to the pool.
+ */
+type LockClient = {
+ query: (text: string, values?: unknown[]) => Promise<{ rows: unknown[]; rowCount: number | null }>
+ release: (destroy?: Error | boolean) => void
+}
+
+export interface SubscriptionCatalogSyncCronDeps {
+ connector?: { connect: () => Promise<LockClient> }
+ /** Injected by `main.ts` so the reconciliation can reach the gateway's materializer. */
+ sync: () => Promise<SubscriptionCatalogReconcileResult>
+}
+
+export interface SubscriptionCatalogSyncTickResult {
+ skippedLock: boolean
+ ran: boolean
+ errored: boolean
+}
+
+/**
+ * One tick: acquire the session advisory lock, reconcile, release. Never throws
+ * — a failure is logged and reported in the result. The lock is released in
+ * `finally` whether the tick ran, skipped, or failed.
+ */
+export async function runSubscriptionCatalogSyncTick(
+ deps: SubscriptionCatalogSyncCronDeps
+): Promise<SubscriptionCatalogSyncTickResult> {
+ const connector = deps.connector ?? pool
+ let lockClient: LockClient | undefined
+ let locked = false
+ try {
+ lockClient = await connector.connect()
+ const lockRes = await lockClient.query(
+ `SELECT pg_try_advisory_lock(${CRON_LOCK_KEY_SQL}) AS acquired`
+ )
+ locked = (lockRes.rows[0] as { acquired?: boolean } | undefined)?.acquired === true
+ if (!locked) {
+ log.debug(
+ { event: 'subscription_catalog_sync_cron_skipped_lock' },
+ 'subscription catalog sync tick skipped: advisory lock held by another replica'
+ )
+ return { skippedLock: true, ran: false, errored: false }
+ }
+
+ const result = await deps.sync()
+ log.info(
+ {
+ event: 'subscription_catalog_sync_cron_tick',
+ synced: result.synced,
+ degraded: result.degraded,
+ raced: result.raced,
+ failed: result.failed,
+ skipped: result.skipped,
+ published: result.published,
+ },
+ `subscription catalog sync tick complete (synced=${result.synced}, degraded=${result.degraded}, raced=${result.raced}, failed=${result.failed}, skipped=${result.skipped}, ${result.published})`
+ )
+ return { skippedLock: false, ran: true, errored: false }
+ } catch (err) {
+ log.error(
+ {
+ event: 'subscription_catalog_sync_cron_error',
+ err: err instanceof Error ? err.message : String(err),
+ },
+ 'subscription catalog sync tick failed'
+ )
+ return { skippedLock: false, ran: false, errored: true }
+ } finally {
+ if (lockClient) {
+ let destroyed = false
+ if (locked) {
+ try {
+ await lockClient.query(`SELECT pg_advisory_unlock(${CRON_LOCK_KEY_SQL})`)
+ } catch (unlockErr) {
+ // The session lock is freed only by an explicit unlock or by CLOSING
+ // the session. The unlock failed, so destroy the connection: a plain
+ // release() would hand a live session still holding the lock back to
+ // the pool and wedge every future tick.
+ const asError = unlockErr instanceof Error ? unlockErr : new Error(String(unlockErr))
+ log.warn(
+ { event: 'subscription_catalog_sync_cron_unlock_failed', err: asError.message },
+ 'pg_advisory_unlock failed; destroying the connection to release the session lock'
+ )
+ lockClient.release(asError)
+ destroyed = true
+ }
+ }
+ if (!destroyed) lockClient.release()
+ }
+ }
+}
+
+let intervalHandle: ReturnType<typeof setInterval> | null = null
+let firstRunHandle: ReturnType<typeof setTimeout> | null = null
+
+/**
+ * Upper bound of the random delay before the first tick. Keeps the replicas of
+ * one rollout from contending for the advisory lock at the same instant; the
+ * lock already makes a collision a harmless no-op.
+ */
+export const SUBSCRIPTION_CATALOG_SYNC_FIRST_RUN_JITTER_MS = 5_000
+
+export function startSubscriptionCatalogSyncCron(
+ deps: SubscriptionCatalogSyncCronDeps,
+ intervalMs: number
+): void {
+ if (intervalHandle || firstRunHandle) return
+
+ const run = (): void => {
+ // runSubscriptionCatalogSyncTick never rejects; the catch is defensive so an
+ // unexpected throw can never kill the timer.
+ void runSubscriptionCatalogSyncTick(deps).catch(err => {
+ log.error(
+ {
+ event: 'subscription_catalog_sync_cron_unhandled',
+ err: err instanceof Error ? err.message : String(err),
+ },
+ 'unhandled error in subscription catalog sync cron'
+ )
+ })
+ }
+
+ const firstDelay = Math.floor(Math.random() * SUBSCRIPTION_CATALOG_SYNC_FIRST_RUN_JITTER_MS)
+ firstRunHandle = setTimeout(() => {
+ firstRunHandle = null
+ run()
+ intervalHandle = setInterval(run, intervalMs)
+ intervalHandle.unref()
+ }, firstDelay)
+ firstRunHandle.unref()
+ log.info(
+ { event: 'subscription_catalog_sync_cron_started', intervalMs, firstRunInMs: firstDelay },
+ 'subscription catalog sync cron started'
+ )
+}
+
+export function stopSubscriptionCatalogSyncCron(): void {
+ if (firstRunHandle) {
+ clearTimeout(firstRunHandle)
+ firstRunHandle = null
+ }
+ if (intervalHandle) {
+ clearInterval(intervalHandle)
+ intervalHandle = null
+ }
+}
diff --git a/control-api/test/routes.admin.grokSubscription.test.ts b/control-api/test/routes.admin.grokSubscription.test.ts
index ce301d8ab..b5aecace1 100644
--- a/control-api/test/routes.admin.grokSubscription.test.ts
+++ b/control-api/test/routes.admin.grokSubscription.test.ts
@@ -571,6 +571,10 @@ describe('admin Grok subscription routes', () => {
expect(materialize).toHaveBeenCalledTimes(1)
})
+ // `catalogStatus: 'never_synced'` is the service's own signal that NOTHING
+ // was persisted for the connection: no grant, a lost revision fence, a held
+ // refresh lock, an OAuth error before the catalog call. There is no new
+ // state for the ConfigMap to carry, so the endpoint must not write one.
it.each([
[{ reason: 'no_grant' }, 404, { error: 'no_grant' }],
[{ reason: 'disabled' }, 404, { error: 'disabled' }],
@@ -578,29 +582,69 @@ describe('admin Grok subscription routes', () => {
[{ reason: 'refresh_in_flight' }, 409, { error: 'refresh_in_flight' }],
[{ reason: 'reauth_required' }, 400, { error: 'reauth_required' }],
[{ reason: 'provider_unavailable' }, 400, { error: 'provider_unavailable' }],
+ ])(
+ 'maps a sync that recorded nothing %j to %i without publishing',
+ async (failure, status, body) => {
+ const materialize = vi.fn(async () => {})
+ grokOAuth.runGrokCatalogSync.mockResolvedValue({
+ ok: false,
+ catalogStatus: 'never_synced',
+ ...failure,
+ })
+ const res = await request(makeApp(makeGateway(materialize))).post(
+ `${GROK}/connections/team-grok/catalog/sync`
+ )
+ expect(res.status).toBe(status)
+ expect(res.body).toEqual(body)
+ // Liveness witness: the sync really ran and really failed with this
+ // reason, so the absent publish is the rule and not an unreached path.
+ expect(grokOAuth.runGrokCatalogSync).toHaveBeenCalledTimes(1)
+ expect(materialize).not.toHaveBeenCalled()
+ }
+ )
+
+ // A non-ready catalogStatus means the OPPOSITE: the sync reached xAI, the
+ // answer was refused or unavailable, and the connection row now carries
+ // that outcome. mcp-host and HCC never read Postgres, so withholding the
+ // publish leaves the runtime serving a grant the control plane already
+ // knows is broken. The Codex branch of this same handler publishes before
+ // its 503 for exactly this reason.
+ it.each([
[
{ reason: 'catalog_sync_failed', catalogStatus: 'unavailable' },
- 503,
{ error: 'catalog_sync_failed', outcome: 'unavailable' },
],
[
{ catalogStatus: 'auth-rejected' },
- 503,
{ error: 'catalog_sync_failed', outcome: 'auth-rejected' },
],
- ])('maps a failed sync %j to %i without publishing', async (failure, status, body) => {
+ ])('publishes the recorded non-ready outcome %j and answers 503', async (failure, body) => {
const materialize = vi.fn(async () => {})
- grokOAuth.runGrokCatalogSync.mockResolvedValue({
- ok: false,
- catalogStatus: 'never_synced',
- ...failure,
- })
+ grokOAuth.runGrokCatalogSync.mockResolvedValue({ ok: false, ...failure })
const res = await request(makeApp(makeGateway(materialize))).post(
`${GROK}/connections/team-grok/catalog/sync`
)
- expect(res.status).toBe(status)
+ expect(res.status).toBe(503)
expect(res.body).toEqual(body)
- expect(materialize).not.toHaveBeenCalled()
+ expect(materialize).toHaveBeenCalledTimes(1)
+ })
+
+ it('answers 503 configmap_write_failed when the recorded outcome cannot be published', async () => {
+ grokOAuth.runGrokCatalogSync.mockResolvedValue({
+ ok: false,
+ catalogStatus: 'auth-rejected',
+ })
+ const res = await request(
+ makeApp(
+ makeGateway(async () => {
+ throw new Error('apiserver down')
+ })
+ )
+ ).post(`${GROK}/connections/team-grok/catalog/sync`)
+ expect(res.status).toBe(503)
+ // The ConfigMap failure wins over the catalog outcome: the operator must
+ // know the runtime snapshot is stale, which is the actionable half.
+ expect(res.body.error).toBe('configmap_write_failed')
})
})
diff --git a/control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts b/control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts
new file mode 100644
index 000000000..418b0b2fa
--- /dev/null
+++ b/control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts
@@ -0,0 +1,378 @@
+/**
+ * T1 for the subscription catalog reconciliation cron.
+ *
+ * The unit suite proves the tick's decision table against doubles. This one
+ * proves the half the doubles cannot: that a tick driven through the real
+ * broker port lands rows in `grok_catalog_models`, rebuilds the
+ * `grok-subscription` union in `llm_allowed_models`, stale-flags a model that
+ * vanished upstream, and stays idempotent across identical ticks.
+ *
+ * Everything below the xAI network boundary is real — OAuth refresh-token
+ * rotation, secret encryption, the revision-fenced outcome write, the
+ * transaction and the union rebuild. Only two things are doubled, and both are
+ * systems outside this process: xAI's HTTP endpoints (`GrokCatalogTransport`
+ * for the models call, `fetchFn` for the token call) and the Kubernetes
+ * ConfigMap writer.
+ */
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomBytes } from 'node:crypto'
+import { Pool } from 'pg'
+import { type DbClient, initDb } from '../src/db.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import {
+ type GrokCatalogTransport,
+ type GrokTransactionRunner,
+} from '../src/services/grokSubscriptionCatalog.js'
+import {
+ createNamedGrokSubscriptionConnection,
+ getSafeGrokSubscriptionConnection,
+ listLiveGrokSubscriptionConnections,
+} from '../src/services/grokSubscriptionConnection.js'
+import {
+ GROK_OAUTH_DEVICE_URL,
+ GROK_OAUTH_REVOKE_URL,
+ GROK_OAUTH_TOKEN_URL,
+ type GrokOAuthDeps,
+ pollGrokDevice,
+ runGrokCatalogSync,
+ startGrokDeviceConnect,
+} from '../src/services/grokSubscriptionOAuth.js'
+import type { AllowedModelsConfigMapMaterializer } from '../src/services/llmAllowedModelsConfigMap.js'
+import {
+ type SubscriptionBrokerPort,
+ filterAddressableGrokConnections,
+ reconcileSubscriptionCatalogs,
+} from '../src/services/subscriptionCatalogSyncCron.js'
+import './realPostgres.requirement.ts'
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+}
+
+function idTokenFor(subject: string): string {
+ return `hdr.${Buffer.from(JSON.stringify({ sub: subject })).toString('base64url')}.sig`
+}
+
+function jsonResponse(status: number, body: Record<string, unknown>): Response {
+ return { ok: status >= 200 && status < 300, status, json: async () => body } as Response
+}
+
+/**
+ * The xAI account behind every exchange in this suite. One subject for the
+ * device grant and for every later refresh, because they are one account: the
+ * refresh recomputes the fingerprint and compares it with the one the grant
+ * stored, so a subject that varied per exchange would read as an account swap
+ * and flip the connection to `reauth_required` before the catalog is touched.
+ */
+const GRANT_SUBJECT = 'subject-cron-grok'
+
+/**
+ * Simulated xAI device-authorization provider. The cron's tick finds an
+ * access token past its expiry and rotates the refresh token through this
+ * before it may read the catalog, so the rotation path is exercised, not
+ * bypassed.
+ */
+function simulatedGrokProvider(): typeof fetch {
+ let issued = 0
+ return (async (url: string | URL) => {
+ const target = String(url)
+ if (target === GROK_OAUTH_DEVICE_URL) {
+ issued += 1
+ return jsonResponse(200, {
+ device_code: `device-code-${issued}-${randomBytes(4).toString('hex')}`,
+ user_code: 'ABCD-EFGH',
+ verification_uri: 'https://auth.x.ai/activate',
+ expires_in: 900,
+ interval: 5,
+ })
+ }
+ if (target === GROK_OAUTH_TOKEN_URL) {
+ return jsonResponse(200, {
+ access_token: `access-${randomBytes(4).toString('hex')}`,
+ refresh_token: `refresh-${randomBytes(4).toString('hex')}`,
+ expires_in: 3600,
+ id_token: idTokenFor(GRANT_SUBJECT),
+ })
+ }
+ if (target === GROK_OAUTH_REVOKE_URL) return jsonResponse(200, {})
+ return jsonResponse(404, {})
+ }) as typeof fetch
+}
+
+function readyTransport(models: Array<{ model: string; contextWindowTokens?: number }>): {
+ transport: GrokCatalogTransport
+ calls: number[]
+} {
+ const calls: number[] = []
+ return {
+ calls,
+ transport: {
+ listModels: async () => {
+ calls.push(models.length)
+ return { outcome: 'ready', models }
+ },
+ },
+ }
+}
+
+type AllowedModelRow = {
+ model: string
+ enabled: boolean
+ stale: boolean
+ source: string
+ vendor: string | null
+ context_window_tokens: number | null
+}
+
+describeRealPostgres('Subscription catalog sync cron on real PostgreSQL', () => {
+ const database = `subscription_catalog_cron_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? `postgresql://postgres@${['127', '0', '0', '1'].join('.')}/postgres`,
+ database
+ )
+ let adminPool: Pool
+ let pool: Pool
+
+ const poolTransaction: GrokTransactionRunner = async work => {
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ const result = await work(client)
+ await client.query('COMMIT')
+ return result
+ } catch (err) {
+ await client.query('ROLLBACK').catch(() => undefined)
+ throw err
+ } finally {
+ client.release()
+ }
+ }
+
+ function oauthDeps(connectionKey: string, db: DbClient = pool): GrokOAuthDeps {
+ return {
+ db,
+ encryptionKey: KEY,
+ fetchFn: simulatedGrokProvider(),
+ clientId: 'b1a00492-073a-47ea-816f-4c329264a828',
+ enabled: true,
+ connectionKey,
+ withTransaction: poolTransaction,
+ }
+ }
+
+ /**
+ * The production Grok port, rebuilt over this suite's pool. Every collaborator
+ * except the transport is the one `createSubscriptionBrokerPorts` wires.
+ */
+ function grokPort(
+ transport: GrokCatalogTransport,
+ syncedKeys: string[] = []
+ ): SubscriptionBrokerPort {
+ return {
+ broker: 'grok-subscription',
+ enabled: true,
+ listConnections: async () =>
+ filterAddressableGrokConnections(await listLiveGrokSubscriptionConnections(pool)),
+ syncCatalog: key => {
+ syncedKeys.push(key)
+ return runGrokCatalogSync(oauthDeps(key), key, transport)
+ },
+ }
+ }
+
+ function recordingMaterializer(): {
+ materializer: AllowedModelsConfigMapMaterializer
+ calls: number[]
+ } {
+ const calls: number[] = []
+ return {
+ calls,
+ materializer: {
+ materialize: async () => {
+ calls.push(Date.now())
+ },
+ },
+ }
+ }
+
+ async function allowedModels(): Promise<AllowedModelRow[]> {
+ const result = await pool.query<AllowedModelRow>(
+ `SELECT model, enabled, stale, source, vendor, context_window_tokens
+ FROM llm_allowed_models
+ WHERE provider = 'grok-subscription'
+ ORDER BY model ASC`
+ )
+ return result.rows
+ }
+
+ async function catalogModels(
+ connectionId: string
+ ): Promise<Array<{ model: string; stale: boolean; enabled: boolean }>> {
+ const result = await pool.query<{ model: string; stale: boolean; enabled: boolean }>(
+ `SELECT model, stale, enabled
+ FROM grok_catalog_models
+ WHERE connection_id = $1
+ ORDER BY model ASC`,
+ [connectionId]
+ )
+ return result.rows
+ }
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ await initDb({ connect: () => pool.connect() })
+ }, 60_000)
+
+ afterAll(async () => {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ await adminPool.end()
+ }
+ })
+
+ it('a tick writes the broker catalog and rebuilds the grok-subscription allowlist', async () => {
+ const key = 'cron-grok-primary'
+ // The grant is created through the device flow the operator uses, not by
+ // writing credential rows: that is what leaves a fingerprint the cron's
+ // own refresh can match, and it is the state a real tick finds.
+ const started = await startGrokDeviceConnect(oauthDeps(key), 'connect')
+ const polled = await pollGrokDevice(oauthDeps(key), started.state)
+ expect(polled.status).toBe('connected')
+ const created = await getSafeGrokSubscriptionConnection(pool, key)
+ expect(created).toMatchObject({ status: 'connected', catalogStatus: 'never_synced' })
+ const { transport, calls } = readyTransport([
+ { model: 'grok-4-fast-reasoning', contextWindowTokens: 2_000_000 },
+ { model: 'grok-4' },
+ ])
+ const { materializer, calls: published } = recordingMaterializer()
+
+ const result = await reconcileSubscriptionCatalogs({
+ brokers: [grokPort(transport)],
+ materializer,
+ })
+
+ expect(result).toEqual({
+ synced: 1,
+ degraded: 0,
+ raced: 0,
+ failed: 0,
+ skipped: 0,
+ published: 'published',
+ })
+ expect(calls).toEqual([2])
+ expect(published).toHaveLength(1)
+ expect(await catalogModels(created!.id)).toEqual([
+ { model: 'grok-4', stale: false, enabled: true },
+ { model: 'grok-4-fast-reasoning', stale: false, enabled: true },
+ ])
+ expect(await allowedModels()).toEqual([
+ {
+ model: 'grok-4',
+ enabled: true,
+ stale: false,
+ source: 'discovery',
+ vendor: 'xAI',
+ context_window_tokens: null,
+ },
+ {
+ model: 'grok-4-fast-reasoning',
+ enabled: true,
+ stale: false,
+ source: 'discovery',
+ vendor: 'xAI',
+ context_window_tokens: 2_000_000,
+ },
+ ])
+ })
+
+ it('an identical second tick records a fresh outcome without duplicating rows', async () => {
+ const key = 'cron-grok-primary'
+ const before = await getSafeGrokSubscriptionConnection(pool, key)
+ expect(before).toMatchObject({ catalogStatus: 'ready' })
+ const { transport } = readyTransport([
+ { model: 'grok-4-fast-reasoning', contextWindowTokens: 2_000_000 },
+ { model: 'grok-4' },
+ ])
+ const { materializer } = recordingMaterializer()
+
+ const result = await reconcileSubscriptionCatalogs({
+ brokers: [grokPort(transport)],
+ materializer,
+ })
+
+ expect(result).toMatchObject({ synced: 1, failed: 0, published: 'published' })
+ // Liveness witness: the tick really re-ran the fenced write. Without it,
+ // "the rows did not change" would also hold for a tick that did nothing.
+ const after = await getSafeGrokSubscriptionConnection(pool, key)
+ expect(after?.catalogRevision).toBe((before?.catalogRevision ?? 0) + 1)
+ expect((await allowedModels()).map(row => row.model)).toEqual([
+ 'grok-4',
+ 'grok-4-fast-reasoning',
+ ])
+ })
+
+ it('a model that vanished upstream is stale-flagged in the catalog and disabled in the union', async () => {
+ const key = 'cron-grok-primary'
+ const connection = await getSafeGrokSubscriptionConnection(pool, key)
+ expect(connection).not.toBeNull()
+ const { transport, calls } = readyTransport([{ model: 'grok-4' }])
+ const { materializer } = recordingMaterializer()
+
+ const result = await reconcileSubscriptionCatalogs({
+ brokers: [grokPort(transport)],
+ materializer,
+ })
+
+ expect(result).toMatchObject({ synced: 1, failed: 0 })
+ expect(calls).toEqual([1])
+ expect(await catalogModels(connection!.id)).toEqual([
+ { model: 'grok-4', stale: false, enabled: true },
+ { model: 'grok-4-fast-reasoning', stale: true, enabled: true },
+ ])
+ expect(await allowedModels()).toEqual([
+ expect.objectContaining({ model: 'grok-4', enabled: true, stale: false }),
+ expect.objectContaining({ model: 'grok-4-fast-reasoning', enabled: false, stale: true }),
+ ])
+ })
+
+ it('a grant that is not connected is skipped and never reaches the broker', async () => {
+ const idle = 'cron-grok-idle'
+ await createNamedGrokSubscriptionConnection(pool, {
+ connectionKey: idle,
+ displayName: 'idle',
+ })
+ const { transport } = readyTransport([{ model: 'grok-4' }])
+ const syncedKeys: string[] = []
+ const { materializer } = recordingMaterializer()
+
+ const result = await reconcileSubscriptionCatalogs({
+ brokers: [grokPort(transport, syncedKeys)],
+ materializer,
+ })
+
+ // The negative claim is `idle` never being synced. Its witness is the
+ // connected grant in the same listing that WAS synced: a port that
+ // returned nothing at all would satisfy the exclusion for free.
+ expect(syncedKeys).toEqual(['cron-grok-primary'])
+ expect(result).toMatchObject({ synced: 1, skipped: 1, failed: 0 })
+ expect(await getSafeGrokSubscriptionConnection(pool, idle)).toMatchObject({
+ status: 'disconnected',
+ catalogStatus: 'never_synced',
+ })
+ })
+})
diff --git a/control-ui/components/CodexSubscriptionHub/index.tsx b/control-ui/components/CodexSubscriptionHub/index.tsx
index c00a6c475..10f295834 100644
--- a/control-ui/components/CodexSubscriptionHub/index.tsx
+++ b/control-ui/components/CodexSubscriptionHub/index.tsx
@@ -20,6 +20,7 @@ import {
pollCodexDevice,
revokeCodexSubscription,
startCodexDeviceConnect,
+ syncCodexSubscriptionCatalog,
} from '@lib/codexSubscription'
import {
type CodexSubscriptionCapability,
@@ -38,6 +39,7 @@ import {
pollGrokDevice,
revokeGrokSubscription,
startGrokDeviceConnect,
+ syncGrokSubscriptionCatalog,
} from '@lib/grokSubscription'
import {
type GrokSubscriptionCapability,
@@ -91,6 +93,30 @@ type HubListErrors = Record<HubBroker, string>
const NO_LIST_ERRORS: HubListErrors = { 'codex-subscription': '', 'grok-subscription': '' }
+// `POST .../connections/:key/catalog/sync` answers with a closed taxonomy the
+// operator can act on. Each code gets the action that resolves it; an unmapped
+// code keeps the API's own message, which carries the status and the code, so a
+// new server-side code is never flattened into a generic failure.
+function catalogSyncErrorMessage(err: unknown, brand: string): string {
+ const coded = err as Error & { code?: string; body?: Record<string, unknown> }
+ const outcome = typeof coded?.body?.outcome === 'string' ? coded.body.outcome : 'unknown'
+ switch (coded?.code) {
+ case 'disabled':
+ return `${brand} subscriptions are turned off for this deployment, so the catalog cannot be synced.`
+ case 'no_grant':
+ case 'not_connected':
+ return `This subscription no longer authorizes with ${brand}. Sign in again, then sync the catalog.`
+ case 'stale_revision':
+ return `The subscription changed while this sync ran. Reopen it to see the current catalog, then sync again.`
+ case 'refresh_in_flight':
+ return `Another ${brand} refresh is already running for this subscription. Wait a moment and sync again.`
+ case 'catalog_sync_failed':
+ return `The ${brand} catalog could not be reached (${outcome}). The stored models are unchanged.`
+ default:
+ return err instanceof Error ? err.message : `Could not sync the ${brand} catalog`
+ }
+}
+
function grantLabel(row: CodexSubscriptionConnectionView): string {
return row.displayName || row.connectionKey
}
@@ -542,6 +568,40 @@ export function CodexSubscriptionHub() {
}
}
+ // Re-reads the broker's catalog on demand. The grant's catalog is otherwise
+ // only refreshed while connecting, so a model the vendor published after that
+ // handshake stays invisible until an operator asks for this.
+ async function handleSyncCatalog(row: HubConnection) {
+ const grok = row.broker === 'grok-subscription'
+ const brand = HUB_PROVIDER_COPY[row.broker].brand
+ setBusyKey(hubRowId(row))
+ setError('')
+ try {
+ const synced = grok
+ ? await syncGrokSubscriptionCatalog(row.connectionKey)
+ : await syncCodexSubscriptionCatalog(row.connectionKey)
+ const models = grok
+ ? await listGrokConnectionModels(row.connectionKey)
+ : await listCodexConnectionModels(row.connectionKey)
+ setEditModels(models)
+ if (synced.connection) setEditing(asHubRow(synced.connection, row.broker))
+ // A refresh failure after a landed sync is partial — the catalog did
+ // change, so it must not surface as "sync failed".
+ await load()
+ if (synced.outcome === 'ready') {
+ showToast('Catalog synced', { tone: 'success' })
+ } else {
+ showToast(`Catalog sync failed (${synced.outcome}). Sign in again to retry.`, {
+ tone: 'error',
+ })
+ }
+ } catch (err) {
+ setError(catalogSyncErrorMessage(err, brand))
+ } finally {
+ setBusyKey(null)
+ }
+ }
+
async function handleToggleModel(row: HubConnection, model: string, enabledNext: boolean) {
setBusyKey(hubRowId(row))
try {
@@ -849,7 +909,12 @@ export function CodexSubscriptionHub() {
? GROK_TOS
: setupNew || !editing
? 'Agents authorize through this subscription’s ChatGPT grant. Sign in to connect it — the catalog syncs automatically.'
- : 'Agents authorize through this subscription’s ChatGPT grant. Reconnect if the grant expired — the catalog refreshes automatically.'}
+ : // The catalog is written at sign-in and never refreshed on its
+ // own, so promising an automatic refresh here was false for
+ // every grant past its handshake. State what the operator can
+ // actually rely on: the manual action, plus reconciliation
+ // where the deployment turns it on.
+ 'Agents authorize through this subscription’s ChatGPT grant. Reconnect if the grant expired. The catalog is read at sign-in — use Sync catalog to pick up models published since, or periodic reconciliation where this deployment enables it.'}
</p>
<div className="cu-form-inline">
<span
@@ -940,6 +1005,16 @@ export function CodexSubscriptionHub() {
{editModels.length} enabled
</span>
) : null}
+ {editing && editing.status === 'connected' ? (
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost cu-btn--sm"
+ onClick={() => void handleSyncCatalog(editing)}
+ disabled={Boolean(busyKey)}
+ >
+ Sync catalog
+ </button>
+ ) : null}
</div>
{editModels.length > 0 ? (
<div className="cu-llm-config__model-row">
diff --git a/control-ui/components/LlmModelTable.tsx b/control-ui/components/LlmModelTable.tsx
index 14f9d8afc..8ade954c0 100644
--- a/control-ui/components/LlmModelTable.tsx
+++ b/control-ui/components/LlmModelTable.tsx
@@ -8,6 +8,7 @@ import {
TableViewport,
useTableSort,
} from '@clerum/frontend-components'
+import { PROVIDER_AUTH_MODE, familyProviderIds, isLlmProviderId } from '@clerum/llm-providers'
import type { LlmAllowedModel } from '@lib/api'
import { catalogGroupKey, formatContextWindow, getProviderDisplayLabel } from '@lib/llm'
import { isUnpricedAllowedModel } from '@lib/llmModelUnpriced'
@@ -41,8 +42,23 @@ type DisplayModel = LlmAllowedModel & {
subscriptionRow?: LlmAllowedModel
}
+/**
+ * The auth mode of a row's provider, or undefined for a provider the canonical
+ * package does not know — catalogGroupKey passes free-form providers through, so
+ * a row here is not guaranteed to be a known id.
+ */
+function rowAuthMode(provider: string): 'static-credentials' | 'oauth-broker' | undefined {
+ return isLlmProviderId(provider) ? PROVIDER_AUTH_MODE[provider] : undefined
+}
+
+/**
+ * Merge the rows a family's providers contribute for the same model into one
+ * line, so an operator sees one model with the credential paths that serve it
+ * rather than one row per provider id. Families with a single member are left
+ * exactly as they are.
+ */
function collapseFamilyRows(family: string, models: LlmAllowedModel[]): DisplayModel[] {
- if (family !== 'openai') {
+ if (familyProviderIds(family).length < 2) {
return models.map(row => ({ ...row, credentialLabel: '' }))
}
const byName = new Map<string, LlmAllowedModel[]>()
@@ -52,8 +68,8 @@ function collapseFamilyRows(family: string, models: LlmAllowedModel[]): DisplayM
byName.set(row.model, list)
}
return Array.from(byName.entries()).map(([, rows]) => {
- const apiKey = rows.find(row => row.provider === 'openai')
- const subscription = rows.find(row => row.provider === 'codex-subscription')
+ const apiKey = rows.find(row => rowAuthMode(row.provider) === 'static-credentials')
+ const subscription = rows.find(row => rowAuthMode(row.provider) === 'oauth-broker')
const primary = apiKey ?? subscription ?? rows[0]
const parts: string[] = []
if (apiKey) parts.push('API key')
diff --git a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx
index 010571f02..77211eb34 100644
--- a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx
+++ b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx
@@ -59,7 +59,10 @@ vi.mock('@lib/codexSubscription', async importOriginal => {
patchCodexCatalogModel: vi.fn(),
startCodexDeviceConnect: vi.fn(),
pollCodexDevice: vi.fn(),
- syncCodexSubscriptionCatalog: vi.fn(),
+ // syncCodexSubscriptionCatalog is deliberately NOT overridden: the catalog
+ // re-sync suite drives the real client against a stubbed `fetch`, so the
+ // assertions cover the method, the URL and the error taxonomy rather than
+ // proving a button is wired to a spy.
revokeCodexSubscription: vi.fn(),
}
})
@@ -333,8 +336,16 @@ describe('CodexSubscriptionHub', () => {
)
fireEvent.click(await screen.findByRole('menuitem', { name: 'Update' }))
expect(await screen.findByRole('button', { name: 'Sign in with ChatGPT' })).toBeInTheDocument()
- // The catalog syncs automatically during connect — no manual sync button.
- expect(screen.queryByRole('button', { name: 'Sync catalog' })).not.toBeInTheDocument()
+ // Connect syncs the catalog once; a connected grant also offers the manual
+ // re-sync, because nothing refreshes it afterwards on its own.
+ expect(screen.getByRole('button', { name: 'Sync catalog' })).toBeInTheDocument()
+ // …and the hint must say so. Nothing refreshes a connected grant's catalog
+ // on its own, so the old "refreshes automatically" was false for every grant
+ // past its handshake. The witness for the negative is the positive clause
+ // rendered by the same element.
+ const signInHint = screen.getByText(/Agents authorize through this subscription/)
+ expect(signInHint).toHaveTextContent('use Sync catalog to pick up models published since')
+ expect(signInHint).not.toHaveTextContent('refreshes automatically')
expect(listCodexConnectionModels).toHaveBeenCalledWith('codex-aaa')
fireEvent.click(screen.getByLabelText('gpt-5.3-codex'))
await waitFor(() => {
@@ -821,3 +832,240 @@ describe('CodexSubscriptionHub with Grok enabled', () => {
}
})
})
+
+// The catalog re-sync action drives the REAL sync clients (neither broker module
+// overrides them) against a stubbed `fetch`, so these assertions cover the HTTP
+// method, the broker-scoped URL and the endpoint's error taxonomy. Asserting a
+// module spy instead would prove only that a button is wired to a stub.
+describe('CodexSubscriptionHub catalog re-sync', () => {
+ function renderHub() {
+ return render(
+ <ToastProvider>
+ <CodexSubscriptionHub />
+ </ToastProvider>
+ )
+ }
+
+ function makeResponse(status: number, body: unknown): Response {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ statusText: status === 200 ? 'OK' : 'Error',
+ json: async () => body,
+ text: async () => JSON.stringify(body),
+ } as unknown as Response
+ }
+
+ let fetchMock: ReturnType<typeof vi.fn>
+
+ beforeEach(() => {
+ confirmMock.mockReset()
+ capabilityProbes.codex.mockResolvedValue({ enabled: true })
+ capabilityProbes.grok.mockResolvedValue({ enabled: true })
+ vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([
+ connection({ connectionKey: 'codex-aaa', displayName: 'Team A' }),
+ ])
+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([
+ connection({ connectionKey: 'grok-aaa', displayName: 'Team Grok', defaultModel: 'grok-4.6' }),
+ ])
+ vi.mocked(listCodexConnectionModels).mockResolvedValue([
+ { model: 'gpt-5.1', enabled: true, stale: false },
+ ])
+ vi.mocked(listGrokConnectionModels).mockResolvedValue([
+ { model: 'grok-4.6', enabled: true, stale: false },
+ ])
+ fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+ vi.unstubAllGlobals()
+ })
+
+ async function openGrokDialog(): Promise<HTMLElement> {
+ renderHub()
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Actions for Grok subscription Team Grok' })
+ )
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Update' }))
+ return screen.findByRole('dialog', { name: 'Update Grok subscription Team Grok' })
+ }
+
+ it('syncs the Grok catalog through the Grok endpoint and re-reads the models', async () => {
+ vi.mocked(listGrokConnectionModels)
+ .mockResolvedValueOnce([{ model: 'grok-4.6', enabled: true, stale: false }])
+ .mockResolvedValueOnce([
+ { model: 'grok-4.6', enabled: true, stale: false },
+ { model: 'grok-4.7', enabled: false, stale: false },
+ ])
+ fetchMock.mockResolvedValueOnce(
+ makeResponse(200, {
+ outcome: 'ready',
+ added: 1,
+ refreshed: 1,
+ staled: 0,
+ connection: connection({ connectionKey: 'grok-aaa', displayName: 'Team Grok' }),
+ })
+ )
+
+ const dialog = await openGrokDialog()
+ expect(await within(dialog).findByLabelText('grok-4.6')).toBeInTheDocument()
+ // The model the upstream has just published is not there yet.
+ expect(within(dialog).queryByLabelText('grok-4.7')).not.toBeInTheDocument()
+ expect(listGrokConnectionModels).toHaveBeenCalledTimes(1)
+
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Sync catalog' }))
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]
+ expect(url).toBe(
+ '/control-api/api/v1/admin/llm/providers/grok-subscription/connections/grok-aaa/catalog/sync'
+ )
+ expect(init.method).toBe('POST')
+ // The models block re-reads from the server; the new model now renders.
+ await waitFor(() => expect(listGrokConnectionModels).toHaveBeenCalledTimes(2))
+ expect(await within(dialog).findByLabelText('grok-4.7')).toBeInTheDocument()
+ expect(await screen.findByText('Catalog synced')).toBeInTheDocument()
+ })
+
+ it('reports a non-ready outcome the endpoint returns with 200 instead of claiming success', async () => {
+ fetchMock.mockResolvedValueOnce(
+ makeResponse(200, {
+ outcome: 'auth-rejected',
+ added: 0,
+ refreshed: 0,
+ staled: 0,
+ connection: connection({
+ connectionKey: 'grok-aaa',
+ displayName: 'Team Grok',
+ status: 'reauth_required',
+ catalogStatus: 'auth-rejected',
+ }),
+ })
+ )
+
+ const dialog = await openGrokDialog()
+ await within(dialog).findByLabelText('grok-4.6')
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Sync catalog' }))
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
+ expect(await screen.findByText(/Catalog sync failed \(auth-rejected\)/)).toBeInTheDocument()
+ expect(screen.queryByText('Catalog synced')).not.toBeInTheDocument()
+ })
+
+ it('syncs the Codex catalog through the Codex endpoint, not the Grok one', async () => {
+ fetchMock.mockResolvedValueOnce(
+ makeResponse(200, {
+ outcome: 'ready',
+ added: 0,
+ refreshed: 1,
+ staled: 0,
+ connection: connection({ connectionKey: 'codex-aaa', displayName: 'Team A' }),
+ })
+ )
+
+ renderHub()
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Actions for ChatGPT subscription Team A' })
+ )
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Update' }))
+ const dialog = await screen.findByRole('dialog', {
+ name: 'Update ChatGPT subscription Team A',
+ })
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Sync catalog' }))
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
+ const [url] = fetchMock.mock.calls[0] as [string, RequestInit]
+ expect(url).toContain('/codex-subscription/connections/codex-aaa/catalog/sync')
+ expect(url).not.toContain('/grok-subscription/')
+ })
+
+ it('reports a raced sync distinctly and leaves the rendered models untouched', async () => {
+ fetchMock.mockResolvedValueOnce(makeResponse(409, { error: 'stale_revision' }))
+
+ const dialog = await openGrokDialog()
+ expect(await within(dialog).findByLabelText('grok-4.6')).toBeInTheDocument()
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Sync catalog' }))
+
+ expect(await within(dialog).findByText(/changed while this sync ran/i)).toBeInTheDocument()
+ // Liveness witness for the negative assertion below: the request was issued
+ // and the endpoint answered, so the untouched list is the failure's doing.
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(listGrokConnectionModels).toHaveBeenCalledTimes(1)
+ expect(within(dialog).getByLabelText('grok-4.6')).toBeInTheDocument()
+ })
+
+ it('names the upstream outcome when the catalog sync itself fails', async () => {
+ fetchMock.mockResolvedValueOnce(
+ makeResponse(503, { error: 'catalog_sync_failed', outcome: 'unavailable' })
+ )
+
+ const dialog = await openGrokDialog()
+ await within(dialog).findByLabelText('grok-4.6')
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Sync catalog' }))
+
+ const banner = await within(dialog).findByText(/could not be reached/i)
+ expect(banner).toHaveTextContent('unavailable')
+ expect(listGrokConnectionModels).toHaveBeenCalledTimes(1)
+ })
+
+ it('tells the operator to reconnect when the grant no longer authorizes', async () => {
+ fetchMock.mockResolvedValueOnce(makeResponse(404, { error: 'no_grant' }))
+
+ const dialog = await openGrokDialog()
+ await within(dialog).findByLabelText('grok-4.6')
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Sync catalog' }))
+
+ expect(
+ await within(dialog).findByText(/no longer authorizes|sign in again/i)
+ ).toBeInTheDocument()
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ // The setup form is the one state where the models block renders while the
+ // grant is still disconnected, so it is the only place the sync action's own
+ // status guard decides anything. Fixtures where the block is hidden anyway
+ // cannot see that guard and would pass with it removed.
+ it('does not offer the sync action while a new grant is still signing in', async () => {
+ vi.stubGlobal(
+ 'open',
+ vi.fn(() => ({}))
+ )
+ vi.mocked(createCodexSubscriptionConnection).mockResolvedValue(
+ connection({
+ connectionKey: 'codex-new',
+ displayName: 'New team',
+ status: 'disconnected',
+ defaultModel: null,
+ })
+ )
+ vi.mocked(startCodexDeviceConnect).mockResolvedValue({
+ userCode: 'ABCD-1234',
+ verificationUri: CODEX_DEVICE_VERIFICATION_URI,
+ intervalSeconds: 600,
+ state: 'state-1',
+ intent: 'connect',
+ })
+ // The device flow never completes during this test, so the grant stays
+ // disconnected while the setup form — models block included — is on screen.
+ vi.mocked(pollCodexDevice).mockReturnValue(new Promise(() => {}))
+
+ renderHub()
+ await screen.findByText('Team A')
+ fireEvent.click(screen.getByRole('button', { name: 'Add subscription' }))
+ fireEvent.change(screen.getByRole('textbox', { name: 'Name' }), {
+ target: { value: 'New team' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Sign in with ChatGPT' }))
+ await waitFor(() =>
+ expect(startCodexDeviceConnect).toHaveBeenCalledWith('connect', 'codex-new')
+ )
+
+ // Liveness witness: the models block the action lives in really rendered.
+ expect(await screen.findByText('Enabled models')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Sync catalog' })).not.toBeInTheDocument()
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/control-ui/components/__tests__/LlmModelTable.test.tsx b/control-ui/components/__tests__/LlmModelTable.test.tsx
index bd39a03fc..07531124d 100644
--- a/control-ui/components/__tests__/LlmModelTable.test.tsx
+++ b/control-ui/components/__tests__/LlmModelTable.test.tsx
@@ -147,6 +147,96 @@ describe('LlmModelTable catalog-lifecycle columns', () => {
fireEvent.click(screen.getByRole('menuitem', { name: 'Edit subscription' }))
expect(onEdit).toHaveBeenCalledWith('oa-sub')
})
+
+ it('groups xAI API-key and subscription rows under one family', () => {
+ renderTable([
+ {
+ ...baseModel,
+ id: 'xai-key',
+ provider: 'xai',
+ model: 'grok-4.6',
+ vendor: 'xAI',
+ display_name: 'Grok 4.6',
+ },
+ {
+ ...baseModel,
+ id: 'xai-sub',
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ vendor: 'xAI',
+ display_name: 'Grok 4.6',
+ },
+ {
+ ...baseModel,
+ id: 'xai-sub-only',
+ provider: 'grok-subscription',
+ model: 'grok-4.6-fast',
+ vendor: 'xAI',
+ display_name: 'Grok 4.6 Fast',
+ },
+ ])
+ // One group, under the vendor's own label — not a second group for the broker.
+ expect(
+ screen.queryByRole('button', { name: /Expand xAI Grok Subscription models/i })
+ ).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'Expand xAI (Grok) models' }))
+ expect(screen.getByText('grok-4.6')).toBeInTheDocument()
+ expect(screen.getByText('API key · Subscription')).toBeInTheDocument()
+ expect(screen.getByText('grok-4.6-fast').closest('tr')).toHaveTextContent('Subscription')
+ })
+
+ it('edits the subscription row of an expanded xAI family through the existing actions menu', () => {
+ const onEdit = vi.fn()
+ render(
+ <LlmModelTable
+ items={[
+ {
+ ...baseModel,
+ id: 'xai-key',
+ provider: 'xai',
+ model: 'grok-4.6',
+ vendor: 'xAI',
+ display_name: 'Grok 4.6',
+ },
+ {
+ ...baseModel,
+ id: 'xai-sub',
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ vendor: 'xAI',
+ display_name: 'Grok 4.6',
+ },
+ ]}
+ unpricedKeys={new Set()}
+ onCreate={vi.fn()}
+ onEdit={onEdit}
+ onDelete={vi.fn().mockResolvedValue(undefined)}
+ onRefresh={vi.fn()}
+ deletingId={null}
+ refreshing={false}
+ loading={false}
+ />
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Expand xAI (Grok) models' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Actions for model xai/grok-4.6' }))
+ // Collapsing merges two rows into one line; the menu must still reach the
+ // broker's own row, not the API-key row it is displayed beside.
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Edit subscription' }))
+ expect(onEdit).toHaveBeenCalledWith('xai-sub')
+ expect(onEdit).not.toHaveBeenCalledWith('xai-key')
+ })
+
+ it('leaves a single-provider family uncollapsed and unlabelled', () => {
+ renderTable([
+ { ...baseModel, id: 'cl-1', model: 'claude-sonnet-4-6' },
+ { ...baseModel, id: 'cl-2', model: 'claude-opus-4-1', display_name: 'Claude Opus 4.1' },
+ ])
+ expandAnthropicModels()
+ expect(screen.getByText('claude-sonnet-4-6')).toBeInTheDocument()
+ expect(screen.getByText('claude-opus-4-1')).toBeInTheDocument()
+ expect(screen.queryByText('API key · Subscription')).not.toBeInTheDocument()
+ expect(screen.queryByText('Subscription')).not.toBeInTheDocument()
+ })
})
describe('LlmModelTable filters', () => {
diff --git a/control-ui/lib/__tests__/grokSubscription.sync.test.ts b/control-ui/lib/__tests__/grokSubscription.sync.test.ts
new file mode 100644
index 000000000..54488a155
--- /dev/null
+++ b/control-ui/lib/__tests__/grokSubscription.sync.test.ts
@@ -0,0 +1,122 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { GROK_SUBSCRIPTION_API_BASE, syncGrokSubscriptionCatalog } from '../grokSubscription'
+
+const connectionKey = 'team/grok primary'
+const encodedKey = encodeURIComponent(connectionKey)
+
+const readyConnection = {
+ connectionKey,
+ displayName: 'Grok primary',
+ status: 'connected',
+ credentialRevision: 4,
+ catalogRevision: 9,
+ catalogStatus: 'ready',
+ catalogSyncedAt: '2026-09-22T10:00:00.000Z',
+}
+
+function makeResponse(status: number, body: unknown): Response {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ statusText: status === 200 ? 'OK' : 'Error',
+ json: async () => body,
+ text: async () => JSON.stringify(body),
+ } as unknown as Response
+}
+
+let fetchMock: ReturnType<typeof vi.fn>
+
+beforeEach(() => {
+ fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+})
+
+afterEach(() => vi.unstubAllGlobals())
+
+describe('Grok subscription catalog sync client', () => {
+ it('POSTs to the connection-scoped catalog sync endpoint on the Grok base', async () => {
+ fetchMock.mockResolvedValueOnce(
+ makeResponse(200, {
+ outcome: 'ready',
+ added: 2,
+ refreshed: 5,
+ staled: 1,
+ connection: readyConnection,
+ })
+ )
+
+ const view = await syncGrokSubscriptionCatalog(connectionKey)
+
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]
+ expect(url).toBe(
+ `/control-api${GROK_SUBSCRIPTION_API_BASE}/connections/${encodedKey}/catalog/sync`
+ )
+ expect(url).toContain('/grok-subscription/')
+ expect(url).not.toContain('/codex-subscription/')
+ expect(init.method).toBe('POST')
+ expect(init.body).toBeUndefined()
+
+ expect(view).toEqual({
+ outcome: 'ready',
+ added: 2,
+ refreshed: 5,
+ staled: 1,
+ connection: expect.objectContaining({ connectionKey, catalogStatus: 'ready' }),
+ })
+ })
+
+ it('surfaces a non-ready outcome the endpoint reports with 200 instead of hiding it', async () => {
+ fetchMock.mockResolvedValueOnce(
+ makeResponse(200, {
+ outcome: 'auth-rejected',
+ added: 0,
+ refreshed: 0,
+ staled: 0,
+ connection: {
+ ...readyConnection,
+ status: 'reauth_required',
+ catalogStatus: 'auth-rejected',
+ },
+ })
+ )
+
+ const view = await syncGrokSubscriptionCatalog(connectionKey)
+
+ expect(view.outcome).toBe('auth-rejected')
+ expect(view.connection?.status).toBe('reauth_required')
+ })
+
+ it('propagates the endpoint error taxonomy with its status and machine code', async () => {
+ fetchMock.mockResolvedValueOnce(makeResponse(409, { error: 'stale_revision' }))
+
+ const rejection = (await syncGrokSubscriptionCatalog(connectionKey).then(
+ () => null,
+ (err: unknown) => err
+ )) as (Error & { status?: number; code?: string }) | null
+
+ // Liveness witness: the request was actually issued, so the rejection comes
+ // from the endpoint's response and not from an unreached code path.
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(rejection).toBeInstanceOf(Error)
+ expect(rejection?.status).toBe(409)
+ expect(rejection?.code).toBe('stale_revision')
+ })
+
+ it('refuses a response that leaks a credential field instead of returning it', async () => {
+ fetchMock.mockResolvedValueOnce(
+ makeResponse(200, {
+ outcome: 'ready',
+ added: 0,
+ refreshed: 1,
+ staled: 0,
+ connection: { ...readyConnection, refreshToken: 'xai-refresh-token' },
+ })
+ )
+
+ await expect(syncGrokSubscriptionCatalog(connectionKey)).rejects.toThrow(
+ /leaked forbidden field/
+ )
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/control-ui/lib/__tests__/llm.test.ts b/control-ui/lib/__tests__/llm.test.ts
index 04bee4ebb..0f3a7d358 100644
--- a/control-ui/lib/__tests__/llm.test.ts
+++ b/control-ui/lib/__tests__/llm.test.ts
@@ -10,6 +10,7 @@ import {
brokerBackedRecipeAuthoringError,
budgetUnitAllowedForProviders,
catalogGroupKey,
+ familyCredentialSources,
getAllModelOptions,
getLlmGroupCompleteness,
getModelOptions,
@@ -18,7 +19,6 @@ import {
inferProviderFromModels,
isOpenAiFamily,
llmChainRequiresSecret,
- openAiCredentialSources,
providerRequiresLlmSecret,
resolveDefaultModel,
validateLlmSecretData,
@@ -90,29 +90,64 @@ describe('OpenAI family presentation', () => {
expect(isOpenAiFamily('codex-subscription')).toBe(true)
})
- it('does not fold Grok subscription into the OpenAI family', () => {
+ it('groups Grok subscription catalog rows under xAI, not under OpenAI', () => {
+ expect(catalogGroupKey('grok-subscription')).toBe('xai')
+ expect(catalogGroupKey('xai')).toBe('xai')
expect(isOpenAiFamily('grok-subscription')).toBe(false)
- expect(catalogGroupKey('grok-subscription')).toBe('grok-subscription')
expect(getProviderLabel('grok-subscription')).not.toBe('OpenAI')
expect(OPERATOR_PROVIDER_OPTIONS.some(option => option.value === 'grok-subscription')).toBe(
true
)
})
- it('marks a model as API key, subscription, or both', () => {
+ it('keeps the broker label distinct from its family label', () => {
+ // grok-subscription is offered in the operator picker beside xai, so the two
+ // must stay tellable apart. Only the catalog GROUPING is unified.
+ expect(getProviderLabel('grok-subscription')).toBe('xAI Grok Subscription')
+ expect(getProviderDisplayLabel('grok-subscription')).toBe('xAI Grok Subscription')
+ expect(getProviderLabel('xai')).toBe('xAI (Grok)')
+ })
+
+ it('passes an unknown provider through as its own group', () => {
+ // The prices table carries free-form providers; they must not throw and must
+ // not be folded into anything.
+ expect(catalogGroupKey('not-a-provider')).toBe('not-a-provider')
+ })
+
+ it('marks a model as API key, subscription, or both, in any family', () => {
const catalog: LlmModelCatalogEntry[] = [
{ provider: 'openai', model: 'gpt-5.1', enabled: true },
{ provider: 'codex-subscription', model: 'gpt-5.1', enabled: true },
{ provider: 'codex-subscription', model: 'gpt-5.3-codex', enabled: true },
+ { provider: 'xai', model: 'grok-4.6', enabled: true },
+ { provider: 'grok-subscription', model: 'grok-4.6', enabled: true },
+ { provider: 'grok-subscription', model: 'grok-4.6-fast', enabled: true },
]
- expect(openAiCredentialSources(catalog, 'gpt-5.1')).toEqual({
+ expect(familyCredentialSources(catalog, 'openai', 'gpt-5.1')).toEqual({
+ apiKey: true,
+ subscription: true,
+ })
+ expect(familyCredentialSources(catalog, 'openai', 'gpt-5.3-codex')).toEqual({
+ apiKey: false,
+ subscription: true,
+ })
+ expect(familyCredentialSources(catalog, 'xai', 'grok-4.6')).toEqual({
apiKey: true,
subscription: true,
})
- expect(openAiCredentialSources(catalog, 'gpt-5.3-codex')).toEqual({
+ expect(familyCredentialSources(catalog, 'xai', 'grok-4.6-fast')).toEqual({
apiKey: false,
subscription: true,
})
+ // A family does not see another family's rows.
+ expect(familyCredentialSources(catalog, 'openai', 'grok-4.6')).toEqual({
+ apiKey: false,
+ subscription: false,
+ })
+ expect(familyCredentialSources(catalog, 'not-a-provider', 'grok-4.6')).toEqual({
+ apiKey: false,
+ subscription: false,
+ })
})
})
diff --git a/control-ui/lib/grokSubscription.ts b/control-ui/lib/grokSubscription.ts
index 4c98d86de..5b82d68db 100644
--- a/control-ui/lib/grokSubscription.ts
+++ b/control-ui/lib/grokSubscription.ts
@@ -8,6 +8,7 @@ import {
type CodexDevicePollView,
type CodexOAuthIntent,
type CodexSubscriptionConnectionView,
+ sanitizeCodexCatalogSync,
sanitizeCodexConnection,
} from './codexSubscription'
@@ -174,6 +175,12 @@ export async function pollGrokDevice(
throw new Error('Grok device poll status is invalid')
}
+export async function syncGrokSubscriptionCatalog(
+ connectionKey: string
+): Promise<GrokCatalogSyncView> {
+ return sanitizeCodexCatalogSync(await apiSend('POST', keyedPath(connectionKey, 'catalog/sync')))
+}
+
export async function revokeGrokSubscription(
connectionKey: string
): Promise<GrokSubscriptionConnectionView> {
diff --git a/control-ui/lib/llm.ts b/control-ui/lib/llm.ts
index 8350937aa..7e45ec589 100644
--- a/control-ui/lib/llm.ts
+++ b/control-ui/lib/llm.ts
@@ -5,7 +5,9 @@ import {
PROVIDER_DISPLAY_LABELS,
PROVIDER_IDS,
PROVIDER_NON_SECRET_ENV,
+ familyProviderIds,
isLlmProviderId,
+ providerFamily,
} from '@clerum/llm-providers'
import { CODEX_UNASSIGNED_CONNECTION_KEY } from './codexSubscription'
@@ -54,7 +56,9 @@ export const OPENAI_SUBSCRIPTION_PROVIDER = 'codex-subscription' as const
export const GROK_SUBSCRIPTION_PROVIDER = 'grok-subscription' as const
export function isOpenAiFamily(provider: string | undefined | null): boolean {
- return provider === 'openai' || provider === OPENAI_SUBSCRIPTION_PROVIDER
+ return typeof provider === 'string' && isLlmProviderId(provider)
+ ? providerFamily(provider) === 'openai'
+ : false
}
export function isOauthBrokerProvider(provider: string | undefined | null): boolean {
@@ -99,28 +103,41 @@ export function runtimeProviderOptions(opts?: {
return options
}
+/**
+ * The catalog group a provider's rows belong to: its family, so a vendor API and
+ * its subscription broker read as one catalog. Free-form providers (the prices
+ * table accepts any string) pass through unchanged and group only with
+ * themselves.
+ */
export function catalogGroupKey(provider: string): string {
- return provider === OPENAI_SUBSCRIPTION_PROVIDER ? 'openai' : provider
+ return isLlmProviderId(provider) ? providerFamily(provider) : provider
}
-export type OpenAiCredentialSource = 'api-key' | 'subscription'
+export type FamilyCredentialSource = 'api-key' | 'subscription'
-export function openAiCredentialSources(
+/**
+ * Which credential paths serve a model inside one family. Derived from each
+ * provider's auth mode rather than named ids, so a family gains a broker without
+ * this function changing. An unknown family has no members, so neither path
+ * serves it.
+ */
+export function familyCredentialSources(
catalog: LlmModelCatalogEntry[],
+ family: string,
model: string
): { apiKey: boolean; subscription: boolean } {
- return {
- apiKey: catalog.some(
- row => row.provider === 'openai' && row.model === model && row.enabled && !row.stale
- ),
- subscription: catalog.some(
+ const members = familyProviderIds(family)
+ const served = (mode: (typeof PROVIDER_AUTH_MODE)[LlmProviderId]): boolean =>
+ catalog.some(
row =>
- row.provider === OPENAI_SUBSCRIPTION_PROVIDER &&
row.model === model &&
row.enabled &&
- !row.stale
- ),
- }
+ !row.stale &&
+ isLlmProviderId(row.provider) &&
+ members.includes(row.provider) &&
+ PROVIDER_AUTH_MODE[row.provider] === mode
+ )
+ return { apiKey: served('static-credentials'), subscription: served('oauth-broker') }
}
// The list of usable models per provider is no longer a static catalog: it is
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 55057f0bb..5238431b6 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.604",
+ "version": "0.1.605",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.604",
+ "version": "0.1.605",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/control-ui/package.json b/control-ui/package.json
index e5c50bedf..e49332bf3 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.604",
+ "version": "0.1.605",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/deploy/base/control-plane/configmaps.yaml b/deploy/base/control-plane/configmaps.yaml
index 0824c9179..1323bf289 100644
--- a/deploy/base/control-plane/configmaps.yaml
+++ b/deploy/base/control-plane/configmaps.yaml
@@ -100,6 +100,18 @@ data:
# control-api starts (fills image_input evidence), then every interval.
# Interval + plausibility floors keep their code defaults.
LLM_CATALOG_SYNC_CRON_ENABLED: "true"
+ # Subscription catalog reconciliation cron. A grant's catalog is written at
+ # sign-in and never refreshed on its own, so a model the vendor publishes
+ # afterwards stays invisible to that subscription until an operator syncs it
+ # from the Hub. This cron re-runs that same per-connection sync periodically.
+ # Off by default: unlike the discovery sync above (one call to models.dev per
+ # tick), each tick calls the broker once PER CONNECTED GRANT, and a Grok
+ # refresh inside the token skew rotates the refresh token. Turn it on
+ # deliberately, per deployment.
+ SUBSCRIPTION_CATALOG_SYNC_CRON_ENABLED: "false"
+ # Floor is 15 minutes (control-api refuses to boot below it). The code default
+ # is 6h; the key is declared here so the interval is visible where it is set.
+ SUBSCRIPTION_CATALOG_SYNC_INTERVAL_MS: "21600000"
---
apiVersion: v1
kind: ConfigMap
diff --git a/docs/testing/codex-subscription-validation.md b/docs/testing/codex-subscription-validation.md
index 312ab128b..006d47bda 100644
--- a/docs/testing/codex-subscription-validation.md
+++ b/docs/testing/codex-subscription-validation.md
@@ -41,6 +41,63 @@ Live upstream is the Playwright connection lane (`codex-subscription-connection.
against a signed-in Control UI. There is no standalone
`e2e-codex-subscription-real-upstream.sh` script.
+## Subscription catalog reconciliation cron
+
+`control-api/src/services/subscriptionCatalogSyncCron.ts` re-reads both
+subscription catalogs on an interval, so a model an upstream publishes after a
+grant's handshake reaches the runtime allowlist without an operator pressing
+anything. It is off by default: `SUBSCRIPTION_CATALOG_SYNC_CRON_ENABLED` and
+`SUBSCRIPTION_CATALOG_SYNC_INTERVAL_MS` in
+`deploy/base/control-plane/configmaps.yaml` carry the deployment's choice, and
+the interval has a 15-minute floor because each tick costs one upstream call
+per connection and a Grok refresh rotates the refresh token.
+
+Two suites, and neither stands in for the other:
+
+- **Unit** — `control-api/src/services/__tests__/subscriptionCatalogSyncCron.test.ts`.
+ Owns the tick's decision table against doubles: the advisory lock, the
+ broker/status skips, per-connection failure isolation, the `never_synced`
+ rule that decides whether the ConfigMap is republished, and the first-run
+ jitter.
+- **T1** — `control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts`,
+ under `CONTROL_API_REAL_PG_REQUIRED=1`. Owns what doubles cannot reach:
+ rows landing in `grok_catalog_models`, the `grok-subscription` union rebuilt
+ in `llm_allowed_models`, a model that vanished upstream stale-flagged in the
+ catalog and disabled in the union, and an identical second tick recording a
+ fresh outcome without duplicating rows. The grant is created through the
+ device flow rather than by writing credential rows, so the tick's own
+ refresh-token rotation runs against a fingerprint it can match. Only xAI's
+ HTTP endpoints and the Kubernetes ConfigMap writer are doubled.
+
+Run the T1 suite the way the lane does, against a real PostgreSQL 16:
+
+```bash
+cd control-api && CONTROL_API_REAL_PG_ADMIN_URL="$DSN" CONTROL_API_REAL_PG_REQUIRED=1 npx vitest run --no-file-parallelism --maxWorkers=1 realPostgres
+```
+
+## On-demand catalog re-sync
+
+The same re-read is available to an operator from the grant modal's **Sync catalog**
+button. Three lanes own three different claims about it, and none substitutes for
+another.
+
+- **Proxy, hermetic** — `codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts`,
+ describe `hermetic catalog re-read`. Owns "the re-read returns a model the upstream
+ published after the handshake". This is the **only** place in the repository where that
+ is provable: `CODEX_CATALOG_ORIGIN` is frozen in `codex-llm-proxy/src/originPolicy.ts`
+ as part of the SSRF boundary, and the in-process `fetchFn`/`lookup` seam in that file is
+ the one thing that redirects it at the fixture. The fixture serves a second model when
+ `CODEX_TEST_UPSTREAM_EXTRA_MODEL` is set; unset keeps the single-model reply every other
+ case expects. The fixture's `models` counter is the liveness witness.
+- **T1** — the cron suite above. Owns the rows and the union allowlist.
+- **Control UI Playwright** —
+ `tests/e2e/playwright/control-ui/codex-subscription-catalog-resync.spec.ts`. Owns the
+ affordance and the operator's verdict: the button exists on a connected grant and
+ nowhere else, the click issues exactly one `POST .../catalog/sync`, a 200 advances
+ `catalogRevision`, and the modal ends on a success toast or a non-empty error banner
+ rather than a spinner. **It cannot prove a new model appears**: that lane deploys no
+ fake upstream, so the grant talks to the frozen origin.
+
## Plugin Workload SDK Desktop lanes
Three Desktop/Electron journeys exercise `codex-subscription` through the
diff --git a/packages/llm-providers/index.cjs b/packages/llm-providers/index.cjs
index 1332a58c9..4cd6804da 100644
--- a/packages/llm-providers/index.cjs
+++ b/packages/llm-providers/index.cjs
@@ -252,6 +252,63 @@ const { PROVIDER_AUTH_MODE, PROVIDER_MODEL_CATALOG_MODE } = buildProviderMaps(
OAUTH_BROKER_IDS
)
+/**
+ * Providers whose family is NOT themselves. A subscription broker and the
+ * vendor API that serves the same models are one catalog to an operator, even
+ * though they remain separate runtime providers with separate credentials and
+ * separate `llm_allowed_models` rows.
+ *
+ * Declared explicitly and never derived from the id's text: `grok-subscription`
+ * reads as "grok" but belongs to `xai`, and `codex-subscription` reads as
+ * "codex" but belongs to `openai`. A prefix heuristic is wrong for both.
+ *
+ * A broker added without an entry here keeps a family of its own and renders as
+ * an unrelated catalog group — the symptom this map exists to prevent. The
+ * exhaustiveness assertions in index.test.cjs are what make that visible.
+ * @type {Record<string, string | undefined>}
+ */
+const PROVIDER_FAMILY_OVERRIDES = Object.freeze({
+ 'codex-subscription': 'openai',
+ 'grok-subscription': 'xai',
+})
+
+/**
+ * Every provider id → the provider id that owns its family. Total over
+ * PROVIDER_IDS; an id absent from the override map owns its own family.
+ * @type {Record<string, string>}
+ */
+const PROVIDER_FAMILY = Object.freeze(
+ Object.fromEntries(
+ PROVIDER_IDS.map(id => [
+ id,
+ Object.prototype.hasOwnProperty.call(PROVIDER_FAMILY_OVERRIDES, id)
+ ? PROVIDER_FAMILY_OVERRIDES[id]
+ : id,
+ ])
+ )
+)
+
+/**
+ * The family of a known provider. Throws on anything else, matching
+ * providerDescriptor: a caller holding an unrecognised string must decide what
+ * to do with it rather than receive an invented family.
+ */
+function providerFamily(id) {
+ if (!isLlmProviderId(id)) {
+ throw new Error(`[llm-providers] unknown provider '${String(id)}'`)
+ }
+ return PROVIDER_FAMILY[id]
+}
+
+/**
+ * The provider ids belonging to a family, in PROVIDER_IDS order. Takes a family
+ * key rather than a provider id, so an unrecognised key is an ordinary answer —
+ * no known provider belongs to it — and returns an empty list, not a throw.
+ */
+function familyProviderIds(family) {
+ return Object.freeze(PROVIDER_IDS.filter(id => PROVIDER_FAMILY[id] === family))
+}
+
/** @type {Record<string, string | undefined>} */
const PROVIDER_EXECUTE_SCOPE = Object.freeze({
'codex-subscription': 'llm:codex:execute',
@@ -277,6 +334,7 @@ function providerDescriptor(id) {
return Object.freeze({
id,
displayLabel: PROVIDER_DISPLAY_LABELS[id],
+ family: PROVIDER_FAMILY[id],
authMode: PROVIDER_AUTH_MODE[id],
modelCatalogMode: PROVIDER_MODEL_CATALOG_MODE[id],
credentialSlots: PROVIDER_CREDENTIAL_SLOTS[id],
@@ -310,11 +368,14 @@ module.exports = {
PROVIDER_NON_SECRET_ENV,
PROVIDER_AUTH_MODE,
PROVIDER_MODEL_CATALOG_MODE,
+ PROVIDER_FAMILY,
OAUTH_BROKER_IDS,
buildProviderMaps,
+ familyProviderIds,
isCredentialSlotOwnedByProvider,
isLlmProviderId,
isRunnableLlmModelId,
providerDescriptor,
+ providerFamily,
requireStaticCredentialSlot,
}
diff --git a/packages/llm-providers/index.d.ts b/packages/llm-providers/index.d.ts
index 06ebf238a..ccb5508e4 100644
--- a/packages/llm-providers/index.d.ts
+++ b/packages/llm-providers/index.d.ts
@@ -129,6 +129,7 @@ export type ProviderModelCatalogMode = 'static' | 'dynamic'
export interface ProviderDescriptor {
id: LlmProviderId
displayLabel: string
+ family: LlmProviderId
authMode: ProviderAuthMode
modelCatalogMode: ProviderModelCatalogMode
credentialSlots: readonly CredentialSlot[]
@@ -149,6 +150,15 @@ export declare function buildProviderMaps(
PROVIDER_AUTH_MODE: Readonly<Record<string, ProviderAuthMode>>
PROVIDER_MODEL_CATALOG_MODE: Readonly<Record<string, ProviderModelCatalogMode>>
}
+/** Every provider id → the provider id that owns its family. Total, frozen. */
+export declare const PROVIDER_FAMILY: Record<LlmProviderId, LlmProviderId>
+/** The family of a known provider. Throws on an unrecognised id. */
+export declare function providerFamily(id: LlmProviderId): LlmProviderId
+/**
+ * The provider ids in a family, in PROVIDER_IDS order. Takes a family key, so an
+ * unrecognised key returns an empty list rather than throwing.
+ */
+export declare function familyProviderIds(family: string): readonly LlmProviderId[]
export declare function providerDescriptor(id: LlmProviderId): ProviderDescriptor
export declare function requireStaticCredentialSlot(
descriptor: Pick<ProviderDescriptor, 'authMode' | 'credentialSlots'>
diff --git a/packages/llm-providers/index.test.cjs b/packages/llm-providers/index.test.cjs
index 211c3fbe6..9e4026b5e 100644
--- a/packages/llm-providers/index.test.cjs
+++ b/packages/llm-providers/index.test.cjs
@@ -35,3 +35,68 @@ describe('buildProviderMaps', () => {
assert.deepEqual(desc.credentialSlots, [])
})
})
+
+describe('provider families', () => {
+ it('maps every provider id to a family owned by a real provider id', () => {
+ assert.equal(typeof providers.PROVIDER_FAMILY, 'object')
+ // Exhaustive by assertion: a provider added without a family entry is a bug,
+ // never a silent default.
+ assert.deepEqual(
+ Object.keys(providers.PROVIDER_FAMILY).sort(),
+ [...providers.PROVIDER_IDS].sort()
+ )
+ for (const id of providers.PROVIDER_IDS) {
+ const family = providers.PROVIDER_FAMILY[id]
+ assert.ok(
+ providers.isLlmProviderId(family),
+ `family '${family}' of '${id}' is not a provider id`
+ )
+ // Closed: the owner of a family belongs to its own family, so resolving
+ // twice equals resolving once and no chain can form.
+ assert.equal(
+ providers.PROVIDER_FAMILY[family],
+ family,
+ `family '${family}' is not its own owner`
+ )
+ }
+ })
+
+ it('groups the two subscription brokers with the vendor that owns them', () => {
+ assert.equal(providers.providerFamily('openai'), 'openai')
+ assert.equal(providers.providerFamily('codex-subscription'), 'openai')
+ assert.equal(providers.providerFamily('xai'), 'xai')
+ assert.equal(providers.providerFamily('grok-subscription'), 'xai')
+ })
+
+ it('leaves every other provider in a family of its own', () => {
+ const grouped = new Set(['openai', 'codex-subscription', 'xai', 'grok-subscription'])
+ for (const id of providers.PROVIDER_IDS) {
+ if (grouped.has(id)) continue
+ assert.equal(providers.providerFamily(id), id)
+ }
+ })
+
+ it('rejects an unknown provider instead of inventing a family for it', () => {
+ // The predicate is load-bearing: a bare assert.throws is satisfied by
+ // `providerFamily is not a function`, so it would pass against no
+ // implementation at all. Require the rejection this function owns.
+ assert.throws(() => providers.providerFamily('not-a-provider'), /unknown provider/)
+ assert.throws(() => providers.providerFamily(undefined), /unknown provider/)
+ })
+
+ it('lists family members in PROVIDER_IDS order, and nothing for an unknown family', () => {
+ assert.deepEqual(providers.familyProviderIds('openai'), ['openai', 'codex-subscription'])
+ assert.deepEqual(providers.familyProviderIds('xai'), ['xai', 'grok-subscription'])
+ assert.deepEqual(providers.familyProviderIds('claude'), ['claude'])
+ // A free-form provider string reaches this from the prices table. The honest
+ // answer is that no known provider belongs to that family.
+ assert.deepEqual(providers.familyProviderIds('not-a-provider'), [])
+ })
+
+ it('carries the family on the descriptor', () => {
+ assert.equal(providers.providerDescriptor('grok-subscription').family, 'xai')
+ assert.equal(providers.providerDescriptor('xai').family, 'xai')
+ assert.equal(providers.providerDescriptor('codex-subscription').family, 'openai')
+ assert.equal(providers.providerDescriptor('claude').family, 'claude')
+ })
+})
diff --git a/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs b/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs
index d6f693c50..99cacaf1b 100755
--- a/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs
+++ b/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs
@@ -38,6 +38,18 @@ if (rawOmitText !== undefined && (rawOmitText !== '1' || fixtureToolCallCount ==
}
const fixtureOmitText = rawOmitText === '1'
+// Optional: a second model id served alongside the baseline one. The catalog
+// re-sync lane needs an upstream that offers a model the grant's seeded state
+// does not carry, so that a model appearing in Control UI can only be the
+// result of re-reading the catalog. Unset keeps the single-model reply every
+// other lane expects, byte for byte.
+const fixtureExtraModel = process.env.CODEX_TEST_UPSTREAM_EXTRA_MODEL || undefined
+if (fixtureExtraModel !== undefined && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(fixtureExtraModel)) {
+ throw new Error(
+ 'CODEX_TEST_UPSTREAM_EXTRA_MODEL must be a model id of letters, digits, dot, underscore or hyphen'
+ )
+}
+
const counters = {
consent: 0,
models: 0,
@@ -128,9 +140,9 @@ const server = createServer({ cert, key }, async (request, response) => {
}
if (request.method === 'GET' && url.pathname === '/backend-api/codex/models') {
counters.models += 1
- return json(response, 200, {
- data: [{ id: 'gpt-5.3-codex', object: 'model' }],
- })
+ const models = [{ id: 'gpt-5.3-codex', object: 'model' }]
+ if (fixtureExtraModel) models.push({ id: fixtureExtraModel, object: 'model' })
+ return json(response, 200, { data: models })
}
if (request.method === 'POST' && url.pathname === '/backend-api/codex/responses') {
const body = JSON.parse((await readBody(request)) || '{}')
diff --git a/tests/e2e/fixtures/package-lock.json b/tests/e2e/fixtures/package-lock.json
index 17b402c80..27ae31092 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.86",
+ "version": "1.0.87",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.86",
+ "version": "1.0.87",
"dependencies": {
"@kubernetes/client-node": "^1.0.0"
},
diff --git a/tests/e2e/fixtures/package.json b/tests/e2e/fixtures/package.json
index a38efcff1..1835ae0ad 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.86",
+ "version": "1.0.87",
"description": "E2E test fixtures and utilities for Clerum testing",
"type": "module",
"main": "index.ts",
diff --git a/tests/e2e/playwright/control-ui/codex-subscription-catalog-resync.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-catalog-resync.spec.ts
new file mode 100644
index 000000000..2f373740a
--- /dev/null
+++ b/tests/e2e/playwright/control-ui/codex-subscription-catalog-resync.spec.ts
@@ -0,0 +1,152 @@
+/**
+ * Codex subscription — on-demand catalog re-sync from the grant modal.
+ *
+ * Scope note, so the next reader does not look here for a claim this lane
+ * cannot carry. The catalog upstream is frozen to chatgpt.com by
+ * `codex-llm-proxy/src/originPolicy.ts` and this lane deploys no fake upstream,
+ * so "a model published after the handshake becomes visible" is NOT provable
+ * here. That claim lives one layer down, in
+ * `codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts` ("hermetic catalog
+ * re-read"), which is the only place that redirects the frozen origin at a
+ * fixture, and one layer down again in
+ * `control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts`
+ * for the rows and the union allowlist.
+ *
+ * What this lane uniquely proves: the affordance exists on a connected grant
+ * and nowhere else, the click really issues the write, and the window settles
+ * on the answer the API gave instead of leaving the operator with a spinner
+ * and no verdict.
+ *
+ * Auth: `/` + loginControlUiVisible. No terminal `goto`. No test.skip.
+ */
+import { type Page, expect, test } from '@playwright/test'
+import { controlApi } from '../helpers/api-client'
+import { loginControlUiVisible } from '../helpers/visible-login'
+import { ControlUiShell, SecretsLlmSubscriptionsPage } from '../pages/codex-subscription'
+
+const SYNC_PATH =
+ /\/api\/v1\/admin\/llm\/providers\/codex-subscription\/connections\/[^/]+\/catalog\/sync$/
+
+// The closed set the route answers with (control-api/src/routes/admin/
+// codexSubscription.ts:734-770). A status outside it means the contract moved
+// and the mapping in CodexSubscriptionHub is stale, which is worth failing on
+// even though the operator-visible outcome would still be "an error banner".
+const DOCUMENTED_SYNC_STATUS = [200, 401, 403, 404, 409, 503]
+
+async function loginFromHome(page: Page) {
+ await page.goto('/')
+ await loginControlUiVisible(page)
+ await expect(page.getByLabel('Main navigation')).toBeVisible()
+}
+
+async function catalogRevisionOf(connectionKey: string): Promise<number> {
+ const row = (await controlApi.listCodexConnections()).find(
+ item => item.connectionKey === connectionKey
+ )
+ expect(row, `grant ${connectionKey} must still be listed`).toBeTruthy()
+ return row!.catalogRevision
+}
+
+test.describe('Codex subscription catalog re-sync', () => {
+ test('R1 Sync catalog issues the write and the modal settles on the API outcome', async ({
+ page,
+ }) => {
+ const shell = new ControlUiShell(page)
+ const hub = new SecretsLlmSubscriptionsPage(page)
+ await loginFromHome(page)
+ await shell.openSecretsLlmSubscriptions()
+
+ const connected = (await controlApi.listCodexConnections()).find(
+ row => row.status === 'connected'
+ )
+ expect(
+ connected,
+ 'R1 named precondition: a connected grant provisioned by the profile lane'
+ ).toBeTruthy()
+ const grantKey = connected!.connectionKey
+ const displayName = connected!.displayName || grantKey
+ const revisionBefore = await catalogRevisionOf(grantKey)
+
+ const modelsGet = page.waitForResponse(
+ response =>
+ new RegExp(
+ `/api/v1/admin/llm/providers/codex-subscription/connections/${grantKey}/models$`
+ ).test(new URL(response.url()).pathname) && response.request().method() === 'GET'
+ )
+ await hub.openGrant(displayName)
+ await modelsGet
+
+ const dialog = page.getByRole('dialog')
+ const syncButton = dialog.getByRole('button', { name: 'Sync catalog' })
+ await expect(syncButton).toBeVisible()
+ await expect(syncButton).toBeEnabled()
+
+ const syncPost = page.waitForResponse(
+ response =>
+ SYNC_PATH.test(new URL(response.url()).pathname) && response.request().method() === 'POST'
+ )
+ await syncButton.click()
+ const syncRes = await syncPost
+ expect(new URL(syncRes.url()).pathname).toBe(
+ `/api/v1/admin/llm/providers/codex-subscription/connections/${grantKey}/catalog/sync`
+ )
+ expect(
+ DOCUMENTED_SYNC_STATUS,
+ `catalog sync answered ${syncRes.status()}, outside the documented set`
+ ).toContain(syncRes.status())
+
+ const successToast = page.getByRole('status').filter({ hasText: 'Catalog synced' })
+ const errorBanner = dialog.locator('.cu-banner--error')
+
+ if (syncRes.status() === 200) {
+ const body = (await syncRes.json()) as { outcome?: string }
+ // A recorded outcome always advances catalog_revision
+ // (codexSubscriptionConnection.ts:692), so this is the business signal
+ // that the write landed rather than the UI merely redrawing.
+ expect(await catalogRevisionOf(grantKey)).toBeGreaterThan(revisionBefore)
+ if (body.outcome === 'ready') {
+ await expect(successToast).toBeVisible()
+ await expect(errorBanner).toHaveCount(0)
+ } else {
+ await expect(
+ page.getByRole('status').filter({ hasText: 'Catalog sync failed' })
+ ).toBeVisible()
+ }
+ } else {
+ // The operator must be told. An empty banner is the failure this guards:
+ // the modal would otherwise look identical to a successful sync.
+ await expect(errorBanner).toBeVisible()
+ await expect(errorBanner).not.toHaveText('')
+ await expect(successToast).toHaveCount(0)
+ }
+
+ // Whatever the outcome, the control comes back: a stuck busy state would
+ // leave the operator unable to retry, and both branches above are
+ // satisfied by a modal frozen mid-request.
+ await expect(syncButton).toBeEnabled()
+ })
+
+ test('R2 a grant that is not connected offers no Sync catalog', async ({ page }) => {
+ const shell = new ControlUiShell(page)
+ const hub = new SecretsLlmSubscriptionsPage(page)
+ const displayName = `e2e-resync-guard-${Date.now().toString(36)}`
+ await loginFromHome(page)
+ await shell.openSecretsLlmSubscriptions()
+
+ const grantKey = await hub.createGrant(displayName)
+ const dialog = page.getByRole('dialog')
+ // Liveness witness for the negative below: this is the connect modal of a
+ // real grant that exists and is not connected, not an empty dialog and not
+ // an unrendered one.
+ await expect(dialog.getByRole('button', { name: 'Sign in with ChatGPT' })).toBeVisible()
+ const created = (await controlApi.listCodexConnections()).find(
+ row => row.connectionKey === grantKey
+ )
+ expect(created, 'the grant under test must be listed').toBeTruthy()
+ expect(created!.status).not.toBe('connected')
+
+ await expect(dialog.getByRole('button', { name: 'Sync catalog' })).toHaveCount(0)
+
+ await hub.closeConnectModal()
+ })
+})
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 2007a8f39..0b13d6b98 100644
--- a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts
+++ b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts
@@ -181,10 +181,16 @@ test.describe('Codex subscription connection', () => {
)
await hub.openGrant(displayName)
await modelsGet
- await expect(
- page.getByRole('dialog').getByRole('button', { name: 'Sync catalog' })
- ).toHaveCount(0)
- await expect(page.getByRole('dialog').locator('input[type="checkbox"]')).toHaveCount(0)
+ // A connected grant's modal carries both affordances. The two assertions
+ // this replaces required their absence, and neither could hold any more:
+ // `b0f84b148` restored the per-model toggles when it restyled the modal,
+ // and the catalog is read only at sign-in, so a connected grant needs a way
+ // to pick up models the vendor published since. Both controls are visible
+ // here, and `expectConnectModal` still requires their absence before the
+ // grant is connected.
+ const syncButton = page.getByRole('dialog').getByRole('button', { name: 'Sync catalog' })
+ await expect(syncButton).toBeVisible()
+ await expect(page.getByRole('dialog').locator('input[type="checkbox"]').first()).toBeVisible()
await page.getByLabel('Default model').click()
const defaultOption = page.getByRole('option').first()
diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.json
index a13bb13e1..7acdea7b6 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.62",
+ "version": "0.1.63",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-playwright-tests",
- "version": "0.1.62",
+ "version": "0.1.63",
"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 df6aab448..8260c6483 100644
--- a/tests/e2e/playwright/package.json
+++ b/tests/e2e/playwright/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-playwright-tests",
- "version": "0.1.62",
+ "version": "0.1.63",
"private": true,
"description": "Playwright E2E tests for Control UI and Desktop App",
"scripts": {