Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(codex): manage ChatGPT grants from the Secrets Subscription hub
Alfredo Lopez7f7d47002903
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 0343b3028..07ed1fa04 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.497",+ "version": "0.1.498","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.497",+ "version": "0.1.498","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 0fa0dfca6..d9a9a03e9 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.497",+ "version": "0.1.498","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/admin/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.tsindex 661df0f00..eeda160d7 100644--- a/control-api/src/routes/admin/codexSubscription.ts+++ b/control-api/src/routes/admin/codexSubscription.ts@@ -13,6 +13,7 @@ import {syncCodexSubscriptionCatalog,} from '../../services/codexSubscriptionCatalog.js'import {+ CODEX_UNASSIGNED_CONNECTION_KEY,CodexSubscriptionInvalidConnectionKeyError,assertCodexConnectionKey,createNamedCodexSubscriptionConnection,@@ -20,6 +21,7 @@ import {listSafeCodexSubscriptionConnections,loadCodexSubscriptionSecrets,normalizeCodexConnectionKey,+ readHostCodexConnectionRef,} from '../../services/codexSubscriptionConnection.js'import {type CodexOAuthDeps,@@ -37,11 +39,13 @@ import {isPublicCodexCliClient,resolveCodexControlUiBaseUrl,} from '../../services/codexSubscriptionRedirectUri.js'+import { getModelAllowlistState, isModelAllowed } from '../../services/llmAllowedModels.js'import { publishAllowedModelsConfigMapAfterGrantChange } from '../../services/llmAllowedModelsConfigMap.js'import {adminCodexReadRateLimits,adminCodexWriteRateLimits,} from '../workflows/shared/rateLimit.js'+import { validateHostSpec } from './hostSpecValidation.js'const log = rootLogger.child({ module: 'admin-codex-subscription' })const BASE = '/admin/llm/providers/codex-subscription'@@ -114,11 +118,37 @@ function sendOAuthError(throw err}-function hostConnectionRef(spec: unknown): string | null {+type HostRecord = {+ metadata?: { name?: string; resourceVersion?: string }+ spec?: unknown+}++function hostModel(spec: unknown): { provider?: string; connectionRef?: string } | null {if (!spec || typeof spec !== 'object') return nullconst model = (spec as { model?: { provider?: string; connectionRef?: string } }).model+ if (!model || typeof model !== 'object') return null+ return model+}++function hostConnectionRef(spec: unknown): string | null {+ const model = hostModel(spec)if (!model || model.provider !== 'codex-subscription') return null- return normalizeCodexConnectionKey(model.connectionRef)+ return readHostCodexConnectionRef(model.connectionRef)+}++function assignableHostFromRecord(+ host: HostRecord+): { name: string; connectionRef: string; displayName: string } | null {+ const name = String(host.metadata?.name ?? '').trim()+ const connectionRef = hostConnectionRef(host.spec)+ if (!name || !connectionRef) return null+ return { name, connectionRef, displayName: name }+}++function storedCodexConnectionRef(spec: unknown): string | null {+ const model = hostModel(spec)+ if (!model || model.provider !== 'codex-subscription') return null+ return typeof model.connectionRef === 'string' ? model.connectionRef.trim() : ''}export function createAdminCodexSubscriptionRouter(@@ -127,32 +157,120 @@ export function createAdminCodexSubscriptionRouter(): Router {const router = Router()- async function listHostsOrUnavailable(): Promise<Array<{- metadata?: { name?: string }- spec?: unknown- }> | null> {+ async function listHostsOrUnavailable(): Promise<HostRecord[] | null> {if (!gateway) return nulltry {- return (await gateway.listResource('hosts', config.hostsNamespace)) as Array<{- metadata?: { name?: string }- spec?: unknown- }>+ return (await gateway.listResource('hosts', config.hostsNamespace)) as HostRecord[]} catch (err) {log.warn({ event: 'codex_assigned_hosts_list_failed', err }, 'failed to list assigned hosts')return null}}- function hostsForConnection(- hosts: Array<{ metadata?: { name?: string }; spec?: unknown }>,- connectionKey: string- ): Array<{ name: string }> {+ function hostsForConnection(hosts: HostRecord[], connectionKey: string): Array<{ name: string }> {return hosts.filter(host => hostConnectionRef(host.spec) === connectionKey).map(host => ({ name: String(host.metadata?.name ?? '') })).filter(host => host.name)}+ function collectAssignableHosts(+ hosts: HostRecord[]+ ): Array<{ name: string; connectionRef: string; displayName: string }> {+ return hosts+ .map(assignableHostFromRecord)+ .filter((row): row is { name: string; connectionRef: string; displayName: string } =>+ Boolean(row)+ )+ }++ async function loadHost(+ hostRef: string+ ): Promise<{ ok: true; host: HostRecord } | { ok: false; status: number; error: string }> {+ if (!gateway) return { ok: false, status: 503, error: 'hosts_unavailable' }+ try {+ const host = (await gateway.getResource(+ 'hosts',+ hostRef,+ config.hostsNamespace+ )) as HostRecord+ return { ok: true, host }+ } catch (err) {+ const name = err instanceof Error ? err.name : ''+ const status = (err as { httpStatus?: number; code?: number } | null)?.httpStatus+ if (name === 'K8sNotFoundError' || status === 404) {+ return { ok: false, status: 404, error: 'host_not_found' }+ }+ log.warn(+ { event: 'codex_host_read_failed', err, hostRef },+ 'failed to read host for bind/unbind'+ )+ return { ok: false, status: 503, error: 'hosts_unavailable' }+ }+ }++ async function writeHostConnectionRef(+ hostRef: string,+ host: HostRecord,+ nextConnectionRef: string+ ): Promise<{ ok: true } | { ok: false; status: number; error: string; message?: string }> {+ if (!gateway) return { ok: false, status: 503, error: 'hosts_unavailable' }+ const spec =+ host.spec && typeof host.spec === 'object'+ ? { ...(host.spec as Record<string, unknown>) }+ : {}+ const model =+ spec.model && typeof spec.model === 'object'+ ? { ...(spec.model as Record<string, unknown>) }+ : {}+ model.provider = 'codex-subscription'+ model.connectionRef = nextConnectionRef+ spec.model = model+ const stored =+ host.spec && typeof host.spec === 'object'+ ? (host.spec as Record<string, unknown>)+ : undefined+ const issue = await validateHostSpec(+ spec,+ {+ isModelAllowed: (provider, model) => isModelAllowed(provider, model),+ getModelAllowlistState,+ },+ {+ stored,+ hostRef: { namespace: config.hostsNamespace, name: hostRef },+ }+ )+ if (issue) {+ return {+ ok: false,+ status: 422,+ error: 'invalid_host_spec',+ message: issue.errors[0]?.message,+ }+ }+ try {+ await gateway.updateResource(+ 'hosts',+ hostRef,+ {+ metadata: host.metadata?.resourceVersion+ ? { resourceVersion: host.metadata.resourceVersion }+ : undefined,+ spec,+ },+ config.hostsNamespace+ )+ return { ok: true }+ } catch (err) {+ log.warn(+ { event: 'codex_host_write_failed', err, hostRef },+ 'failed to write host connectionRef'+ )+ return { ok: false, status: 503, error: 'hosts_unavailable' }+ }+ }+async function publishRuntimeAllowlist(): Promise<void> {await publishAllowedModelsConfigMapAfterGrantChange(gateway?.llmAllowedModelsConfigMap())}@@ -192,7 +310,7 @@ export function createAdminCodexSubscriptionRouter(async function withAssignedHosts<T extends { connectionKey: string }>(connection: T,- hosts?: Array<{ metadata?: { name?: string }; spec?: unknown }> | null+ hosts?: HostRecord[] | null) {const resolved = hosts === undefined ? await listHostsOrUnavailable() : hostsif (resolved === null) {@@ -363,7 +481,14 @@ export function createAdminCodexSubscriptionRouter(for (const row of rows) {connections.push(await withAssignedHosts(row, hosts))}- res.status(200).json({ connections })+ if (hosts === null) {+ res.status(200).json({ connections, assignableHostsUnavailable: true })+ return+ }+ res.status(200).json({+ connections,+ assignableHosts: collectAssignableHosts(hosts),+ })}))@@ -424,5 +549,117 @@ export function createAdminCodexSubscriptionRouter(}))+ router.get(+ `${BASE}/assignable-hosts`,+ ...adminCodexReadRateLimits(),+ asyncHandler(async (_req, res) => {+ if (!config.codexSubscriptionEnabled) {+ res.status(404).json({ error: 'disabled' })+ return+ }+ const hosts = await listHostsOrUnavailable()+ if (hosts === null) {+ res.status(503).json({ error: 'hosts_unavailable' })+ return+ }+ res.status(200).json({ hosts: collectAssignableHosts(hosts) })+ })+ )++ const bindUnbindHandler = (action: 'bind' | 'unbind') =>+ asyncHandler(async (req, res) => {+ if (!config.codexSubscriptionEnabled) {+ res.status(404).json({ error: 'disabled' })+ return+ }+ let connectionKey: string+ try {+ connectionKey = assertCodexConnectionKey(+ typeof req.params.key === 'string' ? req.params.key : ''+ )+ } catch (err) {+ sendOAuthError(res, err)+ return+ }+ const hostRef = typeof req.params.hostRef === 'string' ? req.params.hostRef.trim() : ''+ if (!hostRef) {+ res.status(400).json({ error: 'invalid_host_ref' })+ return+ }++ const loaded = await loadHost(hostRef)+ if (!loaded.ok) {+ res.status(loaded.status).json({ error: loaded.error })+ return+ }+ const storedRef = storedCodexConnectionRef(loaded.host.spec)+ if (storedRef === null) {+ res.status(409).json({ error: 'not_codex_host' })+ return+ }+ // Bind must see the stored ref. Empty/missing is not deployment-default.+ if (action === 'bind' && !storedRef) {+ res.status(409).json({ error: 'empty_connection_ref' })+ return+ }+ const currentRef = storedRef || CODEX_SUBSCRIPTION_CONNECTION_KEY++ if (action === 'unbind') {+ if (currentRef === CODEX_UNASSIGNED_CONNECTION_KEY) {+ res.status(200).json({+ host: hostRef,+ connectionRef: CODEX_UNASSIGNED_CONNECTION_KEY,+ })+ return+ }+ if (currentRef !== connectionKey) {+ res.status(409).json({ error: 'connection_mismatch' })+ return+ }+ const written = await writeHostConnectionRef(+ hostRef,+ loaded.host,+ CODEX_UNASSIGNED_CONNECTION_KEY+ )+ if (!written.ok) {+ res.status(written.status).json({+ error: written.error,+ ...(written.message ? { message: written.message } : {}),+ })+ return+ }+ res.status(200).json({+ host: hostRef,+ connectionRef: CODEX_UNASSIGNED_CONNECTION_KEY,+ })+ return+ }++ if (currentRef === connectionKey) {+ res.status(200).json({ host: hostRef, connectionRef: connectionKey })+ return+ }+ const written = await writeHostConnectionRef(hostRef, loaded.host, connectionKey)+ if (!written.ok) {+ res.status(written.status).json({+ error: written.error,+ ...(written.message ? { message: written.message } : {}),+ })+ return+ }+ res.status(200).json({ host: hostRef, connectionRef: connectionKey })+ })++ router.post(+ `${BASE}/connections/:key/hosts/:hostRef/unbind`,+ ...adminCodexWriteRateLimits(),+ bindUnbindHandler('unbind')+ )+ router.post(+ `${BASE}/connections/:key/hosts/:hostRef/bind`,+ ...adminCodexWriteRateLimits(),+ bindUnbindHandler('bind')+ )+return router}diff --git a/control-api/src/routes/admin/hostSpecValidation.ts b/control-api/src/routes/admin/hostSpecValidation.tsindex e2c2be756..b082394ae 100644--- a/control-api/src/routes/admin/hostSpecValidation.ts+++ b/control-api/src/routes/admin/hostSpecValidation.ts@@ -6,6 +6,10 @@ import {isLlmProviderId,} from '@clerum/llm-providers'import { rootLogger } from '../../observability/logger.js'+import {+ isCodexUnassignedConnectionKey,+ readHostCodexConnectionRef,+} from '../../services/codexSubscriptionConnection.js'import {getModelAllowlistState as getModelAllowlistStateDefault,isModelAllowed as isModelAllowedDefault,@@ -340,7 +344,11 @@ export async function validateHostSpec(}const connectionRef =provider === 'codex-subscription' ? resolvedCodexConnectionRef(model) : undefined- const allowed = await deps.isModelAllowed(provider, name, connectionRef)+ const skipCodexAllowlist =+ provider === 'codex-subscription' && isCodexUnassignedConnectionKey(connectionRef)+ const allowed = skipCodexAllowlist+ ? true+ : await deps.isModelAllowed(provider, name, connectionRef)// Switching connectionRef is a new assignment even when (provider, model)// already lived on the Host. A revoked/unknown grant must not ride the// identity/channels full-replace tolerance. An unchanged revoked ref stays@@ -543,23 +551,19 @@ async function maybeWarnStale(* the gate skips its rejection.*/function resolvedCodexConnectionRef(model: unknown): string {- if (- isPlainObject(model) &&- typeof model.connectionRef === 'string' &&- model.connectionRef.trim()- ) {- return model.connectionRef.trim()- }- return 'deployment-default'+ if (!isPlainObject(model)) return 'deployment-default'+ return readHostCodexConnectionRef(+ typeof model.connectionRef === 'string' ? model.connectionRef : null+ )}function storedCodexConnectionRef(stored: Record<string, unknown> | undefined): string | undefined {if (!isPlainObject(stored) || !isPlainObject(stored.model)) return undefinedconst provider = typeof stored.model.provider === 'string' ? stored.model.provider.trim() : ''if (provider !== 'codex-subscription') return undefined- return typeof stored.model.connectionRef === 'string' && stored.model.connectionRef.trim()- ? stored.model.connectionRef.trim()- : 'deployment-default'+ return readHostCodexConnectionRef(+ typeof stored.model.connectionRef === 'string' ? stored.model.connectionRef : null+ )}function toleratePair(@@ -653,11 +657,14 @@ async function validateAllowedModels(// catalog can never be offered by a host — unless tolerating a pre-existing// incoherence this write does not worsen (Pieza D). A tolerated pair is still// added to `offered` so the coherence gate below sees the host as offering it.- const allowed = await deps.isModelAllowed(- provider,- model,- provider === 'codex-subscription' ? connectionRef : undefined- )+ const allowed =+ provider === 'codex-subscription' && isCodexUnassignedConnectionKey(connectionRef)+ ? true+ : await deps.isModelAllowed(+ provider,+ model,+ provider === 'codex-subscription' ? connectionRef : undefined+ )if (!allowed && !toleratePair(provider, model, 'subset', tol)) {return {errors: [@@ -826,11 +833,14 @@ async function validateLlmPolicy(// Allowlist gate LAST: it is the only async (DB) check, so cheap structural// rejections above avoid a needless query. Tolerated (Pieza D) when the pair// is a pre-existing incoherence this write does not worsen.- const allowed = await deps.isModelAllowed(- provider,- model,- provider === 'codex-subscription' ? connectionRef : undefined- )+ const allowed =+ provider === 'codex-subscription' && isCodexUnassignedConnectionKey(connectionRef)+ ? true+ : await deps.isModelAllowed(+ provider,+ model,+ provider === 'codex-subscription' ? connectionRef : undefined+ )if (!allowed && !toleratePair(provider, model, 'fallback', tol)) {return {errors: [diff --git a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.tsindex 2e1ad593a..462d798fd 100644--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts@@ -23,6 +23,7 @@ const ERROR_STATUS: Record<string, number> = {model_not_allowed: 403,budget_denied: 403,connection_unavailable: 503,+ unassigned_connection: 403,host_binding_mismatch: 403,unknown_field: 400,invalid_request: 400,diff --git a/control-api/src/services/codexSubscriptionConnection.ts b/control-api/src/services/codexSubscriptionConnection.tsindex d4c9544b9..ed917eaf4 100644--- a/control-api/src/services/codexSubscriptionConnection.ts+++ b/control-api/src/services/codexSubscriptionConnection.ts@@ -3,17 +3,33 @@ import type { DbClient } from '../db.js'import { decryptOAuthSecret, encryptOAuthSecret } from '../oauth/encryption.js'export const CODEX_SUBSCRIPTION_CONNECTION_KEY = 'deployment-default' as const+/** Fail-closed Host sentinel. Not a grant row; never maps to deployment-default. */+export const CODEX_UNASSIGNED_CONNECTION_KEY = 'unassigned' as constconst CONNECTION_KEY_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/+export function isCodexUnassignedConnectionKey(value?: string | null): boolean {+ return typeof value === 'string' && value.trim() === CODEX_UNASSIGNED_CONNECTION_KEY+}++/**+ * Host spec reader: empty/missing becomes deployment-default; `unassigned` stays.+ */+export function readHostCodexConnectionRef(value?: string | null): string {+ const trimmed = typeof value === 'string' ? value.trim() : ''+ if (!trimmed) return CODEX_SUBSCRIPTION_CONNECTION_KEY+ return trimmed+}+export function normalizeCodexConnectionKey(value?: string | null): string {const trimmed = typeof value === 'string' ? value.trim() : ''+ if (isCodexUnassignedConnectionKey(trimmed)) return CODEX_UNASSIGNED_CONNECTION_KEYreturn trimmed || CODEX_SUBSCRIPTION_CONNECTION_KEY}export function assertCodexConnectionKey(value: string): string {const key = value.trim()- if (!CONNECTION_KEY_RE.test(key)) {+ if (!CONNECTION_KEY_RE.test(key) || isCodexUnassignedConnectionKey(key)) {throw new CodexSubscriptionInvalidConnectionKeyError(key)}return keydiff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.tsindex ef560c6fd..5f47d1a45 100644--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts@@ -15,6 +15,7 @@ import { getCodexCatalogModelState } from './codexSubscriptionCatalog.js'import {CODEX_SUBSCRIPTION_CONNECTION_KEY,getSafeCodexSubscriptionConnection,+ isCodexUnassignedConnectionKey,normalizeCodexConnectionKey,} from './codexSubscriptionConnection.js'import {@@ -49,6 +50,7 @@ export type LlmProviderAttemptAuthorizeErrorCode =| 'model_not_allowed'| 'budget_denied'| 'connection_unavailable'+ | 'unassigned_connection'| 'host_binding_mismatch'| 'unknown_field'| 'invalid_request'@@ -246,6 +248,12 @@ export async function authorizeLlmProviderAttempt(const connectionKey = normalizeCodexConnectionKey(await resolvedDeps.resolveConnectionKey(caller.hostRef))+ if (isCodexUnassignedConnectionKey(connectionKey)) {+ throw new LlmProviderAttemptAuthorizeError(+ 'unassigned_connection',+ 'Host has no ChatGPT subscription assigned'+ )+ }return resolvedDeps.withTransaction(async tx => {const db: DbClient = txconst connection = await resolvedDeps.getConnection(db, connectionKey)diff --git a/control-api/test/hostSpecValidation.codexSubscription.test.ts b/control-api/test/hostSpecValidation.codexSubscription.test.tsindex cf318c37e..8a174a5ff 100644--- a/control-api/test/hostSpecValidation.codexSubscription.test.ts+++ b/control-api/test/hostSpecValidation.codexSubscription.test.ts@@ -49,6 +49,22 @@ describe('codex-subscription Host admission', () => {expect(res!.errors[0].field).toBe('spec.secretRef')})+ it('persists an unassigned connectionRef without rematching deployment-default', async () => {+ process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED = 'true'+ const isModelAllowed = vi.fn().mockResolvedValue(false)+ const spec = {+ model: {+ provider: 'codex-subscription',+ name: 'gpt-5.1',+ connectionRef: 'unassigned',+ },+ }+ const res = await validateHostSpec(spec, { isModelAllowed })+ expect(res).toBeNull()+ expect(isModelAllowed).not.toHaveBeenCalled()+ expect((spec.model as { connectionRef?: string }).connectionRef).toBe('unassigned')+ })+it('defaults a missing connectionRef to deployment-default and checks that grant', async () => {process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED = 'true'const isModelAllowed = vi.fn().mockResolvedValue(true)diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.tsindex 3ad98946d..31efed055 100644--- a/control-api/test/routes.admin.codexSubscription.test.ts+++ b/control-api/test/routes.admin.codexSubscription.test.ts@@ -51,6 +51,14 @@ vi.mock('../src/db.js', () => ({pool: { query: vi.fn() },}))+vi.mock('../src/routes/admin/hostSpecValidation.js', async () => {+ const actual = await vi.importActual('../src/routes/admin/hostSpecValidation.js')+ return {+ ...actual,+ validateHostSpec: vi.fn().mockResolvedValue(null),+ }+})+const { pool } = await import('../src/db.js')const { config } = await import('../src/config.js')@@ -62,12 +70,16 @@ const { createAdminCodexSubscriptionRouter } =function makeGateway(materialize: () => Promise<void> = async () => {}) {return {listResource: vi.fn().mockResolvedValue([]),+ getResource: vi.fn(),+ updateResource: vi.fn(),llmAllowedModelsConfigMap: () => ({ materialize }),}}function makeAuthedApp(gateway?: {listResource: ReturnType<typeof vi.fn>+ getResource?: ReturnType<typeof vi.fn>+ updateResource?: ReturnType<typeof vi.fn>llmAllowedModelsConfigMap?: () => { materialize: () => Promise<void> }}) {const app = express()@@ -126,6 +138,7 @@ describe('admin Codex subscription routes', () => {for (const fn of Object.values(oauth)) fn.mockReset()catalog.loadSecrets.mockReset()catalog.sync.mockReset()+ vi.mocked(pool.query).mockReset()})it('returns 404 while the feature flag is off', async () => {@@ -423,4 +436,167 @@ describe('admin Codex subscription routes', () => {expect(materialize).not.toHaveBeenCalled()assertNoLeak(res.body)})++ it('rejects creating a reserved unassigned connection key', async () => {+ const res = await request(app)+ .post('/admin/llm/providers/codex-subscription/connections')+ .send({ displayName: 'Nope', connectionKey: 'unassigned' })+ expect(res.status).toBe(400)+ expect(res.body).toEqual({ error: 'invalid_connection_key' })+ expect(vi.mocked(pool.query).mock.calls).toEqual([])+ })++ it('lists assignable Codex hosts next to connections', async () => {+ vi.mocked(pool.query).mockResolvedValueOnce({ rows: [], rowCount: 0 })+ const gateway = makeGateway()+ gateway.listResource.mockResolvedValue([+ {+ metadata: { name: 'chatllm' },+ spec: {+ model: {+ provider: 'codex-subscription',+ connectionRef: 'codex-aaa',+ },+ },+ },+ {+ metadata: { name: 'other' },+ spec: { model: { provider: 'openai', name: 'gpt-5.4' } },+ },+ ])+ const res = await request(makeAuthedApp(gateway)).get(+ '/admin/llm/providers/codex-subscription/connections'+ )+ expect(res.status).toBe(200)+ expect(res.body.assignableHosts).toEqual([+ { name: 'chatllm', connectionRef: 'codex-aaa', displayName: 'chatllm' },+ ])+ })++ it('unbinds one host to unassigned without revoking', async () => {+ const gateway = makeGateway()+ gateway.getResource.mockResolvedValue({+ metadata: { name: 'chatllm', resourceVersion: '11' },+ spec: {+ model: { provider: 'codex-subscription', name: 'gpt-5.6-luna', connectionRef: 'codex-aaa' },+ },+ })+ gateway.updateResource.mockResolvedValue({})+ const res = await request(makeAuthedApp(gateway)).post(+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/hosts/chatllm/unbind'+ )+ expect(res.status).toBe(200)+ expect(res.body).toEqual({ host: 'chatllm', connectionRef: 'unassigned' })+ expect(oauth.revoke).not.toHaveBeenCalled()+ expect(gateway.updateResource).toHaveBeenCalledWith(+ 'hosts',+ 'chatllm',+ expect.objectContaining({+ spec: expect.objectContaining({+ model: expect.objectContaining({ connectionRef: 'unassigned' }),+ }),+ }),+ expect.any(String)+ )+ })++ it('refuses unbind when the host list cannot be read', async () => {+ const gateway = makeGateway()+ gateway.getResource.mockRejectedValue(new Error('k8s down'))+ const res = await request(makeAuthedApp(gateway)).post(+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/hosts/chatllm/unbind'+ )+ expect(res.status).toBe(503)+ expect(res.body).toEqual({ error: 'hosts_unavailable' })+ expect(gateway.updateResource).not.toHaveBeenCalled()+ })++ it('refuses unbind when the host is bound to another grant', async () => {+ const gateway = makeGateway()+ gateway.getResource.mockResolvedValue({+ metadata: { name: 'chatllm' },+ spec: {+ model: { provider: 'codex-subscription', connectionRef: 'codex-bbb' },+ },+ })+ const res = await request(makeAuthedApp(gateway)).post(+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/hosts/chatllm/unbind'+ )+ expect(res.status).toBe(409)+ expect(res.body).toEqual({ error: 'connection_mismatch' })+ expect(gateway.updateResource).not.toHaveBeenCalled()+ })++ it('binds an unassigned host and can switch from another named grant', async () => {+ const gateway = makeGateway()+ gateway.getResource.mockResolvedValueOnce({+ metadata: { name: 'chatllm' },+ spec: {+ model: { provider: 'codex-subscription', connectionRef: 'unassigned' },+ },+ })+ gateway.updateResource.mockResolvedValue({})+ const first = await request(makeAuthedApp(gateway)).post(+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/hosts/chatllm/bind'+ )+ expect(first.status).toBe(200)+ expect(first.body).toEqual({ host: 'chatllm', connectionRef: 'codex-aaa' })++ gateway.getResource.mockResolvedValueOnce({+ metadata: { name: 'chatllm' },+ spec: {+ model: { provider: 'codex-subscription', connectionRef: 'codex-bbb' },+ },+ })+ const switched = await request(makeAuthedApp(gateway)).post(+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/hosts/chatllm/bind'+ )+ expect(switched.status).toBe(200)+ expect(switched.body).toEqual({ host: 'chatllm', connectionRef: 'codex-aaa' })+ expect(oauth.revoke).not.toHaveBeenCalled()+ })++ it('rejects bind when the Host connectionRef is empty', async () => {+ const gateway = makeGateway()+ gateway.getResource.mockResolvedValue({+ metadata: { name: 'chatllm' },+ spec: { model: { provider: 'codex-subscription' } },+ })+ const res = await request(makeAuthedApp(gateway)).post(+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/hosts/chatllm/bind'+ )+ expect(res.status).toBe(409)+ expect(res.body).toEqual({ error: 'empty_connection_ref' })+ expect(gateway.updateResource).not.toHaveBeenCalled()+ expect(oauth.revoke).not.toHaveBeenCalled()+ })++ it('revokes a grant without rewriting Host CRs', async () => {+ const gateway = makeGateway()+ oauth.revoke.mockResolvedValue({+ connectionKey: 'codex-aaa',+ status: 'revoked',+ credentialRevision: 3,+ })+ const res = await request(makeAuthedApp(gateway)).post(+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/revoke'+ )+ expect(res.status).toBe(200)+ expect(res.body.status).toBe('revoked')+ expect(gateway.updateResource).not.toHaveBeenCalled()+ })++ it('rejects bind on a non-Codex host', async () => {+ const gateway = makeGateway()+ gateway.getResource.mockResolvedValue({+ metadata: { name: 'api-agent' },+ spec: { model: { provider: 'openai', name: 'gpt-5.4' } },+ })+ const res = await request(makeAuthedApp(gateway)).post(+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/hosts/api-agent/bind'+ )+ expect(res.status).toBe(409)+ expect(res.body).toEqual({ error: 'not_codex_host' })+ expect(gateway.updateResource).not.toHaveBeenCalled()+ })})diff --git a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts b/control-api/test/routes.mcp-host.llmProviderAttempts.test.tsindex 85e22f514..b9b7bca69 100644--- a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts+++ b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts@@ -109,6 +109,16 @@ describe('POST /api/v1/mcp-host/llm/provider-attempts/authorize', () => {.send({ request: {} })expect(budget.status).toBe(403)expect(budget.body).toEqual({ error: 'budget_denied' })++ vi.mocked(authorizer.authorizeLlmProviderAttempt).mockRejectedValueOnce(+ new LlmProviderAttemptAuthorizeError('unassigned_connection', 'no grant assigned')+ )+ const unassigned = await request(app)+ .post('/api/v1/mcp-host/llm/provider-attempts/authorize')+ .set('Authorization', `Bearer ${token()}`)+ .send({ request: {} })+ expect(unassigned.status).toBe(403)+ expect(unassigned.body).toEqual({ error: 'unassigned_connection' })})it('returns the authorize contract without leaking tokens', async () => {@@ -149,6 +159,11 @@ describe('resolveHostAssignedConnectionKey', () => {await expect(resolveHostAssignedConnectionKey(gateway, 'agent-b')).resolves.toBe('deployment-default')++ gateway.getResource.mockResolvedValueOnce({+ spec: { model: { provider: 'codex-subscription', connectionRef: 'unassigned' } },+ })+ await expect(resolveHostAssignedConnectionKey(gateway, 'agent-c')).resolves.toBe('unassigned')})it('aliases a recipe caller to deployment-default without a Host GET', async () => {diff --git a/control-api/test/services.codexSubscriptionConnection.test.ts b/control-api/test/services.codexSubscriptionConnection.test.tsindex f51a5a107..571995eb6 100644--- a/control-api/test/services.codexSubscriptionConnection.test.ts+++ b/control-api/test/services.codexSubscriptionConnection.test.ts@@ -2,10 +2,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { deriveOAuthEncryptionKey, encryptOAuthSecret } from '../src/oauth/encryption.js'import {CodexSubscriptionFingerprintConflictError,+ CodexSubscriptionInvalidConnectionKeyError,CodexSubscriptionStaleRevisionError,+ assertCodexConnectionKey,generateCodexConnectionKey,getSafeCodexSubscriptionConnection,insertInitialCodexSubscriptionConnection,+ normalizeCodexConnectionKey,+ readHostCodexConnectionRef,rotateCodexSubscriptionCredentials,} from '../src/services/codexSubscriptionConnection.js'@@ -165,6 +169,17 @@ describe('codex subscription connection repository', () => {expect(sql).not.toMatch(/revoked_at = NULL/)})+ it('rejects the reserved unassigned key and keeps it on Host reads', () => {+ expect(() => assertCodexConnectionKey('unassigned')).toThrow(+ CodexSubscriptionInvalidConnectionKeyError+ )+ expect(readHostCodexConnectionRef('unassigned')).toBe('unassigned')+ expect(readHostCodexConnectionRef('')).toBe('deployment-default')+ expect(readHostCodexConnectionRef('codex-aaa')).toBe('codex-aaa')+ expect(normalizeCodexConnectionKey('unassigned')).toBe('unassigned')+ expect(normalizeCodexConnectionKey('')).toBe('deployment-default')+ })+it('generates distinct identity keys that are not derived from the display name', () => {const keys = new Set(Array.from({ length: 8 }, () => generateCodexConnectionKey()))expect(keys.size).toBe(8)diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.test.tsindex 34a4ff199..e188eb3bb 100644--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts@@ -228,6 +228,17 @@ describe('authorizeLlmProviderAttempt', () => {).rejects.toMatchObject({ code: 'invalid_request' })})+ it('rejects an unassigned Host connectionRef as unassigned_connection', async () => {+ await expect(+ authorizeLlmProviderAttempt(claims(), body(), {+ ...current,+ resolveConnectionKey: async () => 'unassigned',+ })+ ).rejects.toMatchObject({ code: 'unassigned_connection' })+ expect(current.getConnection).not.toHaveBeenCalled()+ expect(current.insertAttempt).not.toHaveBeenCalled()+ })+it('fails closed for every Host on a revoked grant and leaves another grant usable', async () => {const teamPlus = connection({id: '22222222-2222-4222-8222-222222222222',diff --git a/control-ui/app/constants/routes.ts b/control-ui/app/constants/routes.tsindex 6c0920e00..449be3aa4 100644--- a/control-ui/app/constants/routes.ts+++ b/control-ui/app/constants/routes.ts@@ -119,6 +119,7 @@ export const CONTROL_ROUTES = {llm: '/secrets/llm',connector: '/secrets/connector',recipe: '/secrets/recipe',+ subscription: '/secrets/subscription',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/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsxindex b218b47cc..fcc78ed43 100644--- a/control-ui/app/hosts/[name]/page.tsx+++ b/control-ui/app/hosts/[name]/page.tsx@@ -550,7 +550,12 @@ export default function HostDetailsPage() {provider: providerDraft,name: modelNameDraft.trim(),...(providerDraft === 'codex-subscription'- ? { connectionRef: connectionRefDraft.trim() || 'deployment-default' }+ ? {+ connectionRef:+ connectionRefDraft.trim() === 'unassigned'+ ? 'unassigned'+ : connectionRefDraft.trim() || 'deployment-default',+ }: {}),},}@@ -1069,6 +1074,7 @@ export default function HostDetailsPage() {providerDraft === 'codex-subscription' ? (<CodexAgentAssignmentconnectionRef={connectionRefDraft}+ hostName={routeName}onConnectionRefChange={setConnectionRefDraft}onModelsChange={setCodexModels}disabled={busy}diff --git a/control-ui/app/secrets/SecretsPageContent.tsx b/control-ui/app/secrets/SecretsPageContent.tsxindex 4eaabf3b3..9c2fa6e25 100644--- a/control-ui/app/secrets/SecretsPageContent.tsx+++ b/control-ui/app/secrets/SecretsPageContent.tsx@@ -3,12 +3,13 @@import { useEffect, useState } from 'react'import { useRouter } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { CodexSubscriptionHub } from '@components/CodexSubscriptionHub'import { DashboardLayout } from '@components/DashboardLayout'import { SecretsTable } from '@components/SecretsTable'import { CONTROL_ROUTES } from '@constants/routes'import { apiGet, isSilentApiError } from '@lib/api'-export type SecretScope = 'llm' | 'mcp' | 'recipe'+export type SecretScope = 'llm' | 'mcp' | 'recipe' | 'subscription'type SecretItem = {name?: string@@ -40,6 +41,16 @@ export function SecretsPageContent({ activeScope }: { activeScope: SecretScope }void loadAll()}, [])+ if (activeScope === 'subscription') {+ return (+ <AuthGate>+ <DashboardLayout>+ <CodexSubscriptionHub />+ </DashboardLayout>+ </AuthGate>+ )+ }+return (<AuthGate><DashboardLayout>diff --git a/control-ui/app/secrets/[scope]/page.tsx b/control-ui/app/secrets/[scope]/page.tsxindex 41978ec31..ebf5f85af 100644--- a/control-ui/app/secrets/[scope]/page.tsx+++ b/control-ui/app/secrets/[scope]/page.tsx@@ -7,7 +7,9 @@ interface SecretsScopePageProps {export default async function SecretsScopePage({ params }: SecretsScopePageProps) {const { scope } = await params- if (scope !== 'llm' && scope !== 'connector' && scope !== 'recipe') notFound()+ if (scope !== 'llm' && scope !== 'connector' && scope !== 'recipe' && scope !== 'subscription') {+ notFound()+ }return <SecretsPageContent activeScope={(scope === 'connector' ? 'mcp' : scope) as SecretScope} />}diff --git a/control-ui/components/CodexAgentAssignment/index.tsx b/control-ui/components/CodexAgentAssignment/index.tsxindex 98310c125..57e367f75 100644--- a/control-ui/components/CodexAgentAssignment/index.tsx+++ b/control-ui/components/CodexAgentAssignment/index.tsx@@ -3,15 +3,17 @@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,- revokeCodexSubscription,startCodexDeviceConnect,syncCodexSubscriptionCatalog,+ unbindCodexHost,} from '@lib/codexSubscription'import {type CodexSubscriptionCapability,@@ -26,17 +28,15 @@ import {export type CodexAgentAssignmentProps = {connectionRef: string+ hostName?: stringonConnectionRefChange: (connectionKey: string) => voidonModelsChange?: (models: string[]) => voiddisabled?: boolean}-function assignedHostNames(connection: CodexSubscriptionConnectionView): string[] {- return (connection.assignedHosts ?? []).map(host => host.name).filter(Boolean)-}-export function CodexAgentAssignment({connectionRef,+ hostName,onConnectionRefChange,onModelsChange,disabled = false,@@ -163,29 +163,21 @@ export function CodexAgentAssignment({}}- async function handleRevoke() {- if (!selected) return- const names = assignedHostNames(selected)+ async function handleUnbind() {+ if (!selected || !hostName) returnconst confirmed = await confirm({- title: 'Revoke this ChatGPT subscription?',- message: selected.assignedHostsUnavailable- ? 'The agent assignment list could not be loaded. Revoke still fail-closes every Host that points at this grant.'- : names.length > 0- ? `This subscription is used by ${names.length} agent(s): ${names.join(', ')}. Revoke disconnects all of them.${- selected.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.',- confirmLabel: 'Revoke',+ title: `Remove ${hostName} from this subscription?`,+ message: `${hostName} will stop using "${selected.displayName ?? selected.connectionKey}" 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',})if (!confirmed) returnsetBusy(true)try {- await revokeCodexSubscription(selected.connectionKey)+ await unbindCodexHost(selected.connectionKey, hostName)+ onConnectionRefChange(CODEX_UNASSIGNED_CONNECTION_KEY)await load()} catch (err) {- showToast(err instanceof Error ? err.message : 'Revoke failed', { tone: 'error' })+ showToast(err instanceof Error ? err.message : 'Could not remove agent', { tone: 'error' })} finally {setBusy(false)}@@ -193,7 +185,12 @@ export function CodexAgentAssignment({if (!enabled) return null- const uiStatus = selected ? mapConnectionStatus(selected.status) : 'disconnected'+ 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">@@ -206,8 +203,10 @@ export function CodexAgentAssignment({disabled={disabled || busy}onChange={event => onConnectionRefChange(event.target.value)}>- {!selected && connectionRef ? (- <option value={connectionRef}>{connectionRef} (unavailable)</option>+ {unassigned || (!selected && connectionRef) ? (+ <option value={connectionRef || CODEX_UNASSIGNED_CONNECTION_KEY}>+ {unassigned ? 'No subscription assigned' : `${connectionRef} (unavailable)`}+ </option>) : null}{assignable.map(row => (<option@@ -224,7 +223,7 @@ export function CodexAgentAssignment({<div className="cu-field"><span className="cu-settings-row__label">Status</span><span className={statusTagClass(uiStatus)} data-testid="codex-connection-status">- {statusLabel(uiStatus)}+ {unassigned ? 'No subscription assigned' : statusLabel(uiStatus)}</span></div>{creating ? (@@ -275,11 +274,21 @@ export function CodexAgentAssignment({<buttontype="button"className="cu-btn cu-btn--ghost"- onClick={() => void handleRevoke()}- disabled={disabled || busy || !selected || selected.status === 'revoked'}+ onClick={() => void handleUnbind()}+ disabled={+ disabled ||+ busy ||+ !selected ||+ !hostName ||+ selected.status === 'revoked' ||+ unassigned+ }>- Revoke+ 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">diff --git a/control-ui/components/CodexSubscriptionHub/index.tsx b/control-ui/components/CodexSubscriptionHub/index.tsxnew file mode 100644index 000000000..1d2230f99--- /dev/null+++ b/control-ui/components/CodexSubscriptionHub/index.tsx@@ -0,0 +1,377 @@+'use client'++import React, { useCallback, useEffect, useState } from 'react'+import { CONTROL_ROUTES } from '@constants/routes'+import {+ type CodexAssignableHost,+ type CodexSubscriptionConnectionView,+ bindCodexHost,+ createCodexSubscriptionConnection,+ listCodexSubscriptionFleet,+ pollCodexDevice,+ revokeCodexSubscription,+ startCodexDeviceConnect,+ syncCodexSubscriptionCatalog,+ unbindCodexHost,+} from '@lib/codexSubscription'+import {+ type CodexSubscriptionCapability,+ isCodexSubscriptionUiEnabled,+ loadCodexSubscriptionCapability,+} from '@lib/codexSubscriptionFeature'+import {+ mapConnectionStatus,+ statusLabel,+ statusTagClass,+} from '../CodexSubscriptionConnection/types'+import { useConfirmDialog } from '../ConfirmDialog'+import { SecretsScopeTabs } from '../SecretsScopeTabs'+import { TablePanelHeader } from '../TablePanelHeader'+import { useToast } from '../Toast'++function grantLabel(row: CodexSubscriptionConnectionView): string {+ return row.displayName || row.connectionKey+}++function otherGrantLabel(+ connections: CodexSubscriptionConnectionView[],+ connectionRef: string+): string {+ return connections.find(row => row.connectionKey === connectionRef)?.displayName || connectionRef+}++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 [busyKey, setBusyKey] = useState<string | null>(null)+ const [userCode, setUserCode] = useState<string | null>(null)+ const [verificationUri, setVerificationUri] = useState<string | null>(null)+ const enabled = isCodexSubscriptionUiEnabled(capability)++ useEffect(() => {+ void loadCodexSubscriptionCapability().then(setCapability)+ }, [])++ const load = useCallback(async () => {+ if (!enabled) return+ const fleet = await listCodexSubscriptionFleet()+ setConnections(fleet.connections)+ setAssignableHosts(fleet.assignableHosts)+ setHostsUnavailable(fleet.assignableHostsUnavailable)+ }, [enabled])++ useEffect(() => {+ if (capability === null) return+ if (!enabled) {+ setLoading(false)+ return+ }+ setLoading(true)+ setError('')+ void load()+ .catch(err => {+ setError(err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions')+ })+ .finally(() => setLoading(false))+ }, [capability, enabled, load])++ async function handleCreate() {+ setBusyKey('create')+ try {+ await createCodexSubscriptionConnection({+ displayName: displayName.trim() || 'Codex subscription',+ })+ setDisplayName('')+ setCreating(false)+ await load()+ } catch (err) {+ showToast(err instanceof Error ? err.message : 'Could not create subscription', {+ tone: 'error',+ })+ } finally {+ setBusyKey(null)+ }+ }++ async function handleConnect(row: CodexSubscriptionConnectionView) {+ setBusyKey(row.connectionKey)+ try {+ const started = await startCodexDeviceConnect(+ row.status === 'connected' ? 'reconnect' : 'connect',+ row.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, row.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 {+ setBusyKey(null)+ }+ }++ async function handleSync(row: CodexSubscriptionConnectionView) {+ setBusyKey(row.connectionKey)+ try {+ await syncCodexSubscriptionCatalog(row.connectionKey)+ await load()+ showToast(`Catalog synced: ${grantLabel(row)}`, { tone: 'success' })+ } catch (err) {+ showToast(err instanceof Error ? err.message : 'Catalog sync failed', { tone: 'error' })+ } 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, use Remove agent on its row.${+ 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, use Remove agent.',+ confirmLabel: 'Revoke subscription',+ })+ if (!confirmed) return+ setBusyKey(row.connectionKey)+ try {+ await revokeCodexSubscription(row.connectionKey)+ await load()+ } catch (err) {+ showToast(err instanceof Error ? err.message : 'Revoke failed', { tone: 'error' })+ } finally {+ setBusyKey(null)+ }+ }++ async function handleUnbind(row: CodexSubscriptionConnectionView, hostName: string) {+ 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',+ })+ if (!confirmed) return+ setBusyKey(row.connectionKey)+ try {+ await unbindCodexHost(row.connectionKey, hostName)+ await load()+ } catch (err) {+ showToast(err instanceof Error ? err.message : 'Could not remove agent', { tone: 'error' })+ } finally {+ setBusyKey(null)+ }+ }++ async function handleAssign(row: CodexSubscriptionConnectionView, host: CodexAssignableHost) {+ if (host.connectionRef !== 'unassigned' && host.connectionRef !== row.connectionKey) {+ const confirmed = await confirm({+ title: `Switch ${host.name} to this subscription?`,+ message: `${host.name} currently uses "${otherGrantLabel(connections, host.connectionRef)}". Assign it to "${grantLabel(row)}"?`,+ confirmLabel: 'Assign agent',+ })+ if (!confirmed) return+ }+ setBusyKey(row.connectionKey)+ try {+ await bindCodexHost(row.connectionKey, host.name)+ await load()+ } catch (err) {+ showToast(err instanceof Error ? err.message : 'Could not assign agent', { tone: 'error' })+ } finally {+ setBusyKey(null)+ }+ }++ return (+ <div className="cu-card" data-testid="codex-subscription-hub">+ {confirmDialog}+ <TablePanelHeader+ title="Subscriptions"+ subtitle="Manage ChatGPT subscriptions and every agent that can use them."+ 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. Assign and Remove agent 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>+ ) : null}+ {!enabled ? (+ <div className="cu-empty">ChatGPT subscriptions are not enabled on this cluster.</div>+ ) : loading ? (+ <div className="cu-empty">Loading subscriptions…</div>+ ) : connections.length === 0 && !creating ? (+ <div className="cu-empty">+ No ChatGPT subscriptions yet. Add a subscription to let agents use ChatGPT models.+ </div>+ ) : (+ <div className="cu-form-stack" style={{ padding: '1rem' }}>+ {creating ? (+ <div className="cu-field">+ <label htmlFor="codex-hub-new-name">New subscription name</label>+ <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"+ onClick={() => void handleCreate()}+ disabled={busyKey !== null}+ >+ Create+ </button>+ </div>+ ) : null}+ {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 busy = busyKey === row.connectionKey+ return (+ <section+ key={row.connectionKey}+ className="cu-llm-config__block"+ data-testid={`codex-hub-grant-${row.connectionKey}`}+ >+ <div className="cu-settings-row">+ <strong>{grantLabel(row)}</strong>+ <span className={statusTagClass(uiStatus)}>{statusLabel(uiStatus)}</span>+ </div>+ <div className="cu-form-actions">+ <button+ type="button"+ className="cu-btn cu-btn--primary"+ onClick={() => void handleConnect(row)}+ disabled={busy || row.status === 'revoked'}+ >+ Sign in with ChatGPT+ </button>+ <button+ type="button"+ className="cu-btn cu-btn--ghost"+ onClick={() => void handleSync(row)}+ disabled={busy || row.status !== 'connected'}+ >+ Sync catalog+ </button>+ <button+ type="button"+ className="cu-btn cu-btn--ghost"+ onClick={() => void handleRevoke(row)}+ disabled={busy || row.status === 'revoked'}+ >+ Revoke subscription+ </button>+ </div>+ <h3>Assigned</h3>+ {assigned.length === 0 ? (+ <p>No agents use this subscription.</p>+ ) : (+ <ul>+ {assigned.map(host => (+ <li key={host.name}>+ <a href={CONTROL_ROUTES.agents.detail(host.name)}>+ {host.displayName || host.name}+ </a>{' '}+ <button+ type="button"+ className="cu-btn cu-btn--ghost cu-btn--sm"+ onClick={() => void handleUnbind(row, host.name)}+ disabled={busy || hostsUnavailable}+ >+ Remove agent+ </button>+ </li>+ ))}+ </ul>+ )}+ <h3>Available</h3>+ {available.length === 0 ? (+ <p>No other ChatGPT-capable agents are available.</p>+ ) : (+ <ul>+ {available.map(host => (+ <li key={host.name}>+ {host.displayName || host.name}+ {host.connectionRef === 'unassigned'+ ? ' (no subscription assigned)'+ : ` (${otherGrantLabel(connections, host.connectionRef)})`}{' '}+ <button+ type="button"+ className="cu-btn cu-btn--ghost cu-btn--sm"+ onClick={() => void handleAssign(row, host)}+ disabled={busy || hostsUnavailable || row.status === 'revoked'}+ >+ Assign+ </button>+ </li>+ ))}+ </ul>+ )}+ </section>+ )+ })}+ </div>+ )}+ </div>+ )+}diff --git a/control-ui/components/SecretsScopeTabs/index.tsx b/control-ui/components/SecretsScopeTabs/index.tsxnew file mode 100644index 000000000..586e59818--- /dev/null+++ b/control-ui/components/SecretsScopeTabs/index.tsx@@ -0,0 +1,22 @@+'use client'++import { CONTROL_ROUTES } from '@constants/routes'+import { TabBar } from '../TabBar'++export type SecretsTabScope = 'llm' | 'mcp' | 'recipe' | 'subscription'++export function SecretsScopeTabs({ activeValue }: { activeValue: SecretsTabScope }) {+ return (+ <TabBar<SecretsTabScope>+ ariaLabel="Secret scopes"+ activeValue={activeValue}+ className="cu-tabs--flush"+ options={[+ { 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 4a7f19b49..a6bd2ce94 100644--- a/control-ui/components/SecretsTable.tsx+++ b/control-ui/components/SecretsTable.tsx@@ -21,9 +21,9 @@ import { collectWorkflowRecipeSecretRefs } from '../lib/workflowRecipeSecretRefsimport { useConfirmDialog } from './ConfirmDialog'import { LlmCredentialFields } from './LlmCredentialFields'import { LlmProviderIcon } from './LlmProviderIcon'+import { SecretsScopeTabs } from './SecretsScopeTabs'import { SectionSearchInput } from './SectionSearchInput'import { IconKey } from './Sidebar/icons'-import { TabBar } from './TabBar'import { TablePanelHeader } from './TablePanelHeader'import { useToast } from './Toast'import { IconPencil, IconRefresh, IconX } from './icons'@@ -571,16 +571,7 @@ export function SecretsTable({/><div className="cu-card__body cu-card__body--auto cu-secrets-strip">- <TabBar<SecretScope>- ariaLabel="Secret scopes"- activeValue={scope}- className="cu-tabs--flush"- options={[- { 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' },- ]}- />+ <SecretsScopeTabs activeValue={scope} /></div>{scope === 'llm' && error && (@@ -636,7 +627,16 @@ export function SecretsTable({</div>) : scope === 'llm' && filteredRows.length === 0 ? (<div className="cu-empty">- {normalizedLlmSearch ? 'No LLM secrets match this search.' : 'No LLM secrets found.'}+ {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>+ </>+ )}</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.tsxindex b9ec6770d..0c6950f38 100644--- a/control-ui/components/__tests__/CodexAgentAssignment.test.tsx+++ b/control-ui/components/__tests__/CodexAgentAssignment.test.tsx@@ -6,8 +6,8 @@ import {listCodexConnectionModels,listCodexSubscriptionConnections,pollCodexDevice,- revokeCodexSubscription,startCodexDeviceConnect,+ unbindCodexHost,} from '@lib/codexSubscription'import { CodexAgentAssignment } from '../CodexAgentAssignment'import { ToastProvider } from '../Toast'@@ -36,7 +36,7 @@ vi.mock('@lib/codexSubscription', async importOriginal => {createCodexSubscriptionConnection: vi.fn(),startCodexDeviceConnect: vi.fn(),pollCodexDevice: vi.fn(),- revokeCodexSubscription: vi.fn(),+ unbindCodexHost: vi.fn(),syncCodexSubscriptionCatalog: vi.fn(),}})@@ -67,6 +67,7 @@ function renderAssignment(connectionRef: string, onConnectionRefChange = vi.fn()<ToastProvider><CodexAgentAssignmentconnectionRef={connectionRef}+ hostName="chatllm"onConnectionRefChange={onConnectionRefChange}/></ToastProvider>@@ -172,20 +173,35 @@ describe('CodexAgentAssignment', () => {expect(screen.queryByTestId('codex-device-code')).not.toBeInTheDocument()})- it('surfaces a revoke API error instead of swallowing it', async () => {+ 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('unbinds this agent without calling revoke', async () => {vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([connection({ connectionKey: 'team-plus', displayName: 'Team Plus' }),])confirmMock.mockResolvedValue(true)- vi.mocked(revokeCodexSubscription).mockRejectedValue(new Error('revoke exploded'))+ vi.mocked(unbindCodexHost).mockResolvedValue({ host: 'chatllm', connectionRef: 'unassigned' })const { onConnectionRefChange } = renderAssignment('team-plus')await waitFor(() => {- expect(screen.getByRole('button', { name: 'Revoke' })).toBeEnabled()+ expect(screen.getByRole('button', { name: 'Remove from this agent' })).toBeEnabled()})- fireEvent.click(screen.getByRole('button', { name: 'Revoke' }))+ fireEvent.click(screen.getByRole('button', { name: 'Remove from this agent' }))await waitFor(() => {- expect(screen.getByText('revoke exploded')).toBeInTheDocument()+ expect(unbindCodexHost).toHaveBeenCalledWith('team-plus', 'chatllm')})- expect(onConnectionRefChange).not.toHaveBeenCalled()+ expect(onConnectionRefChange).toHaveBeenCalledWith('unassigned')})})diff --git a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsxnew file mode 100644index 000000000..debc6d778--- /dev/null+++ b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx@@ -0,0 +1,207 @@+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 {+ bindCodexHost,+ createCodexSubscriptionConnection,+ listCodexSubscriptionFleet,+ revokeCodexSubscription,+ unbindCodexHost,+} from '@lib/codexSubscription'+import { CodexSubscriptionHub } from '../CodexSubscriptionHub'+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,+ listCodexSubscriptionFleet: vi.fn(),+ listCodexSubscriptionConnections: vi.fn(),+ createCodexSubscriptionConnection: vi.fn(),+ startCodexDeviceConnect: vi.fn(),+ pollCodexDevice: vi.fn(),+ syncCodexSubscriptionCatalog: vi.fn(),+ revokeCodexSubscription: vi.fn(),+ unbindCodexHost: vi.fn(),+ bindCodexHost: 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,+ }+}++describe('CodexSubscriptionHub', () => {+ beforeEach(() => {+ confirmMock.mockReset()+ vi.mocked(listCodexSubscriptionFleet).mockResolvedValue({+ connections: [connection({ connectionKey: 'codex-aaa', displayName: 'Team A' })],+ assignableHosts: [+ { name: 'chatllm', connectionRef: 'codex-aaa' },+ { name: 'writer', connectionRef: 'unassigned' },+ ],+ assignableHostsUnavailable: false,+ })+ })++ afterEach(() => {+ cleanup()+ vi.clearAllMocks()+ })++ it('creates a subscription from the hub CTA', async () => {+ vi.mocked(createCodexSubscriptionConnection).mockResolvedValue(+ connection({ connectionKey: 'codex-bbb', displayName: 'New team' })+ )+ render(+ <ToastProvider>+ <CodexSubscriptionHub />+ </ToastProvider>+ )+ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'Add subscription' })).toBeInTheDocument()+ })+ fireEvent.click(screen.getByRole('button', { name: 'Add subscription' }))+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))+ await waitFor(() => {+ expect(createCodexSubscriptionConnection).toHaveBeenCalled()+ })+ expect(revokeCodexSubscription).not.toHaveBeenCalled()+ })++ it('shows Assigned and Available fleet rows for a grant', async () => {+ render(+ <ToastProvider>+ <CodexSubscriptionHub />+ </ToastProvider>+ )+ await waitFor(() => {+ expect(screen.getByRole('heading', { name: 'Assigned' })).toBeInTheDocument()+ })+ expect(screen.getByRole('link', { name: 'chatllm' })).toBeInTheDocument()+ expect(screen.getByRole('heading', { name: 'Available' })).toBeInTheDocument()+ expect(screen.getByText(/writer/)).toBeInTheDocument()+ expect(screen.getByText(/no subscription assigned/i)).toBeInTheDocument()+ })++ it('assigns an available agent without revoking', async () => {+ vi.mocked(bindCodexHost).mockResolvedValue({ host: 'writer', connectionRef: 'codex-aaa' })+ render(+ <ToastProvider>+ <CodexSubscriptionHub />+ </ToastProvider>+ )+ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'Assign' })).toBeInTheDocument()+ })+ fireEvent.click(screen.getByRole('button', { name: 'Assign' }))+ await waitFor(() => {+ expect(bindCodexHost).toHaveBeenCalledWith('codex-aaa', 'writer')+ })+ 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>+ )+ await waitFor(() => {+ expect(screen.getAllByRole('button', { name: 'Assign' }).length).toBeGreaterThan(0)+ })+ fireEvent.click(screen.getAllByRole('button', { name: 'Assign' })[0])+ await waitFor(() => {+ expect(confirmMock).toHaveBeenCalledWith(+ expect.objectContaining({+ title: 'Switch chatllm to this subscription?',+ })+ )+ })+ expect(bindCodexHost).toHaveBeenCalledWith('codex-aaa', 'chatllm')+ expect(revokeCodexSubscription).not.toHaveBeenCalled()+ })++ 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' })).toBeInTheDocument()+ })+ fireEvent.click(screen.getByRole('button', { name: 'Remove agent' }))+ await waitFor(() => {+ expect(unbindCodexHost).toHaveBeenCalledWith('codex-aaa', 'chatllm')+ })+ expect(revokeCodexSubscription).not.toHaveBeenCalled()+ })++ it('revokes only from the hub danger action', async () => {+ confirmMock.mockResolvedValue(true)+ vi.mocked(revokeCodexSubscription).mockResolvedValue(+ connection({ connectionKey: 'codex-aaa', displayName: 'Team A', status: 'revoked' })+ )+ render(+ <ToastProvider>+ <CodexSubscriptionHub />+ </ToastProvider>+ )+ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'Revoke subscription' })).toBeInTheDocument()+ })+ fireEvent.click(screen.getByRole('button', { name: 'Revoke subscription' }))+ await waitFor(() => {+ expect(revokeCodexSubscription).toHaveBeenCalledWith('codex-aaa')+ })+ })+})diff --git a/control-ui/components/__tests__/SecretsTable.test.tsx b/control-ui/components/__tests__/SecretsTable.test.tsxindex 00b7284a1..5cb6ecce9 100644--- a/control-ui/components/__tests__/SecretsTable.test.tsx+++ b/control-ui/components/__tests__/SecretsTable.test.tsx@@ -504,3 +504,25 @@ describe('SecretsTable — recipe pending refs', () => {expect(mockPush).toHaveBeenCalledWith('/secrets/recipe/ui-creds/edit?namespace=sandbox-ui')})})++describe('SecretsTable — LLM empty state', () => {+ it('links ChatGPT subscriptions to the Subscription hub', async () => {+ rtlRender(+ <ToastProvider>+ <SecretsTable+ activeScope="llm"+ items={[]}+ onChanged={async () => {}}+ onCreateLlmSecret={() => {}}+ onCreateMcpSecret={() => {}}+ onCreateRecipeSecret={() => {}}+ onCreateRecipeSecretFor={() => {}}+ />+ </ToastProvider>+ )+ const link = await screen.findByRole('link', {+ name: 'ChatGPT subscriptions are managed in the Subscription tab.',+ })+ expect(link).toHaveAttribute('href', '/secrets/subscription')+ })+})diff --git a/control-ui/lib/__tests__/routes.test.ts b/control-ui/lib/__tests__/routes.test.tsindex 31450dba9..1336f5d9a 100644--- a/control-ui/lib/__tests__/routes.test.ts+++ b/control-ui/lib/__tests__/routes.test.ts@@ -31,4 +31,8 @@ describe('CONTROL_ROUTES', () => {it('does not expose an LLM Models Codex subscription owner path', () => {expect('codexSubscription' in CONTROL_ROUTES.llmModels).toBe(false)})++ it('exposes the Secrets Subscription hub path', () => {+ expect(CONTROL_ROUTES.secrets.subscription).toBe('/secrets/subscription')+ })})diff --git a/control-ui/lib/codexSubscription.ts b/control-ui/lib/codexSubscription.tsindex 10f49906b..a7a58d5ec 100644--- a/control-ui/lib/codexSubscription.ts+++ b/control-ui/lib/codexSubscription.ts@@ -15,6 +15,14 @@ export type CodexOAuthIntent = 'connect' | 'reconnect' | 'replace'export type CodexAssignedHost = { name: string }+export type CodexAssignableHost = {+ name: string+ connectionRef: string+ displayName?: string+}++export const CODEX_UNASSIGNED_CONNECTION_KEY = 'unassigned'+export type CodexSubscriptionConnectionView = {id?: stringconnectionKey: string@@ -214,13 +222,73 @@ export function sanitizeCodexCatalogSync(raw: unknown): CodexCatalogSyncView {}}+function sanitizeAssignableHost(raw: unknown): CodexAssignableHost | null {+ if (!isPlainObject(raw)) return null+ const name = pickString(raw.name)+ const connectionRef = pickString(raw.connectionRef)+ if (!name || !connectionRef) return null+ return { name, connectionRef, displayName: pickString(raw.displayName) ?? name }+}+export async function listCodexSubscriptionConnections(): Promise<CodexSubscriptionConnectionView[]> {+ const fleet = await listCodexSubscriptionFleet()+ return fleet.connections+}++export async function listCodexSubscriptionFleet(): Promise<{+ connections: CodexSubscriptionConnectionView[]+ assignableHosts: CodexAssignableHost[]+ assignableHostsUnavailable: boolean+}> {const raw = (await apiGet(`${CODEX_SUBSCRIPTION_API_BASE}/connections`)) as {connections?: unknown+ assignableHosts?: unknown+ assignableHostsUnavailable?: unknown+ }+ const connections = Array.isArray(raw.connections)+ ? raw.connections.map(sanitizeCodexConnection)+ : []+ return {+ connections,+ assignableHosts: Array.isArray(raw.assignableHosts)+ ? raw.assignableHosts+ .map(sanitizeAssignableHost)+ .filter((row): row is CodexAssignableHost => Boolean(row))+ : [],+ assignableHostsUnavailable:+ raw.assignableHostsUnavailable === true ||+ connections.some(row => row.assignedHostsUnavailable === true),+ }+}++export async function unbindCodexHost(+ connectionKey: string,+ hostRef: string+): Promise<{ host: string; connectionRef: string }> {+ const raw = (await apiSend(+ 'POST',+ `${CODEX_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}/hosts/${encodeURIComponent(hostRef)}/unbind`+ )) as { host?: unknown; connectionRef?: unknown }+ return {+ host: pickString(raw.host) ?? hostRef,+ connectionRef: pickString(raw.connectionRef) ?? CODEX_UNASSIGNED_CONNECTION_KEY,+ }+}++export async function bindCodexHost(+ connectionKey: string,+ hostRef: string+): Promise<{ host: string; connectionRef: string }> {+ const raw = (await apiSend(+ 'POST',+ `${CODEX_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}/hosts/${encodeURIComponent(hostRef)}/bind`+ )) as { host?: unknown; connectionRef?: unknown }+ return {+ host: pickString(raw.host) ?? hostRef,+ connectionRef: pickString(raw.connectionRef) ?? connectionKey,}- return Array.isArray(raw.connections) ? raw.connections.map(sanitizeCodexConnection) : []}export async function createCodexSubscriptionConnection(input: {diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 6a2c37b1d..2ec4fe8e5 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.453",+ "version": "0.1.454","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.453",+ "version": "0.1.454","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 5d0f54fc2..1d989a4b6 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.453",+ "version": "0.1.454","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/scripts/tests/test-codex-subscription-t0.sh b/scripts/tests/test-codex-subscription-t0.shindex bdd90aa1b..fafc2fb55 100755--- a/scripts/tests/test-codex-subscription-t0.sh+++ b/scripts/tests/test-codex-subscription-t0.sh@@ -156,7 +156,10 @@ run_group "control-api" "control-api" \"test/codexSubscriptionRedirectUri.test.ts" \"test/routes.admin.codexSubscription.test.ts" \"test/routes.auth.codexSubscriptionCallback.test.ts" \+ "test/routes.mcp-host.llmProviderAttempts.test.ts" \+ "test/hostSpecValidation.codexSubscription.test.ts" \"test/llmProviders.test.ts" \+ "test/services.codexSubscriptionConnection.test.ts" \"test/services.codexSubscriptionOAuth.test.ts" \"test/services.codexSubscriptionCatalog.test.ts" \"test/services.llmProviderAttemptAuthorizer.test.ts" \@@ -189,7 +192,8 @@ run_group "workflow-recipes" "workflow-recipes" \"src/workflow/networkPolicyFactory.codex.test.ts"run_group "control-ui" "control-ui" \- "components/__tests__/CodexSubscriptionConnection.test.tsx" \+ "components/__tests__/CodexAgentAssignment.test.tsx" \+ "components/__tests__/CodexSubscriptionHub.test.tsx" \"components/__tests__/HostWizard.test.tsx" \"components/__tests__/RecipeEditor.test.tsx"diff --git a/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.tsindex 4ea716153..8b7032526 100644--- a/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts+++ b/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts@@ -9,6 +9,15 @@ 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 ({+ 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)+ })+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 })diff --git a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.tsindex 1e7ab1903..33153b6cf 100644--- a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts+++ b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts@@ -1,10 +1,11 @@/**- * Codex subscription — assign, connect, sync, reuse, and revoke from the- * agent model page.+ * Codex subscription — assign/unbind on the agent model tab; create, assign,+ * and revoke from Secrets → Subscription.** Guardian: prove the route, not the destination. ChatGPT OAuth is the only- * mocked external boundary. Happy path starts at `/` and clicks through Agents.- * Direct `goto` of an agent model tab is not the happy-path entry.+ * mocked external boundary. Happy path starts at `/` and clicks through the+ * sidebar. Direct `goto` of an agent model tab or `/secrets/subscription` is+ * not the happy-path entry.*/import { type Page, expect, test } from '@playwright/test'import { controlApi } from '../helpers/api-client'@@ -92,6 +93,14 @@ function subscriptionPicker(page: Page) {return page.locator('#codex-subscription')}+async function openSecretsSubscription(page: Page) {+ await page.getByRole('link', { name: 'Secrets', exact: true }).click()+ await expect(page).toHaveURL(/\/secrets\/(llm)?$|\/secrets\/llm$/)+ await page.getByRole('tab', { name: 'Subscription' }).click()+ await expect(page).toHaveURL(/\/secrets\/subscription$/)+ await expect(page.getByTestId('codex-subscription-hub')).toBeVisible()+}+async function listConnections(): Promise<CodexConnection[]> {return controlApi.listCodexConnections()}@@ -273,9 +282,7 @@ test.describe('Codex subscription connection', () => {await expect(page.getByRole('option', { name: displayName })).toHaveCount(1)})- test('revoking a shared grant from the agent page fail-closes that key only', async ({- page,- }) => {+ test('agent models can unbind this host and never expose grant Revoke', async ({ page }) => {await page.goto('/')await loginControlUiVisible(page)await openAgents(page)@@ -284,7 +291,7 @@ test.describe('Codex subscription connection', () => {await chooseSubscriptionCredential(page)await page.getByRole('button', { name: 'New subscription' }).click()- const displayName = `e2e-revoke-${Date.now().toString(36)}`+ const displayName = `e2e-unbind-${Date.now().toString(36)}`await page.getByLabel('New subscription name').fill(displayName)const created = page.waitForResponse(response =>@@ -296,35 +303,122 @@ test.describe('Codex subscription connection', () => {const createRes = await createdexpect(createRes.ok()).toBe(true)const createdBody = (await createRes.json()) as { connectionKey?: string }- const revokeKey = String(createdBody.connectionKey)+ const grantKey = String(createdBody.connectionKey)- const revoke = page.waitForResponse(+ const put = page.waitForResponse(+ response =>+ new RegExp(`/api/v1/admin/hosts/${firstName}$`).test(new URL(response.url()).pathname) &&+ response.request().method() === 'PUT'+ )+ await page.getByRole('button', { name: 'Save', exact: true }).click()+ expect((await put).ok()).toBe(true)++ await expect(page.getByRole('button', { name: 'Revoke', exact: true })).toHaveCount(0)+ await expect(page.getByRole('link', { name: 'Manage subscription' })).toBeVisible()++ const unbind = page.waitForResponse(response =>new RegExp(- `/api/v1/admin/llm/providers/codex-subscription/connections/${revokeKey}/revoke$`+ `/api/v1/admin/llm/providers/codex-subscription/connections/${grantKey}/hosts/${firstName}/unbind$`).test(new URL(response.url()).pathname) && response.request().method() === 'POST')- await page.getByRole('button', { name: 'Revoke', exact: true }).click()+ await page.getByRole('button', { name: 'Remove from this agent' }).click()await expect(page.getByRole('alertdialog')).toBeVisible()- await expect(page.getByRole('alertdialog')).toContainText(/agent/i)- await page.getByRole('alertdialog').getByRole('button', { name: 'Revoke', exact: true }).click()- const response = await revoke- expect(response.ok(), `revoke must succeed, got ${response.status()}`).toBe(true)- const body = (await response.json()) as { status?: string; connectionKey?: string }- expect(body.status).toBe('revoked')- expect(body.connectionKey).toBe(revokeKey)+ await page.getByRole('alertdialog').getByRole('button', { name: 'Remove agent' }).click()+ const unbindRes = await unbind+ expect(unbindRes.ok(), `unbind must succeed, got ${unbindRes.status()}`).toBe(true)await expect(page).toHaveURL(new RegExp(`/((?:hosts|agents))/${firstName}/model`))- await expect(page.getByTestId('codex-connection-status')).toHaveText(/Revoked/i)- await expect(page.getByRole('button', { name: 'Sync catalog' })).toBeDisabled()+ await expect(page.getByTestId('codex-connection-status')).toHaveText(+ /No subscription assigned/i+ )+ const host = (await controlApi.getHost(firstName)) as {+ spec?: { model?: { connectionRef?: string } }+ }+ expect(host.spec?.model?.connectionRef).toBe('unassigned')const after = await listConnections()- const revoked = after.find(row => row.connectionKey === revokeKey)- expect(revoked?.status).toBe('revoked')- const otherLive = after.find(- row => row.connectionKey !== revokeKey && row.status === 'connected'+ expect(after.find(row => row.connectionKey === grantKey)?.status).not.toBe('revoked')+ })++ test('Secrets Subscription hub creates, assigns, and is the only revoke path', async ({+ page,+ }) => {+ await page.goto('/')+ await loginControlUiVisible(page)+ await openAgents(page)+ await ensureListedAgents(page, 2)+ await openSecretsSubscription(page)++ await page.getByRole('button', { name: 'Add subscription' }).click()+ const displayName = `e2e-hub-${Date.now().toString(36)}`+ await page.getByLabel('New subscription name').fill(displayName)+ const created = page.waitForResponse(+ response =>+ /\/api\/v1\/admin\/llm\/providers\/codex-subscription\/connections$/.test(+ new URL(response.url()).pathname+ ) && response.request().method() === 'POST'+ )+ await page.getByRole('button', { name: 'Create', exact: true }).click()+ const createRes = await created+ expect(createRes.ok()).toBe(true)+ const createdBody = (await createRes.json()) as { connectionKey?: string }+ const grantKey = String(createdBody.connectionKey)+ await expect(page.getByText(displayName)).toBeVisible()++ const grantCard = page.getByTestId(`codex-hub-grant-${grantKey}`)+ await expect(grantCard.getByRole('heading', { name: 'Assigned' })).toBeVisible()+ await expect(grantCard.getByRole('heading', { name: 'Available' })).toBeVisible()+ const assignable = grantCard.getByRole('button', { name: 'Assign' }).first()+ test.skip((await assignable.count()) === 0, 'hub assign requires a second Codex agent')+ const bind = page.waitForResponse(+ response =>+ new RegExp(+ `/api/v1/admin/llm/providers/codex-subscription/connections/${grantKey}/hosts/[^/]+/bind$`+ ).test(new URL(response.url()).pathname) && response.request().method() === 'POST')- if (otherLive) {- expect(otherLive.status).toBe('connected')+ await assignable.click()+ const bindRes = await bind+ expect(bindRes.ok(), `bind must succeed, got ${bindRes.status()}`).toBe(true)+ const bindBody = (await bindRes.json()) as { host?: string; connectionRef?: string }+ expect(bindBody.connectionRef).toBe(grantKey)+ const boundHost = String(bindBody.host)+ const host = (await controlApi.getHost(boundHost)) as {+ spec?: { model?: { connectionRef?: string } }+ }+ expect(host.spec?.model?.connectionRef).toBe(grantKey)++ 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 grantCard.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)+ const afterHost = (await controlApi.getHost(boundHost)) as {+ spec?: { model?: { connectionRef?: string } }+ }+ expect(afterHost.spec?.model?.connectionRef).toBe(grantKey)+ })++ test('LLM secrets empty state links to the Subscription hub', async ({ page }) => {+ await page.goto('/')+ await loginControlUiVisible(page)+ await page.getByRole('link', { name: 'Secrets', exact: true }).click()+ await expect(page).toHaveURL(/\/secrets\/llm$/)+ const link = page.getByRole('link', {+ name: 'ChatGPT subscriptions are managed in the Subscription tab.',+ })+ if (await link.isVisible().catch(() => false)) {+ await link.click()+ await expect(page).toHaveURL(/\/secrets\/subscription$/)+ await expect(page.getByTestId('codex-subscription-hub')).toBeVisible()}})})diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.jsonindex be59c91ac..33ac64ea4 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.29",+ "version": "0.1.30","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-playwright-tests",- "version": "0.1.29",+ "version": "0.1.30","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 36e13f19d..11f4311da 100644--- a/tests/e2e/playwright/package.json+++ b/tests/e2e/playwright/package.json@@ -1,6 +1,6 @@{"name": "clerum-playwright-tests",- "version": "0.1.29",+ "version": "0.1.30","private": true,"description": "Playwright E2E tests for Control UI and Desktop App","scripts": {