Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(ui): seed an offered ChatGPT model so host save is not 422
Alfredo Lopez6861b3f900b8
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex 26fc31eeb..cf01288fd 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -12467,3 +12467,87 @@ button.cu-gfs-tree__button:focus-visible,.cu-llm-policy__actions {display: flex;}++.cu-codex-hub__create {+ display: flex;+ flex-direction: column;+ gap: 0.35rem;+ padding: 0.75rem 1rem 0;+}++.cu-codex-hub__create-row {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+ align-items: center;+}++.cu-codex-hub__create-row input {+ min-width: 16rem;+ flex: 1 1 16rem;+}++.cu-codex-hub__agents-cell {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.cu-codex-hub__agent-chip {+ display: inline-flex;+ align-items: center;+ gap: 0.35rem;+}++.cu-codex-hub__agent-chip a {+ color: inherit;+ text-decoration: none;+ font-weight: 600;+}++.cu-codex-hub__agent-chip a:hover {+ text-decoration: underline;+}++.cu-codex-hub__chip-remove {+ display: inline-grid;+ place-items: center;+ width: 1.1rem;+ height: 1.1rem;+ padding: 0;+ border: 0;+ border-radius: 0.25rem;+ background: transparent;+ color: var(--cu-text-muted);+ cursor: pointer;+}++.cu-codex-hub__chip-remove:hover:not(:disabled) {+ color: var(--cu-text);+ background: var(--cu-bg-panel);+}++.cu-codex-hub__chip-remove:disabled {+ opacity: 0.45;+ cursor: not-allowed;+}++.cu-codex-hub__add {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-start;+ gap: 0.5rem;+}++.cu-codex-hub__picker {+ min-width: 14rem;+ max-width: 22rem;+ flex: 1 1 14rem;+}++.cu-codex-hub__row-actions {+ display: inline-flex;+ flex-wrap: wrap;+ justify-content: flex-end;+ gap: 0.35rem;+}diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsxindex ac62a3916..03a164cc1 100644--- a/control-ui/app/hosts/[name]/page.tsx+++ b/control-ui/app/hosts/[name]/page.tsx@@ -16,6 +16,7 @@ import { LlmProviderConfig } from '../../../components/LlmProviderConfig'import { IconRobot } from '../../../components/Sidebar/icons'import { IconCheck, IconPencil, IconX } from '../../../components/icons'import { apiSend, getHost, getHostDetailBundle } from '../../../lib/api'+import { CODEX_UNASSIGNED_CONNECTION_KEY } from '../../../lib/codexSubscription'import { useLlmAllowedModels } from '../../../lib/hooks/useLlmAllowedModels'import { FIRST_PARTY_CHANNEL_WORKFLOW_CONTROL_SCOPES } from '../../../lib/hostWorkflowControl'import {@@ -24,9 +25,11 @@ import {type LlmPolicy,type LlmProvider,buildAllowedModelsSpec,+ constrainModelOptions,getActiveCredentialKeys,getModelOptions,getProviderLabel,+ hostModelNameError,isOpenAiFamily,isProviderUsable,llmChainRequiresSecret,@@ -34,6 +37,7 @@ import {normalizeLlmPolicy,normalizeProvider,projectCredentialDraft,+ resolveCodexGrantModel,resolveDefaultModel,validateLlmPolicy,validateLlmSecretData,@@ -125,7 +129,7 @@ export default function HostDetailsPage() {error: modelsError,} = useLlmAllowedModels()const [modelNameDraft, setModelNameDraft] = useState('')- const [connectionRefDraft, setConnectionRefDraft] = useState('deployment-default')+ const [connectionRefDraft, setConnectionRefDraft] = useState(CODEX_UNASSIGNED_CONNECTION_KEY)const [codexModels, setCodexModels] = useState<string[]>([])const catalogForEditor = useMemo(() => {if (providerDraft !== 'codex-subscription' || codexModels.length === 0) return allowedCatalog@@ -214,10 +218,20 @@ export default function HostDetailsPage() {// fell out of the allowlist stays selectable, spec R3.7). Cannot loop: it// only fires on an empty draft and always sets a non-empty value.useEffect(() => {+ if (providerDraft === 'codex-subscription') {+ const offered = constrainModelOptions(+ catalogForEditor,+ allowedModelsDraft,+ 'codex-subscription'+ )+ const next = resolveCodexGrantModel(modelNameDraft, offered)+ if (next && next !== modelNameDraft) setModelNameDraft(next)+ return+ }if (modelNameDraft === '' && providerModelOptions.length > 0) {setModelNameDraft(resolveDefaultModel(providerDraft, providerModelOptions))}- }, [modelNameDraft, providerDraft, providerModelOptions])+ }, [allowedModelsDraft, catalogForEditor, modelNameDraft, providerDraft, providerModelOptions])useEffect(() => {setActiveTab(parseHostTab(params.tab))@@ -284,7 +298,7 @@ export default function HostDetailsPage() {setConnectionRefDraft(String((spec.model as { connectionRef?: string } | undefined)?.connectionRef || ''- ).trim() || 'deployment-default'+ ).trim() || CODEX_UNASSIGNED_CONNECTION_KEY)setSecretRefDraft(String(spec.secretRef || ''))setLlmPolicyDraft(normalizeLlmPolicy(spec.llmPolicy))@@ -465,6 +479,11 @@ export default function HostDetailsPage() {// (identity, context, channels, lifecycle) are preserved via the// `...currentHost.spec` spread (full-replace semantics).async function saveModelAndCredentials(): Promise<boolean> {+ const modelNameProblem = hostModelNameError(modelNameDraft)+ if (modelNameProblem) {+ setError(modelNameProblem)+ return false+ }// Client-side mirror of control-api's write gate (spec R5.3): block a save// with an out-of-allowlist fallback model before the round-trip. Skip the// check when the allowlist failed to load (`allowedCatalog` empty) — every@@ -550,10 +569,7 @@ export default function HostDetailsPage() {name: modelNameDraft.trim(),...(providerDraft === 'codex-subscription'? {- connectionRef:- connectionRefDraft.trim() === 'unassigned'- ? 'unassigned'- : connectionRefDraft.trim() || 'deployment-default',+ connectionRef: connectionRefDraft.trim() || CODEX_UNASSIGNED_CONNECTION_KEY,}: {}),},@@ -943,7 +959,7 @@ export default function HostDetailsPage() {setEditingModel(false)}}}- disabled={busy}+ disabled={busy || Boolean(hostModelNameError(modelNameDraft))}>{busy ? 'Saving…' : 'Save'}</button>@@ -979,7 +995,9 @@ export default function HostDetailsPage() {<div className="cu-field"><label htmlFor="model-subscription">Subscription</label><div className="cu-field__readonly">- {connectionRefDraft || 'deployment-default'}+ {connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY+ ? 'No subscription assigned'+ : connectionRefDraft}</div></div>) : null}@@ -1093,7 +1111,7 @@ export default function HostDetailsPage() {catalog={catalogForEditor}catalogLoading={modelsLoading}catalogError={modelsError}- replacePrimaryModelWithAllowedModels+ replacePrimaryModelWithAllowedModels={providerDraft !== 'codex-subscription'}credentials={llmChainRequiresSecret(providerDraft, llmPolicyDraft?.fallbacks)? {diff --git a/control-ui/components/CodexSubscriptionHub/index.tsx b/control-ui/components/CodexSubscriptionHub/index.tsxindex 1d2230f99..ccb9db1de 100644--- a/control-ui/components/CodexSubscriptionHub/index.tsx+++ b/control-ui/components/CodexSubscriptionHub/index.tsx@@ -26,13 +26,19 @@ import {} from '../CodexSubscriptionConnection/types'import { useConfirmDialog } from '../ConfirmDialog'import { SecretsScopeTabs } from '../SecretsScopeTabs'+import { SelectionDropdown } from '../SelectionDropdown'import { TablePanelHeader } from '../TablePanelHeader'import { useToast } from '../Toast'+import { IconRefresh, IconX } from '../icons'function grantLabel(row: CodexSubscriptionConnectionView): string {return row.displayName || row.connectionKey}+function hostLabel(host: CodexAssignableHost): string {+ return host.displayName || host.name+}+function otherGrantLabel(connections: CodexSubscriptionConnectionView[],connectionRef: string@@ -40,6 +46,14 @@ function otherGrantLabel(return connections.find(row => row.connectionKey === connectionRef)?.displayName || connectionRef}+function assignmentCaption(+ host: CodexAssignableHost,+ connections: CodexSubscriptionConnectionView[]+): string {+ if (host.connectionRef === 'unassigned') return 'No subscription'+ return otherGrantLabel(connections, host.connectionRef)+}+export function CodexSubscriptionHub() {const { showToast } = useToast()const { confirm, confirmDialog } = useConfirmDialog()@@ -54,6 +68,7 @@ export function CodexSubscriptionHub() {const [busyKey, setBusyKey] = useState<string | null>(null)const [userCode, setUserCode] = useState<string | null>(null)const [verificationUri, setVerificationUri] = useState<string | null>(null)+ const [pickedByGrant, setPickedByGrant] = useState<Record<string, string[]>>({})const enabled = isCodexSubscriptionUiEnabled(capability)useEffect(() => {@@ -158,12 +173,12 @@ export function CodexSubscriptionHub() {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.${+ ? `This signs out the subscription itself. All ${names.length} agent(s) using it (${names.join(', ')}) will lose ChatGPT access immediately. Agents keep their assignment and stop authorizing; they are not reassigned automatically. To detach a single agent instead, remove it from the Agents column.${row.connectionKey === 'deployment-default'? ' Workflow recipes that use a ChatGPT subscription also fail closed on this grant.': ''}`- : 'Revoke disconnects this ChatGPT grant. Assigned agents keep the reference and stop authorizing. To detach a single agent instead, use Remove agent.',+ : 'Revoke disconnects this ChatGPT grant. Assigned agents keep the reference and stop authorizing. To detach a single agent instead, remove it from the Agents column.',confirmLabel: 'Revoke subscription',})if (!confirmed) return@@ -196,32 +211,67 @@ export function CodexSubscriptionHub() {}}- async function handleAssign(row: CodexSubscriptionConnectionView, host: CodexAssignableHost) {- if (host.connectionRef !== 'unassigned' && host.connectionRef !== row.connectionKey) {+ async function handleAssignMany(+ row: CodexSubscriptionConnectionView,+ hosts: CodexAssignableHost[]+ ) {+ if (hosts.length === 0) return+ const switching = hosts.filter(+ host => host.connectionRef !== 'unassigned' && host.connectionRef !== row.connectionKey+ )+ if (switching.length > 0) {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',+ title:+ hosts.length === 1+ ? `Switch ${hosts[0].name} to this subscription?`+ : `Add ${hosts.length} agents to this subscription?`,+ message: `${switching.map(host => hostLabel(host)).join(', ')} currently use another grant. Assign ${+ hosts.length === 1 ? 'it' : 'them'+ } to "${grantLabel(row)}"?`,+ confirmLabel: hosts.length === 1 ? 'Assign agent' : `Add ${hosts.length} agents`,})if (!confirmed) return}setBusyKey(row.connectionKey)+ const assigned: string[] = []+ const failed: string[] = []try {- await bindCodexHost(row.connectionKey, host.name)+ for (const host of hosts) {+ try {+ await bindCodexHost(row.connectionKey, host.name)+ assigned.push(hostLabel(host))+ } catch (err) {+ failed.push(hostLabel(host))+ showToast(err instanceof Error ? err.message : `Could not assign ${hostLabel(host)}`, {+ tone: 'error',+ })+ }+ }+ setPickedByGrant(prev => ({ ...prev, [row.connectionKey]: [] }))await load()- } catch (err) {- showToast(err instanceof Error ? err.message : 'Could not assign agent', { tone: 'error' })+ if (assigned.length > 0 && failed.length === 0) {+ showToast(+ assigned.length === 1+ ? `Assigned ${assigned[0]} to ${grantLabel(row)}`+ : `Assigned ${assigned.length} agents to ${grantLabel(row)}`,+ { tone: 'success' }+ )+ } else if (assigned.length > 0) {+ showToast(`Assigned ${assigned.length} of ${hosts.length} agents to ${grantLabel(row)}`, {+ tone: 'success',+ })+ }} finally {setBusyKey(null)}}return (- <div className="cu-card" data-testid="codex-subscription-hub">+ <div className="cu-card cu-card--viewport-fill" data-testid="codex-subscription-hub">{confirmDialog}<TablePanelHeadertitle="Subscriptions"- subtitle="Manage ChatGPT subscriptions and every agent that can use them."+ subtitle="ChatGPT grants in the same table as other Secrets. Assign any number of agents per row."actions={<buttontype="button"@@ -239,8 +289,8 @@ export function CodexSubscriptionHub() {{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.+ Agent assignments could not be loaded. Revoke still works. Add and Remove are disabled+ until hosts are available.</div>) : null}{userCode ? (@@ -248,128 +298,227 @@ export function CodexSubscriptionHub() {Enter {userCode} at {verificationUri ?? 'https://auth.openai.com/codex/device'}</div>) : null}+ {creating ? (+ <div className="cu-codex-hub__create">+ <label htmlFor="codex-hub-new-name">New subscription name</label>+ <div className="cu-codex-hub__create-row">+ <input+ id="codex-hub-new-name"+ value={displayName}+ onChange={event => setDisplayName(event.target.value)}+ disabled={busyKey !== null}+ />+ <button+ type="button"+ className="cu-btn cu-btn--primary cu-btn--sm"+ onClick={() => void handleCreate()}+ disabled={busyKey !== null}+ >+ Create+ </button>+ </div>+ </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-table-wrap">+ <table className="cu-table cu-table--header-band">+ <thead>+ <tr>+ <th>Name</th>+ <th>Status</th>+ <th>Agents</th>+ <th style={{ width: '12rem', textAlign: 'right' }} aria-label="Actions" />+ </tr>+ </thead>+ <tbody>+ {Array.from({ length: 3 }).map((_, idx) => (+ <tr key={idx}>+ <td>+ <div+ className="cu-skeleton cu-skeleton--cell"+ style={{ width: `${50 + ((idx * 11) % 24)}%` }}+ />+ </td>+ <td>+ <div className="cu-skeleton cu-skeleton--cell" style={{ width: '5rem' }} />+ </td>+ <td>+ <div className="cu-skeleton cu-skeleton--cell" style={{ width: '70%' }} />+ </td>+ <td>+ <div+ className="cu-skeleton cu-skeleton--cell"+ style={{ width: '5rem', marginLeft: 'auto' }}+ />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ ) : connections.length === 0 ? (<div className="cu-empty">No ChatGPT subscriptions yet. Add a subscription to let agents use ChatGPT models.</div>) : (- <div className="cu-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>{' '}+ <div className="cu-table-wrap">+ <table className="cu-table cu-table--header-band" data-testid="codex-hub-table">+ <caption className="sr-only">ChatGPT subscriptions and assigned agents</caption>+ <thead>+ <tr>+ <th scope="col">Name</th>+ <th scope="col" style={{ width: '8rem' }}>+ Status+ </th>+ <th scope="col">Agents</th>+ <th+ scope="col"+ style={{ width: '14rem', textAlign: 'right' }}+ aria-label="Actions"+ />+ </tr>+ </thead>+ <tbody>+ {connections.map(row => {+ const uiStatus = mapConnectionStatus(row.status)+ const assigned = assignableHosts.filter(+ host => host.connectionRef === row.connectionKey+ )+ const available = assignableHosts.filter(+ host => host.connectionRef !== row.connectionKey+ )+ const picked = pickedByGrant[row.connectionKey] ?? []+ const pickedHosts = available.filter(host => picked.includes(host.name))+ const busy = busyKey === row.connectionKey+ return (+ <tr key={row.connectionKey} data-testid={`codex-hub-grant-${row.connectionKey}`}>+ <td>{grantLabel(row)}</td>+ <td>+ <span className={statusTagClass(uiStatus)}>{statusLabel(uiStatus)}</span>+ </td>+ <td>+ <div className="cu-codex-hub__agents-cell">+ {assigned.length === 0 ? (+ <span className="cu-table__cell-muted">No agents assigned</span>+ ) : (+ <div+ className="cu-chip-row"+ data-testid="codex-hub-agent-chips"+ aria-label={`Agents on ${grantLabel(row)}`}+ >+ {assigned.map(host => (+ <span key={host.name} className="cu-chip cu-codex-hub__agent-chip">+ <a href={CONTROL_ROUTES.agents.detail(host.name)}>+ {hostLabel(host)}+ </a>+ <button+ type="button"+ className="cu-codex-hub__chip-remove"+ onClick={() => void handleUnbind(row, host.name)}+ disabled={busy || hostsUnavailable}+ aria-label={`Remove agent ${hostLabel(host)}`}+ >+ <IconX width={12} height={12} />+ </button>+ </span>+ ))}+ </div>+ )}+ <div className="cu-codex-hub__add" data-testid="codex-hub-add-agents">+ {available.length === 0 ? (+ <span className="cu-table__cell-muted">+ All agents already use this grant.+ </span>+ ) : (+ <>+ <label+ className="sr-only"+ htmlFor={`codex-hub-add-${row.connectionKey}`}+ >+ Add agents to this subscription+ </label>+ <SelectionDropdown+ id={`codex-hub-add-${row.connectionKey}`}+ className="cu-codex-hub__picker"+ multiple+ value={picked}+ options={available.map(host => ({+ value: host.name,+ label: hostLabel(host),+ description: assignmentCaption(host, connections),+ badge:+ host.connectionRef === 'unassigned'+ ? 'unassigned'+ : 'other grant',+ }))}+ placeholder="Add agents…"+ searchPlaceholder="Search agents…"+ selectionLabel="agents"+ emptyLabel="No ChatGPT-capable agents available."+ disabled={busy || hostsUnavailable || row.status === 'revoked'}+ onChange={next =>+ setPickedByGrant(prev => ({+ ...prev,+ [row.connectionKey]: next,+ }))+ }+ />+ <button+ type="button"+ className="cu-btn cu-btn--primary cu-btn--sm"+ onClick={() => void handleAssignMany(row, pickedHosts)}+ disabled={+ busy ||+ hostsUnavailable ||+ row.status === 'revoked' ||+ pickedHosts.length === 0+ }+ >+ {pickedHosts.length > 1+ ? `Add ${pickedHosts.length} agents`+ : 'Add agents'}+ </button>+ </>+ )}+ </div>+ </div>+ </td>+ <td style={{ textAlign: 'right' }}>+ <div className="cu-codex-hub__row-actions"><buttontype="button"className="cu-btn cu-btn--ghost cu-btn--sm"- onClick={() => void handleUnbind(row, host.name)}- disabled={busy || hostsUnavailable}+ onClick={() => void handleConnect(row)}+ disabled={busy || row.status === 'revoked'}+ >+ Sign in+ </button>+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--toolbar"+ onClick={() => void handleSync(row)}+ disabled={busy || row.status !== 'connected'}+ aria-label={`Sync catalog ${grantLabel(row)}`}>- Remove agent+ <IconRefresh width={16} height={16} /></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)})`}{' '}<buttontype="button"className="cu-btn cu-btn--ghost cu-btn--sm"- onClick={() => void handleAssign(row, host)}- disabled={busy || hostsUnavailable || row.status === 'revoked'}+ onClick={() => void handleRevoke(row)}+ disabled={busy || row.status === 'revoked'}>- Assign+ Revoke subscription</button>- </li>- ))}- </ul>- )}- </section>- )- })}+ </div>+ </td>+ </tr>+ )+ })}+ </tbody>+ </table></div>)}</div>diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsxindex 97b15f6fa..7450f31ef 100644--- a/control-ui/components/HostWizard/index.tsx+++ b/control-ui/components/HostWizard/index.tsx@@ -19,6 +19,7 @@ import {updateAgentUsers,} from '@/lib/api'import { cn } from '@/lib/cn'+import { CODEX_UNASSIGNED_CONNECTION_KEY } from '@/lib/codexSubscription'import { useLlmAllowedModels } from '@/lib/hooks/useLlmAllowedModels'import { getAgentNameError } from '@/lib/k8sValidation'import {@@ -26,6 +27,7 @@ import {type LlmPolicy,type LlmProvider,buildAllowedModelsSpec,+ constrainModelOptions,createEmptyLlmKeyDraft,getActiveCredentialKeys,getModelOptions,@@ -34,6 +36,7 @@ import {isProviderUsable,llmChainRequiresSecret,projectCredentialDraft,+ resolveCodexGrantModel,resolveDefaultModel,validateLlmSecretData,} from '@/lib/llm'@@ -342,7 +345,7 @@ export function HostWizard({error: modelsError,} = useLlmAllowedModels()const [modelName, setModelName] = useState('')- const [connectionRef, setConnectionRef] = useState('deployment-default')+ const [connectionRef, setConnectionRef] = useState(CODEX_UNASSIGNED_CONNECTION_KEY)const [codexModels, setCodexModels] = useState<string[]>([])const [stateless, setStateless] = useState(false)const [users, setUsers] = useState<@@ -441,12 +444,18 @@ export function HostWizard({// switch left the model out of range.useEffect(() => {if (modelsLoading) return+ if (provider === 'codex-subscription') {+ const offered = constrainModelOptions(catalogForEditor, allowedModels, provider)+ const next = resolveCodexGrantModel(modelName, offered)+ if (next !== modelName) setModelName(next)+ return+ }if (!providerModelOptions.includes(modelName)) {setModelName(resolveDefaultModel(provider, providerModelOptions))}// Intentionally omit modelName: this reconciles the picker to the options.// eslint-disable-next-line react-hooks/exhaustive-deps- }, [providerModelOptions, modelsLoading])+ }, [allowedModels, catalogForEditor, modelsLoading, provider, providerModelOptions])// Auto-derive the new Secret name from the agent name ("this agent's// credentials") until the operator edits it, so naming a Kubernetes Secret isdiff --git a/control-ui/components/LlmProviderConfig/index.tsx b/control-ui/components/LlmProviderConfig/index.tsxindex 8f40f4258..c540ab639 100644--- a/control-ui/components/LlmProviderConfig/index.tsx+++ b/control-ui/components/LlmProviderConfig/index.tsx@@ -29,6 +29,7 @@ import {mintFallbackSlot,normalizeProvider,providerSupportsFallbackCredentialSlot,+ resolveCodexGrantModel,resolveDefaultModel,validateLlmSecretData,} from '@/lib/llm'@@ -311,8 +312,8 @@ export function LlmProviderConfig({onChange={() =>onPrimaryChange({provider: OPENAI_SUBSCRIPTION_PROVIDER,- model: resolveDefaultModel(- OPENAI_SUBSCRIPTION_PROVIDER,+ model: resolveCodexGrantModel(+ model,constrainModelOptions(catalog,allowedModels,diff --git a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsxindex debc6d778..b675892f9 100644--- a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx+++ b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'import type { CodexSubscriptionConnectionView } from '@lib/codexSubscription'import {bindCodexHost,@@ -67,8 +67,9 @@ describe('CodexSubscriptionHub', () => {vi.mocked(listCodexSubscriptionFleet).mockResolvedValue({connections: [connection({ connectionKey: 'codex-aaa', displayName: 'Team A' })],assignableHosts: [- { name: 'chatllm', connectionRef: 'codex-aaa' },- { name: 'writer', connectionRef: 'unassigned' },+ { name: 'chatllm', connectionRef: 'codex-aaa', displayName: 'chatllm' },+ { name: 'writer', connectionRef: 'unassigned', displayName: 'writer' },+ { name: 'researcher', connectionRef: 'unassigned', displayName: 'researcher' },],assignableHostsUnavailable: false,})@@ -99,22 +100,26 @@ describe('CodexSubscriptionHub', () => {expect(revokeCodexSubscription).not.toHaveBeenCalled()})- it('shows Assigned and Available fleet rows for a grant', async () => {+ it('renders subscriptions as one Secrets table, not stacked cards', async () => {render(<ToastProvider><CodexSubscriptionHub /></ToastProvider>)await waitFor(() => {- expect(screen.getByRole('heading', { name: 'Assigned' })).toBeInTheDocument()+ expect(screen.getByTestId('codex-hub-table')).toBeInTheDocument()})+ expect(screen.getByRole('columnheader', { name: 'Name' })).toBeInTheDocument()+ expect(screen.getByRole('columnheader', { name: 'Status' })).toBeInTheDocument()+ expect(screen.getByRole('columnheader', { name: 'Agents' })).toBeInTheDocument()expect(screen.getByRole('link', { name: 'chatllm' })).toBeInTheDocument()- expect(screen.getByRole('heading', { name: 'Available' })).toBeInTheDocument()- expect(screen.getByText(/writer/)).toBeInTheDocument()- expect(screen.getByText(/no subscription assigned/i)).toBeInTheDocument()+ expect(screen.queryByRole('heading', { name: 'Available' })).not.toBeInTheDocument()+ expect(screen.queryByRole('heading', { name: 'Assigned' })).not.toBeInTheDocument()+ expect(document.querySelectorAll('.cu-llm-config__block').length).toBe(0)+ expect(screen.getByLabelText('Add agents to this subscription')).toBeInTheDocument()})- it('assigns an available agent without revoking', async () => {+ it('assigns one available agent without revoking', async () => {vi.mocked(bindCodexHost).mockResolvedValue({ host: 'writer', connectionRef: 'codex-aaa' })render(<ToastProvider>@@ -122,12 +127,62 @@ describe('CodexSubscriptionHub', () => {</ToastProvider>)await waitFor(() => {- expect(screen.getByRole('button', { name: 'Assign' })).toBeInTheDocument()+ expect(screen.getByLabelText('Add agents to this subscription')).toBeInTheDocument()})- fireEvent.click(screen.getByRole('button', { name: 'Assign' }))+ fireEvent.click(screen.getByLabelText('Add agents to this subscription'))+ fireEvent.click(screen.getByRole('option', { name: 'writer' }))+ fireEvent.click(screen.getByRole('button', { name: 'Add agents' }))await waitFor(() => {expect(bindCodexHost).toHaveBeenCalledWith('codex-aaa', 'writer')})+ expect(bindCodexHost).toHaveBeenCalledTimes(1)+ expect(revokeCodexSubscription).not.toHaveBeenCalled()+ })++ it('assigns multiple available agents to the same subscription in one action', async () => {+ vi.mocked(bindCodexHost)+ .mockResolvedValueOnce({ host: 'writer', connectionRef: 'codex-aaa' })+ .mockResolvedValueOnce({ host: 'researcher', connectionRef: 'codex-aaa' })+ render(+ <ToastProvider>+ <CodexSubscriptionHub />+ </ToastProvider>+ )+ await waitFor(() => {+ expect(screen.getByLabelText('Add agents to this subscription')).toBeInTheDocument()+ })+ fireEvent.click(screen.getByLabelText('Add agents to this subscription'))+ fireEvent.click(screen.getByRole('option', { name: 'writer' }))+ fireEvent.click(screen.getByRole('option', { name: 'researcher' }))+ fireEvent.click(screen.getByRole('button', { name: 'Add 2 agents' }))+ await waitFor(() => {+ expect(bindCodexHost).toHaveBeenCalledTimes(2)+ })+ expect(bindCodexHost).toHaveBeenNthCalledWith(1, 'codex-aaa', 'writer')+ expect(bindCodexHost).toHaveBeenNthCalledWith(2, 'codex-aaa', 'researcher')+ expect(revokeCodexSubscription).not.toHaveBeenCalled()+ })++ it('keeps assigning remaining agents when one bind fails', async () => {+ vi.mocked(bindCodexHost)+ .mockRejectedValueOnce(new Error('writer bind failed'))+ .mockResolvedValueOnce({ host: 'researcher', connectionRef: 'codex-aaa' })+ render(+ <ToastProvider>+ <CodexSubscriptionHub />+ </ToastProvider>+ )+ await waitFor(() => {+ expect(screen.getByLabelText('Add agents to this subscription')).toBeInTheDocument()+ })+ fireEvent.click(screen.getByLabelText('Add agents to this subscription'))+ fireEvent.click(screen.getByRole('option', { name: 'writer' }))+ fireEvent.click(screen.getByRole('option', { name: 'researcher' }))+ fireEvent.click(screen.getByRole('button', { name: 'Add 2 agents' }))+ await waitFor(() => {+ expect(bindCodexHost).toHaveBeenCalledTimes(2)+ })+ expect(bindCodexHost).toHaveBeenNthCalledWith(2, 'codex-aaa', 'researcher')expect(revokeCodexSubscription).not.toHaveBeenCalled()})@@ -150,10 +205,10 @@ describe('CodexSubscriptionHub', () => {<CodexSubscriptionHub /></ToastProvider>)- await waitFor(() => {- expect(screen.getAllByRole('button', { name: 'Assign' }).length).toBeGreaterThan(0)- })- fireEvent.click(screen.getAllByRole('button', { name: 'Assign' })[0])+ const teamA = await screen.findByTestId('codex-hub-grant-codex-aaa')+ fireEvent.click(within(teamA).getByLabelText('Add agents to this subscription'))+ fireEvent.click(within(teamA).getByRole('option', { name: 'chatllm' }))+ fireEvent.click(within(teamA).getByRole('button', { name: 'Add agents' }))await waitFor(() => {expect(confirmMock).toHaveBeenCalledWith(expect.objectContaining({@@ -177,9 +232,9 @@ describe('CodexSubscriptionHub', () => {</ToastProvider>)await waitFor(() => {- expect(screen.getByRole('button', { name: 'Remove agent' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Remove agent chatllm' })).toBeInTheDocument()})- fireEvent.click(screen.getByRole('button', { name: 'Remove agent' }))+ fireEvent.click(screen.getByRole('button', { name: 'Remove agent chatllm' }))await waitFor(() => {expect(unbindCodexHost).toHaveBeenCalledWith('codex-aaa', 'chatllm')})diff --git a/control-ui/components/__tests__/HostWizard.test.tsx b/control-ui/components/__tests__/HostWizard.test.tsxindex 068770c53..21610f5ad 100644--- a/control-ui/components/__tests__/HostWizard.test.tsx+++ b/control-ui/components/__tests__/HostWizard.test.tsx@@ -822,7 +822,7 @@ describe('HostWizard — broker-backed Codex authoring', () => {model: {provider: 'codex-subscription',name: 'gpt-5.1',- connectionRef: 'deployment-default',+ connectionRef: 'unassigned',},}),})@@ -840,6 +840,23 @@ describe('HostWizard — broker-backed Codex authoring', () => {).toBe(false)}, 15_000)+ it('seeds the first offered grant model when switching to a ChatGPT subscription', async () => {+ await renderWizard()+ await walkToModelStep({ agentName: 'codex-keep-model' })+ await waitFor(() => {+ expect(+ screen.getByLabelText('Default model', { selector: '#llm-primary-model' })+ ).toHaveTextContent(/\S/)+ })+ fireEvent.click(screen.getByRole('radio', { name: /ChatGPT subscription/i }))+ await waitFor(() => {+ expect(+ screen.getByLabelText('Default model', { selector: '#llm-primary-model' })+ ).toHaveTextContent('gpt-5.1')+ })+ expect(screen.queryByText(/Use an existing secret/i)).not.toBeInTheDocument()+ }, 15_000)+it('requires exact credential slots when a static fallback joins a Codex primary', async () => {await renderWizard()await walkToModelStep({ agentName: 'codex-mixed' })diff --git a/control-ui/components/__tests__/LlmProviderConfig.test.tsx b/control-ui/components/__tests__/LlmProviderConfig.test.tsxindex 5ad44408d..6e060e0b7 100644--- a/control-ui/components/__tests__/LlmProviderConfig.test.tsx+++ b/control-ui/components/__tests__/LlmProviderConfig.test.tsx@@ -22,6 +22,7 @@ function Harness({existingKeys,replacePrimaryModelWithAllowedModels = false,subscriptionCredentialEnabled = false,+ catalog = CATALOG,}: {initialProvider?: LlmProviderinitialModel?: string@@ -31,6 +32,7 @@ function Harness({existingKeys?: string[]replacePrimaryModelWithAllowedModels?: booleansubscriptionCredentialEnabled?: boolean+ catalog?: LlmModelCatalogEntry[]}) {const [provider, setProvider] = useState<LlmProvider>(initialProvider)const [model, setModel] = useState(initialModel)@@ -49,7 +51,7 @@ function Harness({onPolicyChange={setPolicy}allowedModels={allowedModels}onAllowedModelsChange={setAllowedModels}- catalog={CATALOG}+ catalog={catalog}credentials={withCredentials? {@@ -187,6 +189,50 @@ describe('LlmProviderConfig (spec Topic 1b — domain projection + usable gate)'expect(screen.getByRole('radio', { name: /ChatGPT subscription/i })).toBeChecked()expect(screen.getByText(/Connect and sync the grant first/i)).toBeInTheDocument()})++ it('keeps the current model name when the ChatGPT grant catalog is empty', () => {+ render(<Harness subscriptionCredentialEnabled initialModel="gpt-5.4-mini" />)+ fireEvent.click(screen.getByRole('radio', { name: /ChatGPT subscription/i }))+ expect(screen.getByLabelText('Model', { selector: '#llm-primary-model' })).toHaveTextContent(+ 'gpt-5.4-mini'+ )+ })++ it('seeds the first offered grant model when the draft is outside the ChatGPT catalog', () => {+ const catalog: LlmModelCatalogEntry[] = [+ ...CATALOG,+ { provider: 'codex-subscription', model: 'gpt-5.6-luna', enabled: true },+ { provider: 'codex-subscription', model: 'gpt-5.6-sol', enabled: true },+ ]+ render(<Harness subscriptionCredentialEnabled initialModel="gpt-5.4-mini" catalog={catalog} />)+ fireEvent.click(screen.getByRole('radio', { name: /ChatGPT subscription/i }))+ expect(screen.getByLabelText('Model', { selector: '#llm-primary-model' })).toHaveTextContent(+ 'gpt-5.6-luna'+ )+ })++ it('seeds the first ChatGPT subset model so Save is not model_not_offered', () => {+ const catalog: LlmModelCatalogEntry[] = [+ ...CATALOG,+ { provider: 'codex-subscription', model: 'gpt-5.6-luna', enabled: true },+ { provider: 'codex-subscription', model: 'gpt-5.6-sol', enabled: true },+ ]+ render(+ <Harness+ subscriptionCredentialEnabled+ initialModel="gpt-5.4-mini"+ catalog={catalog}+ initialAllowed={[+ { provider: 'codex-subscription', model: 'gpt-5.6-luna' },+ { provider: 'codex-subscription', model: 'gpt-5.6-sol' },+ ]}+ />+ )+ fireEvent.click(screen.getByRole('radio', { name: /ChatGPT subscription/i }))+ expect(screen.getByLabelText('Model', { selector: '#llm-primary-model' })).toHaveTextContent(+ 'gpt-5.6-luna'+ )+ })})describe('LlmProviderConfig (spec Topic 3a — per-host allowed-models subset)', () => {diff --git a/control-ui/lib/__tests__/llm.codexGrantModel.test.ts b/control-ui/lib/__tests__/llm.codexGrantModel.test.tsnew file mode 100644index 000000000..d17dfe664--- /dev/null+++ b/control-ui/lib/__tests__/llm.codexGrantModel.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest'+import {+ HOST_MODEL_NAME_REQUIRED,+ hostModelNameError,+ resolveCodexGrantModel,+ resolveDefaultModel,+} from '../llm'++describe('resolveCodexGrantModel', () => {+ it('keeps a named draft that is already in the grant catalog', () => {+ expect(resolveDefaultModel('codex-subscription', ['gpt-5.1'])).toBe('')+ expect(resolveCodexGrantModel('gpt-5.1', ['gpt-5.1', 'gpt-5.2'])).toBe('gpt-5.1')+ })++ it('seeds the first offered grant model when the draft is empty', () => {+ expect(resolveCodexGrantModel('', ['gpt-5.1', 'gpt-5.2'])).toBe('gpt-5.1')+ expect(resolveCodexGrantModel(' ', ['gpt-5.1'])).toBe('gpt-5.1')+ })++ it('replaces a named draft that is not in the offered grant list', () => {+ expect(resolveCodexGrantModel('gpt-5.4-mini', ['gpt-5.6-luna', 'gpt-5.6-sol'])).toBe(+ 'gpt-5.6-luna'+ )+ })++ it('keeps a named draft when the grant catalog is empty so Save is not an empty-name 422', () => {+ expect(resolveCodexGrantModel('gpt-5.4-mini', [])).toBe('gpt-5.4-mini')+ expect(resolveCodexGrantModel('', [])).toBe('')+ })+})++describe('hostModelNameError', () => {+ it('blocks the empty spec.model.name that the API rejects with 422', () => {+ expect(hostModelNameError('')).toBe(HOST_MODEL_NAME_REQUIRED)+ expect(hostModelNameError(' ')).toBe(HOST_MODEL_NAME_REQUIRED)+ expect(hostModelNameError('gpt-5.1')).toBeNull()+ })+})diff --git a/control-ui/lib/llm.ts b/control-ui/lib/llm.tsindex fd190e5e1..217c2c240 100644--- a/control-ui/lib/llm.ts+++ b/control-ui/lib/llm.ts@@ -537,6 +537,27 @@ export function resolveDefaultModel(provider: LlmProvider, enabledModels: stringreturn enabledModels[0] ?? ''}+export const HOST_MODEL_NAME_REQUIRED =+ 'Select a model before saving. The agent needs a non-empty model name.'++export function hostModelNameError(name: string): string | null {+ return name.trim() ? null : HOST_MODEL_NAME_REQUIRED+}++/**+ * ChatGPT grants still need a concrete spec.model.name. Keep the draft only+ * when it is already in the offered grant list (or the list is empty, so a+ * named draft can save before catalog sync). Otherwise seed the first offered+ * model — never resolveDefaultModel, which is always '' for oauth-broker.+ */+export function resolveCodexGrantModel(current: string, grantModels: string[]): string {+ const trimmed = current.trim()+ if (trimmed && (grantModels.length === 0 || grantModels.includes(trimmed))) {+ return trimmed+ }+ return grantModels[0] ?? trimmed+}+// ── Per-host model allowlist subset (spec Topic 3a) ───────────────────────// `spec.allowedModels` on a Host: a flat, OPTIONAL list of (provider, model)// pairs = the SUBSET of the global operator allowlist this host offers to enddiff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex fe4130736..17c73022c 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.455",+ "version": "0.1.456","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.455",+ "version": "0.1.456","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 f717e25df..baf02e9fd 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.455",+ "version": "0.1.456","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 fafc2fb55..027566fd0 100755--- a/scripts/tests/test-codex-subscription-t0.sh+++ b/scripts/tests/test-codex-subscription-t0.sh@@ -194,6 +194,8 @@ run_group "workflow-recipes" "workflow-recipes" \run_group "control-ui" "control-ui" \"components/__tests__/CodexAgentAssignment.test.tsx" \"components/__tests__/CodexSubscriptionHub.test.tsx" \+ "components/__tests__/LlmProviderConfig.test.tsx" \+ "lib/__tests__/llm.codexGrantModel.test.ts" \"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 8b7032526..30615501b 100644--- a/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts+++ b/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts@@ -1,9 +1,10 @@/*** Codex subscription — Control UI admission and route guards.*- * Contract:- * - Unauthenticated deep link to an agent model tab must not expose Connect.- * - LLM Models no longer owns ChatGPT assignment; the old URL has no Connect owner.+ * Negative contract (direct terminal access is the behavior under test here):+ * - Unauthenticated `/secrets/subscription` must show login, not the hub.+ * - Unauthenticated `/agents/:name/model` must show login, not Connect.+ * - LLM Models is no longer the ChatGPT assignment owner.*/import { expect, test } from '@playwright/test'import { loginControlUiVisible } from '../helpers/visible-login'@@ -29,12 +30,16 @@ test.describe('Codex subscription admission', () => {await page.goto('/')await loginControlUiVisible(page)- await page.getByRole('link', { name: 'LLM Models' }).click()- await expect(page).toHaveURL(/\/llm-models/)- await expect(page.getByRole('tab', { name: 'Codex subscription' })).toHaveCount(0)+ await test.step('sidebar LLM Models has no Codex subscription tab', async () => {+ await page.getByRole('link', { name: 'LLM Models' }).click()+ await expect(page).toHaveURL(/\/llm-models/)+ await expect(page.getByRole('tab', { name: 'Codex subscription' })).toHaveCount(0)+ })- await page.goto('/llm-models/providers/codex-subscription')- await expect(page.getByRole('button', { name: 'Sign in with ChatGPT' })).toHaveCount(0)- await expect(page.getByTestId('codex-connection-status')).toHaveCount(0)+ await test.step('legacy provider URL does not expose Connect', async () => {+ await page.goto('/llm-models/providers/codex-subscription')+ await expect(page.getByRole('button', { name: 'Sign in with ChatGPT' })).toHaveCount(0)+ await expect(page.getByTestId('codex-connection-status')).toHaveCount(0)+ })})})diff --git a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.tsindex 33153b6cf..90bee3079 100644--- a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts+++ b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts@@ -1,15 +1,35 @@/**- * Codex subscription — assign/unbind on the agent model tab; create, assign,+ * Codex subscription — assign/unbind on the agent model tab; create, multi-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 the- * sidebar. Direct `goto` of an agent model tab or `/secrets/subscription` is- * not the happy-path entry.+ * E2E contract+ * ------------+ * Journey | Entry | Actions | Transitions | Business signal+ * API key → ChatGPT | `/` + visible login + Agents | Open agent → Models → ChatGPT → Save | `/agents/:name/model` | PUT host ≠ 422, spec.model.name non-empty+ * Assign from agent | same | Create grant in UI → Save | stay on model tab | PUT 200, connectionRef persisted+ * Device login | same | Sign in with ChatGPT | stay on model, no oauth URL | device start 200 + userCode in UI+ * Sync catalog | same | Select grant → Sync | stay on model | disabled until connected; POST sync when connected+ * Reuse grant | Agents list with 2 seeded | Create grant on A → pick same grant on B | second agent model tab | picker value = shared key+ * Unbind | agent model | Create → Save → Remove from this agent | stay on model | unbind 200, connectionRef=unassigned, grant not revoked+ * Hub table + assign | `/` → Secrets → Subscription | Create grant → pick 2 agents → Add 2 → Revoke| `/secrets/subscription` + table | 2 bind 200s, chips, revoke status+ * LLM → Subscription | Secrets LLM | Empty-state link or Subscription tab | `/secrets/subscription` | hub visible+ *+ * Forbidden shortcuts: happy-path `goto` of `/secrets/subscription` or an agent+ * model tab; `test.skip`; silent `return` after an empty model; mutating storage+ * to skip login. API host create is a named precondition only.+ *+ * ChatGPT OAuth is the only mocked/external boundary (live device code is+ * asserted, not completed).*/import { type Page, expect, test } from '@playwright/test'import { controlApi } from '../helpers/api-client'import { loginControlUiVisible } from '../helpers/visible-login'+import {+ AgentListPage,+ AgentModelPage,+ CodexSubscriptionHubPage,+ ControlUiShell,+} from '../pages/codex-subscription'type CodexConnection = {connectionKey: string@@ -19,86 +39,46 @@ type CodexConnection = {assignedHosts?: Array<{ name: string }>}-async function openAgents(page: Page) {- await page.getByRole('link', { name: 'Agents', exact: true }).click()- await expect(page).toHaveURL(/\/(?:hosts|agents)$/)-}--async function agentRows(page: Page) {- return page.getByRole('row', { name: /Open agent / })+async function loginFromHome(page: Page) {+ await page.goto('/')+ await loginControlUiVisible(page)+ await expect(page.getByLabel('Main navigation')).toBeVisible()}-async function ensureListedAgents(page: Page, minimum = 1): Promise<void> {+/**+ * Named API precondition — not the behavior under test. Seeds ChatGPT-capable+ * hosts so the Agents table and hub picker have rows. Fails loud if create fails.+ */+async function seedCodexAgents(page: Page, minimum: number): Promise<void> {const listed = await controlApi.getHosts()const items = Array.isArray(listed.items) ? listed.items : []const needed = Math.max(0, minimum - items.length)for (let index = 0; index < needed; index += 1) {const name = `e2e-codex-guardian${needed === 1 && index === 0 ? '' : `-${index + 1}`}`- try {- await controlApi.createHost({- metadata: { name },- spec: {- host: name,- contextRef: '',- secretRef: '',- channels: [],- model: {- provider: 'codex-subscription',- name: 'gpt-5.1',- connectionRef: 'deployment-default',- },+ await controlApi.createHost({+ metadata: { name },+ spec: {+ host: name,+ contextRef: '',+ secretRef: '',+ channels: [],+ model: {+ provider: 'codex-subscription',+ name: 'gpt-5.1',+ connectionRef: 'unassigned',},- })- } catch {- break- }+ },+ })}if (needed > 0) {await page.getByRole('button', { name: /Reload agents/i }).click()}- await expect((await agentRows(page)).first()).toBeVisible()-}--async function openFirstAgent(page: Page): Promise<string> {- await ensureListedAgents(page, 1)- const row = (await agentRows(page)).first()- await expect(row).toBeVisible()- const label = (await row.getAttribute('aria-label')) ?? ''- const name = label.replace(/^Open agent\s+/, '').trim()- await row.click()- await expect(page).toHaveURL(/\/(?:hosts|agents)\/[^/]+/)- return decodeURIComponent(name)-}--async function openModelEditor(page: Page) {- await page.getByRole('tab', { name: 'Models & creds' }).click()- await expect(page).toHaveURL(/\/(?:hosts|agents)\/[^/]+\/model/)- await expect(page.getByRole('tab', { name: 'Models & creds', selected: true })).toBeVisible()- const edit = page.getByRole('button', { name: 'Edit', exact: true })- if (await edit.isVisible().catch(() => false)) {- await edit.click()- }- await expect(page.getByLabel('Provider')).toBeVisible()-}--async function chooseSubscriptionCredential(page: Page) {- await page.getByLabel('Provider').click()- await page.getByRole('option', { name: 'OpenAI', exact: true }).click()- await expect(page.getByRole('option', { name: 'OpenAI Codex Subscription' })).toHaveCount(0)- await page.getByRole('radio', { name: 'ChatGPT subscription' }).check()- await expect(page.getByTestId('codex-agent-assignment')).toBeVisible()-}--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()+ const agents = new AgentListPage(page)+ await expect(agents.rows().first()).toBeVisible()+ expect(+ await agents.rows().count(),+ `need ${minimum} agents after named API seed`+ ).toBeGreaterThanOrEqual(minimum)}async function listConnections(): Promise<CodexConnection[]> {@@ -106,80 +86,90 @@ async function listConnections(): Promise<CodexConnection[]> {}test.describe('Codex subscription connection', () => {- test('operator assigns a subscription from the agent model tab', async ({ page }) => {- await page.goto('/')- await loginControlUiVisible(page)- await openAgents(page)- const agentName = await openFirstAgent(page)- await openModelEditor(page)- await chooseSubscriptionCredential(page)+ test('switching from API key to ChatGPT keeps a model name and never 422s', async ({ page }) => {+ const shell = new ControlUiShell(page)+ const agents = new AgentListPage(page)+ const model = new AgentModelPage(page)++ await test.step('enter from home and open the first agent model editor', async () => {+ await loginFromHome(page)+ await shell.openAgents()+ await seedCodexAgents(page, 1)+ await agents.openNth(0)+ await model.openEditor()+ })- const picker = subscriptionPicker(page)- await expect(picker).toBeVisible()- await expect(page.getByLabel(/OpenAI API key/i)).toHaveCount(0)+ await test.step('switch OpenAI API key → ChatGPT subscription', async () => {+ await model.chooseChatGPTSubscription()+ await model.expectNamedModel()+ })- const connections = await listConnections()- let selectedKey = await picker.inputValue()- if (!connections.some(row => row.connectionKey === selectedKey)) {- const usable = connections.find(row => row.status !== 'revoked')- expect(usable, 'an assignable ChatGPT subscription must exist').toBeTruthy()- await picker.selectOption(usable!.connectionKey)- selectedKey = usable!.connectionKey- }- const selected = connections.find(row => row.connectionKey === selectedKey)- test.skip(- selected?.status !== 'connected',- 'assign+save requires a live ChatGPT grant as fixture setup'- )+ await test.step('Save persists a non-empty spec.model.name', async () => {+ const save = model.saveButton()+ await expect(save).toBeEnabled()+ const put = page.waitForResponse(+ response =>+ /\/api\/v1\/admin\/hosts\/[^/]+$/.test(new URL(response.url()).pathname) &&+ response.request().method() === 'PUT'+ )+ await save.click()+ const response = await put+ expect(+ response.status(),+ 'API-key → ChatGPT save must not 422 empty model.name or model_not_offered'+ ).not.toBe(422)+ expect(response.ok(), `save must succeed, got ${response.status()}`).toBe(true)+ const body = (await response.json()) as { spec?: { model?: { name?: string } } }+ expect(body.spec?.model?.name).toEqual(expect.stringMatching(/\S/))+ })+ })- const put = page.waitForResponse(- response =>- new RegExp(`/api/v1/admin/hosts/${agentName}$`).test(new URL(response.url()).pathname) &&- response.request().method() === 'PUT'- )- const modelSelect = page.getByLabel(/^Model$/i)- const optionCount = await modelSelect- .locator('option')- .count()- .catch(() => 0)- if (optionCount > 1) {- await modelSelect.selectOption({ index: 1 })- }- await page.getByRole('button', { name: 'Save', exact: true }).click()- const response = await put- expect(response.ok(), `assign save must succeed, got ${response.status()}`).toBe(true)- const body = (await response.json()) as {- spec?: { model?: { provider?: string; connectionRef?: string } }- }+ test('operator assigns a subscription from the agent model tab', async ({ page }) => {+ const shell = new ControlUiShell(page)+ const agents = new AgentListPage(page)+ const model = new AgentModelPage(page)+ const displayName = `e2e-assign-${Date.now().toString(36)}`++ await loginFromHome(page)+ await shell.openAgents()+ await seedCodexAgents(page, 1)+ const agentName = await agents.openNth(0)+ await model.openEditor()+ await model.chooseChatGPTSubscription()++ const grantKey = await test.step('create the grant through the agent UI', () =>+ model.createGrant(displayName))+ await model.expectNamedModel()++ const body = await test.step('Save assigns the grant without a 422', () =>+ model.saveHost(agentName))expect(body.spec?.model?.provider).toBe('codex-subscription')- expect(body.spec?.model?.connectionRef).toBe(selectedKey)+ expect(body.spec?.model?.name).toEqual(expect.stringMatching(/\S/))+ expect(body.spec?.model?.connectionRef).toBe(grantKey)const host = (await controlApi.getHost(agentName)) as {- spec?: { model?: { connectionRef?: string } }+ spec?: { model?: { connectionRef?: string; name?: string } }}- expect(host.spec?.model?.connectionRef).toBe(selectedKey)+ expect(host.spec?.model?.connectionRef).toBe(grantKey)+ expect(host.spec?.model?.name).toEqual(expect.stringMatching(/\S/))})test('Sign in with ChatGPT starts device login from the agent page', async ({ page }) => {- await page.goto('/')- await loginControlUiVisible(page)- await openAgents(page)- await openFirstAgent(page)- await openModelEditor(page)- await chooseSubscriptionCredential(page)- await expect(subscriptionPicker(page)).toBeVisible()+ const shell = new ControlUiShell(page)+ const agents = new AgentListPage(page)+ const model = new AgentModelPage(page)++ await loginFromHome(page)+ await shell.openAgents()+ await seedCodexAgents(page, 1)+ await agents.openNth(0)+ await model.openEditor()+ await model.chooseChatGPTSubscription()+ await expect(model.subscriptionPicker()).toBeVisible()+const signIn = page.getByRole('button', { name: 'Sign in with ChatGPT' })- if (!(await signIn.isEnabled())) {- await page.getByRole('button', { name: 'New subscription' }).click()- await page.getByLabel('New subscription name').fill(`e2e-device-${Date.now().toString(36)}`)- 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()- expect((await created).ok()).toBe(true)+ if ((await signIn.count()) === 0 || !(await signIn.isEnabled())) {+ await model.createGrant(`e2e-device-${Date.now().toString(36)}`)}await expect(signIn).toBeEnabled()@@ -201,26 +191,34 @@ test.describe('Codex subscription connection', () => {})test('Sync catalog is disabled until that grant is connected', async ({ page }) => {- await page.goto('/')- await loginControlUiVisible(page)- await openAgents(page)- await openFirstAgent(page)- await openModelEditor(page)- await chooseSubscriptionCredential(page)+ const shell = new ControlUiShell(page)+ const agents = new AgentListPage(page)+ const model = new AgentModelPage(page)++ await loginFromHome(page)+ await shell.openAgents()+ await seedCodexAgents(page, 1)+ await agents.openNth(0)+ await model.openEditor()+ await model.chooseChatGPTSubscription()const connections = await listConnections()- const picker = subscriptionPicker(page)+ const picker = model.subscriptionPicker()const disconnected = connections.find(row => row.status !== 'connected' && row.status !== 'revoked')+ const connected = connections.find(row => row.status === 'connected')+if (disconnected) {await picker.selectOption(disconnected.connectionKey)await expect(page.getByRole('button', { name: 'Sync catalog' })).toBeDisabled()}- const connected = connections.find(row => row.status === 'connected')if (!connected) {- await expect(page.getByRole('button', { name: 'Sync catalog' })).toBeDisabled()+ await expect(+ page.getByRole('button', { name: 'Sync catalog' }),+ 'without a connected grant Sync must stay disabled'+ ).toBeDisabled()return}@@ -245,73 +243,50 @@ test.describe('Codex subscription connection', () => {})test('operator reuses the same grant on a second agent', async ({ page }) => {- await page.goto('/')- await loginControlUiVisible(page)- await openAgents(page)- await openFirstAgent(page)- await openModelEditor(page)- await chooseSubscriptionCredential(page)-- await page.getByRole('button', { name: 'New subscription' }).click()+ const shell = new ControlUiShell(page)+ const agents = new AgentListPage(page)+ const model = new AgentModelPage(page)const displayName = `e2e-shared-${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 sharedKey = createdBody.connectionKey- expect(sharedKey).toEqual(expect.any(String))- await expect(subscriptionPicker(page)).toHaveValue(String(sharedKey))-- await openAgents(page)- await ensureListedAgents(page, 2)- const agents = await agentRows(page)- test.skip((await agents.count()) < 2, 'reuse requires a second agent in the list')- await agents.nth(1).click()- await expect(page).toHaveURL(/\/(?:hosts|agents)\/[^/]+/)- await openModelEditor(page)- await chooseSubscriptionCredential(page)- await subscriptionPicker(page).selectOption(String(sharedKey))- await expect(subscriptionPicker(page)).toHaveValue(String(sharedKey))++ await loginFromHome(page)+ await shell.openAgents()+ await seedCodexAgents(page, 2)+ await agents.openNth(0)+ await model.openEditor()+ await model.chooseChatGPTSubscription()+ const sharedKey = await model.createGrant(displayName)++ await test.step('open a second agent through the list', async () => {+ await shell.openAgents()+ expect(+ await agents.rows().count(),+ 'reuse requires two seeded agents'+ ).toBeGreaterThanOrEqual(2)+ await agents.openNth(1)+ await model.openEditor()+ await model.chooseChatGPTSubscription()+ })++ await model.subscriptionPicker().selectOption(sharedKey)+ await expect(model.subscriptionPicker()).toHaveValue(sharedKey)await expect(page.getByRole('option', { name: displayName })).toHaveCount(1)})test('agent models can unbind this host and never expose grant Revoke', async ({ page }) => {- await page.goto('/')- await loginControlUiVisible(page)- await openAgents(page)- const firstName = await openFirstAgent(page)- await openModelEditor(page)- await chooseSubscriptionCredential(page)-- await page.getByRole('button', { name: 'New subscription' }).click()+ const shell = new ControlUiShell(page)+ const agents = new AgentListPage(page)+ const model = new AgentModelPage(page)const displayName = `e2e-unbind-${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)- 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 loginFromHome(page)+ await shell.openAgents()+ await seedCodexAgents(page, 1)+ const firstName = await agents.openNth(0)+ await model.openEditor()+ await model.chooseChatGPTSubscription()+ const grantKey = await model.createGrant(displayName)+ await model.expectNamedModel()+ await model.saveHost(firstName)await expect(page.getByRole('button', { name: 'Revoke', exact: true })).toHaveCount(0)await expect(page.getByRole('link', { name: 'Manage subscription' })).toBeVisible()@@ -340,85 +315,82 @@ test.describe('Codex subscription connection', () => {expect(after.find(row => row.connectionKey === grantKey)?.status).not.toBe('revoked')})- test('Secrets Subscription hub creates, assigns, and is the only revoke path', async ({+ test('Secrets Subscription hub creates, assigns two agents, 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 shell = new ControlUiShell(page)+ const hub = new CodexSubscriptionHubPage(page)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'- )- 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 } }++ await test.step('reach the hub through Secrets → Subscription', async () => {+ await loginFromHome(page)+ await shell.openAgents()+ await seedCodexAgents(page, 2)+ await shell.openSecretsSubscription()+ await hub.expectTable()+ })++ const grantKey = await test.step('create a grant from the hub CTA', () =>+ hub.createGrant(displayName))++ const bound = await test.step('assign two agents in one hub action', () =>+ hub.assignFirstAgents(grantKey, 2))++ 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: hostName })).toBeVisible()+ const host = (await controlApi.getHost(hostName)) as {+ spec?: { model?: { connectionRef?: string } }+ }+ expect(host.spec?.model?.connectionRef).toBe(grantKey)}- 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 } }+ await test.step('revoke only from the hub danger action', async () => {+ const revoke = page.waitForResponse(+ response =>+ new RegExp(+ `/api/v1/admin/llm/providers/codex-subscription/connections/${grantKey}/revoke$`+ ).test(new URL(response.url()).pathname) && response.request().method() === 'POST'+ )+ await grantRow.getByRole('button', { name: 'Revoke subscription' }).click()+ await expect(page.getByRole('alertdialog')).toBeVisible()+ await page+ .getByRole('alertdialog')+ .getByRole('button', { name: 'Revoke subscription' })+ .click()+ const revokeRes = await revoke+ expect(revokeRes.ok(), `revoke must succeed, got ${revokeRes.status()}`).toBe(true)+ const revokeBody = (await revokeRes.json()) as { status?: string; connectionKey?: string }+ expect(revokeBody.status).toBe('revoked')+ expect(revokeBody.connectionKey).toBe(grantKey)+ })++ for (const hostName of bound) {+ const afterHost = (await controlApi.getHost(hostName)) as {+ spec?: { model?: { connectionRef?: string } }+ }+ expect(afterHost.spec?.model?.connectionRef).toBe(grantKey)}- 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()+ test('LLM secrets empty state or tab reaches the Subscription hub', async ({ page }) => {+ const shell = new ControlUiShell(page)+ await loginFromHome(page)+ await shell.openSecretsLlm()await expect(page).toHaveURL(/\/secrets\/llm$/)- const link = page.getByRole('link', {++ const emptyLink = 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()+ const tab = page.getByRole('tab', { name: 'Subscription' })+ await expect(tab).toBeVisible()+ if ((await emptyLink.count()) > 0) {+ await emptyLink.click()+ } else {+ await tab.click()}+ await expect(page).toHaveURL(/\/secrets\/subscription$/)+ await expect(page.getByTestId('codex-subscription-hub')).toBeVisible()})})diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.jsonindex 33ac64ea4..aa59e6028 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.30",+ "version": "0.1.31","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-playwright-tests",- "version": "0.1.30",+ "version": "0.1.31","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 11f4311da..bc0f1d782 100644--- a/tests/e2e/playwright/package.json+++ b/tests/e2e/playwright/package.json@@ -1,6 +1,6 @@{"name": "clerum-playwright-tests",- "version": "0.1.30",+ "version": "0.1.31","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.tsnew file mode 100644index 000000000..01ccfd6a6--- /dev/null+++ b/tests/e2e/playwright/pages/codex-subscription.ts@@ -0,0 +1,243 @@+/**+ * Page objects for Codex subscription Control UI journeys.+ *+ * Guardian: helpers only click/assert user-visible controls. API seeding lives+ * in the spec and is named as a precondition, never as the behavior under test.+ */+import { type Locator, type Page, expect } from '@playwright/test'++export class ControlUiShell {+ constructor(readonly page: Page) {}++ async openAgents() {+ await this.page.getByRole('link', { name: 'Agents', exact: true }).click()+ await expect(this.page).toHaveURL(/\/(?:hosts|agents)$/)+ await expect(this.page.getByRole('button', { name: /Reload agents/i })).toBeVisible()+ }++ async openSecretsLlm() {+ await this.page.getByRole('link', { name: 'Secrets', exact: true }).click()+ await expect(this.page).toHaveURL(/\/secrets\/(llm)?$/)+ }++ async openSecretsSubscription() {+ await this.openSecretsLlm()+ await this.page.getByRole('tab', { name: 'Subscription' }).click()+ await expect(this.page).toHaveURL(/\/secrets\/subscription$/)+ await expect(this.page.getByTestId('codex-subscription-hub')).toBeVisible()+ }+}++export class AgentListPage {+ constructor(readonly page: Page) {}++ rows(): Locator {+ return this.page.getByRole('row', { name: /Open agent / })+ }++ async openNamed(name: string): Promise<void> {+ const row = this.page.getByRole('row', { name: `Open agent ${name}` })+ await expect(row).toBeVisible()+ await row.click()+ await expect(this.page).toHaveURL(new RegExp(`/((?:hosts|agents))/${name}(?:/|$)`))+ }++ async openNth(index: number): Promise<string> {+ const row = this.rows().nth(index)+ await expect(row).toBeVisible()+ const label = (await row.getAttribute('aria-label')) ?? ''+ const name = label.replace(/^Open agent\s+/, '').trim()+ expect(name, 'agent row must expose a name').toMatch(/\S/)+ await row.click()+ await expect(this.page).toHaveURL(/\/(?:hosts|agents)\/[^/]+/)+ return decodeURIComponent(name)+ }+}++export class AgentModelPage {+ constructor(readonly page: Page) {}++ subscriptionPicker(): Locator {+ return this.page.locator('#codex-subscription')+ }++ modelSelect(): Locator {+ return this.page.getByLabel(/^Model$/i)+ }++ saveButton(): Locator {+ return this.page.getByRole('button', { name: 'Save', exact: true })+ }++ async openEditor() {+ await this.page.getByRole('tab', { name: 'Models & creds' }).click()+ await expect(this.page).toHaveURL(/\/(?:hosts|agents)\/[^/]+\/model/)+ await expect(+ this.page.getByRole('tab', { name: 'Models & creds', selected: true })+ ).toBeVisible()+ const edit = this.page.getByRole('button', { name: 'Edit', exact: true })+ if ((await edit.count()) > 0) {+ await edit.click()+ }+ await expect(this.page.getByLabel('Provider')).toBeVisible()+ }++ async chooseChatGPTSubscription() {+ await this.page.getByLabel('Provider').click()+ await this.page.getByRole('option', { name: 'OpenAI', exact: true }).click()+ await expect(this.page.getByRole('option', { name: 'OpenAI Codex Subscription' })).toHaveCount(+ 0+ )+ await this.page.getByRole('radio', { name: 'ChatGPT subscription' }).check()+ await expect(this.page.getByTestId('codex-agent-assignment')).toBeVisible()+ await expect(this.page.getByLabel(/OpenAI API key/i)).toHaveCount(0)+ }++ async expectNamedModel(): Promise<string> {+ const select = this.modelSelect()+ await expect(select).toBeVisible()+ const value = ((await select.textContent()) ?? '').trim()+ expect(+ value,+ 'ChatGPT switch must keep or seed spec.model.name — empty name is the 422 bug'+ ).toMatch(/\S/)+ expect(value, 'placeholder is not a saved model name').not.toMatch(+ /select model|no enabled models/i+ )+ return value+ }++ async createGrant(displayName: string): Promise<string> {+ await this.page.getByRole('button', { name: 'New subscription' }).click()+ await this.page.getByLabel('New subscription name').fill(displayName)+ const created = this.page.waitForResponse(+ response =>+ /\/api\/v1\/admin\/llm\/providers\/codex-subscription\/connections$/.test(+ new URL(response.url()).pathname+ ) && response.request().method() === 'POST'+ )+ await this.page.getByRole('button', { name: 'Create', exact: true }).click()+ const response = await created+ expect(response.ok(), `create grant must succeed, got ${response.status()}`).toBe(true)+ const body = (await response.json()) as { connectionKey?: string }+ expect(body.connectionKey).toEqual(expect.any(String))+ await expect(this.subscriptionPicker()).toHaveValue(String(body.connectionKey))+ return String(body.connectionKey)+ }++ async saveHost(agentName: string) {+ await expect(this.saveButton()).toBeEnabled()+ const put = this.page.waitForResponse(+ response =>+ new RegExp(`/api/v1/admin/hosts/${agentName}$`).test(new URL(response.url()).pathname) &&+ response.request().method() === 'PUT'+ )+ await this.saveButton().click()+ const response = await put+ expect(+ response.status(),+ 'assign save must not 422 empty model.name or model_not_offered'+ ).not.toBe(422)+ expect(response.ok(), `assign save must succeed, got ${response.status()}`).toBe(true)+ return (await response.json()) as {+ spec?: { model?: { provider?: string; name?: string; connectionRef?: string } }+ }+ }+}++export class CodexSubscriptionHubPage {+ constructor(readonly page: Page) {}++ table(): Locator {+ return this.page.getByTestId('codex-hub-table')+ }++ grantRow(connectionKey: string): Locator {+ return this.page.getByTestId(`codex-hub-grant-${connectionKey}`)+ }++ async expectTable() {+ await expect(this.table()).toBeVisible()+ await expect(this.page.getByRole('columnheader', { name: 'Name' })).toBeVisible()+ await expect(this.page.getByRole('columnheader', { name: 'Status' })).toBeVisible()+ await expect(this.page.getByRole('columnheader', { name: 'Agents' })).toBeVisible()+ await expect(this.page.getByRole('heading', { name: 'Available' })).toHaveCount(0)+ await expect(this.page.getByRole('heading', { name: 'Assigned' })).toHaveCount(0)+ }++ async createGrant(displayName: string): Promise<string> {+ await this.page.getByRole('button', { name: 'Add subscription' }).click()+ await this.page.getByLabel('New subscription name').fill(displayName)+ const created = this.page.waitForResponse(+ response =>+ /\/api\/v1\/admin\/llm\/providers\/codex-subscription\/connections$/.test(+ new URL(response.url()).pathname+ ) && response.request().method() === 'POST'+ )+ await this.page.getByRole('button', { name: 'Create', exact: true }).click()+ const response = await created+ expect(response.ok(), `hub create must succeed, got ${response.status()}`).toBe(true)+ const body = (await response.json()) as { connectionKey?: string }+ expect(body.connectionKey).toEqual(expect.any(String))+ await expect(this.page.getByText(displayName)).toBeVisible()+ return String(body.connectionKey)+ }++ async assignFirstAgents(connectionKey: string, count: number): Promise<string[]> {+ const row = this.grantRow(connectionKey)+ await expect(row.getByLabel('Add agents to this subscription')).toBeVisible()+ await row.getByLabel('Add agents to this subscription').click()+ const options = row.getByRole('option')+ await expect(+ options.first(),+ 'hub assign requires seeded Codex agents — API seed is a named precondition'+ ).toBeVisible()+ const available = await options.count()+ expect(+ available,+ `hub multi-assign needs ${count} agents, found ${available}`+ ).toBeGreaterThanOrEqual(count)++ const names: string[] = []+ for (let index = 0; index < count; index += 1) {+ const option = options.nth(index)+ const label = ((await option.getAttribute('aria-label')) ?? '').trim()+ expect(label, `assignable agent #${index + 1} must have a name`).toMatch(/\S/)+ names.push(label)+ await option.click()+ }++ const bindPath = new RegExp(+ `/api/v1/admin/llm/providers/codex-subscription/connections/${connectionKey}/hosts/[^/]+/bind$`+ )+ const bindBodies: Promise<{ host?: string; connectionRef?: string; ok: boolean }>[] = []+ const onResponse = (response: import('@playwright/test').Response) => {+ if (+ bindPath.test(new URL(response.url()).pathname) &&+ response.request().method() === 'POST'+ ) {+ bindBodies.push(+ response.json().then(body => ({+ ...(body as { host?: string; connectionRef?: string }),+ ok: response.ok(),+ }))+ )+ }+ }+ this.page.on('response', onResponse)++ await row+ .getByRole('button', { name: count > 1 ? `Add ${count} agents` : 'Add agents' })+ .click()+ await expect+ .poll(() => bindBodies.length, { message: `expected ${count} bind responses` })+ .toBe(count)+ this.page.off('response', onResponse)+ const binds = await Promise.all(bindBodies)+ for (const bind of binds) {+ expect(bind.ok, 'each hub bind must succeed').toBe(true)+ expect(bind.connectionRef).toBe(connectionKey)+ }+ return names+ }+}