Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(codex): fold ChatGPT subscriptions into Secrets LLM
Alfredo Lopezffd9543dc9ee
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex c21e5539f..7c300491b 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.502",+ "version": "0.1.503","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.502",+ "version": "0.1.503","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/image-policy": "file:../packages/image-policy",diff --git a/control-api/package.json b/control-api/package.jsonindex 4a24ed023..85b2d1640 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.502",+ "version": "0.1.503","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/db.ts b/control-api/src/db.tsindex c448b0232..c041a4323 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -8,6 +8,7 @@ import { config } from './config.js'import { applyCodexCatalogModelsSchema } from './services/codexSubscriptionCatalog.js'import {applyCodexChatgptAccountIdSchema,+ applyCodexGrantDefaultModelSchema,applyCodexMultiConnectionSchema,applyCodexSubscriptionConnectionSchema,} from './services/codexSubscriptionConnection.js'@@ -5976,6 +5977,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [version: '0103_llm_provider_attempts_connection_id',apply: applyLlmProviderAttemptConnectionIdSchema,},+ {+ version: '0104_codex_grant_default_model',+ apply: applyCodexGrantDefaultModelSchema,+ },]async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {diff --git a/control-api/src/routes/admin/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.tsindex b73a5c2a3..cb9d2dd6f 100644--- a/control-api/src/routes/admin/codexSubscription.ts+++ b/control-api/src/routes/admin/codexSubscription.ts@@ -12,6 +12,7 @@ import {listCodexCatalogModels,listOfferedCodexModelsForAssignment,pickCodexGrantModel,+ setCodexCatalogModelEnabled,syncCodexSubscriptionCatalog,} from '../../services/codexSubscriptionCatalog.js'import {@@ -20,9 +21,11 @@ import {assertCodexConnectionKey,createNamedCodexSubscriptionConnection,generateCodexConnectionKey,+ getSafeCodexSubscriptionConnection,listSafeCodexSubscriptionConnections,loadCodexSubscriptionSecrets,normalizeCodexConnectionKey,+ updateCodexSubscriptionConnectionMetadata,} from '../../services/codexSubscriptionConnection.js'import {type CodexOAuthDeps,@@ -269,7 +272,8 @@ export function createAdminCodexSubscriptionRouter('This subscription has no offered models yet. Sign in and sync the catalog before assigning agents.',}}- resolvedModel = pickCodexGrantModel(resolvedModel, offered)+ const grant = await getSafeCodexSubscriptionConnection(dbClient(), nextConnectionRef)+ resolvedModel = pickCodexGrantModel(resolvedModel, offered, grant?.defaultModel)model.name = resolvedModel}spec.model = model@@ -595,6 +599,95 @@ export function createAdminCodexSubscriptionRouter(}))+ router.patch(+ `${BASE}/connections/:key`,+ ...adminCodexWriteRateLimits(),+ asyncHandler(async (req, res) => {+ if (!config.codexSubscriptionEnabled) {+ res.status(404).json({ error: 'disabled' })+ return+ }+ let connectionKey: string+ try {+ connectionKey = keyFromReq(req)+ } catch (err) {+ sendOAuthError(res, err)+ return+ }+ const hasDisplayName = typeof req.body?.displayName === 'string'+ const hasDefaultModel = Object.prototype.hasOwnProperty.call(req.body ?? {}, 'defaultModel')+ if (!hasDisplayName && !hasDefaultModel) {+ res.status(400).json({ error: 'empty_patch' })+ return+ }+ const defaultModel = hasDefaultModel+ ? typeof req.body.defaultModel === 'string'+ ? req.body.defaultModel.trim()+ : ''+ : undefined+ if (defaultModel) {+ const offered = await listOfferedCodexModelsForAssignment(dbClient(), connectionKey)+ if (!offered.includes(defaultModel)) {+ res.status(422).json({ error: 'default_model_not_offered' })+ return+ }+ }+ const updated = await updateCodexSubscriptionConnectionMetadata(dbClient(), connectionKey, {+ ...(hasDisplayName ? { displayName: req.body.displayName } : {}),+ ...(hasDefaultModel ? { defaultModel: defaultModel || null } : {}),+ })+ if (!updated) {+ res.status(404).json({ error: 'no_grant' })+ return+ }+ res.status(200).json(await withAssignedHosts(updated))+ })+ )++ router.patch(+ `${BASE}/connections/:key/models/:model`,+ ...adminCodexWriteRateLimits(),+ asyncHandler(async (req, res) => {+ if (!config.codexSubscriptionEnabled) {+ res.status(404).json({ error: 'disabled' })+ return+ }+ let connectionKey: string+ try {+ connectionKey = keyFromReq(req)+ } catch (err) {+ sendOAuthError(res, err)+ return+ }+ if (typeof req.body?.enabled !== 'boolean') {+ res.status(400).json({ error: 'invalid_enabled' })+ return+ }+ const connection = await getSafeCodexSubscriptionConnection(dbClient(), connectionKey)+ if (!connection) {+ res.status(404).json({ error: 'no_grant' })+ return+ }+ const model = typeof req.params.model === 'string' ? req.params.model.trim() : ''+ if (!model) {+ res.status(404).json({ error: 'model_not_found' })+ return+ }+ const models = await setCodexCatalogModelEnabled(+ dbClient(),+ connection.id,+ model,+ req.body.enabled+ )+ if (!models) {+ res.status(404).json({ error: 'model_not_found' })+ return+ }+ if (await publishRuntimeAllowlistOrFail(res)) return+ res.status(200).json({ models })+ })+ )+router.get(`${BASE}/assignable-hosts`,...adminCodexReadRateLimits(),diff --git a/control-api/src/services/codexSubscriptionCatalog.ts b/control-api/src/services/codexSubscriptionCatalog.tsindex 17e5e6b9d..2c0351219 100644--- a/control-api/src/services/codexSubscriptionCatalog.ts+++ b/control-api/src/services/codexSubscriptionCatalog.ts@@ -181,9 +181,15 @@ export async function isCodexAssignmentAllowed(* only when that grant already offers it. Otherwise seed the first offered* model — never invent deployment-default or a global allowlist default.*/-export function pickCodexGrantModel(current: string, offered: string[]): string {+export function pickCodexGrantModel(+ current: string,+ offered: string[],+ grantDefault?: string | null+): string {const trimmed = current.trim()if (trimmed && offered.includes(trimmed)) return trimmed+ const fallback = grantDefault?.trim() ?? ''+ if (fallback && offered.includes(fallback)) return fallbackreturn offered[0] ?? trimmed}@@ -229,6 +235,26 @@ export async function listEnabledCodexModelsGroupedByConnection(return grouped}+export async function setCodexCatalogModelEnabled(+ db: DbClient,+ connectionId: string,+ model: string,+ enabled: boolean+): Promise<Array<{ model: string; enabled: boolean; stale: boolean }> | null> {+ const updated = await db.query(+ `UPDATE codex_catalog_models+ SET enabled = $3,+ updated_at = now()+ WHERE connection_id = $1+ AND model = $2+ RETURNING model`,+ [connectionId, model, enabled]+ )+ if (updated.rowCount === 0) return null+ await rebuildLiveCodexUnionAllowlist(db)+ return listCodexCatalogModels(db, connectionId)+}+export async function listCodexCatalogModels(db: DbClient,connectionId: stringdiff --git a/control-api/src/services/codexSubscriptionConnection.ts b/control-api/src/services/codexSubscriptionConnection.tsindex cef7d24d1..1b6fe91db 100644--- a/control-api/src/services/codexSubscriptionConnection.ts+++ b/control-api/src/services/codexSubscriptionConnection.ts@@ -76,6 +76,7 @@ export type CodexSubscriptionSafeConnection = {id: stringconnectionKey: stringdisplayName: string+ defaultModel: string | nullcreatedBy: string | nullstatus: CodexSubscriptionConnectionStatuscredentialRevision: number@@ -112,6 +113,7 @@ type SafeConnectionRow = {id: stringconnection_key: stringdisplay_name: string | null+ default_model: string | nullcreated_by: string | nullstatus: CodexSubscriptionConnectionStatuscredential_revision: string | number@@ -132,6 +134,7 @@ const SAFE_CONNECTION_COLUMNS = `id,connection_key,display_name,+ default_model,created_by,status,credential_revision,@@ -246,6 +249,13 @@ export async function applyCodexMultiConnectionSchema(db: DbClient): Promise<voi`)}+export async function applyCodexGrantDefaultModelSchema(db: DbClient): Promise<void> {+ await db.query(`+ ALTER TABLE codex_subscription_connections+ ADD COLUMN IF NOT EXISTS default_model TEXT+ `)+}+export async function getSafeCodexSubscriptionConnection(db: DbClient,connectionKey: string = CODEX_SUBSCRIPTION_CONNECTION_KEY@@ -628,11 +638,44 @@ function remapFingerprintConflict(err: unknown): never | Error {throw err}+export async function updateCodexSubscriptionConnectionMetadata(+ db: DbClient,+ connectionKey: string,+ patch: { displayName?: string; defaultModel?: string | null }+): Promise<CodexSubscriptionSafeConnection | null> {+ const key = assertCodexConnectionKey(normalizeCodexConnectionKey(connectionKey))+ const sets: string[] = ['updated_at = now()']+ const values: unknown[] = []+ if (typeof patch.displayName === 'string') {+ values.push(patch.displayName.trim() || key)+ sets.push(`display_name = $${values.length}`)+ }+ if (patch.defaultModel !== undefined) {+ const next = typeof patch.defaultModel === 'string' ? patch.defaultModel.trim() : ''+ values.push(next || null)+ sets.push(`default_model = $${values.length}`)+ }+ if (values.length === 0) {+ return getSafeCodexSubscriptionConnection(db, key)+ }+ values.push(key)+ const result = await db.query(+ `UPDATE codex_subscription_connections+ SET ${sets.join(', ')}+ WHERE connection_key = $${values.length}+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,+ values+ )+ const row = result.rows[0] as SafeConnectionRow | undefined+ return row ? toSafeConnection(row) : null+}+function toSafeConnection(row: SafeConnectionRow): CodexSubscriptionSafeConnection {return {id: String(row.id),connectionKey: row.connection_key,displayName: row.display_name?.trim() || row.connection_key,+ defaultModel: row.default_model?.trim() || null,createdBy: row.created_by,status: row.status,credentialRevision: Number(row.credential_revision),diff --git a/control-api/test/db.codexSubscriptionMigration.test.ts b/control-api/test/db.codexSubscriptionMigration.test.tsindex d90e5d192..c40572a3f 100644--- a/control-api/test/db.codexSubscriptionMigration.test.ts+++ b/control-api/test/db.codexSubscriptionMigration.test.ts@@ -57,6 +57,11 @@ describe('00a0/00a1 Codex subscription persistence', () => {expect(dbSource.indexOf("version: '0102_codex_catalog_models'")).toBeLessThan(dbSource.indexOf("version: '0103_llm_provider_attempts_connection_id'"))+ expect(dbSource).toContain("version: '0104_codex_grant_default_model'")+ expect(dbSource.indexOf("version: '0103_llm_provider_attempts_connection_id'")).toBeLessThan(+ dbSource.indexOf("version: '0104_codex_grant_default_model'")+ )+ expect(connectionSource).toContain('ADD COLUMN IF NOT EXISTS default_model')})it('creates a single active deployment-default connection with ciphertext and revisions', () => {diff --git a/control-api/test/routes.admin.codexSubscription.hostWrite.test.ts b/control-api/test/routes.admin.codexSubscription.hostWrite.test.tsindex 5a78d7d0a..cdb8d3f85 100644--- a/control-api/test/routes.admin.codexSubscription.hostWrite.test.ts+++ b/control-api/test/routes.admin.codexSubscription.hostWrite.test.ts@@ -21,6 +21,7 @@ vi.mock('../src/db.js', () => ({pool: { query: vi.fn() },}))+const { pool } = await import('../src/db.js')const { config } = await import('../src/config.js')const { createAdminCodexSubscriptionRouter } =await import('../src/routes/admin/codexSubscription.js')@@ -57,6 +58,32 @@ describe('admin Codex bind/unbind host write contract', () => {assignment.isCodexAssignmentAllowed.mockResolvedValue(true)assignment.listOfferedCodexModelsForAssignment.mockReset()assignment.listOfferedCodexModelsForAssignment.mockResolvedValue(['gpt-5.6-luna'])+ vi.mocked(pool.query).mockReset()+ vi.mocked(pool.query).mockResolvedValue({+ rows: [+ {+ id: 'id-codex-aaa',+ connection_key: 'codex-aaa',+ display_name: 'Team A',+ default_model: null,+ created_by: null,+ status: 'connected',+ credential_revision: 1,+ catalog_revision: 1,+ account_fingerprint: 'fp',+ catalog_status: 'ready',+ catalog_synced_at: new Date(),+ last_refresh_at: new Date(),+ last_auth_at: new Date(),+ refresh_lock_token: null,+ refresh_lock_expires_at: null,+ revoked_at: null,+ created_at: new Date(),+ updated_at: new Date(),+ },+ ],+ rowCount: 1,+ })})afterEach(() => {@@ -209,7 +236,32 @@ describe('admin Codex bind/unbind host write contract', () => {})it('converts a non-Codex host and seeds the grant default model', async () => {- assignment.listOfferedCodexModelsForAssignment.mockResolvedValue(['gpt-5.1'])+ assignment.listOfferedCodexModelsForAssignment.mockResolvedValue(['gpt-5.1', 'gpt-5.6-luna'])+ vi.mocked(pool.query).mockResolvedValue({+ rows: [+ {+ id: 'id-codex-aaa',+ connection_key: 'codex-aaa',+ display_name: 'Team A',+ default_model: 'gpt-5.1',+ created_by: null,+ status: 'connected',+ credential_revision: 1,+ catalog_revision: 1,+ account_fingerprint: 'fp',+ catalog_status: 'ready',+ catalog_synced_at: new Date(),+ last_refresh_at: new Date(),+ last_auth_at: new Date(),+ refresh_lock_token: null,+ refresh_lock_expires_at: null,+ revoked_at: null,+ created_at: new Date(),+ updated_at: new Date(),+ },+ ],+ rowCount: 1,+ })const gateway = makeGateway()gateway.getResource.mockResolvedValue({metadata: { name: 'api-agent', resourceVersion: '4' },diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.tsindex 652efd169..3924b943e 100644--- a/control-api/test/routes.admin.codexSubscription.test.ts+++ b/control-api/test/routes.admin.codexSubscription.test.ts@@ -103,6 +103,7 @@ function safeCreatedRow(connectionKey: string, displayName: string) {id: `id-${connectionKey}`,connection_key: connectionKey,display_name: displayName,+ default_model: null,created_by: null,status: 'disconnected',credential_revision: 1,@@ -559,6 +560,10 @@ describe('admin Codex subscription routes', () => {it('binds an unassigned host and can switch from another named grant', async () => {const gateway = makeGateway()+ vi.mocked(pool.query).mockResolvedValue({+ rows: [{ ...safeCreatedRow('codex-aaa', 'Team A'), default_model: 'gpt-5.1' }],+ rowCount: 1,+ })gateway.getResource.mockResolvedValueOnce({metadata: { name: 'chatllm' },spec: {@@ -596,6 +601,10 @@ describe('admin Codex subscription routes', () => {it('binds a Codex host whose connectionRef is missing as unassigned', async () => {const gateway = makeGateway()+ vi.mocked(pool.query).mockResolvedValue({+ rows: [{ ...safeCreatedRow('codex-aaa', 'Team A'), default_model: 'gpt-5.1' }],+ rowCount: 1,+ })gateway.getResource.mockResolvedValue({metadata: { name: 'chatllm' },spec: { model: { provider: 'codex-subscription' } },@@ -641,4 +650,83 @@ describe('admin Codex subscription routes', () => {expect(res.body).toEqual({ error: 'not_codex_host' })expect(gateway.updateResource).not.toHaveBeenCalled()})++ it('patches displayName and defaultModel when the model is offered', async () => {+ catalog.listOffered.mockResolvedValue(['gpt-5.1', 'gpt-5.6-luna'])+ vi.mocked(pool.query).mockResolvedValueOnce({+ rows: [{ ...safeCreatedRow('codex-aaa', 'Team Plus'), default_model: 'gpt-5.6-luna' }],+ rowCount: 1,+ })+ const res = await request(app)+ .patch('/admin/llm/providers/codex-subscription/connections/codex-aaa')+ .send({ displayName: 'Team Plus', defaultModel: 'gpt-5.6-luna' })+ expect(res.status).toBe(200)+ expect(res.body.displayName).toBe('Team Plus')+ expect(res.body.defaultModel).toBe('gpt-5.6-luna')+ assertNoLeak(res.body)+ })++ it('rejects a defaultModel that the grant does not offer', async () => {+ catalog.listOffered.mockResolvedValue(['gpt-5.1'])+ const res = await request(app)+ .patch('/admin/llm/providers/codex-subscription/connections/codex-aaa')+ .send({ defaultModel: 'gpt-5.6-luna' })+ expect(res.status).toBe(422)+ expect(res.body).toEqual({ error: 'default_model_not_offered' })+ })++ it('lists grant models and toggles enabled', async () => {+ oauth.getConnection.mockResolvedValue({+ id: 'id-codex-aaa',+ connectionKey: 'codex-aaa',+ status: 'connected',+ })+ vi.mocked(pool.query)+ .mockResolvedValueOnce({+ rows: [+ { model: 'gpt-5.1', enabled: true, stale: false },+ { model: 'gpt-5.6-luna', enabled: true, stale: false },+ ],+ })+ .mockResolvedValueOnce({ rows: [{ ...safeCreatedRow('codex-aaa', 'Team') }], rowCount: 1 })+ .mockResolvedValueOnce({ rows: [{ model: 'gpt-5.1' }], rowCount: 1 })+ .mockResolvedValue({ rows: [], rowCount: 0 })+ const listed = await request(app).get(+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/models'+ )+ expect(listed.status).toBe(200)+ expect(listed.body.models).toEqual([+ { model: 'gpt-5.1', enabled: true, stale: false },+ { model: 'gpt-5.6-luna', enabled: true, stale: false },+ ])++ const gateway = makeGateway()+ vi.mocked(pool.query).mockImplementation(async (sql: unknown) => {+ const text = String(sql)+ if (text.includes('UPDATE codex_catalog_models')) {+ return { rows: [{ model: 'gpt-5.1' }], rowCount: 1 }+ }+ if (text.includes('SELECT model, enabled, stale')) {+ return {+ rows: [+ { model: 'gpt-5.1', enabled: false, stale: false },+ { model: 'gpt-5.6-luna', enabled: true, stale: false },+ ],+ rowCount: 2,+ }+ }+ if (text.includes('codex_subscription_connections')) {+ return { rows: [{ ...safeCreatedRow('codex-aaa', 'Team') }], rowCount: 1 }+ }+ return { rows: [], rowCount: 0 }+ })+ const patched = await request(makeAuthedApp(gateway))+ .patch('/admin/llm/providers/codex-subscription/connections/codex-aaa/models/gpt-5.1')+ .send({ enabled: false })+ expect(patched.status).toBe(200)+ expect(patched.body.models).toEqual([+ { model: 'gpt-5.1', enabled: false, stale: false },+ { model: 'gpt-5.6-luna', enabled: true, stale: false },+ ])+ })})diff --git a/control-api/test/services.codexSubscriptionCatalog.test.ts b/control-api/test/services.codexSubscriptionCatalog.test.tsindex b52c24dd4..c592bbe84 100644--- a/control-api/test/services.codexSubscriptionCatalog.test.ts+++ b/control-api/test/services.codexSubscriptionCatalog.test.ts@@ -24,6 +24,17 @@ describe('pickCodexGrantModel', () => {expect(pickCodexGrantModel('gpt-5.4-mini', [])).toBe('gpt-5.4-mini')expect(pickCodexGrantModel('', [])).toBe('')})++ it('prefers the grant default when the current name is not offered', () => {+ expect(pickCodexGrantModel('', ['gpt-5.1', 'gpt-5.6-luna'], 'gpt-5.6-luna')).toBe(+ 'gpt-5.6-luna'+ )+ expect(pickCodexGrantModel('gpt-5.1', ['gpt-5.1', 'gpt-5.6-luna'], 'gpt-5.6-luna')).toBe(+ 'gpt-5.1'+ )+ expect(pickCodexGrantModel('', ['gpt-5.1'], 'missing')).toBe('gpt-5.1')+ expect(pickCodexGrantModel('', [], 'gpt-5.6-luna')).toBe('')+ })})describe('planCodexCatalogReconcile', () => {diff --git a/control-ui/app/constants/routes.ts b/control-ui/app/constants/routes.tsindex 1ac2f2275..0966ada4f 100644--- a/control-ui/app/constants/routes.ts+++ b/control-ui/app/constants/routes.ts@@ -121,9 +121,10 @@ export const CONTROL_ROUTES = {secrets: {root: '/secrets',llm: '/secrets/llm',+ llmSubscriptions: '/secrets/llm/subscriptions',connector: '/secrets/connector',recipe: '/secrets/recipe',- subscription: '/secrets/subscription',+ subscription: '/secrets/llm/subscriptions',new: (query?: ControlRouteQuery) => withQuery('/secrets/new', query),editRecipe: (name: string, query?: ControlRouteQuery) =>withQuery(`/secrets/recipe/${segment(name)}/edit`, query),diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex 256ede412..26fc31eeb 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -12467,93 +12467,3 @@ button.cu-gfs-tree__button:focus-visible,.cu-llm-policy__actions {display: flex;}--.cu-codex-hub__create {- display: flex;- flex-direction: column;- gap: 0.35rem;- padding: 0.75rem 1rem 0;-}--.cu-codex-hub__create-row {- display: flex;- flex-wrap: wrap;- gap: 0.5rem;- align-items: center;-}--.cu-codex-hub__create-row input {- min-width: 16rem;- flex: 1 1 16rem;-}--.cu-codex-hub__agents-cell {- display: flex;- flex-direction: column;- gap: 0.5rem;-}--.cu-codex-hub__agent-chip {- display: inline-flex;- align-items: center;- gap: 0.35rem;-}--.cu-codex-hub__agent-chip a {- color: inherit;- text-decoration: none;- font-weight: 600;-}--.cu-codex-hub__agent-chip a:hover {- text-decoration: underline;-}--.cu-codex-hub__agent-model {- color: var(--cu-text-muted);- font-weight: 400;- font-size: 0.85em;-}--.cu-codex-hub__chip-remove {- display: inline-grid;- place-items: center;- width: 1.1rem;- height: 1.1rem;- padding: 0;- border: 0;- border-radius: 0.25rem;- background: transparent;- color: var(--cu-text-muted);- cursor: pointer;-}--.cu-codex-hub__chip-remove:hover:not(:disabled) {- color: var(--cu-text);- background: var(--cu-bg-panel);-}--.cu-codex-hub__chip-remove:disabled {- opacity: 0.45;- cursor: not-allowed;-}--.cu-codex-hub__add {- display: flex;- flex-wrap: wrap;- align-items: flex-start;- gap: 0.5rem;-}--.cu-codex-hub__picker {- min-width: 14rem;- max-width: 22rem;- flex: 1 1 14rem;-}--.cu-codex-hub__row-actions {- display: inline-flex;- flex-wrap: wrap;- justify-content: flex-end;- gap: 0.35rem;-}diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsxindex 9e6f75852..a8529bd6c 100644--- a/control-ui/app/hosts/[name]/page.tsx+++ b/control-ui/app/hosts/[name]/page.tsx@@ -7,7 +7,6 @@ import { DetailPageShell } from '@components/DetailPageShell'import { useToast } from '@components/Toast'import { HOST_DEFAULT_TAB, HOST_TABS } from '@constants/hostDetails'import { CONTROL_ROUTES } from '@constants/routes'-import { CodexAgentAssignment } from '../../../components/CodexAgentAssignment'import { HostAccessTab } from '../../../components/HostAccessTab'import { HostAdvancedTab } from '../../../components/HostAdvancedTab'import type { HostGuardrails } from '../../../components/HostGuardrailsSection/types'@@ -19,6 +18,7 @@ import { apiSend, getHost, getHostDetailBundle } from '../../../lib/api'import {CODEX_UNASSIGNED_CONNECTION_KEY,type CodexSubscriptionConnectionView,+ listCodexConnectionModels,listCodexSubscriptionConnections,} from '../../../lib/codexSubscription'import { useLlmAllowedModels } from '../../../lib/hooks/useLlmAllowedModels'@@ -34,7 +34,6 @@ import {getModelOptions,getProviderLabel,hostModelNameError,- isOpenAiFamily,isProviderUsable,llmChainRequiresSecret,normalizeAllowedModels,@@ -46,6 +45,7 @@ import {validateLlmPolicy,validateLlmSecretData,} from '../../../lib/llm'+import { credentialSelectValue, parseCredentialSelect } from '../../../lib/llmCredentialSelect'import type { HostTab } from './types'const TAB_LABELS: Record<HostTab, string> = {@@ -145,8 +145,9 @@ export default function HostDetailsPage() {const [codexModels, setCodexModels] = useState<string[]>([])const [codexConnections, setCodexConnections] = useState<CodexSubscriptionConnectionView[]>([])const catalogForEditor = useMemo(() => {- if (providerDraft !== 'codex-subscription' || codexModels.length === 0) return allowedCatalog+ if (providerDraft !== 'codex-subscription') return allowedCatalogconst others = allowedCatalog.filter(row => row.provider !== 'codex-subscription')+ if (codexModels.length === 0) return othersreturn [...others,...codexModels.map(model => ({@@ -247,10 +248,6 @@ export default function HostDetailsPage() {}, [allowedModelsDraft, catalogForEditor, modelNameDraft, providerDraft, providerModelOptions])useEffect(() => {- if (providerDraft !== 'codex-subscription') {- setCodexConnections([])- return- }let cancelled = falsevoid listCodexSubscriptionConnections().then(rows => {@@ -262,7 +259,26 @@ export default function HostDetailsPage() {return () => {cancelled = true}- }, [providerDraft])+ }, [])++ useEffect(() => {+ if (!connectionRefDraft.trim() || connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY) {+ setCodexModels([])+ return+ }+ let cancelled = false+ void listCodexConnectionModels(connectionRefDraft)+ .then(models => {+ if (cancelled) return+ setCodexModels(models.filter(row => row.enabled && !row.stale).map(row => row.model))+ })+ .catch(() => {+ if (!cancelled) setCodexModels([])+ })+ return () => {+ cancelled = true+ }+ }, [connectionRefDraft])useEffect(() => {setActiveTab(parseHostTab(params.tab))@@ -459,6 +475,39 @@ export default function HostDetailsPage() {setLlmKeyDraft({})}+ function handleCredentialChange(value: string) {+ const parsed = parseCredentialSelect(value)+ if (parsed.kind === 'empty') {+ setSecretRefDraft('')+ setConnectionRefDraft(CODEX_UNASSIGNED_CONNECTION_KEY)+ setCodexModels([])+ return+ }+ if (parsed.kind === 'subscription') {+ const grant = codexConnections.find(row => row.connectionKey === parsed.connectionKey)+ setSecretRefDraft('')+ setConnectionRefDraft(parsed.connectionKey)+ setProviderDraft('codex-subscription')+ void listCodexConnectionModels(parsed.connectionKey)+ .then(models => {+ const offered = models.filter(row => row.enabled && !row.stale).map(row => row.model)+ setCodexModels(offered)+ setModelNameDraft(resolveCodexGrantModel(grant?.defaultModel ?? '', offered))+ })+ .catch(() => {+ setCodexModels([])+ })+ return+ }+ setSecretRefDraft(parsed.name)+ setConnectionRefDraft(CODEX_UNASSIGNED_CONNECTION_KEY)+ setCodexModels([])+ if (providerDraft === 'codex-subscription') {+ setProviderDraft('openai')+ setModelNameDraft(resolveDefaultModel('openai', getModelOptions(allowedCatalog, 'openai')))+ }+ }+async function saveHost(): Promise<boolean> {const nextHostName = hostNameDraft.trim()if (!nextHostName) return false@@ -1044,25 +1093,17 @@ export default function HostDetailsPage() {<label htmlFor="model-provider">Model provider</label><div className="cu-field__readonly">{getProviderLabel(providerDraft)}</div></div>- {isOpenAiFamily(providerDraft) ? (- <div className="cu-field">- <label htmlFor="model-openai-credential">OpenAI credential</label>- <div className="cu-field__readonly">- {providerDraft === 'codex-subscription' ? 'ChatGPT subscription' : 'API key'}- </div>- </div>- ) : null}- {providerDraft === 'codex-subscription' ? (- <div className="cu-field">- <label htmlFor="model-subscription">Subscription</label>- <div className="cu-field__readonly" id="model-subscription">- {connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY- ? 'No subscription assigned'+ <div className="cu-field">+ <label htmlFor="model-credential">Credential</label>+ <div className="cu-field__readonly" id="model-credential">+ {providerDraft === 'codex-subscription'+ ? connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY+ ? 'No credential assigned': codexConnections.find(row => row.connectionKey === connectionRefDraft)- ?.displayName || connectionRefDraft}- </div>+ ?.displayName || connectionRefDraft+ : secretRefDraft || '-'}</div>- ) : null}+ </div><div className="cu-field"><label htmlFor="model-name">Default model</label><div className="cu-field__readonly" id="model-name">@@ -1085,17 +1126,13 @@ export default function HostDetailsPage() {</div>)}</div>- {llmChainRequiresSecret(providerDraft, llmPolicyDraft?.fallbacks) ? (+ {providerDraft === 'codex-subscription' &&+ llmChainRequiresSecret(providerDraft, llmPolicyDraft?.fallbacks) ? (<div className="cu-field"><label htmlFor="model-secret">Secret reference</label><div className="cu-field__readonly">{secretRefDraft || '-'}</div></div>- ) : (- <div className="cu-field">- <label htmlFor="model-secret">Secret reference</label>- <div className="cu-field__readonly">Broker-backed — no LLM secret required</div>- </div>- )}+ ) : null}<div className="cu-field"><label htmlFor="model-fallback">Fallback policy</label>{llmPolicyDraft && llmPolicyDraft.fallbacks.length > 0 ? (@@ -1130,12 +1167,68 @@ export default function HostDetailsPage() {</button></div>) : null}- {llmChainRequiresSecret(providerDraft, llmPolicyDraft?.fallbacks) ? (- <div className="cu-form-stack" style={{ marginBottom: '1rem' }}>+ <div className="cu-form-stack" style={{ marginBottom: '1rem' }}>+ <div className="cu-field">+ <label htmlFor="host-secret">Credential</label>+ <select+ id="host-secret"+ value={credentialSelectValue(secretRefDraft, connectionRefDraft)}+ onChange={e => handleCredentialChange(e.target.value)}+ disabled={busy}+ >+ <option value="">Select credential</option>+ {availableSecrets.length > 0 ? (+ <optgroup label="API keys">+ {availableSecrets.map(secretName => (+ <option key={secretName} value={secretName}>+ {secretName}+ </option>+ ))}+ {secretRefDraft &&+ parseCredentialSelect(secretRefDraft).kind === 'secret' &&+ !availableSecrets.includes(secretRefDraft) ? (+ <option value={secretRefDraft}>{secretRefDraft} (custom)</option>+ ) : null}+ </optgroup>+ ) : secretRefDraft &&+ parseCredentialSelect(secretRefDraft).kind === 'secret' ? (+ <optgroup label="API keys">+ <option value={secretRefDraft}>{secretRefDraft} (custom)</option>+ </optgroup>+ ) : null}+ {codexConnections.some(row => row.status !== 'revoked') ? (+ <optgroup label="Subscriptions">+ {codexConnections+ .filter(row => row.status !== 'revoked')+ .map(row => (+ <option+ key={row.connectionKey}+ value={credentialSelectValue('', row.connectionKey)}+ >+ {row.displayName || row.connectionKey}+ </option>+ ))}+ </optgroup>+ ) : null}+ </select>+ <p className="cu-muted" style={{ marginTop: '0.35rem' }}>+ <a+ href={+ providerDraft === 'codex-subscription'+ ? CONTROL_ROUTES.secrets.llmSubscriptions+ : CONTROL_ROUTES.secrets.llm+ }+ >+ Manage credentials in Secrets+ </a>+ </p>+ </div>+ {providerDraft === 'codex-subscription' &&+ llmChainRequiresSecret(providerDraft, llmPolicyDraft?.fallbacks) ? (<div className="cu-field">- <label htmlFor="host-secret">Secret reference</label>+ <label htmlFor="host-fallback-secret">Secret reference</label><select- id="host-secret"+ id="host-fallback-secret"value={secretRefDraft}onChange={e => setSecretRefDraft(e.target.value)}disabled={busy}@@ -1151,27 +1244,19 @@ export default function HostDetailsPage() {) : null}</select></div>- </div>- ) : null}+ ) : null}+ </div><LlmProviderConfigprovider={providerDraft}model={modelNameDraft}modelLabel="Default model"- subscriptionCredentialEnabled- afterPrimaryProvider={- providerDraft === 'codex-subscription' ? (- <CodexAgentAssignment- connectionRef={connectionRefDraft}- hostName={routeName}- onConnectionRefChange={setConnectionRefDraft}- onModelsChange={setCodexModels}- disabled={busy}- />- ) : null- }onPrimaryChange={next => {setProviderDraft(next.provider)setModelNameDraft(next.model)+ if (next.provider !== 'codex-subscription') {+ setConnectionRefDraft(CODEX_UNASSIGNED_CONNECTION_KEY)+ setCodexModels([])+ }}}policy={llmPolicyDraft}onPolicyChange={handlePolicyChange}diff --git a/control-ui/app/secrets/SecretsPageContent.tsx b/control-ui/app/secrets/SecretsPageContent.tsxindex 9c2fa6e25..f2f9b28dd 100644--- a/control-ui/app/secrets/SecretsPageContent.tsx+++ b/control-ui/app/secrets/SecretsPageContent.tsx@@ -9,7 +9,8 @@ import { SecretsTable } from '@components/SecretsTable'import { CONTROL_ROUTES } from '@constants/routes'import { apiGet, isSilentApiError } from '@lib/api'-export type SecretScope = 'llm' | 'mcp' | 'recipe' | 'subscription'+export type SecretScope = 'llm' | 'mcp' | 'recipe'+export type LlmSecretsSubTab = 'api-key' | 'subscriptions'type SecretItem = {name?: string@@ -17,7 +18,13 @@ type SecretItem = {keys?: string[]}-export function SecretsPageContent({ activeScope }: { activeScope: SecretScope }) {+export function SecretsPageContent({+ activeScope,+ llmSubTab = 'api-key',+}: {+ activeScope: SecretScope+ llmSubTab?: LlmSecretsSubTab+}) {const router = useRouter()const [secrets, setSecrets] = useState<SecretItem[]>([])const [loading, setLoading] = useState(true)@@ -41,7 +48,7 @@ export function SecretsPageContent({ activeScope }: { activeScope: SecretScope }void loadAll()}, [])- if (activeScope === 'subscription') {+ if (activeScope === 'llm' && llmSubTab === 'subscriptions') {return (<AuthGate><DashboardLayout>diff --git a/control-ui/app/secrets/[scope]/page.tsx b/control-ui/app/secrets/[scope]/page.tsxindex ebf5f85af..ced50ca20 100644--- a/control-ui/app/secrets/[scope]/page.tsx+++ b/control-ui/app/secrets/[scope]/page.tsx@@ -7,7 +7,7 @@ interface SecretsScopePageProps {export default async function SecretsScopePage({ params }: SecretsScopePageProps) {const { scope } = await params- if (scope !== 'llm' && scope !== 'connector' && scope !== 'recipe' && scope !== 'subscription') {+ if (scope !== 'llm' && scope !== 'connector' && scope !== 'recipe') {notFound()}diff --git a/control-ui/app/secrets/llm/subscriptions/page.tsx b/control-ui/app/secrets/llm/subscriptions/page.tsxnew file mode 100644index 000000000..124e0213d--- /dev/null+++ b/control-ui/app/secrets/llm/subscriptions/page.tsx@@ -0,0 +1,5 @@+import { SecretsPageContent } from '../../SecretsPageContent'++export default function LlmSubscriptionsPage() {+ return <SecretsPageContent activeScope="llm" llmSubTab="subscriptions" />+}diff --git a/control-ui/app/secrets/subscription/page.tsx b/control-ui/app/secrets/subscription/page.tsxnew file mode 100644index 000000000..37feb06f1--- /dev/null+++ b/control-ui/app/secrets/subscription/page.tsx@@ -0,0 +1,6 @@+import { redirect } from 'next/navigation'+import { CONTROL_ROUTES } from '@constants/routes'++export default function LegacySubscriptionSecretsPage() {+ redirect(CONTROL_ROUTES.secrets.llmSubscriptions)+}diff --git a/control-ui/components/CodexAgentAssignment/index.tsx b/control-ui/components/CodexAgentAssignment/index.tsxdeleted file mode 100644index 10a8833d3..000000000--- a/control-ui/components/CodexAgentAssignment/index.tsx+++ /dev/null@@ -1,290 +0,0 @@-'use client'--import React, { useCallback, useEffect, useState } from 'react'-import { useConfirmDialog } from '@components/ConfirmDialog'-import { useToast } from '@components/Toast'-import { CONTROL_ROUTES } from '@constants/routes'-import {- CODEX_UNASSIGNED_CONNECTION_KEY,- type CodexSubscriptionConnectionView,- createCodexSubscriptionConnection,- listCodexConnectionModels,- listCodexSubscriptionConnections,- pollCodexDevice,- startCodexDeviceConnect,- syncCodexSubscriptionCatalog,-} from '@lib/codexSubscription'-import {- type CodexSubscriptionCapability,- isCodexSubscriptionUiEnabled,- loadCodexSubscriptionCapability,-} from '@lib/codexSubscriptionFeature'-import {- mapConnectionStatus,- statusLabel,- statusTagClass,-} from '../CodexSubscriptionConnection/types'--export type CodexAgentAssignmentProps = {- connectionRef: string- hostName?: string- onConnectionRefChange: (connectionKey: string) => void- onModelsChange?: (models: string[]) => void- disabled?: boolean-}--export function CodexAgentAssignment({- connectionRef,- hostName,- onConnectionRefChange,- onModelsChange,- disabled = false,-}: CodexAgentAssignmentProps) {- const { showToast } = useToast()- const { confirm, confirmDialog } = useConfirmDialog()- const [connections, setConnections] = useState<CodexSubscriptionConnectionView[]>([])- const [selected, setSelected] = useState<CodexSubscriptionConnectionView | null>(null)- const [userCode, setUserCode] = useState<string | null>(null)- const [verificationUri, setVerificationUri] = useState<string | null>(null)- const [creating, setCreating] = useState(false)- const [displayName, setDisplayName] = useState('')- const [busy, setBusy] = useState(false)- const [capability, setCapability] = useState<CodexSubscriptionCapability | null>(null)- const enabled = isCodexSubscriptionUiEnabled(capability)-- useEffect(() => {- void loadCodexSubscriptionCapability().then(setCapability)- }, [])-- const load = useCallback(async () => {- if (!enabled) return- const rows = await listCodexSubscriptionConnections()- setConnections(rows)- const current = rows.find(row => row.connectionKey === connectionRef) ?? null- setSelected(current)- if (current?.status === 'connected') {- const models = await listCodexConnectionModels(current.connectionKey)- onModelsChange?.(models.filter(row => row.enabled && !row.stale).map(row => row.model))- } else {- onModelsChange?.([])- }- }, [connectionRef, enabled, onModelsChange])-- useEffect(() => {- void load().catch(err => {- showToast(err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions', {- tone: 'error',- })- })- }, [load, showToast])-- const assignable = connections.filter(- row => row.status !== 'revoked' || row.connectionKey === connectionRef- )-- async function handleCreate() {- setBusy(true)- try {- const created = await createCodexSubscriptionConnection({- displayName: displayName.trim() || 'Codex subscription',- })- setCreating(false)- setDisplayName('')- onConnectionRefChange(created.connectionKey)- await load()- } catch (err) {- showToast(err instanceof Error ? err.message : 'Could not create subscription', {- tone: 'error',- })- } finally {- setBusy(false)- }- }-- async function handleConnect() {- if (!selected) return- setBusy(true)- try {- const started = await startCodexDeviceConnect(- selected.status === 'connected' ? 'reconnect' : 'connect',- selected.connectionKey- )- setUserCode(started.userCode)- setVerificationUri(started.verificationUri)- const deadline = Date.now() + started.intervalSeconds * 1000 * 40- while (Date.now() < deadline) {- await new Promise(resolve => setTimeout(resolve, started.intervalSeconds * 1000))- const polled = await pollCodexDevice(started.state, selected.connectionKey)- if (polled.status === 'connected') {- setUserCode(null)- setVerificationUri(null)- await load()- return- }- if (polled.status === 'expired' || polled.status === 'denied') {- setUserCode(null)- setVerificationUri(null)- break- }- }- setUserCode(null)- setVerificationUri(null)- } catch (err) {- setUserCode(null)- setVerificationUri(null)- showToast(err instanceof Error ? err.message : 'ChatGPT sign-in failed', { tone: 'error' })- } finally {- setBusy(false)- }- }-- async function handleSync() {- if (!selected || selected.status !== 'connected') return- setBusy(true)- try {- await syncCodexSubscriptionCatalog(selected.connectionKey)- await load()- showToast(`Catalog synced: ${selected.displayName ?? selected.connectionKey}`, {- tone: 'success',- })- } catch (err) {- const code = (err as { code?: string } | null)?.code- showToast(- err instanceof Error- ? err.message- : code === 'no_grant'- ? 'Connect ChatGPT first'- : 'Catalog sync failed',- { tone: 'error' }- )- } finally {- setBusy(false)- }- }-- async function handleUnbind() {- if (!selected || !hostName) return- const confirmed = await confirm({- title: `Remove ${hostName} from this subscription?`,- message: `${hostName} will stop using "${selected.displayName ?? selected.connectionKey}" after you Save. Until then this is only a draft. The subscription stays connected and other agents are not affected.`,- confirmLabel: 'Remove agent',- })- if (!confirmed) return- onConnectionRefChange(CODEX_UNASSIGNED_CONNECTION_KEY)- }-- if (!enabled) return null-- const unassigned = connectionRef === CODEX_UNASSIGNED_CONNECTION_KEY- const uiStatus = selected- ? mapConnectionStatus(selected.status)- : unassigned- ? 'disconnected'- : 'unavailable'-- return (- <div className="cu-form-stack" data-testid="codex-agent-assignment">- {confirmDialog}- <div className="cu-field">- <label htmlFor="codex-subscription">ChatGPT subscription</label>- <select- id="codex-subscription"- value={selected?.connectionKey ?? connectionRef}- disabled={disabled || busy}- onChange={event => onConnectionRefChange(event.target.value)}- >- {unassigned || (!selected && connectionRef) ? (- <option value={connectionRef || CODEX_UNASSIGNED_CONNECTION_KEY}>- {unassigned ? 'No subscription assigned' : `${connectionRef} (unavailable)`}- </option>- ) : null}- {assignable.map(row => (- <option- key={row.connectionKey}- value={row.connectionKey}- disabled={row.status === 'revoked'}- >- {row.displayName || row.connectionKey}- {row.status === 'revoked' ? ' (revoked)' : ''}- </option>- ))}- </select>- </div>- <div className="cu-field">- <span className="cu-settings-row__label">Status</span>- <span className={statusTagClass(uiStatus)} data-testid="codex-connection-status">- {unassigned ? 'No subscription assigned' : statusLabel(uiStatus)}- </span>- </div>- {creating ? (- <div className="cu-field">- <label htmlFor="codex-new-name">New subscription name</label>- <input- id="codex-new-name"- value={displayName}- onChange={event => setDisplayName(event.target.value)}- disabled={disabled || busy}- />- <button- type="button"- className="cu-btn cu-btn--primary"- onClick={() => void handleCreate()}- disabled={busy}- >- Create- </button>- </div>- ) : (- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- onClick={() => setCreating(true)}- disabled={disabled || busy}- >- New subscription- </button>- )}- <div className="cu-form-actions">- <button- type="button"- className="cu-btn cu-btn--primary"- onClick={() => void handleConnect()}- disabled={disabled || busy || !selected}- >- Sign in with ChatGPT- </button>- <button- type="button"- className="cu-btn cu-btn--ghost"- onClick={() => void handleSync()}- disabled={disabled || busy || selected?.status !== 'connected'}- >- Sync catalog- </button>- <button- type="button"- className="cu-btn cu-btn--ghost"- onClick={() => void handleUnbind()}- disabled={- disabled ||- busy ||- !selected ||- !hostName ||- selected.status === 'revoked' ||- unassigned- }- >- Remove from this agent- </button>- <a className="cu-btn cu-btn--ghost" href={CONTROL_ROUTES.secrets.subscription}>- Manage subscription- </a>- </div>- {userCode ? (- <div className="cu-banner" data-testid="codex-device-code">- Enter {userCode} at {verificationUri ?? 'https://auth.openai.com/codex/device'}- </div>- ) : null}- </div>- )-}diff --git a/control-ui/components/CodexSubscriptionHub/index.tsx b/control-ui/components/CodexSubscriptionHub/index.tsxindex dc9134f48..3e83695ad 100644--- a/control-ui/components/CodexSubscriptionHub/index.tsx+++ b/control-ui/components/CodexSubscriptionHub/index.tsx@@ -1,88 +1,62 @@'use client'-import React, { useCallback, useEffect, useState } from 'react'-import { CONTROL_ROUTES } from '@constants/routes'+import React, { useCallback, useEffect, useMemo, useState } from 'react'import {- type CodexAssignableHost,type CodexSubscriptionConnectionView,- bindCodexHost,createCodexSubscriptionConnection,- listCodexSubscriptionFleet,+ listCodexConnectionModels,+ listCodexSubscriptionConnections,+ patchCodexCatalogModel,+ patchCodexSubscriptionConnection,pollCodexDevice,revokeCodexSubscription,startCodexDeviceConnect,syncCodexSubscriptionCatalog,- unbindCodexHost,} from '@lib/codexSubscription'import {type CodexSubscriptionCapability,isCodexSubscriptionUiEnabled,loadCodexSubscriptionCapability,} from '@lib/codexSubscriptionFeature'-import { getProviderLabel } from '@lib/llm'import {mapConnectionStatus,statusLabel,statusTagClass,} from '../CodexSubscriptionConnection/types'import { useConfirmDialog } from '../ConfirmDialog'+import { LlmProviderIcon } from '../LlmProviderIcon'+import { LlmSecretsSubTabs } from '../LlmSecretsSubTabs'import { SecretsScopeTabs } from '../SecretsScopeTabs'+import { SectionSearchInput } from '../SectionSearchInput'import { SelectionDropdown } from '../SelectionDropdown'+import { IconKey } from '../Sidebar/icons'import { TablePanelHeader } from '../TablePanelHeader'import { useToast } from '../Toast'-import { IconRefresh, IconX } from '../icons'+import { IconPencil, IconRefresh, IconX } from '../icons'function grantLabel(row: CodexSubscriptionConnectionView): string {return row.displayName || row.connectionKey}-function hostLabel(host: CodexAssignableHost): string {- return host.displayName || host.name-}--function otherGrantLabel(- connections: CodexSubscriptionConnectionView[],- connectionRef: string-): string {- return connections.find(row => row.connectionKey === connectionRef)?.displayName || connectionRef-}--function isNonCodexHost(host: CodexAssignableHost): boolean {- return Boolean(host.provider && host.provider !== 'codex-subscription')-}--function assignmentCaption(- host: CodexAssignableHost,- connections: CodexSubscriptionConnectionView[]-): string {- if (isNonCodexHost(host)) {- return [getProviderLabel(host.provider), host.model].filter(Boolean).join(' · ')- }- if (host.connectionRef === 'unassigned') return 'No subscription'- const grant = otherGrantLabel(connections, host.connectionRef)- return host.model ? `${grant} · ${host.model}` : grant-}--function assignmentBadge(host: CodexAssignableHost): string {- if (isNonCodexHost(host)) return 'other provider'- return host.connectionRef === 'unassigned' ? 'unassigned' : 'other grant'-}-export function CodexSubscriptionHub() {const { showToast } = useToast()const { confirm, confirmDialog } = useConfirmDialog()const [capability, setCapability] = useState<CodexSubscriptionCapability | null>(null)const [connections, setConnections] = useState<CodexSubscriptionConnectionView[]>([])- const [assignableHosts, setAssignableHosts] = useState<CodexAssignableHost[]>([])- const [hostsUnavailable, setHostsUnavailable] = useState(false)const [loading, setLoading] = useState(true)const [error, setError] = useState('')- const [creating, setCreating] = useState(false)- const [displayName, setDisplayName] = useState('')+ const [searchQuery, setSearchQuery] = useState('')const [busyKey, setBusyKey] = useState<string | null>(null)+ const [creating, setCreating] = useState(false)+ const [createName, setCreateName] = useState('')+ const [editing, setEditing] = useState<CodexSubscriptionConnectionView | null>(null)+ const [editName, setEditName] = useState('')+ const [editDefault, setEditDefault] = useState('')+ const [editModels, setEditModels] = useState<+ Array<{ model: string; enabled: boolean; stale: boolean }>+ >([])const [userCode, setUserCode] = useState<string | null>(null)const [verificationUri, setVerificationUri] = useState<string | null>(null)- const [pickedByGrant, setPickedByGrant] = useState<Record<string, string[]>>({})const enabled = isCodexSubscriptionUiEnabled(capability)useEffect(() => {@@ -91,10 +65,8 @@ export function CodexSubscriptionHub() {const load = useCallback(async () => {if (!enabled) return- const fleet = await listCodexSubscriptionFleet()- setConnections(fleet.connections)- setAssignableHosts(fleet.assignableHosts)- setHostsUnavailable(fleet.assignableHostsUnavailable)+ const rows = await listCodexSubscriptionConnections()+ setConnections(rows)}, [enabled])useEffect(() => {@@ -107,24 +79,83 @@ export function CodexSubscriptionHub() {setError('')void load().catch(err => {- setError(err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions')+ setError(err instanceof Error ? err.message : 'Failed to load ChatGPT subscriptions')}).finally(() => setLoading(false))}, [capability, enabled, load])+ const filtered = useMemo(() => {+ const q = searchQuery.trim().toLowerCase()+ const rows = connections.filter(row => row.status !== 'revoked')+ if (!q) return rows+ return rows.filter(row =>+ [grantLabel(row), row.connectionKey, row.status].join(' ').toLowerCase().includes(q)+ )+ }, [connections, searchQuery])+async function handleCreate() {+ const displayName = createName.trim()+ if (!displayName) {+ setError('Subscription name is required.')+ return+ }setBusyKey('create')try {- await createCodexSubscriptionConnection({- displayName: displayName.trim() || 'Codex subscription',- })- setDisplayName('')+ await createCodexSubscriptionConnection({ displayName })+ setCreateName('')setCreating(false)+ setError('')await load()+ showToast(`Subscription ${displayName} created.`, { tone: 'success' })} catch (err) {- showToast(err instanceof Error ? err.message : 'Could not create subscription', {- tone: 'error',+ setError(err instanceof Error ? err.message : 'Could not create subscription')+ } finally {+ setBusyKey(null)+ }+ }++ async function openEdit(row: CodexSubscriptionConnectionView) {+ setEditing(row)+ setEditName(grantLabel(row))+ setEditDefault(row.defaultModel ?? '')+ setUserCode(null)+ setVerificationUri(null)+ setError('')+ if (row.status === 'connected') {+ try {+ const models = await listCodexConnectionModels(row.connectionKey)+ setEditModels(models)+ } catch {+ setEditModels([])+ }+ } else {+ setEditModels([])+ }+ }++ function closeEdit() {+ setEditing(null)+ setEditName('')+ setEditDefault('')+ setEditModels([])+ setUserCode(null)+ setVerificationUri(null)+ }++ async function handleSaveEdit() {+ if (!editing) return+ setBusyKey(editing.connectionKey)+ try {+ const updated = await patchCodexSubscriptionConnection(editing.connectionKey, {+ displayName: editName.trim() || grantLabel(editing),+ defaultModel: editDefault.trim() || null,})+ setEditing(updated)+ await load()+ showToast(`Subscription ${grantLabel(updated)} updated.`, { tone: 'success' })+ closeEdit()+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Could not update subscription')} finally {setBusyKey(null)}@@ -146,6 +177,10 @@ export function CodexSubscriptionHub() {if (polled.status === 'connected') {setUserCode(null)setVerificationUri(null)+ const latest = polled.connection+ setEditing(latest)+ const models = await listCodexConnectionModels(latest.connectionKey)+ setEditModels(models)await load()return}@@ -160,401 +195,440 @@ export function CodexSubscriptionHub() {} catch (err) {setUserCode(null)setVerificationUri(null)- showToast(err instanceof Error ? err.message : 'ChatGPT sign-in failed', { tone: 'error' })+ setError(err instanceof Error ? err.message : 'ChatGPT sign-in failed')} finally {setBusyKey(null)}}async function handleSync(row: CodexSubscriptionConnectionView) {+ if (row.status !== 'connected') returnsetBusyKey(row.connectionKey)try {await syncCodexSubscriptionCatalog(row.connectionKey)+ const models = await listCodexConnectionModels(row.connectionKey)+ setEditModels(models)await load()showToast(`Catalog synced: ${grantLabel(row)}`, { tone: 'success' })} catch (err) {- showToast(err instanceof Error ? err.message : 'Catalog sync failed', { tone: 'error' })+ setError(err instanceof Error ? err.message : 'Catalog sync failed')} finally {setBusyKey(null)}}- async function handleRevoke(row: CodexSubscriptionConnectionView) {- const assigned = assignableHosts.filter(host => host.connectionRef === row.connectionKey)- const names = assigned.map(host => host.name)- const confirmed = await confirm({- title: 'Revoke this ChatGPT subscription?',- message: hostsUnavailable- ? 'The agent assignment list could not be loaded. Revoke still fail-closes every Host that points at this grant.'- : names.length > 0- ? `This signs out the subscription itself. All ${names.length} agent(s) using it (${names.join(', ')}) will lose ChatGPT access immediately. Agents keep their assignment and stop authorizing; they are not reassigned automatically. To detach a single agent instead, remove it from the Agents column.${- row.connectionKey === 'deployment-default'- ? ' Workflow recipes that use a ChatGPT subscription also fail closed on this grant.'- : ''- }`- : 'Revoke disconnects this ChatGPT grant. Assigned agents keep the reference and stop authorizing. To detach a single agent instead, remove it from the Agents column.',- confirmLabel: 'Revoke subscription',- })- if (!confirmed) return+ async function handleToggleModel(+ row: CodexSubscriptionConnectionView,+ model: string,+ enabledNext: boolean+ ) {setBusyKey(row.connectionKey)try {- await revokeCodexSubscription(row.connectionKey)- await load()+ const models = await patchCodexCatalogModel(row.connectionKey, model, enabledNext)+ setEditModels(models)+ if (editDefault === model && !enabledNext) setEditDefault('')} catch (err) {- showToast(err instanceof Error ? err.message : 'Revoke failed', { tone: 'error' })+ setError(err instanceof Error ? err.message : 'Could not update model')} finally {setBusyKey(null)}}- async function handleUnbind(row: CodexSubscriptionConnectionView, hostName: string) {+ async function handleRevoke(row: CodexSubscriptionConnectionView) {const confirmed = await confirm({- title: `Remove ${hostName} from this subscription?`,- message: `${hostName} will stop using "${grantLabel(row)}" and will have no ChatGPT subscription assigned until you pick another one. The subscription stays connected and other agents are not affected.`,- confirmLabel: 'Remove agent',+ title: 'Delete ChatGPT subscription',+ message: `Revoke ${grantLabel(row)}? Assigned agents keep the reference and stop authorizing.`,+ confirmLabel: 'Delete',+ tone: 'danger',})if (!confirmed) returnsetBusyKey(row.connectionKey)try {- await unbindCodexHost(row.connectionKey, hostName)+ await revokeCodexSubscription(row.connectionKey)+ if (editing?.connectionKey === row.connectionKey) closeEdit()await load()+ showToast(`Subscription ${grantLabel(row)} revoked.`, { tone: 'success' })} catch (err) {- showToast(err instanceof Error ? err.message : 'Could not remove agent', { tone: 'error' })+ setError(err instanceof Error ? err.message : 'Could not revoke subscription')} finally {setBusyKey(null)}}- async function handleAssignMany(- row: CodexSubscriptionConnectionView,- hosts: CodexAssignableHost[]- ) {- if (hosts.length === 0) return- const converting = hosts.filter(isNonCodexHost)- const switching = hosts.filter(- host =>- !isNonCodexHost(host) &&- host.connectionRef !== 'unassigned' &&- host.connectionRef !== row.connectionKey+ const offeredDefaults = editModels.filter(row => row.enabled && !row.stale).map(row => row.model)+ const initialLoad = loading && connections.length === 0+ const uiStatus = editing ? mapConnectionStatus(editing.status) : 'disconnected'++ if (!enabled && capability !== null) {+ return (+ <div className="cu-card cu-card--viewport-fill">+ <TablePanelHeader+ title={+ <>+ <IconKey /> Secrets+ </>+ }+ subtitle="Manage LLM, connector, and recipe credentials in one place."+ />+ <div className="cu-card__body cu-card__body--auto cu-secrets-strip">+ <SecretsScopeTabs activeValue="llm" />+ <LlmSecretsSubTabs activeValue="subscriptions" />+ </div>+ <div className="cu-empty">ChatGPT subscriptions are disabled.</div>+ </div>)- if (converting.length > 0 || switching.length > 0) {- const convertingNames = converting.map(host => hostLabel(host)).join(', ')- const switchingNames = switching.map(host => hostLabel(host)).join(', ')- const confirmed = await confirm({- title:- hosts.length === 1 && converting.length === 1- ? `Switch ${hosts[0].name} to ChatGPT?`- : hosts.length === 1- ? `Switch ${hosts[0].name} to this subscription?`- : `Add ${hosts.length} agents to this subscription?`,- message: [- converting.length > 0- ? `${convertingNames} will switch to ChatGPT on "${grantLabel(row)}". This sets the provider, subscription, and a default model from this grant.`- : '',- switching.length > 0- ? `${switchingNames} currently use another grant. Assign ${- switching.length === 1 ? 'it' : 'them'- } to "${grantLabel(row)}"?`- : '',- ]- .filter(Boolean)- .join(' '),- confirmLabel: hosts.length === 1 ? 'Assign agent' : `Add ${hosts.length} agents`,- })- if (!confirmed) return- }- setBusyKey(row.connectionKey)- const assigned: string[] = []- const failed: string[] = []- let lastModel = ''- try {- for (const host of hosts) {- try {- const written = await bindCodexHost(row.connectionKey, host.name)- assigned.push(hostLabel(host))- if (written.model) lastModel = written.model- } catch (err) {- failed.push(hostLabel(host))- showToast(err instanceof Error ? err.message : `Could not assign ${hostLabel(host)}`, {- tone: 'error',- })- }- }- setPickedByGrant(prev => ({ ...prev, [row.connectionKey]: [] }))- await load()- const modelSuffix = lastModel && assigned.length === 1 ? ` · ${lastModel}` : ''- if (assigned.length > 0 && failed.length === 0) {- showToast(- assigned.length === 1- ? `Assigned ${assigned[0]} to ${grantLabel(row)}${modelSuffix}`- : `Assigned ${assigned.length} agents to ${grantLabel(row)}`,- { tone: 'success' }- )- } else if (assigned.length > 0) {- showToast(`Assigned ${assigned.length} of ${hosts.length} agents to ${grantLabel(row)}`, {- tone: 'success',- })- }- } finally {- setBusyKey(null)- }}return (- <div className="cu-card cu-card--viewport-fill" data-testid="codex-subscription-hub">- {confirmDialog}- <TablePanelHeader- title="Subscriptions"- subtitle="Assign agents here to connect a grant and set a default ChatGPT model. Models & creds edits one agent at a time."- actions={- <button- type="button"- className="cu-btn cu-btn--primary cu-btn--sm"- onClick={() => setCreating(true)}- disabled={!enabled || busyKey !== null}- >- Add subscription- </button>- }- />- <div className="cu-card__body cu-card__body--auto cu-secrets-strip">- <SecretsScopeTabs activeValue="subscription" />- </div>- {error ? <div className="cu-banner cu-banner--error">{error}</div> : null}- {hostsUnavailable ? (- <div className="cu-banner cu-banner--warning">- Agent assignments could not be loaded. Revoke still works. Add and Remove are disabled- until hosts are available.- </div>- ) : null}- {userCode ? (- <div className="cu-banner" data-testid="codex-device-code">- Enter {userCode} at {verificationUri ?? 'https://auth.openai.com/codex/device'}+ <>+ <div className="cu-card cu-card--viewport-fill" style={{ marginBottom: '1.25rem' }}>+ <TablePanelHeader+ title={+ <>+ <IconKey />+ {initialLoad ? 'Secrets' : `Secrets (${filtered.length})`}+ </>+ }+ subtitle="Manage LLM, connector, and recipe credentials in one place."+ actions={+ <>+ <SectionSearchInput+ value={searchQuery}+ onChange={setSearchQuery}+ placeholder="Search secrets"+ ariaLabel="Search ChatGPT subscriptions"+ disabled={initialLoad}+ />+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--toolbar"+ onClick={() => void load()}+ disabled={initialLoad || loading}+ aria-label={loading ? 'Refreshing...' : 'Reload ChatGPT subscriptions'}+ >+ <IconRefresh className={loading ? 'cu-spin' : undefined} width={18} height={18} />+ </button>+ <button+ type="button"+ className="cu-btn cu-btn--primary cu-btn--sm"+ onClick={() => {+ setCreating(true)+ setCreateName('')+ setError('')+ }}+ disabled={initialLoad}+ >+ Add subscription+ </button>+ </>+ }+ />++ <div className="cu-card__body cu-card__body--auto cu-secrets-strip">+ <SecretsScopeTabs activeValue="llm" />+ <LlmSecretsSubTabs activeValue="subscriptions" /></div>- ) : null}- {creating ? (- <div className="cu-codex-hub__create">- <label htmlFor="codex-hub-new-name">New subscription name</label>- <div className="cu-codex-hub__create-row">- <input- id="codex-hub-new-name"- value={displayName}- onChange={event => setDisplayName(event.target.value)}- disabled={busyKey !== null}- />- <button- type="button"- className="cu-btn cu-btn--primary cu-btn--sm"- onClick={() => void handleCreate()}- disabled={busyKey !== null}- >- Create- </button>++ {error ? (+ <div className="cu-card__body cu-card__body--auto cu-secrets-message-strip">+ <div className="cu-banner cu-banner--error">{error}</div></div>- </div>- ) : null}- {!enabled ? (- <div className="cu-empty">ChatGPT subscriptions are not enabled on this cluster.</div>- ) : loading ? (- <div className="cu-table-wrap">- <table className="cu-table cu-table--header-band">- <thead>- <tr>- <th>Name</th>- <th>Status</th>- <th>Agents</th>- <th style={{ width: '12rem', textAlign: 'right' }} aria-label="Actions" />- </tr>- </thead>- <tbody>- {Array.from({ length: 3 }).map((_, idx) => (- <tr key={idx}>- <td>- <div- className="cu-skeleton cu-skeleton--cell"- style={{ width: `${50 + ((idx * 11) % 24)}%` }}- />- </td>- <td>- <div className="cu-skeleton cu-skeleton--cell" style={{ width: '5rem' }} />- </td>- <td>- <div className="cu-skeleton cu-skeleton--cell" style={{ width: '70%' }} />- </td>- <td>- <div- className="cu-skeleton cu-skeleton--cell"- style={{ width: '5rem', marginLeft: 'auto' }}- />- </td>+ ) : null}++ {initialLoad ? (+ <div className="cu-table-wrap">+ <table className="cu-table cu-table--header-band">+ <thead>+ <tr>+ <th>Name</th>+ <th>Status</th>+ <th style={{ width: '8rem', textAlign: 'right' }} aria-label="Actions" /></tr>- ))}- </tbody>- </table>- </div>- ) : connections.length === 0 ? (- <div className="cu-empty">- No ChatGPT subscriptions yet. Add a subscription to let agents use ChatGPT models.- </div>- ) : (- <div className="cu-table-wrap">- <table className="cu-table cu-table--header-band" data-testid="codex-hub-table">- <caption className="sr-only">ChatGPT subscriptions and assigned agents</caption>- <thead>- <tr>- <th scope="col">Name</th>- <th scope="col" style={{ width: '8rem' }}>- Status- </th>- <th scope="col">Agents</th>- <th- scope="col"- style={{ width: '14rem', textAlign: 'right' }}- aria-label="Actions"- />- </tr>- </thead>- <tbody>- {connections.map(row => {- const uiStatus = mapConnectionStatus(row.status)- const assigned = assignableHosts.filter(- host => host.connectionRef === row.connectionKey- )- const available = assignableHosts.filter(- host => host.connectionRef !== row.connectionKey- )- const picked = pickedByGrant[row.connectionKey] ?? []- const pickedHosts = available.filter(host => picked.includes(host.name))- const busy = busyKey === row.connectionKey- return (- <tr key={row.connectionKey} data-testid={`codex-hub-grant-${row.connectionKey}`}>- <td>{grantLabel(row)}</td>+ </thead>+ <tbody>+ {Array.from({ length: 3 }).map((_, idx) => (+ <tr key={idx}><td>- <span className={statusTagClass(uiStatus)}>{statusLabel(uiStatus)}</span>+ <div className="cu-skeleton cu-skeleton--cell" style={{ width: '55%' }} /></td><td>- <div className="cu-codex-hub__agents-cell">- {assigned.length === 0 ? (- <span className="cu-table__cell-muted">No agents assigned</span>- ) : (- <div- className="cu-chip-row"- data-testid="codex-hub-agent-chips"- aria-label={`Agents on ${grantLabel(row)}`}- >- {assigned.map(host => (- <span key={host.name} className="cu-chip cu-codex-hub__agent-chip">- <a href={CONTROL_ROUTES.agents.tab(host.name, 'model')}>- {hostLabel(host)}- </a>- {host.model ? (- <span className="cu-codex-hub__agent-model">{host.model}</span>- ) : null}- <button- type="button"- className="cu-codex-hub__chip-remove"- onClick={() => void handleUnbind(row, host.name)}- disabled={busy || hostsUnavailable}- aria-label={`Remove agent ${hostLabel(host)}`}- >- <IconX width={12} height={12} />- </button>- </span>- ))}- </div>- )}- <div className="cu-codex-hub__add" data-testid="codex-hub-add-agents">- {available.length === 0 ? (- <span className="cu-table__cell-muted">- All agents already use this grant.- </span>- ) : (- <>- <label- className="sr-only"- htmlFor={`codex-hub-add-${row.connectionKey}`}- >- Add agents to this subscription- </label>- <SelectionDropdown- id={`codex-hub-add-${row.connectionKey}`}- className="cu-codex-hub__picker"- multiple- value={picked}- options={available.map(host => ({- value: host.name,- label: hostLabel(host),- description: assignmentCaption(host, connections),- badge: assignmentBadge(host),- }))}- placeholder="Add agents…"- searchPlaceholder="Search agents…"- selectionLabel="agents"- emptyLabel="No agents available."- disabled={busy || hostsUnavailable || row.status === 'revoked'}- onChange={next =>- setPickedByGrant(prev => ({- ...prev,- [row.connectionKey]: next,- }))- }- />- <button- type="button"- className="cu-btn cu-btn--primary cu-btn--sm"- onClick={() => void handleAssignMany(row, pickedHosts)}- disabled={- busy ||- hostsUnavailable ||- row.status === 'revoked' ||- pickedHosts.length === 0- }- >- {pickedHosts.length > 1- ? `Add ${pickedHosts.length} agents`- : 'Add agents'}- </button>- </>- )}- </div>- </div>+ <div className="cu-skeleton cu-skeleton--cell" style={{ width: '40%' }} /></td>- <td style={{ textAlign: 'right' }}>- <div className="cu-codex-hub__row-actions">- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- onClick={() => void handleConnect(row)}- disabled={busy || row.status === 'revoked'}- >- Sign in- </button>- <button- type="button"- className="cu-btn cu-btn--icon cu-btn--toolbar"- onClick={() => void handleSync(row)}- disabled={busy || row.status !== 'connected'}- aria-label={`Sync catalog ${grantLabel(row)}`}- >- <IconRefresh width={16} height={16} />- </button>- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- onClick={() => void handleRevoke(row)}- disabled={busy || row.status === 'revoked'}- >- Revoke subscription- </button>- </div>+ <td>+ <div className="cu-skeleton cu-skeleton--cell" style={{ width: '4rem' }} /></td></tr>- )- })}- </tbody>- </table>+ ))}+ </tbody>+ </table>+ </div>+ ) : filtered.length === 0 ? (+ <div className="cu-empty">+ {searchQuery.trim()+ ? 'No ChatGPT subscriptions match this search.'+ : 'No ChatGPT subscriptions found.'}+ </div>+ ) : (+ <div className="cu-table-wrap">+ <table className="cu-table cu-table--header-band">+ <thead>+ <tr>+ <th>Name</th>+ <th>Status</th>+ <th style={{ width: '8rem', textAlign: 'right' }} aria-label="Actions" />+ </tr>+ </thead>+ <tbody>+ {filtered.map(row => {+ const mapped = mapConnectionStatus(row.status)+ return (+ <tr key={row.connectionKey}>+ <td>{grantLabel(row)}</td>+ <td>+ <span className={statusTagClass(mapped)}>{statusLabel(mapped)}</span>+ </td>+ <td style={{ textAlign: 'right' }}>+ <div style={{ display: 'inline-flex', gap: '0.35rem' }}>+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--toolbar"+ onClick={() => void openEdit(row)}+ aria-label={`Update ChatGPT subscription ${grantLabel(row)}`}+ >+ <IconPencil width={16} height={16} />+ </button>+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--danger-icon"+ onClick={() => void handleRevoke(row)}+ disabled={busyKey === row.connectionKey}+ aria-label={+ busyKey === row.connectionKey+ ? 'Deleting…'+ : `Delete ChatGPT subscription ${grantLabel(row)}`+ }+ >+ <IconX width={16} height={16} />+ </button>+ </div>+ </td>+ </tr>+ )+ })}+ </tbody>+ </table>+ </div>+ )}+ </div>++ {creating ? (+ <div+ style={{+ position: 'fixed',+ inset: 0,+ background: 'var(--cu-overlay)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000,+ padding: '1rem',+ }}+ role="presentation"+ onClick={e => {+ if (e.target === e.currentTarget && busyKey !== 'create') {+ setCreating(false)+ }+ }}+ >+ <div+ className="cu-modal-panel"+ role="dialog"+ aria-labelledby="codex-create-title"+ onClick={e => e.stopPropagation()}+ >+ <div className="cu-modal-panel__head">+ <strong id="codex-create-title" style={{ fontSize: '1rem', lineHeight: 1.35 }}>+ Add subscription+ </strong>+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--ghost"+ onClick={() => setCreating(false)}+ disabled={busyKey === 'create'}+ aria-label="Close"+ >+ <IconX width={18} height={18} />+ </button>+ </div>+ <div className="cu-form-stack">+ <div className="cu-field">+ <label htmlFor="codex-new-name">Name</label>+ <input+ id="codex-new-name"+ value={createName}+ onChange={e => setCreateName(e.target.value)}+ disabled={busyKey === 'create'}+ />+ </div>+ </div>+ <div className="cu-modal-panel__foot">+ <button+ type="button"+ className="cu-btn cu-btn--ghost cu-btn--sm"+ onClick={() => setCreating(false)}+ disabled={busyKey === 'create'}+ >+ Cancel+ </button>+ <button+ type="button"+ className="cu-btn cu-btn--primary"+ onClick={() => void handleCreate()}+ disabled={busyKey === 'create'}+ >+ {busyKey === 'create' ? 'Saving…' : 'Create'}+ </button>+ </div>+ </div>+ </div>+ ) : null}++ {editing ? (+ <div+ style={{+ position: 'fixed',+ inset: 0,+ background: 'var(--cu-overlay)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000,+ padding: '1rem',+ }}+ role="presentation"+ onClick={e => {+ if (e.target === e.currentTarget && !busyKey) closeEdit()+ }}+ >+ <div+ className="cu-modal-panel"+ role="dialog"+ aria-labelledby="codex-edit-title"+ onClick={e => e.stopPropagation()}+ >+ <div className="cu-modal-panel__head">+ <strong id="codex-edit-title" style={{ fontSize: '1rem', lineHeight: 1.35 }}>+ Update ChatGPT subscription {grantLabel(editing)}+ </strong>+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--ghost"+ onClick={closeEdit}+ disabled={Boolean(busyKey)}+ aria-label="Close"+ >+ <IconX width={18} height={18} />+ </button>+ </div>+ <div className="cu-form-stack" style={{ maxWidth: '100%' }}>+ <div className="cu-field">+ <label htmlFor="codex-edit-name">Name</label>+ <input+ id="codex-edit-name"+ value={editName}+ onChange={e => setEditName(e.target.value)}+ disabled={Boolean(busyKey)}+ />+ </div>+ <div className="cu-field">+ <span className="cu-field__label">Status</span>+ <span className={statusTagClass(uiStatus)}>{statusLabel(uiStatus)}</span>+ </div>+ <div>+ <button+ type="button"+ className="cu-btn cu-btn--ghost cu-btn--sm"+ onClick={() => void handleConnect(editing)}+ disabled={Boolean(busyKey)}+ >+ Sign in with ChatGPT+ </button>{' '}+ <button+ type="button"+ className="cu-btn cu-btn--ghost cu-btn--sm"+ onClick={() => void handleSync(editing)}+ disabled={Boolean(busyKey) || editing.status !== 'connected'}+ >+ Sync catalog+ </button>+ </div>+ {userCode ? (+ <p data-testid="codex-device-code">+ Enter {userCode}+ {verificationUri ? ` at ${verificationUri}` : ''}+ </p>+ ) : null}+ {editModels.length > 0 ? (+ <fieldset className="cu-field">+ <legend className="cu-field__label">Enabled models</legend>+ {editModels.map(model => (+ <label key={model.model} className="cu-field" style={{ display: 'block' }}>+ <input+ type="checkbox"+ checked={model.enabled}+ disabled={Boolean(busyKey) || model.stale}+ onChange={e =>+ void handleToggleModel(editing, model.model, e.target.checked)+ }+ />{' '}+ {model.model}+ {model.stale ? ' (stale)' : ''}+ </label>+ ))}+ </fieldset>+ ) : null}+ <div className="cu-field">+ <label htmlFor="codex-edit-default">Default model</label>+ <SelectionDropdown+ id="codex-edit-default"+ value={editDefault ? [editDefault] : []}+ options={offeredDefaults.map(model => ({+ value: model,+ label: model,+ icon: <LlmProviderIcon provider="codex-subscription" label={model} />,+ }))}+ placeholder={offeredDefaults.length === 0 ? 'No enabled models' : 'Select model…'}+ searchPlaceholder="Search models…"+ selectionLabel="model"+ multiple={false}+ showSelectedChips={false}+ disabled={Boolean(busyKey) || offeredDefaults.length === 0}+ onChange={next => setEditDefault(next[0] ?? '')}+ />+ </div>+ </div>+ <div className="cu-modal-panel__foot">+ <button+ type="button"+ className="cu-btn cu-btn--ghost cu-btn--sm"+ onClick={closeEdit}+ disabled={Boolean(busyKey)}+ >+ Cancel+ </button>+ <button+ type="button"+ className="cu-btn cu-btn--primary"+ onClick={() => void handleSaveEdit()}+ disabled={Boolean(busyKey)}+ >+ {busyKey ? 'Saving…' : 'Update subscription'}+ </button>+ </div>+ </div></div>- )}- </div>+ ) : null}+ {confirmDialog}+ </>)}diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsxindex bd3fae442..0a786247d 100644--- a/control-ui/components/HostWizard/index.tsx+++ b/control-ui/components/HostWizard/index.tsx@@ -1,7 +1,6 @@'use client'import React, { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react'-import { CodexAgentAssignment } from '@/components/CodexAgentAssignment'import { CreateFlowPanel } from '@/components/CreateFlowPanel'import { CreateStepFlow } from '@/components/CreateStepFlow'import { LlmProviderConfig } from '@/components/LlmProviderConfig'@@ -19,7 +18,12 @@ import {updateAgentUsers,} from '@/lib/api'import { cn } from '@/lib/cn'-import { CODEX_UNASSIGNED_CONNECTION_KEY } from '@/lib/codexSubscription'+import {+ CODEX_UNASSIGNED_CONNECTION_KEY,+ type CodexSubscriptionConnectionView,+ listCodexConnectionModels,+ listCodexSubscriptionConnections,+} from '@/lib/codexSubscription'import { useLlmAllowedModels } from '@/lib/hooks/useLlmAllowedModels'import { getAgentNameError } from '@/lib/k8sValidation'import {@@ -40,6 +44,7 @@ import {resolveDefaultModel,validateLlmSecretData,} from '@/lib/llm'+import { credentialSelectValue, parseCredentialSelect } from '@/lib/llmCredentialSelect'import { toKebabCase, toKebabInput } from '@/lib/string'import {HOST_NAMESPACE,@@ -121,39 +126,43 @@ function WizardSelect({{options.length === 0 ? (<span className="cu-agent-select__empty">No options available.</span>) : (- options.map(option => (- <button- key={option.value}- type="button"- className="cu-agent-select__option"- data-active={value === option.value ? 'true' : 'false'}- role="option"- aria-selected={value === option.value}- onClick={() => {- onChange(option.value)- setOpen(false)- }}- >- <span className="cu-agent-select__option-copy">- <span className="cu-agent-select__option-name">{option.label}</span>- {option.providers && option.providers.length > 0 ? (- <span className="cu-agent-select__providers">- <span className="cu-agent-select__providers-label">Providers: </span>- {option.providers.map((provider, index) => (- <Fragment key={provider.id}>- {index > 0 ? ', ' : null}- <span className="cu-agent-select__provider">- <LlmProviderIcon provider={provider.id} label={provider.label} />- <span>{provider.label}</span>- </span>- </Fragment>- ))}- </span>- ) : option.meta ? (- <span className="cu-agent-select__option-meta">{option.meta}</span>- ) : null}- </span>- </button>+ options.map((option, index) => (+ <Fragment key={option.value}>+ {option.group && option.group !== options[index - 1]?.group ? (+ <span className="cu-agent-select__empty">{option.group}</span>+ ) : null}+ <button+ type="button"+ className="cu-agent-select__option"+ data-active={value === option.value ? 'true' : 'false'}+ role="option"+ aria-selected={value === option.value}+ onClick={() => {+ onChange(option.value)+ setOpen(false)+ }}+ >+ <span className="cu-agent-select__option-copy">+ <span className="cu-agent-select__option-name">{option.label}</span>+ {option.providers && option.providers.length > 0 ? (+ <span className="cu-agent-select__providers">+ <span className="cu-agent-select__providers-label">Providers: </span>+ {option.providers.map((provider, index) => (+ <Fragment key={provider.id}>+ {index > 0 ? ', ' : null}+ <span className="cu-agent-select__provider">+ <LlmProviderIcon provider={provider.id} label={provider.label} />+ <span>{provider.label}</span>+ </span>+ </Fragment>+ ))}+ </span>+ ) : option.meta ? (+ <span className="cu-agent-select__option-meta">{option.meta}</span>+ ) : null}+ </span>+ </button>+ </Fragment>)))}</div>@@ -245,6 +254,7 @@ function isStepValid(selectedMcp: string[]secretMode: HostLlmSecretModeexistingSecret: string+ existingLlmSecret: stringnewSecretName: stringllmKeyDraft: Record<string, string>llmPolicy: LlmPolicy | undefined@@ -287,7 +297,9 @@ function isStepValid(getActiveCredentialKeys(state.provider, state.llmPolicy))return state.secretMode === 'existing'- ? state.existingSecret.trim().length > 0+ ? state.provider === 'codex-subscription'+ ? state.existingLlmSecret.trim().length > 0+ : parseCredentialSelect(state.existingSecret).kind === 'secret': toKebabCase(state.newSecretName).length > 0 &&primaryCredentialUsable(state.provider, state.llmKeyDraft) &&validateLlmSecretData(projectedDraft).length === 0@@ -333,6 +345,7 @@ export function HostWizard({// remains available when the operator explicitly chooses New credential.const [secretMode, setSecretMode] = useState<HostLlmSecretMode>('existing')const [existingSecret, setExistingSecret] = useState('')+ const [existingLlmSecret, setExistingLlmSecret] = useState('')const [newSecretName, setNewSecretName] = useState('')const [secretNameTouched, setSecretNameTouched] = useState(false)const [llmKeyDraft, setLlmKeyDraft] = useState<Record<string, string>>(createEmptyLlmKeyDraft)@@ -353,6 +366,7 @@ export function HostWizard({const [modelName, setModelName] = useState('')const [connectionRef, setConnectionRef] = useState(CODEX_UNASSIGNED_CONNECTION_KEY)const [codexModels, setCodexModels] = useState<string[]>([])+ const [codexConnections, setCodexConnections] = useState<CodexSubscriptionConnectionView[]>([])const [stateless, setStateless] = useState(false)const [users, setUsers] = useState<Array<{ id: string; email: string; name: string | null; displayName: string | null }>@@ -372,8 +386,8 @@ export function HostWizard({)const secretOptions = useMemo(- () =>- existingSecrets+ () => [+ ...existingSecrets.map(secret => {const name = secret.name || secret.metadata?.nameif (!name) return null@@ -387,6 +401,7 @@ export function HostWizard({? `Providers: ${providers.map(getProviderLabel).join(', ')}`: 'No recognized provider credentials'return {+ group: 'API keys',value: name,label: name,meta: providerSummary,@@ -398,7 +413,20 @@ export function HostWizard({}).filter(option => option !== null).sort((left, right) => left.value.localeCompare(right.value)),- [existingSecrets]+ ...codexConnections+ .filter(row => row.status !== 'revoked')+ .map(row => ({+ group: 'Subscriptions',+ value: credentialSelectValue('', row.connectionKey),+ label: row.displayName || row.connectionKey,+ meta: 'ChatGPT subscription',+ })),+ ],+ [codexConnections, existingSecrets]+ )+ const apiKeyOptions = useMemo(+ () => secretOptions.filter(option => option.group === 'API keys'),+ [secretOptions])const selectedContextOption = useMemo(() =>@@ -407,8 +435,9 @@ export function HostWizard({[existingContexts, selectedExistingContext])const catalogForEditor = useMemo(() => {- if (provider !== 'codex-subscription' || codexModels.length === 0) return allowedCatalog+ if (provider !== 'codex-subscription') return allowedCatalogconst others = allowedCatalog.filter(row => row.provider !== 'codex-subscription')+ if (codexModels.length === 0) return othersreturn [...others,...codexModels.map(model => ({@@ -432,19 +461,57 @@ export function HostWizard({const handleExistingSecretChange = useCallback((secretName: string) => {setExistingSecret(secretName)+ const parsed = parseCredentialSelect(secretName)+ if (parsed.kind === 'subscription') {+ const grant = codexConnections.find(row => row.connectionKey === parsed.connectionKey)+ setConnectionRef(parsed.connectionKey)+ setProvider('codex-subscription')+ void listCodexConnectionModels(parsed.connectionKey)+ .then(models => {+ const offered = models.filter(row => row.enabled && !row.stale).map(row => row.model)+ setCodexModels(offered)+ setModelName(resolveCodexGrantModel(grant?.defaultModel ?? '', offered))+ })+ .catch(() => {+ setCodexModels([])+ })+ return+ }+ setConnectionRef(CODEX_UNASSIGNED_CONNECTION_KEY)+ setCodexModels([])const selectedSecret = existingSecrets.find(secret => (secret.name || secret.metadata?.name) === secretName)if (!Array.isArray(selectedSecret?.keys)) returnconst [linkedProvider] = getProvidersWithCompleteCredentials(selectedSecret.keys)if (!linkedProvider) return- setProvider(linkedProvider)+ setProvider(linkedProvider === 'codex-subscription' ? 'openai' : linkedProvider)setModelName(- resolveDefaultModel(linkedProvider, getModelOptions(allowedCatalog, linkedProvider))+ resolveDefaultModel(+ linkedProvider === 'codex-subscription' ? 'openai' : linkedProvider,+ getModelOptions(+ allowedCatalog,+ linkedProvider === 'codex-subscription' ? 'openai' : linkedProvider+ )+ ))},- [allowedCatalog, existingSecrets]+ [allowedCatalog, codexConnections, existingSecrets])++ useEffect(() => {+ let cancelled = false+ void listCodexSubscriptionConnections()+ .then(rows => {+ if (!cancelled) setCodexConnections(rows)+ })+ .catch(() => {+ if (!cancelled) setCodexConnections([])+ })+ return () => {+ cancelled = true+ }+ }, [])// Keep the selected model valid for the current provider's enabled models:// seed the default once the allowlist loads, and re-default if a provider// switch left the model out of range.@@ -512,6 +579,7 @@ export function HostWizard({selectedMcp,secretMode,existingSecret,+ existingLlmSecret,newSecretName,llmKeyDraft,llmPolicy,@@ -531,6 +599,7 @@ export function HostWizard({selectedMcp,secretMode,existingSecret,+ existingLlmSecret,newSecretName,llmKeyDraft,llmPolicy,@@ -605,11 +674,13 @@ export function HostWizard({selectedMcp,secretMode,existingSecret,+ existingLlmSecret,newSecretName,llmKeyDraft,llmPolicy,provider,modelName,+ connectionRef,selectedUserIds,selectedTeamIds,directoryLoadFailed: directoryLoadError.length > 0,@@ -629,11 +700,13 @@ export function HostWizard({selectedMcp,secretMode,existingSecret,+ existingLlmSecret,newSecretName,llmKeyDraft,llmPolicy,provider,modelName,+ connectionRef,selectedUserIds,selectedTeamIds,directoryLoadError,@@ -658,7 +731,20 @@ export function HostWizard({return 'Choose a ChatGPT subscription before continuing.'}if (step === 2 && llmChainRequiresSecret(provider, llmPolicy?.fallbacks)) {- if (secretMode === 'existing' && !existingSecret.trim()) return 'Select an existing secret.'+ if (+ secretMode === 'existing' &&+ provider === 'codex-subscription' &&+ !existingLlmSecret.trim()+ ) {+ return 'Select an existing secret.'+ }+ if (+ secretMode === 'existing' &&+ provider !== 'codex-subscription' &&+ !existingSecret.trim()+ ) {+ return 'Select an existing secret.'+ }if (secretMode === 'new' && !toKebabCase(newSecretName)) {return 'For a new secret, set a name.'}@@ -684,6 +770,7 @@ export function HostWizard({selectedMcp,secretMode,existingSecret,+ existingLlmSecret,newSecretName,llmKeyDraft,llmPolicy,@@ -705,6 +792,9 @@ export function HostWizard({setSelectedMcp([])setSecretMode('existing')setExistingSecret('')+ setExistingLlmSecret('')+ setConnectionRef(CODEX_UNASSIGNED_CONNECTION_KEY)+ setCodexModels([])setNewSecretName('')setSecretNameTouched(false)setLlmKeyDraft(createEmptyLlmKeyDraft())@@ -816,12 +906,20 @@ export function HostWizard({allowedCatalog)+ const resolvedSecretRef = !chainRequiresSecret+ ? ''+ : secretMode === 'new'+ ? normalizedSecretName+ : provider === 'codex-subscription'+ ? existingLlmSecret.trim()+ : parseCredentialSelect(existingSecret).kind === 'secret'+ ? existingSecret+ : ''+const hostSpec: Record<string, unknown> = {host: normalizedHostName,contextRef: resolvedContextName,- ...(chainRequiresSecret- ? { secretRef: secretMode === 'existing' ? existingSecret : normalizedSecretName }- : {}),+ ...(resolvedSecretRef ? { secretRef: resolvedSecretRef } : {}),channels: [],model: {provider,@@ -1120,19 +1218,13 @@ export function HostWizard({<LlmProviderConfigprovider={provider}model={modelName}- subscriptionCredentialEnabled- afterPrimaryProvider={- provider === 'codex-subscription' ? (- <CodexAgentAssignment- connectionRef={connectionRef}- onConnectionRefChange={setConnectionRef}- onModelsChange={setCodexModels}- />- ) : null- }onPrimaryChange={next => {setProvider(next.provider)setModelName(next.model)+ if (next.provider !== 'codex-subscription') {+ setConnectionRef(CODEX_UNASSIGNED_CONNECTION_KEY)+ setCodexModels([])+ }}}policy={llmPolicy}onPolicyChange={setLlmPolicy}@@ -1156,85 +1248,100 @@ export function HostWizard({fallbackProvidersInitiallyCollapseddisabled={busy}/>- {chainRequiresSecret ? (- <div className="cu-agent-access-section">- <strong>Credentials</strong>- <span className="cu-muted cu-agent-access-hint">- Store this agent's own LLM credentials, or use a shared secret.- </span>- <div className="cu-agent-radio-group">- <label className="cu-agent-radio cu-agent-radio--card">- <input- type="radio"- checked={secretMode === 'existing'}- onChange={() => setSecretMode('existing')}- />- <span className="cu-agent-radio__copy">- <span className="cu-agent-radio__title">Use an existing secret</span>- <span className="cu-agent-radio__description">- Select a saved secret that already contains LLM API keys.- </span>+ <div className="cu-agent-access-section">+ <strong>Credentials</strong>+ <span className="cu-muted cu-agent-access-hint">+ Choose an API key secret or a ChatGPT subscription, or create a new secret.+ </span>+ <div className="cu-agent-radio-group">+ <label className="cu-agent-radio cu-agent-radio--card">+ <input+ type="radio"+ checked={secretMode === 'existing'}+ onChange={() => setSecretMode('existing')}+ />+ <span className="cu-agent-radio__copy">+ <span className="cu-agent-radio__title">Use an existing secret</span>+ <span className="cu-agent-radio__description">+ Select a saved API key secret or a ChatGPT grant.</span>- </label>- <label className="cu-agent-radio cu-agent-radio--card">- <input- type="radio"- checked={secretMode === 'new'}- onChange={() => setSecretMode('new')}- />- <span className="cu-agent-radio__copy">- <span className="cu-agent-radio__title">New secret</span>- <span className="cu-agent-radio__description">- Create a new secret for this agent. Its name is derived from the agent name.- </span>+ </span>+ </label>+ <label className="cu-agent-radio cu-agent-radio--card">+ <input+ type="radio"+ checked={secretMode === 'new'}+ onChange={() => {+ setSecretMode('new')+ if (provider === 'codex-subscription' && !llmPolicy?.fallbacks.length) {+ setConnectionRef(CODEX_UNASSIGNED_CONNECTION_KEY)+ setCodexModels([])+ setExistingSecret('')+ setProvider('openai')+ setModelName(+ resolveDefaultModel('openai', getModelOptions(allowedCatalog, 'openai'))+ )+ }+ }}+ />+ <span className="cu-agent-radio__copy">+ <span className="cu-agent-radio__title">New secret</span>+ <span className="cu-agent-radio__description">+ Create a new secret for this agent. Its name is derived from the agent name.</span>- </label>+ </span>+ </label>+ </div>+ {secretMode === 'existing' ? (+ <div className="cu-agent-access-section">+ <strong>Credential</strong>+ <WizardSelect+ value={existingSecret}+ placeholder="Select credential"+ options={secretOptions}+ onChange={handleExistingSecretChange}+ />+ {provider === 'codex-subscription' && chainRequiresSecret ? (+ <>+ <strong>LLM secret</strong>+ <WizardSelect+ value={existingLlmSecret}+ placeholder="Select secret..."+ options={apiKeyOptions}+ onChange={setExistingLlmSecret}+ />+ </>+ ) : null}</div>- {secretMode === 'existing' ? (- <div className="cu-agent-access-section">- <strong>Credential</strong>- <WizardSelect- value={existingSecret}- placeholder="Select secret..."- options={secretOptions}- onChange={handleExistingSecretChange}+ ) : (+ <Field+ description="Auto-named from the agent — edit if you prefer a different name."+ label="Secret name"+ >+ <span className="cu-agent-input-shell">+ <TextInput+ value={newSecretName}+ onChange={e => {+ setSecretNameTouched(true)+ setNewSecretName(toKebabInput(e.target.value))+ }}+ placeholder="secret-name"/>- </div>- ) : (- <Field- description="Auto-named from the agent — edit if you prefer a different name."- label="Secret name"- >- <span className="cu-agent-input-shell">- <TextInput- value={newSecretName}- onChange={e => {- setSecretNameTouched(true)- setNewSecretName(toKebabInput(e.target.value))- }}- placeholder="secret-name"- />- <span- className={cn(- 'cu-agent-input-shell__status',- !toKebabCase(newSecretName) && 'cu-agent-input-shell__status--empty'- )}- aria-label={- toKebabCase(newSecretName) ? 'Valid secret name' : 'Secret name empty'- }- >- {toKebabCase(newSecretName) ? <IconCheck width={16} height={16} /> : null}- </span>+ <span+ className={cn(+ 'cu-agent-input-shell__status',+ !toKebabCase(newSecretName) && 'cu-agent-input-shell__status--empty'+ )}+ aria-label={+ toKebabCase(newSecretName) ? 'Valid secret name' : 'Secret name empty'+ }+ >+ {toKebabCase(newSecretName) ? <IconCheck width={16} height={16} /> : null}</span>- </Field>- )}- </div>- ) : (- <p className="cu-muted cu-agent-access-hint">- This OpenAI credential authenticates through a ChatGPT subscription. No LLM secret- is required unless you add a static-credentials fallback.- </p>- )}+ </span>+ </Field>+ )}+ </div></div>)}diff --git a/control-ui/components/HostWizard/types.ts b/control-ui/components/HostWizard/types.tsindex 1ce5abd57..b4ec0c763 100644--- a/control-ui/components/HostWizard/types.ts+++ b/control-ui/components/HostWizard/types.ts@@ -49,6 +49,7 @@ export type HostWizardProps = {}export type WizardSelectOption = {+ group?: stringlabel: ReactNodemeta?: ReactNodeproviders?: { id: string; label: string }[]diff --git a/control-ui/components/LlmProviderConfig/index.tsx b/control-ui/components/LlmProviderConfig/index.tsxindex c540ab639..cd2e38ffa 100644--- a/control-ui/components/LlmProviderConfig/index.tsx+++ b/control-ui/components/LlmProviderConfig/index.tsx@@ -11,7 +11,6 @@ import { IconChevronRight } from '@/components/icons'import { Button, Field, TextAreaInput, TextInput } from '@/components/ui'import { cn } from '@/lib/cn'import {- LLM_PROVIDER_OPTIONS,type LlmCredentialField,type LlmCredentialGroup,type LlmProvider,@@ -29,7 +28,6 @@ import {mintFallbackSlot,normalizeProvider,providerSupportsFallbackCredentialSlot,- resolveCodexGrantModel,resolveDefaultModel,validateLlmSecretData,} from '@/lib/llm'@@ -105,8 +103,6 @@ export function LlmProviderConfig({secretKeys = [],fallbackProvidersInitiallyCollapsed = false,disabled = false,- subscriptionCredentialEnabled = false,- afterPrimaryProvider,}: LlmProviderConfigProps) {const [fallbackProvidersOpen, setFallbackProvidersOpen] = useState(!fallbackProvidersInitiallyCollapsed@@ -129,9 +125,7 @@ export function LlmProviderConfig({[catalog, allowedModels, provider])const primaryModelOutOfAllowlist = Boolean(model) && !primaryModelOptions.includes(model)- const pickerOptions = subscriptionCredentialEnabled- ? OPERATOR_PROVIDER_OPTIONS- : LLM_PROVIDER_OPTIONS+ const pickerOptions = OPERATOR_PROVIDER_OPTIONSconst primaryProviderOptions = useMemo(() =>pickerOptions.map(option => ({@@ -274,64 +268,6 @@ export function LlmProviderConfig({}}/></Field>- {subscriptionCredentialEnabled && isOpenAiFamily(provider) ? (- <fieldset- className="cu-field cu-llm-config__credential-kind"- data-testid="openai-credential-kind"- >- <legend className="cu-field__label">OpenAI credential</legend>- <div- className="cu-agent-radio-group"- role="radiogroup"- aria-label="OpenAI credential"- >- <label className="cu-agent-radio">- <input- type="radio"- name="openai-credential-kind"- checked={provider === 'openai'}- disabled={disabled}- onChange={() =>- onPrimaryChange({- provider: 'openai',- model: resolveDefaultModel(- 'openai',- constrainModelOptions(catalog, allowedModels, 'openai')- ),- })- }- />- API key- </label>- <label className="cu-agent-radio">- <input- type="radio"- name="openai-credential-kind"- checked={provider === OPENAI_SUBSCRIPTION_PROVIDER}- disabled={disabled}- onChange={() =>- onPrimaryChange({- provider: OPENAI_SUBSCRIPTION_PROVIDER,- model: resolveCodexGrantModel(- model,- constrainModelOptions(- catalog,- allowedModels,- OPENAI_SUBSCRIPTION_PROVIDER- )- ),- })- }- />- ChatGPT subscription- </label>- </div>- </fieldset>- ) : null}- {afterPrimaryProvider ? (- <div className="cu-llm-config__after-provider">{afterPrimaryProvider}</div>- ) : null}-{replacePrimaryModelWithAllowedModels && showAllowedModels ? (<AllowedModelsFieldprovider={provider}diff --git a/control-ui/components/LlmProviderConfig/types.ts b/control-ui/components/LlmProviderConfig/types.tsindex d077708a7..645b39fd3 100644--- a/control-ui/components/LlmProviderConfig/types.ts+++ b/control-ui/components/LlmProviderConfig/types.ts@@ -1,4 +1,3 @@-import type { ReactNode } from 'react'import type { HostAllowedModel, LlmModelCatalogEntry, LlmPolicy, LlmProvider } from '@/lib/llm'// Write-only credential wiring. Values are NEVER read back from the server; the@@ -59,9 +58,4 @@ export type LlmProviderConfigProps = {fallbackProvidersInitiallyCollapsed?: booleandisabled?: boolean-- /** When true, OpenAI offers API key vs ChatGPT subscription. Runtime id stays separate. */- subscriptionCredentialEnabled?: boolean- /** Rendered after the OpenAI credential radios (grant picker). */- afterPrimaryProvider?: ReactNode}diff --git a/control-ui/components/LlmSecretsSubTabs/index.tsx b/control-ui/components/LlmSecretsSubTabs/index.tsxnew file mode 100644index 000000000..f84e590d5--- /dev/null+++ b/control-ui/components/LlmSecretsSubTabs/index.tsx@@ -0,0 +1,24 @@+'use client'++import { CONTROL_ROUTES } from '@constants/routes'+import { TabBar } from '../TabBar'++export type LlmSecretsSubTab = 'api-key' | 'subscriptions'++export function LlmSecretsSubTabs({ activeValue }: { activeValue: LlmSecretsSubTab }) {+ return (+ <TabBar<LlmSecretsSubTab>+ ariaLabel="LLM secret kinds"+ activeValue={activeValue}+ className="cu-tabs--flush"+ options={[+ { value: 'api-key', href: CONTROL_ROUTES.secrets.llm, label: 'API-KEY' },+ {+ value: 'subscriptions',+ href: CONTROL_ROUTES.secrets.llmSubscriptions,+ label: 'Subscriptions',+ },+ ]}+ />+ )+}diff --git a/control-ui/components/SecretsScopeTabs/index.tsx b/control-ui/components/SecretsScopeTabs/index.tsxindex 586e59818..d50dbb64e 100644--- a/control-ui/components/SecretsScopeTabs/index.tsx+++ b/control-ui/components/SecretsScopeTabs/index.tsx@@ -3,7 +3,7 @@import { CONTROL_ROUTES } from '@constants/routes'import { TabBar } from '../TabBar'-export type SecretsTabScope = 'llm' | 'mcp' | 'recipe' | 'subscription'+export type SecretsTabScope = 'llm' | 'mcp' | 'recipe'export function SecretsScopeTabs({ activeValue }: { activeValue: SecretsTabScope }) {return (@@ -15,7 +15,6 @@ export function SecretsScopeTabs({ activeValue }: { activeValue: SecretsTabScope{ value: 'llm', href: CONTROL_ROUTES.secrets.llm, label: 'LLM' },{ value: 'mcp', href: CONTROL_ROUTES.secrets.connector, label: 'Connector' },{ value: 'recipe', href: CONTROL_ROUTES.secrets.recipe, label: 'Recipe' },- { value: 'subscription', href: CONTROL_ROUTES.secrets.subscription, label: 'Subscription' },]}/>)diff --git a/control-ui/components/SecretsTable.tsx b/control-ui/components/SecretsTable.tsxindex a6bd2ce94..779975d3f 100644--- a/control-ui/components/SecretsTable.tsx+++ b/control-ui/components/SecretsTable.tsx@@ -21,6 +21,7 @@ import { collectWorkflowRecipeSecretRefs } from '../lib/workflowRecipeSecretRefsimport { useConfirmDialog } from './ConfirmDialog'import { LlmCredentialFields } from './LlmCredentialFields'import { LlmProviderIcon } from './LlmProviderIcon'+import { LlmSecretsSubTabs } from './LlmSecretsSubTabs'import { SecretsScopeTabs } from './SecretsScopeTabs'import { SectionSearchInput } from './SectionSearchInput'import { IconKey } from './Sidebar/icons'@@ -572,6 +573,7 @@ export function SecretsTable({<div className="cu-card__body cu-card__body--auto cu-secrets-strip"><SecretsScopeTabs activeValue={scope} />+ {scope === 'llm' ? <LlmSecretsSubTabs activeValue="api-key" /> : null}</div>{scope === 'llm' && error && (@@ -627,16 +629,7 @@ export function SecretsTable({</div>) : scope === 'llm' && filteredRows.length === 0 ? (<div className="cu-empty">- {normalizedLlmSearch ? (- 'No LLM secrets match this search.'- ) : (- <>- No LLM secrets found.{' '}- <a href={CONTROL_ROUTES.secrets.subscription}>- ChatGPT subscriptions are managed in the Subscription tab.- </a>- </>- )}+ {normalizedLlmSearch ? 'No LLM secrets match this search.' : <>No LLM secrets found.</>}</div>) : scope === 'llm' ? (<div className="cu-table-wrap">diff --git a/control-ui/components/__tests__/CodexAgentAssignment.test.tsx b/control-ui/components/__tests__/CodexAgentAssignment.test.tsxdeleted file mode 100644index a6eda5b56..000000000--- a/control-ui/components/__tests__/CodexAgentAssignment.test.tsx+++ /dev/null@@ -1,219 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'-import type { CodexSubscriptionConnectionView } from '@lib/codexSubscription'-import {- createCodexSubscriptionConnection,- listCodexConnectionModels,- listCodexSubscriptionConnections,- pollCodexDevice,- startCodexDeviceConnect,-} from '@lib/codexSubscription'-import { CodexAgentAssignment } from '../CodexAgentAssignment'-import { ToastProvider } from '../Toast'--const confirmMock = vi.fn()--vi.mock('@components/ConfirmDialog', () => ({- useConfirmDialog: () => ({- confirm: confirmMock,- confirmDialog: null,- }),-}))--vi.mock('@lib/codexSubscriptionFeature', () => ({- isCodexSubscriptionUiEnabled: (capability?: { enabled?: boolean } | null) =>- capability?.enabled === true,- loadCodexSubscriptionCapability: async () => ({ enabled: true }),-}))--vi.mock('@lib/codexSubscription', async importOriginal => {- const actual = await importOriginal<typeof import('@lib/codexSubscription')>()- return {- ...actual,- listCodexSubscriptionConnections: vi.fn(),- listCodexConnectionModels: vi.fn(),- createCodexSubscriptionConnection: vi.fn(),- startCodexDeviceConnect: vi.fn(),- pollCodexDevice: vi.fn(),- syncCodexSubscriptionCatalog: vi.fn(),- }-})--function connection(- overrides: Partial<CodexSubscriptionConnectionView> &- Pick<CodexSubscriptionConnectionView, 'connectionKey'>-): CodexSubscriptionConnectionView {- return {- status: 'connected',- credentialRevision: 1,- catalogRevision: 1,- accountFingerprint: 'fp',- catalogStatus: 'ready',- catalogSyncedAt: '2026-08-20T00:00:00.000Z',- lastRefreshAt: '2026-08-20T00:00:00.000Z',- lastAuthAt: '2026-08-20T00:00:00.000Z',- refreshLockHeld: false,- displayName: overrides.connectionKey,- ...overrides,- }-}--function renderAssignment(connectionRef: string, onConnectionRefChange = vi.fn()) {- return {- onConnectionRefChange,- ...render(- <ToastProvider>- <CodexAgentAssignment- connectionRef={connectionRef}- hostName="chatllm"- onConnectionRefChange={onConnectionRefChange}- />- </ToastProvider>- ),- }-}--describe('CodexAgentAssignment', () => {- beforeEach(() => {- vi.mocked(listCodexConnectionModels).mockResolvedValue([])- confirmMock.mockReset()- })-- afterEach(() => {- cleanup()- vi.clearAllMocks()- })-- it('keeps an unknown connectionRef and does not rematch on load', async () => {- vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([- connection({ connectionKey: 'deployment-default', displayName: 'Default deployment' }),- ])- const { onConnectionRefChange } = renderAssignment('ghost-grant')- await waitFor(() => {- expect(screen.getByRole('option', { name: 'ghost-grant (unavailable)' })).toBeInTheDocument()- })- expect((screen.getByLabelText('ChatGPT subscription') as HTMLSelectElement).value).toBe(- 'ghost-grant'- )- expect(onConnectionRefChange).not.toHaveBeenCalled()- })-- it('does not rewrite connectionRef when the connection list fails', async () => {- vi.mocked(listCodexSubscriptionConnections).mockRejectedValue(new Error('list failed'))- const { onConnectionRefChange } = renderAssignment('team-plus')- await waitFor(() => {- expect(screen.getByText('list failed')).toBeInTheDocument()- })- expect(onConnectionRefChange).not.toHaveBeenCalled()- expect((screen.getByLabelText('ChatGPT subscription') as HTMLSelectElement).value).toBe(- 'team-plus'- )- })-- it('keeps a revoked current grant visible instead of replacing it', async () => {- vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([- connection({- connectionKey: 'team-plus',- displayName: 'Team Plus',- status: 'revoked',- }),- connection({ connectionKey: 'deployment-default', displayName: 'Default deployment' }),- ])- const { onConnectionRefChange } = renderAssignment('team-plus')- await waitFor(() => {- expect(screen.getByRole('option', { name: 'Team Plus (revoked)' })).toBeInTheDocument()- })- expect((screen.getByLabelText('ChatGPT subscription') as HTMLSelectElement).value).toBe(- 'team-plus'- )- expect(onConnectionRefChange).not.toHaveBeenCalled()- })-- it('changes connectionRef only after a successful create', async () => {- vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([- connection({ connectionKey: 'deployment-default', displayName: 'Default deployment' }),- ])- vi.mocked(createCodexSubscriptionConnection).mockResolvedValue(- connection({ connectionKey: 'codex-aabbccddeeff0011', displayName: 'Codex subscription' })- )- const { onConnectionRefChange } = renderAssignment('deployment-default')- await waitFor(() => {- expect(screen.getByRole('button', { name: 'New subscription' })).toBeInTheDocument()- })- fireEvent.click(screen.getByRole('button', { name: 'New subscription' }))- fireEvent.click(screen.getByRole('button', { name: 'Create' }))- await waitFor(() => {- expect(onConnectionRefChange).toHaveBeenCalledWith('codex-aabbccddeeff0011')- })- expect(onConnectionRefChange).toHaveBeenCalledTimes(1)- })-- it('clears the device-code banner after the poll expires', async () => {- vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([- connection({ connectionKey: 'team-plus', displayName: 'Team Plus' }),- ])- vi.mocked(startCodexDeviceConnect).mockResolvedValue({- userCode: 'ABCD-1234',- verificationUri: 'https://auth.openai.com/codex/device',- intervalSeconds: 0.01,- state: 'device-state',- intent: 'connect',- })- vi.mocked(pollCodexDevice).mockResolvedValue({ status: 'expired' })- renderAssignment('team-plus')- await waitFor(() => {- expect(screen.getByRole('button', { name: 'Sign in with ChatGPT' })).toBeEnabled()- })- fireEvent.click(screen.getByRole('button', { name: 'Sign in with ChatGPT' }))- await waitFor(() => {- expect(pollCodexDevice).toHaveBeenCalled()- })- expect(screen.queryByTestId('codex-device-code')).not.toBeInTheDocument()- })-- it('does not expose grant Revoke on the agent assignment surface', async () => {- vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([- connection({ connectionKey: 'team-plus', displayName: 'Team Plus' }),- ])- renderAssignment('team-plus')- await waitFor(() => {- expect(screen.getByRole('button', { name: 'Remove from this agent' })).toBeEnabled()- })- expect(screen.queryByRole('button', { name: 'Revoke', exact: true })).not.toBeInTheDocument()- expect(screen.getByRole('link', { name: 'Manage subscription' })).toHaveAttribute(- 'href',- '/secrets/subscription'- )- })-- it('drafts an unassigned connectionRef on Remove and does not persist until Save', async () => {- vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([- connection({ connectionKey: 'team-plus', displayName: 'Team Plus' }),- ])- confirmMock.mockResolvedValue(true)- const { onConnectionRefChange } = renderAssignment('team-plus')- await waitFor(() => {- expect(screen.getByRole('button', { name: 'Remove from this agent' })).toBeEnabled()- })- fireEvent.click(screen.getByRole('button', { name: 'Remove from this agent' }))- await waitFor(() => {- expect(onConnectionRefChange).toHaveBeenCalledWith('unassigned')- })- })-- it('drafts a selected grant and does not persist until Save', async () => {- vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([- connection({ connectionKey: 'team-plus', displayName: 'Team Plus' }),- connection({ connectionKey: 'personal-pro', displayName: 'Personal Pro' }),- ])- const { onConnectionRefChange } = renderAssignment('team-plus')- await waitFor(() => {- expect(screen.getByRole('option', { name: 'Personal Pro' })).toBeInTheDocument()- })- fireEvent.change(screen.getByLabelText('ChatGPT subscription'), {- target: { value: 'personal-pro' },- })- expect(onConnectionRefChange).toHaveBeenCalledWith('personal-pro')- expect(onConnectionRefChange).toHaveBeenCalledTimes(1)- })-})diff --git a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsxindex 3d566e61e..c1c476930 100644--- a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx+++ b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx@@ -1,12 +1,15 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import type { CodexSubscriptionConnectionView } from '@lib/codexSubscription'import {- bindCodexHost,createCodexSubscriptionConnection,- listCodexSubscriptionFleet,+ listCodexConnectionModels,+ listCodexSubscriptionConnections,+ patchCodexCatalogModel,+ patchCodexSubscriptionConnection,revokeCodexSubscription,- unbindCodexHost,+ startCodexDeviceConnect,+ syncCodexSubscriptionCatalog,} from '@lib/codexSubscription'import { CodexSubscriptionHub } from '../CodexSubscriptionHub'import { ToastProvider } from '../Toast'@@ -30,15 +33,15 @@ vi.mock('@lib/codexSubscription', async importOriginal => {const actual = await importOriginal<typeof import('@lib/codexSubscription')>()return {...actual,- listCodexSubscriptionFleet: vi.fn(),listCodexSubscriptionConnections: vi.fn(),+ listCodexConnectionModels: vi.fn(),createCodexSubscriptionConnection: vi.fn(),+ patchCodexSubscriptionConnection: vi.fn(),+ patchCodexCatalogModel: vi.fn(),startCodexDeviceConnect: vi.fn(),pollCodexDevice: vi.fn(),syncCodexSubscriptionCatalog: vi.fn(),revokeCodexSubscription: vi.fn(),- unbindCodexHost: vi.fn(),- bindCodexHost: vi.fn(),}})@@ -57,6 +60,7 @@ function connection(lastAuthAt: '2026-08-20T00:00:00.000Z',refreshLockHeld: false,displayName: overrides.connectionKey,+ defaultModel: 'gpt-5.1',...overrides,}}@@ -64,21 +68,13 @@ function connection(describe('CodexSubscriptionHub', () => {beforeEach(() => {confirmMock.mockReset()- vi.mocked(listCodexSubscriptionFleet).mockResolvedValue({- connections: [connection({ connectionKey: 'codex-aaa', displayName: 'Team A' })],- assignableHosts: [- {- name: 'chatllm',- connectionRef: 'codex-aaa',- displayName: 'chatllm',- provider: 'codex-subscription',- model: 'gpt-5.1',- },- { name: 'writer', connectionRef: 'unassigned', displayName: 'writer' },- { name: 'researcher', connectionRef: 'unassigned', displayName: 'researcher' },- ],- assignableHostsUnavailable: false,- })+ vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([+ connection({ connectionKey: 'codex-aaa', displayName: 'Team A' }),+ ])+ vi.mocked(listCodexConnectionModels).mockResolvedValue([+ { model: 'gpt-5.1', enabled: true, stale: false },+ { model: 'gpt-5.3-codex', enabled: false, stale: false },+ ])})afterEach(() => {@@ -86,7 +82,7 @@ describe('CodexSubscriptionHub', () => {vi.clearAllMocks()})- it('creates a subscription from the hub CTA', async () => {+ it('creates a subscription from the Add modal', async () => {vi.mocked(createCodexSubscriptionConnection).mockResolvedValue(connection({ connectionKey: 'codex-bbb', displayName: 'New team' }))@@ -95,205 +91,93 @@ describe('CodexSubscriptionHub', () => {<CodexSubscriptionHub /></ToastProvider>)- await waitFor(() => {- expect(screen.getByRole('button', { name: 'Add subscription' })).toBeInTheDocument()- })+ expect(await screen.findByText('Team A')).toBeInTheDocument()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: 'Create' }))await waitFor(() => {- expect(createCodexSubscriptionConnection).toHaveBeenCalled()+ expect(createCodexSubscriptionConnection).toHaveBeenCalledWith({ displayName: 'New team' })})expect(revokeCodexSubscription).not.toHaveBeenCalled()})- it('renders subscriptions as one Secrets table, not stacked cards', async () => {+ it('renders subscriptions as a Secrets table with pencil and delete actions', async () => {render(<ToastProvider><CodexSubscriptionHub /></ToastProvider>)- await waitFor(() => {- expect(screen.getByTestId('codex-hub-table')).toBeInTheDocument()- })+ expect(await screen.findByText('Team A')).toBeInTheDocument()expect(screen.getByRole('columnheader', { name: 'Name' })).toBeInTheDocument()expect(screen.getByRole('columnheader', { name: 'Status' })).toBeInTheDocument()- expect(screen.getByRole('columnheader', { name: 'Agents' })).toBeInTheDocument()- expect(screen.getByRole('link', { name: 'chatllm' })).toBeInTheDocument()- expect(screen.getByText('gpt-5.1')).toBeInTheDocument()- expect(screen.queryByRole('heading', { name: 'Available' })).not.toBeInTheDocument()- expect(screen.queryByRole('heading', { name: 'Assigned' })).not.toBeInTheDocument()- expect(document.querySelectorAll('.cu-llm-config__block').length).toBe(0)- expect(screen.getByLabelText('Add agents to this subscription')).toBeInTheDocument()- })-- it('assigns one available agent without revoking', async () => {- vi.mocked(bindCodexHost).mockResolvedValue({- host: 'writer',- connectionRef: 'codex-aaa',- model: 'gpt-5.1',- })- render(- <ToastProvider>- <CodexSubscriptionHub />- </ToastProvider>+ expect(screen.getByRole('tab', { name: 'API-KEY' })).toHaveAttribute('href', '/secrets/llm')+ expect(screen.getByRole('tab', { name: 'Subscriptions' })).toHaveAttribute(+ 'href',+ '/secrets/llm/subscriptions')- await waitFor(() => {- expect(screen.getByLabelText('Add agents to this subscription')).toBeInTheDocument()- })- fireEvent.click(screen.getByLabelText('Add agents to this subscription'))- fireEvent.click(screen.getByRole('option', { name: 'writer' }))- fireEvent.click(screen.getByRole('button', { name: 'Add agents' }))- await waitFor(() => {- expect(bindCodexHost).toHaveBeenCalledWith('codex-aaa', 'writer')- })- expect(bindCodexHost).toHaveBeenCalledTimes(1)- expect(revokeCodexSubscription).not.toHaveBeenCalled()+ expect(screen.queryByRole('columnheader', { name: 'Agents' })).not.toBeInTheDocument()+ expect(screen.queryByLabelText('Add agents to this subscription')).not.toBeInTheDocument()+ expect(+ screen.getByRole('button', { name: 'Update ChatGPT subscription Team A' })+ ).toBeInTheDocument()+ expect(+ screen.getByRole('button', { name: 'Delete ChatGPT subscription Team A' })+ ).toBeInTheDocument()})- it('assigns multiple available agents to the same subscription in one action', async () => {- vi.mocked(bindCodexHost)- .mockResolvedValueOnce({ host: 'writer', connectionRef: 'codex-aaa' })- .mockResolvedValueOnce({ host: 'researcher', connectionRef: 'codex-aaa' })- render(- <ToastProvider>- <CodexSubscriptionHub />- </ToastProvider>+ it('opens the grant modal for Sign in, Sync, and model toggles without binding hosts', async () => {+ vi.mocked(startCodexDeviceConnect).mockResolvedValue({+ userCode: 'ABCD-1234',+ verificationUri: 'https://chatgpt.com/device',+ intervalSeconds: 1,+ state: 'state-1',+ intent: 'connect',+ })+ vi.mocked(syncCodexSubscriptionCatalog).mockResolvedValue({+ outcome: 'ready',+ added: 1,+ refreshed: 0,+ staled: 0,+ connection: connection({ connectionKey: 'codex-aaa', displayName: 'Team A' }),+ })+ vi.mocked(patchCodexCatalogModel).mockResolvedValue([+ { model: 'gpt-5.1', enabled: true, stale: false },+ { model: 'gpt-5.3-codex', enabled: true, stale: false },+ ])+ vi.mocked(patchCodexSubscriptionConnection).mockResolvedValue(+ connection({ connectionKey: 'codex-aaa', displayName: 'Team A', defaultModel: 'gpt-5.1' }))- await waitFor(() => {- expect(screen.getByLabelText('Add agents to this subscription')).toBeInTheDocument()- })- fireEvent.click(screen.getByLabelText('Add agents to this subscription'))- fireEvent.click(screen.getByRole('option', { name: 'writer' }))- fireEvent.click(screen.getByRole('option', { name: 'researcher' }))- fireEvent.click(screen.getByRole('button', { name: 'Add 2 agents' }))- await waitFor(() => {- expect(bindCodexHost).toHaveBeenCalledTimes(2)- })- expect(bindCodexHost).toHaveBeenNthCalledWith(1, 'codex-aaa', 'writer')- expect(bindCodexHost).toHaveBeenNthCalledWith(2, 'codex-aaa', 'researcher')- expect(revokeCodexSubscription).not.toHaveBeenCalled()- })-- it('keeps assigning remaining agents when one bind fails', async () => {- vi.mocked(bindCodexHost)- .mockRejectedValueOnce(new Error('writer bind failed'))- .mockResolvedValueOnce({ host: 'researcher', connectionRef: 'codex-aaa' })- render(- <ToastProvider>- <CodexSubscriptionHub />- </ToastProvider>- )- await waitFor(() => {- expect(screen.getByLabelText('Add agents to this subscription')).toBeInTheDocument()- })- fireEvent.click(screen.getByLabelText('Add agents to this subscription'))- fireEvent.click(screen.getByRole('option', { name: 'writer' }))- fireEvent.click(screen.getByRole('option', { name: 'researcher' }))- fireEvent.click(screen.getByRole('button', { name: 'Add 2 agents' }))- await waitFor(() => {- expect(bindCodexHost).toHaveBeenCalledTimes(2)- })- expect(bindCodexHost).toHaveBeenNthCalledWith(2, 'codex-aaa', 'researcher')- expect(revokeCodexSubscription).not.toHaveBeenCalled()- })-- it('confirms before switching a host from another named grant', async () => {- confirmMock.mockResolvedValue(true)- vi.mocked(listCodexSubscriptionFleet).mockResolvedValue({- connections: [- connection({ connectionKey: 'codex-aaa', displayName: 'Team A' }),- connection({ connectionKey: 'codex-bbb', displayName: 'Team B' }),- ],- assignableHosts: [- { name: 'chatllm', connectionRef: 'codex-bbb', displayName: 'chatllm' },- { name: 'writer', connectionRef: 'unassigned', displayName: 'writer' },- ],- assignableHostsUnavailable: false,- })- vi.mocked(bindCodexHost).mockResolvedValue({ host: 'chatllm', connectionRef: 'codex-aaa' })render(<ToastProvider><CodexSubscriptionHub /></ToastProvider>)- const teamA = await screen.findByTestId('codex-hub-grant-codex-aaa')- fireEvent.click(within(teamA).getByLabelText('Add agents to this subscription'))- fireEvent.click(within(teamA).getByRole('option', { name: 'chatllm' }))- fireEvent.click(within(teamA).getByRole('button', { name: 'Add agents' }))- await waitFor(() => {- expect(confirmMock).toHaveBeenCalledWith(- expect.objectContaining({- title: 'Switch chatllm to this subscription?',- })- )- })- expect(bindCodexHost).toHaveBeenCalledWith('codex-aaa', 'chatllm')- expect(revokeCodexSubscription).not.toHaveBeenCalled()- })-- it('confirms before switching a non-Codex agent to ChatGPT', async () => {- confirmMock.mockResolvedValue(true)- vi.mocked(listCodexSubscriptionFleet).mockResolvedValue({- connections: [connection({ connectionKey: 'codex-aaa', displayName: 'Team A' })],- assignableHosts: [- {- name: 'writer',- connectionRef: 'unassigned',- displayName: 'writer',- provider: 'zai',- model: 'glm-4.7',- },- ],- assignableHostsUnavailable: false,- })- vi.mocked(bindCodexHost).mockResolvedValue({- host: 'writer',- connectionRef: 'codex-aaa',- model: 'gpt-5.1',- })- render(- <ToastProvider>- <CodexSubscriptionHub />- </ToastProvider>+ fireEvent.click(+ await screen.findByRole('button', { name: 'Update ChatGPT subscription Team A' }))+ expect(await screen.findByRole('button', { name: 'Sign in with ChatGPT' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Sync catalog' })).toBeInTheDocument()+ expect(listCodexConnectionModels).toHaveBeenCalledWith('codex-aaa')+ fireEvent.click(screen.getByRole('button', { name: 'Sync catalog' }))await waitFor(() => {- expect(screen.getByLabelText('Add agents to this subscription')).toBeInTheDocument()+ expect(syncCodexSubscriptionCatalog).toHaveBeenCalledWith('codex-aaa')})- fireEvent.click(screen.getByLabelText('Add agents to this subscription'))- fireEvent.click(screen.getByRole('option', { name: 'writer' }))- fireEvent.click(screen.getByRole('button', { name: 'Add agents' }))+ fireEvent.click(screen.getByLabelText('gpt-5.3-codex'))await waitFor(() => {- expect(confirmMock).toHaveBeenCalledWith(- expect.objectContaining({- title: 'Switch writer to ChatGPT?',- })- )+ expect(patchCodexCatalogModel).toHaveBeenCalledWith('codex-aaa', 'gpt-5.3-codex', true)})- expect(bindCodexHost).toHaveBeenCalledWith('codex-aaa', 'writer')- })-- it('unbinds an assigned agent without revoking', async () => {- confirmMock.mockResolvedValue(true)- vi.mocked(unbindCodexHost).mockResolvedValue({- host: 'chatllm',- connectionRef: 'unassigned',- })- render(- <ToastProvider>- <CodexSubscriptionHub />- </ToastProvider>- )- await waitFor(() => {- expect(screen.getByRole('button', { name: 'Remove agent chatllm' })).toBeInTheDocument()- })- fireEvent.click(screen.getByRole('button', { name: 'Remove agent chatllm' }))+ fireEvent.click(screen.getByRole('button', { name: 'Update subscription' }))await waitFor(() => {- expect(unbindCodexHost).toHaveBeenCalledWith('codex-aaa', 'chatllm')+ expect(patchCodexSubscriptionConnection).toHaveBeenCalledWith('codex-aaa', {+ displayName: 'Team A',+ defaultModel: 'gpt-5.1',+ })})- expect(revokeCodexSubscription).not.toHaveBeenCalled()})- it('revokes only from the hub danger action', async () => {+ it('revokes from the table delete action after confirm', async () => {confirmMock.mockResolvedValue(true)vi.mocked(revokeCodexSubscription).mockResolvedValue(connection({ connectionKey: 'codex-aaa', displayName: 'Team A', status: 'revoked' })@@ -303,10 +187,9 @@ describe('CodexSubscriptionHub', () => {<CodexSubscriptionHub /></ToastProvider>)- await waitFor(() => {- expect(screen.getByRole('button', { name: 'Revoke subscription' })).toBeInTheDocument()- })- fireEvent.click(screen.getByRole('button', { name: 'Revoke subscription' }))+ fireEvent.click(+ await screen.findByRole('button', { name: 'Delete ChatGPT subscription Team A' })+ )await waitFor(() => {expect(revokeCodexSubscription).toHaveBeenCalledWith('codex-aaa')})diff --git a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsxindex d480c7a73..3650fa09f 100644--- a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx+++ b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx@@ -32,10 +32,6 @@ vi.mock('../HostIdentityTab', () => ({),}))-vi.mock('../CodexAgentAssignment', () => ({- CodexAgentAssignment: () => <div data-testid="codex-agent-assignment" />,-}))-vi.mock('../HostAccessTab', () => ({HostAccessTab: ({ hostName }: { hostName: string }) => (<div data-testid="access-tab">Access editor for {hostName}</div>@@ -47,6 +43,7 @@ vi.mock('../../lib/codexSubscription', async importOriginal => {return {...actual,listCodexSubscriptionConnections: vi.fn().mockResolvedValue([]),+ listCodexConnectionModels: vi.fn().mockResolvedValue([]),}})@@ -145,7 +142,7 @@ describe('HostDetailsPage identity integration', () => {expect(screen.getByText('Default model')).toBeInTheDocument()expect(screen.getByText('gpt-5.4')).toBeInTheDocument()expect(screen.queryByText('Model name')).not.toBeInTheDocument()- expect(screen.getByText('Secret reference')).toBeInTheDocument()+ expect(screen.getByText('Credential')).toBeInTheDocument()expect(container.querySelector('.cu-agent-detail-card')).toBeNull()expect(container.querySelector('.cu-agent-detail-heading')).not.toBeNull()expect(container.querySelector('.cu-agent-detail-toolbar')).toBeNull()@@ -156,7 +153,7 @@ describe('HostDetailsPage identity integration', () => {screen.getByLabelText('Allowed models · OpenAI', { selector: '#llm-allowed-openai' })).toBeInTheDocument()expect(screen.queryByLabelText('Model', { selector: '#llm-primary-model' })).toBeNull()- expect(screen.getByLabelText('Secret reference')).toBeInTheDocument()+ expect(screen.getByLabelText('Credential')).toBeInTheDocument()expect(screen.getByRole('button', { name: 'Save' }).closest('.cu-agent-detail-toolbar')).not.toBeNull()@@ -178,6 +175,7 @@ describe('HostDetailsPage identity integration', () => {lastRefreshAt: '2026-08-20T00:00:00.000Z',lastAuthAt: '2026-08-20T00:00:00.000Z',refreshLockHeld: false,+ defaultModel: 'gpt-5.1',},])const codexHost = {@@ -207,7 +205,9 @@ describe('HostDetailsPage identity integration', () => {expect(screen.getByText('gpt-5.1')).toBeInTheDocument()expect(screen.getByText('Team A')).toBeInTheDocument()expect(screen.queryByText('codex-aaa')).not.toBeInTheDocument()- expect(screen.getByText('Broker-backed — no LLM secret required')).toBeInTheDocument()+ expect(screen.getByText('Team A')).toBeInTheDocument()+ expect(screen.getByText('Credential')).toBeInTheDocument()+ expect(screen.queryByText('Broker-backed — no LLM secret required')).not.toBeInTheDocument()expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()})@@ -439,10 +439,12 @@ describe('HostDetailsPage identity integration', () => {mockParams = { name: 'foo', tab: 'model' }render(<HostDetailsPage />)- expect(await screen.findByText('Broker-backed — no LLM secret required')).toBeInTheDocument()- expect(screen.getByText('ChatGPT subscription')).toBeInTheDocument()+ expect(await screen.findByText('No credential assigned')).toBeInTheDocument()+ expect(screen.getByText('Credential')).toBeInTheDocument()expect(screen.queryByText('OpenAI Codex Subscription')).not.toBeInTheDocument()fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ expect(screen.getByLabelText('Credential')).toBeInTheDocument()+ expect(screen.queryByRole('radio', { name: /ChatGPT subscription/i })).not.toBeInTheDocument()fireEvent.click(screen.getByRole('button', { name: 'Save' }))await waitFor(() =>diff --git a/control-ui/components/__tests__/HostWizard.test.tsx b/control-ui/components/__tests__/HostWizard.test.tsxindex 7f08f0a5c..be388f6a8 100644--- a/control-ui/components/__tests__/HostWizard.test.tsx+++ b/control-ui/components/__tests__/HostWizard.test.tsx@@ -22,19 +22,31 @@ import { ToastProvider } from '../Toast'* These tests lock the new behavior so it cannot regress.*/-vi.mock('../CodexAgentAssignment', () => ({- CodexAgentAssignment: ({- onConnectionRefChange,- }: {- onConnectionRefChange: (connectionKey: string) => void- }) => (- <div data-testid="codex-agent-assignment">- <button type="button" onClick={() => onConnectionRefChange('codex-aaa')}>- Assign test grant- </button>- </div>- ),-}))+vi.mock('../../lib/codexSubscription', async importOriginal => {+ const actual = await importOriginal<typeof import('../../lib/codexSubscription')>()+ return {+ ...actual,+ listCodexSubscriptionConnections: vi.fn().mockResolvedValue([+ {+ connectionKey: 'codex-aaa',+ displayName: 'Team A',+ status: 'connected',+ defaultModel: 'gpt-5.1',+ credentialRevision: 1,+ catalogRevision: 1,+ accountFingerprint: 'fp',+ catalogStatus: 'ready',+ catalogSyncedAt: '2026-08-20T00:00:00.000Z',+ lastRefreshAt: '2026-08-20T00:00:00.000Z',+ lastAuthAt: '2026-08-20T00:00:00.000Z',+ refreshLockHeld: false,+ },+ ]),+ listCodexConnectionModels: vi+ .fn()+ .mockResolvedValue([{ model: 'gpt-5.1', enabled: true, stale: false }]),+ }+})// Mock lib/api BEFORE importing the component. vi.mock is hoisted.vi.mock('../../lib/api', () => ({@@ -176,7 +188,7 @@ async function walkToAccessStep(opts?: { agentName?: string }) {// Step 2: Model & Credentials — default model is valid; reuse the secret we provided.fireEvent.click(screen.getByLabelText(/Use an existing Secret/i))- fireEvent.click(screen.getByRole('button', { name: /Select secret/i }))+ fireEvent.click(screen.getByRole('button', { name: /Select credential/i }))fireEvent.click(screen.getByRole('option', { name: /secret-a/i }))fireEvent.click(screen.getByRole('button', { name: 'Next' }))@@ -261,7 +273,7 @@ describe('HostWizard — credential draft is projected onto the active providerfireEvent.change(screen.getByPlaceholderText(/context-name/i), { target: { value: 'ctx1' } })fireEvent.click(screen.getByRole('button', { name: 'Next' }))fireEvent.click(screen.getByLabelText(/Use an existing Secret/i))- fireEvent.click(screen.getByRole('button', { name: /Select secret/i }))+ fireEvent.click(screen.getByRole('button', { name: /Select credential/i }))const option = screen.getByRole('option', { name: /shared-llm-keys/ })expect(option).toHaveTextContent(/Providers: OpenAI, Amazon Bedrock/)@@ -285,7 +297,7 @@ describe('HostWizard — credential draft is projected onto the active providerfireEvent.change(screen.getByPlaceholderText(/context-name/i), { target: { value: 'ctx1' } })fireEvent.click(screen.getByRole('button', { name: 'Next' }))- fireEvent.click(screen.getByRole('button', { name: /Select secret/i }))+ fireEvent.click(screen.getByRole('button', { name: /Select credential/i }))fireEvent.click(screen.getByRole('option', { name: /zai-only/i }))const providerField = screen.getByText('Provider', { selector: 'label' }).parentElementconst modelField = screen.getByText('Default model', { selector: 'label' }).parentElement@@ -798,17 +810,14 @@ async function walkToModelStep(opts?: { agentName?: string }) {}async function selectCodexSubscription(model = 'gpt-5.1') {- fireEvent.click(screen.getByLabelText('Provider', { selector: '#llm-primary-provider' }))- fireEvent.click(screen.getByRole('option', { name: /^OpenAI$/i }))- fireEvent.click(screen.getByRole('radio', { name: /ChatGPT subscription/i }))+ fireEvent.click(screen.getByRole('button', { name: /Select credential/i }))+ fireEvent.click(screen.getByRole('option', { name: /Team A/i }))await waitFor(() => {- expect(screen.queryByText(/Use an existing secret/i)).not.toBeInTheDocument()+ expect(+ screen.getByLabelText('Default model', { selector: '#llm-primary-model' })+ ).toHaveTextContent(model)})- expect(- screen.queryByRole('option', { name: /OpenAI Codex Subscription/i })- ).not.toBeInTheDocument()- fireEvent.click(screen.getByLabelText('Default model', { selector: '#llm-primary-model' }))- fireEvent.click(screen.getByRole('option', { name: model }))+ expect(screen.queryByRole('radio', { name: /^ChatGPT subscription$/i })).not.toBeInTheDocument()}describe('HostWizard — broker-backed Codex authoring', () => {@@ -819,11 +828,7 @@ describe('HostWizard — broker-backed Codex authoring', () => {expect(screen.queryByLabelText(/OpenAI API key/i)).not.toBeInTheDocument()fireEvent.click(screen.getByLabelText('Default model', { selector: '#llm-primary-model' }))expect(screen.queryByRole('option', { name: 'old-codex' })).not.toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()- fireEvent.click(screen.getByRole('button', { name: 'Assign test grant' }))- await waitFor(() => {- expect(screen.getByRole('button', { name: 'Next' })).toBeEnabled()- })+ expect(screen.getByRole('button', { name: 'Next' })).toBeEnabled()fireEvent.click(screen.getByRole('button', { name: 'Next' }))fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))@@ -858,19 +863,16 @@ describe('HostWizard — broker-backed Codex authoring', () => {it('blocks Next until a ChatGPT subscription is chosen', async () => {await renderWizard()await walkToModelStep({ agentName: 'codex-needs-grant' })- await selectCodexSubscription()expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()- expect(screen.getByText('Choose a ChatGPT subscription before continuing.')).toBeInTheDocument()- fireEvent.click(screen.getByRole('button', { name: 'Assign test grant' }))+ expect(screen.getByText('Select an existing secret.')).toBeInTheDocument()+ await selectCodexSubscription()await waitFor(() => {expect(screen.getByRole('button', { name: 'Next' })).toBeEnabled()})- expect(- screen.queryByText('Choose a ChatGPT subscription before continuing.')- ).not.toBeInTheDocument()+ expect(screen.queryByText('Select an existing secret.')).not.toBeInTheDocument()}, 15_000)- it('seeds the first offered grant model when switching to a ChatGPT subscription', async () => {+ it('seeds the grant default model when a ChatGPT subscription is chosen', async () => {await renderWizard()await walkToModelStep({ agentName: 'codex-keep-model' })await waitFor(() => {@@ -878,13 +880,11 @@ describe('HostWizard — broker-backed Codex authoring', () => {screen.getByLabelText('Default model', { selector: '#llm-primary-model' })).toHaveTextContent(/\S/)})- fireEvent.click(screen.getByRole('radio', { name: /ChatGPT subscription/i }))- await waitFor(() => {- expect(- screen.getByLabelText('Default model', { selector: '#llm-primary-model' })- ).toHaveTextContent('gpt-5.1')- })- expect(screen.queryByText(/Use an existing secret/i)).not.toBeInTheDocument()+ await selectCodexSubscription()+ expect(+ screen.getByLabelText('Default model', { selector: '#llm-primary-model' })+ ).toHaveTextContent('gpt-5.1')+ expect(screen.getByText(/Use an existing secret/i)).toBeInTheDocument()}, 15_000)it('requires exact credential slots when a static fallback joins a Codex primary', async () => {@@ -897,13 +897,11 @@ describe('HostWizard — broker-backed Codex authoring', () => {target: { value: 'openai' },})await waitFor(() => {- expect(screen.getByText(/Use an existing secret/i)).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /Select secret/i })).toBeInTheDocument()})expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()- fireEvent.click(screen.getByLabelText(/Use an existing Secret/i))fireEvent.click(screen.getByRole('button', { name: /Select secret/i }))fireEvent.click(screen.getByRole('option', { name: /secret-a/i }))- fireEvent.click(screen.getByRole('button', { name: 'Assign test grant' }))await waitFor(() => {expect(screen.getByRole('button', { name: 'Next' })).not.toBeDisabled()})diff --git a/control-ui/components/__tests__/LlmProviderConfig.test.tsx b/control-ui/components/__tests__/LlmProviderConfig.test.tsxindex 6e060e0b7..9fcc3690f 100644--- a/control-ui/components/__tests__/LlmProviderConfig.test.tsx+++ b/control-ui/components/__tests__/LlmProviderConfig.test.tsx@@ -21,7 +21,6 @@ function Harness({withCredentials = true,existingKeys,replacePrimaryModelWithAllowedModels = false,- subscriptionCredentialEnabled = false,catalog = CATALOG,}: {initialProvider?: LlmProvider@@ -31,7 +30,6 @@ function Harness({withCredentials?: booleanexistingKeys?: string[]replacePrimaryModelWithAllowedModels?: boolean- subscriptionCredentialEnabled?: booleancatalog?: LlmModelCatalogEntry[]}) {const [provider, setProvider] = useState<LlmProvider>(initialProvider)@@ -62,7 +60,6 @@ function Harness({: undefined}replacePrimaryModelWithAllowedModels={replacePrimaryModelWithAllowedModels}- subscriptionCredentialEnabled={subscriptionCredentialEnabled}secretKeys={existingKeys}/>)@@ -178,60 +175,15 @@ describe('LlmProviderConfig (spec Topic 1b — domain projection + usable gate)'expect(screen.getByLabelText('Model', { selector: '#llm-primary-model' })).toBeInTheDocument()})- it('offers OpenAI plus a credential type instead of a Codex provider option', () => {- render(<Harness subscriptionCredentialEnabled />)+ it('offers one OpenAI provider and does not invent a ChatGPT radio', () => {+ render(<Harness />)fireEvent.click(screen.getByLabelText('Provider', { selector: '#llm-primary-provider' }))expect(screen.getByRole('option', { name: /^OpenAI$/i })).toBeInTheDocument()expect(screen.queryByRole('option', { name: /OpenAI Codex Subscription/i })).not.toBeInTheDocument()- fireEvent.click(screen.getByRole('radio', { name: /ChatGPT subscription/i }))- expect(screen.getByRole('radio', { name: /ChatGPT subscription/i })).toBeChecked()- expect(screen.getByText(/Connect and sync the grant first/i)).toBeInTheDocument()- })-- it('keeps the current model name when the ChatGPT grant catalog is empty', () => {- render(<Harness subscriptionCredentialEnabled initialModel="gpt-5.4-mini" />)- fireEvent.click(screen.getByRole('radio', { name: /ChatGPT subscription/i }))- expect(screen.getByLabelText('Model', { selector: '#llm-primary-model' })).toHaveTextContent(- 'gpt-5.4-mini'- )- })-- it('seeds the first offered grant model when the draft is outside the ChatGPT catalog', () => {- const catalog: LlmModelCatalogEntry[] = [- ...CATALOG,- { provider: 'codex-subscription', model: 'gpt-5.6-luna', enabled: true },- { provider: 'codex-subscription', model: 'gpt-5.6-sol', enabled: true },- ]- render(<Harness subscriptionCredentialEnabled initialModel="gpt-5.4-mini" catalog={catalog} />)- fireEvent.click(screen.getByRole('radio', { name: /ChatGPT subscription/i }))- expect(screen.getByLabelText('Model', { selector: '#llm-primary-model' })).toHaveTextContent(- 'gpt-5.6-luna'- )- })-- it('seeds the first ChatGPT subset model so Save is not model_not_offered', () => {- const catalog: LlmModelCatalogEntry[] = [- ...CATALOG,- { provider: 'codex-subscription', model: 'gpt-5.6-luna', enabled: true },- { provider: 'codex-subscription', model: 'gpt-5.6-sol', enabled: true },- ]- render(- <Harness- subscriptionCredentialEnabled- initialModel="gpt-5.4-mini"- catalog={catalog}- initialAllowed={[- { provider: 'codex-subscription', model: 'gpt-5.6-luna' },- { provider: 'codex-subscription', model: 'gpt-5.6-sol' },- ]}- />- )- fireEvent.click(screen.getByRole('radio', { name: /ChatGPT subscription/i }))- expect(screen.getByLabelText('Model', { selector: '#llm-primary-model' })).toHaveTextContent(- 'gpt-5.6-luna'- )+ expect(screen.queryByRole('radio', { name: /ChatGPT subscription/i })).not.toBeInTheDocument()+ expect(screen.queryByRole('radio', { name: /API key/i })).not.toBeInTheDocument()})})diff --git a/control-ui/components/__tests__/SecretsTable.test.tsx b/control-ui/components/__tests__/SecretsTable.test.tsxindex 5cb6ecce9..25cbd5e40 100644--- a/control-ui/components/__tests__/SecretsTable.test.tsx+++ b/control-ui/components/__tests__/SecretsTable.test.tsx@@ -506,7 +506,7 @@ describe('SecretsTable — recipe pending refs', () => {})describe('SecretsTable — LLM empty state', () => {- it('links ChatGPT subscriptions to the Subscription hub', async () => {+ it('keeps LLM nested under API-KEY without a sibling Subscription scope', async () => {rtlRender(<ToastProvider><SecretsTable@@ -520,9 +520,13 @@ describe('SecretsTable — LLM empty state', () => {/></ToastProvider>)- const link = await screen.findByRole('link', {- name: 'ChatGPT subscriptions are managed in the Subscription tab.',- })- expect(link).toHaveAttribute('href', '/secrets/subscription')+ expect(await screen.findByText('No LLM secrets found.')).toBeInTheDocument()+ expect(screen.getByRole('tab', { name: 'API-KEY' })).toHaveAttribute('aria-selected', 'true')+ expect(screen.getByRole('tab', { name: 'Subscriptions' })).toHaveAttribute(+ 'href',+ '/secrets/llm/subscriptions'+ )+ expect(screen.getByRole('tab', { name: 'LLM' })).toBeInTheDocument()+ expect(screen.queryByRole('tab', { name: /^Subscription$/ })).not.toBeInTheDocument()})})diff --git a/control-ui/lib/__tests__/llmCredentialSelect.test.ts b/control-ui/lib/__tests__/llmCredentialSelect.test.tsnew file mode 100644index 000000000..906ca3de5--- /dev/null+++ b/control-ui/lib/__tests__/llmCredentialSelect.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest'+import { credentialSelectValue, parseCredentialSelect } from '../llmCredentialSelect'++describe('llmCredentialSelect', () => {+ it('encodes a subscription without colliding with a secret of the same name', () => {+ expect(credentialSelectValue('Team Plus', 'codex-aaa')).toBe('sub:codex-aaa')+ expect(parseCredentialSelect('sub:codex-aaa')).toEqual({+ kind: 'subscription',+ connectionKey: 'codex-aaa',+ })+ expect(parseCredentialSelect('Team Plus')).toEqual({ kind: 'secret', name: 'Team Plus' })+ })++ it('treats unassigned and blank as empty', () => {+ expect(credentialSelectValue('', 'unassigned')).toBe('')+ expect(parseCredentialSelect('')).toEqual({ kind: 'empty' })+ expect(parseCredentialSelect('sub:unassigned')).toEqual({ kind: 'empty' })+ })+})diff --git a/control-ui/lib/__tests__/routes.test.ts b/control-ui/lib/__tests__/routes.test.tsindex 1336f5d9a..058e7c9c8 100644--- a/control-ui/lib/__tests__/routes.test.ts+++ b/control-ui/lib/__tests__/routes.test.ts@@ -32,7 +32,8 @@ describe('CONTROL_ROUTES', () => {expect('codexSubscription' in CONTROL_ROUTES.llmModels).toBe(false)})- it('exposes the Secrets Subscription hub path', () => {- expect(CONTROL_ROUTES.secrets.subscription).toBe('/secrets/subscription')+ it('nests ChatGPT subscriptions under Secrets LLM', () => {+ expect(CONTROL_ROUTES.secrets.llmSubscriptions).toBe('/secrets/llm/subscriptions')+ expect(CONTROL_ROUTES.secrets.subscription).toBe('/secrets/llm/subscriptions')})})diff --git a/control-ui/lib/codexSubscription.ts b/control-ui/lib/codexSubscription.tsindex f0d9d826c..e25f870af 100644--- a/control-ui/lib/codexSubscription.ts+++ b/control-ui/lib/codexSubscription.ts@@ -29,6 +29,7 @@ export type CodexSubscriptionConnectionView = {id?: stringconnectionKey: stringdisplayName?: string+ defaultModel?: string | nullstatus: CodexConnectionStatuscredentialRevision: numbercatalogRevision: number@@ -133,6 +134,7 @@ export function sanitizeCodexConnection(raw: unknown): CodexSubscriptionConnectireturn {connectionKey,displayName: pickString(raw.displayName) ?? undefined,+ defaultModel: pickString(raw.defaultModel),assignedHosts: Array.isArray(raw.assignedHosts)? raw.assignedHosts.filter(@@ -395,6 +397,40 @@ export async function revokeCodexSubscription(return sanitizeCodexConnection(await apiSend('POST', keyedPath(connectionKey, 'revoke')))}+export async function patchCodexSubscriptionConnection(+ connectionKey: string,+ patch: { displayName?: string; defaultModel?: string | null }+): Promise<CodexSubscriptionConnectionView> {+ return sanitizeCodexConnection(+ await apiSend(+ 'PATCH',+ `${CODEX_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}`,+ patch+ )+ )+}++export async function patchCodexCatalogModel(+ connectionKey: string,+ model: string,+ enabled: boolean+): Promise<Array<{ model: string; enabled: boolean; stale: boolean }>> {+ const raw = (await apiSend(+ 'PATCH',+ `${CODEX_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}/models/${encodeURIComponent(model)}`,+ { enabled }+ )) as { models?: Array<{ model?: string; enabled?: boolean; stale?: boolean }> }+ return Array.isArray(raw.models)+ ? raw.models+ .filter(row => typeof row.model === 'string' && row.model.trim())+ .map(row => ({+ model: String(row.model),+ enabled: row.enabled === true,+ stale: row.stale === true,+ }))+ : []+}+const CODEX_OAUTH_QUERY_PARAM = 'codex_oauth'export function readCodexOAuthQueryParam(diff --git a/control-ui/lib/llmCredentialSelect.ts b/control-ui/lib/llmCredentialSelect.tsnew file mode 100644index 000000000..19e19bae3--- /dev/null+++ b/control-ui/lib/llmCredentialSelect.ts@@ -0,0 +1,29 @@+import { CODEX_UNASSIGNED_CONNECTION_KEY } from './codexSubscription'++export const SUBSCRIPTION_CREDENTIAL_PREFIX = 'sub:'++export type ParsedCredentialSelect =+ | { kind: 'empty' }+ | { kind: 'secret'; name: string }+ | { kind: 'subscription'; connectionKey: string }++export function credentialSelectValue(secretRef: string, connectionRef: string): string {+ const key = connectionRef.trim()+ if (key && key !== CODEX_UNASSIGNED_CONNECTION_KEY) {+ return `${SUBSCRIPTION_CREDENTIAL_PREFIX}${key}`+ }+ return secretRef.trim()+}++export function parseCredentialSelect(value: string): ParsedCredentialSelect {+ const trimmed = value.trim()+ if (!trimmed) return { kind: 'empty' }+ if (trimmed.startsWith(SUBSCRIPTION_CREDENTIAL_PREFIX)) {+ const connectionKey = trimmed.slice(SUBSCRIPTION_CREDENTIAL_PREFIX.length).trim()+ if (!connectionKey || connectionKey === CODEX_UNASSIGNED_CONNECTION_KEY) {+ return { kind: 'empty' }+ }+ return { kind: 'subscription', connectionKey }+ }+ return { kind: 'secret', name: trimmed }+}diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 886a7d583..ecd63b31d 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.460",+ "version": "0.1.461","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.460",+ "version": "0.1.461","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 94a5d9dd2..e949ea249 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.460",+ "version": "0.1.461","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.tsindex 30615501b..0114e6dd4 100644--- a/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts+++ b/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts@@ -2,27 +2,33 @@* Codex subscription — Control UI admission and route guards.** Negative contract (direct terminal access is the behavior under test here):- * - Unauthenticated `/secrets/subscription` must show login, not the hub.- * - Unauthenticated `/agents/:name/model` must show login, not Connect.+ * - Unauthenticated `/secrets/llm/subscriptions` must show login, not the table.+ * - Unauthenticated `/agents/:name/model` must show login, not credentials.* - LLM Models is no longer the ChatGPT assignment owner.*/import { expect, test } from '@playwright/test'import { loginControlUiVisible } from '../helpers/visible-login'test.describe('Codex subscription admission', () => {- test('unauthenticated Secrets Subscription deep link is blocked by AuthGate', async ({+ test('unauthenticated nested Subscriptions deep link is blocked by AuthGate', async ({page,}) => {+ await page.goto('/secrets/llm/subscriptions')+ await expect(page.getByLabel('Username or email')).toBeVisible({ timeout: 20_000 })+ await expect(page.getByRole('button', { name: 'Add subscription' })).toHaveCount(0)+ await expect(page.getByRole('columnheader', { name: 'Name' })).toHaveCount(0)+ })++ test('unauthenticated legacy Subscription path is blocked by AuthGate', async ({ page }) => {await page.goto('/secrets/subscription')await expect(page.getByLabel('Username or email')).toBeVisible({ timeout: 20_000 })- await expect(page.getByTestId('codex-subscription-hub')).toHaveCount(0)- await expect(page.getByRole('button', { name: 'Revoke subscription' })).toHaveCount(0)+ await expect(page.getByRole('button', { name: 'Add subscription' })).toHaveCount(0)})test('unauthenticated agent model deep link is blocked by AuthGate', async ({ page }) => {await page.goto('/agents/e2e-codex-authoring/model')await expect(page.getByLabel('Username or email')).toBeVisible({ timeout: 20_000 })- await expect(page.getByTestId('codex-agent-assignment')).toHaveCount(0)+ await expect(page.getByLabel('Credential', { exact: true })).toHaveCount(0)await expect(page.getByRole('button', { name: 'Sign in with ChatGPT' })).toHaveCount(0)})diff --git a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.tsindex 01e4018d7..ec97e87b1 100644--- a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts+++ b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts@@ -1,25 +1,8 @@/**- * Codex subscription — assign/unbind on the agent model tab; create, multi-assign,- * and revoke from Secrets → Subscription.+ * Codex subscription — Secrets LLM nested tabs + one agent Credential select.*- * E2E contract- * ------------- * Journey | Entry | Actions | Transitions | Business signal- * API key → ChatGPT | `/` + visible login + Agents | Open agent → Models → ChatGPT → Save | `/agents/:name/model` | PUT host ≠ 422, spec.model.name non-empty- * Assign from agent | same | Create grant in UI → Save | stay on model tab | PUT 200, connectionRef persisted- * Device login | same | Sign in with ChatGPT | stay on model, no oauth URL | device start 200 + userCode in UI- * Sync catalog | same | Select grant → Sync | stay on model | disabled until connected; POST sync when connected- * Reuse grant | Agents list with 2 seeded | Create grant on A → pick same grant on B | second agent model tab | picker value = shared key- * Unbind | agent model | Create → Save → Remove → Save | stay on model | PUT 200, connectionRef=unassigned, grant not revoked- * Hub table + assign | `/` → Secrets → Subscription | Create grant → pick 2 agents → Add 2 → Revoke| `/secrets/subscription` + table | 2 bind 200s, chips, revoke status- * LLM → Subscription | Secrets LLM | Empty-state link or Subscription tab | `/secrets/subscription` | hub visible- *- * Forbidden shortcuts: happy-path `goto` of `/secrets/subscription` or an agent- * model tab; `test.skip`; silent `return` after an empty model; mutating storage- * to skip login. API host create is a named precondition only.- *- * ChatGPT OAuth is the only mocked/external boundary (live device code is- * asserted, not completed).+ * Journeys J1–J10 from the redesign plan. Auth: `/` + loginControlUiVisible.+ * Terminal `goto` only in J2. No test.skip. No silent return.*/import { type Page, expect, test } from '@playwright/test'import { controlApi } from '../helpers/api-client'@@ -27,16 +10,15 @@ import { loginControlUiVisible } from '../helpers/visible-login'import {AgentListPage,AgentModelPage,- CodexSubscriptionHubPage,ControlUiShell,+ SecretsLlmSubscriptionsPage,} from '../pages/codex-subscription'type CodexConnection = {connectionKey: stringdisplayName?: string+ defaultModel?: string | nullstatus: string- catalogRevision: number- assignedHosts?: Array<{ name: string }>}async function loginFromHome(page: Page) {@@ -45,10 +27,6 @@ async function loginFromHome(page: Page) {await expect(page.getByLabel('Main navigation')).toBeVisible()}-/**- * Named API precondition — not the behavior under test. Seeds ChatGPT-capable- * hosts so the Agents table and hub picker have rows. Fails loud if create fails.- */async function seedCodexAgents(page: Page, minimum: number): Promise<void> {const listed = await controlApi.getHosts()const items = Array.isArray(listed.items) ? listed.items : []@@ -86,93 +64,56 @@ async function listConnections(): Promise<CodexConnection[]> {}test.describe('Codex subscription connection', () => {- test('switching from API key to ChatGPT keeps a model name and never 422s', async ({ page }) => {+ test('J1 nested LLM tabs open Subscriptions without a sibling Subscription scope', async ({+ page,+ }) => {const shell = new ControlUiShell(page)- const agents = new AgentListPage(page)- const model = new AgentModelPage(page)-- await test.step('enter from home and open the first agent model editor', async () => {- await loginFromHome(page)- await shell.openAgents()- await seedCodexAgents(page, 1)- await agents.openNth(0)- await model.openEditor()- })+ const hub = new SecretsLlmSubscriptionsPage(page)+ await loginFromHome(page)+ await shell.openSecretsLlmSubscriptions()+ await hub.expectTable()+ await expect(page.getByRole('tab', { name: 'LLM' })).toBeVisible()+ await expect(page.getByRole('tab', { name: 'Connector' })).toBeVisible()+ await expect(page.getByRole('tab', { name: 'Recipe' })).toBeVisible()+ })- await test.step('switch OpenAI API key → ChatGPT subscription', async () => {- await model.chooseChatGPTSubscription()- await model.expectNamedModel()- })+ test('J2 authenticated deep link and legacy redirect; unauth is AuthGate', async ({ page }) => {+ await page.goto('/secrets/llm/subscriptions')+ await expect(page.getByLabel('Username or email')).toBeVisible({ timeout: 20_000 })+ await expect(page.getByRole('button', { name: 'Add subscription' })).toHaveCount(0)- await test.step('Save persists a non-empty spec.model.name', async () => {- const save = model.saveButton()- await expect(save).toBeEnabled()- const put = page.waitForResponse(- response =>- /\/api\/v1\/admin\/hosts\/[^/]+$/.test(new URL(response.url()).pathname) &&- response.request().method() === 'PUT'- )- await save.click()- const response = await put- expect(- response.status(),- 'API-key → ChatGPT save must not 422 empty model.name or model_not_offered'- ).not.toBe(422)- expect(response.ok(), `save must succeed, got ${response.status()}`).toBe(true)- const body = (await response.json()) as { spec?: { model?: { name?: string } } }- expect(body.spec?.model?.name).toEqual(expect.stringMatching(/\S/))- })+ await page.goto('/')+ await loginControlUiVisible(page)+ await page.goto('/secrets/subscription')+ await expect(page).toHaveURL(/\/secrets\/llm\/subscriptions$/)+ await expect(page.getByRole('tab', { name: 'Subscriptions', selected: true })).toBeVisible()})- test('operator assigns a subscription from the agent model tab', async ({ page }) => {+ test('J3 Add subscription POSTs 201 and shows the displayName row', async ({ page }) => {const shell = new ControlUiShell(page)- const agents = new AgentListPage(page)- const model = new AgentModelPage(page)- const displayName = `e2e-assign-${Date.now().toString(36)}`-+ const hub = new SecretsLlmSubscriptionsPage(page)+ const displayName = `e2e-add-${Date.now().toString(36)}`await loginFromHome(page)- await shell.openAgents()- await seedCodexAgents(page, 1)- const agentName = await agents.openNth(0)- await model.openEditor()- await model.chooseChatGPTSubscription()-- const grantKey = await test.step('create the grant through the agent UI', () =>- model.createGrant(displayName))- await model.expectNamedModel()-- const body = await test.step('Save assigns the grant without a 422', () =>- model.saveHost(agentName))- expect(body.spec?.model?.provider).toBe('codex-subscription')- expect(body.spec?.model?.name).toEqual(expect.stringMatching(/\S/))- expect(body.spec?.model?.connectionRef).toBe(grantKey)-- const host = (await controlApi.getHost(agentName)) as {- spec?: { model?: { connectionRef?: string; name?: string } }- }- expect(host.spec?.model?.connectionRef).toBe(grantKey)- expect(host.spec?.model?.name).toEqual(expect.stringMatching(/\S/))+ await shell.openSecretsLlmSubscriptions()+ const key = await hub.createGrant(displayName)+ const listed = await listConnections()+ expect(listed.find(row => row.connectionKey === key)?.displayName).toBe(displayName)})- test('Sign in with ChatGPT starts device login from the agent page', async ({ page }) => {+ test('J4 pencil Sign in and Sync live on Secrets, never on the agent', async ({ page }) => {const shell = new ControlUiShell(page)+ const hub = new SecretsLlmSubscriptionsPage(page)const agents = new AgentListPage(page)const model = new AgentModelPage(page)+ const displayName = `e2e-signin-${Date.now().toString(36)}`await loginFromHome(page)- await shell.openAgents()- await seedCodexAgents(page, 1)- await agents.openNth(0)- await model.openEditor()- await model.chooseChatGPTSubscription()- await expect(model.subscriptionPicker()).toBeVisible()+ await shell.openSecretsLlmSubscriptions()+ const grantKey = await hub.createGrant(displayName)+ await hub.openGrant(displayName)const signIn = page.getByRole('button', { name: 'Sign in with ChatGPT' })- if ((await signIn.count()) === 0 || !(await signIn.isEnabled())) {- await model.createGrant(`e2e-device-${Date.now().toString(36)}`)- }await expect(signIn).toBeEnabled()-const deviceStart = page.waitForResponse(response =>/\/api\/v1\/admin\/llm\/providers\/codex-subscription\/(connections\/[^/]+\/)?device\/start$/.test(@@ -180,225 +121,255 @@ test.describe('Codex subscription connection', () => {) && response.request().method() === 'POST')await signIn.click()- const response = await deviceStart- expect(response.ok(), `device start must succeed, got ${response.status()}`).toBe(true)- const body = (await response.json()) as { userCode?: string; verificationUri?: string }- expect(body.userCode).toEqual(expect.any(String))- expect(body.verificationUri).toMatch(/^https:\/\/auth\.openai\.com\/codex\/device/)- await expect(page.getByTestId('codex-device-code')).toContainText(String(body.userCode))- await expect(page).toHaveURL(/\/(?:hosts|agents)\/[^/]+\/model/)- await expect(page).not.toHaveURL(/oauth\/authorize/)- })-- test('Sync catalog is disabled until that grant is connected', async ({ page }) => {- const shell = new ControlUiShell(page)- const agents = new AgentListPage(page)- const model = new AgentModelPage(page)+ const deviceRes = await deviceStart+ expect(deviceRes.ok(), `device start must succeed, got ${deviceRes.status()}`).toBe(true)+ const deviceBody = (await deviceRes.json()) as { userCode?: string }+ expect(deviceBody.userCode).toEqual(expect.any(String))+ await expect(page.getByTestId('codex-device-code')).toContainText(String(deviceBody.userCode))++ const grant = (await listConnections()).find(row => row.connectionKey === grantKey)+ expect(grant, 'created grant must be listed').toBeTruthy()+ const sync = page.getByRole('button', { name: 'Sync catalog' })+ if (grant?.status === 'connected') {+ const syncResPromise = page.waitForResponse(+ response =>+ new RegExp(+ `/api/v1/admin/llm/providers/codex-subscription/connections/${grantKey}/catalog/sync$`+ ).test(new URL(response.url()).pathname) && response.request().method() === 'POST'+ )+ await sync.click()+ const syncRes = await syncResPromise+ expect(syncRes.ok(), `catalog sync must succeed, got ${syncRes.status()}`).toBe(true)+ } else {+ await expect(sync, 'Sync stays disabled until the grant is connected').toBeDisabled()+ }- await loginFromHome(page)+ await page.getByRole('button', { name: 'Cancel' }).click()await shell.openAgents()await seedCodexAgents(page, 1)await agents.openNth(0)await model.openEditor()- await model.chooseChatGPTSubscription()+ await model.expectOneCredentialSelect()+ })- const connections = await listConnections()- const picker = model.subscriptionPicker()- const disconnected = connections.find(- row => row.status !== 'connected' && row.status !== 'revoked'+ test('J5 enable and default PATCH, then reopen matches GET models', async ({ page }) => {+ const shell = new ControlUiShell(page)+ const hub = new SecretsLlmSubscriptionsPage(page)+ await loginFromHome(page)+ await shell.openSecretsLlmSubscriptions()+ const connected = (await listConnections()).find(row => row.status === 'connected')+ expect(connected, 'J5 named precondition: a connected grant with a synced catalog').toBeTruthy()+ const grantKey = connected!.connectionKey+ const displayName = connected!.displayName || grantKey++ await hub.openGrant(displayName)+ 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')- const connected = connections.find(row => row.status === 'connected')-- if (disconnected) {- await picker.selectOption(disconnected.connectionKey)- await expect(page.getByRole('button', { name: 'Sync catalog' })).toBeDisabled()- }+ await modelsGet+ const firstToggle = page.locator('dialog input[type="checkbox"]').first()+ await expect(firstToggle, 'grant modal must list catalog models').toBeVisible()+ const modelName = (+ (await firstToggle.evaluate(node => node.closest('label')?.textContent)) ?? ''+ )+ .replace('(stale)', '')+ .trim()+ expect(modelName).toMatch(/\S/)- if (!connected) {- await expect(- page.getByRole('button', { name: 'Sync catalog' }),- 'without a connected grant Sync must stay disabled'- ).toBeDisabled()- return- }+ const patchModel = page.waitForResponse(+ response =>+ new RegExp(+ `/api/v1/admin/llm/providers/codex-subscription/connections/${grantKey}/models/`+ ).test(new URL(response.url()).pathname) && response.request().method() === 'PATCH'+ )+ const wasEnabled = await firstToggle.isChecked()+ await firstToggle.click()+ const patchRes = await patchModel+ expect(patchRes.ok(), `model PATCH must succeed, got ${patchRes.status()}`).toBe(true)++ await page.getByLabel('Default model').click()+ const defaultOption = page.getByRole('option').first()+ await expect(defaultOption).toBeVisible()+ const defaultName = ((await defaultOption.textContent()) ?? '').trim()+ const patchDefault = page.waitForResponse(+ response =>+ new RegExp(`/api/v1/admin/llm/providers/codex-subscription/connections/${grantKey}$`).test(+ new URL(response.url()).pathname+ ) && response.request().method() === 'PATCH'+ )+ await defaultOption.click()+ await page.getByRole('button', { name: 'Update subscription' }).click()+ const defaultRes = await patchDefault+ expect(defaultRes.ok(), `defaultModel PATCH must succeed, got ${defaultRes.status()}`).toBe(+ true+ )- await picker.selectOption(connected.connectionKey)- const sync = page.waitForResponse(+ await hub.openGrant(displayName)+ const reopened = page.waitForResponse(response =>new RegExp(- `/api/v1/admin/llm/providers/codex-subscription/connections/${connected.connectionKey}/catalog/sync$`- ).test(new URL(response.url()).pathname) && response.request().method() === 'POST'+ `/api/v1/admin/llm/providers/codex-subscription/connections/${grantKey}/models$`+ ).test(new URL(response.url()).pathname) && response.request().method() === 'GET')- await page.getByRole('button', { name: 'Sync catalog' }).click()- const response = await sync- expect(response.ok(), `catalog sync must succeed, got ${response.status()}`).toBe(true)- const body = (await response.json()) as {- added?: number- refreshed?: number- connection?: { catalogRevision?: number; connectionKey?: string }+ const modelsRes = await reopened+ const modelsBody = (await modelsRes.json()) as {+ models?: Array<{ model?: string; enabled?: boolean }>+ }+ const toggled = modelsBody.models?.find(row => row.model === modelName)+ expect(toggled?.enabled).toBe(!wasEnabled)+ if (defaultName) {+ await expect(page.getByLabel('Default model')).toContainText(defaultName)}- expect(body.connection?.connectionKey).toBe(connected.connectionKey)- expect(typeof body.connection?.catalogRevision).toBe('number')- expect((body.added ?? 0) + (body.refreshed ?? 0)).toBeGreaterThanOrEqual(0)})- test('operator reuses the same grant on a second agent', async ({ page }) => {+ test('J6 one Credential select saves subscription or secret without a ChatGPT radio', async ({+ page,+ }) => {const shell = new ControlUiShell(page)+ const hub = new SecretsLlmSubscriptionsPage(page)const agents = new AgentListPage(page)const model = new AgentModelPage(page)- const displayName = `e2e-shared-${Date.now().toString(36)}`+ const displayName = `e2e-cred-${Date.now().toString(36)}`await loginFromHome(page)+ await shell.openSecretsLlmSubscriptions()+ const grantKey = await hub.createGrant(displayName)await shell.openAgents()- await seedCodexAgents(page, 2)- await agents.openNth(0)+ await seedCodexAgents(page, 1)+ const agentName = await agents.openNth(0)await model.openEditor()- await model.chooseChatGPTSubscription()- const sharedKey = await model.createGrant(displayName)-- await test.step('open a second agent through the list', async () => {- await shell.openAgents()- expect(- await agents.rows().count(),- 'reuse requires two seeded agents'- ).toBeGreaterThanOrEqual(2)- await agents.openNth(1)- await model.openEditor()- await model.chooseChatGPTSubscription()- })-- await model.subscriptionPicker().selectOption(sharedKey)- await expect(model.subscriptionPicker()).toHaveValue(sharedKey)- await expect(page.getByRole('option', { name: displayName })).toHaveCount(1)+ await model.expectOneCredentialSelect()+ await expect(model.credentialSelect().locator('optgroup[label="Subscriptions"]')).toBeVisible()+ const secretName = (+ await page.locator('#host-secret optgroup[label="API keys"] option').allTextContents()+ )+ .map(text => text.replace(' (custom)', '').trim())+ .find(Boolean)+ await model.chooseSubscription(displayName)+ const saved = await model.saveHost(agentName)+ expect(saved.spec?.model?.provider).toBe('codex-subscription')+ expect(saved.spec?.model?.connectionRef).toBe(grantKey)+ expect(saved.spec?.model?.name).toEqual(expect.stringMatching(/\S/))+ expect(saved.spec?.secretRef).toBeUndefined()+ await expect(page.getByLabel('Credential')).toHaveText(displayName)++ expect(secretName, 'J6 named precondition: at least one API key secret').toMatch(/\S/)+ await page.getByRole('button', { name: 'Edit' }).click()+ await model.chooseSecret(secretName!)+ const secretSaved = await model.saveHost(agentName)+ expect(secretSaved.spec?.secretRef).toBe(secretName)+ expect(secretSaved.spec?.model?.connectionRef).toBeUndefined()+ await expect(page.getByLabel('Credential')).toHaveText(secretName!)})- test('agent models can unbind this host and never expose grant Revoke', async ({ page }) => {+ test('J7 the same displayName appears once on a second agent', async ({ page }) => {const shell = new ControlUiShell(page)+ const hub = new SecretsLlmSubscriptionsPage(page)const agents = new AgentListPage(page)const model = new AgentModelPage(page)- const displayName = `e2e-unbind-${Date.now().toString(36)}`+ const displayName = `e2e-reuse-${Date.now().toString(36)}`await loginFromHome(page)+ await shell.openSecretsLlmSubscriptions()+ await hub.createGrant(displayName)await shell.openAgents()- await seedCodexAgents(page, 1)- const firstName = await agents.openNth(0)+ await seedCodexAgents(page, 2)+ await agents.openNth(0)await model.openEditor()- await model.chooseChatGPTSubscription()- const grantKey = await model.createGrant(displayName)- await model.expectNamedModel()- await model.saveHost(firstName)-- await expect(page.getByRole('button', { name: 'Revoke', exact: true })).toHaveCount(0)- await expect(page.getByRole('link', { name: 'Manage subscription' })).toBeVisible()-- await page.getByRole('button', { name: 'Remove from this agent' }).click()- await expect(page.getByRole('alertdialog')).toBeVisible()- await page.getByRole('alertdialog').getByRole('button', { name: 'Remove agent' }).click()- await expect(page.getByTestId('codex-connection-status')).toHaveText(- /No subscription assigned/i+ await model.chooseSubscription(displayName)+ await shell.openAgents()+ await agents.openNth(1)+ await model.openEditor()+ await expect(model.credentialSelect().locator(`option:text-is("${displayName}")`)).toHaveCount(+ 1)- const saved = await model.saveHost(firstName)- expect(saved.spec?.model?.connectionRef).toBe('unassigned')- await expect(page).toHaveURL(new RegExp(`/((?:hosts|agents))/${firstName}/model`))-- const host = (await controlApi.getHost(firstName)) as {- spec?: { model?: { connectionRef?: string } }- }- expect(host.spec?.model?.connectionRef).toBe('unassigned')- const after = await listConnections()- expect(after.find(row => row.connectionKey === grantKey)?.status).not.toBe('revoked')})- test('Secrets Subscription hub creates, assigns two agents, and is the only revoke path', async ({+ test('J8 clearing Credential saves unassigned and does not revoke the grant', async ({page,}) => {const shell = new ControlUiShell(page)- const hub = new CodexSubscriptionHubPage(page)- const displayName = `e2e-hub-${Date.now().toString(36)}`-- await test.step('reach the hub through Secrets → Subscription', async () => {- await loginFromHome(page)- await shell.openAgents()- await seedCodexAgents(page, 2)- await shell.openSecretsSubscription()- await hub.expectTable()- })-- const grantKey = await test.step('create a grant from the hub CTA', () =>- hub.createGrant(displayName))-- const bound = await test.step('assign two agents in one hub action', () =>- hub.assignFirstAgents(grantKey, 2))-- await test.step('remove one agent from the hub chips without revoking', async () => {- await hub.removeAgentFromGrant(grantKey, bound[0])- const afterUnbind = (await controlApi.getHost(bound[0])) as {- spec?: { model?: { connectionRef?: string } }- }- expect(afterUnbind.spec?.model?.connectionRef).toBe('unassigned')- })+ const hub = new SecretsLlmSubscriptionsPage(page)+ const agents = new AgentListPage(page)+ const model = new AgentModelPage(page)+ const displayName = `e2e-clear-${Date.now().toString(36)}`- const remaining = bound.slice(1)- const grantRow = hub.grantRow(grantKey)- await expect(grantRow.getByTestId('codex-hub-agent-chips')).toBeVisible()- await expect(grantRow.getByRole('link', { name: bound[0] })).toHaveCount(0)- for (const hostName of remaining) {- await expect(grantRow.getByRole('link', { name: hostName })).toBeVisible()- const host = (await controlApi.getHost(hostName)) as {- spec?: { model?: { connectionRef?: string } }- }- expect(host.spec?.model?.connectionRef).toBe(grantKey)- }+ await loginFromHome(page)+ await shell.openSecretsLlmSubscriptions()+ const grantKey = await hub.createGrant(displayName)+ await shell.openAgents()+ await seedCodexAgents(page, 1)+ const agentName = await agents.openNth(0)+ await model.openEditor()+ await model.chooseSubscription(displayName)+ await model.saveHost(agentName)+ await page.getByRole('button', { name: 'Edit' }).click()+ await model.clearCredential()+ const saved = await model.saveHost(agentName)+ expect(saved.spec?.model?.connectionRef ?? 'unassigned').toBe('unassigned')+ expect(saved.spec?.secretRef).toBeUndefined()+ const after = await listConnections()+ expect(after.find(row => row.connectionKey === grantKey)?.status).not.toBe('revoked')+ })- await test.step('revoke only from the hub danger action', async () => {- const revoke = page.waitForResponse(- response =>- new RegExp(- `/api/v1/admin/llm/providers/codex-subscription/connections/${grantKey}/revoke$`- ).test(new URL(response.url()).pathname) && response.request().method() === 'POST'- )- await grantRow.getByRole('button', { name: 'Revoke subscription' }).click()- await expect(page.getByRole('alertdialog')).toBeVisible()- await page- .getByRole('alertdialog')- .getByRole('button', { name: 'Revoke subscription' })- .click()- const revokeRes = await revoke- expect(revokeRes.ok(), `revoke must succeed, got ${revokeRes.status()}`).toBe(true)- const revokeBody = (await revokeRes.json()) as { status?: string; connectionKey?: string }- expect(revokeBody.status).toBe('revoked')- expect(revokeBody.connectionKey).toBe(grantKey)- })+ test('J9 revoke is only the Secrets IconX and does not rewrite hosts', async ({ page }) => {+ const shell = new ControlUiShell(page)+ const hub = new SecretsLlmSubscriptionsPage(page)+ const agents = new AgentListPage(page)+ const model = new AgentModelPage(page)+ const displayName = `e2e-revoke-${Date.now().toString(36)}`- const afterRemoved = (await controlApi.getHost(bound[0])) as {+ await loginFromHome(page)+ await shell.openSecretsLlmSubscriptions()+ const grantKey = await hub.createGrant(displayName)+ await shell.openAgents()+ await seedCodexAgents(page, 1)+ const agentName = await agents.openNth(0)+ await model.openEditor()+ await model.chooseSubscription(displayName)+ await model.saveHost(agentName)+ const before = (await controlApi.getHost(agentName)) as {spec?: { model?: { connectionRef?: string } }}- expect(afterRemoved.spec?.model?.connectionRef).toBe('unassigned')- for (const hostName of remaining) {- const afterHost = (await controlApi.getHost(hostName)) as {- spec?: { model?: { connectionRef?: string } }- }- expect(afterHost.spec?.model?.connectionRef).toBe(grantKey)+ await shell.openSecretsLlmSubscriptions()+ await hub.revokeGrant(displayName, grantKey)+ const after = (await controlApi.getHost(agentName)) as {+ spec?: { model?: { connectionRef?: string } }}+ expect(after.spec?.model?.connectionRef).toBe(before.spec?.model?.connectionRef)+ await expect(page.getByRole('cell', { name: displayName, exact: true })).toHaveCount(0)})- test('LLM secrets empty state or tab reaches the Subscription hub', async ({ page }) => {+ test('J10 API-KEY does not PATCH grants; Subscriptions does not PUT secrets', async ({+ page,+ }) => {const shell = new ControlUiShell(page)+ const hub = new SecretsLlmSubscriptionsPage(page)+ const displayName = `e2e-iso-${Date.now().toString(36)}`await loginFromHome(page)await shell.openSecretsLlm()- await expect(page).toHaveURL(/\/secrets\/llm$/)-- const emptyLink = page.getByRole('link', {- name: 'ChatGPT subscriptions are managed in the Subscription tab.',+ const grantPatches: string[] = []+ const secretPuts: string[] = []+ page.on('request', request => {+ const url = new URL(request.url())+ if (+ request.method() === 'PATCH' &&+ /\/codex-subscription\/connections\//.test(url.pathname)+ ) {+ grantPatches.push(url.pathname)+ }+ if (request.method() === 'PUT' && /\/api\/v1\/admin\/secrets$/.test(url.pathname)) {+ secretPuts.push(url.pathname)+ }})- const tab = page.getByRole('tab', { name: 'Subscription' })- await expect(tab).toBeVisible()- if ((await emptyLink.count()) > 0) {- await emptyLink.click()- } else {- await tab.click()- }- await expect(page).toHaveURL(/\/secrets\/subscription$/)- await expect(page.getByTestId('codex-subscription-hub')).toBeVisible()+ await page.getByRole('tab', { name: 'API-KEY' }).click()+ await expect(page).toHaveURL(/\/secrets\/llm$/)+ expect(grantPatches, 'API-KEY must not PATCH grant metadata').toEqual([])+ await shell.openSecretsLlmSubscriptions()+ await hub.createGrant(displayName)+ expect(secretPuts, 'Subscriptions must not PUT LLM secrets').toEqual([])})})diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.jsonindex cab916900..99e9584e0 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.32",+ "version": "0.1.33","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-playwright-tests",- "version": "0.1.32",+ "version": "0.1.33","devDependencies": {"@playwright/test": "^1.50.0","@types/node": "^22.0.0"diff --git a/tests/e2e/playwright/package.json b/tests/e2e/playwright/package.jsonindex 9c5f94e36..1fac92c88 100644--- a/tests/e2e/playwright/package.json+++ b/tests/e2e/playwright/package.json@@ -1,6 +1,6 @@{"name": "clerum-playwright-tests",- "version": "0.1.32",+ "version": "0.1.33","private": true,"description": "Playwright E2E tests for Control UI and Desktop App","scripts": {diff --git a/tests/e2e/playwright/pages/codex-subscription.ts b/tests/e2e/playwright/pages/codex-subscription.tsindex 4ff82a06f..6806b9839 100644--- a/tests/e2e/playwright/pages/codex-subscription.ts+++ b/tests/e2e/playwright/pages/codex-subscription.ts@@ -1,5 +1,5 @@/**- * Page objects for Codex subscription Control UI journeys.+ * Page objects for Secrets LLM subscriptions and the agent Credential select.** Guardian: helpers only click/assert user-visible controls. API seeding lives* in the spec and is named as a precondition, never as the behavior under test.@@ -20,11 +20,13 @@ export class ControlUiShell {await expect(this.page).toHaveURL(/\/secrets\/(llm)?$/)}- async openSecretsSubscription() {+ async openSecretsLlmSubscriptions() {await this.openSecretsLlm()- await this.page.getByRole('tab', { name: 'Subscription' }).click()- await expect(this.page).toHaveURL(/\/secrets\/subscription$/)- await expect(this.page.getByTestId('codex-subscription-hub')).toBeVisible()+ await this.page.getByRole('tab', { name: 'Subscriptions' }).click()+ await expect(this.page).toHaveURL(/\/secrets\/llm\/subscriptions$/)+ await expect(+ this.page.getByRole('tab', { name: 'Subscriptions', selected: true })+ ).toBeVisible()}}@@ -57,12 +59,8 @@ export class AgentListPage {export class AgentModelPage {constructor(readonly page: Page) {}- subscriptionPicker(): Locator {- return this.page.locator('#codex-subscription')- }-- modelSelect(): Locator {- return this.page.getByLabel(/^Model$/i)+ credentialSelect(): Locator {+ return this.page.getByLabel('Credential', { exact: true })}saveButton(): Locator {@@ -79,50 +77,27 @@ export class AgentModelPage {if ((await edit.count()) > 0) {await edit.click()}- await expect(this.page.getByLabel('Provider')).toBeVisible()+ await expect(this.credentialSelect()).toBeVisible()}- async chooseChatGPTSubscription() {- await this.page.getByLabel('Provider').click()- await this.page.getByRole('option', { name: 'OpenAI', exact: true }).click()- await expect(this.page.getByRole('option', { name: 'OpenAI Codex Subscription' })).toHaveCount(- 0- )- await this.page.getByRole('radio', { name: 'ChatGPT subscription' }).check()- await expect(this.page.getByTestId('codex-agent-assignment')).toBeVisible()- await expect(this.page.getByLabel(/OpenAI API key/i)).toHaveCount(0)+ async expectOneCredentialSelect() {+ await expect(this.credentialSelect()).toHaveCount(1)+ await expect(this.page.getByRole('radio', { name: /ChatGPT subscription/i })).toHaveCount(0)+ await expect(this.page.getByRole('button', { name: 'Sign in with ChatGPT' })).toHaveCount(0)+ await expect(this.page.getByRole('button', { name: 'Sync catalog' })).toHaveCount(0)+ await expect(this.page.getByRole('button', { name: 'New subscription' })).toHaveCount(0)}- async expectNamedModel(): Promise<string> {- const select = this.modelSelect()- await expect(select).toBeVisible()- const value = ((await select.textContent()) ?? '').trim()- expect(- value,- 'ChatGPT switch must keep or seed spec.model.name — empty name is the 422 bug'- ).toMatch(/\S/)- expect(value, 'placeholder is not a saved model name').not.toMatch(- /select model|no enabled models/i- )- return value+ async chooseSubscription(displayName: string) {+ await this.credentialSelect().selectOption({ label: displayName })}- async createGrant(displayName: string): Promise<string> {- await this.page.getByRole('button', { name: 'New subscription' }).click()- await this.page.getByLabel('New subscription name').fill(displayName)- const created = this.page.waitForResponse(- response =>- /\/api\/v1\/admin\/llm\/providers\/codex-subscription\/connections$/.test(- new URL(response.url()).pathname- ) && response.request().method() === 'POST'- )- await this.page.getByRole('button', { name: 'Create', exact: true }).click()- const response = await created- expect(response.ok(), `create grant must succeed, got ${response.status()}`).toBe(true)- const body = (await response.json()) as { connectionKey?: string }- expect(body.connectionKey).toEqual(expect.any(String))- await expect(this.subscriptionPicker()).toHaveValue(String(body.connectionKey))- return String(body.connectionKey)+ async chooseSecret(secretName: string) {+ await this.credentialSelect().selectOption(secretName)+ }++ async clearCredential() {+ await this.credentialSelect().selectOption('')}async saveHost(agentName: string) {@@ -140,34 +115,33 @@ export class AgentModelPage {).not.toBe(422)expect(response.ok(), `assign save must succeed, got ${response.status()}`).toBe(true)return (await response.json()) as {- spec?: { model?: { provider?: string; name?: string; connectionRef?: string } }+ spec?: {+ secretRef?: string+ model?: { provider?: string; name?: string; connectionRef?: string }+ }}}}-export class CodexSubscriptionHubPage {+export class SecretsLlmSubscriptionsPage {constructor(readonly page: Page) {}- table(): Locator {- return this.page.getByTestId('codex-hub-table')- }-- grantRow(connectionKey: string): Locator {- return this.page.getByTestId(`codex-hub-grant-${connectionKey}`)- }-async expectTable() {- await expect(this.table()).toBeVisible()await expect(this.page.getByRole('columnheader', { name: 'Name' })).toBeVisible()await expect(this.page.getByRole('columnheader', { name: 'Status' })).toBeVisible()- await expect(this.page.getByRole('columnheader', { name: 'Agents' })).toBeVisible()- await expect(this.page.getByRole('heading', { name: 'Available' })).toHaveCount(0)- await expect(this.page.getByRole('heading', { name: 'Assigned' })).toHaveCount(0)+ await expect(this.page.getByRole('columnheader', { name: 'Agents' })).toHaveCount(0)+ await expect(this.page.getByRole('tab', { name: /^Subscription$/ })).toHaveCount(0)+ await expect(this.page.getByRole('tab', { name: 'API-KEY' })).toBeVisible()+ await expect(this.page.getByRole('tab', { name: 'Subscriptions' })).toBeVisible()+ }++ grantRow(displayName: string): Locator {+ return this.page.getByRole('row', { name: new RegExp(displayName) })}async createGrant(displayName: string): Promise<string> {await this.page.getByRole('button', { name: 'Add subscription' }).click()- await this.page.getByLabel('New subscription name').fill(displayName)+ await this.page.getByLabel('Name', { exact: true }).fill(displayName)const created = this.page.waitForResponse(response =>/\/api\/v1\/admin\/llm\/providers\/codex-subscription\/connections$/.test(@@ -176,86 +150,36 @@ export class CodexSubscriptionHubPage {)await this.page.getByRole('button', { name: 'Create', exact: true }).click()const response = await created- expect(response.ok(), `hub create must succeed, got ${response.status()}`).toBe(true)+ expect(response.ok(), `create grant must succeed, got ${response.status()}`).toBe(true)const body = (await response.json()) as { connectionKey?: string }expect(body.connectionKey).toEqual(expect.any(String))- await expect(this.page.getByText(displayName)).toBeVisible()+ await expect(this.page.getByRole('cell', { name: displayName, exact: true })).toBeVisible()return String(body.connectionKey)}- async assignFirstAgents(connectionKey: string, count: number): Promise<string[]> {- const row = this.grantRow(connectionKey)- await expect(row.getByLabel('Add agents to this subscription')).toBeVisible()- await row.getByLabel('Add agents to this subscription').click()- const options = row.getByRole('option')- await expect(- options.first(),- 'hub assign requires seeded Codex agents — API seed is a named precondition'- ).toBeVisible()- const available = await options.count()- expect(- available,- `hub multi-assign needs ${count} agents, found ${available}`- ).toBeGreaterThanOrEqual(count)-- const names: string[] = []- for (let index = 0; index < count; index += 1) {- const option = options.nth(index)- const label = ((await option.getAttribute('aria-label')) ?? '').trim()- expect(label, `assignable agent #${index + 1} must have a name`).toMatch(/\S/)- names.push(label)- await option.click()- }-- const bindPath = new RegExp(- `/api/v1/admin/llm/providers/codex-subscription/connections/${connectionKey}/hosts/[^/]+/bind$`- )- const bindBodies: Promise<{ host?: string; connectionRef?: string; ok: boolean }>[] = []- const onResponse = (response: import('@playwright/test').Response) => {- if (- bindPath.test(new URL(response.url()).pathname) &&- response.request().method() === 'POST'- ) {- bindBodies.push(- response.json().then(body => ({- ...(body as { host?: string; connectionRef?: string }),- ok: response.ok(),- }))- )- }- }- this.page.on('response', onResponse)-- await row- .getByRole('button', { name: count > 1 ? `Add ${count} agents` : 'Add agents' })+ async openGrant(displayName: string) {+ await this.page+ .getByRole('button', { name: `Update ChatGPT subscription ${displayName}` }).click()- await expect- .poll(() => bindBodies.length, { message: `expected ${count} bind responses` })- .toBe(count)- this.page.off('response', onResponse)- const binds = await Promise.all(bindBodies)- for (const bind of binds) {- expect(bind.ok, 'each hub bind must succeed').toBe(true)- expect(bind.connectionRef).toBe(connectionKey)- }- return names+ await expect(this.page.getByRole('dialog')).toBeVisible()}- async removeAgentFromGrant(connectionKey: string, hostName: string) {- const row = this.grantRow(connectionKey)- const unbind = this.page.waitForResponse(+ async revokeGrant(displayName: string, connectionKey: string) {+ const revoke = this.page.waitForResponse(response =>new RegExp(- `/api/v1/admin/llm/providers/codex-subscription/connections/${connectionKey}/hosts/${hostName}/unbind$`+ `/api/v1/admin/llm/providers/codex-subscription/connections/${connectionKey}/revoke$`).test(new URL(response.url()).pathname) && response.request().method() === 'POST')- await row.getByRole('button', { name: `Remove agent ${hostName}` }).click()+ await this.page+ .getByRole('button', { name: `Delete ChatGPT subscription ${displayName}` })+ .click()await expect(this.page.getByRole('alertdialog')).toBeVisible()- await this.page.getByRole('alertdialog').getByRole('button', { name: 'Remove agent' }).click()- const response = await unbind- expect(response.ok(), `hub unbind must succeed, got ${response.status()}`).toBe(true)- const body = (await response.json()) as { host?: string; connectionRef?: string }- expect(body.host).toBe(hostName)- expect(body.connectionRef).toBe('unassigned')+ await this.page.getByRole('alertdialog').getByRole('button', { name: 'Delete' }).click()+ const response = await revoke+ expect(response.ok(), `revoke must succeed, got ${response.status()}`).toBe(true)}}++/** @deprecated Use SecretsLlmSubscriptionsPage. Kept for any leftover imports. */+export class CodexSubscriptionHubPage extends SecretsLlmSubscriptionsPage {}