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
surface a third-party bridge re-pointing Codex model routing, and let the user pin runs to PortOS's own account (#6304)
[._.]/ Adam Eivy52ebfc81e14f
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsxindex 92bd664331..3484ddd9f2 100644--- a/client/src/components/providers/ProviderCard.jsx+++ b/client/src/components/providers/ProviderCard.jsx@@ -19,6 +19,7 @@ import {filterHardwareCompatibleProviderModels,isApiProvider,isCodexSubscriptionProvider,+ codexRoutingAdvisory,gatewayForProvider,isPrivateNetworkEndpoint,isFleetProvider,@@ -35,7 +36,7 @@ import { formatContextLength } from '../../utils/formatters';import { isHttpsUrl } from '../../utils/urlNormalize';import ProviderRuntimeStatus from './ProviderRuntimeStatus';import ProviderReadiness from './ProviderReadiness';-import { GatewayKeyHint } from './ProviderNotices';+import { CodexRoutingNotice, GatewayKeyHint } from './ProviderNotices';// One phrasing for "this command isn't on the CoS Agent Runner's allowlist".// The editor states the same thing in its own inline banner, in prose.@@ -118,6 +119,9 @@ export default function ProviderCard({onCodexEnable,}) {const style = CARD_STATE_STYLES[cardState.state];+ // Non-blocking: it never touches `cardState`, only what the card SAYS about+ // where this provider's runs actually go.+ const routingAdvisory = codexRoutingAdvisory(provider);const compatibleModels = filterHardwareCompatibleProviderModels(provider.models, provider);const fleetProvider = isFleetProvider(provider);const fleetHost = fleetProvider && URL.canParse(provider.endpoint)@@ -316,8 +320,14 @@ export default function ProviderCard({{/* Card body — full width, below the header row rather than beside theaction buttons. */}<div className="mt-3 space-y-2">+ <CodexRoutingNotice+ advisory={routingAdvisory}+ className="max-w-3xl"+ onEdit={() => onEdit(provider)}+ />{codexSubscription && (<CodexSubscriptionPanel+ routingOverridden={Boolean(routingAdvisory)}account={codexAccount}models={codexModels}loading={codexAccountLoading}@@ -549,6 +559,7 @@ function CodexSubscriptionPanel({onCopyCode,subscriptionEnabled,onEnable,+ routingOverridden = false,}) {const status = account?.status || 'unknown';const login = account?.login;@@ -577,6 +588,12 @@ function CodexSubscriptionPanel({</div><p className="text-gray-400">{action}</p>{windows.length > 0 && <p className="text-gray-400">{windows.join(' · ')}</p>}+ {routingOverridden && (+ <p className="text-port-warning">+ These are this ChatGPT account’s limits. Your Codex config re-points model routing, so PortOS+ runs on this provider may not be counted here.+ </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>}diff --git a/client/src/components/providers/ProviderCard.test.jsx b/client/src/components/providers/ProviderCard.test.jsxindex 81474b0566..1d8eb327f1 100644--- a/client/src/components/providers/ProviderCard.test.jsx+++ b/client/src/components/providers/ProviderCard.test.jsx@@ -149,3 +149,41 @@ describe('ProviderCard model refresh', () => {});});++/**+ * The routing-override badge (#6304). What this uniquely catches: the card+ * silently presenting ChatGPT account quota for work that account never served,+ * and the inverse leak — the machine-local base URL reaching a card that has no+ * advisory to render.+ */+describe('ProviderCard codex routing override', () => {+ const codex = (overrides = {}) => ({+ id: 'codex',+ name: 'Codex CLI',+ type: 'cli',+ command: 'codex',+ models: ['gpt-5.6-terra'],+ enabled: true,+ ...overrides,+ });+ const advisory = {+ code: 'codexRoutingOverridden',+ label: 'Codex model routing is overridden by your own ~/.codex/config.toml',+ keys: ['openai_base_url'],+ baseUrl: 'http://127.0.0.1:9999/v1',+ };++ it('names the overridden route and caveats the subscription quota', () => {+ renderCard(codex({ prerequisiteAdvisories: [advisory] }));+ expect(screen.getByText(/Model routing is overridden by your Codex config/)).toBeTruthy();+ expect(screen.getByText('http://127.0.0.1:9999/v1')).toBeTruthy();+ expect(screen.getByText(/may not be counted here/)).toBeTruthy();+ });++ it('renders nothing — and no base URL — when the server published no advisory', () => {+ renderCard(codex({ prerequisiteAdvisories: [] }));+ expect(screen.queryByText(/Model routing is overridden/)).toBeNull();+ expect(screen.queryByText(/127\.0\.0\.1/)).toBeNull();+ expect(screen.queryByText(/may not be counted here/)).toBeNull();+ });+});diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsxindex 7eab930333..94625ad11e 100644--- a/client/src/components/providers/ProviderForm.jsx+++ b/client/src/components/providers/ProviderForm.jsx@@ -2,7 +2,7 @@ import { useState } from 'react';import { AlertTriangle } from 'lucide-react';import toast from '../ui/Toast';import * as api from '../../services/api';-import { filterHardwareCompatibleProviderModels, filterGenerationModels, isEmbeddingModel, isProviderHardwareCompatible, isProviderModelHardwareCompatible, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, isProcessProvider, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, gatewayForProvider, isClaudeCommandProvider, generationControlsFor } from '../../utils/providers';+import { filterHardwareCompatibleProviderModels, filterGenerationModels, isEmbeddingModel, isProviderHardwareCompatible, isProviderModelHardwareCompatible, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, isProcessProvider, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, gatewayForProvider, isClaudeCommandProvider, generationControlsFor, isCodexProvider } from '../../utils/providers';import Banner from '../ui/Banner';import {formatDurationMs,@@ -55,6 +55,7 @@ export default function ProviderForm({ provider, onClose, onSave, onEditProviderendpoint: provider?.endpoint || '',apiKey: '',allowCustomEndpoint: provider?.allowCustomEndpoint === true,+ ignoreUserConfig: provider?.ignoreUserConfig === true,models: provider?.models || [],hardwareRequirements: provider?.hardwareRequirements,modelHardwareRequirements: provider?.modelHardwareRequirements,@@ -356,6 +357,9 @@ export default function ProviderForm({ provider, onClose, onSave, onEditProviderdelete data.textTransportEnabled;delete data.textTransportReadRiskAcknowledged;}+ // `--ignore-user-config` is a Codex flag. Never stamp it onto a record+ // running another vendor's binary, where it would be a stored lie.+ if (!isCodexProvider({ ...provider, ...data, id: provider?.id })) delete data.ignoreUserConfig;// Only send apiKey if user entered a new value (avoid overwriting existing key with empty string)if (!data.apiKey && provider) {@@ -595,6 +599,26 @@ export default function ProviderForm({ provider, onClose, onSave, onEditProvider</>)}+ {isCodexProvider({ ...provider, ...formData, id: provider?.id }) && isProcessProvider(formData) && (+ <FormField label="Codex user config">+ <label htmlFor="ignoreUserConfig" className="flex items-start gap-2 cursor-pointer">+ <input+ id="ignoreUserConfig"+ type="checkbox"+ checked={formData.ignoreUserConfig}+ onChange={(e) => setFormData(prev => ({ ...prev, ignoreUserConfig: e.target.checked }))}+ className="mt-1"+ />+ <span className="text-sm text-gray-300">+ Ignore <code>~/.codex/config.toml</code> when PortOS runs this provider+ (<code>--ignore-user-config</code>). Leave off to keep today’s behavior. Turn it on when a+ third-party bridge has re-pointed Codex model routing and you want PortOS runs pinned to+ the account this card reports on.+ </span>+ </label>+ </FormField>+ )}+<label className="flex items-center gap-2"><inputtype="checkbox"diff --git a/client/src/components/providers/ProviderNotices.jsx b/client/src/components/providers/ProviderNotices.jsxindex b5ad0994fb..698e6669d6 100644--- a/client/src/components/providers/ProviderNotices.jsx+++ b/client/src/components/providers/ProviderNotices.jsx@@ -59,3 +59,46 @@ export function GatewayKeyHint({ gateway, sibling, className = '', onEdit }) {</div>);}++/**+ * "Your own `~/.codex/config.toml` is re-pointing this provider's model+ * routing."+ *+ * A third-party bridge installs itself by writing top-level routing keys into+ * that file, and the Codex CLI honors it on every invocation — so PortOS's runs+ * go wherever the file says while this page reports the signed-in ChatGPT+ * account's readiness and quota. Choosing such a bridge is legitimate; being+ * unable to SEE it is the bug, which is why this is an informational notice and+ * not a NEEDS SETUP state.+ *+ * `advisory.baseUrl` is machine-local (it can embed a host name or a port), so+ * it renders here and is never logged, persisted or federated.+ */+export function CodexRoutingNotice({ advisory, className = '', onEdit }) {+ if (!advisory) return null;+ return (+ <div className={`text-xs rounded-md border border-port-accent/40 bg-port-accent/10 px-2.5 py-2 leading-relaxed ${className}`}>+ <p className="text-port-accent font-medium">Model routing is overridden by your Codex config</p>+ <p className="mt-1 text-gray-300 break-words">+ <code className="font-mono">~/.codex/config.toml</code> sets{' '}+ {advisory.keys.map((key, index) => (+ <span key={key}>+ {index > 0 ? ', ' : ''}<code className="font-mono">{key}</code>+ </span>+ ))}+ {advisory.baseUrl ? <> — Codex traffic goes to <code className="font-mono break-all">{advisory.baseUrl}</code></> : null}.+ PortOS runs on this provider follow that route, so the account and usage figures below+ may not describe the work PortOS actually sent.+ </p>+ {onEdit && (+ <button+ type="button"+ onClick={onEdit}+ className="mt-2 text-port-accent hover:text-port-accent/80 underline underline-offset-2"+ >+ Pin PortOS runs to this provider’s own account+ </button>+ )}+ </div>+ );+}diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex ce7293514e..0d994be1c7 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -42,7 +42,7 @@ grep -i "what you want to do" client/src/utils/README.md| `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`, `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. `PUBLIC_REVIEW_NO_TOOL_POSTURE` / `PUBLIC_REVIEW_ACTIONS_POSTURE`, `supportsPublicReviewPosture`, `enforcesPublicReviewPosture`, and `publicReviewSelectionPolicy` are the pr-reviewer counterpart (mirror of server `agentExecutionProfiles.js`): a pipeline stage names a POSTURE, the server publishes each provider's `publicReviewPostures` (runnable) and `publicReviewEnforcedPostures` (backed by a vendor sandbox recipe) on `GET /api/providers`, and the picker offers exactly the providers this install can run the stage on — no vendor is named on either side. 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. `PUBLIC_REVIEW_NO_TOOL_POSTURE` / `PUBLIC_REVIEW_ACTIONS_POSTURE`, `supportsPublicReviewPosture`, `enforcesPublicReviewPosture`, and `publicReviewSelectionPolicy` are the pr-reviewer counterpart (mirror of server `agentExecutionProfiles.js`): a pipeline stage names a POSTURE, the server publishes each provider's `publicReviewPostures` (runnable) and `publicReviewEnforcedPostures` (backed by a vendor sandbox recipe) on `GET /api/providers`, and the picker offers exactly the providers this install can run the stage on — no vendor is named on either side. 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. `codexRoutingAdvisory(provider)` reads the server-published `prerequisiteAdvisories` entry saying the install’s own `~/.codex/config.toml` re-points Codex model routing — a NON-blocking notice (never in `missingPrerequisites`, so it never buckets a card as NEEDS SETUP) whose `baseUrl` is machine-local and renders in the UI only. Server-only, with no client fallback: the browser cannot read that file. 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 1e9937f2e9..4eac030c5d 100644--- a/client/src/utils/providers.js+++ b/client/src/utils/providers.js@@ -111,6 +111,26 @@ export const isCodexSubscriptionProvider = (provider) =>(provider?.type === 'cli' || provider?.type === 'tui')&& commandBasename(provider?.command) === 'codex';+/**+ * The 'your own ~/.codex/config.toml is re-pointing this provider' advisory the+ * server publishes on `GET /api/providers`, or `null`.+ *+ * Deliberately NOT part of `missingPrerequisites`: pointing Codex at a local+ * bridge is a legitimate choice, so it must never bucket a card as NEEDS SETUP.+ * What it fixes is PortOS reporting a ChatGPT account's readiness and quota for+ * work that account never served. `advisory.baseUrl` is machine-local — render+ * it here and nowhere else.+ *+ * SERVER-ONLY, with no client fallback: the browser cannot read the user's+ * config file, so an older server publishing nothing correctly yields `null`.+ * @returns {{code:string,label:string,keys:string[],baseUrl:string|null}|null}+ */+export const codexRoutingAdvisory = (provider) => (+ Array.isArray(provider?.prerequisiteAdvisories)+ ? provider.prerequisiteAdvisories.find((entry) => entry?.code === 'codexRoutingOverridden') || null+ : null+);+/*** 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).diff --git a/data.reference/providers.json b/data.reference/providers.jsonindex cf98bac1d1..f6d8b01557 100644--- a/data.reference/providers.json+++ b/data.reference/providers.json@@ -71,6 +71,7 @@"timeout": 300000,"enabled": true,"textTransport": "codex-app-server",+ "ignoreUserConfig": false,"envVars": {}},"antigravity-cli": {@@ -102,6 +103,7 @@"timeout": 600000,"enabled": false,"textTransport": "codex-app-server",+ "ignoreUserConfig": false,"envVars": {},"tuiPromptDelayMs": 2500},diff --git a/scripts/migrations/345-codex-ignore-user-config.js b/scripts/migrations/345-codex-ignore-user-config.jsnew file mode 100644index 0000000000..aa15fdf06e--- /dev/null+++ b/scripts/migrations/345-codex-ignore-user-config.js@@ -0,0 +1,63 @@+/**+ * Give existing Codex provider records the explicit `ignoreUserConfig: false`+ * the shipped seed now carries (#6304).+ *+ * PortOS can now SAY when the install's own `~/.codex/config.toml` re-points+ * Codex model routing at a third-party bridge, and offer a per-provider pin+ * (`--ignore-user-config` at spawn) that puts the run back on the account the+ * provider card reports. `false` is the pin OFF, which is exactly today's+ * behavior — this migration changes no run, it only makes the field present so+ * the Providers toggle round-trips against a real stored value on an install+ * that predates the field, instead of on an absent one.+ *+ * Gated on the PRESENCE of a Codex record, never on the absence of the new+ * field (root AGENTS.md): the field is what this writes, so keying on its+ * absence would be keying on its own output. A record that already carries the+ * field — the user having toggled it, or a newer seed having landed — is left+ * exactly as it is.+ *+ * Command-keyed, matching `isCodexProvider`, so a renamed clone of the shipped+ * record is covered and a record repointed at somebody else's binary is not.+ * The rule is inlined rather than imported because a migration is a frozen+ * snapshot and must not drift when that helper changes.+ */++import { readProvidersDoc, writeJsonAtomic } from './_lib.js';++const CODEX_COMMAND = 'codex';+const PROVIDERS_REL_PATH = 'data/providers.json';++const SKIP_REASONS = {+ 'no-file': 'not present (a fresh install seeds these from data.reference)',+ unreadable: 'is not valid JSON',+ 'bad-shape': 'has no providers map',+};++/** `commandBasename`, inlined: case-insensitive basename with `.exe` stripped. */+const basename = (command) => (typeof command === 'string' ? command.trim() : '')+ .split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '');++const isCodexRecord = (provider) => (provider?.type === 'cli' || provider?.type === 'tui')+ && basename(provider.command) === CODEX_COMMAND;++export default {+ async up({ rootDir }) {+ const doc = await readProvidersDoc({ rootDir });+ if (!doc.ok) {+ const why = SKIP_REASONS[doc.reason] ?? 'could not be read';+ console.log(`📄 ${PROVIDERS_REL_PATH} ${why} — skipping the Codex ignore-user-config stamp`);+ return { ok: false, reason: doc.reason, updated: 0 };+ }++ const codexRecords = Object.values(doc.providers).filter(isCodexRecord);+ if (codexRecords.length === 0) return { ok: true, reason: 'no-codex-records', updated: 0 };++ const targets = codexRecords.filter((provider) => typeof provider.ignoreUserConfig !== 'boolean');+ if (targets.length === 0) return { ok: true, reason: 'already-current', updated: 0 };++ for (const provider of targets) provider.ignoreUserConfig = false;+ await writeJsonAtomic(doc.path, doc.config);+ console.log(`📝 ${PROVIDERS_REL_PATH}: ${targets.length} Codex provider record${targets.length === 1 ? '' : 's'} stamped with ignoreUserConfig=false`);+ return { ok: true, reason: 'updated', updated: targets.length };+ },+};diff --git a/scripts/migrations/345-codex-ignore-user-config.test.js b/scripts/migrations/345-codex-ignore-user-config.test.jsnew file mode 100644index 0000000000..452e916213--- /dev/null+++ b/scripts/migrations/345-codex-ignore-user-config.test.js@@ -0,0 +1,64 @@+/**+ * Migration 345. What this uniquely catches: a gate keyed on the migration's+ * own OUTPUT (which would let a shipped seed stand where the user's record was)+ * and a stamp that overwrites a pin the user already made.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './345-codex-ignore-user-config.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 345 — codex ignoreUserConfig', () => {+ let rootDir;+ let providersPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-345-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ providersPath = join(rootDir, 'data/providers.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('stamps the field off on codex records, including a path-configured clone', async () => {+ writeJson(providersPath, {+ providers: {+ codex: { id: 'codex', type: 'cli', command: 'codex' },+ 'codex-tui': { id: 'codex-tui', type: 'tui', command: '/opt/tools/codex' },+ 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' },+ },+ });++ expect(await migration.up({ rootDir })).toMatchObject({ ok: true, updated: 2 });+ const out = readJson(providersPath).providers;+ expect(out.codex.ignoreUserConfig).toBe(false);+ expect(out['codex-tui'].ignoreUserConfig).toBe(false);+ expect(out['claude-code']).not.toHaveProperty('ignoreUserConfig');+ });++ it('never overwrites a pin the user already made, and is a no-op on re-run', async () => {+ writeJson(providersPath, {+ providers: { codex: { id: 'codex', type: 'cli', command: 'codex', ignoreUserConfig: true } },+ });++ expect(await migration.up({ rootDir })).toMatchObject({ reason: 'already-current', updated: 0 });+ expect(readJson(providersPath).providers.codex.ignoreUserConfig).toBe(true);+ });++ it('skips an install with no codex record rather than inventing one', async () => {+ writeJson(providersPath, {+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },+ });++ expect(await migration.up({ rootDir })).toMatchObject({ reason: 'no-codex-records', updated: 0 });+ });++ it('skips a missing providers file', async () => {+ expect(await migration.up({ rootDir })).toMatchObject({ ok: false, updated: 0 });+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 59615738f9..14ce40d7e9 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -216,6 +216,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `runners.js` | Image-runner family constants (`RUNNER_FAMILIES`, `loraCompatKey`), video LoRA families, MiniMax H3 runtime predicates, and the shared `AUDIO_TO_VIDEO_RUNTIMES` / `isAudioToVideoRuntime` capability gate (LTX plus H3 Ref2VA). Mirrored to `client/src/lib/runnerFamilies.js`. || `codexAccount.js` | The ChatGPT-subscription half of the Codex providers (#5589), pure. The fixed `codex app-server` invocation, the `account/*` method + notification names, `CODEX_ACCOUNT_STATUS` (`runtime-missing` / `unknown` / `signed-out` / `login-pending` / `ready` / `quota-exhausted` / `reauth-required`) and `CODEX_ERROR_CODES`, `isCodexSubscriptionProvider` (keyed on the `codex` COMMAND, so a renamed clone still resolves), the `normalizeCodexAccount` / `normalizeCodexRateLimits` / `normalizeCodexLoginStart` payload normalizers, `redactCodexPayload` (every log/error/response path runs through it, so "PortOS never writes down a Codex token" is one function rather than a rule per call site), and `deriveCodexAccountStatus`. Sentinels are load-bearing: `runtimeInstalled: null` = NOT PROBED, `accountFetched: false` ≠ signed out, `rateLimits: null` (failed fetch) ≠ a fetched window with nothing to report. The process half is `services/codexAppServer.js`. || `codexTurn.js` | The INFERENCE half of the Codex ChatGPT-subscription provider (#5590), pure. The `thread/start` / `turn/start` / `turn/interrupt` / `model/list` method names and the turn notifications, `CODEX_TEXT_TRANSPORT` plus `providerDeclaresCodexTextTransport` (advertises, reusing `codexAccount.isCodexSubscriptionProvider` so the two halves cannot drift) vs `isCodexTextTransportEnabled` (requires both the explicit opt-in and the Providers-UI read-risk acknowledgement), the `CODEX_TEXT_THREAD_CONFIG` safety envelope a generic text call runs under (empty throwaway cwd, no writes, no network, fail-closed approvals, no MCP servers, no web search — Codex can still read local files by absolute path; see the module docstring), `normalizeCodexModels` / `normalizeCodexTokenUsage` / `resolveCodexEffort`, the `createTurnAccumulator` → `applyCodexTurnEvent` → `finalizeCodexTurn` projection (a non-`completed` turn yields an error, NEVER the partial text), and `classifyCodexTurnError` / `classifyCodexTransportError`, which fold both failure shapes onto the shared `ERROR_CATEGORIES` the cooldown policy reads. `models: null` = never fetched, `[]` = fetched-and-empty. The process half is `services/codexAppServer.js`. |+| `codexUserConfig.js` | READ-ONLY probe of the user's own `~/.codex/config.toml` (honoring `CODEX_HOME`), so PortOS can SAY when a third-party bridge has re-pointed Codex model routing away from the account its cards report on. `parseCodexRoutingOverride` (pure) reports which of the top-level `openai_base_url` / `model_provider` / `model_catalog_json` keys are assigned and the base URL they name — top-level ONLY, since the same key inside a `[table]` is per-provider configuration and must not trip the badge. `readCodexRoutingOverride` adds a short TTL cache and the load-bearing sentinel: `null` = could not read (never paint that as "not overridden"), an ABSENT file = a definite `overridden: false`. PortOS never writes this file, and `baseUrl` is machine-local — render it, never log or federate it. || `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. || `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. || `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens`/`estimateTokensFromChars` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. |diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.jsonindex 3dac9a794c..ed1daf157d 100644--- a/server/lib/aiToolkit/defaults/providers.sample.json+++ b/server/lib/aiToolkit/defaults/providers.sample.json@@ -472,6 +472,7 @@"timeout": 300000,"enabled": true,"textTransport": "codex-app-server",+ "ignoreUserConfig": false,"envVars": {},"secretEnvVars": []},@@ -490,6 +491,7 @@"timeout": 600000,"enabled": false,"textTransport": "codex-app-server",+ "ignoreUserConfig": false,"envVars": {},"secretEnvVars": [],"tuiPromptDelayMs": 2500diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 1eab79a500..e36708a280 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -695,6 +695,10 @@ export function createProviderService(config = {}) {// non-allowlisted) endpoint — see endpointGuard.js. Only// persisted when true so existing keyless/local providers stay clean....(providerData.allowCustomEndpoint === true ? { allowCustomEndpoint: true } : {}),+ // Codex 'ignore my ~/.codex/config.toml' pin. Only persisted when true so+ // every existing record stays byte-identical and an older install+ // reading this file sees nothing new.+ ...(providerData.ignoreUserConfig === true ? { ignoreUserConfig: true } : {}),envVars: providerData.envVars || {},secretEnvVars: providerData.secretEnvVars || [],headlessArgs: providerData.headlessArgs || [],diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex 3e8b31d8d5..f42d0eaeb6 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -178,6 +178,13 @@ export const providerSchema = z.object({// exfiltration to a hostile or mistyped host — see// endpointGuard.js. Metadata endpoints stay blocked even when true.allowCustomEndpoint: z.boolean().optional(),+ // Pin a Codex CLI/TUI provider to PortOS's own account by appending+ // `--ignore-user-config` at spawn, so a bridge that re-pointed model routing+ // in the user's `~/.codex/config.toml` no longer decides where PortOS's runs+ // go. Default OFF: today's behavior (Codex reads the user's config) is the+ // one an existing install already relies on, and an override that silently+ // turned itself on would be its own surprise.+ ignoreUserConfig: z.boolean().optional(),envVars: z.record(z.string()).optional(),secretEnvVars: z.array(z.string()).optional(),headlessArgs: z.array(z.string()).optional(),diff --git a/server/lib/codex.js b/server/lib/codex.jsindex 24057606d2..c07053ea60 100644--- a/server/lib/codex.js+++ b/server/lib/codex.js@@ -48,11 +48,17 @@ function codexHasApprovalPolicy(args) {// independent of the approval posture (the modal is orthogonal to sandboxing),// so it rides even when a provider pins its own policy, while the bypass flag is// skipped when the argv already declares an approval/sandbox posture.-export function ensureCodexTuiArgs(args) {+export function ensureCodexTuiArgs(args, provider = null) {const prefix = [];if (!codexHasApprovalPolicy(args)) {prefix.push('--dangerously-bypass-approvals-and-sandbox');}+ // Same pin the CLI arm applies: an interactive Codex session reads the user's+ // `~/.codex/config.toml` too, so a provider the user pinned to PortOS's own+ // account must not silently route through a bridge here either.+ if (provider?.ignoreUserConfig === true && !args.includes('--ignore-user-config')) {+ prefix.push('--ignore-user-config');+ }prefix.push(...buildCodexStartupArgs(args));return prefix.length ? [...prefix, ...args] : args;}diff --git a/server/lib/codexUserConfig.js b/server/lib/codexUserConfig.jsnew file mode 100644index 0000000000..4bc6f08f3a--- /dev/null+++ b/server/lib/codexUserConfig.js@@ -0,0 +1,137 @@+/**+ * Read-only view of the user's own `~/.codex/config.toml` model routing.+ *+ * WHY THIS EXISTS. Third-party bridges re-point the Codex CLI by writing+ * top-level routing keys — a base URL, a named model provider, a model catalog+ * — into that file. Every `codex` invocation on the machine then runs through+ * whatever the file names, PortOS's own spawns included, while the AI Providers+ * card keeps reporting the signed-in ChatGPT account's readiness and the quota+ * meters keep reporting that account's limits. Nothing is wrong with choosing+ * such a bridge; the failure is that PortOS reports one thing and does another.+ * This module is what lets it say so.+ *+ * READ ONLY, ALWAYS. Never write, repair, or migrate this file — it is the+ * user's, several tools edit it, and a rewrite by PortOS can silently unpick+ * somebody else's install. Detection is a read and a report, never a fix and+ * never a fail-closed prerequisite.+ *+ * MACHINE-LOCAL. `baseUrl` can embed a host name or a port, so it is the+ * user's private data (root AGENTS.md, Sensitive Data & Privacy): render it in+ * the local UI, never log it, never persist it, and never let it cross+ * federation.+ *+ * A few anchored line matches, deliberately not a TOML parser: the question is+ * only whether one of three well-known keys is assigned at the TOP level, and a+ * dependency to answer it would be a poor trade.+ */++import { readFileSync } from 'fs';+import { homedir } from 'os';+import { join } from 'path';++/** Codex's config directory, honoring the CLI's own `CODEX_HOME` override. */+export const codexHomeDir = () => process.env.CODEX_HOME || join(homedir(), '.codex');++/**+ * The top-level keys that re-point where Codex sends model traffic. A key of+ * the same name inside a `[table]` is a DIFFERENT setting (per-provider+ * configuration Codex only uses when that provider is selected) and must not+ * trip the badge.+ */+export const CODEX_ROUTING_KEYS = Object.freeze(['openai_base_url', 'model_provider', 'model_catalog_json']);++const KEY_ASSIGNMENT = /^\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_.-]+))\s*=\s*(.*)$/;+const TABLE_HEADER = /^\s*\[/;++/** Strip a TOML scalar's surrounding quotes; a non-string value returns null. */+const stringValue = (raw) => {+ const trimmed = String(raw ?? '').trim();+ const quoted = /^"([^"]*)"|^'([^']*)'/.exec(trimmed);+ return quoted ? (quoted[1] ?? quoted[2]) : null;+};++/**+ * Which routing keys `tomlText` assigns at the top level, and the base URL it+ * points at. Pure — exported for tests.+ *+ * @returns {{overridden: boolean, keys: string[], baseUrl: string|null}}+ */+export function parseCodexRoutingOverride(tomlText) {+ const keys = [];+ let baseUrl = null;+ let inTable = false;+ let openHeredoc = null; // the `"""` / `'''` fence a multi-line string is inside+ for (const line of String(tomlText || '').split('\n')) {+ if (openHeredoc) {+ if (line.includes(openHeredoc)) openHeredoc = null;+ continue;+ }+ const stripped = line.trim();+ if (stripped === '' || stripped.startsWith('#')) continue;+ if (TABLE_HEADER.test(line)) {+ // Everything after the first table header belongs to that table, so no+ // later assignment is top-level however the file is ordered.+ inTable = true;+ continue;+ }+ const match = KEY_ASSIGNMENT.exec(line);+ if (!match) continue;+ const value = match[4];+ const fence = /^("""|''')/.exec(value.trim());+ // A multi-line string opened and not closed on this line swallows the lines+ // that follow — otherwise a base URL quoted inside a prompt would read as+ // an assignment.+ if (fence && value.trim().indexOf(fence[1], fence[1].length) === -1) openHeredoc = fence[1];+ if (inTable) continue;+ const key = match[1] ?? match[2] ?? match[3];+ if (!CODEX_ROUTING_KEYS.includes(key)) continue;+ if (!keys.includes(key)) keys.push(key);+ if (key === 'openai_base_url' && baseUrl === null) baseUrl = stringValue(value);+ }+ return { overridden: keys.length > 0, keys, baseUrl };+}++// Cache-only reads: `GET /api/providers` is polled, and re-reading the file per+// request would be a syscall per card. Short enough that a user who edits the+// file sees the badge follow within one refresh.+const SNAPSHOT_TTL_MS = 10_000;+let cached = null;+let cachedAt = 0;++/**+ * The install's current Codex routing snapshot, or `null` for NOT DETERMINED.+ *+ * `null` is a real sentinel and must never be painted as "not overridden": it+ * means the file exists but could not be read (permissions, a mid-write+ * truncation). A file that is simply ABSENT is a definite answer — Codex is+ * using its own defaults — and comes back as `overridden: false`.+ *+ * @param {object} [options]+ * @param {string} [options.codexHome] — override the config directory (tests)+ * @param {boolean} [options.force] — bypass the TTL cache+ * @returns {{overridden: boolean, keys: string[], baseUrl: string|null}|null}+ */+export function readCodexRoutingOverride({ codexHome = null, force = false } = {}) {+ const home = codexHome || codexHomeDir();+ const now = Date.now();+ if (!codexHome && !force && cachedAt > 0 && now - cachedAt < SNAPSHOT_TTL_MS) return cached;+ let snapshot;+ try {+ snapshot = parseCodexRoutingOverride(readFileSync(join(home, 'config.toml'), 'utf8'));+ } catch (err) {+ // ENOENT is an answer ("no user config, so no override"); anything else is+ // "could not tell", which the sentinel above keeps distinct.+ snapshot = err?.code === 'ENOENT' ? { overridden: false, keys: [], baseUrl: null } : null;+ }+ if (!codexHome) {+ cached = snapshot;+ cachedAt = now;+ }+ return snapshot;+}++/** Test-only: drop the TTL cache so a suite isn't order-dependent. */+export function __resetCodexRoutingCache() {+ cached = null;+ cachedAt = 0;+}diff --git a/server/lib/codexUserConfig.test.js b/server/lib/codexUserConfig.test.jsnew file mode 100644index 0000000000..0751e40d8d--- /dev/null+++ b/server/lib/codexUserConfig.test.js@@ -0,0 +1,114 @@+/**+ * The routing-override probe. What it uniquely catches: a badge that fires on a+ * key the user did NOT set at the top level (a comment, a `[table]` entry, a+ * value quoted inside a multi-line string), and the sentinel collapse where an+ * unreadable config would be reported as "not overridden".+ */+import { describe, it, expect, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import {+ parseCodexRoutingOverride,+ readCodexRoutingOverride,+ codexHomeDir,+ __resetCodexRoutingCache,+} from './codexUserConfig.js';++const withConfig = (contents) => {+ const home = mkdtempSync(join(tmpdir(), 'codex-home-'));+ if (contents !== null) writeFileSync(join(home, 'config.toml'), contents);+ return home;+};++const temps = [];+const tempHome = (contents) => {+ const home = withConfig(contents);+ temps.push(home);+ return home;+};++afterEach(() => {+ while (temps.length) rmSync(temps.pop(), { recursive: true, force: true });+ __resetCodexRoutingCache();+ delete process.env.CODEX_HOME;+});++describe('parseCodexRoutingOverride', () => {+ it('reports each top-level routing key and the base URL it names', () => {+ expect(parseCodexRoutingOverride([+ 'openai_base_url = "http://127.0.0.1:9999/v1"',+ 'model_provider = "example-bridge"',+ 'model_catalog_json = "/opt/example/models.json"',+ 'model = "gpt-5.6-terra"',+ ].join('\n'))).toEqual({+ overridden: true,+ keys: ['openai_base_url', 'model_provider', 'model_catalog_json'],+ baseUrl: 'http://127.0.0.1:9999/v1',+ });+ });++ it('ignores a commented assignment', () => {+ expect(parseCodexRoutingOverride('# openai_base_url = "http://example.invalid/v1"'))+ .toEqual({ overridden: false, keys: [], baseUrl: null });+ });++ it('ignores the same key inside a table — that is a different setting', () => {+ expect(parseCodexRoutingOverride([+ '[model_providers.example]',+ 'openai_base_url = "http://example.invalid/v1"',+ 'model_provider = "example"',+ ].join('\n'))).toEqual({ overridden: false, keys: [], baseUrl: null });+ });++ it('ignores an assignment quoted inside a multi-line string', () => {+ expect(parseCodexRoutingOverride([+ 'notes = """',+ 'openai_base_url = "http://example.invalid/v1"',+ '"""',+ ].join('\n'))).toEqual({ overridden: false, keys: [], baseUrl: null });+ });++ it('reports a quoted key, and a non-string base URL as no URL', () => {+ expect(parseCodexRoutingOverride('"openai_base_url" = 42'))+ .toEqual({ overridden: true, keys: ['openai_base_url'], baseUrl: null });+ });++ it('is empty for an empty file', () => {+ expect(parseCodexRoutingOverride('')).toEqual({ overridden: false, keys: [], baseUrl: null });+ });+});++describe('readCodexRoutingOverride', () => {+ it('reads config.toml from an explicit home', () => {+ const home = tempHome('openai_base_url = "http://127.0.0.1:9999/v1"\n');+ expect(readCodexRoutingOverride({ codexHome: home })).toEqual({+ overridden: true,+ keys: ['openai_base_url'],+ baseUrl: 'http://127.0.0.1:9999/v1',+ });+ });++ it('treats an ABSENT config as a definite "not overridden"', () => {+ expect(readCodexRoutingOverride({ codexHome: tempHome(null) }))+ .toEqual({ overridden: false, keys: [], baseUrl: null });+ });++ it('returns the NOT-DETERMINED sentinel when the file cannot be read', () => {+ const home = tempHome(null);+ // A directory where the file should be: readable path, unreadable content.+ mkdirSync(join(home, 'config.toml'));+ expect(readCodexRoutingOverride({ codexHome: home })).toBeNull();+ });++ it('honors CODEX_HOME the way the Codex CLI does', () => {+ const home = tempHome('model_provider = "example-bridge"\n');+ process.env.CODEX_HOME = home;+ expect(codexHomeDir()).toBe(home);+ expect(readCodexRoutingOverride({ force: true })).toEqual({+ overridden: true,+ keys: ['model_provider'],+ baseUrl: null,+ });+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 90c6e9444d..b69ab42b43 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -137,6 +137,7 @@ export * from './cliStderrNoise.js';export * from './codex.js';export * from './codexAccount.js';export * from './codexTurn.js';+export * from './codexUserConfig.js';export * from './codexAssistantExtract.js';export * from './codexCliOutput.js';export * from './contextBudget.js';diff --git a/server/lib/providerPrerequisites.js b/server/lib/providerPrerequisites.jsindex 6969843e51..f0af2f95b2 100644--- a/server/lib/providerPrerequisites.js+++ b/server/lib/providerPrerequisites.js@@ -38,7 +38,7 @@import { PROVIDER_TYPES } from './aiToolkit/constants.js';import { CODEX_ACCOUNT_STATUS, isCodexSubscriptionProvider } from './codexAccount.js';import { isLocalInstanceHost } from './localProviderRuntime.js';-import { commandBasename } from './providerModels.js';+import { commandBasename, isCodexProvider } from './providerModels.js';import { gatewayForProvider } from './providerGateways.js';/**@@ -189,6 +189,33 @@ const codexAccountFinding = (provider, readiness) => {}};+/**+ * The 'your own Codex config is re-pointing this provider' notice, or `null`.+ *+ * An ADVISORY, not a prerequisite: it never lands in `missing`, never reaches+ * {@link ROUTING_BLOCKING_CODES}, and never makes a card read NEEDS SETUP.+ * Pointing Codex at a local bridge is a legitimate choice — the only failure is+ * PortOS reporting a ChatGPT account's readiness and quota for work that+ * account never served. So: report it, and offer the opt-out (the provider's+ * `ignoreUserConfig` flag, which appends `--ignore-user-config` at spawn).+ *+ * Silent once the provider already ignores the user config, since then the file+ * describes nothing PortOS runs. Silent on a `null` snapshot too — that is+ * NOT DETERMINED, and accusing an install whose config could not be read would+ * be exactly the false report this exists to prevent.+ */+const codexRoutingAdvisory = (provider, routing) => {+ if (!routing?.overridden || !isCodexProvider(provider)) return null;+ if (provider?.ignoreUserConfig === true) return null;+ return {+ code: 'codexRoutingOverridden',+ label: 'Codex model routing is overridden by your own ~/.codex/config.toml',+ keys: [...routing.keys],+ // Machine-local: for the local UI only. Never log it, never federate it.+ baseUrl: routing.baseUrl || null,+ };+};+/*** Which prerequisites `provider` is missing, and whether it is runnable at all.*@@ -203,9 +230,12 @@ const codexAccountFinding = (provider, readiness) => {* id, does the sibling API provider of that id hold the key an OpenCode* wrapper inherits at spawn time? `false` covers both "no key" and "sibling* deleted"; `null`/absent is "cannot tell".- * @returns {{met: boolean, missing: {code: string, label: string}[]}}+ * @param {object|null} [options.codexRouting] — the user's `~/.codex/config.toml`+ * routing snapshot from `lib/codexUserConfig.js`, or `null` for NOT+ * DETERMINED. Produces an ADVISORY only (see {@link codexRoutingAdvisory}).+ * @returns {{met: boolean, missing: {code: string, label: string}[], advisories: object[]}}*/-export const providerPrerequisites = (provider, { runtime = null, gatewayKeySet = null, codexAccount = null } = {}) => {+export const providerPrerequisites = (provider, { runtime = null, gatewayKeySet = null, codexAccount = null, codexRouting = null } = {}) => {const missing = [];if (runtime && runtime.installed === false) {@@ -229,7 +259,15 @@ export const providerPrerequisites = (provider, { runtime = null, gatewayKeySetconst codexFinding = codexAccountFinding(provider, codexAccount);if (codexFinding) missing.push(codexFinding);- return { met: missing.length === 0, missing };+ // Advisories are a SEPARATE list on purpose: everything in `missing` blocks+ // something (a card's bucket, a strict readiness verdict), and this must+ // block nothing.+ const routingAdvisory = codexRoutingAdvisory(provider, codexRouting);+ return {+ met: missing.length === 0,+ missing,+ advisories: routingAdvisory ? [routingAdvisory] : [],+ };};/**diff --git a/server/lib/providerPrerequisites.test.js b/server/lib/providerPrerequisites.test.jsindex deb7ce69d9..79747a9478 100644--- a/server/lib/providerPrerequisites.test.js+++ b/server/lib/providerPrerequisites.test.js@@ -193,3 +193,42 @@ describe('blocksRouting', () => {expect([...ROUTING_BLOCKING_CODES]).toEqual(['runtime']);});});++/**+ * The routing advisory (#6304). What this uniquely catches: the advisory+ * leaking into `missing`, where it would bucket a perfectly runnable Codex card+ * as NEEDS SETUP and (via the strict readiness map) block authoritative task+ * choices — the exact opposite of "report, do not block".+ */+describe('codex routing advisory', () => {+ const codex = { id: 'codex', type: 'cli', command: 'codex' };+ const overridden = { overridden: true, keys: ['openai_base_url'], baseUrl: 'http://127.0.0.1:9999/v1' };++ it('reports the override without adding a missing prerequisite', () => {+ const result = providerPrerequisites(codex, { codexRouting: overridden });+ expect(result.met).toBe(true);+ expect(result.missing).toEqual([]);+ expect(result.advisories).toEqual([{+ code: 'codexRoutingOverridden',+ label: expect.stringContaining('config.toml'),+ keys: ['openai_base_url'],+ baseUrl: 'http://127.0.0.1:9999/v1',+ }]);+ });++ it('stays silent for a not-determined snapshot, a clean config, and a non-codex provider', () => {+ expect(providerPrerequisites(codex, { codexRouting: null }).advisories).toEqual([]);+ expect(providerPrerequisites(codex, {+ codexRouting: { overridden: false, keys: [], baseUrl: null },+ }).advisories).toEqual([]);+ expect(providerPrerequisites(+ { id: 'claude-code', type: 'cli', command: 'claude' },+ { codexRouting: overridden },+ ).advisories).toEqual([]);+ });++ it('stays silent once the provider is pinned past the user config', () => {+ expect(providerPrerequisites({ ...codex, ignoreUserConfig: true }, { codexRouting: overridden }).advisories)+ .toEqual([]);+ });+});diff --git a/server/lib/providerVendors.codexIgnoreUserConfig.test.js b/server/lib/providerVendors.codexIgnoreUserConfig.test.jsnew file mode 100644index 0000000000..ea6d77d095--- /dev/null+++ b/server/lib/providerVendors.codexIgnoreUserConfig.test.js@@ -0,0 +1,50 @@+/**+ * The `ignoreUserConfig` pin at the Codex spawn boundary (#6304).+ *+ * The regression this uniquely catches: a toggle the AI Providers page offers+ * that never reaches argv (so PortOS keeps routing through the user's config+ * while reporting its own account), and the inverse — the flag appearing on a+ * provider that never asked for it, which would silently change every existing+ * install's Codex behavior. The public-review recipes are asserted unchanged+ * because they already pass the flag unconditionally and must keep doing so.+ */+import { describe, expect, it } from 'vitest';+import { PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from './agentExecutionProfiles.js';+import { applyCommandDefaults, buildVendorCliArgs, buildVendorSpawnConfig } from './providerVendors.js';++const codexCli = { id: 'codex', type: 'cli', command: 'codex' };+const codexTui = { id: 'codex-tui', type: 'tui', command: 'codex' };+const pinned = (provider) => ({ ...provider, ignoreUserConfig: true });++describe('codex --ignore-user-config pin', () => {+ it('is absent by default on both spawn paths', () => {+ expect(buildVendorCliArgs(codexCli, [], {})).not.toContain('--ignore-user-config');+ expect(buildVendorSpawnConfig(codexCli, {}).args).not.toContain('--ignore-user-config');+ expect(applyCommandDefaults('codex', [], codexTui)).not.toContain('--ignore-user-config');+ });++ it('appends the flag on every spawn path once the provider opts in', () => {+ expect(buildVendorCliArgs(pinned(codexCli), [], {})).toContain('--ignore-user-config');+ expect(buildVendorSpawnConfig(pinned(codexCli), {}).args).toContain('--ignore-user-config');+ expect(applyCommandDefaults('codex', [], pinned(codexTui))).toContain('--ignore-user-config');+ });++ it('does not duplicate a flag the user already pinned in provider args', () => {+ const args = buildVendorCliArgs(pinned(codexCli), ['--ignore-user-config'], {});+ expect(args.filter((arg) => arg === '--ignore-user-config')).toHaveLength(1);+ const tuiArgs = applyCommandDefaults('codex', ['--ignore-user-config'], pinned(codexTui));+ expect(tuiArgs.filter((arg) => arg === '--ignore-user-config')).toHaveLength(1);+ });++ it('leaves the public-review recipe passing the flag regardless of the toggle', () => {+ for (const provider of [codexCli, pinned(codexCli)]) {+ const config = buildVendorSpawnConfig(provider, { safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE });+ expect(config.args.filter((arg) => arg === '--ignore-user-config')).toHaveLength(1);+ }+ });++ it('never reaches a non-codex vendor', () => {+ const claude = { id: 'claude-code', type: 'cli', command: 'claude', ignoreUserConfig: true };+ expect(buildVendorSpawnConfig(claude, {}).args).not.toContain('--ignore-user-config');+ });+});diff --git a/server/lib/providerVendors.js b/server/lib/providerVendors.jsindex 4452364f04..6b8483e49c 100644--- a/server/lib/providerVendors.js+++ b/server/lib/providerVendors.js@@ -156,12 +156,27 @@ const isDirectBinaryProvider = (provider) => provider?.type === PROVIDER_TYPES.C// ─── codex ──────────────────────────────────────────────────────────────────+// The opt-in that pins a Codex run to the account PortOS believes it is using.+// A third-party bridge re-points Codex by writing top-level routing keys into+// `~/.codex/config.toml`, and codex honors that file on every invocation — so+// without this flag PortOS's runs, reviewer rounds and autofixer repairs route+// wherever that file says while the provider card reports a ChatGPT account.+// Default OFF (an absent flag is today's behavior); the AI Providers page badges+// the override and offers the toggle. Same flag the public-review recipes+// already pass, so no new Codex surface is introduced here.+const codexIgnoreUserConfigArgs = (provider, existingArgs = []) => (+ provider?.ignoreUserConfig === true && !existingArgs.includes('--ignore-user-config')+ ? ['--ignore-user-config']+ : []+);+function codexCliArgs(baseArgs, { model, effort, provider }) {// Detect an existing leading `exec` in user/legacy args so we don't end up// running `codex exec --full-auto exec -` after migration of legacy// configs that already pinned an `exec` subcommand.const hasExec = baseArgs.includes('exec');const args = hasExec ? [...baseArgs] : [...baseArgs, 'exec'];+ args.push(...codexIgnoreUserConfigArgs(provider, args));args.push(...buildCodexStartupArgs(baseArgs));if (model) {args.push('--model', model);@@ -178,6 +193,7 @@ function codexSpawnArgs(provider, { effectiveModel, effort, maxConcurrentThreadsconst args = ['exec','--dangerously-bypass-approvals-and-sandbox',+ ...codexIgnoreUserConfigArgs(provider),...buildCodexStartupArgs(),...buildCodexAgentThreadArgs(maxConcurrentThreads),];@@ -779,10 +795,13 @@ export function inferTuiCommand(id) {* friends append `--dangerously-skip-permissions`-class defaults, which would* undo the recipe.)*/-export function applyCommandDefaults(command, args) {+export function applyCommandDefaults(command, args, provider = null) {const vendor = PROVIDER_VENDORS.find((v) => v.tuiArgs && v.matchCommand(command));if (!vendor) return args;- return vendor.tuiArgs(args);+ // `provider` is optional and only some vendors read it (codex, for the+ // `ignoreUserConfig` pin) — a vendor that ignores the second argument keeps+ // behaving exactly as before.+ return vendor.tuiArgs(args, provider);}/**diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex c4de90663a..86f687141d 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -963,7 +963,7 @@ export { applyCommandDefaults };*/export function buildTuiInvocation(provider, model) {const command = provider?.command || inferTuiCommand(provider?.id);- const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])]);+ const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])], provider);const effort = provider?.effort || null;return {command,diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 62013f6e6a..7653d4773a 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -201,6 +201,11 @@ export function createPortOSProviderRoutes(aiToolkit) {...presentProvider(provider, capabilities),prerequisitesMet: prerequisites[provider.id]?.met ?? true,missingPrerequisites: prerequisites[provider.id]?.missing ?? [],+ // NON-blocking notices — today only 'this install's own ~/.codex/config.toml+ // re-points Codex model routing'. Kept OUT of `missingPrerequisites` so a+ // legitimate user choice never buckets a card as NEEDS SETUP; the card+ // renders it as a badge and caveats the subscription quota with it.+ prerequisiteAdvisories: prerequisites[provider.id]?.advisories ?? [],...(isCodexSubscriptionProvider(provider) ? { codexAccount, codexModelCatalog } : {}),})),runnerAllowedCommands: RUNNER_ALLOWED_COMMANDSdiff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex b7dfd66065..e07ba47f75 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -314,7 +314,7 @@ export function buildTuiSpawnConfig(provider, model, {};}const command = provider?.command || inferTuiCommand(provider?.id);- const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])]);+ const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])], provider);// Model+effort injection (including the antigravity-validates-the-pair special// case) is shared with tuiHandshake.js#buildTuiInvocation via// providerVendors.js#injectTuiModelAndEffort, so the two spawn paths can'tdiff --git a/server/services/providerPrerequisites.js b/server/services/providerPrerequisites.jsindex a38016eb22..f6bd259e51 100644--- a/server/services/providerPrerequisites.js+++ b/server/services/providerPrerequisites.js@@ -35,6 +35,7 @@import { blocksRouting, describeMissingPrerequisites, providerPrerequisites, providerRuntimeKey } from '../lib/providerPrerequisites.js';import { PROVIDER_GATEWAYS } from '../lib/providerGateways.js';+import { readCodexRoutingOverride } from '../lib/codexUserConfig.js';import { inferTuiCommand } from '../lib/providerVendors.js';import { findCommandOnPath } from '../lib/processEnv.js';import { peekCodexAccountReadiness } from './codexAppServer.js';@@ -108,6 +109,10 @@ const forProvider = (provider, runtimes, gatewayKeySet) => providerPrerequisitesruntime: runtimes?.[providerRuntimeKey(provider) ?? ''] ?? null,gatewayKeySet,codexAccount: peekCodexAccountReadiness(),+ // A short-TTL read of a small local file — no spawn, no network, no LLM.+ // Advisory only: it never reaches `missing`, so it cannot change routing or+ // a readiness verdict.+ codexRouting: readCodexRoutingOverride(),});const effectiveProcessCommand = (provider) => {diff --git a/server/services/providerPrerequisites.test.js b/server/services/providerPrerequisites.test.jsindex 22c622d58b..e149dcaef8 100644--- a/server/services/providerPrerequisites.test.js+++ b/server/services/providerPrerequisites.test.js@@ -11,6 +11,12 @@ vi.mock('./providerRuntimeInstaller.js', async (importOriginal) => ({peekProviderRuntimeStatuses: vi.fn(),}));+// The routing probe reads the DEVELOPER's own ~/.codex/config.toml otherwise,+// which would make every assertion below depend on the machine the suite runs+// on. Stubbed to a clean snapshot; the advisory path has its own case.+vi.mock('../lib/codexUserConfig.js', () => ({ readCodexRoutingOverride: vi.fn() }));++const { readCodexRoutingOverride } = await import('../lib/codexUserConfig.js');const {getProviderRuntimeStatus,getProviderRuntimeStatuses,@@ -33,6 +39,7 @@ beforeEach(() => {vi.clearAllMocks();__resetPrerequisiteRefresh();peekProviderRuntimeStatuses.mockReturnValue({});+ readCodexRoutingOverride.mockReturnValue({ overridden: false, keys: [], baseUrl: null });getProviderRuntimeStatus.mockResolvedValue(null);getProviderRuntimeStatuses.mockResolvedValue({});vi.spyOn(console, 'log').mockImplementation(() => {});@@ -49,7 +56,7 @@ describe('getProviderPrerequisiteMap', () => {{ id: 'lmstudio', type: 'api', endpoint: 'http://localhost:1234/v1' },]);- expect(map.codex).toEqual({ met: false, missing: [{ code: 'runtime', label: 'Codex CLI is not installed' }] });+ expect(map.codex).toEqual({ met: false, missing: [{ code: 'runtime', label: 'Codex CLI is not installed' }], advisories: [] });expect(map.openai.met).toBe(false);expect(map.lmstudio.met).toBe(true);});@@ -59,7 +66,7 @@ describe('getProviderPrerequisiteMap', () => {it('never awaits the probe; a cold cache publishes no runtime finding and refreshes behind the request', () => {const map = getProviderPrerequisiteMap([codex()]);- expect(map.codex).toEqual({ met: true, missing: [] });+ expect(map.codex).toEqual({ met: true, missing: [], advisories: [] });expect(getProviderRuntimeStatuses).toHaveBeenCalledTimes(1);});@@ -313,3 +320,34 @@ describe('prerequisitesMetForRouting', () => {expect(console.log).toHaveBeenCalledWith(expect.stringContaining('Codex CLI is not installed'));});});++/**+ * The routing advisory reaches the published map without ever becoming a+ * prerequisite — the regression that would otherwise bench a working Codex+ * provider for a configuration choice the user deliberately made.+ */+describe('codex routing advisory in the published map', () => {+ it('publishes the advisory while the verdict stays met', () => {+ readCodexRoutingOverride.mockReturnValue({+ overridden: true,+ keys: ['openai_base_url'],+ baseUrl: 'http://127.0.0.1:9999/v1',+ });+ peekProviderRuntimeStatuses.mockReturnValue({ codex: CODEX_PRESENT });++ const map = getProviderPrerequisiteMap([codex()]);++ expect(map.codex.met).toBe(true);+ expect(map.codex.missing).toEqual([]);+ expect(map.codex.advisories[0]).toMatchObject({ code: 'codexRoutingOverridden' });+ });++ it('keeps an overridden route out of the strict readiness verdict', async () => {+ readCodexRoutingOverride.mockReturnValue({ overridden: true, keys: ['model_provider'], baseUrl: null });+ peekProviderRuntimeStatuses.mockReturnValue({ codex: CODEX_PRESENT });++ const readiness = await getProviderPrerequisiteReadinessMap([codex()]);++ expect(readiness.codex).toEqual({ status: 'ready', reasonCodes: [] });+ });+});diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex 311ab357a2..66491f092a 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -1,5 +1,4 @@import { readdir } from 'fs/promises';-import { homedir } from 'os';import { join } from 'path';import { getAllProviders } from './providers.js';import { getClaudeCodeUsage, systemTimeZone } from './claudeCodeUsage.js';@@ -9,6 +8,7 @@ import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';import { createStaleWhileRevalidate, PENDING, WAIT } from '../lib/staleWhileRevalidate.js';import { parseHumanReset } from '../lib/quotaReset.js';import { readFileTail } from '../lib/fileUtils.js';+import { codexHomeDir, readCodexRoutingOverride } from '../lib/codexUserConfig.js';import { getSettings } from './settings.js';import { getImageGenQuota, IMAGE_GEN_FAMILY } from './imageGenQuota.js';import { mergeFleetQuotaCards } from '../lib/fleetQuotas.js';@@ -67,8 +67,6 @@ const CODEX_TAIL_BYTES = 256 * 1024;// hold a window that has not already reset.const CODEX_MAX_WINDOW_MS = 8 * 24 * 60 * 60 * 1000;-const codexHomeDir = () => process.env.CODEX_HOME || join(homedir(), '.codex');-function humanizeWindowMinutes(minutes) {if (!Number.isFinite(minutes)) return 'window';if (minutes % 10080 === 0) return minutes === 10080 ? 'week' : `${minutes / 10080} weeks`;@@ -181,7 +179,21 @@ function codexNoWindowsMessage(rateLimits, now) {* Pure: map a codex `rate_limits` payload + event timestamp to the common* quota shape. Exported for tests.*/-export function mapCodexQuota(rateLimits, timestamp, { now = Date.now() } = {}) {+/**+ * The caveat every Codex quota card carries when the install's own+ * `~/.codex/config.toml` re-points model routing: these meters describe the+ * signed-in ChatGPT account, and PortOS's Codex runs may not be going there.+ * Names no base URL — that value is machine-local and belongs only in the UI+ * that reads it directly.+ */+const CODEX_ROUTING_CAVEAT = 'Your ~/.codex/config.toml overrides Codex model routing, so PortOS runs may not be counted here.';++export function mapCodexQuota(rateLimits, timestamp, {+ now = Date.now(),+ // Injected so the mapper stays deterministic in a test: read from the+ // install's own config by default, never probed twice per card.+ routingOverridden = readCodexRoutingOverride()?.overridden === true,+} = {}) {const limits = codexUsableWindows(rateLimits, now);return {family: 'codex',@@ -193,9 +205,14 @@ export function mapCodexQuota(rateLimits, timestamp, { now = Date.now() } = {})approximate: true,// Wording is "telemetry", not "session activity": the reading can come from// an older session than the newest one when that session reported no window.- note: timestamp- ? `As of the last Codex rate-limit telemetry (${timestamp}). Local telemetry only.`- : 'As of the last Codex rate-limit telemetry. Local telemetry only.',+ note: [+ timestamp+ ? `As of the last Codex rate-limit telemetry (${timestamp}). Local telemetry only.`+ : 'As of the last Codex rate-limit telemetry. Local telemetry only.',+ // Advisory only — a routing override never suppresses the meters, it just+ // stops them being presented as if they described PortOS's own work.+ routingOverridden ? CODEX_ROUTING_CAVEAT : null,+ ].filter(Boolean).join(' '),...(limits.length ? {} : { error: codexNoWindowsMessage(rateLimits, now) }),fetchedAt: new Date().toISOString()};@@ -244,6 +261,7 @@ async function listCodexRolloutFiles(codexHome) {/** Exported for tests (which point `codexHome` at a fixture tree). */export async function fetchCodexQuota({ codexHome = codexHomeDir(), now = Date.now() } = {}) {+ const routingOverridden = readCodexRoutingOverride()?.overridden === true;const files = await listCodexRolloutFiles(codexHome);// Newest-usable-wins across files, exactly as parseCodexRateLimits applies it// within one: keep the newest window-less reading as a fallback, but keep@@ -260,7 +278,7 @@ export async function fetchCodexQuota({ codexHome = codexHomeDir(), now = Date.nif (!tail) continue;const found = parseCodexRateLimits(tail, { now });if (!found) continue;- const quota = mapCodexQuota(found.rateLimits, found.timestamp, { now });+ const quota = mapCodexQuota(found.rateLimits, found.timestamp, { now, routingOverridden });if (quota.limits.length) return quota;fallback ??= quota;}diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.jsindex e8ce6eae38..12613d1acb 100644--- a/server/services/providerUsage.test.js+++ b/server/services/providerUsage.test.js@@ -194,6 +194,27 @@ describe('mapCodexQuota', () => {expect(quota.error).toBeUndefined();});+ // The meters describe the signed-in ChatGPT account. When the install's own+ // ~/.codex/config.toml re-points model routing, PortOS's runs may not be+ // going there — the card must say so rather than present the numbers as if+ // they covered its own work (#6304).+ it('caveats the note when the user config overrides Codex routing, and names no base URL', () => {+ const quota = mapCodexQuota(SAMPLE_RATE_LIMITS, '2026-01-02T00:00:00Z', {+ now: SAMPLE_NOW,+ routingOverridden: true,+ });+ expect(quota.note).toContain('2026-01-02T00:00:00Z');+ expect(quota.note).toContain('~/.codex/config.toml overrides Codex model routing');+ expect(quota.note).not.toMatch(/https?:\/\//);+ expect(quota.limits).toHaveLength(2);++ const clean = mapCodexQuota(SAMPLE_RATE_LIMITS, '2026-01-02T00:00:00Z', {+ now: SAMPLE_NOW,+ routingOverridden: false,+ });+ expect(clean.note).not.toContain('config.toml');+ });+it('renders a fully-spent window as a 100%-used meter, not an empty card', () => {const spent = { ...SAMPLE_RATE_LIMITS, primary: null, secondary: { used_percent: 100, window_minutes: 10080, resets_at: 1767830400 } };const quota = mapCodexQuota(spent, '2026-01-02T00:00:00Z', { now: SAMPLE_NOW });