Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add Codex subscription sign-in UX (#5591)
Adam Eivy93948820eb93
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsxindex f6d46e3843..92bd664331 100644--- a/client/src/components/providers/ProviderCard.jsx+++ b/client/src/components/providers/ProviderCard.jsx@@ -12,12 +12,13 @@*/import { Link } from 'react-router';-import { Network, Terminal } from 'lucide-react';+import { ExternalLink, Network, Terminal } from 'lucide-react';import {CONTEXT_WINDOW_SOURCE,PROVIDER_CARD_STATE,filterHardwareCompatibleProviderModels,isApiProvider,+ isCodexSubscriptionProvider,gatewayForProvider,isPrivateNetworkEndpoint,isFleetProvider,@@ -31,6 +32,7 @@ import {supportsModelRefresh,} from '../../utils/providers';import { formatContextLength } from '../../utils/formatters';+import { isHttpsUrl } from '../../utils/urlNormalize';import ProviderRuntimeStatus from './ProviderRuntimeStatus';import ProviderReadiness from './ProviderReadiness';import { GatewayKeyHint } from './ProviderNotices';@@ -62,6 +64,12 @@ export const CARD_STATE_STYLES = {badge: 'bg-port-warning/20 text-port-warning',hint: 'Missing a prerequisite — install the CLI or add the API key to use it.',},+ [PROVIDER_CARD_STATE.UNKNOWN]: {+ label: 'CHECK ACCOUNT',+ border: 'border-port-warning/50',+ badge: 'bg-port-warning/20 text-port-warning',+ hint: 'PortOS could not determine the ChatGPT subscription state yet.',+ },[PROVIDER_CARD_STATE.DISABLED]: {label: 'DISABLED',border: 'border-port-border',@@ -97,6 +105,17 @@ export default function ProviderCard({onUseServedModel,onServeWantedModel,servingModel = false,+ codexAccount,+ codexModels = null,+ codexAccountLoading = false,+ codexLoginLoading = false,+ onCodexCheckAccount,+ onCodexSignIn,+ onCodexCancelLogin,+ onCodexLogout,+ onCodexRefreshModels,+ onCodexCopyCode,+ onCodexEnable,}) {const style = CARD_STATE_STYLES[cardState.state];const compatibleModels = filterHardwareCompatibleProviderModels(provider.models, provider);@@ -111,6 +130,9 @@ export default function ProviderCard({// `cardState`, not `provider.enabled`, so the setup widgets below can never// tone one way while the badge, border, and section file the card another.const optional = cardState.state === PROVIDER_CARD_STATE.DISABLED;+ const codexSubscription = isCodexSubscriptionProvider(provider);+ const subscriptionAccountReady = !codexSubscription || codexAccount?.status === 'ready';+ const subscriptionReady = !codexSubscription || (subscriptionAccountReady && provider.textTransportEnabled === true);return (<divclassName={`@container bg-port-card border border-l-4 rounded-xl p-4 ${style.border} ${style.dim || ''} ${@@ -236,7 +258,7 @@ export default function ProviderCard({<buttononClick={() => onTest(provider.id)}- disabled={testResult?.testing}+ disabled={testResult?.testing || !subscriptionReady}className="px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors disabled:opacity-50">{testResult?.testing ? 'Testing...' : 'Test'}@@ -255,6 +277,7 @@ export default function ProviderCard({<buttononClick={() => onToggleEnabled(provider)}+ disabled={!provider.enabled && !subscriptionAccountReady}className={`px-3 py-1.5 text-sm rounded transition-colors ${provider.enabled? 'bg-port-warning/20 text-port-warning hover:bg-port-warning/30'@@ -267,6 +290,7 @@ export default function ProviderCard({{!isDefault && provider.enabled && (<buttononClick={() => onSetActive(provider.id)}+ disabled={!subscriptionReady}className="px-3 py-1.5 text-sm bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded transition-colors">Set Default@@ -292,6 +316,22 @@ export default function ProviderCard({{/* Card body — full width, below the header row rather than beside theaction buttons. */}<div className="mt-3 space-y-2">+ {codexSubscription && (+ <CodexSubscriptionPanel+ account={codexAccount}+ models={codexModels}+ loading={codexAccountLoading}+ loginLoading={codexLoginLoading}+ onCheck={onCodexCheckAccount}+ onSignIn={onCodexSignIn}+ onCancel={onCodexCancelLogin}+ onLogout={onCodexLogout}+ onRefreshModels={onCodexRefreshModels}+ onCopyCode={onCodexCopyCode}+ subscriptionEnabled={provider.textTransportEnabled === true}+ onEnable={onCodexEnable}+ />+ )}<ProviderRuntimeStatusruntime={runtime}onInstall={onInstallRuntime}@@ -485,3 +525,111 @@ export default function ProviderCard({</div>);}++const BUTTON_CLASS = 'px-3 py-1.5 text-sm rounded transition-colors bg-port-accent/20 text-port-accent hover:bg-port-accent/30 disabled:opacity-50 disabled:cursor-not-allowed';++const quotaText = (window) => {+ if (!window || typeof window !== 'object') return null;+ const used = typeof window.usedPercent === 'number' ? Math.max(0, Math.min(100, Math.round(window.usedPercent))) : null;+ const label = typeof window.limitName === 'string' && window.limitName.trim() ? window.limitName.trim() : 'Usage window';+ const reset = typeof window.resetsAt === 'string' && window.resetsAt.trim() ? ` · resets ${window.resetsAt.trim()}` : '';+ return used === null ? `${label}${reset}` : `${label}: ${used}% used${reset}`;+};++function CodexSubscriptionPanel({+ account,+ models,+ loading,+ loginLoading,+ onCheck,+ onSignIn,+ onCancel,+ onLogout,+ onRefreshModels,+ onCopyCode,+ subscriptionEnabled,+ onEnable,+}) {+ const status = account?.status || 'unknown';+ const login = account?.login;+ const verificationUrl = isHttpsUrl(login?.verificationUrl) ? login.verificationUrl : null;+ const authUrl = isHttpsUrl(login?.authUrl) ? login.authUrl : null;+ const windows = [quotaText(account?.rateLimits?.primary), quotaText(account?.rateLimits?.secondary)].filter(Boolean);+ const catalogCount = Array.isArray(models?.models) ? models.models.length : null;+ const modelError = models?.error;+ const action = status === 'runtime-missing'+ ? 'Install Codex CLI from the runtime control below.'+ : status === 'signed-out' || status === 'reauth-required'+ ? 'Sign in with ChatGPT to use this subscription.'+ : status === 'quota-exhausted'+ ? 'Wait for a reported usage window to reset, then check the account again.'+ : status === 'login-pending'+ ? 'Finish sign-in in the opened browser or use the device-code fallback.'+ : status === 'ready'+ ? 'This provider uses ChatGPT subscription limits, not an OpenAI API key.'+ : 'Check the account again. PortOS could not determine this state.';++ return (+ <div className="max-w-3xl text-xs rounded border border-port-border bg-port-bg/50 px-3 py-2.5 space-y-2">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <p className="font-medium text-gray-200">ChatGPT subscription</p>+ <span className="text-gray-400">{account?.account?.planType ? `${account.account.planType} plan` : status.replaceAll('-', ' ')}</span>+ </div>+ <p className="text-gray-400">{action}</p>+ {windows.length > 0 && <p className="text-gray-400">{windows.join(' · ')}</p>}+ {typeof account?.checkedAt === 'number' && <p className="text-gray-500">Last usage refresh: {new Date(account.checkedAt).toLocaleString()}</p>}+ {catalogCount !== null && <p className="text-gray-500">Subscription catalog: {catalogCount} model{catalogCount === 1 ? '' : 's'} available.</p>}+ {modelError && <p className="text-port-warning">Using the last known model catalog while a refresh is unavailable.</p>}+ {verificationUrl && (+ <div className="rounded bg-port-card px-2.5 py-2 text-gray-300 space-y-1">+ <p>Headless sign-in: open the verification page and enter this code.</p>+ {login.userCode && (+ <div className="flex flex-wrap items-center gap-2">+ <code className="text-port-accent font-semibold">{login.userCode}</code>+ <button type="button" className={BUTTON_CLASS} onClick={() => onCopyCode?.(login.userCode)}>Copy code</button>+ </div>+ )}+ <a className="inline-flex items-center gap-1 text-port-accent hover:underline" href={verificationUrl} target="_blank" rel="noreferrer">+ Open verification page <ExternalLink size={12} />+ </a>+ </div>+ )}+ {authUrl && (+ <a className="inline-flex items-center gap-1 text-port-accent hover:underline" href={authUrl} target="_blank" rel="noreferrer">+ Open ChatGPT sign-in <ExternalLink size={12} />+ </a>+ )}+ <div className="flex flex-wrap gap-2">+ {(status === 'signed-out' || status === 'reauth-required' || status === 'unknown') && (+ <button type="button" className={BUTTON_CLASS} disabled={loading || loginLoading} onClick={() => onSignIn?.(false)}>+ {loginLoading ? 'Starting sign-in…' : 'Sign in with ChatGPT'}+ </button>+ )}+ {(status === 'signed-out' || status === 'reauth-required' || status === 'login-pending' || status === 'unknown') && (+ <button type="button" className="px-3 py-1.5 text-sm rounded transition-colors bg-port-border hover:bg-port-border/80 text-white disabled:opacity-50" disabled={loading || loginLoading} onClick={() => onSignIn?.(true)}>+ Use device code+ </button>+ )}+ {status === 'login-pending' && login?.loginId && (+ <button type="button" className="px-3 py-1.5 text-sm rounded transition-colors bg-port-warning/20 text-port-warning hover:bg-port-warning/30 disabled:opacity-50" disabled={loading || loginLoading} onClick={() => onCancel?.(login.loginId)}>+ Cancel sign-in+ </button>+ )}+ {status === 'ready' && (+ <>+ {!subscriptionEnabled && (+ <button type="button" className={BUTTON_CLASS} disabled={loading} onClick={onEnable}>+ Enable subscription transport+ </button>+ )}+ <button type="button" className={BUTTON_CLASS} disabled={loading} onClick={onRefreshModels}>Refresh subscription models</button>+ <button type="button" className="px-3 py-1.5 text-sm rounded transition-colors bg-port-warning/20 text-port-warning hover:bg-port-warning/30 disabled:opacity-50" disabled={loading} onClick={onLogout}>Log out</button>+ </>+ )}+ {(status === 'quota-exhausted' || status === 'unknown') && (+ <button type="button" className={BUTTON_CLASS} disabled={loading} onClick={onCheck}>{loading ? 'Checking…' : 'Check account'}</button>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/components/providers/ProviderCard.test.jsx b/client/src/components/providers/ProviderCard.test.jsxindex 14c97af7a1..e4e5f16223 100644--- a/client/src/components/providers/ProviderCard.test.jsx+++ b/client/src/components/providers/ProviderCard.test.jsx@@ -84,3 +84,52 @@ describe('ProviderCard fleet identity', () => {expect(screen.queryByText('FLEET HOST')).not.toBeInTheDocument();});});++describe('ProviderCard ChatGPT subscription', () => {+ it('shows a safe sign-in action without rendering account identity or credentials', () => {+ render(+ <MemoryRouter>+ <ProviderCard+ provider={{ id: 'codex', name: 'Codex', type: 'cli', command: 'codex', models: [], enabled: true }}+ cardState={{ state: PROVIDER_CARD_STATE.BLOCKED, missing: [{ code: 'codexAccount', label: 'No ChatGPT account is signed in' }] }}+ runtime={null}+ status={null}+ isDefault={false}+ providersById={{}}+ runnerAllowedCommands={[]}+ testResult={null}+ codexAccount={{+ status: 'signed-out',+ account: { accountId: 'private-account', email: '[email protected]' },+ rateLimits: null,+ }}+ />+ </MemoryRouter>+ );++ expect(screen.getByRole('button', { name: 'Sign in with ChatGPT' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Use device code' })).toBeInTheDocument();+ expect(screen.queryByText('private-account')).toBeNull();+ expect(screen.queryByText('[email protected]')).toBeNull();+ });++ it('does not render a non-HTTPS sign-in link', () => {+ render(+ <MemoryRouter>+ <ProviderCard+ provider={{ id: 'codex', name: 'Codex', type: 'cli', command: 'codex', models: [], enabled: true }}+ cardState={{ state: PROVIDER_CARD_STATE.BLOCKED, missing: [{ code: 'codexAccount', label: 'No ChatGPT account is signed in' }] }}+ runtime={null}+ status={null}+ isDefault={false}+ providersById={{}}+ runnerAllowedCommands={[]}+ testResult={null}+ codexAccount={{ status: 'login-pending', login: { authUrl: 'javascript:alert(1)' } }}+ />+ </MemoryRouter>+ );++ expect(screen.queryByRole('link', { name: 'Open ChatGPT sign-in' })).toBeNull();+ });+});diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex c5eaac0f81..d6dab5a3c6 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -4,7 +4,9 @@ import { AlertTriangle, Gauge, Network } from 'lucide-react';import toast from '../components/ui/Toast';import * as api from '../services/api';import socket from '../services/socket';-import { filterHardwareCompatibleProviderModels, filterSelectableModels, filterGenerationModels, isEmbeddingModel, isProviderHardwareCompatible, isProviderModelHardwareCompatible, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isLocalEndpoint, isLocalInstanceProvider, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, gatewayForProvider, isClaudeCommandProvider, generationControlsFor, providerRuntimeKey, providerCardState, PROVIDER_CARD_STATE } from '../utils/providers';+import { filterHardwareCompatibleProviderModels, filterSelectableModels, filterGenerationModels, isEmbeddingModel, isProviderHardwareCompatible, isProviderModelHardwareCompatible, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isCodexSubscriptionProvider, isLocalEndpoint, isLocalInstanceProvider, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, gatewayForProvider, isClaudeCommandProvider, generationControlsFor, providerRuntimeKey, providerCardState, PROVIDER_CARD_STATE } from '../utils/providers';+import { copyToClipboard } from '../lib/clipboard';+import { isHttpsUrl } from '../utils/urlNormalize';import useLocalModels from '../hooks/useLocalModels';import { useAutoRefetch } from '../hooks/useAutoRefetch';import BrailleSpinner from '../components/BrailleSpinner';@@ -60,7 +62,7 @@ export const PROVIDER_SECTIONS = [title: 'Needs setup',hint: 'Switched on but missing a CLI or an API key — these cannot run yet',dot: 'bg-port-warning',- states: [PROVIDER_CARD_STATE.BLOCKED],+ states: [PROVIDER_CARD_STATE.BLOCKED, PROVIDER_CARD_STATE.UNKNOWN],},{key: 'disabled',@@ -122,6 +124,13 @@ export default function AIProviders() {const [loadError, setLoadError] = useState(false);const [testResults, setTestResults] = useState({});const [refreshing, setRefreshing] = useState({});+ // `undefined` = this page has not asked the account endpoint yet; `null` =+ // the endpoint did not give a verdict. The distinction keeps a failed fetch+ // from posing as either signed out or ready.+ const [codexAccount, setCodexAccount] = useState(undefined);+ const [codexModels, setCodexModels] = useState(null);+ const [codexAccountLoading, setCodexAccountLoading] = useState(false);+ const [codexLoginLoading, setCodexLoginLoading] = useState(false);const [showRunPanel, setShowRunPanel] = useState(false);const [runPrompt, setRunPrompt] = useState('');const [selectedWorkspace, setSelectedWorkspace] = useState('');@@ -140,6 +149,52 @@ export default function AIProviders() {() => sampleProviders.filter(isProviderHardwareCompatible),[sampleProviders],);+ const hasCodexSubscriptionProvider = providers.some(isCodexSubscriptionProvider);++ const mergeCodexCatalog = useCallback((catalog) => {+ if (!Array.isArray(catalog)) return;+ const ids = catalog.map((model) => (typeof model === 'string' ? model : model?.id))+ .filter((id) => typeof id === 'string' && id.trim() !== '');+ setProviders((current) => current.map((provider) => (+ isCodexSubscriptionProvider(provider)+ ? { ...provider, models: mergeModelLists(provider.models, ids) }+ : provider+ )));+ }, []);++ const loadCodexModels = useCallback(async (fresh = false) => {+ const result = await api.getCodexModels({ fresh, silent: true }).catch(() => null);+ if (!result || !Object.hasOwn(result, 'models')) return null;+ setCodexModels(result);+ // `null` is never fetched; an empty list is a real catalog. Only merge a+ // real array, preserving every current default/tier pin even if it is no+ // longer in the catalog so the form can show it as stale rather than clear+ // a saved choice behind the user's back.+ mergeCodexCatalog(result.models);+ return result;+ }, [mergeCodexCatalog]);++ const loadCodexAccount = useCallback(async (fresh = false) => {+ // Compatibility with a server that predates the account endpoint. The+ // normal client library always has this function; the guard makes a mixed+ // client/server upgrade leave the established provider controls intact.+ if (typeof api.getCodexAccount !== 'function') return undefined;+ setCodexAccountLoading(true);+ const result = await api.getCodexAccount({ fresh, silent: true }).catch(() => null);+ const readiness = result?.readiness && typeof result.readiness === 'object' ? result.readiness : null;+ setCodexAccount(readiness);+ setCodexAccountLoading(false);+ if (readiness?.status === 'ready') loadCodexModels(fresh);+ return readiness;+ }, [loadCodexModels]);++ useEffect(() => {+ if (hasCodexSubscriptionProvider) loadCodexAccount();+ else {+ setCodexAccount(undefined);+ setCodexModels(null);+ }+ }, [hasCodexSubscriptionProvider, loadCodexAccount]);// CLI availability per provider card, keyed by `providerRuntimeKey`. An empty// map means the endpoint was not reached (for example, an older server during// an upgrade) — distinct from a confirmed missing CLI — and simply renders no@@ -274,7 +329,11 @@ export default function AIProviders() {// `useAutoRefetch` rather than a raw interval so both polls pause while the// tab is hidden — a readiness tick costs one HTTP probe per distinct local// endpoint, which a backgrounded settings tab should not keep spending.- const pollCards = useCallback(() => Promise.all([refreshStatuses(), loadReadiness()]), [refreshStatuses, loadReadiness]);+ const pollCards = useCallback(() => Promise.all([+ refreshStatuses(),+ loadReadiness(),+ hasCodexSubscriptionProvider ? loadCodexAccount() : Promise.resolve(),+ ]), [refreshStatuses, loadReadiness, hasCodexSubscriptionProvider, loadCodexAccount]);useAutoRefetch(pollCards, 20000, { pollOnly: true });// Clear a provider's bench (runtime unavailability) so the next call retries it.@@ -310,10 +369,73 @@ export default function AIProviders() {};const handleToggleEnabled = async (provider) => {- await api.updateProvider(provider.id, { enabled: !provider.enabled });+ await api.updateProvider(provider.id, {+ enabled: !provider.enabled,+ });loadData();};+ const handleEnableCodexSubscription = async (provider) => {+ const updated = await api.updateProvider(provider.id, { textTransportEnabled: true }, { silent: true }).catch(() => null);+ if (!updated) {+ toast.error('Could not save the ChatGPT subscription transport');+ return;+ }+ setProviders((current) => current.map((entry) => (+ entry.id === provider.id ? { ...entry, textTransportEnabled: true } : entry+ )));+ toast.success('ChatGPT subscription transport enabled');+ };++ const handleCodexSignIn = async (deviceCode) => {+ setCodexLoginLoading(true);+ const result = await api.startCodexLogin(deviceCode, { silent: true }).catch(() => null);+ setCodexLoginLoading(false);+ if (!result?.login) {+ toast.error('Could not start ChatGPT sign-in');+ return;+ }+ const login = {+ ...result.login,+ authUrl: isHttpsUrl(result.login.authUrl) ? result.login.authUrl : null,+ verificationUrl: isHttpsUrl(result.login.verificationUrl) ? result.login.verificationUrl : null,+ };+ setCodexAccount((current) => ({+ ...(current && typeof current === 'object' ? current : {}),+ status: 'login-pending',+ login,+ }));+ if (login.authUrl) window.open(login.authUrl, '_blank', 'noopener,noreferrer');+ };++ const handleCancelCodexLogin = async (loginId) => {+ setCodexLoginLoading(true);+ const result = await api.cancelCodexLogin(loginId, { silent: true }).catch(() => null);+ setCodexLoginLoading(false);+ if (!result?.readiness) {+ toast.error('Could not cancel ChatGPT sign-in');+ return;+ }+ setCodexAccount(result.readiness);+ };++ const handleCodexLogout = async () => {+ setCodexAccountLoading(true);+ const result = await api.codexLogout({ silent: true }).catch(() => null);+ setCodexAccountLoading(false);+ if (!result?.readiness) {+ toast.error('Could not log out of ChatGPT');+ return;+ }+ setCodexAccount(result.readiness);+ toast.success('ChatGPT subscription signed out');+ };++ const handleCopyCodexDeviceCode = async (code) => {+ if (await copyToClipboard(code)) toast.success('Device code copied');+ else toast.error('Could not copy the device code');+ };+// llama.cpp (and similar local daemons) answer as a single model id — the// server's `--alias`, not the preset name on this card. Matching the// provider's default to what is actually served is the in-place fix for the@@ -511,6 +633,7 @@ export default function AIProviders() {const readinessById = Object.fromEntries(providers.map((provider) => [provider.id, providerCardState(provider, {runtime: runtimeById[provider.id],status: statuses[provider.id],+ codexAccount: isCodexSubscriptionProvider(provider) ? codexAccount : undefined,keySetFor: (id) => {const referenced = byId[id];// The list is authoritative once this memo runs. A missing sibling was@@ -541,7 +664,7 @@ export default function AIProviders() {: runnable.filter(p => section.states.includes(readinessById[p.id].state))),])),};- }, [providers, statuses, activeProviderId, runtimeForProvider]);+ }, [providers, statuses, activeProviderId, runtimeForProvider, codexAccount]);// Resolved only once the list has loaded, so an /ai/edit/:providerId reload can't// flash the editor in "Add Provider" mode before the record arrives. An id@@ -870,7 +993,18 @@ export default function AIProviders() {onUseServedModel={handleUseServedModel}onServeWantedModel={handleServeWantedModel}servingModel={Boolean(servingModel[provider.id])}- />+ codexAccount={isCodexSubscriptionProvider(provider) ? codexAccount : undefined}+ codexModels={codexModels}+ codexAccountLoading={codexAccountLoading}+ codexLoginLoading={codexLoginLoading}+ onCodexCheckAccount={() => loadCodexAccount(true)}+ onCodexSignIn={handleCodexSignIn}+ onCodexCancelLogin={handleCancelCodexLogin}+ onCodexLogout={handleCodexLogout}+ onCodexRefreshModels={() => loadCodexModels(true)}+ onCodexCopyCode={handleCopyCodexDeviceCode}+ onCodexEnable={() => handleEnableCodexSubscription(provider)}+ />))}</CollapsibleSection>);diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsxindex d71f0b0993..43d2dee3c6 100644--- a/client/src/pages/AIProviders.test.jsx+++ b/client/src/pages/AIProviders.test.jsx@@ -8,6 +8,14 @@ const api = vi.hoisted(() => ({getProviderStatuses: vi.fn(),getProviderRuntimes: vi.fn(),getProviderReadiness: vi.fn(),+ // Kept pending by default so existing page tests that use a Codex fixture do+ // not accidentally assert a subscription account state. Subscription-specific+ // tests replace this with a bounded readiness response.+ getCodexAccount: vi.fn(() => new Promise(() => {})),+ getCodexModels: vi.fn(),+ startCodexLogin: vi.fn(),+ cancelCodexLogin: vi.fn(),+ codexLogout: vi.fn(),getInstances: vi.fn(),getSampleProviders: vi.fn(),createProvider: vi.fn(),@@ -90,6 +98,7 @@ describe('AIProviders page load error handling', () => {api.getProviderStatuses.mockResolvedValue({ providers: {} });api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });api.getProviderReadiness.mockResolvedValue({ readiness: {} });+ api.getCodexAccount.mockImplementation(() => new Promise(() => {}));localModels.value = { ctxById: {}, installed: { ollama: null, lmstudio: null } };});diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.jsindex d4f494d10d..8f3fffc9ad 100644--- a/client/src/services/apiProviders.js+++ b/client/src/services/apiProviders.js@@ -14,9 +14,10 @@ export const createProvider = (data) => request('/providers', {method: 'POST',body: JSON.stringify(data)});-export const updateProvider = (id, data) => request(`/providers/${id}`, {+export const updateProvider = (id, data, options = {}) => request(`/providers/${id}`, {method: 'PUT',- body: JSON.stringify(data)+ body: JSON.stringify(data),+ ...options,});export const deleteProvider = (id) => request(`/providers/${id}`, { method: 'DELETE' });export const getSampleProviders = () => request('/providers/samples');diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 866e328b1d..09f452826b 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -38,10 +38,10 @@ grep -i "what you want to do" client/src/utils/README.md| `hashString` | Deterministic string → 32-bit hash (stable colors, keys, seeds). || `modelFit` | `fitModelToHeight(object, { targetHeight, feetOnGround, yOffset })` — normalize a loaded GLB to a fixed on-screen height and anchor it vertically, either by bounding-box center (portrait framing) or by its lowest point (a figure standing on a ground plane). Recenters x/z, guards a zero-height model against an infinite scale, leaves a geometry-less object or a non-finite `targetHeight` untouched rather than writing `NaN`/`Infinity` through the transform, and resets to identity before measuring so a repeat call (StrictMode's double mount effect) converges instead of blowing the model back up. Call from an effect, never during render — a skinned mesh measures wrong before `useAnimations` binds the skeleton. || `sleep` | `sleep(ms)` — promise-returning `setTimeout` for retry backoffs and race timeouts. Use instead of re-declaring a local `delay`. |-| `urlNormalize` | `isUrl` detection, `normalizeUrl` (optional git/`requireDot` modes), `isHttpUrl` (explicit http(s) only — safe-href check), and `tiktokVideoId` / `tiktokEmbedSrc` (host-anchored TikTok video-id extraction + its Embed Player URL, so a reference embeds without loading TikTok's embed.js). |+| `urlNormalize` | `isUrl` detection, `normalizeUrl` (optional git/`requireDot` modes), `isHttpUrl` / `isHttpsUrl` (safe-href checks), and `tiktokVideoId` / `tiktokEmbedSrc` (host-anchored TikTok video-id extraction + its Embed Player URL, so a reference embeds without loading TikTok's embed.js). || `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. || `navWorkingSet` | Recent/pinned nav persistence (`recordVisit`, `togglePin`, `isPinned`) plus `resolveRecentNavEntries` for mapping stored deep links back to their longest matching nav-manifest entry. Also `migrateLegacyNavPath(path, commands)` — maps a stored path onto the CURRENT path of the page that used to answer to it, driven by each command's own `previousPaths` (declared in `server/lib/navManifest.js` beside the page that moved, shipped whole in the palette manifest). A pin is a stored route path, so without it a moved page's pin stops matching the manifest and the sidebar row silently vanishes on update. |-| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isAntigravityProvider`, `isLaunchableTuiProvider` — a TUI provider carrying the server-resolved `tuiCommandLine`, i.e. one a human can start at a shell prompt; shared by the Providers card's "Launch in Shell" button and the Shell page's launch menu so the two can't disagree — `PROVIDER_GATEWAYS` / `gatewayForProvider` / `isGatewayBackedProvider` (an OpenCode wrapper front-ending a hosted OpenAI-compatible gateway — `orcarouter`, `openrouter` — which inherits its API key at spawn time from the sibling API provider whose id equals the gateway id; reads the generic `gatewayBacked` marker and, forever, the legacy per-gateway boolean. MIRROR of `server/lib/providerGateways.js`, which the browser cannot import; keep the three copies in lockstep), `filterSelectableModels`, `resolveCliEffort` (mirror — what a stored effort actually runs as, so the picker can name a clamped level), `configuredDefaultIn` — the sentinel a provider's catalog carries, so a picker can render an option matching a sentinel-valued tier instead of a blank select — `getProviderTimeout`, `resolveEffectiveProvider` — the provider a record actually runs on (its pin, else the active provider) plus whether it fell back, so a "Default" option can name what it resolves to — `resolveSeriesRunLlm` (mirror of server `seriesLlmOverride.js`: which provider/model a Pipeline **series** run resolves to — per-run override → `series.llm` → active provider) and `providerModelLabel` (the one "Provider / model" phrasing), configured-default sentinels, and the claude/codex/agy thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). `TOOL_FREE_LOCAL_PROVIDER_IDS`, `TOOL_FREE_LOCAL_TEXT_CAPABILITIES`, `isToolFreeLocalProvider`, `isToolFreeLocalModel`, and `toolFreeLocalSelectionPolicy` share the fail-closed local/text/no-tools filter used by security-sensitive provider/model/effort pickers. Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner (`/spawn`, `/spawn-tui`) accept this command? Mirrors only the *normalization* in `server/cos-runner/allowedCommands.js` (the list itself arrives as `runnerAllowedCommands` on `GET /api/providers`, because the allowlist is an exec boundary and stays hand-curated server-side); returns `null` for "list not fetched / field blank" so a failed fetch never renders a warning. Pinned by `server/cos-runner/allowedCommands.parity.test.js`. `isPrivateNetworkEndpoint(endpoint)` — loopback, RFC1918/tailnet address, or a `.local`/`.ts.net`/single-label host, i.e. somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key. `isLocalInstanceProvider(provider)` — the narrower question, mirroring server `localProviderRuntime.js#isLocalInstanceEndpoint`: does this provider talk to a daemon on THIS machine (loopback, or no endpoint at all)? Gate anything that explains a provider by inspecting the host PortOS runs on — install state, "start it from Settings → Local LLM" — since `localBackendForProvider` matches by NAME and would otherwise claim a peer's LM Studio. And `credentialSource(provider)` plus `providerCardState(provider, { runtime, status, keySetFor, envVarSet })` + `PROVIDER_CARD_STATE` — is a provider ready to run, benched, blocked on a missing prerequisite (CLI not installed / API key absent / empty credential environment variable), or simply switched off? Reads the SERVER's `missingPrerequisites` (published per provider on `GET /api/providers` from `server/lib/providerPrerequisites.js`, and the same computation `getFallbackProvider` routes on) and adds the local-app runtime shape plus tri-state checks for stored, inherited, and process environment credentials. Unknown lookup values mean "not probed", never "missing". Drives the AI Providers page card colors and grouping — distinct from `ProviderReadiness`/`GET /api/providers/readiness`, which probes the local daemon behind a provider. `resolvesOutsidePortosPath(provider)` — does this provider resolve its binary somewhere the runtime probe never looked (an explicit path in `command`, or its own `PATH` in `envVars`)? Mirror of the same two guards in the server's `providerRuntimeKey`, and what keeps the card's badge from accusing a working provider the router happily routes. And `providerRuntimeKey(provider)` — the key a provider's runtime is published under by `GET /api/providers/runtimes`, so a card can show its CLI install status (bare binary name for a cli/tui provider, provider id for an API provider fronted by a local app); the runtime table itself stays server-side. |+| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isCodexSubscriptionProvider` (subscription readiness is keyed on the `codex` command, never an editable id), `isAntigravityProvider`, `isLaunchableTuiProvider` — a TUI provider carrying the server-resolved `tuiCommandLine`, i.e. one a human can start at a shell prompt; shared by the Providers card's "Launch in Shell" button and the Shell page's launch menu so the two can't disagree — `PROVIDER_GATEWAYS` / `gatewayForProvider` / `isGatewayBackedProvider` (an OpenCode wrapper front-ending a hosted OpenAI-compatible gateway — `orcarouter`, `openrouter` — which inherits its API key at spawn time from the sibling API provider whose id equals the gateway id; reads the generic `gatewayBacked` marker and, forever, the legacy per-gateway boolean. MIRROR of `server/lib/providerGateways.js`, which the browser cannot import; keep the three copies in lockstep), `filterSelectableModels`, `resolveCliEffort` (mirror — what a stored effort actually runs as, so the picker can name a clamped level), `configuredDefaultIn` — the sentinel a provider's catalog carries, so a picker can render an option matching a sentinel-valued tier instead of a blank select — `getProviderTimeout`, `resolveEffectiveProvider` — the provider a record actually runs on (its pin, else the active provider) plus whether it fell back, so a "Default" option can name what it resolves to — `resolveSeriesRunLlm` (mirror of server `seriesLlmOverride.js`: which provider/model a Pipeline **series** run resolves to — per-run override → `series.llm` → active provider) and `providerModelLabel` (the one "Provider / model" phrasing), configured-default sentinels, and the claude/codex/agy thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). `TOOL_FREE_LOCAL_PROVIDER_IDS`, `TOOL_FREE_LOCAL_TEXT_CAPABILITIES`, `isToolFreeLocalProvider`, `isToolFreeLocalModel`, and `toolFreeLocalSelectionPolicy` share the fail-closed local/text/no-tools filter used by security-sensitive provider/model/effort pickers. Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner (`/spawn`, `/spawn-tui`) accept this command? Mirrors only the *normalization* in `server/cos-runner/allowedCommands.js` (the list itself arrives as `runnerAllowedCommands` on `GET /api/providers`, because the allowlist is an exec boundary and stays hand-curated server-side); returns `null` for "list not fetched / field blank" so a failed fetch never renders a warning. Pinned by `server/cos-runner/allowedCommands.parity.test.js`. `isPrivateNetworkEndpoint(endpoint)` — loopback, RFC1918/tailnet address, or a `.local`/`.ts.net`/single-label host, i.e. somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key. `isLocalInstanceProvider(provider)` — the narrower question, mirroring server `localProviderRuntime.js#isLocalInstanceEndpoint`: does this provider talk to a daemon on THIS machine (loopback, or no endpoint at all)? Gate anything that explains a provider by inspecting the host PortOS runs on — install state, "start it from Settings → Local LLM" — since `localBackendForProvider` matches by NAME and would otherwise claim a peer's LM Studio. And `credentialSource(provider)` plus `providerCardState(provider, { runtime, status, keySetFor, envVarSet })` + `PROVIDER_CARD_STATE` — is a provider ready to run, benched, blocked on a missing prerequisite (CLI not installed / API key absent / empty credential environment variable), or simply switched off? Reads the SERVER's `missingPrerequisites` (published per provider on `GET /api/providers` from `server/lib/providerPrerequisites.js`, and the same computation `getFallbackProvider` routes on) and adds the local-app runtime shape plus tri-state checks for stored, inherited, and process environment credentials. Unknown lookup values mean "not probed", never "missing". Drives the AI Providers page card colors and grouping — distinct from `ProviderReadiness`/`GET /api/providers/readiness`, which probes the local daemon behind a provider. `resolvesOutsidePortosPath(provider)` — does this provider resolve its binary somewhere the runtime probe never looked (an explicit path in `command`, or its own `PATH` in `envVars`)? Mirror of the same two guards in the server's `providerRuntimeKey`, and what keeps the card's badge from accusing a working provider the router happily routes. And `providerRuntimeKey(provider)` — the key a provider's runtime is published under by `GET /api/providers/runtimes`, so a card can show its CLI install status (bare binary name for a cli/tui provider, provider id for an API provider fronted by a local app); the runtime table itself stays server-side. || `systemCapabilities` | Server-annotated hardware compatibility helpers: preserve model/provider choices when compatibility is unknown, and hide only entries whose `hardwareCompatibility.state` is definitively `unavailable`. || `layeredIntelligenceReasons` | Canonical gloss for the Layered Intelligence loop's run-outcome reason tokens, shared by the on-demand toast and the durable "Last run" line (`formatLiReason`, `liReasonTone`, `LI_NEUTRAL_REASONS`). |diff --git a/client/src/utils/providers.js b/client/src/utils/providers.jsindex d7b02c76b0..0e21f4feab 100644--- a/client/src/utils/providers.js+++ b/client/src/utils/providers.js@@ -87,6 +87,17 @@ export const isCodexProvider = (provider) => {return id === 'codex' || id === 'codex-tui' || commandBasename(provider?.command) === 'codex';};+/**+ * True when a CLI/TUI record uses Codex's ChatGPT subscription. This mirrors+ * server/lib/codexAccount.js: the command, not an editable provider id, owns+ * the account contract.+ * @param {{type?:string, command?:string}|null|undefined} provider+ * @returns {boolean}+ */+export const isCodexSubscriptionProvider = (provider) =>+ (provider?.type === 'cli' || provider?.type === 'tui')+ && commandBasename(provider?.command) === 'codex';+/*** True when a provider is Kimi-Code-flavored — the shipped `kimi-cli`/`kimi-tui`* ids or any provider whose launch command basename is `kimi` (path/exe tolerant).@@ -1382,9 +1393,16 @@ const credentialEnvVars = (provider) => {* provider carrying `provider.apiKey` untouched at spawn time.** @param {{id?:string,type?:string,endpoint?:string,apiKey?:string,hasApiKey?:boolean,gatewayBacked?:string,orcarouterBacked?:boolean,envVars?:Record<string,string>,secretEnvVars?:string[]}|null|undefined} provider- * @returns {{kind:'stored'|'inherited'|'env'|'none',ref:string|null}}+ * @returns {{kind:'stored'|'inherited'|'env'|'subscription'|'none',ref:string|null}}*/export const credentialSource = (provider) => {+ // Codex CLI/TUI providers can use the ChatGPT subscription that Codex owns+ // outside PortOS. It is neither a stored API key nor an environment+ // credential, so the regular credential UI must not tell the user to paste a+ // key. `providerCardState` receives the separate, bounded account verdict.+ if (isCodexSubscriptionProvider(provider)) {+ return { kind: 'subscription', ref: 'codex' };+ }// Local API endpoints need no credential, even if an old record happens to// retain one from before the endpoint was changed.if (isApiProvider(provider) && isPrivateNetworkEndpoint(provider?.endpoint)) {@@ -1460,7 +1478,7 @@ const inheritedCredentialMissing = (provider, keySetFor) => {const credentialMissing = (provider, { keySetFor = null, envVarSet = null } = {}) => {const source = credentialSource(provider);- if (source.kind === 'none' || !source.ref) return null;+ if (source.kind === 'none' || source.kind === 'subscription' || !source.ref) return null;if (source.kind === 'env') {const groups = credentialEnvGroups(provider).map((group) => group.map((name) => {@@ -1515,6 +1533,7 @@ export const PROVIDER_CARD_STATE = Object.freeze({READY: 'ready',BENCHED: 'benched',BLOCKED: 'blocked',+ UNKNOWN: 'unknown',DISABLED: 'disabled',});@@ -1575,6 +1594,10 @@ export const providerCardState = (provider, {status = null,keySetFor = null,envVarSet = null,+ // `undefined` means an older server did not provide the account feature at+ // all; `null` means this page tried to fetch it but could not determine a+ // verdict. They must not collapse into "signed out" or "ready".+ codexAccount = undefined,} = {}) => {// The server publishes its own verdict on `GET /api/providers`// (`missingPrerequisites`, from server/lib/providerPrerequisites.js) and@@ -1623,9 +1646,23 @@ export const providerCardState = (provider, {}}+ const codexSubscription = isCodexSubscriptionProvider(provider);+ const accountStatus = codexAccount && typeof codexAccount === 'object'+ ? codexAccount.status+ : null;+ if (codexSubscription && accountStatus === 'signed-out') {+ addMissing('codexAccount', 'No ChatGPT account is signed in');+ } else if (codexSubscription && accountStatus === 'reauth-required') {+ addMissing('codexAccount', 'ChatGPT sign-in has expired');+ } else if (codexSubscription && accountStatus === 'quota-exhausted') {+ addMissing('codexQuota', 'ChatGPT usage limit reached');+ }+// Switched off wins over every finding — see the precedence note above. The// findings ride along so the card can still say what enabling it would take.if (!provider?.enabled) return { state: PROVIDER_CARD_STATE.DISABLED, missing };+ if (codexSubscription && codexAccount === null) return { state: PROVIDER_CARD_STATE.UNKNOWN, missing };+ if (codexSubscription && accountStatus === 'unknown') return { state: PROVIDER_CARD_STATE.UNKNOWN, missing };if (missing.length > 0) return { state: PROVIDER_CARD_STATE.BLOCKED, missing };if (status?.available === false) return { state: PROVIDER_CARD_STATE.BENCHED, missing };return { state: PROVIDER_CARD_STATE.READY, missing };diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.jsindex 94fe7d0c05..3cf5495b8d 100644--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@ -51,6 +51,7 @@ import {isGrokBuildCli,isKimiProvider,isCodexProvider,+ isCodexSubscriptionProvider,supportsModelRefresh,isAntigravityProvider,effortLevelsForProvider,@@ -1482,6 +1483,17 @@ describe('credentialSource', () => {})).toEqual({ kind: 'none', ref: null });});+ it('keeps a Codex ChatGPT subscription separate from API-key credentials', () => {+ expect(credentialSource({ id: 'codex', type: 'cli', command: 'codex', apiKey: 'legacy-key' }))+ .toEqual({ kind: 'subscription', ref: 'codex' });+ });++ it('keys Codex subscription credentials on the command, not an editable id', () => {+ const renamed = { id: 'codex', type: 'cli', command: 'opencode', envVars: { CUSTOM_API_KEY: '' } };+ expect(isCodexSubscriptionProvider(renamed)).toBe(false);+ expect(credentialSource(renamed)).toEqual({ kind: 'env', ref: 'CUSTOM_API_KEY' });+ });+it('lets a wrapper carrying its own key stand down from inheritance', () => {expect(credentialSource({ id: 'wrapper', type: 'cli', apiKey: 'sk-example', orcarouterBacked: true })).toEqual({ kind: 'stored', ref: 'wrapper' });@@ -1506,6 +1518,20 @@ describe('providerCardState', () => {.toEqual({ state: PROVIDER_CARD_STATE.READY, missing: [] });});+ it('uses bounded Codex account states without calling a subscription an API-key provider', () => {+ const codex = { id: 'codex', type: 'cli', command: 'codex', enabled: true };+ expect(providerCardState(codex, { codexAccount: { status: 'signed-out' } })).toEqual({+ state: PROVIDER_CARD_STATE.BLOCKED,+ missing: [{ code: 'codexAccount', label: 'No ChatGPT account is signed in' }],+ });+ expect(providerCardState(codex, { codexAccount: { status: 'unknown' } }))+ .toEqual({ state: PROVIDER_CARD_STATE.UNKNOWN, missing: [] });+ expect(providerCardState(codex, { codexAccount: null }))+ .toEqual({ state: PROVIDER_CARD_STATE.UNKNOWN, missing: [] });+ expect(providerCardState(codex, { codexAccount: { status: 'ready' } }))+ .toEqual({ state: PROVIDER_CARD_STATE.READY, missing: [] });+ });+// An unprobed runtime (older server, or the card drawn before the probe// lands) must read as "can't tell", never as a missing binary.it('never blocks on an unprobed runtime', () => {diff --git a/client/src/utils/urlNormalize.js b/client/src/utils/urlNormalize.jsindex 37430d2be8..6ddf065ad0 100644--- a/client/src/utils/urlNormalize.js+++ b/client/src/utils/urlNormalize.js@@ -24,6 +24,17 @@ const DOMAIN_PATTERN = /^\S+\.\S+$/;*/export const isHttpUrl = (url) => /^https?:\/\//i.test(url || '');+/**+ * True only for a syntactically valid HTTPS URL. Use this for provider-issued+ * browser handoffs, where a local process response must never become a script+ * URL in the PortOS page.+ *+ * @param {string} url+ * @returns {boolean}+ */+export const isHttpsUrl = (url) =>+ typeof url === 'string' && URL.canParse(url) && new URL(url).protocol === 'https:';+/*** Extract a TikTok video id from a share/watch URL so a reference can render* TikTok's documented iframe Embed Player instead of loading their embed.js.diff --git a/client/src/utils/urlNormalize.test.js b/client/src/utils/urlNormalize.test.jsindex 455b3888ca..4f0eada19b 100644--- a/client/src/utils/urlNormalize.test.js+++ b/client/src/utils/urlNormalize.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { isUrl, normalizeUrl, tiktokEmbedSrc, tiktokVideoId } from './urlNormalize';+import { isHttpsUrl, isUrl, normalizeUrl, tiktokEmbedSrc, tiktokVideoId } from './urlNormalize';describe('tiktokVideoId', () => {it('extracts the id from the share/watch, short, and embed forms', () => {@@ -65,6 +65,15 @@ describe('isUrl', () => {});});+describe('isHttpsUrl', () => {+ it('accepts valid HTTPS browser handoffs and rejects unsafe schemes', () => {+ expect(isHttpsUrl('https://auth.example.com/sign-in')).toBe(true);+ expect(isHttpsUrl('http://auth.example.com/sign-in')).toBe(false);+ expect(isHttpsUrl('javascript:alert(1)')).toBe(false);+ expect(isHttpsUrl('not a URL')).toBe(false);+ });+});+describe('normalizeUrl', () => {it('returns null for empty / whitespace-only input', () => {expect(normalizeUrl('')).toBe(null);diff --git a/server/lib/codexAccount.js b/server/lib/codexAccount.jsindex d4e52b380c..a70a5370ac 100644--- a/server/lib/codexAccount.js+++ b/server/lib/codexAccount.js@@ -272,8 +272,12 @@ export const normalizeCodexLoginStart = (result) => {if (!result || typeof result !== 'object') throw new Error('login start returned a non-object result');const loginId = trimmedString(result.loginId);if (!loginId) throw new Error('login start returned no loginId');- const authUrl = trimmedString(result.authUrl);- const verificationUrl = trimmedString(result.verificationUrl);+ const httpsUrl = (value) => {+ const url = trimmedString(value);+ return url && URL.canParse(url) && new URL(url).protocol === 'https:' ? url : null;+ };+ const authUrl = httpsUrl(result.authUrl);+ const verificationUrl = httpsUrl(result.verificationUrl);if (!authUrl && !verificationUrl) throw new Error('login start returned no sign-in URL');return {loginId,diff --git a/server/lib/codexAccount.test.js b/server/lib/codexAccount.test.jsindex 405db6085d..30045bd91e 100644--- a/server/lib/codexAccount.test.js+++ b/server/lib/codexAccount.test.js@@ -128,6 +128,11 @@ describe('normalizeCodexLoginStart', () => {expect(() => normalizeCodexLoginStart({ authUrl: 'https://auth.example.com/x' })).toThrow(/loginId/);expect(() => normalizeCodexLoginStart({ loginId: 'login-3' })).toThrow(/sign-in URL/);});++ it('refuses a non-HTTPS browser handoff', () => {+ expect(() => normalizeCodexLoginStart({ loginId: 'login-4', authUrl: 'javascript:alert(1)' })).toThrow(/sign-in URL/);+ expect(() => normalizeCodexLoginStart({ loginId: 'login-5', verificationUrl: 'http://auth.example.com/device' })).toThrow(/sign-in URL/);+ });});describe('deriveCodexAccountStatus', () => {