Skip to content

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

TypeScript

fix(control-ui): coordinate subscription reads and preserve agent state

Alfredo Lopez5e0105efe81b
diff --git a/control-ui/app/constants/readRequests.ts b/control-ui/app/constants/readRequests.ts
new file mode 100644
index 000000000..b65d87280
--- /dev/null
+++ b/control-ui/app/constants/readRequests.ts
@@ -0,0 +1,6 @@
+export const METADATA_READ_TTL_MS = 30_000
+export const METADATA_READ_CACHE_MAX_ENTRIES = 128
+export const METADATA_READ_MAX_RECOVERY_ATTEMPTS = 1
+// A server denial without valid timing still gets one bounded delayed read.
+export const METADATA_READ_UNTIMED_COOLDOWN_MS = 1_000
+export const CONTROL_UI_SESSION_INVALIDATION_EVENT = 'control-ui-session-invalidation'
diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsx
index 70bca45c8..11458b412 100644
--- a/control-ui/app/hosts/[name]/page.tsx
+++ b/control-ui/app/hosts/[name]/page.tsx
@@ -11,9 +11,11 @@ import {
import { useConfirmDialog } from '@components/ConfirmDialog'
import { DetailPageShell } from '@components/DetailPageShell'
import { SelectionDropdown } from '@components/SelectionDropdown'
+import { SubscriptionCapabilityNotice } from '@components/SubscriptionCapabilityNotice'
import { useToast } from '@components/Toast'
import { HOST_DEFAULT_TAB, HOST_TABS } from '@constants/hostDetails'
import { CONTROL_ROUTES } from '@constants/routes'
+import { useSubscriptionCapabilities } from '@lib/hooks/useSubscriptionCapabilities'
import { HostAccessTab } from '../../../components/HostAccessTab'
import { HostAdvancedTab } from '../../../components/HostAdvancedTab'
import type { HostGuardrails } from '../../../components/HostGuardrailsSection/types'
@@ -126,6 +128,12 @@ function agentConnectorMutationError(error: unknown): string {
return contextMutationError(error, 'Failed to update connectors for this agent.')
}
+function subscriptionInventoryMessage(error: unknown, brand: string): string {
+ return error instanceof Error && error.message
+ ? error.message
+ : `Could not load ${brand} subscriptions`
+}
+
function AgentActionsMenu({ busy, onDelete }: { busy: boolean; onDelete: () => void }) {
const [open, setOpen] = useState(false)
const ref = useRef<HTMLDivElement>(null)
@@ -202,6 +210,11 @@ export default function HostDetailsPage() {
const [initialLoading, setInitialLoading] = useState(true)
const [editingModel, setEditingModel] = useState(false)
+ const subscriptionCapabilities = useSubscriptionCapabilities({ enabled: editingModel })
+ const codexEnabled =
+ subscriptionCapabilities.capabilities?.providers['codex-subscription'].enabled ?? false
+ const grokEnabled =
+ subscriptionCapabilities.capabilities?.providers['grok-subscription'].enabled ?? false
const [llmSecretModalOpen, setLlmSecretModalOpen] = useState(false)
const [showDeleteAgentConfirm, setShowDeleteAgentConfirm] = useState(false)
const [deletingAgent, setDeletingAgent] = useState(false)
@@ -235,8 +248,12 @@ export default function HostDetailsPage() {
const [codexConnections, setCodexConnections] = useState<CodexSubscriptionConnectionView[]>([])
const [grokModels, setGrokModels] = useState<string[]>([])
const [grokConnections, setGrokConnections] = useState<GrokSubscriptionConnectionView[]>([])
- const [grokEnabled, setGrokEnabled] = useState(false)
+ const [codexInventoryLoaded, setCodexInventoryLoaded] = useState(false)
+ const [grokInventoryLoaded, setGrokInventoryLoaded] = useState(false)
const [grantCatalogError, setGrantCatalogError] = useState('')
+ const [subscriptionInventoryError, setSubscriptionInventoryError] = useState('')
+ const [subscriptionInventoryLoading, setSubscriptionInventoryLoading] = useState(false)
+ const [inventoryRetryNonce, setInventoryRetryNonce] = useState(0)
const catalogForEditor = useMemo(() => {
if (providerDraft === 'codex-subscription') {
const others = allowedCatalog.filter(row => row.provider !== 'codex-subscription')
@@ -392,86 +409,111 @@ export default function HostDetailsPage() {
])
useEffect(() => {
- let cancelled = false
- void listCodexSubscriptionConnections()
- .then(rows => {
- if (!cancelled) setCodexConnections(rows)
- })
- .catch(err => {
- if (!cancelled) {
- setCodexConnections([])
- if (!isDisabledCapabilityError(err)) {
- setError(err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions')
- }
+ if (!editingModel || !subscriptionCapabilities.capabilities) {
+ setSubscriptionInventoryError('')
+ setSubscriptionInventoryLoading(false)
+ return
+ }
+ const controller = new AbortController()
+ setSubscriptionInventoryLoading(true)
+ const requests = [
+ codexEnabled
+ ? listCodexSubscriptionConnections({
+ signal: controller.signal,
+ refresh: inventoryRetryNonce > 0,
+ })
+ : Promise.resolve([]),
+ ...(grokEnabled
+ ? [
+ listGrokSubscriptionConnections({
+ signal: controller.signal,
+ refresh: inventoryRetryNonce > 0,
+ }),
+ ]
+ : []),
+ ]
+ Promise.allSettled(requests)
+ .then(([codexResult, grokResult]) => {
+ if (controller.signal.aborted) return
+ if (codexResult.status === 'fulfilled') {
+ setCodexConnections(codexResult.value)
+ setCodexInventoryLoaded(codexEnabled)
}
- })
- void listGrokSubscriptionConnections()
- .then(rows => {
- if (!cancelled) {
- setGrokConnections(rows)
- setGrokEnabled(true)
+ if (grokResult?.status === 'fulfilled') {
+ setGrokConnections(grokResult.value)
+ setGrokInventoryLoaded(true)
}
+ setSubscriptionInventoryError('')
+ const failure = [codexResult, grokResult].find(
+ result => result?.status === 'rejected' && !isDisabledCapabilityError(result.reason)
+ )
+ if (failure?.status === 'rejected') throw failure.reason
})
.catch(err => {
- if (!cancelled) {
- setGrokConnections([])
- setGrokEnabled(false)
- if (!isDisabledCapabilityError(err)) {
- setError(err instanceof Error ? err.message : 'Could not load Grok subscriptions')
- }
- }
+ if (controller.signal.aborted || isDisabledCapabilityError(err)) return
+ setSubscriptionInventoryError(subscriptionInventoryMessage(err, 'subscription'))
})
- return () => {
- cancelled = true
- }
- }, [])
+ .finally(() => {
+ if (!controller.signal.aborted) setSubscriptionInventoryLoading(false)
+ })
+ return () => controller.abort()
+ }, [
+ codexEnabled,
+ editingModel,
+ grokEnabled,
+ inventoryRetryNonce,
+ subscriptionCapabilities.capabilities,
+ ])
useEffect(() => {
+ if (!editingModel) return
if (!connectionRefDraft.trim() || connectionRefDraft === CODEX_UNASSIGNED_CONNECTION_KEY) {
setCodexModels([])
setGrokModels([])
setGrantCatalogError('')
return
}
- let cancelled = false
+ const controller = new AbortController()
setGrantCatalogError('')
if (providerDraft === GROK_SUBSCRIPTION_PROVIDER) {
setCodexModels([])
- void listGrokConnectionModels(connectionRefDraft)
+ void listGrokConnectionModels(connectionRefDraft, {
+ signal: controller.signal,
+ refresh: inventoryRetryNonce > 0,
+ })
.then(models => {
- if (cancelled) return
+ if (controller.signal.aborted) return
setGrokModels(offeredCodexModelNames(models))
})
.catch(err => {
- if (cancelled) return
- setGrokModels([])
- setModelNameDraft('')
+ if (controller.signal.aborted) return
setGrantCatalogError(
err instanceof Error ? err.message : 'Could not load Grok grant models'
)
})
return () => {
- cancelled = true
+ controller.abort()
}
}
setGrokModels([])
- void listCodexConnectionModels(connectionRefDraft)
+ void listCodexConnectionModels(connectionRefDraft, {
+ signal: controller.signal,
+ refresh: inventoryRetryNonce > 0,
+ })
.then(models => {
- if (cancelled) return
+ if (controller.signal.aborted) return
setCodexModels(offeredCodexModelNames(models))
})
.catch(err => {
- if (cancelled) return
- setCodexModels([])
- setModelNameDraft('')
+ if (controller.signal.aborted) return
setGrantCatalogError(
err instanceof Error ? err.message : 'Could not load ChatGPT grant models'
)
})
return () => {
- cancelled = true
+ controller.abort()
}
- }, [connectionRefDraft, providerDraft])
+ }, [connectionRefDraft, editingModel, inventoryRetryNonce, providerDraft])
useEffect(() => {
setActiveTab(parseHostTab(params.tab))
@@ -784,7 +826,7 @@ export default function HostDetailsPage() {
options.push({
group: 'ChatGPT subscriptions',
value: credentialSelectValue('', connectionRefDraft),
- label: `${connectionRefDraft} (unavailable)`,
+ label: codexInventoryLoaded ? `${connectionRefDraft} (unavailable)` : connectionRefDraft,
meta: 'ChatGPT subscription',
providers: [{ id: 'codex-subscription', label: 'ChatGPT Subscription' }],
})
@@ -800,7 +842,7 @@ export default function HostDetailsPage() {
options.push({
group: 'Grok subscriptions',
value: credentialSelectValue('', connectionRefDraft, GROK_SUBSCRIPTION_PROVIDER),
- label: `${connectionRefDraft} (unavailable)`,
+ label: grokInventoryLoaded ? `${connectionRefDraft} (unavailable)` : connectionRefDraft,
meta: 'Grok subscription',
providers: [{ id: GROK_SUBSCRIPTION_PROVIDER, label: 'xAI Grok Subscription' }],
})
@@ -810,6 +852,8 @@ export default function HostDetailsPage() {
availableLlmSecrets,
codexConnections,
grokConnections,
+ codexInventoryLoaded,
+ grokInventoryLoaded,
connectionRefDraft,
currentSecretKeys,
providerDraft,
@@ -1457,6 +1501,24 @@ export default function HostDetailsPage() {
title="Edit model configuration"
>
<div className="cu-form-stack cu-form-stack--wide">
+ <SubscriptionCapabilityNotice state={subscriptionCapabilities} />
+ {subscriptionInventoryLoading ? (
+ <p className="cu-muted" role="status">
+ Loading subscription options…
+ </p>
+ ) : null}
+ {subscriptionInventoryError || grantCatalogError ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ <span>{subscriptionInventoryError || grantCatalogError}</span>
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost cu-btn--sm"
+ onClick={() => setInventoryRetryNonce(value => value + 1)}
+ >
+ Retry
+ </button>
+ </div>
+ ) : null}
<LlmProviderConfig
provider={providerDraft}
model={modelNameDraft}
diff --git a/control-ui/app/plugin-workload-sdk/page.tsx b/control-ui/app/plugin-workload-sdk/page.tsx
index 98f2191a5..f24699c22 100644
--- a/control-ui/app/plugin-workload-sdk/page.tsx
+++ b/control-ui/app/plugin-workload-sdk/page.tsx
@@ -6,6 +6,7 @@ import { DashboardLayout } from '@components/DashboardLayout'
import { SectionSearchInput } from '@components/SectionSearchInput'
import { SelectionDropdown } from '@components/SelectionDropdown'
import { IconPluginSdk } from '@components/Sidebar/icons'
+import { SubscriptionCapabilityNotice } from '@components/SubscriptionCapabilityNotice'
import { TablePanelHeader } from '@components/TablePanelHeader'
import { useToast } from '@components/Toast'
import { IconRefresh, IconX } from '@components/icons'
@@ -42,8 +43,8 @@ import {
listGrokConnectionModels,
listGrokSubscriptionConnections,
} from '@lib/grokSubscription'
-import { loadGrokSubscriptionCapability } from '@lib/grokSubscriptionFeature'
import { useLlmAllowedModels } from '@lib/hooks/useLlmAllowedModels'
+import { useSubscriptionCapabilities } from '@lib/hooks/useSubscriptionCapabilities'
import {
GROK_SUBSCRIPTION_PROVIDER,
LLM_PROVIDER_OPTIONS,
@@ -449,6 +450,9 @@ function GrantFormModal({
onSaved: () => void
}) {
const { showToast } = useToast()
+ const subscriptionCapabilities = useSubscriptionCapabilities()
+ const grokEnabled =
+ subscriptionCapabilities.capabilities?.providers['grok-subscription']?.enabled ?? false
const isEdit = grant !== null
const initialRecipeInfo = sdkRecipes.find(
recipe => recipe.namespace === grant?.recipeNamespace && recipe.name === grant?.recipeName
@@ -483,11 +487,13 @@ function GrantFormModal({
const isCodexProvider = modelProvider === OPENAI_SUBSCRIPTION_PROVIDER
const isGrokProvider = modelProvider === GROK_SUBSCRIPTION_PROVIDER
const isBrokerProvider = isCodexProvider || isGrokProvider
- const [grokEnabled, setGrokEnabled] = useState(false)
const [codexConnectionRef, setCodexConnectionRef] = useState('')
const [codexConnections, setCodexConnections] = useState<CodexSubscriptionConnectionView[]>([])
const [grokConnections, setGrokConnections] = useState<GrokSubscriptionConnectionView[]>([])
const [codexModels, setCodexModels] = useState<string[]>([])
+ const [grantInventoryError, setGrantInventoryError] = useState('')
+ const [grantInventoryLoading, setGrantInventoryLoading] = useState(false)
+ const [grantInventoryRetryNonce, setGrantInventoryRetryNonce] = useState(0)
const [allowedEventTypes, setAllowedEventTypes] = useState(
(grant?.allowedEventTypes ?? []).join(', ')
)
@@ -552,79 +558,74 @@ function GrantFormModal({
}, [])
useEffect(() => {
if (!isCodexProvider) return
- let cancelled = false
- listCodexSubscriptionConnections()
+ const controller = new AbortController()
+ setGrantInventoryLoading(true)
+ listCodexSubscriptionConnections({
+ signal: controller.signal,
+ refresh: grantInventoryRetryNonce > 0,
+ })
.then(connections => {
- if (cancelled) return
+ if (controller.signal.aborted) return
setCodexConnections(connections.filter(isAssignableCodexGrant))
+ setGrantInventoryError('')
})
.catch(err => {
- if (cancelled) return
- setCodexConnections([])
- if (!isDisabledCapabilityError(err)) {
- setError(err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions')
- }
- })
- return () => {
- cancelled = true
- }
- }, [isCodexProvider])
- useEffect(() => {
- let cancelled = false
- loadGrokSubscriptionCapability()
- .then(capability => {
- if (!cancelled) setGrokEnabled(capability.enabled)
+ if (controller.signal.aborted || isDisabledCapabilityError(err)) return
+ setGrantInventoryError(
+ err instanceof Error && err.message ? err.message : 'Could not load ChatGPT subscriptions'
+ )
})
- .catch(err => {
- if (cancelled) return
- // loadGrokSubscriptionCapability already maps "disabled" to
- // { enabled: false }; anything reaching here is a real probe failure
- // and must not be presented as the flag being off.
- setGrokEnabled(false)
- setError(err instanceof Error ? err.message : 'Could not load Grok subscriptions')
+ .finally(() => {
+ if (!controller.signal.aborted) setGrantInventoryLoading(false)
})
- return () => {
- cancelled = true
- }
- }, [])
+ return () => controller.abort()
+ }, [grantInventoryRetryNonce, isCodexProvider])
useEffect(() => {
if (!isGrokProvider) return
- let cancelled = false
- listGrokSubscriptionConnections()
+ const controller = new AbortController()
+ setGrantInventoryLoading(true)
+ listGrokSubscriptionConnections({
+ signal: controller.signal,
+ refresh: grantInventoryRetryNonce > 0,
+ })
.then(connections => {
- if (cancelled) return
+ if (controller.signal.aborted) return
setGrokConnections(connections.filter(isAssignableGrokGrant))
+ setGrantInventoryError('')
})
.catch(err => {
- if (cancelled) return
- setGrokConnections([])
- if (!isDisabledCapabilityError(err)) {
- setError(err instanceof Error ? err.message : 'Could not load Grok subscriptions')
- }
+ if (controller.signal.aborted || isDisabledCapabilityError(err)) return
+ setGrantInventoryError(
+ err instanceof Error && err.message ? err.message : 'Could not load Grok subscriptions'
+ )
})
- return () => {
- cancelled = true
- }
- }, [isGrokProvider])
+ .finally(() => {
+ if (!controller.signal.aborted) setGrantInventoryLoading(false)
+ })
+ return () => controller.abort()
+ }, [grantInventoryRetryNonce, isGrokProvider])
useEffect(() => {
if (!isBrokerProvider || !codexConnectionRef) {
setCodexModels([])
return
}
- let cancelled = false
+ const controller = new AbortController()
const loader = isGrokProvider ? listGrokConnectionModels : listCodexConnectionModels
- loader(codexConnectionRef)
+ loader(codexConnectionRef, { signal: controller.signal, refresh: grantInventoryRetryNonce > 0 })
.then(models => {
- if (cancelled) return
+ if (controller.signal.aborted) return
setCodexModels(models.filter(row => row.enabled && !row.stale).map(row => row.model))
})
- .catch(() => {
- if (!cancelled) setCodexModels([])
+ .catch(err => {
+ if (!controller.signal.aborted)
+ setGrantInventoryError(
+ err instanceof Error ? err.message : 'Could not load subscription models'
+ )
})
return () => {
- cancelled = true
+ controller.abort()
}
- }, [isBrokerProvider, isGrokProvider, codexConnectionRef])
+ }, [isBrokerProvider, isGrokProvider, codexConnectionRef, grantInventoryRetryNonce])
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState('')
@@ -854,6 +855,25 @@ function GrantFormModal({
</div>
<form onSubmit={handleSubmit}>
<div className="cu-modal-panel__body">
+ <SubscriptionCapabilityNotice state={subscriptionCapabilities} />
+ {grantInventoryLoading ? (
+ <p className="cu-muted" role="status">
+ Loading subscription options…
+ </p>
+ ) : null}
+ {grantInventoryError ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ <span>{grantInventoryError}</span>
+ <Button
+ type="button"
+ className="cu-btn--sm"
+ variant="ghost"
+ onClick={() => setGrantInventoryRetryNonce(value => value + 1)}
+ >
+ Retry
+ </Button>
+ </div>
+ ) : null}
{error ? <div className="cu-banner cu-banner--error">{error}</div> : null}
<FormSection title="Recipe binding">
diff --git a/control-ui/components/AuthContext.tsx b/control-ui/components/AuthContext.tsx
index 24322ad45..d03fc3817 100644
--- a/control-ui/components/AuthContext.tsx
+++ b/control-ui/components/AuthContext.tsx
@@ -10,13 +10,16 @@ import React, {
useState,
} from 'react'
import { useRouter } from 'next/navigation'
+import { CONTROL_UI_SESSION_INVALIDATION_EVENT } from '@constants/readRequests'
import { CONTROL_ROUTES } from '@constants/routes'
import {
type AdminLoginResponse,
+ clearAdminAuthToken,
getControlUIAuthMe,
isSilentApiError,
loginControlUI,
logoutControlUI,
+ setControlUIReadPrincipal,
setGlobalAuthErrorHandler,
} from '../lib/api'
import { buildControlUiLoginPath, getCurrentControlUiPath } from '../lib/authRedirect'
@@ -71,6 +74,12 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const checkAuth = useCallback(async () => {
try {
const response = await getControlUIAuthMe()
+ if (!response.me.id) {
+ clearAdminAuthToken()
+ setAuthState({ id: '', isLoggedIn: false, isLoading: false, username: '', email: '' })
+ return
+ }
+ setControlUIReadPrincipal(response.me.id, response.me.role || 'admin')
sessionExpiredToastShownRef.current = false
setAuthState(prev => ({
...prev,
@@ -86,17 +95,23 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
setAuthState({ id: '', isLoggedIn: false, isLoading: false, username: '', email: '' })
return
}
+ clearAdminAuthToken()
setAuthState({ id: '', isLoggedIn: false, isLoading: false, username: '', email: '' })
}
}, [])
useEffect(() => {
void checkAuth()
+ const onRemoteInvalidation = () => void checkAuth()
+ window.addEventListener(CONTROL_UI_SESSION_INVALIDATION_EVENT, onRemoteInvalidation)
+ return () =>
+ window.removeEventListener(CONTROL_UI_SESSION_INVALIDATION_EVENT, onRemoteInvalidation)
}, [checkAuth])
const login = useCallback(
async (username: string, password: string): Promise<AdminLoginResponse> => {
const result = await loginControlUI(username, password)
+ setControlUIReadPrincipal(result.me.id, 'admin')
resetPublishScopeCache()
invalidateRegistryCapabilityCache()
sessionExpiredToastShownRef.current = false
diff --git a/control-ui/components/CodexSubscriptionHub/index.tsx b/control-ui/components/CodexSubscriptionHub/index.tsx
index 230e78684..3616238fd 100644
--- a/control-ui/components/CodexSubscriptionHub/index.tsx
+++ b/control-ui/components/CodexSubscriptionHub/index.tsx
@@ -8,6 +8,7 @@ import {
TableViewport,
useTableSort,
} from '@clerum/frontend-components'
+import { SubscriptionCapabilityNotice } from '@components/SubscriptionCapabilityNotice'
import { copyTextToClipboard } from '@lib/clipboard'
import {
CODEX_DEVICE_VERIFICATION_URI,
@@ -25,7 +26,6 @@ import {
import {
type CodexSubscriptionCapability,
isCodexSubscriptionUiEnabled,
- loadCodexSubscriptionCapability,
} from '@lib/codexSubscriptionFeature'
import {
GROK_DEVICE_VERIFICATION_ORIGIN,
@@ -45,8 +45,8 @@ import {
import {
type GrokSubscriptionCapability,
isGrokSubscriptionUiEnabled,
- loadGrokSubscriptionCapability,
} from '@lib/grokSubscriptionFeature'
+import { useSubscriptionCapabilities } from '@lib/hooks/useSubscriptionCapabilities'
import {
mapConnectionStatus,
statusLabel,
@@ -173,6 +173,9 @@ async function copyDeviceValue(
export function CodexSubscriptionHub() {
const { showToast } = useToast()
const { confirm, confirmDialog } = useConfirmDialog()
+ const subscriptionCapabilities = useSubscriptionCapabilities()
+ const lifetimeController = useRef(new AbortController())
+ const editReadController = useRef<AbortController | null>(null)
const [capability, setCapability] = useState<CodexSubscriptionCapability | null>(null)
const [grokCapability, setGrokCapability] = useState<GrokSubscriptionCapability | null>(null)
const [rowsByBroker, setRowsByBroker] = useState<Record<HubBroker, HubConnection[]>>({
@@ -209,27 +212,33 @@ export function CodexSubscriptionHub() {
const grokEnabled = isGrokSubscriptionUiEnabled(grokCapability)
useEffect(() => {
- // A capability probe that fails for any reason other than "disabled" is
- // kept on the capability itself, so later action-error resets cannot
- // hide it and the other provider still loads.
- void loadCodexSubscriptionCapability()
- .then(setCapability)
- .catch(err => {
- setCapability({
- enabled: false,
- error: err instanceof Error ? err.message : 'Failed to load ChatGPT subscriptions',
- })
- setLoading(false)
+ lifetimeController.current = new AbortController()
+ return () => {
+ lifetimeController.current.abort()
+ editReadController.current?.abort()
+ }
+ }, [])
+
+ useEffect(() => {
+ const { capabilities, error: capabilityError } = subscriptionCapabilities
+ if (capabilities) {
+ setCapability({
+ enabled: capabilities.providers['codex-subscription'].enabled,
})
- void loadGrokSubscriptionCapability()
- .then(setGrokCapability)
- .catch(err => {
- setGrokCapability({
- enabled: false,
- error: err instanceof Error ? err.message : 'Failed to load Grok subscriptions',
- })
+ setGrokCapability({
+ enabled: capabilities.providers['grok-subscription'].enabled,
})
- }, [])
+ }
+ if (capabilityError) {
+ const message = capabilityError.message || 'Failed to load subscription capabilities'
+ setCapability(current =>
+ current?.enabled ? { enabled: true, error: message } : { enabled: false, error: message }
+ )
+ setGrokCapability(current =>
+ current?.enabled ? { enabled: true, error: message } : { enabled: false, error: message }
+ )
+ }
+ }, [subscriptionCapabilities.capabilities, subscriptionCapabilities.error])
const connections = useMemo(
() => [...rowsByBroker['codex-subscription'], ...rowsByBroker['grok-subscription']],
@@ -239,42 +248,48 @@ export function CodexSubscriptionHub() {
// Each provider loads independently: a failing list keeps that provider's
// last rows and records its own error, and never discards the healthy
// provider's result. Resolves with whether any enabled provider failed.
- const load = useCallback(async (): Promise<{ failed: boolean }> => {
- const [codexResult, grokResult] = await Promise.allSettled([
- enabled ? listCodexSubscriptionConnections() : Promise.resolve([]),
- grokEnabled ? listGrokSubscriptionConnections() : Promise.resolve([]),
- ])
- const bothEnabled = enabled && grokEnabled
- const describeFailure = (broker: HubBroker, reason: unknown) => {
- const brand = HUB_PROVIDER_COPY[broker].brand
- const message =
- reason instanceof Error && reason.message
- ? reason.message
- : `Failed to load ${brand} subscriptions`
- return bothEnabled ? `${brand} subscriptions: ${message}` : message
- }
- setRowsByBroker(current => ({
- 'codex-subscription':
- codexResult.status === 'fulfilled'
- ? codexResult.value.map(row => asHubRow(row, 'codex-subscription'))
- : current['codex-subscription'],
- 'grok-subscription':
- grokResult.status === 'fulfilled'
- ? grokResult.value.map(row => asHubRow(row, 'grok-subscription'))
- : current['grok-subscription'],
- }))
- setListErrors({
- 'codex-subscription':
- codexResult.status === 'rejected'
- ? describeFailure('codex-subscription', codexResult.reason)
- : '',
- 'grok-subscription':
- grokResult.status === 'rejected'
- ? describeFailure('grok-subscription', grokResult.reason)
- : '',
- })
- return { failed: codexResult.status === 'rejected' || grokResult.status === 'rejected' }
- }, [enabled, grokEnabled])
+ const load = useCallback(
+ async (options: { refresh?: boolean } = {}): Promise<{ failed: boolean }> => {
+ const signal = lifetimeController.current.signal
+ const requestOptions = { ...options, signal }
+ const [codexResult, grokResult] = await Promise.allSettled([
+ enabled ? listCodexSubscriptionConnections(requestOptions) : Promise.resolve([]),
+ grokEnabled ? listGrokSubscriptionConnections(requestOptions) : Promise.resolve([]),
+ ])
+ if (signal.aborted) return { failed: true }
+ const bothEnabled = enabled && grokEnabled
+ const describeFailure = (broker: HubBroker, reason: unknown) => {
+ const brand = HUB_PROVIDER_COPY[broker].brand
+ const message =
+ reason instanceof Error && reason.message
+ ? reason.message
+ : `Failed to load ${brand} subscriptions`
+ return bothEnabled ? `${brand} subscriptions: ${message}` : message
+ }
+ setRowsByBroker(current => ({
+ 'codex-subscription':
+ codexResult.status === 'fulfilled'
+ ? codexResult.value.map(row => asHubRow(row, 'codex-subscription'))
+ : current['codex-subscription'],
+ 'grok-subscription':
+ grokResult.status === 'fulfilled'
+ ? grokResult.value.map(row => asHubRow(row, 'grok-subscription'))
+ : current['grok-subscription'],
+ }))
+ setListErrors({
+ 'codex-subscription':
+ codexResult.status === 'rejected'
+ ? describeFailure('codex-subscription', codexResult.reason)
+ : '',
+ 'grok-subscription':
+ grokResult.status === 'rejected'
+ ? describeFailure('grok-subscription', grokResult.reason)
+ : '',
+ })
+ return { failed: codexResult.status === 'rejected' || grokResult.status === 'rejected' }
+ },
+ [enabled, grokEnabled]
+ )
useEffect(() => {
if (capability === null || grokCapability === null) return
@@ -362,7 +377,13 @@ export function CodexSubscriptionHub() {
}
async function openEdit(row: HubConnection) {
- connectEpoch.current += 1
+ const epoch = ++connectEpoch.current
+ editReadController.current?.abort()
+ const controller = new AbortController()
+ editReadController.current = controller
+ if (editing?.broker !== row.broker || editing.connectionKey !== row.connectionKey) {
+ setEditModels([])
+ }
setEditing(row)
setEditName(grantLabel(row))
setEditDefault(row.defaultModel ?? '')
@@ -375,11 +396,18 @@ export function CodexSubscriptionHub() {
try {
const models =
row.broker === 'grok-subscription'
- ? await listGrokConnectionModels(row.connectionKey)
- : await listCodexConnectionModels(row.connectionKey)
+ ? await listGrokConnectionModels(row.connectionKey, {
+ refresh: true,
+ signal: controller.signal,
+ })
+ : await listCodexConnectionModels(row.connectionKey, {
+ refresh: true,
+ signal: controller.signal,
+ })
+ if (controller.signal.aborted || connectEpoch.current !== epoch) return
setEditModels(models)
} catch (err) {
- setEditModels([])
+ if (controller.signal.aborted || connectEpoch.current !== epoch) return
setError(err instanceof Error ? err.message : 'Could not load grant models')
}
} else {
@@ -389,6 +417,7 @@ export function CodexSubscriptionHub() {
function closeEdit() {
connectEpoch.current += 1
+ editReadController.current?.abort()
setCreating(false)
setEditing(null)
setEditName('')
@@ -628,7 +657,7 @@ export function CodexSubscriptionHub() {
try {
const models = grok
? await listGrokConnectionModels(row.connectionKey)
- : await listCodexConnectionModels(row.connectionKey)
+ : await listCodexConnectionModels(row.connectionKey, { refresh: true })
setEditModels(models)
if (synced.connection) setEditing(asHubRow(synced.connection, row.broker))
await load()
@@ -722,10 +751,11 @@ export function CodexSubscriptionHub() {
<SecretsScopeTabs activeValue="llm-subscriptions" />
</div>
<div className="cu-empty">
- {capability.error ||
- grokCapability.error ||
- error ||
- 'Coding-plan subscriptions are disabled.'}
+ {subscriptionCapabilities.error ? (
+ <SubscriptionCapabilityNotice state={subscriptionCapabilities} />
+ ) : (
+ error || 'Coding-plan subscriptions are disabled.'
+ )}
</div>
</div>
)
@@ -758,7 +788,7 @@ export function CodexSubscriptionHub() {
<button
type="button"
className="cu-btn cu-btn--icon cu-btn--toolbar"
- onClick={() => void load()}
+ onClick={() => void load({ refresh: true })}
disabled={initialLoad || loading}
aria-label={loading ? 'Refreshing...' : `Reload ${listNoun}`}
>
diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsx
index 04a01edeb..4ff5adab2 100644
--- a/control-ui/components/HostWizard/index.tsx
+++ b/control-ui/components/HostWizard/index.tsx
@@ -2,6 +2,8 @@
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { validateDisplayField } from '@clerum/display-field'
+import { SubscriptionCapabilityNotice } from '@components/SubscriptionCapabilityNotice'
+import { useSubscriptionCapabilities } from '@lib/hooks/useSubscriptionCapabilities'
import { CreateFlowPanel } from '@/components/CreateFlowPanel'
import { CreateStepFlow } from '@/components/CreateStepFlow'
import { LlmProviderConfig } from '@/components/LlmProviderConfig'
@@ -247,6 +249,11 @@ export function HostWizard({
const { showToast } = useToast()
const [step, setStep] = useState(0)
const [busy, setBusy] = useState(false)
+ const subscriptionCapabilities = useSubscriptionCapabilities({ enabled: step === 1 })
+ const codexEnabled =
+ subscriptionCapabilities.capabilities?.providers['codex-subscription'].enabled ?? false
+ const grokEnabled =
+ subscriptionCapabilities.capabilities?.providers['grok-subscription'].enabled ?? false
const [error, setError] = useState('')
const [directoryLoading, setDirectoryLoading] = useState(false)
const [directoryLoadError, setDirectoryLoadError] = useState('')
@@ -300,7 +307,10 @@ export function HostWizard({
const [codexConnections, setCodexConnections] = useState<CodexSubscriptionConnectionView[]>([])
const [grokModels, setGrokModels] = useState<string[]>([])
const [grokConnections, setGrokConnections] = useState<GrokSubscriptionConnectionView[]>([])
- const [grokEnabled, setGrokEnabled] = useState(false)
+ const [grantInventoryError, setGrantInventoryError] = useState('')
+ const [grantCatalogError, setGrantCatalogError] = useState('')
+ const [grantInventoryLoading, setGrantInventoryLoading] = useState(false)
+ const [inventoryRetryNonce, setInventoryRetryNonce] = useState(0)
const [stateless, setStateless] = useState(false)
const [users, setUsers] = useState<
Array<{ id: string; email: string; name: string | null; displayName: string | null }>
@@ -442,79 +452,100 @@ export function HostWizard({
[allowedCatalog, existingSecrets]
)
useEffect(() => {
- let cancelled = false
- void listCodexSubscriptionConnections()
- .then(rows => {
- if (!cancelled) setCodexConnections(rows)
+ if (step !== 1 || !subscriptionCapabilities.capabilities) {
+ setGrantInventoryError('')
+ setGrantInventoryLoading(false)
+ return
+ }
+ const controller = new AbortController()
+ setGrantInventoryLoading(true)
+ const requests = [
+ codexEnabled
+ ? listCodexSubscriptionConnections({
+ signal: controller.signal,
+ refresh: inventoryRetryNonce > 0,
+ })
+ : Promise.resolve([]),
+ ...(grokEnabled
+ ? [
+ listGrokSubscriptionConnections({
+ signal: controller.signal,
+ refresh: inventoryRetryNonce > 0,
+ }),
+ ]
+ : []),
+ ]
+ Promise.allSettled(requests)
+ .then(([codexResult, grokResult]) => {
+ if (controller.signal.aborted) return
+ if (codexResult.status === 'fulfilled') setCodexConnections(codexResult.value)
+ if (grokResult?.status === 'fulfilled') setGrokConnections(grokResult.value)
+ setGrantInventoryError('')
+ const failure = [codexResult, grokResult].find(
+ result => result?.status === 'rejected' && !isDisabledCapabilityError(result.reason)
+ )
+ if (failure?.status === 'rejected') throw failure.reason
})
.catch(err => {
- if (!cancelled) {
- setCodexConnections([])
- if (!isDisabledCapabilityError(err)) {
- setError(err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions')
- }
- }
- })
- void listGrokSubscriptionConnections()
- .then(rows => {
- if (!cancelled) {
- setGrokConnections(rows)
- setGrokEnabled(true)
- }
+ if (controller.signal.aborted || isDisabledCapabilityError(err)) return
+ setGrantInventoryError(
+ err instanceof Error && err.message ? err.message : 'Could not load subscription options'
+ )
})
- .catch(err => {
- if (!cancelled) {
- setGrokConnections([])
- setGrokEnabled(false)
- if (!isDisabledCapabilityError(err)) {
- setError(err instanceof Error ? err.message : 'Could not load Grok subscriptions')
- }
- }
+ .finally(() => {
+ if (!controller.signal.aborted) setGrantInventoryLoading(false)
})
- return () => {
- cancelled = true
- }
- }, [])
+ return () => controller.abort()
+ }, [codexEnabled, grokEnabled, inventoryRetryNonce, step, subscriptionCapabilities.capabilities])
useEffect(() => {
+ if (step !== 1) return
if (!connectionRef.trim() || connectionRef === CODEX_UNASSIGNED_CONNECTION_KEY) {
setCodexModels([])
setGrokModels([])
+ setGrantCatalogError('')
return
}
- let cancelled = false
+ setGrantCatalogError('')
+ const controller = new AbortController()
if (provider === GROK_SUBSCRIPTION_PROVIDER) {
setCodexModels([])
- void listGrokConnectionModels(connectionRef)
+ void listGrokConnectionModels(connectionRef, {
+ signal: controller.signal,
+ refresh: inventoryRetryNonce > 0,
+ })
.then(models => {
- if (!cancelled) setGrokModels(offeredCodexModelNames(models))
+ if (!controller.signal.aborted) setGrokModels(offeredCodexModelNames(models))
})
- .catch(() => {
- if (!cancelled) {
- setGrokModels([])
- setModelName('')
- setError('Could not load Grok grant models')
+ .catch(err => {
+ if (!controller.signal.aborted) {
+ setGrantCatalogError(
+ err instanceof Error ? err.message : 'Could not load Grok grant models'
+ )
}
})
return () => {
- cancelled = true
+ controller.abort()
}
}
setGrokModels([])
- void listCodexConnectionModels(connectionRef)
+ void listCodexConnectionModels(connectionRef, {
+ signal: controller.signal,
+ refresh: inventoryRetryNonce > 0,
+ })
.then(models => {
- if (!cancelled) setCodexModels(offeredCodexModelNames(models))
+ if (!controller.signal.aborted) setCodexModels(offeredCodexModelNames(models))
})
- .catch(() => {
- if (!cancelled) {
- setCodexModels([])
- setModelName('')
- setError('Could not load ChatGPT grant models')
+ .catch(err => {
+ if (!controller.signal.aborted) {
+ setGrantCatalogError(
+ err instanceof Error ? err.message : 'Could not load ChatGPT grant models'
+ )
}
})
return () => {
- cancelled = true
+ controller.abort()
}
- }, [connectionRef, provider])
+ }, [connectionRef, inventoryRetryNonce, provider, step])
// 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.
@@ -928,6 +959,7 @@ export function HostWizard({
>
{step === 0 && (
<div className="cu-form-stack cu-agent-form-stack">
+ <SubscriptionCapabilityNotice state={subscriptionCapabilities} />
<Field
description="The name members see. The identifier used in URLs is derived automatically."
htmlFor="wizard-agent-name"
@@ -1020,6 +1052,37 @@ export function HostWizard({
{step === 1 && (
<div className="cu-form-stack cu-agent-form-stack">
+ {grantInventoryLoading ? (
+ <p className="cu-muted" role="status">
+ Loading subscription options…
+ </p>
+ ) : null}
+ {grantInventoryError ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ <span>{grantInventoryError}</span>
+ <Button
+ type="button"
+ className="cu-btn--sm"
+ variant="ghost"
+ onClick={() => setInventoryRetryNonce(value => value + 1)}
+ >
+ Retry
+ </Button>
+ </div>
+ ) : null}
+ {grantCatalogError ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ {grantCatalogError}
+ <Button
+ type="button"
+ className="cu-btn--sm"
+ variant="ghost"
+ onClick={() => setInventoryRetryNonce(value => value + 1)}
+ >
+ Retry
+ </Button>
+ </div>
+ ) : null}
<div className="cu-agent-access-section">
<strong>LLM credentials</strong>
<span className="cu-muted cu-agent-access-hint">
diff --git a/control-ui/components/LlmModelForm/index.tsx b/control-ui/components/LlmModelForm/index.tsx
index ce9e93cd1..6e2cf14f7 100644
--- a/control-ui/components/LlmModelForm/index.tsx
+++ b/control-ui/components/LlmModelForm/index.tsx
@@ -3,7 +3,7 @@
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 { useSubscriptionCapabilities } from '@lib/hooks/useSubscriptionCapabilities'
import {
GROK_SUBSCRIPTION_PROVIDER,
LLM_PROVIDER_OPTIONS,
@@ -11,6 +11,7 @@ import {
isOauthBrokerProvider,
runtimeProviderOptions,
} from '@lib/llm'
+import { SubscriptionCapabilityNotice } from '../SubscriptionCapabilityNotice'
import type { LlmModelFormProps } from './types'
// Returns a positive integer, or null when empty. Returns undefined when the
@@ -46,11 +47,14 @@ export function LlmModelForm({
)
const [enabled, setEnabled] = useState(initial?.enabled ?? true)
const [showErrors, setShowErrors] = useState(false)
- const grokEnabled = useGrokSubscriptionEnabled()
+ const subscriptionCapabilities = useSubscriptionCapabilities()
+ const grokEnabled =
+ subscriptionCapabilities.capabilities?.providers['grok-subscription']?.enabled ?? false
const savedProvider = initial?.provider ?? prefill?.provider
+ const grokAvailabilityKnown = subscriptionCapabilities.capabilities !== null
const providerOptions = useMemo(
- () => runtimeProviderOptions({ grokEnabled, saved: [savedProvider] }),
- [grokEnabled, savedProvider]
+ () => runtimeProviderOptions({ grokEnabled, grokAvailabilityKnown, saved: [savedProvider] }),
+ [grokAvailabilityKnown, grokEnabled, savedProvider]
)
const providerIsKnown = isKnownProvider(provider)
@@ -83,6 +87,7 @@ export function LlmModelForm({
return (
<form className="cu-create-content cu-px-form" onSubmit={handleSubmit}>
+ <SubscriptionCapabilityNotice state={subscriptionCapabilities} />
<FormSection
title="Model"
description="Provider (runtime/platform id) and the exact model name callers request."
diff --git a/control-ui/components/LlmPriceForm/index.tsx b/control-ui/components/LlmPriceForm/index.tsx
index 3e5e2d3ee..34ef15b79 100644
--- a/control-ui/components/LlmPriceForm/index.tsx
+++ b/control-ui/components/LlmPriceForm/index.tsx
@@ -5,14 +5,15 @@ 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 { useSubscriptionCapabilities } from '@lib/hooks/useSubscriptionCapabilities'
import {
LLM_PROVIDER_OPTIONS,
getModelOptions,
isKnownProvider,
runtimeProviderOptions,
} from '@lib/llm'
+import { SubscriptionCapabilityNotice } from '../SubscriptionCapabilityNotice'
import { DEFAULT_CURRENCY, PRICE_FIELDS } from './constants'
import type { LlmPriceFormProps, PriceFieldKey } from './types'
@@ -66,11 +67,14 @@ export function LlmPriceForm({
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 subscriptionCapabilities = useSubscriptionCapabilities()
+ const grokEnabled =
+ subscriptionCapabilities.capabilities?.providers['grok-subscription']?.enabled ?? false
const savedProvider = initial?.provider ?? prefill?.provider
+ const grokAvailabilityKnown = subscriptionCapabilities.capabilities !== null
const providerOptions = useMemo(
- () => runtimeProviderOptions({ grokEnabled, saved: [savedProvider] }),
- [grokEnabled, savedProvider]
+ () => runtimeProviderOptions({ grokEnabled, grokAvailabilityKnown, saved: [savedProvider] }),
+ [grokAvailabilityKnown, grokEnabled, savedProvider]
)
const priceErrors = useMemo(() => {
@@ -109,6 +113,7 @@ export function LlmPriceForm({
return (
<form className="cu-create-content cu-px-form" onSubmit={handleSubmit}>
+ <SubscriptionCapabilityNotice state={subscriptionCapabilities} />
<FormSection
title="Model"
description="Provider and model name must match the values reported in usage."
diff --git a/control-ui/components/RecipeEditor.tsx b/control-ui/components/RecipeEditor.tsx
index 14a4bf16b..12c975cfc 100644
--- a/control-ui/components/RecipeEditor.tsx
+++ b/control-ui/components/RecipeEditor.tsx
@@ -1754,51 +1754,6 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
}
}, [])
- useEffect(() => {
- let cancelled = false
- void listCodexSubscriptionConnections()
- .then(rows => {
- if (!cancelled) {
- setCodexConnections(rows)
- setCodexGrantLoadError('')
- }
- })
- .catch(err => {
- if (!cancelled) {
- setCodexConnections([])
- if (!isDisabledCapabilityError(err)) {
- setCodexGrantLoadError(
- err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions'
- )
- } else {
- setCodexGrantLoadError('')
- }
- }
- })
- 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
- }
- }, [])
-
useEffect(() => {
setGrantSelection(storedRecipeGrantSelection(currentInitial))
}, [currentInitial])
@@ -1825,6 +1780,10 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
const [codexGrantLoadError, setCodexGrantLoadError] = useState('')
const [grokConnections, setGrokConnections] = useState<GrokSubscriptionConnectionView[]>([])
const [grokGrantLoadError, setGrokGrantLoadError] = useState('')
+ const [grantInventoryLoading, setGrantInventoryLoading] = useState(false)
+ const [grantInventoryRetryNonce, setGrantInventoryRetryNonce] = useState(0)
+ const [codexInventoryLoaded, setCodexInventoryLoaded] = useState(false)
+ const [grokInventoryLoaded, setGrokInventoryLoaded] = useState(false)
const [grantSelection, setGrantSelection] = useState<RecipeGrantSelection>(() =>
storedRecipeGrantSelection(initial)
)
@@ -1881,6 +1840,39 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
}, [jsonInput])
const isCodexRecipe = manifestBrokerProvider === OPENAI_SUBSCRIPTION_PROVIDER
const isGrokRecipe = manifestBrokerProvider === GROK_SUBSCRIPTION_PROVIDER
+
+ useEffect(() => {
+ if (step !== 'confirm' || (!isCodexRecipe && !isGrokRecipe)) return
+ const controller = new AbortController()
+ setGrantInventoryLoading(true)
+ const loader = isGrokRecipe ? listGrokSubscriptionConnections : listCodexSubscriptionConnections
+ loader({ signal: controller.signal, refresh: grantInventoryRetryNonce > 0 })
+ .then(rows => {
+ if (controller.signal.aborted) return
+ if (isGrokRecipe) {
+ setGrokConnections(rows)
+ setGrokInventoryLoaded(true)
+ } else {
+ setCodexConnections(rows)
+ setCodexInventoryLoaded(true)
+ }
+ if (isGrokRecipe) setGrokGrantLoadError('')
+ else setCodexGrantLoadError('')
+ })
+ .catch(err => {
+ if (controller.signal.aborted || isDisabledCapabilityError(err)) return
+ const message =
+ err instanceof Error && err.message
+ ? err.message
+ : `Could not load ${isGrokRecipe ? 'Grok' : 'ChatGPT'} subscriptions`
+ if (isGrokRecipe) setGrokGrantLoadError(message)
+ else setCodexGrantLoadError(message)
+ })
+ .finally(() => {
+ if (!controller.signal.aborted) setGrantInventoryLoading(false)
+ })
+ return () => controller.abort()
+ }, [grantInventoryRetryNonce, isCodexRecipe, isGrokRecipe, step])
const codexGrant = grantSelectionForProvider(
grantSelection,
OPENAI_SUBSCRIPTION_PROVIDER,
@@ -1913,13 +1905,13 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
options.unshift({
group: 'ChatGPT subscriptions',
value: credentialSelectValue('', codexGrantKey),
- label: `${codexGrantKey} (unavailable)`,
+ label: codexInventoryLoaded ? `${codexGrantKey} (unavailable)` : codexGrantKey,
meta: 'ChatGPT subscription',
providers: [{ id: 'codex-subscription', label: 'ChatGPT Subscription' }],
})
}
return options
- }, [codexConnections, codexGrantKey])
+ }, [codexConnections, codexGrantKey, codexInventoryLoaded])
const grokGrantOptions = useMemo<LlmSecretSelectOption[]>(() => {
const options: LlmSecretSelectOption[] = grokConnections
@@ -1938,13 +1930,13 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
options.unshift({
group: 'Grok subscriptions',
value: credentialSelectValue('', grokGrantKey, GROK_SUBSCRIPTION_PROVIDER),
- label: `${grokGrantKey} (unavailable)`,
+ label: grokInventoryLoaded ? `${grokGrantKey} (unavailable)` : grokGrantKey,
meta: 'Grok subscription',
providers: [{ id: GROK_SUBSCRIPTION_PROVIDER, label: 'xAI Grok Subscription' }],
})
}
return options
- }, [grokConnections, grokGrantKey])
+ }, [grokConnections, grokGrantKey, grokInventoryLoaded])
const deploying = deployPhase !== 'idle'
@@ -2802,6 +2794,11 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
{step === 'confirm' && isCodexRecipe ? (
<div className="cu-recipe-status-panel" data-testid="codex-recipe-grant">
+ {grantInventoryLoading ? (
+ <p className="cu-muted" role="status">
+ Loading ChatGPT grants…
+ </p>
+ ) : null}
<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{' '}
@@ -2835,6 +2832,13 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
{codexGrantLoadError ? (
<div className="cu-banner cu-banner--error" role="alert" style={{ marginTop: 10 }}>
{codexGrantLoadError}
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost cu-btn--sm"
+ onClick={() => setGrantInventoryRetryNonce(value => value + 1)}
+ >
+ Retry
+ </button>
</div>
) : null}
</div>
@@ -2842,6 +2846,11 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
{step === 'confirm' && isGrokRecipe ? (
<div className="cu-recipe-status-panel" data-testid="grok-recipe-grant">
+ {grantInventoryLoading ? (
+ <p className="cu-muted" role="status">
+ Loading Grok grants…
+ </p>
+ ) : null}
<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{' '}
@@ -2873,6 +2882,13 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
{grokGrantLoadError ? (
<div className="cu-banner cu-banner--error" role="alert" style={{ marginTop: 10 }}>
{grokGrantLoadError}
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost cu-btn--sm"
+ onClick={() => setGrantInventoryRetryNonce(value => value + 1)}
+ >
+ Retry
+ </button>
</div>
) : null}
</div>
diff --git a/control-ui/components/SubscriptionCapabilityNotice/index.tsx b/control-ui/components/SubscriptionCapabilityNotice/index.tsx
new file mode 100644
index 000000000..0e9013450
--- /dev/null
+++ b/control-ui/components/SubscriptionCapabilityNotice/index.tsx
@@ -0,0 +1,29 @@
+'use client'
+
+import { Button } from '@components/ui'
+import type { SubscriptionCapabilityNoticeProps } from './types'
+
+export function SubscriptionCapabilityNotice({ state }: SubscriptionCapabilityNoticeProps) {
+ if (!state.capabilities && state.loading) {
+ return (
+ <p className="cu-muted" role="status">
+ Checking available providers…
+ </p>
+ )
+ }
+ if (!state.error) return null
+ return (
+ <div className="cu-banner cu-banner--error" role="alert">
+ <span>Provider availability could not be checked. {state.error.message}</span>
+ <Button
+ type="button"
+ className="cu-btn--sm"
+ variant="ghost"
+ onClick={state.retry}
+ disabled={state.loading}
+ >
+ {state.loading ? 'Retrying…' : 'Retry'}
+ </Button>
+ </div>
+ )
+}
diff --git a/control-ui/components/SubscriptionCapabilityNotice/types.ts b/control-ui/components/SubscriptionCapabilityNotice/types.ts
new file mode 100644
index 000000000..0e81490a5
--- /dev/null
+++ b/control-ui/components/SubscriptionCapabilityNotice/types.ts
@@ -0,0 +1,5 @@
+import type { SubscriptionCapabilitiesState } from '@lib/hooks/useSubscriptionCapabilities'
+
+export type SubscriptionCapabilityNoticeProps = {
+ state: SubscriptionCapabilitiesState
+}
diff --git a/control-ui/components/TokenBudgetForm/index.tsx b/control-ui/components/TokenBudgetForm/index.tsx
index 3ede0ff66..fe29a345a 100644
--- a/control-ui/components/TokenBudgetForm/index.tsx
+++ b/control-ui/components/TokenBudgetForm/index.tsx
@@ -13,9 +13,10 @@ import {
getLlmPrices,
getRecipeSecrets,
} from '@lib/api'
-import { useGrokSubscriptionEnabled } from '@lib/hooks/useGrokSubscriptionEnabled'
import { useLlmAllowedModels } from '@lib/hooks/useLlmAllowedModels'
+import { useSubscriptionCapabilities } from '@lib/hooks/useSubscriptionCapabilities'
import { budgetUnitAllowedForProviders, getAllModelOptions, runtimeProviderOptions } from '@lib/llm'
+import { SubscriptionCapabilityNotice } from '../SubscriptionCapabilityNotice'
import { ScopeSelector } from './ScopeSelector'
import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE } from './constants'
import type { ScopeDimensionConfig, ScopeOption, TokenBudgetFormProps } from './types'
@@ -60,11 +61,14 @@ export function TokenBudgetForm({
// 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 subscriptionCapabilities = useSubscriptionCapabilities()
+ const grokEnabled =
+ subscriptionCapabilities.capabilities?.providers['grok-subscription']?.enabled ?? false
const savedProviders = initial?.scope?.provider
+ const grokAvailabilityKnown = subscriptionCapabilities.capabilities !== null
const providerOptions = useMemo<ScopeOption[]>(
- () => runtimeProviderOptions({ grokEnabled, saved: savedProviders }),
- [grokEnabled, savedProviders]
+ () => runtimeProviderOptions({ grokEnabled, grokAvailabilityKnown, saved: savedProviders }),
+ [grokAvailabilityKnown, grokEnabled, savedProviders]
)
// Dimension option sources (best-effort; a failed fetch just leaves a
@@ -231,6 +235,7 @@ export function TokenBudgetForm({
return (
<form className="cu-create-content cu-tb-form" onSubmit={handleSubmit}>
+ <SubscriptionCapabilityNotice state={subscriptionCapabilities} />
<FormSection title="Budget" description="A name and the limit this budget enforces.">
<div className="cu-form-grid cu-form-grid--2">
<Field
diff --git a/control-ui/components/__tests__/AuthContext.test.tsx b/control-ui/components/__tests__/AuthContext.test.tsx
index cadca4949..0bda4731b 100644
--- a/control-ui/components/__tests__/AuthContext.test.tsx
+++ b/control-ui/components/__tests__/AuthContext.test.tsx
@@ -1,6 +1,6 @@
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { apiGet } from '../../lib/api'
import {
PublishScopeProvider,
@@ -11,6 +11,10 @@ import {
__resetRegistryCapabilityCacheForTests,
useRegistryCapability,
} from '../../lib/hooks/useRegistryCapability'
+import {
+ __resetReadRequestCacheForTests,
+ getReadRequestPrincipal,
+} from '../../lib/readRequestCache'
import { AuthProvider, useAuth } from '../AuthContext'
import { ToastProvider } from '../Toast'
@@ -104,6 +108,7 @@ afterEach(() => {
__resetRegistryCapabilityCacheForTests()
window.localStorage.clear()
vi.unstubAllGlobals()
+ __resetReadRequestCacheForTests()
})
describe('AuthProvider session expiry handling', () => {
@@ -413,6 +418,38 @@ describe('AuthProvider session expiry handling', () => {
expect(window.localStorage.getItem('controlUiAdminToken')).toBeNull()
})
+ it('reverifies a remote cookie-session change once without an invalidation loop', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ response(200, { me: { id: 'admin-a', username: 'admin-a', role: 'admin' } })
+ )
+ .mockResolvedValueOnce(
+ response(200, { me: { id: 'admin-b', username: 'admin-b', role: 'admin' } })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+ render(
+ <ToastProvider>
+ <AuthProvider>
+ <AuthUserProbe />
+ </AuthProvider>
+ </ToastProvider>
+ )
+ await waitFor(() => expect(screen.getByTestId('auth-user')).toHaveTextContent('admin-a'))
+ const otherTab = new BroadcastChannel('control-ui-read-metadata-invalidation')
+ const loopMessages: unknown[] = []
+ otherTab.onmessage = event => loopMessages.push(event.data)
+ await act(async () => {
+ otherTab.postMessage({ type: 'session-invalidation' })
+ await new Promise(resolve => setTimeout(resolve, 0))
+ })
+ await waitFor(() => expect(screen.getByTestId('auth-user')).toHaveTextContent('admin-b'))
+ expect(getReadRequestPrincipal()?.principalId).toBe('admin-b')
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(loopMessages).toEqual([])
+ otherTab.close()
+ })
+
it('redirects after logout even when token revocation fails', async () => {
window.localStorage.setItem('controlUiAdminToken', 'valid-token')
const fetchMock = vi
diff --git a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx
index e48f738e8..f66f9df10 100644
--- a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx
+++ b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx
@@ -45,7 +45,15 @@ vi.mock('@lib/codexSubscriptionFeature', () => ({
vi.mock('@lib/grokSubscriptionFeature', () => ({
isGrokSubscriptionUiEnabled: (capability?: { enabled?: boolean } | null) =>
capability?.enabled === true,
- loadGrokSubscriptionCapability: () => capabilityProbes.grok(),
+}))
+
+vi.mock('@lib/subscriptionCapabilities', () => ({
+ loadSubscriptionCapabilities: async () => ({
+ providers: {
+ 'codex-subscription': await capabilityProbes.codex(),
+ 'grok-subscription': await capabilityProbes.grok(),
+ },
+ }),
}))
vi.mock('@lib/codexSubscription', async importOriginal => {
@@ -362,7 +370,10 @@ describe('CodexSubscriptionHub', () => {
const signInHint = screen.getByText(/Agents authorize through this subscription/)
expect(signInHint).toHaveTextContent('use Sync catalog to pick up models published since')
expect(signInHint).not.toHaveTextContent('refreshes automatically')
- expect(listCodexConnectionModels).toHaveBeenCalledWith('codex-aaa')
+ expect(listCodexConnectionModels).toHaveBeenCalledWith('codex-aaa', {
+ refresh: true,
+ signal: expect.any(AbortSignal),
+ })
fireEvent.click(screen.getByLabelText('gpt-5.3-codex'))
await waitFor(() => {
expect(patchCodexCatalogModel).toHaveBeenCalledWith('codex-aaa', 'gpt-5.3-codex', true)
@@ -703,25 +714,50 @@ describe('CodexSubscriptionHub with Grok enabled', () => {
expect(screen.getByText('Team A')).toBeInTheDocument()
})
- it('surfaces a non-disabled Codex capability probe error while Grok is enabled', async () => {
- capabilityProbes.codex.mockRejectedValue(new Error('codex probe boom'))
+ it('keeps both loaded provider inventories through a real throttle-shaped error and explicit recovery', async () => {
renderHub()
+ expect(await screen.findByText('Team A')).toBeInTheDocument()
expect(await screen.findByText('Team Grok')).toBeInTheDocument()
+ vi.mocked(listGrokSubscriptionConnections).mockRejectedValueOnce(
+ Object.assign(new Error('This request limit has been reached. Try again in 12 seconds.'), {
+ status: 429,
+ code: 'rate_limited',
+ retryAfterSeconds: 12,
+ body: { error: 'Too Many Requests', code: 'rate_limited', retryAfterSeconds: 12 },
+ })
+ )
+ fireEvent.click(screen.getByRole('button', { name: /^Reload/ }))
+ expect(await screen.findByText(/Try again in 12 seconds/)).toBeInTheDocument()
+ expect(screen.getByText('Team A')).toBeInTheDocument()
+ expect(screen.getByText('Team Grok')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: /^Reload/ }))
+ await waitFor(() => expect(screen.queryByText(/Try again in 12 seconds/)).toBeNull())
+ expect(screen.getByText('Team Grok')).toBeInTheDocument()
+ expect(startGrokDeviceConnect).not.toHaveBeenCalled()
+ expect(pollGrokDevice).not.toHaveBeenCalled()
+ expect(revokeGrokSubscription).not.toHaveBeenCalled()
+ })
+
+ it('surfaces a shared capability read error without inventing provider connectivity', async () => {
+ capabilityProbes.codex.mockRejectedValue(new Error('codex probe boom'))
+ renderHub()
expect(await screen.findByText(/codex probe boom/)).toBeInTheDocument()
+ expect(screen.queryByText('Team Grok')).not.toBeInTheDocument()
})
- it('surfaces a non-disabled Grok capability probe error while Codex is enabled', async () => {
+ it('surfaces a Grok capability read error without treating it as a confirmed disabled flag', async () => {
capabilityProbes.grok.mockRejectedValue(new Error('grok probe boom'))
renderHub()
- expect(await screen.findByText('Team A')).toBeInTheDocument()
expect(await screen.findByText(/grok probe boom/)).toBeInTheDocument()
+ expect(screen.queryByText('Team A')).not.toBeInTheDocument()
})
- it('surfaces a non-disabled Grok capability probe error when Codex is disabled', async () => {
+ it('keeps a capability error distinct from both integrations being disabled', async () => {
capabilityProbes.codex.mockResolvedValue({ enabled: false })
capabilityProbes.grok.mockRejectedValue(new Error('grok probe boom'))
renderHub()
expect(await screen.findByText(/grok probe boom/)).toBeInTheDocument()
+ expect(screen.queryByText(/Coding-plan subscriptions are disabled/)).not.toBeInTheDocument()
})
it('keeps same-key Codex and Grok rows independent for keys, busy state and edit-close', async () => {
diff --git a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx
index b6eb01efb..ed2293451 100644
--- a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx
+++ b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx
@@ -223,6 +223,12 @@ afterEach(() => {
describe('HostDetailsPage identity integration', () => {
beforeEach(() => {
vi.clearAllMocks()
+ vi.mocked(api.apiGet).mockResolvedValue({
+ providers: {
+ 'codex-subscription': { enabled: true },
+ 'grok-subscription': { enabled: true },
+ },
+ })
mockParams = { name: 'foo' }
setupApiMocks()
})
@@ -428,8 +434,9 @@ describe('HostDetailsPage identity integration', () => {
const summary = await screen.findByRole('region', { name: 'LLM configuration summary' })
expect(summary).toHaveTextContent('Current model')
expect(summary).toHaveTextContent('gpt-5.1')
- expect(screen.getByText('Team A')).toBeInTheDocument()
- expect(screen.queryByText('codex-aaa')).not.toBeInTheDocument()
+ expect(screen.getByText('codex-aaa')).toBeInTheDocument()
+ expect(screen.queryByText('Team A')).not.toBeInTheDocument()
+ expect(listCodexSubscriptionConnections).not.toHaveBeenCalled()
expect(screen.getByText('Credential')).toBeInTheDocument()
expect(screen.queryByText('Secret reference')).not.toBeInTheDocument()
expect(screen.queryByText('Broker-backed — no LLM secret required')).not.toBeInTheDocument()
@@ -627,6 +634,7 @@ describe('HostDetailsPage identity integration', () => {
;(api.getHost as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(grokHost)
render(<HostDetailsPage />)
fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled())
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
await waitFor(() => {
expect(api.apiSend).toHaveBeenCalledWith(
@@ -740,7 +748,10 @@ describe('HostDetailsPage identity integration', () => {
render(<HostDetailsPage />)
fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
await waitFor(() => {
- expect(listCodexConnectionModels).toHaveBeenCalledWith('codex-aaa')
+ expect(listCodexConnectionModels).toHaveBeenCalledWith(
+ 'codex-aaa',
+ expect.objectContaining({ signal: expect.any(AbortSignal) })
+ )
})
fireEvent.click(await findGrokProviderOption())
await waitFor(() => {
@@ -776,18 +787,31 @@ describe('HostDetailsPage identity integration', () => {
render(<HostDetailsPage />)
fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
await waitFor(() => {
- expect(listGrokConnectionModels).toHaveBeenCalledWith('team-grok')
+ expect(listGrokConnectionModels).toHaveBeenCalledWith(
+ 'team-grok',
+ expect.objectContaining({ signal: expect.any(AbortSignal) })
+ )
})
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
})
it('hides the Grok provider option when the Grok capability probe reports disabled', async () => {
mockParams = { name: 'foo', tab: 'model' }
+ vi.mocked(api.apiGet).mockResolvedValue({
+ providers: {
+ 'codex-subscription': { enabled: true },
+ 'grok-subscription': { enabled: false },
+ },
+ })
vi.mocked(listGrokSubscriptionConnections).mockRejectedValue({ status: 404 })
render(<HostDetailsPage />)
fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
await waitFor(() => {
- expect(listGrokSubscriptionConnections).toHaveBeenCalled()
+ expect(api.apiGet).toHaveBeenCalledWith(
+ '/api/v1/admin/llm/providers/capabilities',
+ {},
+ expect.objectContaining({ metadataRead: 'subscription-capabilities' })
+ )
})
fireEvent.click(screen.getByLabelText('Provider', { selector: '#llm-primary-provider' }))
expect(screen.getByRole('option', { name: /^OpenAI$/ })).toBeInTheDocument()
diff --git a/control-ui/components/__tests__/HostDetailsPage.rateLimit.test.tsx b/control-ui/components/__tests__/HostDetailsPage.rateLimit.test.tsx
new file mode 100644
index 000000000..3ee9afe6f
--- /dev/null
+++ b/control-ui/components/__tests__/HostDetailsPage.rateLimit.test.tsx
@@ -0,0 +1,277 @@
+import React from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import HostDetailsPage from '../../app/hosts/[name]/page'
+import * as api from '../../lib/api'
+import { __resetReadRequestCacheForTests } from '../../lib/readRequestCache'
+import { buildContextResource } from '../../test/fixtures/contextResource'
+import { ToastProvider } from '../Toast'
+
+const navigation = vi.hoisted(() => ({
+ replace: vi.fn(),
+ push: vi.fn(),
+ tab: undefined as string | undefined,
+}))
+
+vi.mock('next/navigation', () => ({
+ useParams: () => ({ name: 'quota-agent', tab: navigation.tab }),
+ usePathname: () => '/agents/quota-agent',
+ useRouter: () => navigation,
+ useSearchParams: () => new URLSearchParams(),
+}))
+vi.mock('next/link', () => ({
+ default: ({ href, children, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement>) => (
+ <a
+ {...props}
+ href={href}
+ onClick={event => {
+ event.preventDefault()
+ navigation.tab = String(href).split('/').at(-1)
+ navigation.replace(href)
+ }}
+ >
+ {children}
+ </a>
+ ),
+}))
+vi.mock('../AuthContext', () => ({ useAuth: () => ({ logout: vi.fn() }) }))
+vi.mock('../Sidebar', () => ({ Sidebar: () => <aside aria-label="Sidebar" /> }))
+// These sections have their own identity/access suites. This regression owns
+// the detail shell, its real overview/model editor, and physical metadata GETs.
+vi.mock('../HostIdentityTab', () => ({
+ HostIdentityTab: ({ hostName }: { hostName: string }) => (
+ <section aria-label="Identity editor">{hostName}</section>
+ ),
+}))
+vi.mock('../HostAccessTab', () => ({
+ HostAccessTab: ({ hostName }: { hostName: string }) => (
+ <section aria-label="Access editor">{hostName}</section>
+ ),
+}))
+vi.mock('../../lib/api', async importOriginal => {
+ const actual = await importOriginal<typeof import('../../lib/api')>()
+ return {
+ ...actual,
+ getHostDetailBundle: vi.fn(),
+ getHost: vi.fn(),
+ getLlmModels: vi.fn(),
+ apiSend: vi.fn(),
+ }
+})
+
+const host = {
+ metadata: {
+ name: 'quota-agent',
+ resourceVersion: 'host-rv-1',
+ creationTimestamp: '2026-01-01T12:00:00Z',
+ },
+ spec: {
+ host: 'Operations agent',
+ description: 'Loaded agent state survives optional metadata throttling.',
+ contextRef: 'quota-context',
+ model: { provider: 'openai', name: 'gpt-4o' },
+ secretRef: 'operator-credential',
+ },
+ status: { lifecycle: { state: 'Active' } },
+}
+
+function json(value: unknown): Response {
+ return new Response(JSON.stringify(value), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+}
+
+function throttle(): Response {
+ return new Response(
+ JSON.stringify({
+ error: 'Too Many Requests',
+ code: 'rate_limited',
+ message: 'This request limit has been reached. Try again in 12 seconds.',
+ retryAfterSeconds: 12,
+ }),
+ {
+ status: 429,
+ statusText: '',
+ headers: { 'content-type': 'application/json', 'retry-after': '12' },
+ }
+ )
+}
+
+let rerenderPage: () => void
+function renderPage() {
+ const element = (
+ <ToastProvider>
+ <HostDetailsPage />
+ </ToastProvider>
+ )
+ const result = render(element)
+ // Reflect the route segment selected through the visible Next Link in this
+ // component test; the real router journey is owned by the E2E lane.
+ rerenderPage = () =>
+ result.rerender(
+ <ToastProvider>
+ <HostDetailsPage />
+ </ToastProvider>
+ )
+ return result
+}
+
+function navigate(label: string) {
+ fireEvent.click(screen.getByRole('tab', { name: label }))
+ rerenderPage()
+}
+
+function assertLoadedOverview() {
+ expect(screen.getByRole('heading', { name: 'Agent: Operations agent' })).toBeInTheDocument()
+ expect(
+ within(screen.getByRole('region', { name: 'Agent identity' })).getByText('Active')
+ ).toBeInTheDocument()
+ expect(screen.getByText(host.spec.description)).toBeInTheDocument()
+ expect(
+ within(screen.getByRole('region', { name: 'Connectors' })).getByText('documents-connector')
+ ).toBeInTheDocument()
+ const access = screen.getByRole('region', { name: 'Access summary' })
+ expect(within(access).getByText('Test operator')).toBeInTheDocument()
+ expect(within(access).getByText('Operations team')).toBeInTheDocument()
+}
+
+describe('HostDetailsPage optional subscription throttling', () => {
+ let fetchMock: ReturnType<typeof vi.fn>
+
+ beforeEach(() => {
+ navigation.tab = undefined
+ __resetReadRequestCacheForTests()
+ api.setControlUIReadPrincipal('unit-test-admin', 'admin')
+ vi.clearAllMocks()
+ vi.mocked(api.getHostDetailBundle).mockResolvedValue({
+ host,
+ contexts: [
+ buildContextResource({
+ metadata: { name: 'quota-context', resourceVersion: 'context-rv-1' },
+ spec: { contextId: 'quota-context', mcpServers: ['documents-connector'] },
+ }),
+ ],
+ secrets: [{ name: 'operator-credential', keys: ['openai-api-key'] }],
+ users: [],
+ teams: [],
+ agentUsers: [
+ { id: 'operator', email: '[email protected]', displayName: 'Test operator' },
+ ],
+ agentTeams: [{ id: 'operations', name: 'Operations team' }],
+ } as never)
+ vi.mocked(api.getHost).mockResolvedValue(host)
+ vi.mocked(api.getLlmModels).mockResolvedValue({
+ rows: ['gpt-4o', 'gpt-4.1'].map((model, index) => ({
+ id: `model-${index}`,
+ provider: 'openai',
+ model,
+ enabled: true,
+ stale: false,
+ vendor: 'OpenAI',
+ display_name: null,
+ context_window_tokens: null,
+ created_at: '',
+ updated_at: '',
+ })),
+ })
+ fetchMock = vi.fn((input: RequestInfo | URL) => {
+ if (String(input).endsWith('/capabilities'))
+ return Promise.resolve(
+ json({
+ providers: {
+ 'codex-subscription': { enabled: true },
+ 'grok-subscription': { enabled: true },
+ },
+ })
+ )
+ return Promise.resolve(json({ connections: [] }))
+ })
+ vi.stubGlobal('fetch', fetchMock)
+ })
+
+ afterEach(() => {
+ cleanup()
+ __resetReadRequestCacheForTests()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it('makes no subscription GET for ordinary sections and reuses editor metadata across reopening', async () => {
+ renderPage()
+ await screen.findByRole('heading', { name: 'Agent: Operations agent' })
+ assertLoadedOverview()
+ navigate('Identity')
+ expect(screen.getByRole('region', { name: 'Identity editor' })).toHaveTextContent('quota-agent')
+ navigate('Access')
+ expect(screen.getByRole('region', { name: 'Access editor' })).toHaveTextContent('quota-agent')
+ navigate('Connectors')
+ expect(screen.getByText('documents-connector')).toBeInTheDocument()
+ navigate('Models & creds')
+ expect(screen.getByRole('region', { name: 'LLM configuration summary' })).toHaveTextContent(
+ 'gpt-4o'
+ )
+ expect(fetchMock).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3))
+ await waitFor(() => expect(screen.queryByText('Loading subscription options…')).toBeNull())
+ expect(new Set(fetchMock.mock.calls.map(call => String(call[0]))).size).toBe(3)
+ fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
+ await waitFor(() => expect(screen.queryByText('Loading subscription options…')).toBeNull())
+ expect(fetchMock).toHaveBeenCalledTimes(3)
+ })
+
+ it('keeps the agent, its summaries and an unsaved model draft when the real API throttle shape rejects catalogs', async () => {
+ fetchMock.mockImplementation((input: RequestInfo | URL) => {
+ if (String(input).endsWith('/capabilities'))
+ return Promise.resolve(
+ json({
+ providers: {
+ 'codex-subscription': { enabled: true },
+ 'grok-subscription': { enabled: true },
+ },
+ })
+ )
+ return Promise.resolve(throttle())
+ })
+ renderPage()
+ await screen.findByRole('heading', { name: 'Agent: Operations agent' })
+ assertLoadedOverview()
+ navigate('Models & creds')
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
+ const dialog = screen.getByRole('dialog', { name: 'Edit model configuration' })
+ const alert = await within(dialog).findByRole('alert')
+ expect(alert).toHaveTextContent('Try again in 12 seconds.')
+ expect(alert).not.toHaveTextContent(/^429$/)
+ expect(screen.getByRole('heading', { name: 'Agent: Operations agent' })).toBeInTheDocument()
+
+ const model = within(dialog).getByLabelText(/model/i, { selector: '#llm-primary-model' })
+ fireEvent.click(model)
+ fireEvent.click(screen.getByRole('option', { name: 'gpt-4.1' }))
+ expect(model).toHaveTextContent('gpt-4.1')
+ const requestsBeforeRetry = fetchMock.mock.calls.length
+ fireEvent.click(within(alert).getByRole('button', { name: 'Retry' }))
+ await act(async () => {
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+ expect(fetchMock).toHaveBeenCalledTimes(requestsBeforeRetry)
+ expect(model).toHaveTextContent('gpt-4.1')
+ expect(api.apiSend).not.toHaveBeenCalled()
+
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ navigate('Overview')
+ assertLoadedOverview()
+ navigate('Connectors')
+ expect(screen.getByText('documents-connector')).toBeInTheDocument()
+ navigate('Access')
+ expect(screen.getByRole('region', { name: 'Access editor' })).toHaveTextContent('quota-agent')
+ navigate('Identity')
+ expect(screen.getByRole('region', { name: 'Identity editor' })).toHaveTextContent('quota-agent')
+ expect(api.apiSend).not.toHaveBeenCalled()
+ })
+})
diff --git a/control-ui/components/__tests__/HostWizard.test.tsx b/control-ui/components/__tests__/HostWizard.test.tsx
index 1805ce903..efd37bfe8 100644
--- a/control-ui/components/__tests__/HostWizard.test.tsx
+++ b/control-ui/components/__tests__/HostWizard.test.tsx
@@ -1,5 +1,5 @@
import React from 'react'
-import { afterEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import * as api from '../../lib/api'
import {
@@ -15,6 +15,26 @@ import { buildSecretSummary } from '../../test/fixtures/secretSummary'
import { HostWizard } from '../HostWizard'
import { ToastProvider } from '../Toast'
+const grokCapabilityState = vi.hoisted(() => ({
+ enabled: true,
+ capabilities: {
+ providers: { 'codex-subscription': { enabled: true }, 'grok-subscription': { enabled: true } },
+ },
+}))
+
+vi.mock('../../lib/hooks/useSubscriptionCapabilities', () => ({
+ useSubscriptionCapabilities: () => {
+ grokCapabilityState.capabilities.providers['grok-subscription'].enabled =
+ grokCapabilityState.enabled
+ return {
+ capabilities: grokCapabilityState.capabilities,
+ loading: false,
+ error: null,
+ retry: vi.fn(),
+ }
+ },
+}))
+
/**
* Tests for the HostWizard refactor that closes an authorization gap: admins
* could create agents without selecting any user in the "Access" step
@@ -149,6 +169,10 @@ if (!Element.prototype.scrollIntoView) {
Element.prototype.scrollIntoView = () => {}
}
+beforeEach(() => {
+ grokCapabilityState.enabled = true
+})
+
async function renderWizard(props?: {
mcpServers?: Array<{ metadata?: { name?: string; namespace?: string } }>
existingSecrets?: Array<{ name?: string; keys?: string[] }>
@@ -1341,17 +1365,39 @@ describe('HostWizard — broker-backed Codex authoring', () => {
}, 15_000)
it('hides the Grok provider when the Grok capability probe reports disabled', async () => {
+ grokCapabilityState.enabled = false
vi.mocked(listGrokSubscriptionConnections).mockRejectedValue({ status: 404 })
await renderWizard()
await walkToModelStep({ agentName: 'grok-flag-off' })
- await waitFor(() => {
- expect(listGrokSubscriptionConnections).toHaveBeenCalled()
- })
+ expect(listGrokSubscriptionConnections).not.toHaveBeenCalled()
fireEvent.click(screen.getByLabelText('Provider', { selector: '#llm-primary-provider' }))
expect(screen.getByRole('option', { name: /^OpenAI$/ })).toBeInTheDocument()
expect(screen.queryByRole('option', { name: 'xAI Grok Subscription' })).not.toBeInTheDocument()
}, 15_000)
+ it('loads inventories only at the model step and keeps the provider through a throttle and explicit retry', async () => {
+ mockGrokGrant()
+ vi.mocked(listGrokSubscriptionConnections).mockRejectedValueOnce(
+ Object.assign(new Error('This request limit has been reached. Try again in 12 seconds.'), {
+ status: 429,
+ code: 'rate_limited',
+ retryAfterSeconds: 12,
+ })
+ )
+ await renderWizard()
+ expect(listGrokSubscriptionConnections).not.toHaveBeenCalled()
+ await walkToModelStep({ agentName: 'quota-draft-agent' })
+ const provider = screen.getByLabelText('Provider', { selector: '#llm-primary-provider' })
+ const before = provider.textContent
+ const alert = await screen.findByRole('alert')
+ expect(alert).toHaveTextContent('Try again in 12 seconds.')
+ fireEvent.click(within(alert).getByRole('button', { name: 'Retry' }))
+ await waitFor(() => expect(screen.queryByText(/Try again in 12 seconds/)).toBeNull())
+ expect(provider).toHaveTextContent(before!)
+ fireEvent.click(screen.getByRole('button', { name: /Select LLM Secret/i }))
+ expect(await screen.findByText('Team Grok')).toBeInTheDocument()
+ }, 15_000)
+
it('offers the Grok provider once the Grok capability probe succeeds', async () => {
mockGrokGrant()
await renderWizard()
diff --git a/control-ui/components/__tests__/LlmCatalogFormsGrokGate.test.tsx b/control-ui/components/__tests__/LlmCatalogFormsGrokGate.test.tsx
index cff66ffd4..58512ddbf 100644
--- a/control-ui/components/__tests__/LlmCatalogFormsGrokGate.test.tsx
+++ b/control-ui/components/__tests__/LlmCatalogFormsGrokGate.test.tsx
@@ -1,7 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, render, screen, waitFor, within } from '@testing-library/react'
+import { cleanup, fireEvent, 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'
@@ -10,10 +9,30 @@ import { TokenBudgetForm } from '../TokenBudgetForm'
// 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() }
-})
+const grokCapabilityState = vi.hoisted(() => ({
+ enabled: false as boolean | null,
+ retry: vi.fn(),
+ error: null as Error | null,
+}))
+
+vi.mock('@lib/hooks/useSubscriptionCapabilities', () => ({
+ useSubscriptionCapabilities: () => ({
+ capabilities:
+ grokCapabilityState.enabled === null
+ ? null
+ : {
+ providers: {
+ 'codex-subscription': { enabled: true },
+ 'grok-subscription': { enabled: grokCapabilityState.enabled },
+ },
+ },
+ loading: grokCapabilityState.enabled === null && !grokCapabilityState.error,
+ error:
+ grokCapabilityState.error ??
+ (grokCapabilityState.enabled === null ? new Error('Capability read failed') : null),
+ retry: grokCapabilityState.retry,
+ }),
+}))
vi.mock('@lib/hooks/useLlmAllowedModels', () => ({
useLlmAllowedModels: () => ({ models: [], loading: false, error: '' }),
@@ -84,8 +103,12 @@ function optionValues(select: HTMLElement): string[] {
.map(option => (option as HTMLOptionElement).value)
}
-function flushProbe() {
- return waitFor(() => expect(loadGrokSubscriptionCapability).toHaveBeenCalled())
+async function flushProbe() {
+ await Promise.resolve()
+}
+
+function setGrokCapability(enabled: boolean | null) {
+ grokCapabilityState.enabled = enabled
}
type SelectForm = {
@@ -131,12 +154,14 @@ const selectForms: SelectForm[] = [
]
beforeEach(() => {
- vi.mocked(loadGrokSubscriptionCapability).mockResolvedValue({ enabled: false })
+ setGrokCapability(false)
+ grokCapabilityState.retry.mockReset()
+ grokCapabilityState.error = null
})
afterEach(() => {
cleanup()
- vi.mocked(loadGrokSubscriptionCapability).mockReset()
+ setGrokCapability(false)
})
describe.each(selectForms)('$name Grok capability gate', form => {
@@ -155,7 +180,7 @@ describe.each(selectForms)('$name Grok capability gate', form => {
})
it('fails closed (no Grok option) when the probe throws', async () => {
- vi.mocked(loadGrokSubscriptionCapability).mockRejectedValue(new Error('probe boom'))
+ setGrokCapability(null)
form.renderCreate()
await flushProbe()
await Promise.resolve()
@@ -163,7 +188,7 @@ describe.each(selectForms)('$name Grok capability gate', form => {
})
it('offers grok-subscription once the probe reports enabled', async () => {
- vi.mocked(loadGrokSubscriptionCapability).mockResolvedValue({ enabled: true })
+ setGrokCapability(true)
form.renderCreate()
await waitFor(() => expect(optionValues(providerSelect())).toContain(GROK))
const grokOption = within(providerSelect())
@@ -185,6 +210,47 @@ describe.each(selectForms)('$name Grok capability gate', form => {
expect(grokOptions[0]).toHaveTextContent(/\(disabled\)$/)
expect(select).not.toHaveTextContent(/unrecognized/)
})
+
+ it('keeps saved provider/model drafts during throttle uncertainty and recovers without calling the provider disabled', async () => {
+ const element = () =>
+ form.name === 'LlmModelForm' ? (
+ <LlmModelForm
+ mode="edit"
+ initial={grokModel}
+ saving={false}
+ onSubmit={noop}
+ onCancel={noop}
+ />
+ ) : (
+ <LlmPriceForm
+ mode="edit"
+ initial={grokPrice}
+ saving={false}
+ onSubmit={noop}
+ onCancel={noop}
+ />
+ )
+ setGrokCapability(null)
+ grokCapabilityState.error = Object.assign(new Error('Try again in 12 seconds.'), {
+ status: 429,
+ })
+ const view = render(element())
+ const model = screen.getByLabelText(/^Model\b/, { selector: 'input' })
+ fireEvent.change(model, { target: { value: 'grok-draft' } })
+ expect(providerSelect()).toHaveValue(GROK)
+ expect(providerSelect()).toHaveTextContent('availability unknown')
+ expect(providerSelect()).not.toHaveTextContent('(disabled)')
+ expect(screen.getByRole('alert')).toHaveTextContent('Try again in 12 seconds.')
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ expect(grokCapabilityState.retry).toHaveBeenCalledOnce()
+ setGrokCapability(true)
+ grokCapabilityState.error = null
+ view.rerender(element())
+ expect(providerSelect()).toHaveValue(GROK)
+ expect(model).toHaveValue('grok-draft')
+ expect(providerSelect()).not.toHaveTextContent(/disabled|availability unknown/)
+ expect(screen.queryByRole('alert')).toBeNull()
+ })
})
describe('TokenBudgetForm Grok capability gate', () => {
@@ -202,7 +268,7 @@ describe('TokenBudgetForm Grok capability gate', () => {
})
it('offers grok-subscription in the provider scope once the probe reports enabled', async () => {
- vi.mocked(loadGrokSubscriptionCapability).mockResolvedValue({ enabled: true })
+ setGrokCapability(true)
render(<TokenBudgetForm mode="create" saving={false} onSubmit={noop} onCancel={noop} />)
await waitFor(() => expect(optionValues(addProviderSelect())).toContain(GROK))
})
@@ -222,4 +288,33 @@ describe('TokenBudgetForm Grok capability gate', () => {
expect(screen.getByText('xAI Grok Subscription (disabled)')).toBeInTheDocument()
expect(optionValues(addProviderSelect())).not.toContain(GROK)
})
+
+ it('retains a saved scope and a name draft while capability throttling is unknown, then recovers', async () => {
+ const element = () => (
+ <TokenBudgetForm
+ mode="edit"
+ initial={grokBudget}
+ saving={false}
+ onSubmit={noop}
+ onCancel={noop}
+ />
+ )
+ setGrokCapability(null)
+ grokCapabilityState.error = Object.assign(new Error('Try again in 12 seconds.'), {
+ status: 429,
+ })
+ const view = render(element())
+ fireEvent.change(screen.getByRole('textbox', { name: /^Name\b/ }), {
+ target: { value: 'Unsaved quota draft' },
+ })
+ expect(screen.getByText('xAI Grok Subscription (availability unknown)')).toBeInTheDocument()
+ expect(screen.queryByText('xAI Grok Subscription (disabled)')).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ setGrokCapability(true)
+ grokCapabilityState.error = null
+ view.rerender(element())
+ expect(screen.getByRole('textbox', { name: /^Name\b/ })).toHaveValue('Unsaved quota draft')
+ expect(screen.getByText('xAI Grok Subscription')).toBeInTheDocument()
+ expect(screen.queryByRole('alert')).toBeNull()
+ })
})
diff --git a/control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsx b/control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsx
index ae70472a8..08e857111 100644
--- a/control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsx
+++ b/control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsx
@@ -11,6 +11,7 @@ import {
listWorkflowGrants,
searchPluginWorkloadSdkInvocations,
} from '@lib/api'
+import { listGrokSubscriptionConnections } from '@lib/grokSubscription'
import PluginWorkloadSdkPage from '../../app/plugin-workload-sdk/page'
const mocks = vi.hoisted(() => ({
@@ -41,11 +42,25 @@ vi.mock('@lib/hooks/useLlmAllowedModels', () => ({
}))
const grokCapability = vi.hoisted(() => ({
- load: vi.fn().mockResolvedValue({ enabled: false }),
+ enabled: false as boolean | null,
+ retry: vi.fn(),
}))
-vi.mock('@lib/grokSubscriptionFeature', () => ({
- loadGrokSubscriptionCapability: (...args: unknown[]) => grokCapability.load(...args),
+vi.mock('@lib/hooks/useSubscriptionCapabilities', () => ({
+ useSubscriptionCapabilities: () => ({
+ capabilities:
+ grokCapability.enabled === null
+ ? null
+ : {
+ providers: {
+ 'codex-subscription': { enabled: true },
+ 'grok-subscription': { enabled: grokCapability.enabled },
+ },
+ },
+ error: grokCapability.enabled === null ? new Error('Grok capability read failed') : null,
+ loading: false,
+ retry: grokCapability.retry,
+ }),
}))
vi.mock('@lib/grokSubscription', async importOriginal => {
@@ -130,7 +145,18 @@ function makeGrant(overrides: Partial<PluginWorkloadSdkGrant>): PluginWorkloadSd
}
beforeEach(() => {
- grokCapability.load.mockResolvedValue({ enabled: false })
+ vi.mocked(listGrokSubscriptionConnections)
+ .mockReset()
+ .mockResolvedValue([
+ {
+ connectionKey: 'team-grok',
+ displayName: 'Team Grok',
+ status: 'connected',
+ catalogStatus: 'ready',
+ },
+ ] as never)
+ grokCapability.enabled = false
+ grokCapability.retry.mockReset()
vi.mocked(getAdminUsers).mockResolvedValue({ items: [manualUser] })
vi.mocked(getPluginWorkloadSdkLegacyInventory).mockResolvedValue({
totalPromptBridgeGrants: 0,
@@ -163,6 +189,48 @@ afterEach(() => {
})
describe('Plugin Workload SDK operator page', () => {
+ it('keeps the provider and recipe draft during a subscription throttle and recovers on explicit retry', async () => {
+ grokCapability.enabled = true
+ vi.mocked(listGrokSubscriptionConnections)
+ .mockRejectedValueOnce(
+ Object.assign(new Error('Try again in 12 seconds.'), {
+ status: 429,
+ code: 'rate_limited',
+ retryAfterSeconds: 12,
+ })
+ )
+ .mockResolvedValueOnce([
+ {
+ connectionKey: 'team-grok',
+ displayName: 'Team Grok',
+ status: 'connected',
+ catalogStatus: 'ready',
+ },
+ ] as never)
+ render(<PluginWorkloadSdkPage />)
+ const create = await screen.findByRole('button', { name: 'New grant' })
+ await waitFor(() => expect(create).toBeEnabled())
+ fireEvent.click(create)
+ const dialog = screen.getByRole('dialog', { name: 'New SDK grant' })
+ fireEvent.change(within(dialog).getByRole('textbox', { name: /^Recipe name\b/ }), {
+ target: { value: 'unsaved-recipe' },
+ })
+ const provider = within(dialog).getByRole('combobox', { name: 'Target provider' })
+ fireEvent.change(provider, { target: { value: 'grok-subscription' } })
+ const alert = await within(dialog).findByRole('alert')
+ expect(alert).toHaveTextContent('Try again in 12 seconds.')
+ expect(provider).toHaveValue('grok-subscription')
+ expect(within(dialog).getByRole('textbox', { name: /^Recipe name\b/ })).toHaveValue(
+ 'unsaved-recipe'
+ )
+ fireEvent.click(within(alert).getByRole('button', { name: 'Retry' }))
+ expect(await within(dialog).findByRole('option', { name: /Team Grok/ })).toBeInTheDocument()
+ expect(provider).toHaveValue('grok-subscription')
+ expect(within(dialog).getByRole('textbox', { name: /^Recipe name\b/ })).toHaveValue(
+ 'unsaved-recipe'
+ )
+ await waitFor(() => expect(within(dialog).queryByText('Try again in 12 seconds.')).toBeNull())
+ })
it('does not let a late recipe-grant response overwrite an explicit recipient selection', async () => {
const prefill = createDeferred<{ items: (typeof prefilledUser)[] }>()
vi.mocked(listWorkflowGrants).mockReturnValue(prefill.promise)
@@ -212,7 +280,7 @@ describe('Plugin Workload SDK operator page', () => {
expect(screen.getByText('platform defaults')).toBeInTheDocument()
})
- it('hides grok-subscription until the Grok capability probe succeeds', async () => {
+ it('hides grok-subscription until the shared capability reports it enabled', async () => {
render(<PluginWorkloadSdkPage />)
const newGrant = await screen.findByRole('button', { name: 'New grant' })
await waitFor(() => expect(newGrant).toBeEnabled())
@@ -221,35 +289,27 @@ describe('Plugin Workload SDK operator page', () => {
const provider = await waitFor(() =>
within(dialog).getByRole('combobox', { name: /target provider/i })
)
- // Liveness: the probe ran and resolved disabled, and the picker rendered
- // its other providers, so the absence below is not a pre-probe snapshot.
- await waitFor(() => expect(grokCapability.load).toHaveBeenCalled())
- await act(async () => {
- await grokCapability.load.mock.results.at(-1)?.value
- })
expect(
within(provider).getByRole('option', { name: /OpenAI Codex Subscription/i })
).toBeInTheDocument()
expect(within(provider).queryByRole('option', { name: /xAI Grok Subscription/i })).toBeNull()
- expect(within(dialog).queryByText(/Could not load Grok subscriptions/)).toBeNull()
+ expect(within(dialog).queryByText(/Provider availability could not be checked/)).toBeNull()
})
- it('surfaces a non-disabled Grok capability probe error and keeps Grok hidden', async () => {
- grokCapability.load.mockRejectedValue(
- Object.assign(new Error('Grok capability probe failed'), { status: 500 })
- )
+ it('surfaces a shared capability read error and keeps Grok hidden', async () => {
+ grokCapability.enabled = null
render(<PluginWorkloadSdkPage />)
const newGrant = await screen.findByRole('button', { name: 'New grant' })
await waitFor(() => expect(newGrant).toBeEnabled())
fireEvent.click(newGrant)
const dialog = await screen.findByRole('dialog', { name: 'New SDK grant' })
- expect(await within(dialog).findByText('Grok capability probe failed')).toBeInTheDocument()
+ expect(await within(dialog).findByText(/Grok capability read failed/)).toBeInTheDocument()
const provider = within(dialog).getByRole('combobox', { name: /target provider/i })
expect(within(provider).queryByRole('option', { name: /xAI Grok Subscription/i })).toBeNull()
})
it('offers Grok grants in the SDK picker when the Grok flag is on', async () => {
- grokCapability.load.mockResolvedValue({ enabled: true })
+ grokCapability.enabled = true
render(<PluginWorkloadSdkPage />)
const newGrant = await screen.findByRole('button', { name: 'New grant' })
await waitFor(() => expect(newGrant).toBeEnabled())
diff --git a/control-ui/components/__tests__/RecipeEditor.rateLimit.test.tsx b/control-ui/components/__tests__/RecipeEditor.rateLimit.test.tsx
new file mode 100644
index 000000000..872d1cc56
--- /dev/null
+++ b/control-ui/components/__tests__/RecipeEditor.rateLimit.test.tsx
@@ -0,0 +1,94 @@
+import React from 'react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { listCodexSubscriptionConnections } from '@lib/codexSubscription'
+import { listGrokSubscriptionConnections } from '@lib/grokSubscription'
+import { RecipeEditor } from '../RecipeEditor'
+import { ToastProvider } from '../Toast'
+
+vi.mock('@lib/api', async importOriginal => {
+ const actual = await importOriginal<typeof import('@lib/api')>()
+ return {
+ ...actual,
+ getControlUINamespaces: vi
+ .fn()
+ .mockResolvedValue({ sandbox: 'sandbox-recipes', mcpServer: 'mcp-server' }),
+ }
+})
+vi.mock('@lib/codexSubscription', async importOriginal => {
+ const actual = await importOriginal<typeof import('@lib/codexSubscription')>()
+ return { ...actual, listCodexSubscriptionConnections: vi.fn() }
+})
+vi.mock('@lib/grokSubscription', async importOriginal => {
+ const actual = await importOriginal<typeof import('@lib/grokSubscription')>()
+ return { ...actual, listGrokSubscriptionConnections: vi.fn() }
+})
+vi.mock('@components/WorkflowAccessPanel', () => ({
+ WorkflowAccessPanel: () => <section aria-label="Workflow access">Loaded access</section>,
+}))
+
+const recipe = {
+ apiVersion: 'clerum.io/v1alpha1',
+ kind: 'WorkflowRecipe',
+ metadata: {
+ name: 'quota-recipe',
+ namespace: 'sandbox-recipes',
+ resourceVersion: 'recipe-rv-1',
+ annotations: { 'clerum.io/subscription-connection-ref': 'team-codex' },
+ },
+ spec: {
+ agent: { provider: 'codex-subscription', model: 'gpt-5.1' },
+ steps: [{ id: 'summarize', instruction: 'Summarize the report.' }],
+ workloads: [],
+ triggers: { onDemand: {} },
+ },
+}
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+})
+
+describe('RecipeEditor optional subscription throttling', () => {
+ it('loads only the selected broker at review and keeps a saved grant through throttling and retry', async () => {
+ vi.mocked(listCodexSubscriptionConnections)
+ .mockRejectedValueOnce(
+ Object.assign(new Error('Try again in 12 seconds.'), {
+ status: 429,
+ code: 'rate_limited',
+ retryAfterSeconds: 12,
+ })
+ )
+ .mockResolvedValueOnce([
+ {
+ connectionKey: 'team-codex',
+ displayName: 'Team subscription',
+ status: 'connected',
+ catalogStatus: 'ready',
+ },
+ ] as never)
+ render(
+ <ToastProvider>
+ <RecipeEditor initial={recipe as never} onSaved={vi.fn()} onCancel={vi.fn()} />
+ </ToastProvider>
+ )
+ expect(listCodexSubscriptionConnections).not.toHaveBeenCalled()
+ expect(listGrokSubscriptionConnections).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'Review manifest' }))
+ const review = await screen.findByRole('button', { name: 'Apply defaults' })
+ expect(review).toBeEnabled()
+ fireEvent.click(review)
+ const access = await screen.findByRole('button', { name: /^4Access & deploy/ })
+ await waitFor(() => expect(access).toBeEnabled())
+ fireEvent.click(access)
+ const panel = await screen.findByTestId('codex-recipe-grant')
+ const alert = await within(panel).findByRole('alert')
+ expect(alert).toHaveTextContent('Try again in 12 seconds.')
+ expect(within(panel).getByText('team-codex')).toBeInTheDocument()
+ expect(within(panel).queryByText('team-codex (unavailable)')).toBeNull()
+ expect(listGrokSubscriptionConnections).not.toHaveBeenCalled()
+ fireEvent.click(within(alert).getByRole('button', { name: 'Retry' }))
+ expect(await within(panel).findByText('Team subscription')).toBeInTheDocument()
+ await waitFor(() => expect(within(panel).queryByRole('alert')).toBeNull())
+ })
+})
diff --git a/control-ui/lib/__tests__/apiErrors.test.ts b/control-ui/lib/__tests__/apiErrors.test.ts
index c090a9f6c..74820f069 100644
--- a/control-ui/lib/__tests__/apiErrors.test.ts
+++ b/control-ui/lib/__tests__/apiErrors.test.ts
@@ -1,5 +1,14 @@
-import { describe, expect, it, vi } from 'vitest'
-import { formatApiError, handleControlUIUnauthorized, setGlobalAuthErrorHandler } from '../api'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ apiGet,
+ apiSend,
+ formatApiError,
+ handleControlUIUnauthorized,
+ retryAfterSeconds,
+ setControlUIReadPrincipal,
+ setGlobalAuthErrorHandler,
+} from '../api'
+import { __resetReadRequestCacheForTests } from '../readRequestCache'
describe('handleControlUIUnauthorized', () => {
it('clears the legacy browser token and invokes the registered session-expiry handler', () => {
@@ -38,4 +47,121 @@ describe('formatApiError', () => {
},
})
})
+
+ it('keeps a server 429 message and numeric retry timing when statusText is empty', () => {
+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'))
+ const text = JSON.stringify({
+ error: 'Too Many Requests',
+ code: 'rate_limited',
+ message: 'This request limit has been reached. Try again in 12 seconds.',
+ retryAfterSeconds: 12,
+ })
+ const error = formatApiError(
+ new Response(text, {
+ status: 429,
+ statusText: '',
+ headers: { 'content-type': 'application/json', 'retry-after': '12' },
+ }),
+ text
+ ) as Error & {
+ retryAfterSeconds?: number
+ retryAtMs?: number
+ code?: string
+ body?: Record<string, unknown>
+ }
+
+ expect(error.message).toBe('This request limit has been reached. Try again in 12 seconds.')
+ expect(error.status).toBe(429)
+ expect(error.code).toBe('rate_limited')
+ expect(error.body).toEqual({
+ error: 'Too Many Requests',
+ code: 'rate_limited',
+ message: 'This request limit has been reached. Try again in 12 seconds.',
+ retryAfterSeconds: 12,
+ })
+ expect(error.retryAfterSeconds).toBe(12)
+ expect(error.retryAtMs).toBe(Date.parse('2026-01-01T00:00:12.000Z'))
+ })
+
+ it.each([
+ ['numeric header', { header: '17', body: '{}' }, 17],
+ ['HTTP-date header', { header: 'Wed, 01 Jan 2026 00:00:30 GMT', body: '{}' }, 30],
+ ['body fallback', { header: 'invalid', body: '{"retryAfterSeconds":9}' }, 9],
+ ] as const)('parses a useful 429 retry interval from %s', (_name, payload, expectedSeconds) => {
+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'))
+ const headers = new Headers()
+ headers.set('retry-after', payload.header)
+ expect(retryAfterSeconds(headers, JSON.parse(payload.body) as Record<string, unknown>)).toBe(
+ expectedSeconds
+ )
+ })
+
+ it('uses bounded 429 copy when timing is missing or invalid', () => {
+ for (const header of ['', 'zero', '0', '-1', 'Wed, 01 Jan 2025 00:00:00 GMT']) {
+ const error = formatApiError(
+ new Response(JSON.stringify({ error: 'Too Many Requests' }), {
+ status: 429,
+ statusText: '',
+ headers: { 'retry-after': header },
+ }),
+ JSON.stringify({ error: 'Too Many Requests' })
+ ) as Error & { retryAfterSeconds?: number; retryAtMs?: number }
+ expect(error.message).toBe('Too many requests. Try again later.')
+ expect(error.retryAfterSeconds).toBeUndefined()
+ expect(error.retryAtMs).toBeUndefined()
+ }
+ })
+
+ it('attaches producer 429 metadata from apiGet without changing conflict formatting', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ message: 'Slow down', retryAfterSeconds: 4 }), {
+ status: 429,
+ statusText: '',
+ headers: { 'retry-after': '4' },
+ })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ const error = (await apiGet('/api/v1/admin/example').catch(reason => reason)) as Error & {
+ status?: number
+ retryAfterSeconds?: number
+ }
+
+ expect(error.message).toBe('Slow down')
+ expect(error.status).toBe(429)
+ expect(error.retryAfterSeconds).toBe(4)
+ expect(fetchMock).toHaveBeenCalledOnce()
+ })
+
+ it('attaches 429 metadata from apiSend and never automatically replays the write', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ message: 'Write limit reached', retryAfterSeconds: 3 }), {
+ status: 429,
+ statusText: '',
+ headers: { 'retry-after': '3' },
+ })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ await expect(apiSend('POST', '/api/v1/admin/example', { value: 1 })).rejects.toMatchObject({
+ message: 'Write limit reached',
+ status: 429,
+ retryAfterSeconds: 3,
+ })
+ expect(fetchMock).toHaveBeenCalledOnce()
+ })
+})
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'))
+ __resetReadRequestCacheForTests()
+ setControlUIReadPrincipal('admin-test', 'admin')
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ __resetReadRequestCacheForTests()
})
diff --git a/control-ui/lib/__tests__/controlApiProxyRoute.test.ts b/control-ui/lib/__tests__/controlApiProxyRoute.test.ts
index 14ddb8e63..44661b12b 100644
--- a/control-ui/lib/__tests__/controlApiProxyRoute.test.ts
+++ b/control-ui/lib/__tests__/controlApiProxyRoute.test.ts
@@ -70,6 +70,36 @@ describe('control-ui control-api proxy route', () => {
await expect(res.json()).resolves.toEqual({ items: [] })
})
+ it('forwards 429 status, body, and Retry-After metadata unchanged', async () => {
+ const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(JSON.stringify({ message: 'Slow down', retryAfterSeconds: 7 }), {
+ status: 429,
+ statusText: '',
+ headers: {
+ 'content-type': 'application/json',
+ 'retry-after': '7',
+ 'x-ratelimit-remaining': '0',
+ },
+ })
+ )
+
+ const req = new NextRequest('http://localhost:3000/control-api/api/v1/admin/llm/providers', {
+ method: 'GET',
+ })
+ const res = await GET(req, {
+ params: { path: ['api', 'v1', 'admin', 'llm', 'providers'] },
+ })
+
+ expect(res.status).toBe(429)
+ expect(res.headers.get('retry-after')).toBe('7')
+ expect(res.headers.get('x-ratelimit-remaining')).toBe('0')
+ await expect(res.json()).resolves.toEqual({
+ message: 'Slow down',
+ retryAfterSeconds: 7,
+ })
+ expect(fetchMock).toHaveBeenCalledOnce()
+ })
+
it('preserves encoded slashes in scoped Marketplace entry names', async () => {
const fetchMock = vi
.spyOn(globalThis, 'fetch')
diff --git a/control-ui/lib/__tests__/grokSubscriptionFeature.test.ts b/control-ui/lib/__tests__/grokSubscriptionFeature.test.ts
index e8eea945c..3aeab13dc 100644
--- a/control-ui/lib/__tests__/grokSubscriptionFeature.test.ts
+++ b/control-ui/lib/__tests__/grokSubscriptionFeature.test.ts
@@ -1,38 +1,40 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { isAllowedGrokVerificationUri, listGrokSubscriptionConnections } from '../grokSubscription'
+import { isAllowedGrokVerificationUri } from '../grokSubscription'
import { loadGrokSubscriptionCapability } from '../grokSubscriptionFeature'
+import { loadSubscriptionCapabilities } from '../subscriptionCapabilities'
-vi.mock('../grokSubscription', async importOriginal => {
- const actual = await importOriginal<typeof import('../grokSubscription')>()
- return {
- ...actual,
- listGrokSubscriptionConnections: vi.fn(),
- }
-})
+vi.mock('../subscriptionCapabilities', () => ({
+ loadSubscriptionCapabilities: vi.fn(),
+}))
afterEach(() => {
vi.clearAllMocks()
})
describe('loadGrokSubscriptionCapability', () => {
- it('is enabled only after the keyed connections list succeeds', async () => {
- vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([])
+ it('reads only the shared Grok integration flag', async () => {
+ vi.mocked(loadSubscriptionCapabilities).mockResolvedValue({
+ providers: {
+ 'codex-subscription': { enabled: false },
+ 'grok-subscription': { enabled: true },
+ },
+ })
await expect(loadGrokSubscriptionCapability()).resolves.toEqual({ enabled: true })
})
- it('maps a 404 or a disabled code to the disabled capability', async () => {
- vi.mocked(listGrokSubscriptionConnections).mockRejectedValueOnce({ status: 404 })
- await expect(loadGrokSubscriptionCapability()).resolves.toEqual({ enabled: false })
- vi.mocked(listGrokSubscriptionConnections).mockRejectedValueOnce({
- status: 403,
- code: 'disabled',
+ it('reports disabled when the integration flag is false', async () => {
+ vi.mocked(loadSubscriptionCapabilities).mockResolvedValue({
+ providers: {
+ 'codex-subscription': { enabled: true },
+ 'grok-subscription': { enabled: false },
+ },
})
await expect(loadGrokSubscriptionCapability()).resolves.toEqual({ enabled: false })
})
- it('rethrows non-disabled probe failures instead of reporting the flag as off', async () => {
- const failure = Object.assign(new Error('control-api unavailable'), { status: 500 })
- vi.mocked(listGrokSubscriptionConnections).mockRejectedValueOnce(failure)
+ it('rethrows transient discovery failures instead of reporting the flag as off', async () => {
+ const failure = Object.assign(new Error('capability read unavailable'), { status: 429 })
+ vi.mocked(loadSubscriptionCapabilities).mockRejectedValueOnce(failure)
await expect(loadGrokSubscriptionCapability()).rejects.toBe(failure)
})
})
@@ -48,11 +50,6 @@ describe('isAllowedGrokVerificationUri', () => {
expect(isAllowedGrokVerificationUri('https://accounts.x.ai/oauth2/device?user_code=ABCD')).toBe(
true
)
- expect(isAllowedGrokVerificationUri('http://accounts.x.ai/oauth2/device')).toBe(false)
- expect(isAllowedGrokVerificationUri('https://accounts.x.ai.evil.example/oauth2/device')).toBe(
- false
- )
- expect(isAllowedGrokVerificationUri('https://evil.x.ai/oauth2/device')).toBe(false)
})
it('rejects other schemes, hosts and look-alike hosts', () => {
diff --git a/control-ui/lib/__tests__/readRequestCache.test.ts b/control-ui/lib/__tests__/readRequestCache.test.ts
new file mode 100644
index 000000000..1cfb82076
--- /dev/null
+++ b/control-ui/lib/__tests__/readRequestCache.test.ts
@@ -0,0 +1,537 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ apiGet,
+ apiSend,
+ clearAdminAuthToken,
+ loginControlUI,
+ setControlUIReadPrincipal,
+ setGlobalAuthErrorHandler,
+} from '../api'
+import { patchCodexCatalogModel } from '../codexSubscription'
+import {
+ __resetReadRequestCacheForTests,
+ getReadRequestCacheEntry,
+ getReadRequestPrincipal,
+ invalidateReadRequestCache,
+ setReadRequestCacheEntry,
+} from '../readRequestCache'
+
+const metadataOptions = { metadataRead: 'subscription-capabilities' } as const
+
+function success(value: unknown): Response {
+ return new Response(JSON.stringify(value), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+}
+
+function throttled(retryAfterSeconds = 12): Response {
+ return new Response(
+ JSON.stringify({
+ error: 'Too Many Requests',
+ code: 'rate_limited',
+ message: `This request limit has been reached. Try again in ${retryAfterSeconds} seconds.`,
+ retryAfterSeconds,
+ }),
+ {
+ status: 429,
+ statusText: '',
+ headers: { 'content-type': 'application/json', 'retry-after': String(retryAfterSeconds) },
+ }
+ )
+}
+
+describe('bounded metadata read reuse', () => {
+ let fetchMock: ReturnType<typeof vi.fn>
+
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'))
+ __resetReadRequestCacheForTests()
+ setControlUIReadPrincipal('admin-one', 'admin')
+ fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ })
+
+ afterEach(() => {
+ __resetReadRequestCacheForTests()
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ setGlobalAuthErrorHandler(undefined)
+ })
+
+ it('deduplicates simultaneous metadata reads and expires the result after thirty seconds', async () => {
+ fetchMock.mockReturnValue(new Promise(resolve => resolve(success({ value: 'first' }))))
+ const first = apiGet('/api/v1/admin/metadata', {}, metadataOptions)
+ const second = apiGet('/api/v1/admin/metadata', {}, metadataOptions)
+
+ await expect(first).resolves.toEqual({ value: 'first' })
+ await expect(second).resolves.toEqual({ value: 'first' })
+ expect(fetchMock).toHaveBeenCalledOnce()
+
+ fetchMock.mockClear()
+ fetchMock.mockReturnValue(new Promise(resolve => resolve(success({ value: 'second' }))))
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ value: 'first',
+ })
+ expect(fetchMock).not.toHaveBeenCalled()
+
+ await vi.advanceTimersByTimeAsync(30_001)
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ value: 'second',
+ })
+ expect(fetchMock).toHaveBeenCalledOnce()
+ })
+
+ it('forces a metadata refresh past the cache and invalidates after a relevant mutation', async () => {
+ fetchMock
+ .mockResolvedValueOnce(success({ revision: 1 }))
+ .mockResolvedValueOnce(success({ revision: 2 }))
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ revision: 1,
+ })
+ await expect(
+ apiGet('/api/v1/admin/metadata', {}, { ...metadataOptions, refresh: true })
+ ).resolves.toEqual({ revision: 2 })
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+
+ fetchMock.mockResolvedValueOnce(success({ models: [] }))
+ await patchCodexCatalogModel('team-subscription', 'model-one', true)
+ fetchMock.mockResolvedValueOnce(success({ revision: 3 }))
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ revision: 3,
+ })
+ expect(fetchMock).toHaveBeenCalledTimes(4)
+ })
+
+ it('bounds the metadata cache to one hundred twenty-eight entries', async () => {
+ for (let index = 0; index <= 128; index += 1) {
+ fetchMock.mockResolvedValueOnce(success({ index }))
+ await apiGet(`/api/v1/admin/metadata/${index}`, {}, metadataOptions)
+ }
+ expect(fetchMock).toHaveBeenCalledTimes(129)
+
+ fetchMock.mockClear()
+ fetchMock.mockResolvedValueOnce(success({ index: 'fresh-first' }))
+ await expect(apiGet('/api/v1/admin/metadata/0', {}, metadataOptions)).resolves.toEqual({
+ index: 'fresh-first',
+ })
+ expect(fetchMock).toHaveBeenCalledOnce()
+ })
+
+ it('shares one cooldown and at most one recovery after Retry-After', async () => {
+ fetchMock.mockImplementationOnce(() => Promise.resolve(throttled(12)))
+ const firstError = (await apiGet('/api/v1/admin/throttled', {}, metadataOptions).catch(
+ reason => reason
+ )) as Error & { retryAfterSeconds?: number }
+
+ expect(firstError.message).toBe('This request limit has been reached. Try again in 12 seconds.')
+ expect(firstError.retryAfterSeconds).toBe(12)
+
+ const immediateError = (await apiGet('/api/v1/admin/throttled', {}, metadataOptions).catch(
+ reason => reason
+ )) as Error
+ expect(immediateError).toBe(firstError)
+ expect(fetchMock).toHaveBeenCalledOnce()
+
+ fetchMock.mockImplementationOnce(() => Promise.resolve(throttled(12)))
+ await vi.advanceTimersByTimeAsync(12_000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+
+ await vi.advanceTimersByTimeAsync(24_000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('shares the denied subscription-read quota across URLs and forced refreshes', async () => {
+ fetchMock.mockResolvedValueOnce(throttled(12))
+ const error = await apiGet('/api/v1/admin/capabilities', {}, metadataOptions).catch(
+ reason => reason
+ )
+ await expect(
+ apiGet(
+ '/api/v1/admin/connections',
+ {},
+ {
+ metadataRead: 'subscription-connections',
+ refresh: true,
+ }
+ )
+ ).rejects.toBe(error)
+ await expect(
+ apiGet(
+ '/api/v1/admin/models',
+ {},
+ {
+ metadataRead: 'subscription-model-catalog',
+ }
+ )
+ ).rejects.toBe(error)
+ expect(fetchMock).toHaveBeenCalledOnce()
+
+ let resolveRecovery!: (response: Response) => void
+ fetchMock.mockImplementationOnce(
+ () =>
+ new Promise<Response>(resolve => {
+ resolveRecovery = resolve
+ })
+ )
+ await vi.advanceTimersByTimeAsync(12_000)
+ const connections = apiGet(
+ '/api/v1/admin/connections',
+ {},
+ {
+ metadataRead: 'subscription-connections',
+ }
+ )
+ const models = apiGet(
+ '/api/v1/admin/models',
+ {},
+ {
+ metadataRead: 'subscription-model-catalog',
+ }
+ )
+ await vi.advanceTimersByTimeAsync(0)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+
+ fetchMock
+ .mockResolvedValueOnce(success({ connections: [] }))
+ .mockResolvedValueOnce(success({ models: [] }))
+ resolveRecovery(success({ providers: {} }))
+ await expect(connections).resolves.toEqual({ connections: [] })
+ await expect(models).resolves.toEqual({ models: [] })
+ expect(fetchMock).toHaveBeenCalledTimes(4)
+ })
+
+ it('deduplicates signalled readers while cancelling only the abandoned subscriber', async () => {
+ let resolveFetch!: (response: Response) => void
+ let physicalSignal: AbortSignal | undefined
+ fetchMock.mockImplementation((_url: unknown, init: RequestInit) => {
+ physicalSignal = init.signal ?? undefined
+ return new Promise<Response>(resolve => {
+ resolveFetch = resolve
+ })
+ })
+ const firstController = new AbortController()
+ const secondController = new AbortController()
+ const first = apiGet(
+ '/api/v1/admin/metadata',
+ {},
+ { ...metadataOptions, signal: firstController.signal }
+ )
+ const second = apiGet(
+ '/api/v1/admin/metadata',
+ {},
+ { ...metadataOptions, signal: secondController.signal }
+ )
+ const cancelled = expect(first).rejects.toMatchObject({ name: 'AbortError' })
+ firstController.abort()
+ await cancelled
+ expect(fetchMock).toHaveBeenCalledOnce()
+ expect(physicalSignal?.aborted).toBe(false)
+ resolveFetch(success({ stillVisible: true }))
+ await expect(second).resolves.toEqual({ stillVisible: true })
+ })
+
+ it('starts a fresh GET when a new mount arrives just after the last old subscriber cancelled', async () => {
+ const old = new AbortController()
+ fetchMock
+ .mockImplementationOnce(
+ (_url: unknown, init: RequestInit) =>
+ new Promise((_resolve, reject) => {
+ init.signal!.addEventListener('abort', () =>
+ reject(new DOMException('Cancelled', 'AbortError'))
+ )
+ })
+ )
+ .mockResolvedValueOnce(success({ revision: 'fresh-mount' }))
+ const oldRead = apiGet('/api/v1/admin/metadata', {}, { ...metadataOptions, signal: old.signal })
+ const rejected = expect(oldRead).rejects.toMatchObject({ name: 'AbortError' })
+ old.abort()
+ const freshRead = apiGet(
+ '/api/v1/admin/metadata',
+ {},
+ { ...metadataOptions, signal: new AbortController().signal }
+ )
+ await rejected
+ await expect(freshRead).resolves.toEqual({ revision: 'fresh-mount' })
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('cancels the physical GET after its last subscriber leaves and cancels an unmounted recovery', async () => {
+ const controller = new AbortController()
+ let physicalSignal!: AbortSignal
+ fetchMock.mockImplementationOnce((_url: unknown, init: RequestInit) => {
+ physicalSignal = init.signal!
+ return new Promise((_resolve, reject) => {
+ physicalSignal.addEventListener('abort', () =>
+ reject(new DOMException('Cancelled', 'AbortError'))
+ )
+ })
+ })
+ const pending = apiGet(
+ '/api/v1/admin/metadata',
+ {},
+ { ...metadataOptions, signal: controller.signal }
+ )
+ const rejected = expect(pending).rejects.toMatchObject({ name: 'AbortError' })
+ controller.abort()
+ await rejected
+ expect(physicalSignal.aborted).toBe(true)
+
+ const mounted = new AbortController()
+ fetchMock.mockResolvedValueOnce(throttled(12))
+ await expect(
+ apiGet(
+ '/api/v1/admin/capabilities',
+ {},
+ {
+ ...metadataOptions,
+ signal: mounted.signal,
+ }
+ )
+ ).rejects.toMatchObject({ status: 429 })
+ mounted.abort()
+ await vi.advanceTimersByTimeAsync(24_000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not result-cache general reads or automatically replay mutations', async () => {
+ fetchMock
+ .mockResolvedValueOnce(success({ revision: 1 }))
+ .mockResolvedValueOnce(success({ revision: 2 }))
+ await expect(apiGet('/api/v1/admin/hosts')).resolves.toEqual({ revision: 1 })
+ await expect(apiGet('/api/v1/admin/hosts')).resolves.toEqual({ revision: 2 })
+ fetchMock.mockResolvedValueOnce(throttled(12))
+ await expect(apiSend('POST', '/api/v1/admin/explicit-action')).rejects.toMatchObject({
+ status: 429,
+ })
+ await vi.advanceTimersByTimeAsync(24_000)
+ expect(fetchMock).toHaveBeenCalledTimes(3)
+ })
+
+ it('keeps a read-family cooldown after a successful independent subscription mutation', async () => {
+ fetchMock.mockResolvedValueOnce(throttled(12))
+ const denied = await apiGet('/api/v1/admin/capabilities', {}, metadataOptions).catch(
+ reason => reason
+ )
+ fetchMock.mockResolvedValueOnce(success({ models: [] }))
+ await patchCodexCatalogModel('team-subscription', 'model-one', true)
+ await expect(
+ apiGet(
+ '/api/v1/admin/connections',
+ {},
+ { metadataRead: 'subscription-connections', refresh: true }
+ )
+ ).rejects.toBe(denied)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('uses the latest family deadline and keeps recovery while another denied reader is still mounted', async () => {
+ const firstController = new AbortController()
+ const secondController = new AbortController()
+ fetchMock.mockResolvedValueOnce(throttled(12)).mockResolvedValueOnce(throttled(20))
+ await Promise.all([
+ apiGet(
+ '/api/v1/admin/capabilities',
+ {},
+ { ...metadataOptions, signal: firstController.signal }
+ ).catch(() => undefined),
+ apiGet(
+ '/api/v1/admin/connections',
+ {},
+ { metadataRead: 'subscription-connections', signal: secondController.signal }
+ ).catch(() => undefined),
+ ])
+ firstController.abort()
+ fetchMock.mockResolvedValueOnce(success({ recovered: true }))
+ await vi.advanceTimersByTimeAsync(12_000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ await vi.advanceTimersByTimeAsync(8_000)
+ expect(fetchMock).toHaveBeenCalledTimes(3)
+ await expect(apiGet('/api/v1/admin/capabilities', {}, metadataOptions)).resolves.toEqual({
+ recovered: true,
+ })
+ })
+
+ it('makes only one recovery when throttle timing is unavailable', async () => {
+ const noTiming = () =>
+ new Response(JSON.stringify({ error: 'Too Many Requests' }), { status: 429 })
+ fetchMock.mockImplementation(() => Promise.resolve(noTiming()))
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).rejects.toMatchObject({
+ status: 429,
+ })
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('clears metadata on an epoch change and broadcasts only a non-sensitive invalidation', async () => {
+ const listener = new BroadcastChannel('control-ui-read-metadata-invalidation')
+ const received: unknown[] = []
+ listener.onmessage = event => received.push(event.data)
+
+ fetchMock.mockResolvedValueOnce(success({ principal: 'one' }))
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ principal: 'one',
+ })
+
+ clearAdminAuthToken()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(received).toEqual([{ type: 'session-invalidation' }])
+ expect(JSON.stringify(received)).not.toContain('admin-one')
+
+ setControlUIReadPrincipal('admin-one', 'admin')
+ setControlUIReadPrincipal('admin-two', 'admin')
+ await vi.advanceTimersByTimeAsync(0)
+ expect(received).toEqual([{ type: 'session-invalidation' }, { type: 'session-invalidation' }])
+
+ fetchMock.mockResolvedValueOnce(success({ principal: 'two' }))
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ principal: 'two',
+ })
+ listener.close()
+ })
+
+ it('invalidates on a remote session change without rebroadcast or caching an unverified identity', async () => {
+ const remoteTab = new BroadcastChannel('control-ui-read-metadata-invalidation')
+ const rebroadcasts: unknown[] = []
+ remoteTab.onmessage = event => rebroadcasts.push(event.data)
+ fetchMock.mockResolvedValueOnce(success({ revision: 'old-tab' }))
+ await apiGet('/api/v1/admin/metadata', {}, metadataOptions)
+ remoteTab.postMessage({ type: 'session-invalidation' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(getReadRequestPrincipal()).toBeNull()
+ expect(rebroadcasts).toEqual([])
+ fetchMock
+ .mockResolvedValueOnce(success({ revision: 'new-tab' }))
+ .mockResolvedValueOnce(success({ revision: 'fresh' }))
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ revision: 'new-tab',
+ })
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ revision: 'fresh',
+ })
+ expect(fetchMock).toHaveBeenCalledTimes(3)
+ remoteTab.close()
+ })
+
+ it('clears cached reads on successful login even when the principal is unchanged', async () => {
+ fetchMock.mockResolvedValueOnce(success({ revision: 1 }))
+ await apiGet('/api/v1/admin/metadata', {}, metadataOptions)
+ fetchMock.mockResolvedValueOnce(success({ me: { id: 'admin-one', role: 'admin' } }))
+ await loginControlUI('operator', 'unit-test-password')
+ setControlUIReadPrincipal('admin-one', 'admin')
+ fetchMock.mockResolvedValueOnce(success({ revision: 2 }))
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ revision: 2,
+ })
+ })
+
+ it('invalidates a scope change for the same verified principal', async () => {
+ fetchMock.mockResolvedValueOnce(success({ scope: 'first' }))
+ await apiGet('/api/v1/admin/metadata', {}, metadataOptions)
+ setControlUIReadPrincipal('admin-one', 'admin:second-scope')
+ fetchMock.mockResolvedValueOnce(success({ scope: 'second' }))
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ scope: 'second',
+ })
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('binds browser metadata to the API origin instead of reusing another origin response', async () => {
+ fetchMock.mockResolvedValueOnce(success({ origin: 'first' }))
+ await apiGet('/api/v1/admin/metadata', {}, metadataOptions)
+ const originalWindow = globalThis.window
+ vi.stubGlobal('window', { location: { origin: 'https://other-control.example.test' } })
+ try {
+ fetchMock.mockResolvedValueOnce(success({ origin: 'second' }))
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ origin: 'second',
+ })
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ } finally {
+ vi.stubGlobal('window', originalWindow)
+ }
+ })
+
+ it('fences old errors and 401 responses before they can invalidate the new principal', async () => {
+ let resolveFetch!: (response: Response) => void
+ fetchMock.mockImplementationOnce(
+ () =>
+ new Promise<Response>(resolve => {
+ resolveFetch = resolve
+ })
+ )
+ const authExpired = vi.fn()
+ setGlobalAuthErrorHandler(authExpired)
+ const oldRead = apiGet('/api/v1/admin/metadata', {}, metadataOptions)
+ const rejected = expect(oldRead).rejects.toMatchObject({ name: 'AuthExpiredError' })
+ setControlUIReadPrincipal('admin-two', 'admin')
+ resolveFetch(new Response('{}', { status: 401 }))
+ await rejected
+ expect(authExpired).not.toHaveBeenCalled()
+ expect(getReadRequestPrincipal()?.principalId).toBe('admin-two')
+ })
+
+ it('fences a delayed response body and a metadata mutation before result delivery', async () => {
+ let resolveBody!: (value: string) => void
+ const response = success({})
+ vi.spyOn(response, 'text').mockImplementation(
+ () =>
+ new Promise(resolve => {
+ resolveBody = resolve
+ })
+ )
+ fetchMock.mockResolvedValueOnce(response)
+ const pending = apiGet('/api/v1/admin/metadata', {}, metadataOptions)
+ await vi.advanceTimersByTimeAsync(0)
+ invalidateReadRequestCache()
+ const rejected = expect(pending).rejects.toMatchObject({ name: 'AbortError' })
+ resolveBody(JSON.stringify({ revision: 'before-mutation' }))
+ await rejected
+ fetchMock.mockResolvedValueOnce(success({ revision: 'after-mutation' }))
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ revision: 'after-mutation',
+ })
+ })
+
+ it('rejects a late old-principal response before caching or delivering it to the new identity', async () => {
+ let resolveFetch!: (response: Response) => void
+ fetchMock.mockReturnValue(
+ new Promise<Response>(resolve => {
+ resolveFetch = resolve
+ })
+ )
+ const staleRead = apiGet('/api/v1/admin/metadata', {}, metadataOptions)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(fetchMock).toHaveBeenCalledOnce()
+
+ setControlUIReadPrincipal('admin-two', 'admin')
+ resolveFetch(success({ principal: 'one' }))
+ await expect(staleRead).rejects.toMatchObject({ name: 'AuthExpiredError' })
+
+ fetchMock.mockResolvedValueOnce(success({ principal: 'two' }))
+ await expect(apiGet('/api/v1/admin/metadata', {}, metadataOptions)).resolves.toEqual({
+ principal: 'two',
+ })
+ })
+
+ it('does not retain or deduplicate opt-in metadata during SSR execution', async () => {
+ const originalWindow = globalThis.window
+ vi.stubGlobal('window', undefined)
+ try {
+ setReadRequestCacheEntry('ssr-key', { value: 'must-not-cache' }, 30_000)
+ expect(getReadRequestCacheEntry('ssr-key')).toBeUndefined()
+ fetchMock
+ .mockResolvedValueOnce(success({ principal: 'server-one' }))
+ .mockResolvedValueOnce(success({ principal: 'server-two' }))
+ const first = apiGet('/api/v1/admin/metadata', {}, metadataOptions)
+ const second = apiGet('/api/v1/admin/metadata', {}, metadataOptions)
+ await expect(first).resolves.toEqual({ principal: 'server-one' })
+ await expect(second).resolves.toEqual({ principal: 'server-two' })
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ } finally {
+ vi.stubGlobal('window', originalWindow)
+ }
+ })
+})
diff --git a/control-ui/lib/__tests__/subscriptionCapabilities.test.ts b/control-ui/lib/__tests__/subscriptionCapabilities.test.ts
new file mode 100644
index 000000000..2e86dd67c
--- /dev/null
+++ b/control-ui/lib/__tests__/subscriptionCapabilities.test.ts
@@ -0,0 +1,79 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { setControlUIReadPrincipal } from '../api'
+import { loadCodexSubscriptionCapability } from '../codexSubscriptionFeature'
+import { loadGrokSubscriptionCapability } from '../grokSubscriptionFeature'
+import { __resetReadRequestCacheForTests } from '../readRequestCache'
+import {
+ loadSubscriptionCapabilities,
+ sanitizeSubscriptionCapabilities,
+} from '../subscriptionCapabilities'
+
+const producerBody = {
+ providers: {
+ 'codex-subscription': { enabled: true },
+ 'grok-subscription': { enabled: false },
+ },
+}
+
+beforeEach(() => {
+ __resetReadRequestCacheForTests()
+ setControlUIReadPrincipal('capability-admin', 'admin')
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(producerBody), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ )
+ )
+})
+
+afterEach(() => {
+ __resetReadRequestCacheForTests()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+})
+
+describe('subscription capabilities', () => {
+ it('sanitizes only safe integration flags', () => {
+ expect(sanitizeSubscriptionCapabilities(producerBody)).toEqual(producerBody)
+ expect(
+ sanitizeSubscriptionCapabilities({
+ providers: {
+ 'codex-subscription': { enabled: false, account: 'must-not-escape' },
+ 'grok-subscription': { enabled: true },
+ },
+ })
+ ).toEqual({
+ providers: {
+ 'codex-subscription': { enabled: false },
+ 'grok-subscription': { enabled: true },
+ },
+ })
+ })
+
+ it('rejects incomplete or invalid capability payloads', () => {
+ expect(() =>
+ sanitizeSubscriptionCapabilities({ providers: { 'codex-subscription': { enabled: true } } })
+ ).toThrow('Subscription capabilities response is incomplete')
+ expect(() =>
+ sanitizeSubscriptionCapabilities({
+ providers: {
+ 'codex-subscription': { enabled: 'yes' },
+ 'grok-subscription': { enabled: true },
+ },
+ })
+ ).toThrow('Subscription capability for codex-subscription is invalid')
+ })
+
+ it('reads the shared authenticated endpoint once for both provider helpers', async () => {
+ await expect(loadCodexSubscriptionCapability()).resolves.toEqual({ enabled: true })
+ await expect(loadGrokSubscriptionCapability()).resolves.toEqual({ enabled: false })
+ await expect(loadSubscriptionCapabilities()).resolves.toEqual(producerBody)
+ expect(vi.mocked(globalThis.fetch)).toHaveBeenCalledOnce()
+ expect(vi.mocked(globalThis.fetch).mock.calls[0][0]).toBe(
+ '/control-api/api/v1/admin/llm/providers/capabilities'
+ )
+ })
+})
diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.ts
index 0cc8fe5d5..e25da01a3 100644
--- a/control-ui/lib/api.ts
+++ b/control-ui/lib/api.ts
@@ -1,11 +1,33 @@
'use client'
+import {
+ CONTROL_UI_SESSION_INVALIDATION_EVENT,
+ METADATA_READ_CACHE_MAX_ENTRIES,
+ METADATA_READ_TTL_MS,
+} from '@constants/readRequests'
+import type { ApiRequestError, ApiRequestOptions } from './api.types'
import type { GenericDiscoveryPrefill } from './oauthGeneric.types'
import type {
McpSecretSummary,
OAuthCredentialManifest,
OAuthInstallSubmit,
} from './oauthInstall.types'
+import {
+ clearReadRequestPrincipal,
+ completeReadRequestRecovery,
+ failReadRequestRecovery,
+ getReadRequestCacheEntry,
+ getReadRequestCacheGeneration,
+ getReadRequestCooldown,
+ getReadRequestPrincipal,
+ getReadRequestRecovery,
+ invalidateReadRequestCacheEntry,
+ reserveReadRequestRecovery,
+ setReadRequestCacheEntry,
+ setReadRequestCooldown,
+ setReadRequestInvalidationHandler,
+ setReadRequestPrincipal,
+} from './readRequestCache'
import {
DEFAULT_MCP_SERVER_SECRET_NAMESPACE,
DEFAULT_SANDBOX_SECRET_NAMESPACE,
@@ -125,11 +147,17 @@ const API_REQUEST_TIMEOUT_MS = 30000
// this constant remains only for the compatibility helper and old API callers.
export const GFS_UPLOAD_TIMEOUT_MS = 300000
const inFlightGetRequests = new Map<string, Promise<unknown>>()
+type SharedMetadataRead = {
+ promise: Promise<unknown>
+ controller: AbortController
+ consumers: Set<{ signal?: AbortSignal }>
+ settled: boolean
+}
+const inFlightMetadataReads = new Map<string, SharedMetadataRead>()
+const activeGetControllers = new Set<AbortController>()
let sessionEpoch = 0
-type ApiRequestOptions = {
- silentUnauthorized?: boolean
- signal?: AbortSignal
-}
+
+setReadRequestInvalidationHandler(abortActiveGetRequests)
function qs(params: Record<string, string | undefined>) {
const search = new URLSearchParams()
@@ -149,6 +177,26 @@ export function controlApiUrl(path: string): string {
return `${API_BASE}${path}`
}
+export function retryAfterSeconds(
+ headers: Headers,
+ body: Record<string, unknown> | null,
+ nowMs = Date.now()
+): number | undefined {
+ const raw = headers.get('retry-after')?.trim()
+ if (raw && /^\d+$/.test(raw)) {
+ const seconds = Number(raw)
+ if (Number.isSafeInteger(seconds) && seconds > 0) return seconds
+ }
+ if (raw) {
+ const at = Date.parse(raw)
+ if (Number.isFinite(at) && at > nowMs) return Math.ceil((at - nowMs) / 1000)
+ }
+ const seconds = body?.retryAfterSeconds
+ return typeof seconds === 'number' && Number.isSafeInteger(seconds) && seconds > 0
+ ? seconds
+ : undefined
+}
+
async function parseJsonResponse(res: Response): Promise<unknown> {
const text = await res.text()
if (!text.trim()) return undefined
@@ -202,8 +250,22 @@ export function formatApiError(res: Response, text: string): Error {
: detail === 'member_registration_misconfigured'
? 'Invitations are unavailable — member registration is misconfigured. Check the server logs for details.'
: detail)
- const error = new Error(`${res.status} ${res.statusText} - ${friendlyDetail}`)
- ;(error as Error & { status?: number }).status = res.status
+ const hasServerMessage =
+ typeof parsedBody?.message === 'string' && Boolean(parsedBody.message.trim())
+ const throttleSeconds =
+ res.status === 429 ? retryAfterSeconds(res.headers, parsedBody) : undefined
+ let throttleDetail: string
+ if (res.status === 429) {
+ throttleDetail = hasServerMessage
+ ? friendlyDetail
+ : throttleSeconds !== undefined
+ ? `Too many requests. Try again in ${throttleSeconds} seconds.`
+ : 'Too many requests. Try again later.'
+ } else {
+ throttleDetail = `${res.status} ${res.statusText} - ${friendlyDetail}`
+ }
+ const error = new Error(throttleDetail) as ApiRequestError
+ error.status = res.status
// Preserve the machine-readable error code and full JSON body so callers can
// render structured, actionable errors (e.g. unpriced_models, price_in_use_by_budget)
// instead of the generic message string.
@@ -212,17 +274,81 @@ export function formatApiError(res: Response, text: string): Error {
parsedBody.error && typeof parsedBody.error === 'object'
? (parsedBody.error as Record<string, unknown>)
: null
- ;(error as Error & { code?: string }).code =
- typeof parsedBody.error === 'string'
- ? parsedBody.error
- : typeof nestedError?.code === 'string'
- ? nestedError.code
- : undefined
- ;(error as Error & { body?: Record<string, unknown> }).body = parsedBody
+ error.code =
+ typeof parsedBody.code === 'string'
+ ? parsedBody.code
+ : typeof parsedBody.error === 'string'
+ ? parsedBody.error
+ : typeof nestedError?.code === 'string'
+ ? nestedError.code
+ : undefined
+ error.body = parsedBody
+ }
+ if (throttleSeconds !== undefined) {
+ error.retryAfterSeconds = throttleSeconds
+ error.retryAtMs = Date.now() + throttleSeconds * 1000
}
return error
}
+function abortActiveGetRequests(remote = false): void {
+ sessionEpoch += 1
+ for (const controller of activeGetControllers) controller.abort()
+ activeGetControllers.clear()
+ inFlightGetRequests.clear()
+ inFlightMetadataReads.clear()
+ if (remote && typeof window !== 'undefined') {
+ window.dispatchEvent(new Event(CONTROL_UI_SESSION_INVALIDATION_EVENT))
+ }
+}
+
+function readPrincipalKey(): string | null {
+ const current = getReadRequestPrincipal()
+ return current ? JSON.stringify([current.principalId, current.scope]) : null
+}
+
+function sameReadContext(epoch: number, principalContext: string | null): boolean {
+ if (typeof window === 'undefined') return true
+ return epoch === sessionEpoch && readPrincipalKey() === principalContext
+}
+
+function readRequestCacheKey(url: string, epoch: number): string | null {
+ if (typeof window === 'undefined') return null
+ const principalContext = getReadRequestPrincipal()
+ if (!principalContext) return null
+ const absoluteUrl = new URL(url, window.location.origin).href
+ return JSON.stringify([absoluteUrl, epoch, principalContext.principalId, principalContext.scope])
+}
+
+function waitForRead<T>(request: Promise<T>, signal?: AbortSignal): Promise<T> {
+ if (!signal) return request
+ if (signal.aborted)
+ return Promise.reject(new DOMException('The read was cancelled', 'AbortError'))
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => reject(new DOMException('The read was cancelled', 'AbortError'))
+ signal.addEventListener('abort', onAbort, { once: true })
+ request.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort))
+ })
+}
+
+function subscribeMetadataRead(shared: SharedMetadataRead, signal?: AbortSignal): Promise<unknown> {
+ const consumer = { signal }
+ shared.consumers.add(consumer)
+ const release = () => {
+ shared.consumers.delete(consumer)
+ if (!shared.settled && shared.consumers.size === 0) shared.controller.abort()
+ }
+ // Release synchronously on abort so an immediate remount cannot join a
+ // request whose last previous subscriber has already left.
+ signal?.addEventListener('abort', release, { once: true })
+ return waitForRead(shared.promise, signal)
+ .then(value => structuredClone(value))
+ .finally(() => {
+ signal?.removeEventListener('abort', release)
+ release()
+ })
+}
+
async function apiPublicPost<T>(path: string, body: unknown): Promise<T> {
const controller = new AbortController()
const timeoutId = window.setTimeout(() => controller.abort(), 15000)
@@ -261,7 +387,7 @@ async function fetchWithTimeout(
// immediately" — this matches the server proxy's resolveProxyTimeoutMs semantics.
const effectiveTimeoutMs =
Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : API_REQUEST_TIMEOUT_MS
- const timeoutId = window.setTimeout(() => controller.abort(), effectiveTimeoutMs)
+ const timeoutId = globalThis.setTimeout(() => controller.abort(), effectiveTimeoutMs)
const signal = init.signal ? AbortSignal.any([init.signal, controller.signal]) : controller.signal
try {
return await fetch(input, {
@@ -276,76 +402,205 @@ async function fetchWithTimeout(
}
throw error
} finally {
- window.clearTimeout(timeoutId)
+ globalThis.clearTimeout(timeoutId)
}
}
-export async function apiGet(
+export function apiGet(
path: string,
query: Record<string, string | undefined> = {},
options: ApiRequestOptions = {}
+) {
+ return apiRead(path, query, options)
+}
+
+async function apiRead(
+ path: string,
+ query: Record<string, string | undefined>,
+ options: ApiRequestOptions,
+ recoveringFamily = false
) {
const url = `${controlApiUrl(path)}${qs(query)}`
const headers = { ...authHeaders() }
- const cacheKey = `${url}|${sessionEpoch}`
- const existing = options.signal ? undefined : inFlightGetRequests.get(cacheKey)
- if (existing) return existing
+ const requestEpoch = sessionEpoch
+ const requestPrincipalKey = readPrincipalKey()
+ const requestGeneration = getReadRequestCacheGeneration()
+ const cacheKey = `${url}|${requestEpoch}`
+ const metadataKey = options.metadataRead ? readRequestCacheKey(url, requestEpoch) : null
+ // Capabilities, connection lists and model catalogs share one server quota.
+ // Coordinate its cooldown across URLs without combining their result caches.
+ const familyKey = metadataKey
+ ? readRequestCacheKey(`${API_BASE}/#admin-subscription-read`, requestEpoch)
+ : null
+ const assertCurrent = () => {
+ if (!sameReadContext(requestEpoch, requestPrincipalKey)) throw new AuthExpiredError()
+ if (metadataKey && requestGeneration !== getReadRequestCacheGeneration()) {
+ throw new DOMException('The metadata read was invalidated', 'AbortError')
+ }
+ if (options.signal?.aborted) throw new DOMException('The read was cancelled', 'AbortError')
+ }
+ assertCurrent()
+ if (metadataKey && !options.refresh) {
+ const cached = getReadRequestCacheEntry(metadataKey)
+ if (cached !== undefined) {
+ const value = await Promise.resolve(cached)
+ assertCurrent()
+ return value
+ }
+ }
+ if (familyKey) {
+ const cooldown = getReadRequestCooldown(familyKey)
+ if (cooldown) throw cooldown
+ if (!recoveringFamily) {
+ const recovery = getReadRequestRecovery(familyKey)
+ if (recovery) {
+ await waitForRead(recovery, options.signal)
+ assertCurrent()
+ return apiRead(path, query, options)
+ }
+ }
+ }
+ const metadataFlightKey = metadataKey ? `${metadataKey}|generation:${requestGeneration}` : null
+ if (metadataFlightKey) {
+ const existing = inFlightMetadataReads.get(metadataFlightKey)
+ if (existing && !existing.controller.signal.aborted) {
+ const value = await subscribeMetadataRead(existing, options.signal)
+ assertCurrent()
+ return value
+ }
+ if (options.refresh) invalidateReadRequestCacheEntry(metadataKey!)
+ } else if (typeof window !== 'undefined' && !options.signal) {
+ const existing = inFlightGetRequests.get(cacheKey)
+ if (existing) {
+ const value = await existing
+ assertCurrent()
+ return value
+ }
+ }
+ const controller = new AbortController()
+ const consumers = new Set<{ signal?: AbortSignal }>()
+ const assertNetworkCurrent = () => {
+ if (!sameReadContext(requestEpoch, requestPrincipalKey)) throw new AuthExpiredError()
+ if (metadataKey && requestGeneration !== getReadRequestCacheGeneration()) {
+ throw new DOMException('The metadata read was invalidated', 'AbortError')
+ }
+ if (controller.signal.aborted) throw new DOMException('The read was cancelled', 'AbortError')
+ }
const request = (async () => {
- const res = await fetchWithTimeout(url, {
- cache: 'no-store',
- headers,
- signal: options.signal,
- })
- if (!res.ok) {
- if (res.status === 401) {
- if (options.silentUnauthorized) {
- clearAdminAuthToken()
- throw new AuthExpiredError()
+ if (typeof window !== 'undefined') activeGetControllers.add(controller)
+ try {
+ const res = await fetchWithTimeout(url, {
+ cache: 'no-store',
+ headers,
+ signal:
+ !metadataKey && options.signal
+ ? AbortSignal.any([options.signal, controller.signal])
+ : controller.signal,
+ })
+ assertNetworkCurrent()
+ if (!res.ok) {
+ if (res.status === 401) {
+ if (options.silentUnauthorized) {
+ clearAdminAuthToken()
+ throw new AuthExpiredError()
+ }
+ handleUnauthorized()
}
- handleUnauthorized()
- }
- // Prefer a server-provided human-safe `message` (e.g. the 503
- // registry_unavailable body) so callers surface the clear text instead of
- // a bare "<status> <statusText>". Bodies carrying only a machine `error`
- // code (or no JSON) keep the existing status-text message. Also attach the
- // machine code, mirroring how registryCodedRequest surfaces `.code`.
- const text = await res.text().catch(() => '')
- let message = `${res.status} ${res.statusText}`
- let code: string | undefined
- let body: Record<string, unknown> | undefined
- try {
- const parsed = JSON.parse(text) as unknown
- if (parsed && typeof parsed === 'object') {
- body = parsed as Record<string, unknown>
- if (typeof body.message === 'string' && body.message.trim()) {
- message = body.message
+ // Prefer a server-provided human-safe message while preserving the
+ // existing non-429 GET status-text contract and structured error data.
+ const text = await res.text().catch(() => '')
+ assertNetworkCurrent()
+ let message = `${res.status} ${res.statusText}`
+ let code: string | undefined
+ let body: Record<string, unknown> | undefined
+ try {
+ const parsed = JSON.parse(text) as unknown
+ if (parsed && typeof parsed === 'object') {
+ body = parsed as Record<string, unknown>
+ if (typeof body.message === 'string' && body.message.trim()) {
+ message = body.message
+ }
+ if (typeof body.code === 'string') code = body.code
+ else if (typeof body.error === 'string') code = body.error
}
- if (typeof body.error === 'string') code = body.error
+ } catch {
+ /* non-JSON error body: keep the status-text message */
}
- } catch {
- /* non-JSON error body: keep the status-text message */
- }
- const error = new Error(message) as Error & {
- status?: number
- code?: string
- body?: Record<string, unknown>
+ const seconds =
+ res.status === 429 ? retryAfterSeconds(res.headers, body ?? null) : undefined
+ if (res.status === 429) {
+ if (typeof body?.message !== 'string' || !body.message.trim()) {
+ message =
+ seconds !== undefined
+ ? `Too many requests. Try again in ${seconds} seconds.`
+ : 'Too many requests. Try again later.'
+ }
+ }
+ const error = new Error(message) as ApiRequestError
+ error.status = res.status
+ if (code) error.code = code
+ if (body) error.body = body
+ if (seconds !== undefined) {
+ error.retryAfterSeconds = seconds
+ error.retryAtMs = Date.now() + seconds * 1000
+ }
+ if (familyKey && res.status === 429) {
+ const delayMs = setReadRequestCooldown(familyKey, error, seconds)
+ reserveReadRequestRecovery(
+ familyKey,
+ Date.now() + delayMs,
+ signal => {
+ if (!sameReadContext(requestEpoch, requestPrincipalKey)) return
+ void apiRead(path, query, { ...options, signal, refresh: false }, true).then(
+ () => completeReadRequestRecovery(familyKey),
+ reason => failReadRequestRecovery(familyKey, reason)
+ )
+ },
+ metadataKey ? Array.from(consumers, consumer => consumer.signal) : [options.signal]
+ )
+ }
+ throw error
}
- error.status = res.status
- if (code) error.code = code
- if (body) error.body = body
+ const parsed = await parseJsonResponse(res)
+ assertNetworkCurrent()
+ if (metadataKey) setReadRequestCacheEntry(metadataKey, parsed, METADATA_READ_TTL_MS)
+ if (familyKey && !getReadRequestCooldown(familyKey)) completeReadRequestRecovery(familyKey)
+ return parsed
+ } catch (error) {
+ assertNetworkCurrent()
throw error
+ } finally {
+ activeGetControllers.delete(controller)
}
- return parseJsonResponse(res)
})()
- if (!options.signal) {
+ const shared: SharedMetadataRead = { promise: request, controller, consumers, settled: false }
+ const settled = () => {
+ shared.settled = true
+ if (metadataFlightKey && inFlightMetadataReads.get(metadataFlightKey) === shared) {
+ inFlightMetadataReads.delete(metadataFlightKey)
+ }
+ if (inFlightGetRequests.get(cacheKey) === request) inFlightGetRequests.delete(cacheKey)
+ }
+ request.then(settled, settled)
+ if (metadataFlightKey) {
+ while (inFlightMetadataReads.size >= METADATA_READ_CACHE_MAX_ENTRIES) {
+ const oldest = inFlightMetadataReads.keys().next().value
+ if (oldest === undefined) break
+ inFlightMetadataReads.get(oldest)?.controller.abort()
+ inFlightMetadataReads.delete(oldest)
+ }
+ inFlightMetadataReads.set(metadataFlightKey, shared)
+ const value = await subscribeMetadataRead(shared, options.signal)
+ assertCurrent()
+ return value
+ }
+ if (typeof window !== 'undefined' && !options.signal) {
inFlightGetRequests.set(cacheKey, request)
- request.then(
- () => inFlightGetRequests.delete(cacheKey),
- () => inFlightGetRequests.delete(cacheKey)
- )
}
- return request
+ const value = await request
+ assertCurrent()
+ return value
}
export async function apiSend(
@@ -576,18 +831,22 @@ export type AdminLoginResponse = {
}
export function clearAdminAuthToken(): void {
- sessionEpoch += 1
- inFlightGetRequests.clear()
+ clearReadRequestPrincipal()
if (typeof window === 'undefined') return
// Remove the legacy browser-readable admin JWT if it exists. Active admin
// sessions now live in an HttpOnly cookie set by control-api.
window.localStorage.removeItem(ADMIN_TOKEN_STORAGE_KEY)
}
+export function setControlUIReadPrincipal(principalId: string, scope: string): void {
+ setReadRequestPrincipal(principalId, scope)
+}
+
export async function loginControlUI(
username: string,
password: string
): Promise<AdminLoginResponse> {
+ clearAdminAuthToken()
const res = await fetch(`${API_BASE}/api/v1/admin/auth/login`, {
method: 'POST',
credentials: 'include',
@@ -604,6 +863,7 @@ export async function loginControlUI(
}
export async function logoutControlUI(): Promise<void> {
+ clearAdminAuthToken()
try {
await apiSend('POST', '/api/v1/admin/auth/logout')
} catch {
diff --git a/control-ui/lib/api.types.ts b/control-ui/lib/api.types.ts
new file mode 100644
index 000000000..2fbb05e3c
--- /dev/null
+++ b/control-ui/lib/api.types.ts
@@ -0,0 +1,22 @@
+export type ApiThrottleMetadata = {
+ retryAfterSeconds?: number
+ retryAtMs?: number
+}
+
+export type ApiRequestError = Error & {
+ status?: number
+ code?: string
+ body?: Record<string, unknown>
+} & ApiThrottleMetadata
+
+export type MetadataReadKind =
+ | 'subscription-capabilities'
+ | 'subscription-connections'
+ | 'subscription-model-catalog'
+
+export type ApiRequestOptions = {
+ silentUnauthorized?: boolean
+ signal?: AbortSignal
+ metadataRead?: MetadataReadKind
+ refresh?: boolean
+}
diff --git a/control-ui/lib/codexSubscription.ts b/control-ui/lib/codexSubscription.ts
index 5faf226d6..8331b1585 100644
--- a/control-ui/lib/codexSubscription.ts
+++ b/control-ui/lib/codexSubscription.ts
@@ -1,4 +1,6 @@
import { apiGet, apiSend } from './api'
+import { invalidateReadRequestCache } from './readRequestCache'
+import type { SubscriptionCapabilityLoadOptions } from './subscriptionCapabilities'
export const CODEX_SUBSCRIPTION_API_BASE = '/api/v1/admin/llm/providers/codex-subscription'
@@ -282,19 +284,29 @@ function sanitizeAssignableHost(raw: unknown): CodexAssignableHost | null {
}
}
-export async function listCodexSubscriptionConnections(): Promise<
- CodexSubscriptionConnectionView[]
-> {
- const fleet = await listCodexSubscriptionFleet()
+export async function listCodexSubscriptionConnections(
+ options: SubscriptionCapabilityLoadOptions = {}
+): Promise<CodexSubscriptionConnectionView[]> {
+ const fleet = await listCodexSubscriptionFleet(options)
return fleet.connections
}
-export async function listCodexSubscriptionFleet(): Promise<{
+export async function listCodexSubscriptionFleet(
+ options: SubscriptionCapabilityLoadOptions = {}
+): Promise<{
connections: CodexSubscriptionConnectionView[]
assignableHosts: CodexAssignableHost[]
assignableHostsUnavailable: boolean
}> {
- const raw = (await apiGet(`${CODEX_SUBSCRIPTION_API_BASE}/connections`)) as {
+ const raw = (await apiGet(
+ `${CODEX_SUBSCRIPTION_API_BASE}/connections`,
+ {},
+ {
+ metadataRead: 'subscription-connections',
+ refresh: options.refresh,
+ signal: options.signal,
+ }
+ )) as {
connections?: unknown
assignableHosts?: unknown
assignableHostsUnavailable?: unknown
@@ -319,16 +331,23 @@ export async function createCodexSubscriptionConnection(input: {
displayName: string
connectionKey?: string
}): Promise<CodexSubscriptionConnectionView> {
- return sanitizeCodexConnection(
- await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/connections`, input)
- )
+ const raw = await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/connections`, input)
+ invalidateReadRequestCache()
+ return sanitizeCodexConnection(raw)
}
export async function listCodexConnectionModels(
- connectionKey: string
+ connectionKey: string,
+ options: SubscriptionCapabilityLoadOptions = {}
): Promise<Array<{ model: string; enabled: boolean; stale: boolean }>> {
const raw = (await apiGet(
- `${CODEX_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}/models`
+ `${CODEX_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}/models`,
+ {},
+ {
+ metadataRead: 'subscription-model-catalog',
+ refresh: options.refresh,
+ signal: options.signal,
+ }
)) as { models?: Array<{ model?: string; enabled?: boolean; stale?: boolean }> }
return Array.isArray(raw.models)
? raw.models
@@ -359,56 +378,66 @@ export async function startCodexBrowserConnect(
intent: CodexOAuthIntent,
connectionKey?: string
): Promise<CodexBrowserStartView> {
- return sanitizeCodexBrowserStart(
- await apiSend('POST', keyedPath(connectionKey, 'browser/start'), { intent })
- )
+ const raw = await apiSend('POST', keyedPath(connectionKey, 'browser/start'), { intent })
+ invalidateReadRequestCache()
+ return sanitizeCodexBrowserStart(raw)
}
export async function startCodexDeviceConnect(
intent: CodexOAuthIntent,
connectionKey?: string
): Promise<CodexDeviceStartView> {
- return sanitizeCodexDeviceStart(
- await apiSend('POST', keyedPath(connectionKey, 'device/start'), { intent })
- )
+ const raw = await apiSend('POST', keyedPath(connectionKey, 'device/start'), { intent })
+ invalidateReadRequestCache()
+ return sanitizeCodexDeviceStart(raw)
}
export async function pollCodexDevice(
state: string,
connectionKey?: string
): Promise<CodexDevicePollView> {
- return sanitizeCodexDevicePoll(await apiGet(keyedPath(connectionKey, 'device/poll'), { state }))
+ const result = sanitizeCodexDevicePoll(
+ await apiGet(keyedPath(connectionKey, 'device/poll'), { state })
+ )
+ if (result.status === 'connected') invalidateReadRequestCache()
+ return result
}
export async function refreshCodexSubscriptionConnection(
connectionKey?: string
): Promise<CodexSubscriptionConnectionView> {
- return sanitizeCodexConnection(await apiSend('POST', keyedPath(connectionKey, 'refresh')))
+ const raw = await apiSend('POST', keyedPath(connectionKey, 'refresh'))
+ invalidateReadRequestCache()
+ return sanitizeCodexConnection(raw)
}
export async function syncCodexSubscriptionCatalog(
connectionKey?: string
): Promise<CodexCatalogSyncView> {
- return sanitizeCodexCatalogSync(await apiSend('POST', keyedPath(connectionKey, 'catalog/sync')))
+ const raw = await apiSend('POST', keyedPath(connectionKey, 'catalog/sync'))
+ invalidateReadRequestCache()
+ return sanitizeCodexCatalogSync(raw)
}
export async function revokeCodexSubscription(
connectionKey?: string
): Promise<CodexSubscriptionConnectionView> {
- return sanitizeCodexConnection(await apiSend('POST', keyedPath(connectionKey, 'revoke')))
+ const raw = await apiSend('POST', keyedPath(connectionKey, 'revoke'))
+ invalidateReadRequestCache()
+ return sanitizeCodexConnection(raw)
}
export async function patchCodexSubscriptionConnection(
connectionKey: string,
patch: { displayName?: string; defaultModel?: string | null }
): Promise<CodexSubscriptionConnectionView> {
- return sanitizeCodexConnection(
- await apiSend(
- 'PATCH',
- `${CODEX_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}`,
- patch
- )
+ const raw = await apiSend(
+ 'PATCH',
+ `${CODEX_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}`,
+ patch
)
+ invalidateReadRequestCache()
+ return sanitizeCodexConnection(raw)
}
export async function patchCodexCatalogModel(
@@ -421,6 +450,7 @@ export async function patchCodexCatalogModel(
`${CODEX_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}/models/${encodeURIComponent(model)}`,
{ enabled }
)) as { models?: Array<{ model?: string; enabled?: boolean; stale?: boolean }> }
+ invalidateReadRequestCache()
return Array.isArray(raw.models)
? raw.models
.filter(row => typeof row.model === 'string' && row.model.trim())
diff --git a/control-ui/lib/codexSubscriptionFeature.ts b/control-ui/lib/codexSubscriptionFeature.ts
index bc8510260..546c419c3 100644
--- a/control-ui/lib/codexSubscriptionFeature.ts
+++ b/control-ui/lib/codexSubscriptionFeature.ts
@@ -1,12 +1,10 @@
-import { getCodexSubscriptionConnection } from './codexSubscription'
+import { loadSubscriptionCapabilities } from './subscriptionCapabilities'
export type CodexSubscriptionCapability = {
enabled: boolean
error?: string
}
-const DISABLED_CAPABILITY: CodexSubscriptionCapability = { enabled: false }
-
export function isDisabledCapabilityError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false
const status = (error as { status?: unknown }).status
@@ -14,18 +12,9 @@ export function isDisabledCapabilityError(error: unknown): boolean {
return status === 404 || code === 'disabled'
}
-/**
- * Control UI default is off. Capability is proven only by a successful
- * Control API connection read — never by a browser-manipulable env var.
- */
export async function loadCodexSubscriptionCapability(): Promise<CodexSubscriptionCapability> {
- try {
- await getCodexSubscriptionConnection()
- return { enabled: true }
- } catch (error) {
- if (isDisabledCapabilityError(error)) return DISABLED_CAPABILITY
- throw error
- }
+ const capabilities = await loadSubscriptionCapabilities()
+ return { enabled: capabilities.providers['codex-subscription'].enabled }
}
export function isCodexSubscriptionUiEnabled(
diff --git a/control-ui/lib/grokSubscription.ts b/control-ui/lib/grokSubscription.ts
index f2e45aca1..a272c4c97 100644
--- a/control-ui/lib/grokSubscription.ts
+++ b/control-ui/lib/grokSubscription.ts
@@ -11,6 +11,8 @@ import {
sanitizeSubscriptionCatalogSync,
sanitizeSubscriptionConnection,
} from './codexSubscription'
+import { invalidateReadRequestCache } from './readRequestCache'
+import type { SubscriptionCapabilityLoadOptions } from './subscriptionCapabilities'
export const GROK_SUBSCRIPTION_API_BASE = '/api/v1/admin/llm/providers/grok-subscription'
export const GROK_UNASSIGNED_CONNECTION_KEY = CODEX_UNASSIGNED_CONNECTION_KEY
@@ -137,8 +139,18 @@ function keyedPath(connectionKey: string, action?: string): string {
return action ? `${base}/${action}` : base
}
-export async function listGrokSubscriptionConnections(): Promise<GrokSubscriptionConnectionView[]> {
- const raw = (await apiGet(`${GROK_SUBSCRIPTION_API_BASE}/connections`)) as {
+export async function listGrokSubscriptionConnections(
+ options: SubscriptionCapabilityLoadOptions = {}
+): Promise<GrokSubscriptionConnectionView[]> {
+ const raw = (await apiGet(
+ `${GROK_SUBSCRIPTION_API_BASE}/connections`,
+ {},
+ {
+ metadataRead: 'subscription-connections',
+ refresh: options.refresh,
+ signal: options.signal,
+ }
+ )) as {
connections?: unknown
}
return Array.isArray(raw.connections)
@@ -150,15 +162,24 @@ export async function createGrokSubscriptionConnection(input: {
displayName: string
connectionKey?: string
}): Promise<GrokSubscriptionConnectionView> {
- return sanitizeGrokConnection(
- await apiSend('POST', `${GROK_SUBSCRIPTION_API_BASE}/connections`, input)
- )
+ const raw = await apiSend('POST', `${GROK_SUBSCRIPTION_API_BASE}/connections`, input)
+ invalidateReadRequestCache()
+ return sanitizeGrokConnection(raw)
}
export async function listGrokConnectionModels(
- connectionKey: string
+ connectionKey: string,
+ options: SubscriptionCapabilityLoadOptions = {}
): Promise<Array<{ model: string; enabled: boolean; stale: boolean }>> {
- const raw = (await apiGet(`${keyedPath(connectionKey)}/models`)) as {
+ const raw = (await apiGet(
+ `${keyedPath(connectionKey)}/models`,
+ {},
+ {
+ metadataRead: 'subscription-model-catalog',
+ refresh: options.refresh,
+ signal: options.signal,
+ }
+ )) as {
models?: Array<{ model?: string; enabled?: boolean; stale?: boolean }>
}
return Array.isArray(raw.models)
@@ -176,9 +197,9 @@ export async function startGrokDeviceConnect(
intent: GrokOAuthIntent,
connectionKey: string
): Promise<GrokDeviceStartView> {
- return sanitizeGrokDeviceStart(
- await apiSend('POST', keyedPath(connectionKey, 'device/start'), { intent })
- )
+ const raw = await apiSend('POST', keyedPath(connectionKey, 'device/start'), { intent })
+ invalidateReadRequestCache()
+ return sanitizeGrokDeviceStart(raw)
}
export async function pollGrokDevice(
@@ -191,7 +212,9 @@ export async function pollGrokDevice(
>
assertNoForbiddenKeys(raw)
if (raw.status === 'connected') {
- return { status: 'connected', connection: sanitizeGrokConnection(raw.connection) }
+ const connection = sanitizeGrokConnection(raw.connection)
+ invalidateReadRequestCache()
+ return { status: 'connected', connection }
}
if (raw.status === 'expired' || raw.status === 'denied') {
return { status: raw.status }
@@ -209,20 +232,26 @@ export async function pollGrokDevice(
export async function syncGrokSubscriptionCatalog(
connectionKey: string
): Promise<GrokCatalogSyncView> {
- return sanitizeGrokCatalogSync(await apiSend('POST', keyedPath(connectionKey, 'catalog/sync')))
+ const raw = await apiSend('POST', keyedPath(connectionKey, 'catalog/sync'))
+ invalidateReadRequestCache()
+ return sanitizeGrokCatalogSync(raw)
}
export async function revokeGrokSubscription(
connectionKey: string
): Promise<GrokSubscriptionConnectionView> {
- return sanitizeGrokConnection(await apiSend('POST', keyedPath(connectionKey, 'revoke')))
+ const raw = await apiSend('POST', keyedPath(connectionKey, 'revoke'))
+ invalidateReadRequestCache()
+ return sanitizeGrokConnection(raw)
}
export async function patchGrokSubscriptionConnection(
connectionKey: string,
patch: { displayName?: string; defaultModel?: string | null }
): Promise<GrokSubscriptionConnectionView> {
- return sanitizeGrokConnection(await apiSend('PATCH', keyedPath(connectionKey), patch))
+ const raw = await apiSend('PATCH', keyedPath(connectionKey), patch)
+ invalidateReadRequestCache()
+ return sanitizeGrokConnection(raw)
}
export async function patchGrokCatalogModel(
@@ -235,6 +264,7 @@ export async function patchGrokCatalogModel(
`${keyedPath(connectionKey)}/models/${encodeURIComponent(model)}`,
{ enabled }
)) as { models?: Array<{ model?: string; enabled?: boolean; stale?: boolean }> }
+ invalidateReadRequestCache()
return Array.isArray(raw.models)
? raw.models
.filter(row => typeof row.model === 'string' && row.model.trim())
diff --git a/control-ui/lib/grokSubscriptionFeature.ts b/control-ui/lib/grokSubscriptionFeature.ts
index 1f87bff02..d241a70c5 100644
--- a/control-ui/lib/grokSubscriptionFeature.ts
+++ b/control-ui/lib/grokSubscriptionFeature.ts
@@ -1,25 +1,13 @@
-import { isDisabledCapabilityError } from './codexSubscriptionFeature'
-import { listGrokSubscriptionConnections } from './grokSubscription'
+import { loadSubscriptionCapabilities } from './subscriptionCapabilities'
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
- }
+ const capabilities = await loadSubscriptionCapabilities()
+ return { enabled: capabilities.providers['grok-subscription'].enabled }
}
export function isGrokSubscriptionUiEnabled(
diff --git a/control-ui/lib/hooks/__tests__/useGrokSubscriptionEnabled.test.tsx b/control-ui/lib/hooks/__tests__/useGrokSubscriptionEnabled.test.tsx
index 12786a6c3..6db2e7f5e 100644
--- a/control-ui/lib/hooks/__tests__/useGrokSubscriptionEnabled.test.tsx
+++ b/control-ui/lib/hooks/__tests__/useGrokSubscriptionEnabled.test.tsx
@@ -1,12 +1,20 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
-import { loadGrokSubscriptionCapability } from '@lib/grokSubscriptionFeature'
+import type { SubscriptionCapabilities } from '../../subscriptionCapabilities'
import { useGrokSubscriptionEnabled } from '../useGrokSubscriptionEnabled'
-vi.mock('@lib/grokSubscriptionFeature', async importOriginal => {
- const actual = await importOriginal<typeof import('@lib/grokSubscriptionFeature')>()
- return { ...actual, loadGrokSubscriptionCapability: vi.fn() }
-})
+const grokCapabilityState = vi.hoisted(() => ({
+ capabilities: null as SubscriptionCapabilities | null,
+}))
+
+vi.mock('@lib/hooks/useSubscriptionCapabilities', () => ({
+ useSubscriptionCapabilities: () => ({
+ capabilities: grokCapabilityState.capabilities,
+ loading: grokCapabilityState.capabilities === null,
+ error: null,
+ retry: vi.fn(),
+ }),
+}))
function Probe() {
return <span data-testid="grok">{String(useGrokSubscriptionEnabled())}</span>
@@ -14,37 +22,52 @@ function Probe() {
afterEach(() => {
cleanup()
+ grokCapabilityState.capabilities = null
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
- })
- )
+ it('starts hidden and turns on after shared capability discovery confirms the integration', async () => {
+ grokCapabilityState.capabilities = null
render(<Probe />)
expect(screen.getByTestId('grok')).toHaveTextContent('false')
- resolve({ enabled: true })
+ cleanup()
+
+ grokCapabilityState.capabilities = {
+ providers: {
+ 'codex-subscription': { enabled: false },
+ 'grok-subscription': { enabled: true },
+ },
+ }
+ render(<Probe />)
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 })
+ it('stays hidden when the shared integration flag is off', () => {
+ grokCapabilityState.capabilities = {
+ providers: {
+ 'codex-subscription': { enabled: false },
+ 'grok-subscription': { 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'))
+ it('fails closed before confirmation', () => {
+ grokCapabilityState.capabilities = null
render(<Probe />)
- await waitFor(() => expect(loadGrokSubscriptionCapability).toHaveBeenCalled())
- await Promise.resolve()
expect(screen.getByTestId('grok')).toHaveTextContent('false')
})
+
+ it('keeps a previously confirmed Grok integration visible during a transient read failure', () => {
+ grokCapabilityState.capabilities = {
+ providers: {
+ 'codex-subscription': { enabled: false },
+ 'grok-subscription': { enabled: true },
+ },
+ }
+ render(<Probe />)
+ expect(screen.getByTestId('grok')).toHaveTextContent('true')
+ })
})
diff --git a/control-ui/lib/hooks/__tests__/useSubscriptionCapabilities.test.tsx b/control-ui/lib/hooks/__tests__/useSubscriptionCapabilities.test.tsx
new file mode 100644
index 000000000..ed9851f2e
--- /dev/null
+++ b/control-ui/lib/hooks/__tests__/useSubscriptionCapabilities.test.tsx
@@ -0,0 +1,132 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
+import { useSubscriptionCapabilities } from '../useSubscriptionCapabilities'
+
+const load = vi.hoisted(() => vi.fn())
+
+vi.mock('../../subscriptionCapabilities', () => ({
+ loadSubscriptionCapabilities: load,
+}))
+
+beforeEach(() => {
+ load.mockReset()
+})
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+ vi.useRealTimers()
+})
+
+describe('useSubscriptionCapabilities', () => {
+ it('loads safe provider flags and exposes explicit retry', async () => {
+ load.mockResolvedValueOnce({
+ providers: {
+ 'codex-subscription': { enabled: true },
+ 'grok-subscription': { enabled: false },
+ },
+ })
+ const { result } = renderHook(() => useSubscriptionCapabilities())
+
+ await waitFor(() => expect(result.current.loading).toBe(false))
+ expect(result.current.capabilities?.providers['codex-subscription'].enabled).toBe(true)
+ expect(result.current.capabilities?.providers['grok-subscription'].enabled).toBe(false)
+ expect(result.current.error).toBeNull()
+
+ load.mockResolvedValueOnce({
+ providers: {
+ 'codex-subscription': { enabled: false },
+ 'grok-subscription': { enabled: true },
+ },
+ })
+ act(() => result.current.retry())
+ await waitFor(() =>
+ expect(result.current.capabilities?.providers['grok-subscription'].enabled).toBe(true)
+ )
+ expect(load).toHaveBeenNthCalledWith(2, { refresh: true, signal: expect.any(AbortSignal) })
+ })
+
+ it('keeps a previously confirmed provider enabled during a transient failure', async () => {
+ load.mockResolvedValueOnce({
+ providers: {
+ 'codex-subscription': { enabled: true },
+ 'grok-subscription': { enabled: true },
+ },
+ })
+ const { result } = renderHook(() => useSubscriptionCapabilities())
+ await waitFor(() => expect(result.current.capabilities).not.toBeNull())
+
+ load.mockRejectedValueOnce(Object.assign(new Error('Temporarily unavailable'), { status: 429 }))
+ act(() => result.current.retry())
+ await waitFor(() => expect(result.current.error).not.toBeNull())
+ expect(result.current.capabilities?.providers['grok-subscription'].enabled).toBe(true)
+ })
+
+ it('does not probe until the consumer is enabled and cancels on disable', async () => {
+ load.mockReturnValue(new Promise(() => undefined))
+ const { rerender } = renderHook(({ enabled }) => useSubscriptionCapabilities({ enabled }), {
+ initialProps: { enabled: false },
+ })
+ expect(load).not.toHaveBeenCalled()
+ rerender({ enabled: true })
+ expect(load).toHaveBeenCalledOnce()
+ const signal = load.mock.calls[0][0].signal as AbortSignal
+ rerender({ enabled: false })
+ expect(signal.aborted).toBe(true)
+ })
+
+ it('limits automatic throttle recovery to one attempt and cancels it on unmount', async () => {
+ vi.useFakeTimers()
+ load.mockRejectedValue(
+ Object.assign(new Error('Try again in 12 seconds.'), {
+ status: 429,
+ retryAtMs: Date.now() + 12_000,
+ })
+ )
+ const { result, unmount } = renderHook(() => useSubscriptionCapabilities())
+ await act(async () => {
+ await Promise.resolve()
+ })
+ expect(result.current.error?.status).toBe(429)
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000)
+ })
+ expect(load).toHaveBeenCalledTimes(2)
+ unmount()
+ expect((load.mock.calls[1][0].signal as AbortSignal).aborted).toBe(true)
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(load).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not automatically retry ordinary failures or deliver an unmounted result', async () => {
+ vi.useFakeTimers()
+ load.mockRejectedValueOnce(Object.assign(new Error('Unavailable'), { status: 503 }))
+ const { result, unmount } = renderHook(() => useSubscriptionCapabilities())
+ await act(async () => {
+ await Promise.resolve()
+ })
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000)
+ })
+ expect(load).toHaveBeenCalledOnce()
+ expect(result.current.error?.status).toBe(503)
+ let resolve!: (value: unknown) => void
+ load.mockReturnValueOnce(
+ new Promise(onResolve => {
+ resolve = onResolve
+ })
+ )
+ act(() => result.current.retry())
+ unmount()
+ await act(async () => {
+ resolve({
+ providers: {
+ 'codex-subscription': { enabled: true },
+ 'grok-subscription': { enabled: true },
+ },
+ })
+ await Promise.resolve()
+ })
+ expect(result.current.capabilities).toBeNull()
+ })
+})
diff --git a/control-ui/lib/hooks/useGrokSubscriptionEnabled.ts b/control-ui/lib/hooks/useGrokSubscriptionEnabled.ts
index 229e8bad7..bbb31e64f 100644
--- a/control-ui/lib/hooks/useGrokSubscriptionEnabled.ts
+++ b/control-ui/lib/hooks/useGrokSubscriptionEnabled.ts
@@ -1,34 +1,16 @@
'use client'
-import { useEffect, useState } from 'react'
-import {
- isGrokSubscriptionUiEnabled,
- loadGrokSubscriptionCapability,
-} from '@lib/grokSubscriptionFeature'
+import { isGrokSubscriptionUiEnabled } from '@lib/grokSubscriptionFeature'
+import { useSubscriptionCapabilities } from './useSubscriptionCapabilities'
/**
- * 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)").
+ * True only once the shared Control API capability response proves the flag on.
+ * A transient failure after a confirmed true value does not hide a previously
+ * confirmed provider; before confirmation it still fails closed.
*/
-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
+export function useGrokSubscriptionEnabled(enabled = true): boolean {
+ const { capabilities } = useSubscriptionCapabilities({ enabled })
+ return isGrokSubscriptionUiEnabled({
+ enabled: capabilities?.providers['grok-subscription']?.enabled ?? false,
+ })
}
diff --git a/control-ui/lib/hooks/useSubscriptionCapabilities.ts b/control-ui/lib/hooks/useSubscriptionCapabilities.ts
new file mode 100644
index 000000000..b84949815
--- /dev/null
+++ b/control-ui/lib/hooks/useSubscriptionCapabilities.ts
@@ -0,0 +1,99 @@
+'use client'
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import {
+ METADATA_READ_MAX_RECOVERY_ATTEMPTS,
+ METADATA_READ_UNTIMED_COOLDOWN_MS,
+} from '@constants/readRequests'
+import type { ApiRequestError } from '../api.types'
+import {
+ type SubscriptionCapabilities,
+ loadSubscriptionCapabilities,
+} from '../subscriptionCapabilities'
+
+export type SubscriptionCapabilitiesState = {
+ capabilities: SubscriptionCapabilities | null
+ loading: boolean
+ error: ApiRequestError | null
+ retry: () => void
+}
+
+export function useSubscriptionCapabilities(
+ options: { enabled?: boolean } = {}
+): SubscriptionCapabilitiesState {
+ const enabled = options.enabled ?? true
+ const [capabilities, setCapabilities] = useState<SubscriptionCapabilities | null>(null)
+ const [loading, setLoading] = useState(true)
+ const [error, setError] = useState<ApiRequestError | null>(null)
+ const [retryNonce, setRetryNonce] = useState(0)
+ const requestRef = useRef(0)
+ const controllerRef = useRef<AbortController | null>(null)
+ const recoveryAttemptsRef = useRef(0)
+ const enabledRef = useRef(enabled)
+ enabledRef.current = enabled
+
+ const load = useCallback(async (refresh: boolean) => {
+ if (!enabledRef.current) return
+ const controller =
+ controllerRef.current && !controllerRef.current.signal.aborted
+ ? controllerRef.current
+ : new AbortController()
+ controllerRef.current = controller
+ const requestId = ++requestRef.current
+ setLoading(true)
+ setError(null)
+ try {
+ const next = await loadSubscriptionCapabilities({ refresh, signal: controller.signal })
+ if (controller.signal.aborted || requestRef.current !== requestId) return
+ setCapabilities(next)
+ recoveryAttemptsRef.current = 0
+ } catch (err) {
+ if (controller.signal.aborted || requestRef.current !== requestId) return
+ if (err instanceof Error && (err.name === 'AbortError' || err.name === 'AuthExpiredError'))
+ return
+ setError(err as ApiRequestError)
+ } finally {
+ if (requestRef.current === requestId) setLoading(false)
+ }
+ }, [])
+
+ useEffect(() => {
+ if (!enabled) {
+ requestRef.current += 1
+ controllerRef.current?.abort()
+ setLoading(false)
+ return
+ }
+ void load(retryNonce > 0)
+ return () => {
+ requestRef.current += 1
+ controllerRef.current?.abort()
+ }
+ }, [enabled, load, retryNonce])
+
+ useEffect(() => {
+ if (
+ !enabled ||
+ error?.status !== 429 ||
+ recoveryAttemptsRef.current >= METADATA_READ_MAX_RECOVERY_ATTEMPTS
+ )
+ return
+ const retryAtMs = error.retryAtMs ?? Date.now() + METADATA_READ_UNTIMED_COOLDOWN_MS
+ const delay = Math.max(0, retryAtMs - Date.now())
+ const timer = setTimeout(() => {
+ recoveryAttemptsRef.current += 1
+ void load(false)
+ }, delay)
+ return () => clearTimeout(timer)
+ }, [enabled, error, load])
+
+ const retry = useCallback(() => {
+ recoveryAttemptsRef.current = 0
+ setRetryNonce(value => value + 1)
+ }, [])
+
+ return useMemo(
+ () => ({ capabilities, loading, error, retry }),
+ [capabilities, error, loading, retry]
+ )
+}
diff --git a/control-ui/lib/llm.ts b/control-ui/lib/llm.ts
index 78037b3a6..42062cd10 100644
--- a/control-ui/lib/llm.ts
+++ b/control-ui/lib/llm.ts
@@ -98,6 +98,7 @@ export function operatorProviderOptions(opts?: {
*/
export function runtimeProviderOptions(opts?: {
grokEnabled?: boolean
+ grokAvailabilityKnown?: boolean
saved?: ReadonlyArray<string | null | undefined>
}): Array<{ value: LlmProvider; label: string }> {
const options = LLM_PROVIDER_OPTIONS.filter(
@@ -106,7 +107,8 @@ export function runtimeProviderOptions(opts?: {
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)` })
+ const availability = opts?.grokAvailabilityKnown === false ? 'availability unknown' : 'disabled'
+ options.push({ value, label: `${PROVIDER_DISPLAY_LABELS[value]} (${availability})` })
}
return options
}
diff --git a/control-ui/lib/readRequestCache.ts b/control-ui/lib/readRequestCache.ts
new file mode 100644
index 000000000..e24bcc2e9
--- /dev/null
+++ b/control-ui/lib/readRequestCache.ts
@@ -0,0 +1,308 @@
+import {
+ METADATA_READ_CACHE_MAX_ENTRIES,
+ METADATA_READ_MAX_RECOVERY_ATTEMPTS,
+ METADATA_READ_UNTIMED_COOLDOWN_MS,
+} from '@constants/readRequests'
+import type { ApiRequestError } from './api.types'
+
+type CacheEntry = {
+ value: unknown
+ expiresAtMs: number
+}
+
+type CooldownEntry = {
+ error: ApiRequestError
+ retryAtMs: number
+}
+
+type RecoveryEntry = {
+ deadlineMs: number
+ timer?: ReturnType<typeof setTimeout>
+ controller: AbortController
+ pending: Promise<void>
+ resolve: () => void
+ reject: (error: unknown) => void
+ state: 'scheduled' | 'running' | 'failed'
+ removeListeners: () => void
+ addSubscribers: (signals: Array<AbortSignal | undefined>) => void
+}
+
+type PrincipalContext = {
+ principalId: string
+ scope: string
+}
+
+const READ_REQUEST_INVALIDATION_CHANNEL = 'control-ui-read-metadata-invalidation'
+const entries = new Map<string, CacheEntry>()
+const cooldowns = new Map<string, CooldownEntry>()
+const recoveries = new Map<string, RecoveryEntry>()
+let principal: PrincipalContext | null = null
+let invalidationChannel: BroadcastChannel | null = null
+let invalidationHandler: ((remote?: boolean) => void) | null = null
+let generation = 0
+
+function isBrowser(): boolean {
+ return typeof window !== 'undefined'
+}
+
+function ensureChannel(): BroadcastChannel | null {
+ if (!isBrowser() || typeof BroadcastChannel === 'undefined') return null
+ if (!invalidationChannel) {
+ invalidationChannel = new BroadcastChannel(READ_REQUEST_INVALIDATION_CHANNEL)
+ invalidationChannel.onmessage = event => {
+ if ((event.data as { type?: unknown } | null)?.type === 'session-invalidation') {
+ // Another tab may have replaced the shared cookie. A fresh authenticated
+ // /me read must confirm the principal before this tab can cache again.
+ principal = null
+ clearReadRequestCache()
+ invalidationHandler?.(true)
+ }
+ }
+ }
+ return invalidationChannel
+}
+
+export function setReadRequestInvalidationHandler(
+ handler: ((remote?: boolean) => void) | null
+): void {
+ invalidationHandler = handler
+}
+
+export function getReadRequestPrincipal(): PrincipalContext | null {
+ return isBrowser() ? principal : null
+}
+
+export function setReadRequestPrincipal(principalId: string, scope: string): void {
+ if (!isBrowser()) return
+ if (!principalId || !scope) {
+ clearReadRequestPrincipal()
+ return
+ }
+ if (principal?.principalId === principalId && principal.scope === scope) return
+ const wasVerified = principal !== null
+ principal = { principalId, scope }
+ clearReadRequestCache()
+ invalidationHandler?.()
+ const channel = ensureChannel()
+ // Initial /me confirmation is local; rebroadcasting it would make two tabs
+ // invalidate one another indefinitely. Actual identity/scope changes propagate.
+ if (wasVerified) channel?.postMessage({ type: 'session-invalidation' })
+}
+
+export function clearReadRequestPrincipal(): void {
+ principal = null
+ clearReadRequestCache()
+ invalidationHandler?.()
+ ensureChannel()?.postMessage({ type: 'session-invalidation' })
+}
+
+export function clearReadRequestCache(): void {
+ generation += 1
+ entries.clear()
+ cooldowns.clear()
+ for (const recovery of recoveries.values()) disposeRecovery(recovery)
+ recoveries.clear()
+}
+
+export function getReadRequestCacheGeneration(): number {
+ return generation
+}
+
+export function invalidateReadRequestCache(): void {
+ // A successful write invalidates displayed metadata, not the independent
+ // read-family quota. Preserve its deadline and one recovery reservation.
+ generation += 1
+ entries.clear()
+}
+
+export function invalidateReadRequestCacheEntry(key: string): void {
+ entries.delete(key)
+}
+
+export function getReadRequestCacheEntry(key: string, nowMs = Date.now()): unknown | undefined {
+ if (!isBrowser()) return undefined
+ const entry = entries.get(key)
+ if (!entry) return undefined
+ if (entry.expiresAtMs <= nowMs) {
+ entries.delete(key)
+ return undefined
+ }
+ entries.delete(key)
+ entries.set(key, entry)
+ return structuredClone(entry.value)
+}
+
+export function setReadRequestCacheEntry(
+ key: string,
+ value: unknown,
+ ttlMs: number,
+ nowMs = Date.now()
+): void {
+ if (!isBrowser()) return
+ entries.delete(key)
+ while (entries.size >= METADATA_READ_CACHE_MAX_ENTRIES) {
+ const oldest = entries.keys().next().value
+ if (oldest === undefined) break
+ entries.delete(oldest)
+ }
+ entries.set(key, { value: structuredClone(value), expiresAtMs: nowMs + ttlMs })
+}
+
+export function getReadRequestCooldown(
+ key: string,
+ nowMs = Date.now()
+): ApiRequestError | undefined {
+ if (!isBrowser()) return undefined
+ const entry = cooldowns.get(key)
+ if (!entry) return undefined
+ if (entry.retryAtMs <= nowMs) {
+ cooldowns.delete(key)
+ return undefined
+ }
+ return entry.error
+}
+
+export function setReadRequestCooldown(
+ key: string,
+ error: ApiRequestError,
+ retryAfterSeconds: number | undefined,
+ nowMs = Date.now()
+): number {
+ if (!isBrowser()) return 0
+ const delayMs =
+ retryAfterSeconds !== undefined ? retryAfterSeconds * 1000 : METADATA_READ_UNTIMED_COOLDOWN_MS
+ const retryAtMs = Math.max(nowMs + delayMs, cooldowns.get(key)?.retryAtMs ?? 0)
+ error.retryAtMs = retryAtMs
+ while (cooldowns.size >= METADATA_READ_CACHE_MAX_ENTRIES && !cooldowns.has(key)) {
+ const oldest = cooldowns.keys().next().value
+ if (oldest === undefined) break
+ cooldowns.delete(oldest)
+ }
+ cooldowns.set(key, { error, retryAtMs })
+ return retryAtMs - nowMs
+}
+
+function disposeRecovery(entry: RecoveryEntry): void {
+ if (entry.timer) clearTimeout(entry.timer)
+ entry.removeListeners()
+ entry.controller.abort()
+ entry.reject(new DOMException('The read was cancelled', 'AbortError'))
+}
+
+export function getReadRequestRecovery(key: string): Promise<void> | undefined {
+ const recovery = recoveries.get(key)
+ return recovery && recovery.state !== 'failed' && recovery.deadlineMs <= Date.now()
+ ? recovery.pending
+ : undefined
+}
+
+export function reserveReadRequestRecovery(
+ key: string,
+ deadlineMs: number,
+ recover: (signal: AbortSignal) => void,
+ signals: Array<AbortSignal | undefined> = [undefined]
+): boolean {
+ if (!isBrowser() || METADATA_READ_MAX_RECOVERY_ATTEMPTS < 1) return false
+ const existing = recoveries.get(key)
+ if (existing) {
+ if (existing.state === 'scheduled') {
+ existing.deadlineMs = Math.max(existing.deadlineMs, deadlineMs)
+ existing.addSubscribers(signals)
+ }
+ return false
+ }
+ if (signals.every(signal => signal?.aborted)) return false
+ let resolve!: () => void
+ let reject!: (error: unknown) => void
+ const pending = new Promise<void>((onResolve, onReject) => {
+ resolve = onResolve
+ reject = onReject
+ })
+ // A recovery can have no current waiter. Keep its rejection handled until a
+ // consumer joins at the deadline; that consumer still receives the real error.
+ void pending.catch(() => undefined)
+ const controller = new AbortController()
+ const interests = new Set<AbortSignal | undefined>()
+ const watchedSignals = new Set<AbortSignal>()
+ const onAbort = () => {
+ if (!Array.from(interests).every(signal => signal?.aborted)) return
+ const entry = recoveries.get(key)
+ if (!entry) return
+ entry.state = 'failed'
+ disposeRecovery(entry)
+ }
+ const entry: RecoveryEntry = {
+ deadlineMs,
+ controller,
+ pending,
+ resolve,
+ reject,
+ state: 'scheduled',
+ removeListeners: () =>
+ watchedSignals.forEach(signal => signal.removeEventListener('abort', onAbort)),
+ addSubscribers: addedSignals => {
+ for (const signal of addedSignals) {
+ if (signal?.aborted || interests.has(signal)) continue
+ interests.add(signal)
+ if (signal) {
+ watchedSignals.add(signal)
+ signal.addEventListener('abort', onAbort, { once: true })
+ }
+ }
+ },
+ }
+ entry.addSubscribers(signals)
+ while (recoveries.size >= METADATA_READ_CACHE_MAX_ENTRIES) {
+ const oldest = recoveries.keys().next().value
+ if (oldest === undefined) break
+ const oldEntry = recoveries.get(oldest)
+ if (oldEntry) disposeRecovery(oldEntry)
+ recoveries.delete(oldest)
+ }
+ recoveries.set(key, entry)
+ const schedule = () => {
+ // Native timers cap their delay at 2^31-1 ms; chunk longer server deadlines
+ // rather than letting the platform clamp them into an immediate retry.
+ entry.timer = setTimeout(
+ () => {
+ if (recoveries.get(key) !== entry || controller.signal.aborted) return
+ if (Date.now() < entry.deadlineMs) {
+ schedule()
+ return
+ }
+ entry.timer = undefined
+ entry.state = 'running'
+ recover(controller.signal)
+ },
+ Math.min(2_147_483_647, Math.max(0, entry.deadlineMs - Date.now()))
+ )
+ }
+ schedule()
+ return true
+}
+
+export function completeReadRequestRecovery(key: string): void {
+ const recovery = recoveries.get(key)
+ if (recovery?.timer) clearTimeout(recovery.timer)
+ recovery?.removeListeners()
+ recovery?.resolve()
+ recoveries.delete(key)
+}
+
+export function failReadRequestRecovery(key: string, error: unknown): void {
+ const recovery = recoveries.get(key)
+ if (!recovery) return
+ recovery.state = 'failed'
+ recovery.removeListeners()
+ recovery.reject(error)
+}
+
+export function __resetReadRequestCacheForTests(): void {
+ principal = null
+ if (invalidationChannel) {
+ invalidationChannel.close()
+ invalidationChannel = null
+ }
+ clearReadRequestCache()
+ invalidationHandler?.()
+}
diff --git a/control-ui/lib/subscriptionCapabilities.ts b/control-ui/lib/subscriptionCapabilities.ts
new file mode 100644
index 000000000..e9b714bc0
--- /dev/null
+++ b/control-ui/lib/subscriptionCapabilities.ts
@@ -0,0 +1,68 @@
+import { apiGet } from './api'
+import type { ApiRequestOptions } from './api.types'
+
+export const SUBSCRIPTION_CAPABILITIES_API_PATH = '/api/v1/admin/llm/providers/capabilities'
+
+export type SubscriptionCapabilityProviderId = 'codex-subscription' | 'grok-subscription'
+
+export type SubscriptionCapabilities = {
+ providers: Record<SubscriptionCapabilityProviderId, { enabled: boolean }>
+}
+
+export type SubscriptionCapabilityLoadOptions = {
+ refresh?: boolean
+ signal?: AbortSignal
+}
+
+function providerId(value: string): SubscriptionCapabilityProviderId | null {
+ return value === 'codex-subscription' || value === 'grok-subscription' ? value : null
+}
+
+export function sanitizeSubscriptionCapabilities(raw: unknown): SubscriptionCapabilities {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
+ throw new Error('Subscription capabilities response is not an object')
+ }
+ const providers = (raw as { providers?: unknown }).providers
+ if (!providers || typeof providers !== 'object' || Array.isArray(providers)) {
+ throw new Error('Subscription capabilities providers are invalid')
+ }
+ const result = {
+ providers: {
+ 'codex-subscription': { enabled: false },
+ 'grok-subscription': { enabled: false },
+ },
+ } as SubscriptionCapabilities
+ let seenCodex = false
+ let seenGrok = false
+ for (const [id, value] of Object.entries(providers as Record<string, unknown>)) {
+ const provider = providerId(id)
+ if (!provider) continue
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new Error(`Subscription capability for ${id} is invalid`)
+ }
+ const enabled = (value as { enabled?: unknown }).enabled
+ if (typeof enabled !== 'boolean') {
+ throw new Error(`Subscription capability for ${id} is invalid`)
+ }
+ result.providers[provider] = { enabled }
+ seenCodex ||= provider === 'codex-subscription'
+ seenGrok ||= provider === 'grok-subscription'
+ }
+ if (!seenCodex || !seenGrok) {
+ throw new Error('Subscription capabilities response is incomplete')
+ }
+ return result
+}
+
+export async function loadSubscriptionCapabilities(
+ options: SubscriptionCapabilityLoadOptions = {}
+): Promise<SubscriptionCapabilities> {
+ const requestOptions: ApiRequestOptions = {
+ signal: options.signal,
+ refresh: options.refresh,
+ metadataRead: 'subscription-capabilities',
+ }
+ return sanitizeSubscriptionCapabilities(
+ await apiGet(SUBSCRIPTION_CAPABILITIES_API_PATH, {}, requestOptions)
+ )
+}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 3a394d317..ace5d18fc 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.703",
+ "version": "0.1.704",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.703",
+ "version": "0.1.704",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/control-ui/package.json b/control-ui/package.json
index 17049afb2..7b4f7e30a 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.703",
+ "version": "0.1.704",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",