Skip to content

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

TypeScript

fix(codex): share Host write admission on bind/unbind

Alfredo Lopezf5b7fa848000
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 179cd8818..fd00bd22d 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.499",
+ "version": "0.1.500",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.499",
+ "version": "0.1.500",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index 3f4430b08..c493a107b 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.499",
+ "version": "0.1.500",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/admin/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.ts
index 9c7458132..d6bc5c9b2 100644
--- a/control-api/src/routes/admin/codexSubscription.ts
+++ b/control-api/src/routes/admin/codexSubscription.ts
@@ -13,7 +13,6 @@ import {
syncCodexSubscriptionCatalog,
} from '../../services/codexSubscriptionCatalog.js'
import {
- CODEX_SUBSCRIPTION_CONNECTION_KEY,
CODEX_UNASSIGNED_CONNECTION_KEY,
CodexSubscriptionInvalidConnectionKeyError,
assertCodexConnectionKey,
@@ -22,7 +21,6 @@ import {
listSafeCodexSubscriptionConnections,
loadCodexSubscriptionSecrets,
normalizeCodexConnectionKey,
- readHostCodexConnectionRef,
} from '../../services/codexSubscriptionConnection.js'
import {
type CodexOAuthDeps,
@@ -40,13 +38,18 @@ import {
isPublicCodexCliClient,
resolveCodexControlUiBaseUrl,
} from '../../services/codexSubscriptionRedirectUri.js'
-import { getModelAllowlistState, isModelAllowed } from '../../services/llmAllowedModels.js'
import { publishAllowedModelsConfigMapAfterGrantChange } from '../../services/llmAllowedModelsConfigMap.js'
+import { K8sConflictError } from '../../services/resourceService.js'
import {
adminCodexReadRateLimits,
adminCodexWriteRateLimits,
} from '../workflows/shared/rateLimit.js'
-import { validateHostSpec } from './hostSpecValidation.js'
+import { createHostValidationDeps, validateHostSpec } from './hostSpecValidation.js'
+import {
+ type HostSpecIncoherenceToleratedEvent,
+ emitHostSpecIncoherenceTolerated,
+} from './hostWriteGateAudit.js'
+import type { StaleModelWarning } from './staleModelWarning.js'
const log = rootLogger.child({ module: 'admin-codex-subscription' })
const BASE = '/admin/llm/providers/codex-subscription'
@@ -134,7 +137,8 @@ function hostModel(spec: unknown): { provider?: string; connectionRef?: string }
function hostConnectionRef(spec: unknown): string | null {
const model = hostModel(spec)
if (!model || model.provider !== 'codex-subscription') return null
- return readHostCodexConnectionRef(model.connectionRef)
+ const raw = typeof model.connectionRef === 'string' ? model.connectionRef.trim() : ''
+ return raw || CODEX_UNASSIGNED_CONNECTION_KEY
}
function assignableHostFromRecord(
@@ -214,7 +218,10 @@ export function createAdminCodexSubscriptionRouter(
hostRef: string,
host: HostRecord,
nextConnectionRef: string
- ): Promise<{ ok: true } | { ok: false; status: number; error: string; message?: string }> {
+ ): Promise<
+ | { ok: true; warnings: StaleModelWarning[] }
+ | { ok: false; status: number; error: string; message?: string; reason?: string }
+ > {
if (!gateway) return { ok: false, status: 503, error: 'hosts_unavailable' }
const spec =
host.spec && typeof host.spec === 'object'
@@ -231,17 +238,14 @@ export function createAdminCodexSubscriptionRouter(
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 },
- }
- )
+ const hostRefId = { namespace: config.hostsNamespace, name: hostRef }
+ const hostTolerations: HostSpecIncoherenceToleratedEvent[] = []
+ const hostWarnings: StaleModelWarning[] = []
+ const issue = await validateHostSpec(spec, createHostValidationDeps(pool), {
+ stored,
+ hostRef: hostRefId,
+ ...(stored !== undefined ? { tolerations: hostTolerations, warnings: hostWarnings } : {}),
+ })
if (issue) {
return {
ok: false,
@@ -262,8 +266,12 @@ export function createAdminCodexSubscriptionRouter(
},
config.hostsNamespace
)
- return { ok: true }
+ for (const event of hostTolerations) emitHostSpecIncoherenceTolerated(event)
+ return { ok: true, warnings: hostWarnings }
} catch (err) {
+ if (err instanceof K8sConflictError) {
+ return { ok: false, status: 409, error: 'conflict', reason: 'resource_changed' }
+ }
log.warn(
{ event: 'codex_host_write_failed', err, hostRef },
'failed to write host connectionRef'
@@ -397,9 +405,7 @@ export function createAdminCodexSubscriptionRouter(
return
}
const db = dbClient()
- const connectionKey = normalizeCodexConnectionKey(
- typeof req.params.key === 'string' ? req.params.key : undefined
- )
+ const connectionKey = keyFromReq(req)
const secrets = await loadCodexSubscriptionSecrets(
db,
deriveOAuthEncryptionKey(config.oauthEncryptionKey),
@@ -598,12 +604,8 @@ export function createAdminCodexSubscriptionRouter(
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
+ // Empty/missing connectionRef is unassigned, never the reserved default grant.
+ const currentRef = storedRef || CODEX_UNASSIGNED_CONNECTION_KEY
if (action === 'unbind') {
if (currentRef === CODEX_UNASSIGNED_CONNECTION_KEY) {
@@ -626,12 +628,14 @@ export function createAdminCodexSubscriptionRouter(
res.status(written.status).json({
error: written.error,
...(written.message ? { message: written.message } : {}),
+ ...(written.reason ? { reason: written.reason } : {}),
})
return
}
res.status(200).json({
host: hostRef,
connectionRef: CODEX_UNASSIGNED_CONNECTION_KEY,
+ ...(written.warnings.length > 0 ? { warnings: written.warnings } : {}),
})
return
}
@@ -645,10 +649,15 @@ export function createAdminCodexSubscriptionRouter(
res.status(written.status).json({
error: written.error,
...(written.message ? { message: written.message } : {}),
+ ...(written.reason ? { reason: written.reason } : {}),
})
return
}
- res.status(200).json({ host: hostRef, connectionRef: connectionKey })
+ res.status(200).json({
+ host: hostRef,
+ connectionRef: connectionKey,
+ ...(written.warnings.length > 0 ? { warnings: written.warnings } : {}),
+ })
})
router.post(
diff --git a/control-api/src/routes/admin/hostSpecValidation.ts b/control-api/src/routes/admin/hostSpecValidation.ts
index b082394ae..5d15131fe 100644
--- a/control-api/src/routes/admin/hostSpecValidation.ts
+++ b/control-api/src/routes/admin/hostSpecValidation.ts
@@ -5,7 +5,9 @@ import {
PROVIDER_CREDENTIAL_SLOTS,
isLlmProviderId,
} from '@clerum/llm-providers'
+import type { DbClient } from '../../db.js'
import { rootLogger } from '../../observability/logger.js'
+import { isCodexAssignmentAllowed } from '../../services/codexSubscriptionCatalog.js'
import {
isCodexUnassignedConnectionKey,
readHostCodexConnectionRef,
@@ -173,6 +175,21 @@ export interface HostSpecValidationDeps {
) => Promise<{ enabled: boolean; stale: boolean } | null>
}
+/**
+ * Shared Host-write deps: Codex assignments check the grant catalog, not the
+ * global allowlist. Bind/unbind and Host PATCH must use this factory so a
+ * second writer cannot drop `connectionRef` or treat it as a DbClient.
+ */
+export function createHostValidationDeps(db: DbClient): HostSpecValidationDeps {
+ return {
+ isModelAllowed: (provider, model, connectionRef) =>
+ provider === 'codex-subscription'
+ ? isCodexAssignmentAllowed(db, connectionRef ?? 'deployment-default', model)
+ : isModelAllowedDefault(provider, model, db),
+ getModelAllowlistState: (provider, model) => getModelAllowlistStateDefault(provider, model, db),
+ }
+}
+
/**
* Per-write context for the no-worsening tolerance (Pieza D). ABSENT on create
* (there is no stored CR, so tolerance can never apply — a fresh spec may not
diff --git a/control-api/src/routes/admin/resources.ts b/control-api/src/routes/admin/resources.ts
index 2da067371..a244c464c 100644
--- a/control-api/src/routes/admin/resources.ts
+++ b/control-api/src/routes/admin/resources.ts
@@ -11,9 +11,7 @@ import { enforceNamespace } from '../../http/namespaceAudit.js'
import { validateCommunicationChannelSpec } from '../../http/validateCommunicationChannelSpec.js'
import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec.js'
import { K8sGateway } from '../../k8s.js'
-import { isCodexAssignmentAllowed } from '../../services/codexSubscriptionCatalog.js'
import { stripHookRefFromHosts } from '../../services/hostGuardrailRefs.js'
-import { getModelAllowlistState, isModelAllowed } from '../../services/llmAllowedModels.js'
import {
K8sConflictError,
K8sNotFoundError,
@@ -32,7 +30,7 @@ import {
} from './communicationChannelSpecHelpers.js'
import { enumerateHostModelReferences } from './hostModelReferences.js'
import { validateHostSecretRef } from './hostSecrets.js'
-import { type HostSpecValidationDeps, validateHostSpec } from './hostSpecValidation.js'
+import { createHostValidationDeps, validateHostSpec } from './hostSpecValidation.js'
import {
type HostSpecIncoherenceToleratedEvent,
emitHostSpecIncoherenceTolerated,
@@ -466,14 +464,8 @@ function hostModelLockNames(spec: unknown): string[] {
// `isModelAllowed` (the fail-closed gate) AND `getModelAllowlistState` (the
// stale-warning lookup) are bound — leaving the latter defaulted would let
// `maybeWarnStale` escape to the global pool under the lock (adenda A3).
-function hostValidationDeps(db: DbClient): HostSpecValidationDeps {
- return {
- isModelAllowed: (provider, model, connectionRef) =>
- provider === 'codex-subscription'
- ? isCodexAssignmentAllowed(db, connectionRef ?? 'deployment-default', model)
- : isModelAllowed(provider, model, db),
- getModelAllowlistState: (provider, model) => getModelAllowlistState(provider, model, db),
- }
+function hostValidationDeps(db: DbClient) {
+ return createHostValidationDeps(db)
}
export function createAdminResourcesRouter(gateway: K8sGateway): Router {
diff --git a/control-api/test/hostSpecValidation.codexSubscription.test.ts b/control-api/test/hostSpecValidation.codexSubscription.test.ts
index 8a174a5ff..2d4361aed 100644
--- a/control-api/test/hostSpecValidation.codexSubscription.test.ts
+++ b/control-api/test/hostSpecValidation.codexSubscription.test.ts
@@ -65,6 +65,38 @@ describe('codex-subscription Host admission', () => {
expect((spec.model as { connectionRef?: string }).connectionRef).toBe('unassigned')
})
+ it('accepts an unbind write that re-validates the stored Host spec', async () => {
+ process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED = 'true'
+ const isModelAllowed = vi.fn().mockResolvedValue(false)
+ const stored = {
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'codex-aaa',
+ },
+ }
+ const spec = {
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'unassigned',
+ },
+ }
+ const tolerations: Array<Record<string, unknown>> = []
+ await expect(
+ validateHostSpec(
+ spec,
+ { isModelAllowed },
+ {
+ stored,
+ hostRef: { namespace: 'mcp-host', name: 'chatllm' },
+ tolerations,
+ }
+ )
+ ).resolves.toBeNull()
+ expect(isModelAllowed).not.toHaveBeenCalled()
+ })
+
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.hostWrite.test.ts b/control-api/test/routes.admin.codexSubscription.hostWrite.test.ts
new file mode 100644
index 000000000..695b45ad2
--- /dev/null
+++ b/control-api/test/routes.admin.codexSubscription.hostWrite.test.ts
@@ -0,0 +1,126 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import express, { type NextFunction, type Request, type Response } from 'express'
+import request from 'supertest'
+import { createCodexCatalogTransportFromEnv } from '../src/services/codexSubscriptionCatalog.js'
+
+const assignment = vi.hoisted(() => ({
+ isCodexAssignmentAllowed: vi.fn(),
+}))
+
+vi.mock('../src/services/codexSubscriptionCatalog.js', async () => {
+ const actual = await vi.importActual('../src/services/codexSubscriptionCatalog.js')
+ return {
+ ...actual,
+ isCodexAssignmentAllowed: assignment.isCodexAssignmentAllowed,
+ }
+})
+
+vi.mock('../src/db.js', () => ({
+ pool: { query: vi.fn() },
+}))
+
+const { config } = await import('../src/config.js')
+const { createAdminCodexSubscriptionRouter } =
+ await import('../src/routes/admin/codexSubscription.js')
+
+function makeGateway() {
+ return {
+ listResource: vi.fn().mockResolvedValue([]),
+ getResource: vi.fn(),
+ updateResource: vi.fn(),
+ llmAllowedModelsConfigMap: () => ({ materialize: async () => {} }),
+ }
+}
+
+function makeAuthedApp(gateway: ReturnType<typeof makeGateway>) {
+ const app = express()
+ app.use(express.json())
+ app.use((req: Request & { adminAuth?: { sub: string } }, _res: Response, next: NextFunction) => {
+ req.adminAuth = { sub: 'admin-1' }
+ next()
+ })
+ app.use(
+ createAdminCodexSubscriptionRouter(createCodexCatalogTransportFromEnv(), gateway as never)
+ )
+ return app
+}
+
+describe('admin Codex bind/unbind host write contract', () => {
+ const originalFlag = process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED
+
+ beforeEach(() => {
+ config.codexSubscriptionEnabled = true
+ process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED = 'true'
+ assignment.isCodexAssignmentAllowed.mockReset()
+ assignment.isCodexAssignmentAllowed.mockResolvedValue(true)
+ })
+
+ afterEach(() => {
+ if (originalFlag === undefined) delete process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED
+ else process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED = originalFlag
+ })
+
+ it('unbinds through the real Host write gate without throwing 500', 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(assignment.isCodexAssignmentAllowed).not.toHaveBeenCalled()
+ expect(gateway.updateResource).toHaveBeenCalled()
+ })
+
+ it('binds through grant-scoped allowlist, not the global table', async () => {
+ const gateway = makeGateway()
+ gateway.getResource.mockResolvedValue({
+ metadata: { name: 'chatllm', resourceVersion: '12' },
+ spec: {
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.6-luna',
+ connectionRef: 'unassigned',
+ },
+ },
+ })
+ gateway.updateResource.mockResolvedValue({})
+ const res = await request(makeAuthedApp(gateway)).post(
+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/hosts/chatllm/bind'
+ )
+ expect(res.status).toBe(200)
+ expect(res.body).toEqual({ host: 'chatllm', connectionRef: 'codex-aaa' })
+ expect(assignment.isCodexAssignmentAllowed).toHaveBeenCalledWith(
+ expect.anything(),
+ 'codex-aaa',
+ 'gpt-5.6-luna'
+ )
+ })
+
+ it('returns 422 when the destination grant does not offer the model', async () => {
+ assignment.isCodexAssignmentAllowed.mockResolvedValue(false)
+ const gateway = makeGateway()
+ gateway.getResource.mockResolvedValue({
+ metadata: { name: 'chatllm' },
+ spec: {
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.6-luna',
+ connectionRef: 'unassigned',
+ },
+ },
+ })
+ const res = await request(makeAuthedApp(gateway)).post(
+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/hosts/chatllm/bind'
+ )
+ expect(res.status).toBe(422)
+ expect(res.body.error).toBe('invalid_host_spec')
+ expect(gateway.updateResource).not.toHaveBeenCalled()
+ })
+})
diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.ts
index 31efed055..13c6d2238 100644
--- a/control-api/test/routes.admin.codexSubscription.test.ts
+++ b/control-api/test/routes.admin.codexSubscription.test.ts
@@ -463,6 +463,10 @@ describe('admin Codex subscription routes', () => {
metadata: { name: 'other' },
spec: { model: { provider: 'openai', name: 'gpt-5.4' } },
},
+ {
+ metadata: { name: 'legacy' },
+ spec: { model: { provider: 'codex-subscription' } },
+ },
])
const res = await request(makeAuthedApp(gateway)).get(
'/admin/llm/providers/codex-subscription/connections'
@@ -470,6 +474,7 @@ describe('admin Codex subscription routes', () => {
expect(res.status).toBe(200)
expect(res.body.assignableHosts).toEqual([
{ name: 'chatllm', connectionRef: 'codex-aaa', displayName: 'chatllm' },
+ { name: 'legacy', connectionRef: 'unassigned', displayName: 'legacy' },
])
})
@@ -556,18 +561,18 @@ describe('admin Codex subscription routes', () => {
expect(oauth.revoke).not.toHaveBeenCalled()
})
- it('rejects bind when the Host connectionRef is empty', async () => {
+ it('binds a Codex host whose connectionRef is missing as unassigned', async () => {
const gateway = makeGateway()
gateway.getResource.mockResolvedValue({
metadata: { name: 'chatllm' },
spec: { model: { provider: 'codex-subscription' } },
})
+ gateway.updateResource.mockResolvedValue({})
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(res.status).toBe(200)
+ expect(res.body).toEqual({ host: 'chatllm', connectionRef: 'codex-aaa' })
expect(oauth.revoke).not.toHaveBeenCalled()
})
diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsx
index 03a164cc1..6f2e1a12c 100644
--- a/control-ui/app/hosts/[name]/page.tsx
+++ b/control-ui/app/hosts/[name]/page.tsx
@@ -119,6 +119,14 @@ export default function HostDetailsPage() {
channels: [] as string[],
stateless: false,
})
+ const savedModelRef = useRef({
+ provider: 'openai' as LlmProvider,
+ modelName: '',
+ connectionRef: CODEX_UNASSIGNED_CONNECTION_KEY,
+ secretRef: '',
+ llmPolicy: undefined as LlmPolicy | undefined,
+ allowedModels: [] as HostAllowedModel[],
+ })
const [providerDraft, setProviderDraft] = useState<LlmProvider>('openai')
// Model options are the operator allowlist (enabled only). The host's saved
// model is always kept selectable even if it fell out of the allowlist
@@ -305,6 +313,19 @@ export default function HostDetailsPage() {
// Hydrate the per-host model subset from the saved spec (Topic 3a); absent
// → [] = unrestricted (offers the full global allowlist per provider).
setAllowedModelsDraft(normalizeAllowedModels(spec.allowedModels))
+ savedModelRef.current = {
+ provider: nextProvider,
+ modelName:
+ currentModel ||
+ resolveDefaultModel(nextProvider, getModelOptions(allowedCatalog, nextProvider)),
+ connectionRef:
+ String(
+ (spec.model as { connectionRef?: string } | undefined)?.connectionRef || ''
+ ).trim() || CODEX_UNASSIGNED_CONNECTION_KEY,
+ secretRef: String(spec.secretRef || ''),
+ llmPolicy: normalizeLlmPolicy(spec.llmPolicy),
+ allowedModels: normalizeAllowedModels(spec.allowedModels),
+ }
// Write-only surfaces reset only when this tab is reloaded or saved.
setLlmKeyDraft({})
setRetireCandidates([])
@@ -404,6 +425,17 @@ export default function HostDetailsPage() {
setStatelessDraft(saved.stateless)
}
+ function resetModelDrafts() {
+ const saved = savedModelRef.current
+ setProviderDraft(saved.provider)
+ setModelNameDraft(saved.modelName)
+ setConnectionRefDraft(saved.connectionRef)
+ setSecretRefDraft(saved.secretRef)
+ setLlmPolicyDraft(saved.llmPolicy)
+ setAllowedModelsDraft(saved.allowedModels)
+ setLlmKeyDraft({})
+ }
+
async function saveHost(): Promise<boolean> {
const nextHostName = hostNameDraft.trim()
if (!nextHostName) return false
@@ -944,7 +976,10 @@ export default function HostDetailsPage() {
<button
type="button"
className="cu-btn cu-btn--ghost cu-btn--sm"
- onClick={() => setEditingModel(false)}
+ onClick={() => {
+ resetModelDrafts()
+ setEditingModel(false)
+ }}
disabled={busy}
>
Cancel
@@ -968,7 +1003,10 @@ export default function HostDetailsPage() {
<button
type="button"
className="cu-btn cu-btn--ghost cu-btn--sm"
- onClick={() => setEditingModel(true)}
+ onClick={() => {
+ resetModelDrafts()
+ setEditingModel(true)
+ }}
disabled={busy}
>
Edit
@@ -1095,6 +1133,13 @@ export default function HostDetailsPage() {
connectionRef={connectionRefDraft}
hostName={routeName}
onConnectionRefChange={setConnectionRefDraft}
+ onAssignmentPersisted={connectionRef => {
+ savedModelRef.current = {
+ ...savedModelRef.current,
+ connectionRef,
+ }
+ setConnectionRefDraft(connectionRef)
+ }}
onModelsChange={setCodexModels}
disabled={busy}
/>
diff --git a/control-ui/components/CodexAgentAssignment/index.tsx b/control-ui/components/CodexAgentAssignment/index.tsx
index 57e367f75..8f914f352 100644
--- a/control-ui/components/CodexAgentAssignment/index.tsx
+++ b/control-ui/components/CodexAgentAssignment/index.tsx
@@ -13,7 +13,6 @@ import {
pollCodexDevice,
startCodexDeviceConnect,
syncCodexSubscriptionCatalog,
- unbindCodexHost,
} from '@lib/codexSubscription'
import {
type CodexSubscriptionCapability,
@@ -30,6 +29,7 @@ export type CodexAgentAssignmentProps = {
connectionRef: string
hostName?: string
onConnectionRefChange: (connectionKey: string) => void
+ onAssignmentPersisted?: (connectionKey: string) => void
onModelsChange?: (models: string[]) => void
disabled?: boolean
}
@@ -38,6 +38,7 @@ export function CodexAgentAssignment({
connectionRef,
hostName,
onConnectionRefChange,
+ onAssignmentPersisted,
onModelsChange,
disabled = false,
}: CodexAgentAssignmentProps) {
@@ -167,20 +168,11 @@ export function CodexAgentAssignment({
if (!selected || !hostName) return
const confirmed = await confirm({
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.`,
+ 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
- setBusy(true)
- try {
- await unbindCodexHost(selected.connectionKey, hostName)
- onConnectionRefChange(CODEX_UNASSIGNED_CONNECTION_KEY)
- await load()
- } catch (err) {
- showToast(err instanceof Error ? err.message : 'Could not remove agent', { tone: 'error' })
- } finally {
- setBusy(false)
- }
+ onConnectionRefChange(CODEX_UNASSIGNED_CONNECTION_KEY)
}
if (!enabled) return null
diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsx
index 7450f31ef..bd3fae442 100644
--- a/control-ui/components/HostWizard/index.tsx
+++ b/control-ui/components/HostWizard/index.tsx
@@ -267,7 +267,13 @@ function isStepValid(
// catalog model and no Secret. Any static primary/fallback still requires
// the exact credential slots (existing Secret or a complete new one).
if (!state.modelName.trim()) return false
- if (state.provider === 'codex-subscription' && !state.connectionRef?.trim()) return false
+ if (
+ state.provider === 'codex-subscription' &&
+ (!state.connectionRef?.trim() ||
+ state.connectionRef.trim() === CODEX_UNASSIGNED_CONNECTION_KEY)
+ ) {
+ return false
+ }
if (!llmChainRequiresSecret(state.provider, state.llmPolicy?.fallbacks)) return true
// New secret: the PRIMARY provider must be usable (asymmetric gate — a
// fallback missing its key only warns). Cross-slot mistakes (half Bedrock
@@ -644,6 +650,13 @@ export function HostWizard({
if (step === 1 && contextMode === 'new' && !contextName.trim())
return 'Context name is required.'
if (step === 2 && !modelName.trim()) return 'Model name is required.'
+ if (
+ step === 2 &&
+ provider === 'codex-subscription' &&
+ (!connectionRef.trim() || connectionRef === CODEX_UNASSIGNED_CONNECTION_KEY)
+ ) {
+ 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 === 'new' && !toKebabCase(newSecretName)) {
@@ -676,6 +689,7 @@ export function HostWizard({
llmPolicy,
provider,
modelName,
+ connectionRef,
selectedUserIds,
selectedTeamIds,
])
diff --git a/control-ui/components/__tests__/CodexAgentAssignment.test.tsx b/control-ui/components/__tests__/CodexAgentAssignment.test.tsx
index 0c6950f38..2ac27a284 100644
--- a/control-ui/components/__tests__/CodexAgentAssignment.test.tsx
+++ b/control-ui/components/__tests__/CodexAgentAssignment.test.tsx
@@ -7,7 +7,6 @@ import {
listCodexSubscriptionConnections,
pollCodexDevice,
startCodexDeviceConnect,
- unbindCodexHost,
} from '@lib/codexSubscription'
import { CodexAgentAssignment } from '../CodexAgentAssignment'
import { ToastProvider } from '../Toast'
@@ -36,7 +35,6 @@ vi.mock('@lib/codexSubscription', async importOriginal => {
createCodexSubscriptionConnection: vi.fn(),
startCodexDeviceConnect: vi.fn(),
pollCodexDevice: vi.fn(),
- unbindCodexHost: vi.fn(),
syncCodexSubscriptionCatalog: vi.fn(),
}
})
@@ -60,15 +58,21 @@ function connection(
}
}
-function renderAssignment(connectionRef: string, onConnectionRefChange = vi.fn()) {
+function renderAssignment(
+ connectionRef: string,
+ onConnectionRefChange = vi.fn(),
+ onAssignmentPersisted = vi.fn()
+) {
return {
onConnectionRefChange,
+ onAssignmentPersisted,
...render(
<ToastProvider>
<CodexAgentAssignment
connectionRef={connectionRef}
hostName="chatllm"
onConnectionRefChange={onConnectionRefChange}
+ onAssignmentPersisted={onAssignmentPersisted}
/>
</ToastProvider>
),
@@ -188,20 +192,19 @@ describe('CodexAgentAssignment', () => {
)
})
- it('unbinds this agent without calling revoke', async () => {
+ 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)
- vi.mocked(unbindCodexHost).mockResolvedValue({ host: 'chatllm', connectionRef: 'unassigned' })
- const { onConnectionRefChange } = renderAssignment('team-plus')
+ const { onConnectionRefChange, onAssignmentPersisted } = 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(unbindCodexHost).toHaveBeenCalledWith('team-plus', 'chatllm')
+ expect(onConnectionRefChange).toHaveBeenCalledWith('unassigned')
})
- expect(onConnectionRefChange).toHaveBeenCalledWith('unassigned')
+ expect(onAssignmentPersisted).not.toHaveBeenCalled()
})
})
diff --git a/control-ui/components/__tests__/HostWizard.test.tsx b/control-ui/components/__tests__/HostWizard.test.tsx
index 21610f5ad..7a514fc09 100644
--- a/control-ui/components/__tests__/HostWizard.test.tsx
+++ b/control-ui/components/__tests__/HostWizard.test.tsx
@@ -23,7 +23,17 @@ import { ToastProvider } from '../Toast'
*/
vi.mock('../CodexAgentAssignment', () => ({
- CodexAgentAssignment: () => <div data-testid="codex-agent-assignment" />,
+ CodexAgentAssignment: ({
+ onConnectionRefChange,
+ }: {
+ onConnectionRefChange: (connectionKey: string) => void
+ }) => (
+ <div data-testid="codex-agent-assignment">
+ <button type="button" onClick={() => onConnectionRefChange('codex-aaa')}>
+ Assign test grant
+ </button>
+ </div>
+ ),
}))
// Mock lib/api BEFORE importing the component. vi.mock is hoisted.
@@ -809,6 +819,11 @@ 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()
+ })
fireEvent.click(screen.getByRole('button', { name: 'Next' }))
fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))
@@ -822,7 +837,7 @@ describe('HostWizard — broker-backed Codex authoring', () => {
model: {
provider: 'codex-subscription',
name: 'gpt-5.1',
- connectionRef: 'unassigned',
+ connectionRef: 'codex-aaa',
},
}),
})
@@ -873,6 +888,7 @@ describe('HostWizard — broker-backed Codex authoring', () => {
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/lib/__tests__/codexSubscription.sanitize.test.ts b/control-ui/lib/__tests__/codexSubscription.sanitize.test.ts
new file mode 100644
index 000000000..7af7096a0
--- /dev/null
+++ b/control-ui/lib/__tests__/codexSubscription.sanitize.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest'
+import { sanitizeCodexConnection } from '../codexSubscription'
+
+function connected(overrides: Record<string, unknown> = {}) {
+ return {
+ connectionKey: 'codex-aaa',
+ status: 'connected',
+ credentialRevision: 1,
+ catalogRevision: 1,
+ accountFingerprint: null,
+ catalogStatus: 'ready',
+ catalogSyncedAt: null,
+ lastRefreshAt: null,
+ lastAuthAt: null,
+ refreshLockHeld: false,
+ ...overrides,
+ }
+}
+
+describe('sanitizeCodexConnection', () => {
+ it('keeps an explicit grant key', () => {
+ expect(sanitizeCodexConnection(connected()).connectionKey).toBe('codex-aaa')
+ })
+
+ it('rejects a missing or reserved connection key instead of inventing deployment-default', () => {
+ expect(() => sanitizeCodexConnection(connected({ connectionKey: '' }))).toThrow(
+ /connection key is invalid/
+ )
+ expect(() => sanitizeCodexConnection(connected({ connectionKey: 'unassigned' }))).toThrow(
+ /connection key is invalid/
+ )
+ expect(() => sanitizeCodexConnection(connected({ connectionKey: undefined }))).toThrow(
+ /connection key is invalid/
+ )
+ })
+})
diff --git a/control-ui/lib/codexSubscription.ts b/control-ui/lib/codexSubscription.ts
index a7a58d5ec..186dedb5e 100644
--- a/control-ui/lib/codexSubscription.ts
+++ b/control-ui/lib/codexSubscription.ts
@@ -124,11 +124,12 @@ export function sanitizeCodexConnection(raw: unknown): CodexSubscriptionConnecti
catalogStatus === 'never_synced'
? catalogStatus
: 'never_synced'
+ const connectionKey = typeof raw.connectionKey === 'string' ? raw.connectionKey.trim() : ''
+ if (!connectionKey || connectionKey === CODEX_UNASSIGNED_CONNECTION_KEY) {
+ throw new Error('Codex subscription connection key is invalid')
+ }
return {
- connectionKey:
- typeof raw.connectionKey === 'string' && raw.connectionKey.trim()
- ? raw.connectionKey.trim()
- : 'deployment-default',
+ connectionKey,
displayName: pickString(raw.displayName) ?? undefined,
assignedHosts: Array.isArray(raw.assignedHosts)
? raw.assignedHosts
@@ -287,7 +288,13 @@ export async function bindCodexHost(
)) as { host?: unknown; connectionRef?: unknown }
return {
host: pickString(raw.host) ?? hostRef,
- connectionRef: pickString(raw.connectionRef) ?? connectionKey,
+ connectionRef: (() => {
+ const next = pickString(raw.connectionRef)
+ if (!next) {
+ throw new Error('Codex subscription bind did not return connectionRef')
+ }
+ return next
+ })(),
}
}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 22ebfb978..9371562e4 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.457",
+ "version": "0.1.458",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.457",
+ "version": "0.1.458",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-ui/package.json b/control-ui/package.json
index 2c1ef70e0..6feb28a82 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.457",
+ "version": "0.1.458",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts
index 90bee3079..01e4018d7 100644
--- a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts
+++ b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts
@@ -10,7 +10,7 @@
* 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 from this agent | stay on model | unbind 200, connectionRef=unassigned, grant not revoked
+ * 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
*
@@ -291,21 +291,15 @@ test.describe('Codex subscription connection', () => {
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/${grantKey}/hosts/${firstName}/unbind$`
- ).test(new URL(response.url()).pathname) && response.request().method() === 'POST'
- )
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()
- 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(
/No subscription assigned/i
)
+ 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 } }
@@ -336,9 +330,19 @@ test.describe('Codex subscription connection', () => {
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 remaining = bound.slice(1)
const grantRow = hub.grantRow(grantKey)
await expect(grantRow.getByTestId('codex-hub-agent-chips')).toBeVisible()
- for (const hostName of bound) {
+ 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 } }
@@ -366,7 +370,11 @@ test.describe('Codex subscription connection', () => {
expect(revokeBody.connectionKey).toBe(grantKey)
})
- for (const hostName of bound) {
+ const afterRemoved = (await controlApi.getHost(bound[0])) 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 } }
}
diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.json
index aa59e6028..cab916900 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.31",
+ "version": "0.1.32",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-playwright-tests",
- "version": "0.1.31",
+ "version": "0.1.32",
"devDependencies": {
"@playwright/test": "^1.50.0",
"@types/node": "^22.0.0"
diff --git a/tests/e2e/playwright/package.json b/tests/e2e/playwright/package.json
index bc0f1d782..9c5f94e36 100644
--- a/tests/e2e/playwright/package.json
+++ b/tests/e2e/playwright/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-playwright-tests",
- "version": "0.1.31",
+ "version": "0.1.32",
"private": true,
"description": "Playwright E2E tests for Control UI and Desktop App",
"scripts": {
diff --git a/tests/e2e/playwright/pages/codex-subscription.ts b/tests/e2e/playwright/pages/codex-subscription.ts
index 01ccfd6a6..4ff82a06f 100644
--- a/tests/e2e/playwright/pages/codex-subscription.ts
+++ b/tests/e2e/playwright/pages/codex-subscription.ts
@@ -240,4 +240,22 @@ export class CodexSubscriptionHubPage {
}
return names
}
+
+ async removeAgentFromGrant(connectionKey: string, hostName: string) {
+ const row = this.grantRow(connectionKey)
+ const unbind = this.page.waitForResponse(
+ response =>
+ new RegExp(
+ `/api/v1/admin/llm/providers/codex-subscription/connections/${connectionKey}/hosts/${hostName}/unbind$`
+ ).test(new URL(response.url()).pathname) && response.request().method() === 'POST'
+ )
+ await row.getByRole('button', { name: `Remove agent ${hostName}` }).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')
+ }
}