Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-ui): add Grok grant pickers, hub, and Desktop selector
Jose Gabriel Ramirez Encinas80be5ef9633c
diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsxindex 8d595cd46..5ef3caaaa 100644--- a/control-ui/app/hosts/[name]/page.tsx+++ b/control-ui/app/hosts/[name]/page.tsx@@ -38,9 +38,16 @@ import {} from '../../../lib/codexSubscription'import { isDisabledCapabilityError } from '../../../lib/codexSubscriptionFeature'import { buildContextUpdatePayload, contextMutationError } from '../../../lib/contextMutation'+import {+ type GrokSubscriptionConnectionView,+ isAssignableGrokGrant,+ listGrokConnectionModels,+ listGrokSubscriptionConnections,+} from '../../../lib/grokSubscription'import { useLlmAllowedModels } from '../../../lib/hooks/useLlmAllowedModels'import { FIRST_PARTY_CHANNEL_WORKFLOW_CONTROL_SCOPES } from '../../../lib/hostWorkflowControl'import {+ GROK_SUBSCRIPTION_PROVIDER,type HostAllowedModel,LLM_EMPTY_TRIGGER_ERROR,type LlmPolicy,@@ -51,6 +58,7 @@ import {getProviderLabel,getProvidersWithCompleteCredentials,hostModelNameError,+ isOauthBrokerProvider,isProviderUsable,llmChainRequiresSecret,normalizeAllowedModels,@@ -213,26 +221,49 @@ export default function HostDetailsPage() {const [connectionRefDraft, setConnectionRefDraft] = useState(CODEX_UNASSIGNED_CONNECTION_KEY)const [codexModels, setCodexModels] = useState<string[]>([])const [codexConnections, setCodexConnections] = useState<CodexSubscriptionConnectionView[]>([])+ const [grokModels, setGrokModels] = useState<string[]>([])+ const [grokConnections, setGrokConnections] = useState<GrokSubscriptionConnectionView[]>([])+ const [grokEnabled, setGrokEnabled] = useState(false)const [grantCatalogError, setGrantCatalogError] = useState('')const catalogForEditor = useMemo(() => {- if (providerDraft !== 'codex-subscription') return allowedCatalog- const others = allowedCatalog.filter(row => row.provider !== 'codex-subscription')- if (codexModels.length === 0) return others- return [- ...others,- ...codexModels.map(model => ({- id: `codex:${model}`,- provider: 'codex-subscription' as const,- model,- vendor: 'OpenAI',- display_name: model,- context_window_tokens: null,- enabled: true,- source: 'discovery' as const,- stale: false,- })),- ]- }, [allowedCatalog, providerDraft, codexModels])+ if (providerDraft === 'codex-subscription') {+ const others = allowedCatalog.filter(row => row.provider !== 'codex-subscription')+ if (codexModels.length === 0) return others+ return [+ ...others,+ ...codexModels.map(model => ({+ id: `codex:${model}`,+ provider: 'codex-subscription' as const,+ model,+ vendor: 'OpenAI',+ display_name: model,+ context_window_tokens: null,+ enabled: true,+ source: 'discovery' as const,+ stale: false,+ })),+ ]+ }+ if (providerDraft === GROK_SUBSCRIPTION_PROVIDER) {+ const others = allowedCatalog.filter(row => row.provider !== GROK_SUBSCRIPTION_PROVIDER)+ if (grokModels.length === 0) return others+ return [+ ...others,+ ...grokModels.map(model => ({+ id: `grok:${model}`,+ provider: GROK_SUBSCRIPTION_PROVIDER,+ model,+ vendor: 'xAI',+ display_name: model,+ context_window_tokens: null,+ enabled: true,+ source: 'discovery' as const,+ stale: false,+ })),+ ]+ }+ return allowedCatalog+ }, [allowedCatalog, providerDraft, codexModels, grokModels])const [secretRefDraft, setSecretRefDraft] = useState('')const [availableLlmSecrets, setAvailableLlmSecrets] = useState<HostSecretResource[]>([])// Fallback policy (spec §3-R5). `undefined` = the Host has no llmPolicy.@@ -322,6 +353,18 @@ export default function HostDetailsPage() {if (next !== modelNameDraft) setModelNameDraft(next)return}+ if (providerDraft === GROK_SUBSCRIPTION_PROVIDER) {+ const offered = constrainModelOptions(+ catalogForEditor,+ allowedModelsDraft,+ GROK_SUBSCRIPTION_PROVIDER+ )+ if (offered.length === 0) return+ const grant = grokConnections.find(row => row.connectionKey === connectionRefDraft)+ const next = resolveCodexGrantModel(modelNameDraft, offered, grant?.defaultModel)+ if (next !== modelNameDraft) setModelNameDraft(next)+ return+ }if (modelNameDraft === '' && providerModelOptions.length > 0) {setModelNameDraft(resolveDefaultModel(providerDraft, providerModelOptions))}@@ -329,6 +372,7 @@ export default function HostDetailsPage() {allowedModelsDraft,catalogForEditor,codexConnections,+ grokConnections,connectionRefDraft,modelNameDraft,providerDraft,@@ -349,6 +393,22 @@ export default function HostDetailsPage() {}}})+ void listGrokSubscriptionConnections()+ .then(rows => {+ if (!cancelled) {+ setGrokConnections(rows)+ setGrokEnabled(true)+ }+ })+ .catch(err => {+ if (!cancelled) {+ setGrokConnections([])+ setGrokEnabled(false)+ if (!isDisabledCapabilityError(err)) {+ setError(err instanceof Error ? err.message : 'Could not load Grok subscriptions')+ }+ }+ })return () => {cancelled = true}@@ -357,11 +417,32 @@ export default function HostDetailsPage() {useEffect(() => {if (!connectionRefDraft.trim() || connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY) {setCodexModels([])+ setGrokModels([])setGrantCatalogError('')return}let cancelled = falsesetGrantCatalogError('')+ if (providerDraft === GROK_SUBSCRIPTION_PROVIDER) {+ setCodexModels([])+ void listGrokConnectionModels(connectionRefDraft)+ .then(models => {+ if (cancelled) return+ setGrokModels(offeredCodexModelNames(models))+ })+ .catch(err => {+ if (cancelled) return+ setGrokModels([])+ setModelNameDraft('')+ setGrantCatalogError(+ err instanceof Error ? err.message : 'Could not load Grok grant models'+ )+ })+ return () => {+ cancelled = true+ }+ }+ setGrokModels([])void listCodexConnectionModels(connectionRefDraft).then(models => {if (cancelled) return@@ -378,7 +459,7 @@ export default function HostDetailsPage() {return () => {cancelled = true}- }, [connectionRefDraft])+ }, [connectionRefDraft, providerDraft])useEffect(() => {setActiveTab(parseHostTab(params.tab))@@ -665,9 +746,19 @@ export default function HostDetailsPage() {providers: [{ id: 'codex-subscription', label: 'ChatGPT Subscription' }],})}+ for (const row of grokConnections.filter(isAssignableGrokGrant)) {+ options.push({+ group: 'Grok subscriptions',+ value: credentialSelectValue('', row.connectionKey, GROK_SUBSCRIPTION_PROVIDER),+ label: row.displayName || row.connectionKey,+ meta: 'Grok subscription',+ providers: [{ id: GROK_SUBSCRIPTION_PROVIDER, label: 'xAI Grok Subscription' }],+ })+ }if (connectionRefDraft &&connectionRefDraft !== CODEX_UNASSIGNED_CONNECTION_KEY &&+ providerDraft === 'codex-subscription' &&!codexConnections.some(row => row.connectionKey === connectionRefDraft && isAssignableCodexGrant(row))@@ -680,26 +771,55 @@ export default function HostDetailsPage() {providers: [{ id: 'codex-subscription', label: 'ChatGPT Subscription' }],})}+ if (+ connectionRefDraft &&+ connectionRefDraft !== CODEX_UNASSIGNED_CONNECTION_KEY &&+ providerDraft === GROK_SUBSCRIPTION_PROVIDER &&+ !grokConnections.some(+ row => row.connectionKey === connectionRefDraft && isAssignableGrokGrant(row)+ )+ ) {+ options.push({+ group: 'Grok subscriptions',+ value: credentialSelectValue('', connectionRefDraft, GROK_SUBSCRIPTION_PROVIDER),+ label: `${connectionRefDraft} (unavailable)`,+ meta: 'Grok subscription',+ providers: [{ id: GROK_SUBSCRIPTION_PROVIDER, label: 'xAI Grok Subscription' }],+ })+ }return options- }, [availableLlmSecrets, codexConnections, connectionRefDraft, currentSecretKeys, secretRefDraft])+ }, [+ availableLlmSecrets,+ codexConnections,+ grokConnections,+ connectionRefDraft,+ currentSecretKeys,+ providerDraft,+ secretRefDraft,+ ])const apiKeySecretOptions = useMemo(- () => llmSecretOptions.filter(option => option.group !== 'ChatGPT subscriptions'),+ () =>+ llmSecretOptions.filter(+ option => option.group !== 'ChatGPT subscriptions' && option.group !== 'Grok subscriptions'+ ),[llmSecretOptions])const chainRequiresSecret = llmChainRequiresSecret(providerDraft, llmPolicyDraft?.fallbacks)- const showFallbackSecretField = providerDraft === 'codex-subscription' && chainRequiresSecret+ const showFallbackSecretField = isOauthBrokerProvider(providerDraft) && chainRequiresSecretconst fallbackSecretLabels = (llmPolicyDraft?.fallbacks ?? []).filter(entry => providerRequiresLlmSecret(entry.provider)).map(entry => getProviderLabel(entry.provider))- const isCodexAssignment = providerDraft === 'codex-subscription'- const isCodexUnassigned =- isCodexAssignment &&+ const isBrokerAssignment = isOauthBrokerProvider(providerDraft)+ const isBrokerUnassigned =+ isBrokerAssignment &&(!connectionRefDraft.trim() || connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY)- const assignedCodexLabel =- codexConnections.find(row => row.connectionKey === connectionRefDraft)?.displayName ||+ const assignedBrokerLabel =+ (providerDraft === GROK_SUBSCRIPTION_PROVIDER+ ? grokConnections.find(row => row.connectionKey === connectionRefDraft)?.displayName+ : codexConnections.find(row => row.connectionKey === connectionRefDraft)?.displayName) ||connectionRefDraft- const credentialFieldLabel = isCodexAssignment ? 'Credential' : 'LLM Secret'+ const credentialFieldLabel = isBrokerAssignment ? 'Credential' : 'LLM Secret'const linkedSecretProviderMismatch =chainRequiresSecret &&@@ -796,19 +916,20 @@ export default function HostDetailsPage() {return}if (parsed.kind === 'subscription') {- if (!llmChainRequiresSecret('codex-subscription', llmPolicyDraft?.fallbacks)) {+ if (!llmChainRequiresSecret(parsed.provider, llmPolicyDraft?.fallbacks)) {setSecretRefDraft('')}setConnectionRefDraft(parsed.connectionKey)- setProviderDraft('codex-subscription')+ setProviderDraft(parsed.provider)setModelNameDraft('')return}setSecretRefDraft(parsed.name)setConnectionRefDraft(CODEX_UNASSIGNED_CONNECTION_KEY)setCodexModels([])+ setGrokModels([])setGrantCatalogError('')- if (providerDraft === 'codex-subscription') {+ if (isOauthBrokerProvider(providerDraft)) {setProviderDraft('openai')setModelNameDraft(resolveDefaultModel('openai', getModelOptions(allowedCatalog, 'openai')))}@@ -820,16 +941,21 @@ export default function HostDetailsPage() {setError(modelNameProblem)return false}- if (providerDraft === 'codex-subscription') {+ if (providerDraft === 'codex-subscription' || providerDraft === GROK_SUBSCRIPTION_PROVIDER) {if (!connectionRefDraft.trim() || connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY) {- setError('Choose a ChatGPT subscription before saving.')+ setError(+ providerDraft === GROK_SUBSCRIPTION_PROVIDER+ ? 'Choose a Grok subscription before saving.'+ : 'Choose a ChatGPT subscription before saving.'+ )return false}if (grantCatalogError) {setError(grantCatalogError)return false}- if (!codexModels.includes(modelNameDraft.trim())) {+ const offered = providerDraft === GROK_SUBSCRIPTION_PROVIDER ? grokModels : codexModels+ if (!offered.includes(modelNameDraft.trim())) {setError('This subscription has no offered models yet. Sign in and sync the catalog before assigning agents.')@@ -1132,17 +1258,29 @@ export default function HostDetailsPage() {id="model-secret"value={showFallbackSecretField- ? credentialSelectValue('', connectionRefDraft)- : credentialSelectValue(secretRefDraft, connectionRefDraft)+ ? credentialSelectValue(+ '',+ connectionRefDraft,+ providerDraft === GROK_SUBSCRIPTION_PROVIDER+ ? GROK_SUBSCRIPTION_PROVIDER+ : 'codex-subscription'+ )+ : credentialSelectValue(+ secretRefDraft,+ connectionRefDraft,+ providerDraft === GROK_SUBSCRIPTION_PROVIDER+ ? GROK_SUBSCRIPTION_PROVIDER+ : 'codex-subscription'+ )}ariaLabel={credentialFieldLabel}onChange={handleCredentialChange}options={llmSecretOptions}placeholder={- isCodexAssignment- ? isCodexUnassigned+ isBrokerAssignment+ ? isBrokerUnassigned? 'No credential assigned'- : assignedCodexLabel+ : assignedBrokerLabel: apiKeySecretOptions.length === 0? 'No LLM Secret available': 'Select an LLM Secret...'@@ -1164,8 +1302,10 @@ export default function HostDetailsPage() {</div><span className="cu-field__hint">{showFallbackSecretField- ? 'Choose the ChatGPT subscription this agent spends. Agents only choose; Secrets creates grants.'- : 'Choose an API-key secret or a ChatGPT subscription. Agents only choose; Secrets creates grants.'}+ ? providerDraft === GROK_SUBSCRIPTION_PROVIDER+ ? 'Choose the Grok subscription this agent spends. Agents only choose; Secrets creates grants.'+ : 'Choose the ChatGPT subscription this agent spends. Agents only choose; Secrets creates grants.'+ : 'Choose an API-key secret or a coding-plan subscription. Agents only choose; Secrets creates grants.'}</span></div>{showFallbackSecretField ? (@@ -1225,9 +1365,10 @@ export default function HostDetailsPage() {onPrimaryChange={next => {setProviderDraft(next.provider)setModelNameDraft(next.model)- if (next.provider !== 'codex-subscription') {+ if (!isOauthBrokerProvider(next.provider)) {setConnectionRefDraft(CODEX_UNASSIGNED_CONNECTION_KEY)setCodexModels([])+ setGrokModels([])setGrantCatalogError('')}}}@@ -1241,6 +1382,7 @@ export default function HostDetailsPage() {modelLabel="Current model"secretKeys={currentSecretKeys}disabled={busy}+ grokEnabled={grokEnabled}/><div className="cu-create-actions"><buttondiff --git a/control-ui/components/CodexSubscriptionHub/index.tsx b/control-ui/components/CodexSubscriptionHub/index.tsxindex 3e16e703a..428bd596c 100644--- a/control-ui/components/CodexSubscriptionHub/index.tsx+++ b/control-ui/components/CodexSubscriptionHub/index.tsx@@ -26,6 +26,23 @@ import {isCodexSubscriptionUiEnabled,loadCodexSubscriptionCapability,} from '@lib/codexSubscriptionFeature'+import {+ GROK_DEVICE_VERIFICATION_ORIGIN,+ type GrokSubscriptionConnectionView,+ createGrokSubscriptionConnection,+ listGrokConnectionModels,+ listGrokSubscriptionConnections,+ patchGrokCatalogModel,+ patchGrokSubscriptionConnection,+ pollGrokDevice,+ revokeGrokSubscription,+ startGrokDeviceConnect,+} from '@lib/grokSubscription'+import {+ type GrokSubscriptionCapability,+ isGrokSubscriptionUiEnabled,+ loadGrokSubscriptionCapability,+} from '@lib/grokSubscriptionFeature'import {mapConnectionStatus,statusLabel,@@ -43,10 +60,23 @@ import { useToast } from '../Toast'import { IconCopy, IconRefresh, IconX } from '../icons'import { CheckboxField } from '../ui'+type HubBroker = 'codex-subscription' | 'grok-subscription'+type HubConnection = CodexSubscriptionConnectionView & { broker: HubBroker }+function grantLabel(row: CodexSubscriptionConnectionView): string {return row.displayName || row.connectionKey}+function asHubRow(+ row: CodexSubscriptionConnectionView | GrokSubscriptionConnectionView,+ broker: HubBroker+): HubConnection {+ return { ...row, broker }+}++const GROK_TOS =+ 'Connecting a Grok subscription authenticates Evenfire to xAI with the SuperGrok / Grok Build coding-plan OAuth client. Inference stays on cli-chat-proxy.grok.com and is not the metered xAI API.'+async function copyDeviceValue(value: string,label: string,@@ -65,13 +95,15 @@ export function CodexSubscriptionHub() {const { showToast } = useToast()const { confirm, confirmDialog } = useConfirmDialog()const [capability, setCapability] = useState<CodexSubscriptionCapability | null>(null)- const [connections, setConnections] = useState<CodexSubscriptionConnectionView[]>([])+ const [grokCapability, setGrokCapability] = useState<GrokSubscriptionCapability | null>(null)+ const [connections, setConnections] = useState<HubConnection[]>([])+ const [createBroker, setCreateBroker] = useState<HubBroker>('codex-subscription')const [loading, setLoading] = useState(true)const [error, setError] = useState('')const [searchQuery, setSearchQuery] = useState('')const [busyKey, setBusyKey] = useState<string | null>(null)const [creating, setCreating] = useState(false)- const [editing, setEditing] = useState<CodexSubscriptionConnectionView | null>(null)+ const [editing, setEditing] = useState<HubConnection | null>(null)const [editName, setEditName] = useState('')const [editDefault, setEditDefault] = useState('')// True while the open modal is the continuation of the CREATE flow — the@@ -91,6 +123,7 @@ export function CodexSubscriptionHub() {// longer touch state after it was abandoned.const connectEpoch = useRef(0)const enabled = isCodexSubscriptionUiEnabled(capability)+ const grokEnabled = isGrokSubscriptionUiEnabled(grokCapability)useEffect(() => {void loadCodexSubscriptionCapability()@@ -100,17 +133,27 @@ export function CodexSubscriptionHub() {setError(err instanceof Error ? err.message : 'Failed to load ChatGPT subscriptions')setLoading(false)})+ void loadGrokSubscriptionCapability()+ .then(setGrokCapability)+ .catch(() => {+ setGrokCapability({ enabled: false })+ })}, [])const load = useCallback(async () => {- if (!enabled) return- const rows = await listCodexSubscriptionConnections()- setConnections(rows)- }, [enabled])+ const [codexRows, grokRows] = await Promise.all([+ enabled ? listCodexSubscriptionConnections() : Promise.resolve([]),+ grokEnabled ? listGrokSubscriptionConnections() : Promise.resolve([]),+ ])+ setConnections([+ ...codexRows.map(row => asHubRow(row, 'codex-subscription')),+ ...grokRows.map(row => asHubRow(row, 'grok-subscription')),+ ])+ }, [enabled, grokEnabled])useEffect(() => {- if (capability === null) return- if (!enabled) {+ if (capability === null || grokCapability === null) return+ if (!enabled && !grokEnabled) {setLoading(false)return}@@ -121,7 +164,7 @@ export function CodexSubscriptionHub() {setError(err instanceof Error ? err.message : 'Failed to load ChatGPT subscriptions')}).finally(() => setLoading(false))- }, [capability, enabled, load])+ }, [capability, grokCapability, enabled, grokEnabled, load])useEffect(() => {return () => {@@ -137,7 +180,7 @@ export function CodexSubscriptionHub() {[grantLabel(row), row.connectionKey, row.status].join(' ').toLowerCase().includes(q))}, [connections, searchQuery])- const subscriptionSort = useTableSort<CodexSubscriptionConnectionView, 'name' | 'status'>({+ const subscriptionSort = useTableSort<HubConnection, 'name' | 'status'>({rows: filtered,defaultKey: 'name',identity: row => row.connectionKey,@@ -161,9 +204,12 @@ export function CodexSubscriptionHub() {return}setBusyKey('create')- let created: CodexSubscriptionConnectionView+ let created: HubConnectiontry {- created = await createCodexSubscriptionConnection({ displayName })+ created =+ createBroker === 'grok-subscription'+ ? asHubRow(await createGrokSubscriptionConnection({ displayName }), 'grok-subscription')+ : asHubRow(await createCodexSubscriptionConnection({ displayName }), 'codex-subscription')} catch (err) {setError(err instanceof Error ? err.message : 'Could not create subscription')setBusyKey(null)@@ -184,6 +230,7 @@ export function CodexSubscriptionHub() {function beginCreate() {setCreating(true)+ setCreateBroker(enabled ? 'codex-subscription' : 'grok-subscription')setEditing(null)setEditName('')setEditDefault('')@@ -195,7 +242,7 @@ export function CodexSubscriptionHub() {setError('')}- async function openEdit(row: CodexSubscriptionConnectionView) {+ async function openEdit(row: HubConnection) {connectEpoch.current += 1setEditing(row)setEditName(grantLabel(row))@@ -207,7 +254,10 @@ export function CodexSubscriptionHub() {setError('')if (row.status === 'connected') {try {- const models = await listCodexConnectionModels(row.connectionKey)+ const models =+ row.broker === 'grok-subscription'+ ? await listGrokConnectionModels(row.connectionKey)+ : await listCodexConnectionModels(row.connectionKey)setEditModels(models)} catch (err) {setEditModels([])@@ -242,10 +292,22 @@ export function CodexSubscriptionHub() {}setBusyKey(editing.connectionKey)try {- const updated = await patchCodexSubscriptionConnection(editing.connectionKey, {- displayName: editName.trim() || grantLabel(editing),- defaultModel: editDefault.trim() || null,- })+ const updated =+ editing.broker === 'grok-subscription'+ ? asHubRow(+ await patchGrokSubscriptionConnection(editing.connectionKey, {+ displayName: editName.trim() || grantLabel(editing),+ defaultModel: editDefault.trim() || null,+ }),+ 'grok-subscription'+ )+ : asHubRow(+ await patchCodexSubscriptionConnection(editing.connectionKey, {+ displayName: editName.trim() || grantLabel(editing),+ defaultModel: editDefault.trim() || null,+ }),+ 'codex-subscription'+ )setEditing(updated)// A refresh failure after a successful patch is partial — the update// itself landed, so it must not surface as "update failed".@@ -264,25 +326,35 @@ export function CodexSubscriptionHub() {}}- async function handleConnect(row: CodexSubscriptionConnectionView) {+ async function handleConnect(row: HubConnection) {const epoch = ++connectEpoch.currentsetBusyKey(row.connectionKey)+ const grok = row.broker === 'grok-subscription'// 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 = nulltry {- openedTab = window.open(CODEX_DEVICE_VERIFICATION_URI, '_blank', 'noopener,noreferrer')+ openedTab = window.open(+ grok ? GROK_DEVICE_VERIFICATION_ORIGIN : CODEX_DEVICE_VERIFICATION_URI,+ '_blank',+ 'noopener,noreferrer'+ )} catch {openedTab = null}setDeviceTabBlocked(!openedTab)try {- const started = await startCodexDeviceConnect(- row.status === 'connected' ? 'reconnect' : 'connect',- row.connectionKey- )+ const started = grok+ ? await startGrokDeviceConnect(+ row.status === 'connected' ? 'reconnect' : 'connect',+ row.connectionKey+ )+ : await startCodexDeviceConnect(+ row.status === 'connected' ? 'reconnect' : 'connect',+ row.connectionKey+ )if (epoch !== connectEpoch.current) returnsetUserCode(started.userCode)setVerificationUri(started.verificationUri)@@ -290,14 +362,18 @@ export function CodexSubscriptionHub() {while (Date.now() < deadline) {await new Promise(resolve => setTimeout(resolve, started.intervalSeconds * 1000))if (epoch !== connectEpoch.current) return- const polled = await pollCodexDevice(started.state, row.connectionKey)+ const polled = grok+ ? await pollGrokDevice(started.state, row.connectionKey)+ : await pollCodexDevice(started.state, row.connectionKey)if (epoch !== connectEpoch.current) returnif (polled.status === 'connected') {setUserCode(null)setVerificationUri(null)- const latest = polled.connection+ const latest = asHubRow(polled.connection, row.broker)setEditing(latest)- const models = await listCodexConnectionModels(latest.connectionKey)+ const models = grok+ ? await listGrokConnectionModels(latest.connectionKey)+ : await listCodexConnectionModels(latest.connectionKey)if (epoch !== connectEpoch.current) returnsetEditModels(models)// A table refresh failure here is partial — connect itself worked,@@ -317,19 +393,19 @@ export function CodexSubscriptionHub() {if (polled.status === 'expired' || polled.status === 'denied') {setUserCode(null)setVerificationUri(null)- setError(`ChatGPT sign-in ${polled.status}. Try again.`)+ setError(`${grok ? 'Grok' : 'ChatGPT'} sign-in ${polled.status}. Try again.`)return}}if (epoch !== connectEpoch.current) returnsetUserCode(null)setVerificationUri(null)- setError('ChatGPT sign-in timed out. Try again.')+ setError(`${grok ? 'Grok' : 'ChatGPT'} sign-in timed out. Try again.`)} catch (err) {if (epoch !== connectEpoch.current) returnsetUserCode(null)setVerificationUri(null)- setError(err instanceof Error ? err.message : 'ChatGPT sign-in failed')+ setError(err instanceof Error ? err.message : `${grok ? 'Grok' : 'ChatGPT'} sign-in failed`)} finally {if (epoch === connectEpoch.current) {setBusyKey(null)@@ -337,14 +413,13 @@ export function CodexSubscriptionHub() {}}- async function handleToggleModel(- row: CodexSubscriptionConnectionView,- model: string,- enabledNext: boolean- ) {+ async function handleToggleModel(row: HubConnection, model: string, enabledNext: boolean) {setBusyKey(row.connectionKey)try {- const models = await patchCodexCatalogModel(row.connectionKey, model, enabledNext)+ const models =+ row.broker === 'grok-subscription'+ ? await patchGrokCatalogModel(row.connectionKey, model, enabledNext)+ : await patchCodexCatalogModel(row.connectionKey, model, enabledNext)setEditModels(models)if (editDefault === model && !enabledNext) setEditDefault('')} catch (err) {@@ -354,9 +429,10 @@ export function CodexSubscriptionHub() {}}- async function handleRevoke(row: CodexSubscriptionConnectionView) {+ async function handleRevoke(row: HubConnection) {+ const grok = row.broker === 'grok-subscription'const confirmed = await confirm({- title: 'Delete ChatGPT subscription',+ title: grok ? 'Delete Grok subscription' : 'Delete ChatGPT subscription',message: `Revoke ${grantLabel(row)}? Assigned agents keep the reference and stop authorizing.`,confirmLabel: 'Delete',tone: 'danger',@@ -364,7 +440,8 @@ export function CodexSubscriptionHub() {if (!confirmed) returnsetBusyKey(row.connectionKey)try {- await revokeCodexSubscription(row.connectionKey)+ if (grok) await revokeGrokSubscription(row.connectionKey)+ else await revokeCodexSubscription(row.connectionKey)if (editing?.connectionKey === row.connectionKey) closeEdit()await load()showToast(`Subscription ${grantLabel(row)} revoked.`, { tone: 'success' })@@ -379,7 +456,7 @@ export function CodexSubscriptionHub() {const initialLoad = loading && connections.length === 0const uiStatus = editing ? mapConnectionStatus(editing.status) : 'disconnected'- if (!enabled && capability !== null) {+ if (capability !== null && grokCapability !== null && !enabled && !grokEnabled) {return (<div className="cu-card cu-card--viewport-fill"><TablePanelHeader@@ -394,7 +471,10 @@ export function CodexSubscriptionHub() {<SecretsScopeTabs activeValue="llm-subscriptions" /></div><div className="cu-empty">- {capability.error || error || 'ChatGPT subscriptions are disabled.'}+ {capability.error ||+ grokCapability.error ||+ error ||+ 'Coding-plan subscriptions are disabled.'}</div></div>)@@ -580,6 +660,26 @@ export function CodexSubscriptionHub() {</div><div className="cu-form-stack cu-form-stack--wide" style={{ maxWidth: '100%' }}>{error ? <div className="cu-banner cu-banner--error">{error}</div> : null}+ {creating && grokEnabled ? (+ <div className="cu-field">+ <label htmlFor="subscription-provider">Provider</label>+ <select+ id="subscription-provider"+ value={createBroker}+ onChange={e =>+ setCreateBroker(+ e.target.value === 'grok-subscription'+ ? 'grok-subscription'+ : 'codex-subscription'+ )+ }+ disabled={Boolean(busyKey)}+ >+ {enabled ? <option value="codex-subscription">ChatGPT</option> : null}+ <option value="grok-subscription">Grok</option>+ </select>+ </div>+ ) : null}<div className="cu-field"><label htmlFor="codex-sub-name">Name</label><input@@ -602,13 +702,19 @@ 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">ChatGPT sign-in</span>+ <span className="cu-llm-config__block-title">+ {(editing?.broker ?? createBroker) === 'grok-subscription'+ ? 'Grok sign-in'+ : 'ChatGPT sign-in'}+ </span><span className={statusTagClass(uiStatus)}>{statusLabel(uiStatus)}</span></div><p className="cu-field__hint" style={{ margin: 0 }}>- {setupNew || !editing- ? 'Agents authorize through this subscription’s ChatGPT grant. Sign in to connect it — the catalog syncs automatically.'- : 'Agents authorize through this subscription’s ChatGPT grant. Reconnect if the grant expired — the catalog refreshes automatically.'}+ {(editing?.broker ?? createBroker) === 'grok-subscription'+ ? GROK_TOS+ : setupNew || !editing+ ? 'Agents authorize through this subscription’s ChatGPT grant. Sign in to connect it — the catalog syncs automatically.'+ : 'Agents authorize through this subscription’s ChatGPT grant. Reconnect if the grant expired — the catalog refreshes automatically.'}</p><div className="cu-form-inline"><span@@ -627,7 +733,9 @@ export function CodexSubscriptionHub() {}}disabled={Boolean(busyKey)}>- Sign in with ChatGPT+ {(editing?.broker ?? createBroker) === 'grok-subscription'+ ? 'Sign in with Grok'+ : 'Sign in with ChatGPT'}</button></span></div>diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsxindex 8932db25c..2dcb70706 100644--- a/control-ui/components/HostWizard/index.tsx+++ b/control-ui/components/HostWizard/index.tsx@@ -25,9 +25,16 @@ import {listCodexSubscriptionConnections,} from '@/lib/codexSubscription'import { isDisabledCapabilityError } from '@/lib/codexSubscriptionFeature'+import {+ type GrokSubscriptionConnectionView,+ isAssignableGrokGrant,+ listGrokConnectionModels,+ listGrokSubscriptionConnections,+} from '@/lib/grokSubscription'import { useLlmAllowedModels } from '@/lib/hooks/useLlmAllowedModels'import { getAgentNameError } from '@/lib/k8sValidation'import {+ GROK_SUBSCRIPTION_PROVIDER,type HostAllowedModel,type LlmPolicy,type LlmProvider,@@ -155,19 +162,21 @@ function isStepValid(stepIndex: number, state: HostWizardValidationState): booleif (stepIndex === 1) {if (!state.modelName.trim()) return falseif (- state.provider === 'codex-subscription' &&+ (state.provider === 'codex-subscription' || state.provider === GROK_SUBSCRIPTION_PROVIDER) &&(!state.connectionRef.trim() ||state.connectionRef.trim() === CODEX_UNASSIGNED_CONNECTION_KEY ||- (state.codexModels.length > 0 && !state.codexModels.includes(state.modelName.trim())))+ (state.provider === GROK_SUBSCRIPTION_PROVIDER+ ? state.grokModels.length > 0 && !state.grokModels.includes(state.modelName.trim())+ : state.codexModels.length > 0 && !state.codexModels.includes(state.modelName.trim())))) {return false}- // Broker-only chains (Codex with no static fallback) need the grant in the- // shared LLM Secret picker. Any static primary/fallback still requires the- // exact credential slots (existing Secret or a complete new one).+ // Broker-only chains need the grant in the shared LLM Secret picker. Any+ // static primary/fallback still requires the exact credential slots.if (!llmChainRequiresSecret(state.provider, state.llmPolicy?.fallbacks)) {return (- state.provider === 'codex-subscription' &&+ (state.provider === 'codex-subscription' ||+ state.provider === GROK_SUBSCRIPTION_PROVIDER) &&parseCredentialSelect(state.existingSecret).kind === 'subscription')}@@ -251,6 +260,9 @@ export function HostWizard({const [connectionRef, setConnectionRef] = useState(CODEX_UNASSIGNED_CONNECTION_KEY)const [codexModels, setCodexModels] = useState<string[]>([])const [codexConnections, setCodexConnections] = useState<CodexSubscriptionConnectionView[]>([])+ const [grokModels, setGrokModels] = useState<string[]>([])+ const [grokConnections, setGrokConnections] = useState<GrokSubscriptionConnectionView[]>([])+ const [grokEnabled, setGrokEnabled] = useState(false)const [stateless, setStateless] = useState(false)const [users, setUsers] = useState<Array<{ id: string; email: string; name: string | null; displayName: string | null }>@@ -304,32 +316,59 @@ export function HostWizard({meta: 'ChatGPT subscription',providers: [{ id: 'codex-subscription', label: 'ChatGPT Subscription' }],})),+ ...grokConnections.filter(isAssignableGrokGrant).map(row => ({+ group: 'Grok subscriptions',+ value: credentialSelectValue('', row.connectionKey, GROK_SUBSCRIPTION_PROVIDER),+ label: row.displayName || row.connectionKey,+ meta: 'Grok subscription',+ providers: [{ id: GROK_SUBSCRIPTION_PROVIDER, label: 'xAI Grok Subscription' }],+ })),],- [codexConnections, existingSecrets]+ [codexConnections, grokConnections, existingSecrets])const apiKeyOptions = useMemo(() => secretOptions.filter(option => option.group === 'API keys'),[secretOptions])const catalogForEditor = useMemo(() => {- if (provider !== 'codex-subscription') return allowedCatalog- const others = allowedCatalog.filter(row => row.provider !== 'codex-subscription')- if (codexModels.length === 0) return others- return [- ...others,- ...codexModels.map(model => ({- id: `codex:${model}`,- provider: 'codex-subscription',- model,- vendor: 'OpenAI',- display_name: model,- context_window_tokens: null,- enabled: true,- source: 'discovery' as const,- stale: false,- })),- ]- }, [allowedCatalog, provider, codexModels])+ if (provider === 'codex-subscription') {+ const others = allowedCatalog.filter(row => row.provider !== 'codex-subscription')+ if (codexModels.length === 0) return others+ return [+ ...others,+ ...codexModels.map(model => ({+ id: `codex:${model}`,+ provider: 'codex-subscription',+ model,+ vendor: 'OpenAI',+ display_name: model,+ context_window_tokens: null,+ enabled: true,+ source: 'discovery' as const,+ stale: false,+ })),+ ]+ }+ if (provider === GROK_SUBSCRIPTION_PROVIDER) {+ const others = allowedCatalog.filter(row => row.provider !== GROK_SUBSCRIPTION_PROVIDER)+ if (grokModels.length === 0) return others+ return [+ ...others,+ ...grokModels.map(model => ({+ id: `grok:${model}`,+ provider: GROK_SUBSCRIPTION_PROVIDER,+ model,+ vendor: 'xAI',+ display_name: model,+ context_window_tokens: null,+ enabled: true,+ source: 'discovery' as const,+ stale: false,+ })),+ ]+ }+ return allowedCatalog+ }, [allowedCatalog, provider, codexModels, grokModels])const providerModelOptions = useMemo(() => getModelOptions(catalogForEditor, provider),[catalogForEditor, provider]@@ -341,12 +380,13 @@ export function HostWizard({const parsed = parseCredentialSelect(secretName)if (parsed.kind === 'subscription') {setConnectionRef(parsed.connectionKey)- setProvider('codex-subscription')+ setProvider(parsed.provider)setModelName('')return}setConnectionRef(CODEX_UNASSIGNED_CONNECTION_KEY)setCodexModels([])+ setGrokModels([])const selectedSecret = existingSecrets.find(secret => (secret.name || secret.metadata?.name) === secretName)@@ -373,6 +413,22 @@ export function HostWizard({}}})+ void listGrokSubscriptionConnections()+ .then(rows => {+ if (!cancelled) {+ setGrokConnections(rows)+ setGrokEnabled(true)+ }+ })+ .catch(err => {+ if (!cancelled) {+ setGrokConnections([])+ setGrokEnabled(false)+ if (!isDisabledCapabilityError(err)) {+ setError(err instanceof Error ? err.message : 'Could not load Grok subscriptions')+ }+ }+ })return () => {cancelled = true}@@ -380,9 +436,28 @@ export function HostWizard({useEffect(() => {if (!connectionRef.trim() || connectionRef === CODEX_UNASSIGNED_CONNECTION_KEY) {setCodexModels([])+ setGrokModels([])return}let cancelled = false+ if (provider === GROK_SUBSCRIPTION_PROVIDER) {+ setCodexModels([])+ void listGrokConnectionModels(connectionRef)+ .then(models => {+ if (!cancelled) setGrokModels(offeredCodexModelNames(models))+ })+ .catch(() => {+ if (!cancelled) {+ setGrokModels([])+ setModelName('')+ setError('Could not load Grok grant models')+ }+ })+ return () => {+ cancelled = true+ }+ }+ setGrokModels([])void listCodexConnectionModels(connectionRef).then(models => {if (!cancelled) setCodexModels(offeredCodexModelNames(models))@@ -397,16 +472,18 @@ export function HostWizard({return () => {cancelled = true}- }, [connectionRef])+ }, [connectionRef, provider])// Keep the selected model valid for the current provider's enabled models:// seed the default once the allowlist loads, and re-default if a provider// switch left the model out of range.useEffect(() => {if (modelsLoading) return- if (provider === 'codex-subscription') {+ if (provider === 'codex-subscription' || provider === GROK_SUBSCRIPTION_PROVIDER) {const offered = constrainModelOptions(catalogForEditor, allowedModels, provider)if (offered.length === 0) return- const grant = codexConnections.find(row => row.connectionKey === connectionRef)+ const grant = (+ provider === GROK_SUBSCRIPTION_PROVIDER ? grokConnections : codexConnections+ ).find(row => row.connectionKey === connectionRef)const next = resolveCodexGrantModel(modelName, offered, grant?.defaultModel)if (next !== modelName) setModelName(next)return@@ -471,6 +548,7 @@ export function HostWizard({modelName,connectionRef,codexModels,+ grokModels,}),[hostName,@@ -484,6 +562,7 @@ export function HostWizard({modelName,connectionRef,codexModels,+ grokModels,])@@ -982,9 +1061,13 @@ export function HostWizard({onPrimaryChange={next => {setProvider(next.provider)setModelName(next.model)- if (next.provider !== 'codex-subscription') {+ if (+ next.provider !== 'codex-subscription' &&+ next.provider !== GROK_SUBSCRIPTION_PROVIDER+ ) {setConnectionRef(CODEX_UNASSIGNED_CONNECTION_KEY)setCodexModels([])+ setGrokModels([])if (parseCredentialSelect(existingSecret).kind === 'subscription') {setExistingSecret('')}@@ -1011,6 +1094,7 @@ export function HostWizard({secretKeys={chainRequiresSecret && secretMode === 'new' ? llmSecretKeys : []}fallbackProvidersInitiallyCollapseddisabled={busy}+ grokEnabled={grokEnabled}/></div>)}diff --git a/control-ui/components/HostWizard/types.ts b/control-ui/components/HostWizard/types.tsindex 42b94250f..591c6f9e9 100644--- a/control-ui/components/HostWizard/types.ts+++ b/control-ui/components/HostWizard/types.ts@@ -78,4 +78,5 @@ export type HostWizardValidationState = {modelName: stringconnectionRef: stringcodexModels: string[]+ grokModels: string[]}diff --git a/control-ui/components/LlmPolicyEditor/index.tsx b/control-ui/components/LlmPolicyEditor/index.tsxindex 4eea35817..53884b073 100644--- a/control-ui/components/LlmPolicyEditor/index.tsx+++ b/control-ui/components/LlmPolicyEditor/index.tsx@@ -4,6 +4,7 @@ import React, { useEffect, useMemo } from 'react'import { IconTrash } from '@/components/icons'import { Button, CheckboxField, Field, SelectInput, TextInput } from '@/components/ui'import {+ GROK_SUBSCRIPTION_PROVIDER,LLM_DEFAULT_COOLDOWN_SECONDS,LLM_TRIGGER_CLASSES,LLM_TRIGGER_LABELS,@@ -12,11 +13,11 @@ import {type LlmProvider,type LlmTriggerClass,OPENAI_SUBSCRIPTION_PROVIDER,- OPERATOR_PROVIDER_OPTIONS,constrainModelOptions,getCredentialSlotOptions,getProviderDisplayLabel,normalizeProvider,+ operatorProviderOptions,providerSupportsFallbackCredentialSlot,resolveDefaultModel,} from '@/lib/llm'@@ -54,7 +55,9 @@ export function LlmPolicyEditor({secretKeys = [],defaultProvider,disabled = false,+ grokEnabled = false,}: LlmPolicyEditorProps) {+ const pickerOptions = operatorProviderOptions({ grokEnabled })const fallbacks = value?.fallbacks ?? []const triggerOn = value?.triggerOn ?? [...LLM_TRIGGER_CLASSES]const cooldownSeconds = value?.cooldownSeconds ?? LLM_DEFAULT_COOLDOWN_SECONDS@@ -179,6 +182,7 @@ export function LlmPolicyEditor({disabled={disabled}isFirst={index === 0}isLast={index === fallbacks.length - 1}+ pickerOptions={pickerOptions}onChange={patch => updateEntry(index, patch)}onRemove={() => removeEntry(index)}onMove={direction => moveEntry(index, direction)}@@ -206,6 +210,7 @@ type FallbackRowProps = {disabled: booleanisFirst: booleanisLast: boolean+ pickerOptions: Array<{ value: LlmProvider; label: string }>onChange: (patch: Partial<LlmFallbackEntry>) => voidonRemove: () => voidonMove: (direction: -1 | 1) => void@@ -220,6 +225,7 @@ function FallbackRow({disabled,isFirst,isLast,+ pickerOptions,onChange,onRemove,onMove,@@ -311,7 +317,7 @@ function FallbackRow({})}}>- {OPERATOR_PROVIDER_OPTIONS.map(option => (+ {pickerOptions.map(option => (<option key={option.value} value={option.value}>{option.label}</option>@@ -319,6 +325,10 @@ function FallbackRow({{entry.provider === OPENAI_SUBSCRIPTION_PROVIDER ? (<option value={OPENAI_SUBSCRIPTION_PROVIDER}>OpenAI (ChatGPT subscription)</option>) : null}+ {entry.provider === GROK_SUBSCRIPTION_PROVIDER &&+ !pickerOptions.some(option => option.value === GROK_SUBSCRIPTION_PROVIDER) ? (+ <option value={GROK_SUBSCRIPTION_PROVIDER}>xAI Grok Subscription</option>+ ) : null}</SelectInput></Field>diff --git a/control-ui/components/LlmPolicyEditor/types.ts b/control-ui/components/LlmPolicyEditor/types.tsindex 61d79eefd..ec2dcd1c9 100644--- a/control-ui/components/LlmPolicyEditor/types.ts+++ b/control-ui/components/LlmPolicyEditor/types.ts@@ -22,4 +22,5 @@ export type LlmPolicyEditorProps = {// The Host's own provider — a freshly added fallback pre-selects it.defaultProvider: LlmProviderdisabled?: boolean+ grokEnabled?: boolean}diff --git a/control-ui/components/LlmProviderConfig/index.tsx b/control-ui/components/LlmProviderConfig/index.tsxindex ecb3b1075..d25236964 100644--- a/control-ui/components/LlmProviderConfig/index.tsx+++ b/control-ui/components/LlmProviderConfig/index.tsx@@ -11,11 +11,11 @@ import { IconChevronRight } from '@/components/icons'import { Button, Field, TextAreaInput, TextInput } from '@/components/ui'import { cn } from '@/lib/cn'import {+ GROK_SUBSCRIPTION_PROVIDER,type LlmCredentialField,type LlmCredentialGroup,type LlmProvider,OPENAI_SUBSCRIPTION_PROVIDER,- OPERATOR_PROVIDER_OPTIONS,allowedModelsForProvider,constrainModelOptions,describeLlmCompleteness,@@ -27,6 +27,7 @@ import {isProviderAllowUnrestricted,mintFallbackSlot,normalizeProvider,+ operatorProviderOptions,providerSupportsFallbackCredentialSlot,resolveDefaultModel,validateLlmSecretData,@@ -103,6 +104,7 @@ export function LlmProviderConfig({secretKeys = [],fallbackProvidersInitiallyCollapsed = false,disabled = false,+ grokEnabled = false,}: LlmProviderConfigProps) {const [fallbackProvidersOpen, setFallbackProvidersOpen] = useState(!fallbackProvidersInitiallyCollapsed@@ -125,7 +127,7 @@ export function LlmProviderConfig({[catalog, allowedModels, provider])const primaryModelOutOfAllowlist = Boolean(model) && !primaryModelOptions.includes(model)- const pickerOptions = OPERATOR_PROVIDER_OPTIONS+ const pickerOptions = operatorProviderOptions({ grokEnabled })const primaryProviderOptions = useMemo(() =>pickerOptions.map(option => ({@@ -304,7 +306,9 @@ export function LlmProviderConfig({<p className="cu-field__error">{provider === OPENAI_SUBSCRIPTION_PROVIDER? 'No enabled models for this subscription. Connect and sync the grant first.'- : 'No enabled models for this provider. Add one under LLM Models first.'}+ : provider === GROK_SUBSCRIPTION_PROVIDER+ ? 'No enabled models for this Grok subscription. Connect and sync the grant first.'+ : 'No enabled models for this provider. Add one under LLM Models first.'}</p>) : null}@@ -367,6 +371,7 @@ export function LlmProviderConfig({secretKeys={secretKeys}defaultProvider={provider}disabled={disabled}+ grokEnabled={grokEnabled}/></div>) : null}diff --git a/control-ui/components/LlmProviderConfig/types.ts b/control-ui/components/LlmProviderConfig/types.tsindex 645b39fd3..271eaf5b7 100644--- a/control-ui/components/LlmProviderConfig/types.ts+++ b/control-ui/components/LlmProviderConfig/types.ts@@ -58,4 +58,7 @@ export type LlmProviderConfigProps = {fallbackProvidersInitiallyCollapsed?: booleandisabled?: boolean++ /** Proven by a successful Grok connections list. Hidden when false/omitted. */+ grokEnabled?: boolean}diff --git a/control-ui/components/LlmProviderIcon/index.tsx b/control-ui/components/LlmProviderIcon/index.tsxindex 35ed13ee2..b98e31e77 100644--- a/control-ui/components/LlmProviderIcon/index.tsx+++ b/control-ui/components/LlmProviderIcon/index.tsx@@ -23,7 +23,11 @@ export function LlmProviderIcon({ provider, label }: LlmProviderIconProps) {{failed ? (<span>{label.slice(0, 1).toUpperCase()}</span>) : (- <img src={`/provider-icons/${provider}.svg`} alt="" onError={() => setFailed(true)} />+ <img+ src={`/provider-icons/${provider === 'grok-subscription' ? 'xai' : provider}.svg`}+ alt=""+ onError={() => setFailed(true)}+ />)}</span>)diff --git a/control-ui/components/RecipeEditor.tsx b/control-ui/components/RecipeEditor.tsxindex 45571d278..6154d149d 100644--- a/control-ui/components/RecipeEditor.tsx+++ b/control-ui/components/RecipeEditor.tsx@@ -33,7 +33,17 @@ import {import { isDisabledCapabilityError } from '../lib/codexSubscriptionFeature'import { analyzeWorkflowRecipeEgress } from '../lib/egressModel'import type { EgressBinding, EgressEditorStatus } from '../lib/egressModel'-import { OPENAI_SUBSCRIPTION_PROVIDER, brokerBackedRecipeAuthoringError } from '../lib/llm'+import {+ type GrokSubscriptionConnectionView,+ SUBSCRIPTION_CONNECTION_REF_ANNOTATION,+ isAssignableGrokGrant,+ listGrokSubscriptionConnections,+} from '../lib/grokSubscription'+import {+ GROK_SUBSCRIPTION_PROVIDER,+ OPENAI_SUBSCRIPTION_PROVIDER,+ brokerBackedRecipeAuthoringError,+} from '../lib/llm'import { credentialSelectValue, parseCredentialSelect } from '../lib/llmCredentialSelect'import { DEFAULT_OPERATOR_DEFAULTS, applyDefaults } from '../lib/recipeDefaults'import {@@ -102,17 +112,37 @@ function readRecipeAgentProvider(spec: unknown): string {function readRecipeCodexGrantAnnotation(resource?: { metadata?: { annotations?: Record<string, string> } } | null): string {- const raw = resource?.metadata?.annotations?.[CODEX_CONNECTION_REF_ANNOTATION]+ 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 : aliasreturn typeof raw === 'string' ? raw.trim() : ''}function recipeGrantAnnotations(provider: string, connectionRef: string): Record<string, string> {+ const parsed = parseCredentialSelect(+ credentialSelectValue(+ '',+ connectionRef,+ provider === GROK_SUBSCRIPTION_PROVIDER ? GROK_SUBSCRIPTION_PROVIDER : 'codex-subscription'+ )+ )+ const key = parsed.kind === 'subscription' ? parsed.connectionKey : ''+ if (provider === GROK_SUBSCRIPTION_PROVIDER) {+ return {+ [CODEX_CONNECTION_REF_ANNOTATION]: '',+ [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: key,+ }+ }if (provider !== OPENAI_SUBSCRIPTION_PROVIDER) {- return { [CODEX_CONNECTION_REF_ANNOTATION]: '' }+ return {+ [CODEX_CONNECTION_REF_ANNOTATION]: '',+ [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: '',+ }}- const parsed = parseCredentialSelect(credentialSelectValue('', connectionRef))return {- [CODEX_CONNECTION_REF_ANNOTATION]: parsed.kind === 'subscription' ? parsed.connectionKey : '',+ [CODEX_CONNECTION_REF_ANNOTATION]: key,+ [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: key,}}@@ -1603,6 +1633,25 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)}}})+ void listGrokSubscriptionConnections()+ .then(rows => {+ if (!cancelled) {+ setGrokConnections(rows)+ setGrokGrantLoadError('')+ }+ })+ .catch(err => {+ if (!cancelled) {+ setGrokConnections([])+ if (!isDisabledCapabilityError(err)) {+ setGrokGrantLoadError(+ err instanceof Error ? err.message : 'Could not load Grok subscriptions'+ )+ } else {+ setGrokGrantLoadError('')+ }+ }+ })return () => {cancelled = true}@@ -1628,6 +1677,8 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)})const [codexConnections, setCodexConnections] = useState<CodexSubscriptionConnectionView[]>([])const [codexGrantLoadError, setCodexGrantLoadError] = useState('')+ const [grokConnections, setGrokConnections] = useState<GrokSubscriptionConnectionView[]>([])+ const [grokGrantLoadError, setGrokGrantLoadError] = useState('')const [codexConnectionRef, setCodexConnectionRef] = useState(() =>readRecipeCodexGrantAnnotation(initial))@@ -1683,6 +1734,15 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)}}, [jsonInput])+ const isGrokRecipe = useMemo(() => {+ try {+ const parsed = JSON.parse(jsonInput) as { spec?: unknown }+ return readRecipeAgentProvider(parsed.spec) === GROK_SUBSCRIPTION_PROVIDER+ } catch {+ return false+ }+ }, [jsonInput])+const codexGrantOptions = useMemo<LlmSecretSelectOption[]>(() => {const options: LlmSecretSelectOption[] = codexConnections.filter(isAssignableCodexGrant)@@ -1711,6 +1771,34 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)return options}, [codexConnections, codexConnectionRef])+ const grokGrantOptions = useMemo<LlmSecretSelectOption[]>(() => {+ const options: LlmSecretSelectOption[] = grokConnections+ .filter(isAssignableGrokGrant)+ .map(row => ({+ group: 'Grok subscriptions',+ value: credentialSelectValue('', row.connectionKey, GROK_SUBSCRIPTION_PROVIDER),+ label: row.displayName || row.connectionKey,+ meta: 'Grok subscription',+ providers: [{ id: GROK_SUBSCRIPTION_PROVIDER, label: 'xAI Grok Subscription' }],+ }))+ if (+ codexConnectionRef &&+ codexConnectionRef !== CODEX_UNASSIGNED_CONNECTION_KEY &&+ !grokConnections.some(+ row => row.connectionKey === codexConnectionRef && isAssignableGrokGrant(row)+ )+ ) {+ options.unshift({+ group: 'Grok subscriptions',+ value: credentialSelectValue('', codexConnectionRef, GROK_SUBSCRIPTION_PROVIDER),+ label: `${codexConnectionRef} (unavailable)`,+ meta: 'Grok subscription',+ providers: [{ id: GROK_SUBSCRIPTION_PROVIDER, label: 'xAI Grok Subscription' }],+ })+ }+ return options+ }, [grokConnections, codexConnectionRef])+const deploying = deployPhase !== 'idle'// If the resolved recipe-secret namespaces change after refs were detected@@ -2542,7 +2630,8 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)<div style={{ fontWeight: 700, marginBottom: 8 }}>ChatGPT grant</div><p style={{ margin: '0 0 10px', color: 'var(--cu-text-muted)' }}>Choose an existing ChatGPT grant. The recipe stores it as{' '}- <code>clerum.io/codex-connection-ref</code>.+ <code>clerum.io/codex-connection-ref</code> and{' '}+ <code>clerum.io/subscription-connection-ref</code>.</p><LlmSecretSelectid="codex-recipe-grant"@@ -2563,6 +2652,32 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)</div>) : null}+ {step === 'confirm' && isGrokRecipe ? (+ <div className="cu-recipe-status-panel" data-testid="grok-recipe-grant">+ <div style={{ fontWeight: 700, marginBottom: 8 }}>Grok grant</div>+ <p style={{ margin: '0 0 10px', color: 'var(--cu-text-muted)' }}>+ Choose an existing Grok grant. The recipe stores it as{' '}+ <code>clerum.io/subscription-connection-ref</code> only.+ </p>+ <LlmSecretSelect+ id="grok-recipe-grant"+ ariaLabel="Grok grant"+ value={credentialSelectValue('', codexConnectionRef, GROK_SUBSCRIPTION_PROVIDER)}+ onChange={value => {+ const parsed = parseCredentialSelect(value)+ setCodexConnectionRef(parsed.kind === 'subscription' ? parsed.connectionKey : '')+ }}+ options={grokGrantOptions}+ placeholder="Choose a Grok grant"+ />+ {grokGrantLoadError ? (+ <div className="cu-banner cu-banner--error" role="alert" style={{ marginTop: 10 }}>+ {grokGrantLoadError}+ </div>+ ) : null}+ </div>+ ) : null}+{/* Policy banner — appears when L1 (client) or L2 (server) rejects. */}{step === 'confirm' && (l1Live || serverValidationMessages.length > 0) && (<div className="cu-recipe-status-panel cu-recipe-status-panel--error" role="alert">diff --git a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsxindex 90d32d74c..0e82e32e7 100644--- a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx+++ b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx@@ -30,6 +30,12 @@ vi.mock('@lib/codexSubscriptionFeature', () => ({loadCodexSubscriptionCapability: async () => ({ enabled: true }),}))+vi.mock('@lib/grokSubscriptionFeature', () => ({+ isGrokSubscriptionUiEnabled: (capability?: { enabled?: boolean } | null) =>+ capability?.enabled === true,+ loadGrokSubscriptionCapability: async () => ({ enabled: false }),+}))+vi.mock('@lib/codexSubscription', async importOriginal => {const actual = await importOriginal<typeof import('@lib/codexSubscription')>()return {@@ -46,6 +52,14 @@ vi.mock('@lib/codexSubscription', async importOriginal => {}})+vi.mock('@lib/grokSubscription', async importOriginal => {+ const actual = await importOriginal<typeof import('@lib/grokSubscription')>()+ return {+ ...actual,+ listGrokSubscriptionConnections: vi.fn().mockResolvedValue([]),+ }+})+function connection(overrides: Partial<CodexSubscriptionConnectionView> &Pick<CodexSubscriptionConnectionView, 'connectionKey'>diff --git a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsxindex 94698937b..46f3e6908 100644--- a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx+++ b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx@@ -50,6 +50,15 @@ vi.mock('../../lib/codexSubscription', async importOriginal => {}})+vi.mock('../../lib/grokSubscription', async importOriginal => {+ const actual = await importOriginal<typeof import('../../lib/grokSubscription')>()+ return {+ ...actual,+ listGrokSubscriptionConnections: vi.fn().mockRejectedValue({ status: 404 }),+ listGrokConnectionModels: vi.fn().mockResolvedValue([]),+ }+})+vi.mock('../../lib/api', () => ({apiGet: vi.fn(),apiSend: vi.fn(),diff --git a/control-ui/components/__tests__/HostWizard.test.tsx b/control-ui/components/__tests__/HostWizard.test.tsxindex 763f14a4d..35ee390f8 100644--- a/control-ui/components/__tests__/HostWizard.test.tsx+++ b/control-ui/components/__tests__/HostWizard.test.tsx@@ -26,6 +26,15 @@ import { ToastProvider } from '../Toast'* These tests lock the new behavior so it cannot regress.*/+vi.mock('../../lib/grokSubscription', async importOriginal => {+ const actual = await importOriginal<typeof import('../../lib/grokSubscription')>()+ return {+ ...actual,+ listGrokSubscriptionConnections: vi.fn().mockRejectedValue({ status: 404 }),+ listGrokConnectionModels: vi.fn().mockResolvedValue([]),+ }+})+vi.mock('../../lib/codexSubscription', async importOriginal => {const actual = await importOriginal<typeof import('../../lib/codexSubscription')>()return {diff --git a/control-ui/components/__tests__/RecipeEditor.test.tsx b/control-ui/components/__tests__/RecipeEditor.test.tsxindex a6ce3a0b6..b7ddce262 100644--- a/control-ui/components/__tests__/RecipeEditor.test.tsx+++ b/control-ui/components/__tests__/RecipeEditor.test.tsx@@ -10,6 +10,14 @@ import { RecipeEditor } from '../RecipeEditor'import { ToastProvider } from '../Toast'// vi.mock is hoisted before imports, factory runs lazily+vi.mock('../../lib/grokSubscription', async importOriginal => {+ const actual = await importOriginal<typeof import('../../lib/grokSubscription')>()+ return {+ ...actual,+ listGrokSubscriptionConnections: vi.fn().mockRejectedValue({ status: 404 }),+ }+})+vi.mock('../../lib/codexSubscription', async importOriginal => {const actual = await importOriginal<typeof import('../../lib/codexSubscription')>()return {@@ -888,7 +896,10 @@ describe('RecipeEditor — deploy flow', () => {const validationPayload = vi.mocked(api.validateRecipeServer).mock.calls[0][0]expect(validationPayload.metadata).toEqual({name: 'namespace-ignored',- annotations: { 'clerum.io/codex-connection-ref': '' },+ annotations: {+ 'clerum.io/codex-connection-ref': '',+ 'clerum.io/subscription-connection-ref': '',+ },})expect(validationPayload.spec.workloads[0]).toEqual(expect.objectContaining({ id: 'api', type: 'deployment' })@@ -898,7 +909,10 @@ describe('RecipeEditor — deploy flow', () => {const createPayload = vi.mocked(api.createRecipe).mock.calls[0][0]expect(createPayload.metadata).toEqual({name: 'namespace-ignored',- annotations: { 'clerum.io/codex-connection-ref': '' },+ annotations: {+ 'clerum.io/codex-connection-ref': '',+ 'clerum.io/subscription-connection-ref': '',+ },})expect(createPayload.spec.workloads[0]).toEqual(expect.objectContaining({ id: 'api', type: 'deployment' })@@ -1759,6 +1773,7 @@ describe('RecipeEditor — grants in editor', () => {expect(createPayload.spec.agent?.secretRef).toBeUndefined()expect(createPayload.metadata?.annotations).toEqual({'clerum.io/codex-connection-ref': 'team-plus',+ 'clerum.io/subscription-connection-ref': 'team-plus',})expect(onSaved).toHaveBeenCalled()})diff --git a/control-ui/lib/__tests__/llm.test.ts b/control-ui/lib/__tests__/llm.test.tsindex 4d73fb288..bd22a6e83 100644--- a/control-ui/lib/__tests__/llm.test.ts+++ b/control-ui/lib/__tests__/llm.test.ts@@ -90,6 +90,15 @@ describe('OpenAI family presentation', () => {expect(isOpenAiFamily('codex-subscription')).toBe(true)})+ it('does not fold Grok subscription into the OpenAI family', () => {+ expect(isOpenAiFamily('grok-subscription')).toBe(false)+ expect(catalogGroupKey('grok-subscription')).toBe('grok-subscription')+ expect(getProviderLabel('grok-subscription')).not.toBe('OpenAI')+ expect(OPERATOR_PROVIDER_OPTIONS.some(option => option.value === 'grok-subscription')).toBe(+ true+ )+ })+it('marks a model as API key, subscription, or both', () => {const catalog: LlmModelCatalogEntry[] = [{ provider: 'openai', model: 'gpt-5.1', enabled: true },@@ -193,10 +202,19 @@ describe('LLM_CREDENTIAL_GROUPS (spec R4.5.1/R4.5.2)', () => {expect(resolveDefaultModel('codex-subscription', ['gpt-5.1'])).toBe('')})+ it('models Grok as a zero-slot broker with no invented default model', () => {+ const grok = LLM_CREDENTIAL_GROUPS.find(g => g.provider === 'grok-subscription')!+ expect(grok.slots).toEqual([])+ expect(LLM_DEFAULT_MODEL_BY_PROVIDER['grok-subscription']).toBeUndefined()+ })+it('keeps oauth-broker providers off the Kubernetes Secret editor list', () => {expect(LLM_SECRET_EDITOR_GROUPS.some(group => group.provider === 'codex-subscription')).toBe(false)+ expect(LLM_SECRET_EDITOR_GROUPS.some(group => group.provider === 'grok-subscription')).toBe(+ false+ )expect(LLM_SECRET_EDITOR_GROUPS.every(group => group.slots.length > 0)).toBe(true)})})diff --git a/control-ui/lib/__tests__/llmCredentialSelect.test.ts b/control-ui/lib/__tests__/llmCredentialSelect.test.tsindex 906ca3de5..068d845bf 100644--- a/control-ui/lib/__tests__/llmCredentialSelect.test.ts+++ b/control-ui/lib/__tests__/llmCredentialSelect.test.ts@@ -3,11 +3,20 @@ import { credentialSelectValue, parseCredentialSelect } from '../llmCredentialSedescribe('llmCredentialSelect', () => {it('encodes a subscription without colliding with a secret of the same name', () => {- expect(credentialSelectValue('Team Plus', 'codex-aaa')).toBe('sub:codex-aaa')+ expect(credentialSelectValue('Team Plus', 'codex-aaa')).toBe('sub:codex-subscription:codex-aaa')expect(parseCredentialSelect('sub:codex-aaa')).toEqual({kind: 'subscription',+ provider: 'codex-subscription',connectionKey: 'codex-aaa',})+ expect(parseCredentialSelect('sub:grok-subscription:team-grok')).toEqual({+ kind: 'subscription',+ provider: 'grok-subscription',+ connectionKey: 'team-grok',+ })+ expect(credentialSelectValue('', 'team-grok', 'grok-subscription')).toBe(+ 'sub:grok-subscription:team-grok'+ )expect(parseCredentialSelect('Team Plus')).toEqual({ kind: 'secret', name: 'Team Plus' })})diff --git a/control-ui/lib/grokSubscription.ts b/control-ui/lib/grokSubscription.tsnew file mode 100644index 000000000..8c267075b--- /dev/null+++ b/control-ui/lib/grokSubscription.ts@@ -0,0 +1,205 @@+import { apiGet, apiSend } from './api'+import {+ CODEX_UNASSIGNED_CONNECTION_KEY,+ type CodexAssignableHost,+ type CodexCatalogStatus,+ type CodexCatalogSyncView,+ type CodexConnectionStatus,+ type CodexDevicePollView,+ type CodexOAuthIntent,+ type CodexSubscriptionConnectionView,+ sanitizeCodexConnection,+} from './codexSubscription'++export const GROK_SUBSCRIPTION_API_BASE = '/api/v1/admin/llm/providers/grok-subscription'+export const GROK_UNASSIGNED_CONNECTION_KEY = CODEX_UNASSIGNED_CONNECTION_KEY+export const SUBSCRIPTION_CONNECTION_REF_ANNOTATION = 'clerum.io/subscription-connection-ref'+export const GROK_DEVICE_VERIFICATION_ORIGIN = 'https://auth.x.ai'++export type GrokSubscriptionConnectionView = CodexSubscriptionConnectionView+export type GrokAssignableHost = CodexAssignableHost+export type GrokCatalogStatus = CodexCatalogStatus+export type GrokConnectionStatus = CodexConnectionStatus+export type GrokOAuthIntent = CodexOAuthIntent+export type GrokDevicePollView = CodexDevicePollView+export type GrokCatalogSyncView = CodexCatalogSyncView++export type GrokDeviceStartView = {+ userCode: string+ verificationUri: string+ intervalSeconds: number+ state: string+ intent: GrokOAuthIntent+}++const FORBIDDEN_KEY =+ /accessToken|refreshToken|deviceCode|authorization|set-cookie|cookie|proxyUrl|proxyURL|accountId|rawAccount|subject/i++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)+}++function assertNoForbiddenKeys(value: unknown, path = 'root'): void {+ if (Array.isArray(value)) {+ value.forEach((entry, index) => assertNoForbiddenKeys(entry, `${path}[${index}]`))+ return+ }+ if (!isPlainObject(value)) return+ for (const [key, nested] of Object.entries(value)) {+ if (FORBIDDEN_KEY.test(key)) {+ throw new Error(`Grok subscription payload leaked forbidden field "${key}" at ${path}`)+ }+ assertNoForbiddenKeys(nested, `${path}.${key}`)+ }+}++function pickString(value: unknown): string | null {+ return typeof value === 'string' && value.trim() ? value : null+}++function pickNumber(value: unknown, fallback = 0): number {+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback+}++export function isAllowedGrokVerificationUri(value: string): boolean {+ try {+ const parsed = new URL(value)+ return parsed.protocol === 'https:' && parsed.hostname === 'auth.x.ai'+ } catch {+ return false+ }+}++export function isAssignableGrokGrant(+ row: Pick<GrokSubscriptionConnectionView, 'status' | 'catalogStatus'>+): boolean {+ return row.status === 'connected' && row.catalogStatus === 'ready'+}++function sanitizeGrokDeviceStart(raw: unknown): GrokDeviceStartView {+ assertNoForbiddenKeys(raw)+ if (!isPlainObject(raw)) throw new Error('Grok device start is not an object')+ const userCode = pickString(raw.userCode)+ const verificationUri = pickString(raw.verificationUri)+ const state = pickString(raw.state)+ const intent = raw.intent+ if (!userCode || !verificationUri || !state) {+ throw new Error('Grok device start is incomplete')+ }+ if (!isAllowedGrokVerificationUri(verificationUri)) {+ throw new Error('Grok device start verification URI is not allowed')+ }+ return {+ userCode,+ verificationUri,+ intervalSeconds: Math.max(1, pickNumber(raw.intervalSeconds, 5)),+ state,+ intent: intent === 'reconnect' || intent === 'replace' ? intent : 'connect',+ }+}++function keyedPath(connectionKey: string, action?: string): string {+ const base = `${GROK_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}`+ return action ? `${base}/${action}` : base+}++export async function listGrokSubscriptionConnections(): Promise<GrokSubscriptionConnectionView[]> {+ const raw = (await apiGet(`${GROK_SUBSCRIPTION_API_BASE}/connections`)) as {+ connections?: unknown+ }+ return Array.isArray(raw.connections) ? raw.connections.map(sanitizeCodexConnection) : []+}++export async function createGrokSubscriptionConnection(input: {+ displayName: string+ connectionKey?: string+}): Promise<GrokSubscriptionConnectionView> {+ return sanitizeCodexConnection(+ await apiSend('POST', `${GROK_SUBSCRIPTION_API_BASE}/connections`, input)+ )+}++export async function listGrokConnectionModels(+ connectionKey: string+): Promise<Array<{ model: string; enabled: boolean; stale: boolean }>> {+ const raw = (await apiGet(`${keyedPath(connectionKey)}/models`)) as {+ models?: Array<{ model?: string; enabled?: boolean; stale?: boolean }>+ }+ return Array.isArray(raw.models)+ ? raw.models+ .filter(row => typeof row.model === 'string' && row.model.trim())+ .map(row => ({+ model: String(row.model),+ enabled: row.enabled === true,+ stale: row.stale === true,+ }))+ : []+}++export async function startGrokDeviceConnect(+ intent: GrokOAuthIntent,+ connectionKey: string+): Promise<GrokDeviceStartView> {+ return sanitizeGrokDeviceStart(+ await apiSend('POST', keyedPath(connectionKey, 'device/start'), { intent })+ )+}++export async function pollGrokDevice(+ state: string,+ connectionKey: string+): Promise<GrokDevicePollView> {+ const raw = (await apiGet(keyedPath(connectionKey, 'device/poll'), { state })) as Record<+ string,+ unknown+ >+ assertNoForbiddenKeys(raw)+ if (raw.status === 'connected') {+ return { status: 'connected', connection: sanitizeCodexConnection(raw.connection) }+ }+ if (raw.status === 'expired' || raw.status === 'denied') {+ return { status: raw.status }+ }+ if (raw.status === 'pending' || raw.status === 'slow_down') {+ return {+ status: raw.status,+ intervalSeconds: Math.max(1, pickNumber(raw.intervalSeconds, 5)),+ state: pickString(raw.state) ?? '',+ }+ }+ throw new Error('Grok device poll status is invalid')+}++export async function revokeGrokSubscription(+ connectionKey: string+): Promise<GrokSubscriptionConnectionView> {+ return sanitizeCodexConnection(await apiSend('POST', keyedPath(connectionKey, 'revoke')))+}++export async function patchGrokSubscriptionConnection(+ connectionKey: string,+ patch: { displayName?: string; defaultModel?: string | null }+): Promise<GrokSubscriptionConnectionView> {+ return sanitizeCodexConnection(await apiSend('PATCH', keyedPath(connectionKey), patch))+}++export async function patchGrokCatalogModel(+ connectionKey: string,+ model: string,+ enabled: boolean+): Promise<Array<{ model: string; enabled: boolean; stale: boolean }>> {+ const raw = (await apiSend(+ 'PATCH',+ `${keyedPath(connectionKey)}/models/${encodeURIComponent(model)}`,+ { enabled }+ )) as { models?: Array<{ model?: string; enabled?: boolean; stale?: boolean }> }+ return Array.isArray(raw.models)+ ? raw.models+ .filter(row => typeof row.model === 'string' && row.model.trim())+ .map(row => ({+ model: String(row.model),+ enabled: row.enabled === true,+ stale: row.stale === true,+ }))+ : []+}diff --git a/control-ui/lib/grokSubscriptionFeature.ts b/control-ui/lib/grokSubscriptionFeature.tsnew file mode 100644index 000000000..1f87bff02--- /dev/null+++ b/control-ui/lib/grokSubscriptionFeature.ts@@ -0,0 +1,29 @@+import { isDisabledCapabilityError } from './codexSubscriptionFeature'+import { listGrokSubscriptionConnections } from './grokSubscription'++export type GrokSubscriptionCapability = {+ enabled: boolean+ error?: string+}++const DISABLED_CAPABILITY: GrokSubscriptionCapability = { enabled: false }++/**+ * Control UI default is off. Capability is proven only by a successful+ * keyed connections list — never the Codex un-keyed `/connection` alias.+ */+export async function loadGrokSubscriptionCapability(): Promise<GrokSubscriptionCapability> {+ try {+ await listGrokSubscriptionConnections()+ return { enabled: true }+ } catch (error) {+ if (isDisabledCapabilityError(error)) return DISABLED_CAPABILITY+ throw error+ }+}++export function isGrokSubscriptionUiEnabled(+ capability: GrokSubscriptionCapability | null | undefined+): boolean {+ return capability?.enabled === true+}diff --git a/control-ui/lib/llm.ts b/control-ui/lib/llm.tsindex 142f5b1b4..6905053c9 100644--- a/control-ui/lib/llm.ts+++ b/control-ui/lib/llm.ts@@ -51,15 +51,29 @@ export const LLM_PROVIDER_OPTIONS: Array<{ value: LlmProvider; label: string }>/** Runtime broker id. Never offer this as a second Provider row in operator pickers. */export const OPENAI_SUBSCRIPTION_PROVIDER = 'codex-subscription' as const+export const GROK_SUBSCRIPTION_PROVIDER = 'grok-subscription' as constexport function isOpenAiFamily(provider: string | undefined | null): boolean {return provider === 'openai' || provider === OPENAI_SUBSCRIPTION_PROVIDER}+export function isOauthBrokerProvider(provider: string | undefined | null): boolean {+ return provider === OPENAI_SUBSCRIPTION_PROVIDER || provider === GROK_SUBSCRIPTION_PROVIDER+}+/** Provider dropdown: one OpenAI entry. Runtime still persists `codex-subscription`. */export const OPERATOR_PROVIDER_OPTIONS: Array<{ value: LlmProvider; label: string }> =LLM_PROVIDER_OPTIONS.filter(option => option.value !== OPENAI_SUBSCRIPTION_PROVIDER)+/** Hide Grok until Control API proves the flag is on. */+export function operatorProviderOptions(opts?: {+ grokEnabled?: boolean+}): Array<{ value: LlmProvider; label: string }> {+ return OPERATOR_PROVIDER_OPTIONS.filter(+ option => option.value !== GROK_SUBSCRIPTION_PROVIDER || opts?.grokEnabled === true+ )+}+export function catalogGroupKey(provider: string): string {return provider === OPENAI_SUBSCRIPTION_PROVIDER ? 'openai' : provider}@@ -288,18 +302,31 @@ export function brokerBackedRecipeAuthoringError(return null}const model = typeof record.model === 'string' ? record.model.trim() : ''- if (!model) return 'Codex subscription requires an explicit catalog model.'+ const grok = provider === GROK_SUBSCRIPTION_PROVIDER+ if (!model) {+ return grok+ ? 'Grok subscription requires an explicit catalog model.'+ : 'Codex subscription requires an explicit catalog model.'+ }if (record.secretRef != null) {- return 'Codex subscription recipes must not declare an LLM secretRef.'+ return grok+ ? 'Grok subscription recipes must not declare an LLM secretRef.'+ : 'Codex subscription recipes must not declare an LLM secretRef.'}const budget = spec.budgetif (budget && typeof budget === 'object' && !Array.isArray(budget)) {const unit = (budget as Record<string, unknown>).unit- if (unit === 'cost') return 'Codex subscription budgets must use unit tokens, not cost.'+ if (unit === 'cost') {+ return grok+ ? 'Grok subscription budgets must use unit tokens, not cost.'+ : 'Codex subscription budgets must use unit tokens, not cost.'+ }}const grant = typeof connectionRef === 'string' ? connectionRef.trim() : ''if (!grant || grant === CODEX_UNASSIGNED_CONNECTION_KEY) {- return 'Codex subscription recipes must choose an existing ChatGPT grant.'+ return grok+ ? 'Grok subscription recipes must choose an existing Grok grant.'+ : 'Codex subscription recipes must choose an existing ChatGPT grant.'}return null}diff --git a/control-ui/lib/llmCredentialSelect.ts b/control-ui/lib/llmCredentialSelect.tsindex 19e19bae3..c5ee84766 100644--- a/control-ui/lib/llmCredentialSelect.ts+++ b/control-ui/lib/llmCredentialSelect.ts@@ -5,12 +5,20 @@ export const SUBSCRIPTION_CREDENTIAL_PREFIX = 'sub:'export type ParsedCredentialSelect =| { kind: 'empty' }| { kind: 'secret'; name: string }- | { kind: 'subscription'; connectionKey: string }+ | {+ kind: 'subscription'+ provider: 'codex-subscription' | 'grok-subscription'+ connectionKey: string+ }-export function credentialSelectValue(secretRef: string, connectionRef: string): string {+export function credentialSelectValue(+ secretRef: string,+ connectionRef: string,+ provider: 'codex-subscription' | 'grok-subscription' = 'codex-subscription'+): string {const key = connectionRef.trim()if (key && key !== CODEX_UNASSIGNED_CONNECTION_KEY) {- return `${SUBSCRIPTION_CREDENTIAL_PREFIX}${key}`+ return `${SUBSCRIPTION_CREDENTIAL_PREFIX}${provider}:${key}`}return secretRef.trim()}@@ -19,11 +27,27 @@ export function parseCredentialSelect(value: string): ParsedCredentialSelect {const trimmed = value.trim()if (!trimmed) return { kind: 'empty' }if (trimmed.startsWith(SUBSCRIPTION_CREDENTIAL_PREFIX)) {- const connectionKey = trimmed.slice(SUBSCRIPTION_CREDENTIAL_PREFIX.length).trim()- if (!connectionKey || connectionKey === CODEX_UNASSIGNED_CONNECTION_KEY) {+ const rest = trimmed.slice(SUBSCRIPTION_CREDENTIAL_PREFIX.length).trim()+ if (!rest || rest === CODEX_UNASSIGNED_CONNECTION_KEY) {return { kind: 'empty' }}- return { kind: 'subscription', connectionKey }+ const grokPrefix = 'grok-subscription:'+ const codexPrefix = 'codex-subscription:'+ if (rest.startsWith(grokPrefix)) {+ const connectionKey = rest.slice(grokPrefix.length).trim()+ if (!connectionKey || connectionKey === CODEX_UNASSIGNED_CONNECTION_KEY) {+ return { kind: 'empty' }+ }+ return { kind: 'subscription', provider: 'grok-subscription', connectionKey }+ }+ if (rest.startsWith(codexPrefix)) {+ const connectionKey = rest.slice(codexPrefix.length).trim()+ if (!connectionKey || connectionKey === CODEX_UNASSIGNED_CONNECTION_KEY) {+ return { kind: 'empty' }+ }+ return { kind: 'subscription', provider: 'codex-subscription', connectionKey }+ }+ return { kind: 'subscription', provider: 'codex-subscription', connectionKey: rest }}return { kind: 'secret', name: trimmed }}diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 6e19a7ac7..03eccd756 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.576",+ "version": "0.1.577","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.576",+ "version": "0.1.577","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.jsonindex 3d70dd5e1..3028160ce 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.576",+ "version": "0.1.577","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/desktop-app/ui/src/components/agents/ModelSelector.tsx b/desktop-app/ui/src/components/agents/ModelSelector.tsxindex 28e23585b..397ee290d 100644--- a/desktop-app/ui/src/components/agents/ModelSelector.tsx+++ b/desktop-app/ui/src/components/agents/ModelSelector.tsx@@ -21,11 +21,10 @@ export interface ModelSelectorProps {const APPLIED_BADGE_MS = 4000/** Broker-backed hosts have no static default; the operator must name a model. */-const CODEX_SUBSCRIPTION_PROVIDER = 'codex-subscription'const SELECT_MODEL_LABEL = 'Select model'function isBrokerBackedProvider(provider: string): boolean {- return provider === CODEX_SUBSCRIPTION_PROVIDER+ return provider === 'codex-subscription' || provider === 'grok-subscription'}function isOfferedForNewPick(option: HostModelOption, sessionModel: string | null): boolean {diff --git a/desktop-app/ui/src/components/agents/__tests__/ModelSelector.test.tsx b/desktop-app/ui/src/components/agents/__tests__/ModelSelector.test.tsxindex 38af98e52..0e3eaca49 100644--- a/desktop-app/ui/src/components/agents/__tests__/ModelSelector.test.tsx+++ b/desktop-app/ui/src/components/agents/__tests__/ModelSelector.test.tsx@@ -136,6 +136,23 @@ describe('ModelSelector', () => {expect(root?.classList.contains('model-selector--up')).toBe(true)})+ it('does not invent a Grok default when the session has no selected model', () => {+ setHook({+ data: baseData({+ provider: 'grok-subscription',+ hostDefault: '',+ sessionModel: null,+ models: [+ { name: 'grok-4.6', displayName: 'Grok 4.6' },+ { name: 'grok-4.5', displayName: 'Grok 4.5' },+ ],+ }),+ })+ renderSelector()+ expect(screen.getByRole('button', { name: /Model — Select model/ })).toBeTruthy()+ expect(screen.queryByRole('button', { name: /Grok 4\.6/ })).toBeNull()+ })+it('does not invent a Codex default when the session has no selected model', () => {setHook({data: baseData({