Skip to content

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

TypeScript

fix(control-ui): bind recipe grants to their provider and isolate hub brokers

Jose Gabriel Ramirez Encinasa42dedf89127
diff --git a/control-ui/app/plugin-workload-sdk/page.tsx b/control-ui/app/plugin-workload-sdk/page.tsx
index def21b349..98f2191a5 100644
--- a/control-ui/app/plugin-workload-sdk/page.tsx
+++ b/control-ui/app/plugin-workload-sdk/page.tsx
@@ -575,8 +575,13 @@ function GrantFormModal({
.then(capability => {
if (!cancelled) setGrokEnabled(capability.enabled)
})
- .catch(() => {
- if (!cancelled) setGrokEnabled(false)
+ .catch(err => {
+ if (cancelled) return
+ // loadGrokSubscriptionCapability already maps "disabled" to
+ // { enabled: false }; anything reaching here is a real probe failure
+ // and must not be presented as the flag being off.
+ setGrokEnabled(false)
+ setError(err instanceof Error ? err.message : 'Could not load Grok subscriptions')
})
return () => {
cancelled = true
diff --git a/control-ui/components/CodexSubscriptionHub/index.tsx b/control-ui/components/CodexSubscriptionHub/index.tsx
index 428bd596c..49cbda9e3 100644
--- a/control-ui/components/CodexSubscriptionHub/index.tsx
+++ b/control-ui/components/CodexSubscriptionHub/index.tsx
@@ -30,6 +30,7 @@ import {
GROK_DEVICE_VERIFICATION_ORIGIN,
type GrokSubscriptionConnectionView,
createGrokSubscriptionConnection,
+ isAllowedGrokVerificationUri,
listGrokConnectionModels,
listGrokSubscriptionConnections,
patchGrokCatalogModel,
@@ -63,6 +64,33 @@ import { CheckboxField } from '../ui'
type HubBroker = 'codex-subscription' | 'grok-subscription'
type HubConnection = CodexSubscriptionConnectionView & { broker: HubBroker }
+// Both brokers let callers choose connection keys in independent namespaces,
+// so every row identity (React key, sort identity, busy state, edit matching)
+// is provider-qualified.
+function hubRowId(row: Pick<HubConnection, 'broker' | 'connectionKey'>): string {
+ return `${row.broker}:${row.connectionKey}`
+}
+
+type HubProviderCopy = {
+ brand: string
+ verificationFallback: string
+}
+
+const HUB_PROVIDER_COPY: Record<HubBroker, HubProviderCopy> = {
+ 'codex-subscription': {
+ brand: 'ChatGPT',
+ verificationFallback: CODEX_DEVICE_VERIFICATION_URI,
+ },
+ 'grok-subscription': {
+ brand: 'Grok',
+ verificationFallback: GROK_DEVICE_VERIFICATION_ORIGIN,
+ },
+}
+
+type HubListErrors = Record<HubBroker, string>
+
+const NO_LIST_ERRORS: HubListErrors = { 'codex-subscription': '', 'grok-subscription': '' }
+
function grantLabel(row: CodexSubscriptionConnectionView): string {
return row.displayName || row.connectionKey
}
@@ -96,7 +124,11 @@ export function CodexSubscriptionHub() {
const { confirm, confirmDialog } = useConfirmDialog()
const [capability, setCapability] = useState<CodexSubscriptionCapability | null>(null)
const [grokCapability, setGrokCapability] = useState<GrokSubscriptionCapability | null>(null)
- const [connections, setConnections] = useState<HubConnection[]>([])
+ const [rowsByBroker, setRowsByBroker] = useState<Record<HubBroker, HubConnection[]>>({
+ 'codex-subscription': [],
+ 'grok-subscription': [],
+ })
+ const [listErrors, setListErrors] = useState<HubListErrors>(NO_LIST_ERRORS)
const [createBroker, setCreateBroker] = useState<HubBroker>('codex-subscription')
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
@@ -126,29 +158,71 @@ export function CodexSubscriptionHub() {
const grokEnabled = isGrokSubscriptionUiEnabled(grokCapability)
useEffect(() => {
+ // A capability probe that fails for any reason other than "disabled" is
+ // kept on the capability itself, so later action-error resets cannot
+ // hide it and the other provider still loads.
void loadCodexSubscriptionCapability()
.then(setCapability)
.catch(err => {
- setCapability({ enabled: false, error: err instanceof Error ? err.message : 'unavailable' })
- setError(err instanceof Error ? err.message : 'Failed to load ChatGPT subscriptions')
+ setCapability({
+ enabled: false,
+ error: err instanceof Error ? err.message : 'Failed to load ChatGPT subscriptions',
+ })
setLoading(false)
})
void loadGrokSubscriptionCapability()
.then(setGrokCapability)
- .catch(() => {
- setGrokCapability({ enabled: false })
+ .catch(err => {
+ setGrokCapability({
+ enabled: false,
+ error: err instanceof Error ? err.message : 'Failed to load Grok subscriptions',
+ })
})
}, [])
- const load = useCallback(async () => {
- const [codexRows, grokRows] = await Promise.all([
+ const connections = useMemo(
+ () => [...rowsByBroker['codex-subscription'], ...rowsByBroker['grok-subscription']],
+ [rowsByBroker]
+ )
+
+ // Each provider loads independently: a failing list keeps that provider's
+ // last rows and records its own error, and never discards the healthy
+ // provider's result. Resolves with whether any enabled provider failed.
+ const load = useCallback(async (): Promise<{ failed: boolean }> => {
+ const [codexResult, grokResult] = await Promise.allSettled([
enabled ? listCodexSubscriptionConnections() : Promise.resolve([]),
grokEnabled ? listGrokSubscriptionConnections() : Promise.resolve([]),
])
- setConnections([
- ...codexRows.map(row => asHubRow(row, 'codex-subscription')),
- ...grokRows.map(row => asHubRow(row, 'grok-subscription')),
- ])
+ const bothEnabled = enabled && grokEnabled
+ const describeFailure = (broker: HubBroker, reason: unknown) => {
+ const brand = HUB_PROVIDER_COPY[broker].brand
+ const message =
+ reason instanceof Error && reason.message
+ ? reason.message
+ : `Failed to load ${brand} subscriptions`
+ return bothEnabled ? `${brand} subscriptions: ${message}` : message
+ }
+ setRowsByBroker(current => ({
+ 'codex-subscription':
+ codexResult.status === 'fulfilled'
+ ? codexResult.value.map(row => asHubRow(row, 'codex-subscription'))
+ : current['codex-subscription'],
+ 'grok-subscription':
+ grokResult.status === 'fulfilled'
+ ? grokResult.value.map(row => asHubRow(row, 'grok-subscription'))
+ : current['grok-subscription'],
+ }))
+ setListErrors({
+ 'codex-subscription':
+ codexResult.status === 'rejected'
+ ? describeFailure('codex-subscription', codexResult.reason)
+ : '',
+ 'grok-subscription':
+ grokResult.status === 'rejected'
+ ? describeFailure('grok-subscription', grokResult.reason)
+ : '',
+ })
+ return { failed: codexResult.status === 'rejected' || grokResult.status === 'rejected' }
}, [enabled, grokEnabled])
useEffect(() => {
@@ -158,12 +232,7 @@ export function CodexSubscriptionHub() {
return
}
setLoading(true)
- setError('')
- void load()
- .catch(err => {
- setError(err instanceof Error ? err.message : 'Failed to load ChatGPT subscriptions')
- })
- .finally(() => setLoading(false))
+ void load().finally(() => setLoading(false))
}, [capability, grokCapability, enabled, grokEnabled, load])
useEffect(() => {
@@ -183,7 +252,7 @@ export function CodexSubscriptionHub() {
const subscriptionSort = useTableSort<HubConnection, 'name' | 'status'>({
rows: filtered,
defaultKey: 'name',
- identity: row => row.connectionKey,
+ identity: hubRowId,
accessors: {
name: grantLabel,
status: row => statusLabel(mapConnectionStatus(row.status)),
@@ -221,9 +290,8 @@ export function CodexSubscriptionHub() {
setBusyKey(null)
// Sign-in starts regardless of whether the table refresh succeeds.
void handleConnect(created)
- try {
- await load()
- } catch {
+ const refreshed = await load()
+ if (refreshed.failed) {
showToast('Subscription created, but the list could not be refreshed.', { tone: 'info' })
}
}
@@ -279,9 +347,7 @@ export function CodexSubscriptionHub() {
setUserCode(null)
setVerificationUri(null)
setDeviceTabBlocked(false)
- void load().catch(err => {
- setError(err instanceof Error ? err.message : 'Failed to load ChatGPT subscriptions')
- })
+ void load()
}
async function handleSaveEdit() {
@@ -290,7 +356,7 @@ export function CodexSubscriptionHub() {
setError('Give the subscription a name before finishing.')
return
}
- setBusyKey(editing.connectionKey)
+ setBusyKey(hubRowId(editing))
try {
const updated =
editing.broker === 'grok-subscription'
@@ -311,7 +377,7 @@ export function CodexSubscriptionHub() {
setEditing(updated)
// A refresh failure after a successful patch is partial — the update
// itself landed, so it must not surface as "update failed".
- await load().catch(() => {})
+ await load()
showToast(
setupNew
? `Subscription ${grantLabel(updated)} is ready.`
@@ -328,21 +394,44 @@ export function CodexSubscriptionHub() {
async function handleConnect(row: HubConnection) {
const epoch = ++connectEpoch.current
- setBusyKey(row.connectionKey)
+ setBusyKey(hubRowId(row))
const grok = row.broker === 'grok-subscription'
+ const brand = HUB_PROVIDER_COPY[row.broker].brand
// Open the verification page synchronously, inside the click handler and
// before any await — popup blockers honour user activation here, so the
// tab reliably appears. The device code lands in the card right after.
// The card only claims the tab opened when open() actually returned one.
let openedTab: Window | null = null
+ // Grok's verification URI is only known once the device start returns, so
+ // Grok opens an empty tab now (detached from this window) and navigates it
+ // to the returned, allow-listed URI after the await.
+ let pendingGrokTab: Window | null = null
+ const discardPendingGrokTab = () => {
+ if (!pendingGrokTab) return
+ try {
+ pendingGrokTab.close()
+ } catch {
+ // The tab may already be gone; nothing to clean up.
+ }
+ pendingGrokTab = null
+ }
try {
- openedTab = window.open(
- grok ? GROK_DEVICE_VERIFICATION_ORIGIN : CODEX_DEVICE_VERIFICATION_URI,
- '_blank',
- 'noopener,noreferrer'
- )
+ if (grok) {
+ openedTab = window.open('', '_blank')
+ if (openedTab) {
+ try {
+ openedTab.opener = null
+ } catch {
+ // Best effort: some browsers expose a read-only opener.
+ }
+ }
+ pendingGrokTab = openedTab
+ } else {
+ openedTab = window.open(CODEX_DEVICE_VERIFICATION_URI, '_blank', 'noopener,noreferrer')
+ }
} catch {
openedTab = null
+ pendingGrokTab = null
}
setDeviceTabBlocked(!openedTab)
try {
@@ -355,7 +444,28 @@ export function CodexSubscriptionHub() {
row.status === 'connected' ? 'reconnect' : 'connect',
row.connectionKey
)
- if (epoch !== connectEpoch.current) return
+ if (epoch !== connectEpoch.current) {
+ discardPendingGrokTab()
+ return
+ }
+ if (grok && pendingGrokTab) {
+ const tab: Window = pendingGrokTab
+ pendingGrokTab = null
+ if (isAllowedGrokVerificationUri(started.verificationUri)) {
+ try {
+ tab.location.replace(started.verificationUri)
+ } catch {
+ setDeviceTabBlocked(true)
+ }
+ } else {
+ try {
+ tab.close()
+ } catch {
+ // Already closed.
+ }
+ setDeviceTabBlocked(true)
+ }
+ }
setUserCode(started.userCode)
setVerificationUri(started.verificationUri)
const deadline = Date.now() + started.intervalSeconds * 1000 * 40
@@ -378,7 +488,7 @@ export function CodexSubscriptionHub() {
setEditModels(models)
// A table refresh failure here is partial — connect itself worked,
// so it must not surface as "sign-in failed".
- await load().catch(() => {})
+ await load()
if (epoch !== connectEpoch.current) return
// The backend syncs the catalog during connect — surface the outcome.
if (latest.catalogStatus === 'ready') {
@@ -393,19 +503,20 @@ export function CodexSubscriptionHub() {
if (polled.status === 'expired' || polled.status === 'denied') {
setUserCode(null)
setVerificationUri(null)
- setError(`${grok ? 'Grok' : 'ChatGPT'} sign-in ${polled.status}. Try again.`)
+ setError(`${brand} sign-in ${polled.status}. Try again.`)
return
}
}
if (epoch !== connectEpoch.current) return
setUserCode(null)
setVerificationUri(null)
- setError(`${grok ? 'Grok' : 'ChatGPT'} sign-in timed out. Try again.`)
+ setError(`${brand} sign-in timed out. Try again.`)
} catch (err) {
+ discardPendingGrokTab()
if (epoch !== connectEpoch.current) return
setUserCode(null)
setVerificationUri(null)
- setError(err instanceof Error ? err.message : `${grok ? 'Grok' : 'ChatGPT'} sign-in failed`)
+ setError(err instanceof Error ? err.message : `${brand} sign-in failed`)
} finally {
if (epoch === connectEpoch.current) {
setBusyKey(null)
@@ -414,7 +525,7 @@ export function CodexSubscriptionHub() {
}
async function handleToggleModel(row: HubConnection, model: string, enabledNext: boolean) {
- setBusyKey(row.connectionKey)
+ setBusyKey(hubRowId(row))
try {
const models =
row.broker === 'grok-subscription'
@@ -432,17 +543,17 @@ export function CodexSubscriptionHub() {
async function handleRevoke(row: HubConnection) {
const grok = row.broker === 'grok-subscription'
const confirmed = await confirm({
- title: grok ? 'Delete Grok subscription' : 'Delete ChatGPT subscription',
+ title: `Delete ${HUB_PROVIDER_COPY[row.broker].brand} subscription`,
message: `Revoke ${grantLabel(row)}? Assigned agents keep the reference and stop authorizing.`,
confirmLabel: 'Delete',
tone: 'danger',
})
if (!confirmed) return
- setBusyKey(row.connectionKey)
+ setBusyKey(hubRowId(row))
try {
if (grok) await revokeGrokSubscription(row.connectionKey)
else await revokeCodexSubscription(row.connectionKey)
- if (editing?.connectionKey === row.connectionKey) closeEdit()
+ if (editing && hubRowId(editing) === hubRowId(row)) closeEdit()
await load()
showToast(`Subscription ${grantLabel(row)} revoked.`, { tone: 'success' })
} catch (err) {
@@ -455,6 +566,21 @@ export function CodexSubscriptionHub() {
const offeredDefaults = editModels.filter(row => row.enabled && !row.stale).map(row => row.model)
const initialLoad = loading && connections.length === 0
const uiStatus = editing ? mapConnectionStatus(editing.status) : 'disconnected'
+ const dialogBroker: HubBroker = editing?.broker ?? createBroker
+ const dialogCopy = HUB_PROVIDER_COPY[dialogBroker]
+ // Table-level copy stays ChatGPT-specific while Grok is off (unchanged Codex
+ // hub); once Grok is on the list is provider-neutral.
+ const listNoun = grokEnabled
+ ? enabled
+ ? 'subscriptions'
+ : 'Grok subscriptions'
+ : 'ChatGPT subscriptions'
+ const loadErrors = [
+ capability?.error ?? '',
+ grokCapability?.error ?? '',
+ listErrors['codex-subscription'],
+ listErrors['grok-subscription'],
+ ].filter(Boolean)
if (capability !== null && grokCapability !== null && !enabled && !grokEnabled) {
return (
@@ -507,15 +633,9 @@ export function CodexSubscriptionHub() {
<button
type="button"
className="cu-btn cu-btn--icon cu-btn--toolbar"
- onClick={() =>
- void load().catch(err => {
- setError(
- err instanceof Error ? err.message : 'Failed to load ChatGPT subscriptions'
- )
- })
- }
+ onClick={() => void load()}
disabled={initialLoad || loading}
- aria-label={loading ? 'Refreshing...' : 'Reload ChatGPT subscriptions'}
+ aria-label={loading ? 'Refreshing...' : `Reload ${listNoun}`}
>
<IconRefresh className={loading ? 'cu-spin' : undefined} width={18} height={18} />
</button>
@@ -525,7 +645,7 @@ export function CodexSubscriptionHub() {
value={searchQuery}
onChange={setSearchQuery}
placeholder="Search secrets"
- ariaLabel="Search ChatGPT subscriptions"
+ ariaLabel={`Search ${listNoun}`}
disabled={initialLoad}
/>
}
@@ -535,9 +655,14 @@ export function CodexSubscriptionHub() {
<SecretsScopeTabs activeValue="llm-subscriptions" />
</div>
- {error && !creating && !editing ? (
+ {(loadErrors.length > 0 || error) && !creating && !editing ? (
<div className="cu-card__body cu-card__body--auto cu-secrets-message-strip">
- <div className="cu-banner cu-banner--error">{error}</div>
+ {loadErrors.map(message => (
+ <div key={message} className="cu-banner cu-banner--error">
+ {message}
+ </div>
+ ))}
+ {error ? <div className="cu-banner cu-banner--error">{error}</div> : null}
</div>
) : null}
@@ -564,34 +689,30 @@ export function CodexSubscriptionHub() {
</thead>
<tbody>
{initialLoad ? (
- <TableStateRow
- colSpan={3}
- kind="loading"
- message="Loading ChatGPT subscriptions…"
- />
- ) : error && filtered.length === 0 ? (
- <TableStateRow colSpan={3} kind="error" message={error} />
+ <TableStateRow colSpan={3} kind="loading" message={`Loading ${listNoun}…`} />
+ ) : (error || loadErrors.length > 0) && filtered.length === 0 ? (
+ <TableStateRow colSpan={3} kind="error" message={error || loadErrors[0]} />
) : filtered.length === 0 ? (
<TableStateRow
colSpan={3}
message={
searchQuery.trim()
- ? 'No ChatGPT subscriptions match this search.'
- : 'No ChatGPT subscriptions found.'
+ ? `No ${listNoun} match this search.`
+ : `No ${listNoun} found.`
}
/>
) : (
subscriptionSort.sortedRows.map(row => {
const mapped = mapConnectionStatus(row.status)
return (
- <tr key={row.connectionKey}>
+ <tr key={hubRowId(row)}>
<td>{grantLabel(row)}</td>
<td>
<span className={statusTagClass(mapped)}>{statusLabel(mapped)}</span>
</td>
<td className="cu-table__cell-actions">
<RowActionsMenu
- ariaLabel={`Actions for ChatGPT subscription ${grantLabel(row)}`}
+ ariaLabel={`Actions for ${HUB_PROVIDER_COPY[row.broker].brand} subscription ${grantLabel(row)}`}
horizontalTrigger
actions={[
{
@@ -601,9 +722,9 @@ export function CodexSubscriptionHub() {
},
{
key: 'delete',
- label: busyKey === row.connectionKey ? 'Deleting…' : 'Delete',
+ label: busyKey === hubRowId(row) ? 'Deleting…' : 'Delete',
danger: true,
- disabled: busyKey === row.connectionKey,
+ disabled: busyKey === hubRowId(row),
onClick: () => void handleRevoke(row),
},
]}
@@ -638,12 +759,12 @@ export function CodexSubscriptionHub() {
<div className="cu-modal-panel__head">
<strong id="codex-modal-title" style={{ fontSize: '1rem', lineHeight: 1.35 }}>
{creating
- ? 'New ChatGPT subscription'
+ ? `New ${dialogCopy.brand} subscription`
: editing && setupNew
- ? `Set up ChatGPT subscription ${grantLabel(editing)}`
+ ? `Set up ${dialogCopy.brand} subscription ${grantLabel(editing)}`
: editing
- ? `Update ChatGPT subscription ${grantLabel(editing)}`
- : 'New ChatGPT subscription'}
+ ? `Update ${dialogCopy.brand} subscription ${grantLabel(editing)}`
+ : `New ${dialogCopy.brand} subscription`}
</strong>
<button
type="button"
@@ -702,15 +823,11 @@ export function CodexSubscriptionHub() {
<section className="cu-llm-config" aria-label="Subscription configuration">
<div className="cu-llm-config__block">
<div className="cu-llm-config__block-head">
- <span className="cu-llm-config__block-title">
- {(editing?.broker ?? createBroker) === 'grok-subscription'
- ? 'Grok sign-in'
- : 'ChatGPT sign-in'}
- </span>
+ <span className="cu-llm-config__block-title">{dialogCopy.brand} sign-in</span>
<span className={statusTagClass(uiStatus)}>{statusLabel(uiStatus)}</span>
</div>
<p className="cu-field__hint" style={{ margin: 0 }}>
- {(editing?.broker ?? createBroker) === 'grok-subscription'
+ {dialogBroker === 'grok-subscription'
? GROK_TOS
: setupNew || !editing
? 'Agents authorize through this subscription’s ChatGPT grant. Sign in to connect it — the catalog syncs automatically.'
@@ -733,9 +850,7 @@ export function CodexSubscriptionHub() {
}}
disabled={Boolean(busyKey)}
>
- {(editing?.broker ?? createBroker) === 'grok-subscription'
- ? 'Sign in with Grok'
- : 'Sign in with ChatGPT'}
+ {`Sign in with ${dialogCopy.brand}`}
</button>
</span>
</div>
@@ -743,13 +858,13 @@ export function CodexSubscriptionHub() {
<div className="cu-device-setup" data-testid="codex-device-code">
<p className="cu-device-setup__step">
{deviceTabBlocked
- ? '1. Open the ChatGPT verification page:'
- : '1. ChatGPT opened in a new tab — if it did not, use this link:'}
+ ? `1. Open the ${dialogCopy.brand} verification page:`
+ : `1. ${dialogCopy.brand} opened in a new tab — if it did not, use this link:`}
</p>
{(() => {
// Locked fallback (from dev): even if the backend
// omits the verification URI, the card keeps a link.
- const deviceUri = verificationUri ?? CODEX_DEVICE_VERIFICATION_URI
+ const deviceUri = verificationUri ?? dialogCopy.verificationFallback
return (
<div className="cu-copy-field">
<a
@@ -792,7 +907,7 @@ export function CodexSubscriptionHub() {
</div>
<p className="cu-device-setup__note" role="status">
Checking automatically — this dialog continues as soon as you approve the
- code in ChatGPT.
+ code in {dialogCopy.brand}.
</p>
</div>
) : null}
@@ -817,15 +932,14 @@ export function CodexSubscriptionHub() {
disabled={Boolean(busyKey) || model.stale}
label={
<span className="cu-px-provider">
- <LlmProviderIcon
- provider="codex-subscription"
- label={model.model}
- />
+ <LlmProviderIcon provider={dialogBroker} label={model.model} />
{model.model}
</span>
}
description={
- model.stale ? 'No longer in the ChatGPT catalog.' : undefined
+ model.stale
+ ? `No longer in the ${dialogCopy.brand} catalog.`
+ : undefined
}
onChange={e =>
editing
@@ -837,12 +951,13 @@ export function CodexSubscriptionHub() {
</div>
) : (
<p className="cu-field__hint" style={{ margin: 0 }}>
- No models yet — confirm the name, sign in with ChatGPT, and sync the catalog
- to load the models this grant offers.
+ No models yet — confirm the name, sign in with {dialogCopy.brand}, and sync
+ the catalog to load the models this grant offers.
</p>
)}
<span className="cu-field__hint">
- Synced from the ChatGPT catalog. Disabled models are not offered to agents.
+ Synced from the {dialogCopy.brand} catalog. Disabled models are not offered to
+ agents.
</span>
</div>
) : null}
@@ -861,7 +976,7 @@ export function CodexSubscriptionHub() {
options={offeredDefaults.map(model => ({
value: model,
label: model,
- icon: <LlmProviderIcon provider="codex-subscription" label={model} />,
+ icon: <LlmProviderIcon provider={dialogBroker} label={model} />,
}))}
placeholder={
offeredDefaults.length === 0 ? 'No enabled models' : 'Select model…'
diff --git a/control-ui/components/RecipeEditor.tsx b/control-ui/components/RecipeEditor.tsx
index 0ee60b238..14a4bf16b 100644
--- a/control-ui/components/RecipeEditor.tsx
+++ b/control-ui/components/RecipeEditor.tsx
@@ -124,16 +124,143 @@ function readRecipeOauthBrokerProvider(spec: unknown): string {
return ids.length === 1 ? ids[0] : ''
}
-function readRecipeCodexGrantAnnotation(
- resource?: { metadata?: { annotations?: Record<string, string> } } | null
-): string {
- const annotations = resource?.metadata?.annotations
- const canonical = annotations?.[SUBSCRIPTION_CONNECTION_REF_ANNOTATION]
- const alias = annotations?.[CODEX_CONNECTION_REF_ANNOTATION]
- const raw = typeof canonical === 'string' && canonical.trim() ? canonical : alias
+type RecipeGrantProvider =
+ | typeof OPENAI_SUBSCRIPTION_PROVIDER
+ | typeof GROK_SUBSCRIPTION_PROVIDER
+ | ''
+
+/**
+ * The recipe's subscription grant is always bound to the oauth-broker provider
+ * it was read or chosen for. A selection for one provider is never reused for
+ * another provider (see `grantSelectionForProvider`).
+ */
+type RecipeGrantSelection = {
+ provider: RecipeGrantProvider
+ key: string
+ /** Non-empty when stored annotations cannot be read for `provider`. */
+ conflict: string
+}
+
+function asRecipeGrantProvider(provider: string): RecipeGrantProvider {
+ return provider === OPENAI_SUBSCRIPTION_PROVIDER || provider === GROK_SUBSCRIPTION_PROVIDER
+ ? provider
+ : ''
+}
+
+function trimmedAnnotation(annotations: Record<string, string> | undefined, key: string): string {
+ const raw = annotations?.[key]
return typeof raw === 'string' ? raw.trim() : ''
}
+function normalizedGrantKey(key: string): string {
+ return key && key !== CODEX_UNASSIGNED_CONNECTION_KEY ? key : ''
+}
+
+/**
+ * Provider-aware reader mirroring the server's subscription grant identity:
+ * Codex accepts canonical or alias but fails when both are set and unequal;
+ * Grok reads only the canonical annotation and fails on any non-empty Codex
+ * alias. An unreadable pair yields no key plus a conflict, so the editor never
+ * turns a mismatch into an assigned grant.
+ */
+function readRecipeGrantAnnotations(
+ provider: RecipeGrantProvider,
+ annotations: Record<string, string> | undefined
+): { key: string; conflict: string } {
+ const canonical = trimmedAnnotation(annotations, SUBSCRIPTION_CONNECTION_REF_ANNOTATION)
+ const alias = trimmedAnnotation(annotations, CODEX_CONNECTION_REF_ANNOTATION)
+ if (provider === OPENAI_SUBSCRIPTION_PROVIDER) {
+ if (canonical && alias && canonical !== alias) {
+ return {
+ key: '',
+ conflict: `Stored ChatGPT grant annotations disagree (${CODEX_CONNECTION_REF_ANNOTATION} and ${SUBSCRIPTION_CONNECTION_REF_ANNOTATION} name different grants). Choose a ChatGPT grant to replace them.`,
+ }
+ }
+ return { key: normalizedGrantKey(canonical || alias), conflict: '' }
+ }
+ if (provider === GROK_SUBSCRIPTION_PROVIDER) {
+ if (alias) {
+ return {
+ key: '',
+ conflict: `Stored grant annotations disagree for Grok: ${CODEX_CONNECTION_REF_ANNOTATION} must be empty on a Grok recipe. Choose a Grok grant to replace them.`,
+ }
+ }
+ return { key: normalizedGrantKey(canonical), conflict: '' }
+ }
+ return { key: '', conflict: '' }
+}
+
+// Control API recipe grant transition rules (POST /validate, POST, PUT). The
+// editor always sends explicit provider-shaped annotations, so most of these
+// only surface on stale or concurrent state; each maps to an actionable message.
+const RECIPE_GRANT_RULE_MESSAGES: Record<string, string> = {
+ subscriptionAnnotationsDisagree: `Subscription grant annotations disagree (${CODEX_CONNECTION_REF_ANNOTATION} and ${SUBSCRIPTION_CONNECTION_REF_ANNOTATION}). Choose the grant again to replace them.`,
+ codexRecipeGrantRequired: 'Codex subscription recipes must choose an existing ChatGPT grant.',
+ grokRecipeGrantRequired: 'Grok subscription recipes must choose an existing Grok grant.',
+ codexRecipeGrantInvalid:
+ 'The selected key is not a valid ChatGPT grant. Choose an existing ChatGPT grant.',
+ grokRecipeGrantInvalid:
+ 'The selected key is not a valid Grok grant. Choose an existing Grok grant.',
+ providerChangeRequiresGrant:
+ 'This change switches the recipe to a different subscription provider. Choose a grant for the new provider before saving.',
+}
+
+function withRecipeGrantRuleMessages(errors: ServerValidationError[]): ServerValidationError[] {
+ return errors.map(err =>
+ err.rule && RECIPE_GRANT_RULE_MESSAGES[err.rule]
+ ? { ...err, message: RECIPE_GRANT_RULE_MESSAGES[err.rule] }
+ : err
+ )
+}
+
+/** Grant-rule 422 from POST/PUT (`{ errors: [...] }` on the thrown API error body). */
+function recipeGrantRuleErrorsFromApiError(error: unknown): ServerValidationError[] | null {
+ if (!error || typeof error !== 'object') return null
+ const body = (error as { body?: unknown }).body
+ if (!body || typeof body !== 'object') return null
+ const errors = (body as { errors?: unknown }).errors
+ if (!Array.isArray(errors)) return null
+ const grantErrors = errors.filter(
+ (entry): entry is ServerValidationError =>
+ Boolean(entry) &&
+ typeof entry === 'object' &&
+ typeof (entry as { rule?: unknown }).rule === 'string' &&
+ Object.prototype.hasOwnProperty.call(
+ RECIPE_GRANT_RULE_MESSAGES,
+ (entry as { rule: string }).rule
+ ) &&
+ typeof (entry as { message?: unknown }).message === 'string'
+ )
+ return grantErrors.length > 0 ? withRecipeGrantRuleMessages(grantErrors) : null
+}
+
+function storedRecipeGrantSelection(
+ resource?: {
+ metadata?: { annotations?: Record<string, string> }
+ spec?: unknown
+ } | null
+): RecipeGrantSelection {
+ const provider = asRecipeGrantProvider(readRecipeOauthBrokerProvider(resource?.spec))
+ return { provider, ...readRecipeGrantAnnotations(provider, resource?.metadata?.annotations) }
+}
+
+/**
+ * The selection that applies to `provider`: the current selection when it was
+ * made for that provider, else the stored annotations when they belong to that
+ * provider, else nothing. A provider change therefore always resets the grant.
+ */
+function grantSelectionForProvider(
+ selection: RecipeGrantSelection,
+ provider: string,
+ stored: RecipeGrantSelection
+): RecipeGrantSelection {
+ const target = asRecipeGrantProvider(provider)
+ if (!target) return { provider: '', key: '', conflict: '' }
+ if (selection.provider === target) return selection
+ if (stored.provider === target) return stored
+ return { provider: target, key: '', conflict: '' }
+}
+
function recipeGrantAnnotations(provider: string, connectionRef: string): Record<string, string> {
const parsed = parseCredentialSelect(
credentialSelectValue(
@@ -1673,8 +1800,12 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
}, [])
useEffect(() => {
- setCodexConnectionRef(readRecipeCodexGrantAnnotation(currentInitial))
+ setGrantSelection(storedRecipeGrantSelection(currentInitial))
}, [currentInitial])
+ const storedGrantSelection = useMemo(
+ () => storedRecipeGrantSelection(currentInitial),
+ [currentInitial]
+ )
const secretNamespaces = useMemo(
() =>
resolveRecipeSecretNamespaces({
@@ -1694,8 +1825,8 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
const [codexGrantLoadError, setCodexGrantLoadError] = useState('')
const [grokConnections, setGrokConnections] = useState<GrokSubscriptionConnectionView[]>([])
const [grokGrantLoadError, setGrokGrantLoadError] = useState('')
- const [codexConnectionRef, setCodexConnectionRef] = useState(() =>
- readRecipeCodexGrantAnnotation(initial)
+ const [grantSelection, setGrantSelection] = useState<RecipeGrantSelection>(() =>
+ storedRecipeGrantSelection(initial)
)
const [step, setStep] = useState<Step>('input')
@@ -1740,23 +1871,28 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
}
}, [jsonInput])
- const isCodexRecipe = useMemo(() => {
- try {
- const parsed = JSON.parse(jsonInput) as { spec?: unknown }
- return readRecipeOauthBrokerProvider(parsed.spec) === OPENAI_SUBSCRIPTION_PROVIDER
- } catch {
- return false
- }
- }, [jsonInput])
-
- const isGrokRecipe = useMemo(() => {
+ const manifestBrokerProvider = useMemo(() => {
try {
const parsed = JSON.parse(jsonInput) as { spec?: unknown }
- return readRecipeOauthBrokerProvider(parsed.spec) === GROK_SUBSCRIPTION_PROVIDER
+ return readRecipeOauthBrokerProvider(parsed.spec)
} catch {
- return false
+ return ''
}
}, [jsonInput])
+ const isCodexRecipe = manifestBrokerProvider === OPENAI_SUBSCRIPTION_PROVIDER
+ const isGrokRecipe = manifestBrokerProvider === GROK_SUBSCRIPTION_PROVIDER
+ const codexGrant = grantSelectionForProvider(
+ grantSelection,
+ OPENAI_SUBSCRIPTION_PROVIDER,
+ storedGrantSelection
+ )
+ const grokGrant = grantSelectionForProvider(
+ grantSelection,
+ GROK_SUBSCRIPTION_PROVIDER,
+ storedGrantSelection
+ )
+ const codexGrantKey = codexGrant.key
+ const grokGrantKey = grokGrant.key
const codexGrantOptions = useMemo<LlmSecretSelectOption[]>(() => {
const options: LlmSecretSelectOption[] = codexConnections
@@ -1769,22 +1905,21 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
providers: [{ id: 'codex-subscription', label: 'ChatGPT Subscription' }],
}))
if (
- codexConnectionRef &&
- codexConnectionRef !== CODEX_UNASSIGNED_CONNECTION_KEY &&
+ codexGrantKey &&
!codexConnections.some(
- row => row.connectionKey === codexConnectionRef && isAssignableCodexGrant(row)
+ row => row.connectionKey === codexGrantKey && isAssignableCodexGrant(row)
)
) {
options.unshift({
group: 'ChatGPT subscriptions',
- value: credentialSelectValue('', codexConnectionRef),
- label: `${codexConnectionRef} (unavailable)`,
+ value: credentialSelectValue('', codexGrantKey),
+ label: `${codexGrantKey} (unavailable)`,
meta: 'ChatGPT subscription',
providers: [{ id: 'codex-subscription', label: 'ChatGPT Subscription' }],
})
}
return options
- }, [codexConnections, codexConnectionRef])
+ }, [codexConnections, codexGrantKey])
const grokGrantOptions = useMemo<LlmSecretSelectOption[]>(() => {
const options: LlmSecretSelectOption[] = grokConnections
@@ -1797,22 +1932,19 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
providers: [{ id: GROK_SUBSCRIPTION_PROVIDER, label: 'xAI Grok Subscription' }],
}))
if (
- codexConnectionRef &&
- codexConnectionRef !== CODEX_UNASSIGNED_CONNECTION_KEY &&
- !grokConnections.some(
- row => row.connectionKey === codexConnectionRef && isAssignableGrokGrant(row)
- )
+ grokGrantKey &&
+ !grokConnections.some(row => row.connectionKey === grokGrantKey && isAssignableGrokGrant(row))
) {
options.unshift({
group: 'Grok subscriptions',
- value: credentialSelectValue('', codexConnectionRef, GROK_SUBSCRIPTION_PROVIDER),
- label: `${codexConnectionRef} (unavailable)`,
+ value: credentialSelectValue('', grokGrantKey, GROK_SUBSCRIPTION_PROVIDER),
+ label: `${grokGrantKey} (unavailable)`,
meta: 'Grok subscription',
providers: [{ id: GROK_SUBSCRIPTION_PROVIDER, label: 'xAI Grok Subscription' }],
})
}
return options
- }, [grokConnections, codexConnectionRef])
+ }, [grokConnections, grokGrantKey])
const deploying = deployPhase !== 'idle'
@@ -1886,10 +2018,16 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
name: string
namespace?: string
}
- const grantAnnotations = recipeGrantAnnotations(
- readRecipeOauthBrokerProvider(specToUse),
- codexConnectionRef
+ // The grant applies only to the provider the manifest being saved
+ // declares; a selection made for another provider is never carried over.
+ const saveBrokerProvider = readRecipeOauthBrokerProvider(specToUse)
+ const saveGrant = grantSelectionForProvider(
+ grantSelection,
+ saveBrokerProvider,
+ storedGrantSelection
)
+ // Always explicit, in the provider's shape (static recipes send both empty).
+ const grantAnnotations = recipeGrantAnnotations(saveBrokerProvider, saveGrant.key)
try {
// Resolve namespaces before grants fallback below. Secret values are not
@@ -1907,7 +2045,20 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
// L2 decides if the CRD is structurally and policy-valid. Missing
// declarative Secret refs come back as pending credentials and do not
// block creation; real validation errors still fail closed here.
- const brokerError = brokerBackedRecipeAuthoringError(specToUse, codexConnectionRef)
+ if (saveGrant.conflict) {
+ setServerValidation({
+ valid: false,
+ errors: [
+ {
+ field: 'metadata.annotations',
+ rule: 'subscriptionAnnotationsDisagree',
+ message: saveGrant.conflict,
+ },
+ ],
+ })
+ return
+ }
+ const brokerError = brokerBackedRecipeAuthoringError(specToUse, saveGrant.key)
if (brokerError) {
setServerValidation({
valid: false,
@@ -1925,7 +2076,10 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
{ mode: isEdit ? 'edit' : 'create' }
)
if (!l2.valid) {
- setServerValidation(l2)
+ setServerValidation({
+ valid: false,
+ errors: withRecipeGrantRuleMessages('errors' in l2 ? (l2.errors ?? []) : []),
+ })
setDeployPhase('idle')
return
}
@@ -1992,6 +2146,12 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
setDeployPhase('idle')
onSaved()
} catch (e) {
+ const grantErrors = recipeGrantRuleErrorsFromApiError(e)
+ if (grantErrors) {
+ setServerValidation({ valid: false, errors: grantErrors })
+ setDeployPhase('idle')
+ return
+ }
setDeployError(e instanceof Error ? e.message : 'Deploy failed')
setDeployPhase('idle')
}
@@ -2651,14 +2811,27 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
<LlmSecretSelect
id="codex-recipe-grant"
ariaLabel="ChatGPT grant"
- value={credentialSelectValue('', codexConnectionRef)}
+ value={credentialSelectValue('', codexGrantKey)}
onChange={value => {
const parsed = parseCredentialSelect(value)
- setCodexConnectionRef(parsed.kind === 'subscription' ? parsed.connectionKey : '')
+ setGrantSelection({
+ provider: OPENAI_SUBSCRIPTION_PROVIDER,
+ key:
+ parsed.kind === 'subscription' &&
+ parsed.provider === OPENAI_SUBSCRIPTION_PROVIDER
+ ? normalizedGrantKey(parsed.connectionKey)
+ : '',
+ conflict: '',
+ })
}}
options={codexGrantOptions}
placeholder="Choose a ChatGPT grant"
/>
+ {codexGrant.conflict ? (
+ <div className="cu-banner cu-banner--error" role="alert" style={{ marginTop: 10 }}>
+ {codexGrant.conflict}
+ </div>
+ ) : null}
{codexGrantLoadError ? (
<div className="cu-banner cu-banner--error" role="alert" style={{ marginTop: 10 }}>
{codexGrantLoadError}
@@ -2677,14 +2850,26 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
<LlmSecretSelect
id="grok-recipe-grant"
ariaLabel="Grok grant"
- value={credentialSelectValue('', codexConnectionRef, GROK_SUBSCRIPTION_PROVIDER)}
+ value={credentialSelectValue('', grokGrantKey, GROK_SUBSCRIPTION_PROVIDER)}
onChange={value => {
const parsed = parseCredentialSelect(value)
- setCodexConnectionRef(parsed.kind === 'subscription' ? parsed.connectionKey : '')
+ setGrantSelection({
+ provider: GROK_SUBSCRIPTION_PROVIDER,
+ key:
+ parsed.kind === 'subscription' && parsed.provider === GROK_SUBSCRIPTION_PROVIDER
+ ? normalizedGrantKey(parsed.connectionKey)
+ : '',
+ conflict: '',
+ })
}}
options={grokGrantOptions}
placeholder="Choose a Grok grant"
/>
+ {grokGrant.conflict ? (
+ <div className="cu-banner cu-banner--error" role="alert" style={{ marginTop: 10 }}>
+ {grokGrant.conflict}
+ </div>
+ ) : null}
{grokGrantLoadError ? (
<div className="cu-banner cu-banner--error" role="alert" style={{ marginTop: 10 }}>
{grokGrantLoadError}
diff --git a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx
index 0e82e32e7..1669c90ff 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 {
CODEX_DEVICE_VERIFICATION_URI,
@@ -12,11 +12,23 @@ import {
revokeCodexSubscription,
startCodexDeviceConnect,
} from '@lib/codexSubscription'
+import {
+ listGrokConnectionModels,
+ listGrokSubscriptionConnections,
+ pollGrokDevice,
+ revokeGrokSubscription,
+ startGrokDeviceConnect,
+} from '@lib/grokSubscription'
import { CodexSubscriptionHub } from '../CodexSubscriptionHub'
import { ToastProvider } from '../Toast'
const confirmMock = vi.fn()
+const capabilityProbes = vi.hoisted(() => ({
+ codex: vi.fn(),
+ grok: vi.fn(),
+}))
+
vi.mock('@components/ConfirmDialog', () => ({
useConfirmDialog: () => ({
confirm: confirmMock,
@@ -27,13 +39,13 @@ vi.mock('@components/ConfirmDialog', () => ({
vi.mock('@lib/codexSubscriptionFeature', () => ({
isCodexSubscriptionUiEnabled: (capability?: { enabled?: boolean } | null) =>
capability?.enabled === true,
- loadCodexSubscriptionCapability: async () => ({ enabled: true }),
+ loadCodexSubscriptionCapability: () => capabilityProbes.codex(),
}))
vi.mock('@lib/grokSubscriptionFeature', () => ({
isGrokSubscriptionUiEnabled: (capability?: { enabled?: boolean } | null) =>
capability?.enabled === true,
- loadGrokSubscriptionCapability: async () => ({ enabled: false }),
+ loadGrokSubscriptionCapability: () => capabilityProbes.grok(),
}))
vi.mock('@lib/codexSubscription', async importOriginal => {
@@ -56,7 +68,14 @@ vi.mock('@lib/grokSubscription', async importOriginal => {
const actual = await importOriginal<typeof import('@lib/grokSubscription')>()
return {
...actual,
- listGrokSubscriptionConnections: vi.fn().mockResolvedValue([]),
+ listGrokSubscriptionConnections: vi.fn(),
+ listGrokConnectionModels: vi.fn(),
+ createGrokSubscriptionConnection: vi.fn(),
+ patchGrokSubscriptionConnection: vi.fn(),
+ patchGrokCatalogModel: vi.fn(),
+ startGrokDeviceConnect: vi.fn(),
+ pollGrokDevice: vi.fn(),
+ revokeGrokSubscription: vi.fn(),
}
})
@@ -83,6 +102,9 @@ function connection(
describe('CodexSubscriptionHub', () => {
beforeEach(() => {
confirmMock.mockReset()
+ capabilityProbes.codex.mockResolvedValue({ enabled: true })
+ capabilityProbes.grok.mockResolvedValue({ enabled: false })
+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([])
vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([
connection({ connectionKey: 'codex-aaa', displayName: 'Team A' }),
])
@@ -384,3 +406,315 @@ describe('CodexSubscriptionHub', () => {
})
})
})
+
+describe('CodexSubscriptionHub with Grok enabled', () => {
+ function renderHub() {
+ return render(
+ <ToastProvider>
+ <CodexSubscriptionHub />
+ </ToastProvider>
+ )
+ }
+
+ function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason: unknown) => void
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res
+ reject = rej
+ })
+ return { promise, resolve, reject }
+ }
+
+ function attributeText(root: HTMLElement): string {
+ return Array.from(root.querySelectorAll('*'))
+ .flatMap(node => [node.getAttribute('aria-label'), node.getAttribute('title')])
+ .filter(Boolean)
+ .join(' ')
+ }
+
+ beforeEach(() => {
+ confirmMock.mockReset()
+ capabilityProbes.codex.mockResolvedValue({ enabled: true })
+ capabilityProbes.grok.mockResolvedValue({ enabled: true })
+ vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([
+ connection({ connectionKey: 'codex-aaa', displayName: 'Team A' }),
+ ])
+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([
+ connection({ connectionKey: 'grok-aaa', displayName: 'Team Grok', defaultModel: 'grok-4.6' }),
+ ])
+ vi.mocked(listCodexConnectionModels).mockResolvedValue([
+ { model: 'gpt-5.1', enabled: true, stale: false },
+ ])
+ vi.mocked(listGrokConnectionModels).mockResolvedValue([
+ { model: 'grok-4.6', enabled: true, stale: false },
+ { model: 'grok-code-old', enabled: false, stale: true },
+ ])
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it('keeps Grok rows and reports the Codex error when the Codex list fails', async () => {
+ vi.mocked(listCodexSubscriptionConnections).mockRejectedValue(new Error('codex list boom'))
+ renderHub()
+ expect(await screen.findByText('Team Grok')).toBeInTheDocument()
+ expect(await screen.findByText(/codex list boom/)).toBeInTheDocument()
+ expect(screen.queryByText('Team A')).not.toBeInTheDocument()
+ })
+
+ it('keeps Codex rows and reports the Grok error when the Grok list fails', async () => {
+ vi.mocked(listGrokSubscriptionConnections).mockRejectedValue(new Error('grok list boom'))
+ renderHub()
+ expect(await screen.findByText('Team A')).toBeInTheDocument()
+ expect(await screen.findByText(/grok list boom/)).toBeInTheDocument()
+ expect(screen.queryByText('Team Grok')).not.toBeInTheDocument()
+ })
+
+ it('recovers the failed provider on reload without losing the healthy one', async () => {
+ vi.mocked(listGrokSubscriptionConnections)
+ .mockRejectedValueOnce(new Error('grok list boom'))
+ .mockResolvedValue([connection({ connectionKey: 'grok-aaa', displayName: 'Team Grok' })])
+ renderHub()
+ expect(await screen.findByText(/grok list boom/)).toBeInTheDocument()
+ expect(screen.getByText('Team A')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: /^Reload/ }))
+ expect(await screen.findByText('Team Grok')).toBeInTheDocument()
+ await waitFor(() => {
+ expect(screen.queryByText(/grok list boom/)).not.toBeInTheDocument()
+ })
+ expect(screen.getByText('Team A')).toBeInTheDocument()
+ })
+
+ it('surfaces a non-disabled Codex capability probe error while Grok is enabled', async () => {
+ capabilityProbes.codex.mockRejectedValue(new Error('codex probe boom'))
+ renderHub()
+ expect(await screen.findByText('Team Grok')).toBeInTheDocument()
+ expect(await screen.findByText(/codex probe boom/)).toBeInTheDocument()
+ })
+
+ it('surfaces a non-disabled Grok capability probe error while Codex is enabled', async () => {
+ capabilityProbes.grok.mockRejectedValue(new Error('grok probe boom'))
+ renderHub()
+ expect(await screen.findByText('Team A')).toBeInTheDocument()
+ expect(await screen.findByText(/grok probe boom/)).toBeInTheDocument()
+ })
+
+ it('surfaces a non-disabled Grok capability probe error when Codex is disabled', async () => {
+ capabilityProbes.codex.mockResolvedValue({ enabled: false })
+ capabilityProbes.grok.mockRejectedValue(new Error('grok probe boom'))
+ renderHub()
+ expect(await screen.findByText(/grok probe boom/)).toBeInTheDocument()
+ })
+
+ it('keeps same-key Codex and Grok rows independent for keys, busy state and edit-close', async () => {
+ const consoleError = vi.spyOn(console, 'error')
+ vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([
+ connection({ connectionKey: 'shared', displayName: 'Shared Codex' }),
+ ])
+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([
+ connection({ connectionKey: 'shared', displayName: 'Shared Grok' }),
+ ])
+ const revoke = deferred<CodexSubscriptionConnectionView>()
+ vi.mocked(revokeCodexSubscription).mockReturnValue(revoke.promise)
+ confirmMock.mockResolvedValue(true)
+ renderHub()
+ expect(await screen.findByText('Shared Codex')).toBeInTheDocument()
+ expect(screen.getByText('Shared Grok')).toBeInTheDocument()
+ expect(consoleError.mock.calls.some(call => String(call[0]).includes('same key'))).toBe(false)
+
+ // Open the Grok row, then delete the same-key Codex row.
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Actions for Grok subscription Shared Grok' })
+ )
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Update' }))
+ expect(
+ await screen.findByRole('dialog', { name: 'Update Grok subscription Shared Grok' })
+ ).toBeInTheDocument()
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Actions for ChatGPT subscription Shared Codex' })
+ )
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' }))
+ await waitFor(() => expect(revokeCodexSubscription).toHaveBeenCalledWith('shared'))
+
+ // Codex row is busy; the same-key Grok row is not.
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Actions for Grok subscription Shared Grok' })
+ )
+ const grokDelete = screen.getByRole('menuitem', { name: 'Delete' })
+ expect(grokDelete).not.toHaveAttribute('aria-disabled', 'true')
+ expect(grokDelete).not.toBeDisabled()
+ fireEvent.keyDown(document, { key: 'Escape' })
+
+ revoke.resolve(connection({ connectionKey: 'shared', status: 'revoked' }))
+ await waitFor(() => expect(listCodexSubscriptionConnections).toHaveBeenCalledTimes(2))
+ // Revoking the Codex row must not close the open Grok dialog.
+ expect(
+ screen.getByRole('dialog', { name: 'Update Grok subscription Shared Grok' })
+ ).toBeInTheDocument()
+ expect(revokeGrokSubscription).not.toHaveBeenCalled()
+ })
+
+ it('uses Grok copy (no ChatGPT wording) across the Grok dialog, device card and models', async () => {
+ const tab = { opener: {} as unknown, location: { replace: vi.fn() }, close: vi.fn() }
+ vi.stubGlobal(
+ 'open',
+ vi.fn(() => tab)
+ )
+ vi.mocked(startGrokDeviceConnect).mockResolvedValue({
+ userCode: 'GROK-1234',
+ verificationUri: 'https://auth.x.ai/device?user_code=GROK-1234',
+ intervalSeconds: 60,
+ state: 'grok-state',
+ intent: 'reconnect',
+ })
+ renderHub()
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Actions for Grok subscription Team Grok' })
+ )
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Update' }))
+ const dialog = await screen.findByRole('dialog', {
+ name: 'Update Grok subscription Team Grok',
+ })
+ expect(await within(dialog).findByLabelText('grok-4.6')).toBeInTheDocument()
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Sign in with Grok' }))
+ expect(await within(dialog).findByTestId('codex-device-code')).toHaveTextContent('GROK-1234')
+ expect(dialog.textContent ?? '').not.toMatch(/ChatGPT/)
+ expect(attributeText(dialog)).not.toMatch(/ChatGPT/)
+ expect(within(dialog).getByText(/No longer in the Grok catalog/)).toBeInTheDocument()
+ expect(dialog.querySelectorAll('[data-provider="codex-subscription"]').length).toBe(0)
+ })
+
+ it('titles the Grok create dialog for Grok when Grok is the selected provider', async () => {
+ renderHub()
+ await screen.findByText('Team Grok')
+ fireEvent.click(screen.getByRole('button', { name: 'Add subscription' }))
+ const dialog = await screen.findByRole('dialog', { name: 'New ChatGPT subscription' })
+ fireEvent.change(within(dialog).getByLabelText('Provider'), {
+ target: { value: 'grok-subscription' },
+ })
+ expect(await screen.findByRole('dialog', { name: 'New Grok subscription' })).toBeInTheDocument()
+ expect(dialog.textContent ?? '').not.toMatch(/ChatGPT sign-in|Sign in with ChatGPT/)
+ })
+
+ it('opens a tab before the awaited start and navigates it to the returned Grok verification URI', async () => {
+ const tab = { opener: {} as unknown, location: { replace: vi.fn() }, close: vi.fn() }
+ const openMock = vi.fn(() => tab)
+ vi.stubGlobal('open', openMock)
+ const started = deferred<{
+ userCode: string
+ verificationUri: string
+ intervalSeconds: number
+ state: string
+ intent: 'reconnect'
+ }>()
+ vi.mocked(startGrokDeviceConnect).mockReturnValue(started.promise)
+ renderHub()
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Actions for Grok subscription Team Grok' })
+ )
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Update' }))
+ fireEvent.click(await screen.findByRole('button', { name: 'Sign in with Grok' }))
+ // Opened synchronously inside the click (user activation), before the start resolves.
+ expect(openMock).toHaveBeenCalledTimes(1)
+ expect(openMock.mock.calls[0]?.[0]).not.toBe('https://auth.x.ai')
+ expect(tab.opener).toBeNull()
+ started.resolve({
+ userCode: 'GROK-1234',
+ verificationUri: 'https://auth.x.ai/device?user_code=GROK-1234',
+ intervalSeconds: 60,
+ state: 'grok-state',
+ intent: 'reconnect',
+ })
+ await waitFor(() => {
+ expect(tab.location.replace).toHaveBeenCalledWith(
+ 'https://auth.x.ai/device?user_code=GROK-1234'
+ )
+ })
+ expect(await screen.findByTestId('codex-device-verification-link')).toHaveAttribute(
+ 'href',
+ 'https://auth.x.ai/device?user_code=GROK-1234'
+ )
+ expect(tab.close).not.toHaveBeenCalled()
+ })
+
+ it('closes the pre-opened Grok tab when the device start fails', async () => {
+ const tab = { opener: {} as unknown, location: { replace: vi.fn() }, close: vi.fn() }
+ vi.stubGlobal(
+ 'open',
+ vi.fn(() => tab)
+ )
+ vi.mocked(startGrokDeviceConnect).mockRejectedValue(new Error('start boom'))
+ renderHub()
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Actions for Grok subscription Team Grok' })
+ )
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Update' }))
+ fireEvent.click(await screen.findByRole('button', { name: 'Sign in with Grok' }))
+ expect(await screen.findByText('start boom')).toBeInTheDocument()
+ expect(tab.close).toHaveBeenCalled()
+ expect(tab.location.replace).not.toHaveBeenCalled()
+ expect(pollGrokDevice).not.toHaveBeenCalled()
+ })
+
+ it('shows the returned Grok verification link when the tab is blocked', async () => {
+ vi.stubGlobal(
+ 'open',
+ vi.fn(() => null)
+ )
+ vi.mocked(startGrokDeviceConnect).mockResolvedValue({
+ userCode: 'GROK-1234',
+ verificationUri: 'https://auth.x.ai/device?user_code=GROK-1234',
+ intervalSeconds: 60,
+ state: 'grok-state',
+ intent: 'reconnect',
+ })
+ renderHub()
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Actions for Grok subscription Team Grok' })
+ )
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Update' }))
+ fireEvent.click(await screen.findByRole('button', { name: 'Sign in with Grok' }))
+ const card = await screen.findByTestId('codex-device-code')
+ expect(card).toHaveTextContent('Open the Grok verification page')
+ expect(screen.getByTestId('codex-device-verification-link')).toHaveAttribute(
+ 'href',
+ 'https://auth.x.ai/device?user_code=GROK-1234'
+ )
+ })
+
+ it('falls back to the Grok verification origin, never the ChatGPT URI, when no URI is returned', async () => {
+ const tab = { opener: {} as unknown, location: { replace: vi.fn() }, close: vi.fn() }
+ vi.stubGlobal(
+ 'open',
+ vi.fn(() => tab)
+ )
+ vi.mocked(startGrokDeviceConnect).mockResolvedValue({
+ userCode: 'GROK-1234',
+ verificationUri: null as unknown as string,
+ intervalSeconds: 60,
+ state: 'grok-state',
+ intent: 'reconnect',
+ })
+ renderHub()
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Actions for Grok subscription Team Grok' })
+ )
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Update' }))
+ fireEvent.click(await screen.findByRole('button', { name: 'Sign in with Grok' }))
+ const link = await screen.findByTestId('codex-device-verification-link')
+ expect(link).toHaveAttribute('href', 'https://auth.x.ai')
+ expect(link).not.toHaveAttribute('href', CODEX_DEVICE_VERIFICATION_URI)
+ // An unusable URI is never navigated to; the pre-opened tab is closed.
+ expect(tab.location.replace).not.toHaveBeenCalled()
+ expect(tab.close).toHaveBeenCalled()
+ expect(screen.getByTestId('codex-device-code')).toHaveTextContent(
+ 'Open the Grok verification page'
+ )
+ })
+})
diff --git a/control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsx b/control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsx
index a65278749..ae70472a8 100644
--- a/control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsx
+++ b/control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsx
@@ -218,7 +218,34 @@ describe('Plugin Workload SDK operator page', () => {
await waitFor(() => expect(newGrant).toBeEnabled())
fireEvent.click(newGrant)
const dialog = await screen.findByRole('dialog', { name: 'New SDK grant' })
- expect(within(dialog).queryByRole('option', { name: /xAI Grok Subscription/i })).toBeNull()
+ const provider = await waitFor(() =>
+ within(dialog).getByRole('combobox', { name: /target provider/i })
+ )
+ // Liveness: the probe ran and resolved disabled, and the picker rendered
+ // its other providers, so the absence below is not a pre-probe snapshot.
+ await waitFor(() => expect(grokCapability.load).toHaveBeenCalled())
+ await act(async () => {
+ await grokCapability.load.mock.results.at(-1)?.value
+ })
+ expect(
+ within(provider).getByRole('option', { name: /OpenAI Codex Subscription/i })
+ ).toBeInTheDocument()
+ expect(within(provider).queryByRole('option', { name: /xAI Grok Subscription/i })).toBeNull()
+ expect(within(dialog).queryByText(/Could not load Grok subscriptions/)).toBeNull()
+ })
+
+ it('surfaces a non-disabled Grok capability probe error and keeps Grok hidden', async () => {
+ grokCapability.load.mockRejectedValue(
+ Object.assign(new Error('Grok capability probe failed'), { status: 500 })
+ )
+ render(<PluginWorkloadSdkPage />)
+ const newGrant = await screen.findByRole('button', { name: 'New grant' })
+ await waitFor(() => expect(newGrant).toBeEnabled())
+ fireEvent.click(newGrant)
+ const dialog = await screen.findByRole('dialog', { name: 'New SDK grant' })
+ expect(await within(dialog).findByText('Grok capability probe failed')).toBeInTheDocument()
+ const provider = within(dialog).getByRole('combobox', { name: /target provider/i })
+ expect(within(provider).queryByRole('option', { name: /xAI Grok Subscription/i })).toBeNull()
})
it('offers Grok grants in the SDK picker when the Grok flag is on', async () => {
diff --git a/control-ui/components/__tests__/RecipeEditor.test.tsx b/control-ui/components/__tests__/RecipeEditor.test.tsx
index 8c90d0151..e1b335cb1 100644
--- a/control-ui/components/__tests__/RecipeEditor.test.tsx
+++ b/control-ui/components/__tests__/RecipeEditor.test.tsx
@@ -1,7 +1,14 @@
import React from 'react'
import type { ReactNode } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
+import {
+ cleanup,
+ fireEvent,
+ render as rtlRender,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react'
import * as api from '../../lib/api'
import type { WorkflowRecipeResource } from '../../lib/api'
import { listCodexSubscriptionConnections } from '../../lib/codexSubscription'
@@ -1880,3 +1887,400 @@ describe('RecipeEditor — grants in editor', () => {
expect(api.createRecipe).not.toHaveBeenCalled()
})
})
+
+describe('RecipeEditor — provider-bound subscription grant', () => {
+ const grokRow = (connectionKey: string, displayName: string) => ({
+ connectionKey,
+ displayName,
+ status: 'connected' as const,
+ catalogStatus: 'ready' as const,
+ credentialRevision: 1,
+ catalogRevision: 1,
+ accountFingerprint: 'fp',
+ catalogSyncedAt: '2026-08-01T00:00:00.000Z',
+ lastRefreshAt: null,
+ lastAuthAt: '2026-08-01T00:00:00.000Z',
+ refreshLockHeld: false,
+ })
+
+ function brokerSpec(provider: 'codex-subscription' | 'grok-subscription') {
+ return {
+ agent: { provider, model: provider === 'grok-subscription' ? 'grok-4.6' : 'gpt-5.1' },
+ triggers: { onDemand: { allowedActors: ['user'] } },
+ steps: [{ id: 'draft', instruction: 'Write', timeoutSeconds: 600 }],
+ }
+ }
+
+ function brokerRecipe(
+ provider: 'codex-subscription' | 'grok-subscription',
+ annotations: Record<string, string>
+ ): WorkflowRecipeResource {
+ return {
+ apiVersion: 'clerum.io/v1alpha1',
+ kind: 'WorkflowRecipe',
+ metadata: { name: 'broker-recipe', namespace: 'sandbox-recipes', annotations },
+ spec: brokerSpec(provider),
+ } as WorkflowRecipeResource
+ }
+
+ function replaceManifestProvider(provider: 'codex-subscription' | 'grok-subscription') {
+ fireEvent.change(screen.getByRole('textbox'), {
+ target: {
+ value: JSON.stringify(
+ {
+ apiVersion: 'clerum.io/v1alpha1',
+ kind: 'WorkflowRecipe',
+ metadata: { name: 'broker-recipe' },
+ spec: brokerSpec(provider),
+ },
+ null,
+ 2
+ ),
+ },
+ })
+ }
+
+ async function clickSave() {
+ fireEvent.click(await screen.findByRole('button', { name: /Deploy plugin|Save|Update plugin/ }))
+ }
+
+ it('flags a Grok recipe whose stored Codex alias is non-empty and blocks save', async () => {
+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([
+ grokRow('team-grok', 'Team Grok'),
+ ])
+ render(
+ <RecipeEditor
+ onSaved={vi.fn()}
+ onCancel={vi.fn()}
+ initial={brokerRecipe('grok-subscription', {
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'clerum.io/subscription-connection-ref': 'team-grok',
+ })}
+ />
+ )
+ reviewAndProceedToDeploy()
+ const panel = await screen.findByTestId('grok-recipe-grant')
+ expect(await within(panel).findByRole('alert')).toHaveTextContent(/annotations disagree/i)
+ await clickSave()
+ await waitFor(() => {
+ expect(screen.getAllByText(/annotations disagree/i).length).toBeGreaterThan(1)
+ })
+ expect(api.validateRecipeServer).not.toHaveBeenCalled()
+ expect(api.updateRecipe).not.toHaveBeenCalled()
+ })
+
+ it('flags a Codex recipe whose alias and canonical annotations disagree and blocks save', async () => {
+ render(
+ <RecipeEditor
+ onSaved={vi.fn()}
+ onCancel={vi.fn()}
+ initial={brokerRecipe('codex-subscription', {
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'clerum.io/subscription-connection-ref': 'team-other',
+ })}
+ />
+ )
+ reviewAndProceedToDeploy()
+ const panel = await screen.findByTestId('codex-recipe-grant')
+ expect(await within(panel).findByRole('alert')).toHaveTextContent(/annotations disagree/i)
+ await clickSave()
+ await waitFor(() => {
+ expect(screen.getAllByText(/annotations disagree/i).length).toBeGreaterThan(1)
+ })
+ expect(api.validateRecipeServer).not.toHaveBeenCalled()
+ expect(api.updateRecipe).not.toHaveBeenCalled()
+ })
+
+ it('keeps a consistent Codex recipe grant and saves the Codex shape', async () => {
+ const onSaved = vi.fn()
+ render(
+ <RecipeEditor
+ onSaved={onSaved}
+ onCancel={vi.fn()}
+ initial={brokerRecipe('codex-subscription', {
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'clerum.io/subscription-connection-ref': 'team-plus',
+ })}
+ />
+ )
+ reviewAndProceedToDeploy()
+ const panel = await screen.findByTestId('codex-recipe-grant')
+ expect(within(panel).queryByRole('alert')).not.toBeInTheDocument()
+ await clickSave()
+ await waitFor(() => expect(api.updateRecipe).toHaveBeenCalled())
+ const payload = vi.mocked(api.updateRecipe).mock.calls[0][1] as {
+ metadata?: { annotations?: Record<string, string> }
+ }
+ expect(payload.metadata?.annotations).toEqual({
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'clerum.io/subscription-connection-ref': 'team-plus',
+ })
+ expect(onSaved).toHaveBeenCalled()
+ })
+
+ it('an explicit Grok grant choice replaces conflicting annotations with the Grok shape', async () => {
+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([
+ grokRow('team-grok', 'Team Grok'),
+ ])
+ render(
+ <RecipeEditor
+ onSaved={vi.fn()}
+ onCancel={vi.fn()}
+ initial={brokerRecipe('grok-subscription', {
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'clerum.io/subscription-connection-ref': 'team-grok',
+ })}
+ />
+ )
+ reviewAndProceedToDeploy()
+ fireEvent.click(await screen.findByRole('button', { name: 'Grok grant' }))
+ fireEvent.click(await screen.findByRole('option', { name: /Team Grok/ }))
+ const panel = screen.getByTestId('grok-recipe-grant')
+ await waitFor(() => expect(within(panel).queryByRole('alert')).not.toBeInTheDocument())
+ await clickSave()
+ await waitFor(() => expect(api.updateRecipe).toHaveBeenCalled())
+ const payload = vi.mocked(api.updateRecipe).mock.calls[0][1] as {
+ metadata?: { annotations?: Record<string, string> }
+ }
+ expect(payload.metadata?.annotations).toEqual({
+ 'clerum.io/codex-connection-ref': '',
+ 'clerum.io/subscription-connection-ref': 'team-grok',
+ })
+ })
+
+ it('resets the grant when the manifest switches Codex to Grok, even for a same-named Grok key', async () => {
+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([
+ grokRow('team-plus', 'Same Key Grok'),
+ grokRow('team-grok', 'Team Grok'),
+ ])
+ render(
+ <RecipeEditor
+ onSaved={vi.fn()}
+ onCancel={vi.fn()}
+ initial={brokerRecipe('codex-subscription', {
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'clerum.io/subscription-connection-ref': 'team-plus',
+ })}
+ />
+ )
+ replaceManifestProvider('grok-subscription')
+ reviewAndProceedToDeploy()
+ await screen.findByTestId('grok-recipe-grant')
+ await clickSave()
+ await waitFor(() => {
+ expect(screen.getByText(/must choose an existing Grok grant/i)).toBeInTheDocument()
+ })
+ expect(api.validateRecipeServer).not.toHaveBeenCalled()
+ expect(api.updateRecipe).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Grok grant' }))
+ fireEvent.click(await screen.findByRole('option', { name: /Team Grok/ }))
+ await clickSave()
+ await waitFor(() => expect(api.updateRecipe).toHaveBeenCalled())
+ const payload = vi.mocked(api.updateRecipe).mock.calls[0][1] as {
+ metadata?: { annotations?: Record<string, string> }
+ }
+ expect(payload.metadata?.annotations).toEqual({
+ 'clerum.io/codex-connection-ref': '',
+ 'clerum.io/subscription-connection-ref': 'team-grok',
+ })
+ })
+
+ it('does not carry the Codex key into the Grok picker as an unavailable option', async () => {
+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([
+ grokRow('team-grok', 'Team Grok'),
+ ])
+ render(
+ <RecipeEditor
+ onSaved={vi.fn()}
+ onCancel={vi.fn()}
+ initial={brokerRecipe('codex-subscription', {
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'clerum.io/subscription-connection-ref': 'team-plus',
+ })}
+ />
+ )
+ replaceManifestProvider('grok-subscription')
+ reviewAndProceedToDeploy()
+ fireEvent.click(await screen.findByRole('button', { name: 'Grok grant' }))
+ expect(await screen.findByRole('option', { name: /Team Grok/ })).toBeInTheDocument()
+ expect(screen.queryByRole('option', { name: /team-plus/ })).not.toBeInTheDocument()
+ })
+
+ it('resets the grant when the manifest switches Grok to Codex and saves only an explicit Codex choice', async () => {
+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([
+ grokRow('team-plus', 'Grok Plus'),
+ ])
+ render(
+ <RecipeEditor
+ onSaved={vi.fn()}
+ onCancel={vi.fn()}
+ initial={brokerRecipe('grok-subscription', {
+ 'clerum.io/codex-connection-ref': '',
+ 'clerum.io/subscription-connection-ref': 'team-plus',
+ })}
+ />
+ )
+ replaceManifestProvider('codex-subscription')
+ reviewAndProceedToDeploy()
+ await screen.findByTestId('codex-recipe-grant')
+ await clickSave()
+ await waitFor(() => {
+ expect(screen.getByText(/must choose an existing ChatGPT grant/i)).toBeInTheDocument()
+ })
+ expect(api.updateRecipe).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'ChatGPT grant' }))
+ fireEvent.click(await screen.findByRole('option', { name: /Team Plus/ }))
+ await clickSave()
+ await waitFor(() => expect(api.updateRecipe).toHaveBeenCalled())
+ const payload = vi.mocked(api.updateRecipe).mock.calls[0][1] as {
+ metadata?: { annotations?: Record<string, string> }
+ }
+ expect(payload.metadata?.annotations).toEqual({
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'clerum.io/subscription-connection-ref': 'team-plus',
+ })
+ })
+
+ it('restores the stored grant when the manifest returns to the stored provider', async () => {
+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([
+ grokRow('team-grok', 'Team Grok'),
+ ])
+ render(
+ <RecipeEditor
+ onSaved={vi.fn()}
+ onCancel={vi.fn()}
+ initial={brokerRecipe('codex-subscription', {
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'clerum.io/subscription-connection-ref': 'team-plus',
+ })}
+ />
+ )
+ replaceManifestProvider('grok-subscription')
+ reviewAndProceedToDeploy()
+ await screen.findByTestId('grok-recipe-grant')
+ // An explicit Grok choice must not leak back into the Codex grant.
+ fireEvent.click(screen.getByRole('button', { name: 'Grok grant' }))
+ fireEvent.click(await screen.findByRole('option', { name: /Team Grok/ }))
+ fireEvent.click(screen.getByRole('button', { name: 'Back' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Back' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Back' }))
+ replaceManifestProvider('codex-subscription')
+ reviewAndProceedToDeploy()
+ await screen.findByTestId('codex-recipe-grant')
+ await clickSave()
+ await waitFor(() => expect(api.updateRecipe).toHaveBeenCalled())
+ const payload = vi.mocked(api.updateRecipe).mock.calls[0][1] as {
+ metadata?: { annotations?: Record<string, string> }
+ }
+ expect(payload.metadata?.annotations).toEqual({
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'clerum.io/subscription-connection-ref': 'team-plus',
+ })
+ })
+
+ it('maps a server grant rule from validate to an actionable provider message', async () => {
+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([
+ grokRow('team-grok', 'Team Grok'),
+ ])
+ vi.mocked(api.validateRecipeServer).mockResolvedValueOnce({
+ valid: false,
+ errors: [
+ {
+ field: 'metadata.annotations.clerum.io/subscription-connection-ref',
+ rule: 'grokRecipeGrantInvalid',
+ message: 'raw-server-grok-invalid',
+ },
+ ],
+ })
+ render(
+ <RecipeEditor
+ onSaved={vi.fn()}
+ onCancel={vi.fn()}
+ initial={brokerRecipe('grok-subscription', {
+ 'clerum.io/codex-connection-ref': '',
+ 'clerum.io/subscription-connection-ref': 'team-grok',
+ })}
+ />
+ )
+ reviewAndProceedToDeploy()
+ await screen.findByTestId('grok-recipe-grant')
+ await clickSave()
+ expect(await screen.findByText(/not a valid Grok grant/i)).toBeInTheDocument()
+ expect(screen.queryByText('raw-server-grok-invalid')).not.toBeInTheDocument()
+ expect(api.updateRecipe).not.toHaveBeenCalled()
+ })
+
+ it('surfaces a PUT grant 422 as a policy message instead of raw JSON', async () => {
+ const onSaved = vi.fn()
+ vi.mocked(api.updateRecipe).mockRejectedValueOnce(
+ Object.assign(new Error('422 Unprocessable Entity - {"errors":[]}'), {
+ status: 422,
+ body: {
+ errors: [
+ {
+ field: 'metadata.annotations.clerum.io/codex-connection-ref',
+ rule: 'providerChangeRequiresGrant',
+ message: 'raw-provider-change',
+ },
+ ],
+ },
+ })
+ )
+ render(
+ <RecipeEditor
+ onSaved={onSaved}
+ onCancel={vi.fn()}
+ initial={brokerRecipe('codex-subscription', {
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'clerum.io/subscription-connection-ref': 'team-plus',
+ })}
+ />
+ )
+ reviewAndProceedToDeploy()
+ await screen.findByTestId('codex-recipe-grant')
+ await clickSave()
+ expect(
+ await screen.findByText(/Choose a grant for the new provider before saving/i)
+ ).toBeInTheDocument()
+ expect(screen.queryByText(/422 Unprocessable Entity/)).not.toBeInTheDocument()
+ expect(screen.queryByText('raw-provider-change')).not.toBeInTheDocument()
+ expect(onSaved).not.toHaveBeenCalled()
+ })
+
+ it('sends empty grant annotations for a static recipe so no SDK identity is set from the editor', async () => {
+ render(
+ <RecipeEditor
+ onSaved={vi.fn()}
+ onCancel={vi.fn()}
+ initial={
+ {
+ apiVersion: 'clerum.io/v1alpha1',
+ kind: 'WorkflowRecipe',
+ metadata: {
+ name: 'my-recipe',
+ namespace: 'sandbox-recipes',
+ annotations: {
+ 'clerum.io/codex-connection-ref': 'sdk-owned',
+ 'clerum.io/subscription-connection-ref': 'sdk-owned',
+ },
+ },
+ spec: { workloads: [{ id: 'api', type: 'deployment', image: 'my-api:latest' }] },
+ } as WorkflowRecipeResource
+ }
+ />
+ )
+ reviewAndProceedToDeploy()
+ await clickSave()
+ await waitFor(() => expect(api.updateRecipe).toHaveBeenCalled())
+ const payload = vi.mocked(api.updateRecipe).mock.calls[0][1] as {
+ metadata?: { annotations?: Record<string, string> }
+ }
+ // Empty or omitted are both valid for a static recipe; a non-empty value
+ // would be the editor trying to write an SDK-owned grant identity.
+ const annotations = payload.metadata?.annotations ?? {}
+ expect(annotations['clerum.io/codex-connection-ref'] ?? '').toBe('')
+ expect(annotations['clerum.io/subscription-connection-ref'] ?? '').toBe('')
+ })
+})
diff --git a/control-ui/lib/__tests__/grokSubscriptionFeature.test.ts b/control-ui/lib/__tests__/grokSubscriptionFeature.test.ts
new file mode 100644
index 000000000..6f1a5375f
--- /dev/null
+++ b/control-ui/lib/__tests__/grokSubscriptionFeature.test.ts
@@ -0,0 +1,53 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { isAllowedGrokVerificationUri, listGrokSubscriptionConnections } from '../grokSubscription'
+import { loadGrokSubscriptionCapability } from '../grokSubscriptionFeature'
+
+vi.mock('../grokSubscription', async importOriginal => {
+ const actual = await importOriginal<typeof import('../grokSubscription')>()
+ return {
+ ...actual,
+ listGrokSubscriptionConnections: vi.fn(),
+ }
+})
+
+afterEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('loadGrokSubscriptionCapability', () => {
+ it('is enabled only after the keyed connections list succeeds', async () => {
+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([])
+ await expect(loadGrokSubscriptionCapability()).resolves.toEqual({ enabled: true })
+ })
+
+ it('maps a 404 or a disabled code to the disabled capability', async () => {
+ vi.mocked(listGrokSubscriptionConnections).mockRejectedValueOnce({ status: 404 })
+ await expect(loadGrokSubscriptionCapability()).resolves.toEqual({ enabled: false })
+ vi.mocked(listGrokSubscriptionConnections).mockRejectedValueOnce({
+ status: 403,
+ code: 'disabled',
+ })
+ await expect(loadGrokSubscriptionCapability()).resolves.toEqual({ enabled: false })
+ })
+
+ it('rethrows non-disabled probe failures instead of reporting the flag as off', async () => {
+ const failure = Object.assign(new Error('control-api unavailable'), { status: 500 })
+ vi.mocked(listGrokSubscriptionConnections).mockRejectedValueOnce(failure)
+ await expect(loadGrokSubscriptionCapability()).rejects.toBe(failure)
+ })
+})
+
+describe('isAllowedGrokVerificationUri', () => {
+ it('accepts https URIs on auth.x.ai, including the returned device path', () => {
+ expect(isAllowedGrokVerificationUri('https://auth.x.ai')).toBe(true)
+ expect(isAllowedGrokVerificationUri('https://auth.x.ai/device?user_code=ABCD')).toBe(true)
+ })
+
+ it('rejects other schemes, hosts and look-alike hosts', () => {
+ expect(isAllowedGrokVerificationUri('http://auth.x.ai/device')).toBe(false)
+ expect(isAllowedGrokVerificationUri('https://auth.x.ai.evil.example/device')).toBe(false)
+ expect(isAllowedGrokVerificationUri('https://evil.example/?next=https://auth.x.ai')).toBe(false)
+ expect(isAllowedGrokVerificationUri('javascript:alert(1)')).toBe(false)
+ expect(isAllowedGrokVerificationUri('not a url')).toBe(false)
+ })
+})
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index d2ca01301..5b9fba7e2 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.590",
+ "version": "0.1.591",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.590",
+ "version": "0.1.591",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/control-ui/package.json b/control-ui/package.json
index 2cd46ba7e..7920bbe71 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.590",
+ "version": "0.1.591",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",