Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-ui): gate Grok in catalog forms and honor device poll intervals
Jose Gabriel Ramirez Encinas7628eafc1326
diff --git a/control-ui/components/CodexSubscriptionHub/index.tsx b/control-ui/components/CodexSubscriptionHub/index.tsxindex 49cbda9e3..f3d6ef2e0 100644--- a/control-ui/components/CodexSubscriptionHub/index.tsx+++ b/control-ui/components/CodexSubscriptionHub/index.tsx@@ -102,6 +102,20 @@ function asHubRow(return { ...row, broker }}+// RFC 8628 §3.5 device polling for both brokers: honor the interval the server+// returns and add 5 seconds on slow_down. Never poll faster than already agreed.+const DEVICE_SLOW_DOWN_BACKOFF_SECONDS = 5++function nextDevicePollIntervalSeconds(+ currentSeconds: number,+ polled: { status: 'pending' | 'slow_down'; intervalSeconds: number }+): number {+ const next = Math.max(currentSeconds, polled.intervalSeconds)+ return polled.status === 'slow_down'+ ? Math.max(next, currentSeconds + DEVICE_SLOW_DOWN_BACKOFF_SECONDS)+ : next+}+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.'@@ -469,8 +483,9 @@ export function CodexSubscriptionHub() {setUserCode(started.userCode)setVerificationUri(started.verificationUri)const deadline = Date.now() + started.intervalSeconds * 1000 * 40+ let pollIntervalSeconds = started.intervalSecondswhile (Date.now() < deadline) {- await new Promise(resolve => setTimeout(resolve, started.intervalSeconds * 1000))+ await new Promise(resolve => setTimeout(resolve, pollIntervalSeconds * 1000))if (epoch !== connectEpoch.current) returnconst polled = grok? await pollGrokDevice(started.state, row.connectionKey)@@ -506,6 +521,9 @@ export function CodexSubscriptionHub() {setError(`${brand} sign-in ${polled.status}. Try again.`)return}+ if ('intervalSeconds' in polled) {+ pollIntervalSeconds = nextDevicePollIntervalSeconds(pollIntervalSeconds, polled)+ }}if (epoch !== connectEpoch.current) returnsetUserCode(null)diff --git a/control-ui/components/LlmModelForm/index.tsx b/control-ui/components/LlmModelForm/index.tsxindex b5d742780..ce9e93cd1 100644--- a/control-ui/components/LlmModelForm/index.tsx+++ b/control-ui/components/LlmModelForm/index.tsx@@ -1,13 +1,15 @@'use client'-import React, { useState } from 'react'+import React, { useMemo, useState } from 'react'import { Button, CheckboxField, Field, FormSection, SelectInput, TextInput } from '@components/ui'import type { CreateLlmModelInput } from '@lib/api'+import { useGrokSubscriptionEnabled } from '@lib/hooks/useGrokSubscriptionEnabled'import {GROK_SUBSCRIPTION_PROVIDER,LLM_PROVIDER_OPTIONS,isKnownProvider,isOauthBrokerProvider,+ runtimeProviderOptions,} from '@lib/llm'import type { LlmModelFormProps } from './types'@@ -44,6 +46,12 @@ export function LlmModelForm({)const [enabled, setEnabled] = useState(initial?.enabled ?? true)const [showErrors, setShowErrors] = useState(false)+ const grokEnabled = useGrokSubscriptionEnabled()+ const savedProvider = initial?.provider ?? prefill?.provider+ const providerOptions = useMemo(+ () => runtimeProviderOptions({ grokEnabled, saved: [savedProvider] }),+ [grokEnabled, savedProvider]+ )const providerIsKnown = isKnownProvider(provider)// Subscription (oauth-broker) models are enabled by their grant catalog sync,@@ -87,7 +95,7 @@ export function LlmModelForm({onChange={event => setProvider(event.target.value)}disabled={saving}>- {LLM_PROVIDER_OPTIONS.map(option => (+ {providerOptions.map(option => (<option key={option.value} value={option.value}>{option.label}</option>diff --git a/control-ui/components/LlmPriceForm/index.tsx b/control-ui/components/LlmPriceForm/index.tsxindex 7f7b60a7f..3e5e2d3ee 100644--- a/control-ui/components/LlmPriceForm/index.tsx+++ b/control-ui/components/LlmPriceForm/index.tsx@@ -5,8 +5,14 @@ import Link from 'next/link'import { Button, CheckboxField, Field, FormSection, SelectInput, TextInput } from '@components/ui'import { CONTROL_ROUTES } from '@constants/routes'import type { CreateLlmPriceInput, LlmModelPrice } from '@lib/api'+import { useGrokSubscriptionEnabled } from '@lib/hooks/useGrokSubscriptionEnabled'import { useLlmAllowedModels } from '@lib/hooks/useLlmAllowedModels'-import { LLM_PROVIDER_OPTIONS, getModelOptions, isKnownProvider } from '@lib/llm'+import {+ LLM_PROVIDER_OPTIONS,+ getModelOptions,+ isKnownProvider,+ runtimeProviderOptions,+} from '@lib/llm'import { DEFAULT_CURRENCY, PRICE_FIELDS } from './constants'import type { LlmPriceFormProps, PriceFieldKey } from './types'@@ -58,6 +64,14 @@ export function LlmPriceForm({const modelSuggestions = getModelOptions(allowedModels, provider, { includeDisabled: true })// Preserve an unrecognized provider as a selectable option instead of dropping it.const providerIsKnown = isKnownProvider(provider)+ // Grok stays hidden until the capability probe proves the flag on; a saved+ // Grok row keeps its provider visible as "(disabled)".+ const grokEnabled = useGrokSubscriptionEnabled()+ const savedProvider = initial?.provider ?? prefill?.provider+ const providerOptions = useMemo(+ () => runtimeProviderOptions({ grokEnabled, saved: [savedProvider] }),+ [grokEnabled, savedProvider]+ )const priceErrors = useMemo(() => {const errors: Partial<Record<PriceFieldKey, string>> = {}@@ -107,7 +121,7 @@ export function LlmPriceForm({onChange={event => setProvider(event.target.value)}disabled={saving}>- {LLM_PROVIDER_OPTIONS.map(option => (+ {providerOptions.map(option => (<option key={option.value} value={option.value}>{option.label}</option>diff --git a/control-ui/components/TokenBudgetForm/index.tsx b/control-ui/components/TokenBudgetForm/index.tsxindex 3636e8117..3ede0ff66 100644--- a/control-ui/components/TokenBudgetForm/index.tsx+++ b/control-ui/components/TokenBudgetForm/index.tsx@@ -13,8 +13,9 @@ import {getLlmPrices,getRecipeSecrets,} from '@lib/api'+import { useGrokSubscriptionEnabled } from '@lib/hooks/useGrokSubscriptionEnabled'import { useLlmAllowedModels } from '@lib/hooks/useLlmAllowedModels'-import { LLM_PROVIDER_OPTIONS, budgetUnitAllowedForProviders, getAllModelOptions } from '@lib/llm'+import { budgetUnitAllowedForProviders, getAllModelOptions, runtimeProviderOptions } from '@lib/llm'import { ScopeSelector } from './ScopeSelector'import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE } from './constants'import type { ScopeDimensionConfig, ScopeOption, TokenBudgetFormProps } from './types'@@ -28,11 +29,6 @@ function parseNumber(raw: string): number | null {return Number.isFinite(n) ? n : null}-const PROVIDER_OPTIONS: ScopeOption[] = LLM_PROVIDER_OPTIONS.map(o => ({- value: o.value,- label: o.label,-}))-export function TokenBudgetForm({mode,initial,@@ -62,6 +58,15 @@ export function TokenBudgetForm({const [scope, setScope] = useState<Record<string, string[]>>(initial?.scope ?? {})const [showErrors, setShowErrors] = useState(false)+ // Grok stays out of the provider scope until the capability probe proves the+ // flag on; a saved Grok scope value keeps a "(disabled)" label.+ const grokEnabled = useGrokSubscriptionEnabled()+ const savedProviders = initial?.scope?.provider+ const providerOptions = useMemo<ScopeOption[]>(+ () => runtimeProviderOptions({ grokEnabled, saved: savedProviders }),+ [grokEnabled, savedProviders]+ )+// Dimension option sources (best-effort; a failed fetch just leaves a// dimension with no select options — the budget can still be saved).const [teamOptions, setTeamOptions] = useState<ScopeOption[]>([])@@ -134,7 +139,7 @@ export function TokenBudgetForm({const dimensions: ScopeDimensionConfig[] = useMemo(() => [- { key: 'provider', label: 'Provider', options: PROVIDER_OPTIONS },+ { key: 'provider', label: 'Provider', options: providerOptions },{key: 'model',label: 'Model',@@ -148,7 +153,7 @@ export function TokenBudgetForm({{ key: 'host_ref', label: 'Agent', options: hostOptions },{ key: 'llm_secret_name', label: 'Secret', options: secretOptions },],- [teamOptions, userOptions, hostOptions, secretOptions, modelSuggestions]+ [providerOptions, teamOptions, userOptions, hostOptions, secretOptions, modelSuggestions])// Labels for already-selected team/user values so edited budgets show names.diff --git a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsxindex 1669c90ff..dd2b82df9 100644--- a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx+++ b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx@@ -99,6 +99,13 @@ function connection(}}+// Advance only the (faked) poll-loop setTimeout clock and flush the awaited+// poll/start promises so the next loop timer is registered.+async function advanceDevicePoll(ms: number) {+ await vi.advanceTimersByTimeAsync(ms)+ await vi.advanceTimersByTimeAsync(0)+}+describe('CodexSubscriptionHub', () => {beforeEach(() => {confirmMock.mockReset()@@ -405,6 +412,54 @@ describe('CodexSubscriptionHub', () => {expect(revokeCodexSubscription).toHaveBeenCalledWith('codex-aaa')})})++ // B-L7: the device poll loop must follow polled.intervalSeconds and back off+ // on slow_down (RFC 8628 §3.5: +5s), not re-use the start interval forever.+ it('backs off by 5s on a Codex slow_down before the next device poll', async () => {+ vi.stubGlobal(+ 'open',+ vi.fn(() => ({}))+ )+ vi.mocked(startCodexDeviceConnect).mockResolvedValue({+ userCode: 'ABCD-1234',+ verificationUri: CODEX_DEVICE_VERIFICATION_URI,+ intervalSeconds: 5,+ state: 'state-1',+ intent: 'reconnect',+ })+ vi.mocked(pollCodexDevice)+ .mockResolvedValueOnce({ status: 'slow_down', intervalSeconds: 5, state: 'state-1' })+ .mockResolvedValue({ status: 'pending', intervalSeconds: 5, state: 'state-1' })+ render(+ <ToastProvider>+ <CodexSubscriptionHub />+ </ToastProvider>+ )+ fireEvent.click(+ await screen.findByRole('button', { name: 'Actions for ChatGPT subscription Team A' })+ )+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Update' }))+ const signIn = await screen.findByRole('button', { name: 'Sign in with ChatGPT' })+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ try {+ fireEvent.click(signIn)+ // RTL findBy* drains via setTimeout(0), which is faked here — flush manually.+ await advanceDevicePoll(0)+ expect(screen.getByTestId('codex-device-code')).toHaveTextContent('ABCD-1234')+ await advanceDevicePoll(4_900)+ expect(pollCodexDevice).not.toHaveBeenCalled()+ await advanceDevicePoll(100)+ expect(pollCodexDevice).toHaveBeenCalledTimes(1)+ // slow_down with the same interval: 5s + 5s back-off, never the start 5s.+ await advanceDevicePoll(9_900)+ expect(pollCodexDevice).toHaveBeenCalledTimes(1)+ await advanceDevicePoll(100)+ expect(pollCodexDevice).toHaveBeenCalledTimes(2)+ expect(pollCodexDevice).toHaveBeenLastCalledWith('state-1', 'codex-aaa')+ } finally {+ vi.useRealTimers()+ }+ })})describe('CodexSubscriptionHub with Grok enabled', () => {@@ -717,4 +772,52 @@ describe('CodexSubscriptionHub with Grok enabled', () => {'Open the Grok verification page')})++ it('follows the polled Grok interval and backs off on slow_down between device polls', 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: 5,+ state: 'grok-state',+ intent: 'reconnect',+ })+ vi.mocked(pollGrokDevice)+ .mockResolvedValueOnce({ status: 'pending', intervalSeconds: 12, state: 'grok-state' })+ .mockResolvedValueOnce({ status: 'slow_down', intervalSeconds: 12, state: 'grok-state' })+ .mockResolvedValue({ status: 'pending', intervalSeconds: 12, state: 'grok-state' })+ renderHub()+ fireEvent.click(+ await screen.findByRole('button', { name: 'Actions for Grok subscription Team Grok' })+ )+ fireEvent.click(screen.getByRole('menuitem', { name: 'Update' }))+ const signIn = await screen.findByRole('button', { name: 'Sign in with Grok' })+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ try {+ fireEvent.click(signIn)+ // RTL findBy* drains via setTimeout(0), which is faked here — flush manually.+ await advanceDevicePoll(0)+ expect(screen.getByTestId('codex-device-code')).toHaveTextContent('GROK-1234')+ await advanceDevicePoll(5_000)+ expect(pollGrokDevice).toHaveBeenCalledTimes(1)+ // pending carried intervalSeconds 12: wait 12s, not the start 5s.+ await advanceDevicePoll(11_900)+ expect(pollGrokDevice).toHaveBeenCalledTimes(1)+ await advanceDevicePoll(100)+ expect(pollGrokDevice).toHaveBeenCalledTimes(2)+ // slow_down: 12s + 5s back-off.+ await advanceDevicePoll(16_900)+ expect(pollGrokDevice).toHaveBeenCalledTimes(2)+ await advanceDevicePoll(100)+ expect(pollGrokDevice).toHaveBeenCalledTimes(3)+ expect(pollGrokDevice).toHaveBeenLastCalledWith('grok-state', 'grok-aaa')+ expect(pollCodexDevice).not.toHaveBeenCalled()+ } finally {+ vi.useRealTimers()+ }+ })})diff --git a/control-ui/components/__tests__/LlmCatalogFormsGrokGate.test.tsx b/control-ui/components/__tests__/LlmCatalogFormsGrokGate.test.tsxnew file mode 100644index 000000000..cff66ffd4--- /dev/null+++ b/control-ui/components/__tests__/LlmCatalogFormsGrokGate.test.tsx@@ -0,0 +1,225 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { cleanup, render, screen, waitFor, within } from '@testing-library/react'+import type { LlmAllowedModel, LlmModelPrice, TokenBudget } from '@lib/api'+import { loadGrokSubscriptionCapability } from '@lib/grokSubscriptionFeature'+import { LlmModelForm } from '../LlmModelForm'+import { LlmPriceForm } from '../LlmPriceForm'+import { TokenBudgetForm } from '../TokenBudgetForm'++// B-M7: the allowlist, price and budget forms list every runtime provider id.+// grok-subscription must stay hidden until the Control API Grok capability+// probe proves the flag on, while a saved Grok value stays visible "(disabled)".++vi.mock('@lib/grokSubscriptionFeature', async importOriginal => {+ const actual = await importOriginal<typeof import('@lib/grokSubscriptionFeature')>()+ return { ...actual, loadGrokSubscriptionCapability: vi.fn() }+})++vi.mock('@lib/hooks/useLlmAllowedModels', () => ({+ useLlmAllowedModels: () => ({ models: [], loading: false, error: '' }),+}))++vi.mock('@lib/api', async importOriginal => {+ const actual = await importOriginal<typeof import('@lib/api')>()+ return {+ ...actual,+ getAdminTeams: vi.fn().mockResolvedValue({ items: [] }),+ getAdminUsers: vi.fn().mockResolvedValue({ items: [] }),+ getHosts: vi.fn().mockResolvedValue({ items: [] }),+ getRecipeSecrets: vi.fn().mockResolvedValue({ items: [] }),+ getLlmPrices: vi.fn().mockResolvedValue({ rows: [] }),+ }+})++const GROK = 'grok-subscription'+const CODEX = 'codex-subscription'+const noop = () => undefined++const grokModel = {+ id: 'model-grok',+ provider: GROK,+ model: 'grok-4.6',+ vendor: 'xAI',+ display_name: null,+ context_window_tokens: null,+ enabled: true,+ source: 'discovery',+ stale: false,+ discovered_at: null,+ last_seen_at: null,+ created_at: '2026-01-01T00:00:00.000Z',+ updated_at: '2026-01-01T00:00:00.000Z',+} as LlmAllowedModel++const grokPrice = {+ id: 'price-grok',+ provider: GROK,+ model: 'grok-4.6',+ input_token_price: 0,+ output_token_price: 0,+ cache_read_token_price: 0,+ cache_write_token_price: 0,+ currency: 'USD',+ enabled: true,+} as unknown as LlmModelPrice++const grokBudget = {+ id: 'budget-grok',+ name: 'Grok cap',+ enabled: true,+ scope: { provider: [GROK] },+ unit: 'tokens',+ currency: null,+ limit_amount: 1000,+ period: 'monthly',+ timezone: 'UTC',+ min_start_amount: 0,+ max_task_amount: null,+ enforcement: 'warn',+} as unknown as TokenBudget++function optionValues(select: HTMLElement): string[] {+ return within(select)+ .getAllByRole('option')+ .map(option => (option as HTMLOptionElement).value)+}++function flushProbe() {+ return waitFor(() => expect(loadGrokSubscriptionCapability).toHaveBeenCalled())+}++type SelectForm = {+ name: string+ selectId: string+ renderCreate: () => void+ renderSavedGrok: () => void+}++const selectForms: SelectForm[] = [+ {+ name: 'LlmModelForm',+ selectId: 'llm-model-provider',+ renderCreate: () =>+ render(<LlmModelForm mode="create" saving={false} onSubmit={noop} onCancel={noop} />),+ renderSavedGrok: () =>+ render(+ <LlmModelForm+ mode="edit"+ initial={grokModel}+ saving={false}+ onSubmit={noop}+ onCancel={noop}+ />+ ),+ },+ {+ name: 'LlmPriceForm',+ selectId: 'llm-price-provider',+ renderCreate: () =>+ render(<LlmPriceForm mode="create" saving={false} onSubmit={noop} onCancel={noop} />),+ renderSavedGrok: () =>+ render(+ <LlmPriceForm+ mode="edit"+ initial={grokPrice}+ saving={false}+ onSubmit={noop}+ onCancel={noop}+ />+ ),+ },+]++beforeEach(() => {+ vi.mocked(loadGrokSubscriptionCapability).mockResolvedValue({ enabled: false })+})++afterEach(() => {+ cleanup()+ vi.mocked(loadGrokSubscriptionCapability).mockReset()+})++describe.each(selectForms)('$name Grok capability gate', form => {+ function providerSelect(): HTMLSelectElement {+ return document.getElementById(form.selectId) as HTMLSelectElement+ }++ it('hides grok-subscription when the probe reports disabled and keeps Codex', async () => {+ form.renderCreate()+ await flushProbe()+ await Promise.resolve()+ const values = optionValues(providerSelect())+ expect(values).not.toContain(GROK)+ expect(values).toContain(CODEX)+ expect(values).toContain('openai')+ })++ it('fails closed (no Grok option) when the probe throws', async () => {+ vi.mocked(loadGrokSubscriptionCapability).mockRejectedValue(new Error('probe boom'))+ form.renderCreate()+ await flushProbe()+ await Promise.resolve()+ expect(optionValues(providerSelect())).not.toContain(GROK)+ })++ it('offers grok-subscription once the probe reports enabled', async () => {+ vi.mocked(loadGrokSubscriptionCapability).mockResolvedValue({ enabled: true })+ form.renderCreate()+ await waitFor(() => expect(optionValues(providerSelect())).toContain(GROK))+ const grokOption = within(providerSelect())+ .getAllByRole('option')+ .find(option => (option as HTMLOptionElement).value === GROK)+ expect(grokOption?.textContent).not.toMatch(/disabled|unrecognized/)+ })++ it('keeps a saved Grok provider selected and labelled "(disabled)" while the flag is off', async () => {+ form.renderSavedGrok()+ await flushProbe()+ await Promise.resolve()+ const select = providerSelect()+ expect(select.value).toBe(GROK)+ const grokOptions = within(select)+ .getAllByRole('option')+ .filter(option => (option as HTMLOptionElement).value === GROK)+ expect(grokOptions).toHaveLength(1)+ expect(grokOptions[0]).toHaveTextContent(/\(disabled\)$/)+ expect(select).not.toHaveTextContent(/unrecognized/)+ })+})++describe('TokenBudgetForm Grok capability gate', () => {+ function addProviderSelect(): HTMLElement {+ return screen.getByRole('combobox', { name: 'Add Provider to scope' })+ }++ it('hides grok-subscription from the provider scope when the probe reports disabled', async () => {+ render(<TokenBudgetForm mode="create" saving={false} onSubmit={noop} onCancel={noop} />)+ await flushProbe()+ await Promise.resolve()+ const values = optionValues(addProviderSelect())+ expect(values).not.toContain(GROK)+ expect(values).toContain(CODEX)+ })++ it('offers grok-subscription in the provider scope once the probe reports enabled', async () => {+ vi.mocked(loadGrokSubscriptionCapability).mockResolvedValue({ enabled: true })+ render(<TokenBudgetForm mode="create" saving={false} onSubmit={noop} onCancel={noop} />)+ await waitFor(() => expect(optionValues(addProviderSelect())).toContain(GROK))+ })++ it('shows a saved Grok scope value as "(disabled)" while the flag is off', async () => {+ render(+ <TokenBudgetForm+ mode="edit"+ initial={grokBudget}+ saving={false}+ onSubmit={noop}+ onCancel={noop}+ />+ )+ await flushProbe()+ await Promise.resolve()+ expect(screen.getByText('xAI Grok Subscription (disabled)')).toBeInTheDocument()+ expect(optionValues(addProviderSelect())).not.toContain(GROK)+ })+})diff --git a/control-ui/lib/hooks/__tests__/useGrokSubscriptionEnabled.test.tsx b/control-ui/lib/hooks/__tests__/useGrokSubscriptionEnabled.test.tsxnew file mode 100644index 000000000..12786a6c3--- /dev/null+++ b/control-ui/lib/hooks/__tests__/useGrokSubscriptionEnabled.test.tsx@@ -0,0 +1,50 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { cleanup, render, screen, waitFor } from '@testing-library/react'+import { loadGrokSubscriptionCapability } from '@lib/grokSubscriptionFeature'+import { useGrokSubscriptionEnabled } from '../useGrokSubscriptionEnabled'++vi.mock('@lib/grokSubscriptionFeature', async importOriginal => {+ const actual = await importOriginal<typeof import('@lib/grokSubscriptionFeature')>()+ return { ...actual, loadGrokSubscriptionCapability: vi.fn() }+})++function Probe() {+ return <span data-testid="grok">{String(useGrokSubscriptionEnabled())}</span>+}++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+})++describe('useGrokSubscriptionEnabled', () => {+ it('starts hidden and turns on only after the capability probe reports enabled', async () => {+ let resolve!: (value: { enabled: boolean }) => void+ vi.mocked(loadGrokSubscriptionCapability).mockReturnValue(+ new Promise(res => {+ resolve = res+ })+ )+ render(<Probe />)+ expect(screen.getByTestId('grok')).toHaveTextContent('false')+ resolve({ enabled: true })+ await waitFor(() => expect(screen.getByTestId('grok')).toHaveTextContent('true'))+ expect(loadGrokSubscriptionCapability).toHaveBeenCalledTimes(1)+ })++ it('stays hidden when the probe reports the flag off', async () => {+ vi.mocked(loadGrokSubscriptionCapability).mockResolvedValue({ enabled: false })+ render(<Probe />)+ await waitFor(() => expect(loadGrokSubscriptionCapability).toHaveBeenCalled())+ await Promise.resolve()+ expect(screen.getByTestId('grok')).toHaveTextContent('false')+ })++ it('fails closed when the probe throws a non-disabled error', async () => {+ vi.mocked(loadGrokSubscriptionCapability).mockRejectedValue(new Error('probe boom'))+ render(<Probe />)+ await waitFor(() => expect(loadGrokSubscriptionCapability).toHaveBeenCalled())+ await Promise.resolve()+ expect(screen.getByTestId('grok')).toHaveTextContent('false')+ })+})diff --git a/control-ui/lib/hooks/useGrokSubscriptionEnabled.ts b/control-ui/lib/hooks/useGrokSubscriptionEnabled.tsnew file mode 100644index 000000000..229e8bad7--- /dev/null+++ b/control-ui/lib/hooks/useGrokSubscriptionEnabled.ts@@ -0,0 +1,34 @@+'use client'++import { useEffect, useState } from 'react'+import {+ isGrokSubscriptionUiEnabled,+ loadGrokSubscriptionCapability,+} from '@lib/grokSubscriptionFeature'++/**+ * True only once the Control API Grok capability probe proves the flag on.+ * Starts false and fails closed: a probe error keeps Grok out of operator+ * pickers exactly like the flag being off (a saved Grok value is still shown by+ * the caller, marked "(disabled)").+ */+export function useGrokSubscriptionEnabled(): boolean {+ const [enabled, setEnabled] = useState(false)++ useEffect(() => {+ let cancelled = false+ loadGrokSubscriptionCapability().then(+ capability => {+ if (!cancelled) setEnabled(isGrokSubscriptionUiEnabled(capability))+ },+ () => {+ if (!cancelled) setEnabled(false)+ }+ )+ return () => {+ cancelled = true+ }+ }, [])++ return enabled+}diff --git a/control-ui/lib/llm.ts b/control-ui/lib/llm.tsindex 76dc723c4..8350937aa 100644--- a/control-ui/lib/llm.ts+++ b/control-ui/lib/llm.ts@@ -78,6 +78,27 @@ export function operatorProviderOptions(opts?: {)}+/**+ * Runtime provider picker for the allowlist, price and budget tables: every+ * provider id (incl. codex-subscription), with Grok hidden until Control API+ * proves the flag on. A saved known provider the picker no longer offers stays+ * available, labelled "(disabled)", so editing never silently drops it.+ */+export function runtimeProviderOptions(opts?: {+ grokEnabled?: boolean+ saved?: ReadonlyArray<string | null | undefined>+}): Array<{ value: LlmProvider; label: string }> {+ const options = LLM_PROVIDER_OPTIONS.filter(+ option => option.value !== GROK_SUBSCRIPTION_PROVIDER || opts?.grokEnabled === true+ )+ for (const value of opts?.saved ?? []) {+ if (!value || !isLlmProviderId(value)) continue+ if (options.some(option => option.value === value)) continue+ options.push({ value, label: `${PROVIDER_DISPLAY_LABELS[value]} (disabled)` })+ }+ return options+}+export function catalogGroupKey(provider: string): string {return provider === OPENAI_SUBSCRIPTION_PROVIDER ? 'openai' : provider}diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 5b9fba7e2..aa6fe2991 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.591",+ "version": "0.1.592","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.591",+ "version": "0.1.592","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 7920bbe71..a2f38f71b 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.591",+ "version": "0.1.592","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",