Skip to content

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

feat: offer the signed-in ChatGPT account's real model catalog in the CoS Codex picker (#6306)

[._.]/ Adam Eivyd0f5e337fa26
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsx
index 932c6d058e..b02a3489c5 100644
--- a/client/src/components/cos/TaskAddForm.jsx
+++ b/client/src/components/cos/TaskAddForm.jsx
@@ -8,7 +8,7 @@ import { processScreenshotUploads, processAttachmentUploads } from '../../servic
import { ATTACHMENT_ACCEPT } from '../../utils/fileUpload';
import FilePickerButton from '../ui/FilePickerButton';
import { formatBytes } from '../../utils/formatters';
-import { effectiveModelFor, effortAwareModelOptions, effortSurvivingModel, isTuiProvider, isCliProvider, isProcessProvider, isCodexProvider, isOpencodeLocalProvider, generationControlsFor, seedModelEffort } from '../../utils/providers';
+import { effectiveModelFor, effortAwareModelOptions, effortSurvivingModel, isTuiProvider, isCliProvider, isProcessProvider, isCodexProvider, isCodexSubscriptionProvider, isOpencodeLocalProvider, generationControlsFor, seedModelEffort, resolveProviderModelOptions, MODEL_SOURCE } from '../../utils/providers';
import { DEFAULT_PR_COMPLETION, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, PR_COMPLETION_OPTIONS, prCompletionOption } from './constants';
import { clickableProps } from '../../lib/a11yKeyboard';
import { slashdoLabel } from '../../lib/slashdoCatalog';
@@ -406,11 +406,27 @@ export default function TaskAddForm({ providers, providersLoaded = true, apps, o
// with the tier picked separately — a legacy suffixed id saved in a template
// stays selectable as its own option.
const selectedProvider = providers?.find(p => p.id === newTask.provider);
- const availableModels = effortAwareModelOptions(selectedProvider, newTask.model);
+ // A Codex-subscription provider offers the SIGNED-IN ACCOUNT's catalog when one
+ // has been fetched, so a tier the plan cannot run is never queued (#6306); every
+ // other state falls back to the shipped list, and the note below says which.
+ const { models: availableModels, source: modelSource, unlistedSelection } =
+ resolveProviderModelOptions(selectedProvider, newTask.model);
+ const NO_ACCOUNT_MODELS_NOTE = 'Your signed-in ChatGPT account exposes no models.';
+ const modelSourceNote = (() => {
+ if (!isCodexSubscriptionProvider(selectedProvider)) return '';
+ if (modelSource === MODEL_SOURCE.account) return 'Models your signed-in ChatGPT account can run.';
+ // Reachable with a stored pin the account no longer lists — the select still
+ // renders that one option, so it must not be labelled as the bundled list.
+ if (modelSource === MODEL_SOURCE.accountEmpty) return NO_ACCOUNT_MODELS_NOTE;
+ return 'Showing PortOS\u2019s bundled list \u2014 the ChatGPT account catalog has not been loaded.';
+ })();
const providerModelNote = (() => {
if (!selectedProvider) return '';
+ if (modelSource === MODEL_SOURCE.accountEmpty) return NO_ACCOUNT_MODELS_NOTE;
if (isTuiProvider(selectedProvider)) return `${selectedProvider.name} runs in an attachable terminal UI session.`;
- if (isCodexProvider(selectedProvider)) return 'Codex uses the model configured in ~/.codex/config.toml.';
+ // PortOS passes `--model` on every Codex spawn (providerVendors.js#codexSpawnArgs),
+ // so ~/.codex/config.toml is NOT what picks the model here.
+ if (isCodexProvider(selectedProvider)) return 'PortOS runs Codex with the model it selects; no models are listed for this provider yet.';
if (isCliProvider(selectedProvider)) return `${selectedProvider.name} uses its CLI configured default model.`;
return 'No models are configured. PortOS will use the provider default.';
})();
@@ -1179,9 +1195,16 @@ export default function TaskAddForm({ providers, providersLoaded = true, apps, o
>
<option value="">Select model...</option>
{availableModels.map(m => (
- <option key={m} value={m}>{m.replace('claude-', '').replace(/-\d+$/, '')}</option>
+ <option key={m} value={m}>
+ {unlistedSelection && m === newTask.model
+ ? `${m} (not in account catalog)`
+ : m.replace('claude-', '').replace(/-\d+$/, '')}
+ </option>
))}
</select>
+ {modelSourceNote && (
+ <p className="mt-1 text-xs text-gray-400">{modelSourceNote}</p>
+ )}
</div>
) : selectedProvider ? (
<div className="flex-1 px-3 py-2 min-h-[44px] bg-port-bg border border-port-border rounded-lg text-xs text-gray-400 flex items-center">
diff --git a/client/src/components/cos/TaskAddForm.test.jsx b/client/src/components/cos/TaskAddForm.test.jsx
index 91bbee8463..a983ce4d9d 100644
--- a/client/src/components/cos/TaskAddForm.test.jsx
+++ b/client/src/components/cos/TaskAddForm.test.jsx
@@ -14,6 +14,9 @@ const api = vi.hoisted(() => ({
applyCosTaskTemplate: vi.fn(),
addCosTask: vi.fn(),
getOrchestrationProfiles: vi.fn(),
+ // Declared so the render-path assertion below is real: the picker must read the
+ // cached catalog off the provider payload, never fetch one of its own (#6306).
+ getCodexModels: vi.fn(),
}));
// useAssignableInstances reads the instance registry straight off apiSystem, so
@@ -719,3 +722,76 @@ describe('TaskAddForm worktree/PR defaults', () => {
});
});
});
+
+// #6306: a Codex task must not be queued against a model the signed-in ChatGPT
+// account cannot run — and a cold/failed catalog must not empty the dropdown.
+describe('TaskAddForm Codex model catalog', () => {
+ const SHIPPED = ['gpt-6-astra', 'gpt-5.6-sol', 'gpt-5.4'];
+ const codexProvider = (codexModelCatalog) => ({
+ id: 'codex',
+ name: 'Codex CLI',
+ type: 'cli',
+ command: 'codex',
+ enabled: true,
+ models: SHIPPED,
+ codexModelCatalog,
+ });
+
+ const renderWithCodex = async (catalog) => {
+ const user = userEvent.setup();
+ render(
+ <TaskAddForm
+ providers={[codexProvider(catalog)]}
+ apps={[{ id: 'example-app', name: 'Example App', repoPath: 'example.com/repo' }]}
+ defaultApp="example-app"
+ onTaskAdded={vi.fn()}
+ />
+ );
+ await waitFor(() => expect(screen.getByLabelText('AI provider')).not.toBeDisabled());
+ await user.selectOptions(screen.getByLabelText('AI provider'), 'codex');
+ return user;
+ };
+
+ const modelValues = () =>
+ Array.from(screen.getByLabelText('AI model').querySelectorAll('option'))
+ .map((option) => option.value)
+ .filter(Boolean);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.getCosPopularTemplates.mockResolvedValue({ templates: [] });
+ api.getCodeReviewDefaults.mockResolvedValue(null);
+ api.getLocalLlmStatus.mockResolvedValue({ ollama: { models: [] }, lmstudio: { models: [] } });
+ api.getProviders.mockResolvedValue({ providers: [] });
+ api.getAppWorkTracker.mockResolvedValue({ resolved: 'github' });
+ api.getAppRepositorySources.mockResolvedValue({
+ issueTargets: { default: 'origin', canChoose: false, origin: { fullName: 'example-org/example-app' }, upstream: { fullName: 'example-org/example-app' } },
+ });
+ api.applyCosTaskTemplate.mockResolvedValue({ success: true });
+ api.getOrchestrationProfiles.mockResolvedValue({ profiles: [] });
+ apiSystem.getAssignableInstances.mockResolvedValue({ instances: [] });
+ });
+
+ it('offers the signed-in account catalog, and never fetches one from a render', async () => {
+ await renderWithCodex({ models: [{ id: 'gpt-5.4' }, { id: 'gpt-5.4-mini' }], fetchedAt: 1, error: null });
+
+ expect(modelValues()).toEqual(['gpt-5.4', 'gpt-5.4-mini']);
+ expect(screen.getByText(/signed-in ChatGPT account can run/i)).toBeInTheDocument();
+ // Rendering a picker must not be what starts `codex app-server`.
+ expect(api.getCodexModels).not.toHaveBeenCalled();
+ });
+
+ it('keeps the shipped list, and says so, when the catalog failed to load', async () => {
+ await renderWithCodex({ models: null, fetchedAt: null, error: { code: 'protocol', message: 'boom' } });
+
+ expect(modelValues()).toEqual(SHIPPED);
+ expect(screen.getByText(/bundled list/i)).toBeInTheDocument();
+ });
+
+ it('explains a successfully-read empty catalog instead of rendering a blank control', async () => {
+ await renderWithCodex({ models: [], fetchedAt: 1, error: null });
+
+ expect(screen.queryByLabelText('AI model')).not.toBeInTheDocument();
+ expect(screen.getByText(/exposes no models/i)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.js
index 2098fb13c3..e67bf1d0b0 100644
--- a/client/src/services/apiProviders.js
+++ b/client/src/services/apiProviders.js
@@ -73,8 +73,10 @@ export const cancelCodexLogin = (loginId, options) => request('/providers/codex/
});
export const codexLogout = (options) => request('/providers/codex/account/logout', { method: 'POST', ...options });
// The models this subscription may run, from the app-server catalog (#5590).
-// Not yet called from a component: the Providers-page picker that consumes it is
-// #5591 (phase 3), which also ships the toggle that sets `textTransportEnabled`.
+// This is the LAZY read that may spawn `codex app-server` — call it only from an
+// explicit user action (the Providers page's refresh). Render paths read the
+// cached catalog off `codexModelCatalog` on the `GET /providers` payload instead
+// (#6306), which spawns nothing.
// Resolves to { models, fetchedAt, error }. `models: null` means NEVER FETCHED
// and `[]` means fetched-and-empty; when `error` is set the list is the
// last-known-good one, so render that rather than emptying the picker.
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 6bb75f4e73..45787310f6 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -543,23 +543,94 @@ export const withStaleAntigravityPin = (provider, models, selectedModel) => {
return stale ? [...list, selectedModel] : list;
};
+/**
+ * The model ids in a signed-in ChatGPT account's catalog, or `null` when the
+ * catalog is not a SUCCESSFUL read.
+ *
+ * The server ships `{ models, fetchedAt, error }` on a Codex-subscription
+ * provider (`codexModelCatalog`), and all three states are distinct:
+ * `models: null` = never fetched, a set `error` = the last read failed (the
+ * list, if any, is only last-known-good), and `[]` = this account genuinely
+ * exposes no models. Only the last two of those are answers about the account,
+ * so a never-fetched or failed read collapses to `null` here and the caller
+ * keeps its shipped list — an offline or signed-out user must never be handed
+ * an empty dropdown.
+ *
+ * CLIENT-ONLY (no server mirror).
+ * @param {{codexModelCatalog?:{models?:unknown, error?:unknown}}|null|undefined} provider
+ * @returns {string[]|null}
+ */
+export const codexCatalogModelIds = (provider) => {
+ const catalog = provider?.codexModelCatalog;
+ if (!catalog || catalog.error || !Array.isArray(catalog.models)) return null;
+ return catalog.models
+ .map((entry) => (typeof entry === 'string' ? entry : entry?.id))
+ .filter((id) => typeof id === 'string' && id !== '');
+};
+
+/** Where a picker's option list came from. */
+export const MODEL_SOURCE = Object.freeze({
+ /** The provider's shipped/configured `models` array. */
+ shipped: 'shipped',
+ /** The signed-in ChatGPT account's own catalog. */
+ account: 'account',
+ /** The account was read successfully and exposes no models. */
+ accountEmpty: 'account-empty',
+});
+
+/**
+ * The option list for a picker, plus WHERE it came from.
+ *
+ * For a Codex-subscription provider whose account catalog has been fetched, the
+ * options are that account's real models — so a tier the plan cannot run is not
+ * selectable and cannot be queued against a worktree that would only fail later.
+ * Every other state (never fetched, failed read, non-Codex provider) falls back
+ * to the shipped list unchanged.
+ *
+ * ADDITIVE: a stored `selectedModel` the catalog no longer lists is retained as
+ * its own option and reported via `unlistedSelection`, so an existing task
+ * template renders what it actually holds instead of silently changing model.
+ *
+ * CLIENT-ONLY (no server mirror).
+ * @param {{id?:string, command?:string, models?:unknown[]}|null|undefined} provider
+ * @param {string|null|undefined} selectedModel
+ * @returns {{models: unknown[], source: string, unlistedSelection: boolean}}
+ */
+export const resolveProviderModelOptions = (provider, selectedModel) => {
+ const shipped = withStaleAntigravityPin(
+ provider,
+ filterSelectableModels(selectableModelsForProvider(provider, provider?.models)),
+ selectedModel,
+ );
+ const catalog = isCodexSubscriptionProvider(provider) ? codexCatalogModelIds(provider) : null;
+ if (!catalog) return { models: shipped, source: MODEL_SOURCE.shipped, unlistedSelection: false };
+ const models = filterSelectableModels(catalog);
+ const unlistedSelection = !!selectedModel
+ && !isConfiguredDefaultModel(selectedModel)
+ && !models.includes(selectedModel);
+ return {
+ models: unlistedSelection ? [...models, selectedModel] : models,
+ source: models.length > 0 ? MODEL_SOURCE.account : MODEL_SOURCE.accountEmpty,
+ unlistedSelection,
+ };
+};
+
/**
* The option list for a picker that renders an effort control but reads
* `provider.models` directly (no `useProviderModels`): base models, sentinels
* stripped, plus any legacy suffixed pin so the stored value stays visible.
* The hook's own list is assembled from the same two primitives, so the two
- * paths can't drift.
+ * paths can't drift. Codex-subscription providers resolve through
+ * `resolveProviderModelOptions`, so every picker offers the same account-aware
+ * answer without each one reimplementing the fallback.
*
* CLIENT-ONLY (no server mirror).
* @param {{id?:string, command?:string, models?:unknown[]}|null|undefined} provider
* @param {string|null|undefined} selectedModel
* @returns {unknown[]}
*/
-export const effortAwareModelOptions = (provider, selectedModel) => withStaleAntigravityPin(
- provider,
- filterSelectableModels(selectableModelsForProvider(provider, provider?.models)),
- selectedModel,
-);
+export const effortAwareModelOptions = (provider, selectedModel) =>
+ resolveProviderModelOptions(provider, selectedModel).models;
/**
* The model a run will ACTUALLY use: the explicit pin, else the provider's own
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 9781d0c291..7f6b2c2804 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -79,6 +79,9 @@ import {
selectableModelsForProvider,
withStaleAntigravityPin,
effortAwareModelOptions,
+ resolveProviderModelOptions,
+ codexCatalogModelIds,
+ MODEL_SOURCE,
effectiveModelFor,
effortSurvivingModel,
seedModelEffort,
@@ -333,6 +336,66 @@ describe('Antigravity base-model split (server mirror)', () => {
});
});
+ // #6306: the CoS picker must offer the SIGNED-IN account's catalog, and must
+ // never be emptied by a cold cache or a failed read.
+ describe('resolveProviderModelOptions (Codex account catalog)', () => {
+ const SHIPPED = ['gpt-6-astra', 'gpt-5.6-sol', 'gpt-5.4'];
+ const codex = (codexModelCatalog) => ({
+ id: 'codex', name: 'Codex CLI', type: 'cli', command: 'codex', models: SHIPPED, codexModelCatalog,
+ });
+
+ it('offers the account catalog when one was fetched', () => {
+ const result = resolveProviderModelOptions(
+ codex({ models: [{ id: 'gpt-5.4' }, { id: 'gpt-5.4-mini' }], fetchedAt: 1, error: null }),
+ 'gpt-5.4',
+ );
+ expect(result.models).toEqual(['gpt-5.4', 'gpt-5.4-mini']);
+ expect(result.source).toBe(MODEL_SOURCE.account);
+ expect(result.unlistedSelection).toBe(false);
+ });
+
+ it('keeps the shipped list for a never-fetched catalog and for a failed read', () => {
+ for (const catalog of [
+ undefined,
+ { models: null, fetchedAt: null, error: null },
+ { models: null, fetchedAt: null, error: { code: 'protocol', message: 'boom' } },
+ // A failed read hands back a LAST-KNOWN-GOOD list, which is not an answer
+ // about the account either — the shipped list stands.
+ { models: [{ id: 'gpt-5.4' }], fetchedAt: 1, error: { code: 'protocol', message: 'boom' } },
+ ]) {
+ const result = resolveProviderModelOptions(codex(catalog), '');
+ expect(result.models).toEqual(SHIPPED);
+ expect(result.source).toBe(MODEL_SOURCE.shipped);
+ }
+ });
+
+ it('reports a successfully-read empty catalog as its own state, not as shipped', () => {
+ const result = resolveProviderModelOptions(codex({ models: [], fetchedAt: 1, error: null }), '');
+ expect(result.models).toEqual([]);
+ expect(result.source).toBe(MODEL_SOURCE.accountEmpty);
+ });
+
+ it('retains a stored model the catalog no longer lists, flagged', () => {
+ const result = resolveProviderModelOptions(
+ codex({ models: [{ id: 'gpt-5.4' }], fetchedAt: 1, error: null }),
+ 'gpt-6-astra',
+ );
+ expect(result.models).toEqual(['gpt-5.4', 'gpt-6-astra']);
+ expect(result.unlistedSelection).toBe(true);
+ });
+
+ it('leaves a non-subscription provider on its own catalog', () => {
+ const agy = { id: 'antigravity-cli', command: 'agy', models: CATALOG, codexModelCatalog: { models: [], error: null } };
+ expect(resolveProviderModelOptions(agy, '').source).toBe(MODEL_SOURCE.shipped);
+ expect(codexCatalogModelIds({ codexModelCatalog: { models: null, error: null } })).toBeNull();
+ });
+
+ it('is what effortAwareModelOptions returns, so every picker agrees', () => {
+ const provider = codex({ models: [{ id: 'gpt-5.4' }], fetchedAt: 1, error: null });
+ expect(effortAwareModelOptions(provider, '')).toEqual(resolveProviderModelOptions(provider, '').models);
+ });
+ });
+
describe('effectiveModelFor', () => {
it('falls back to the provider default when no model is pinned', () => {
expect(effectiveModelFor({ defaultModel: 'gemini-3.6-flash' }, '')).toBe('gemini-3.6-flash');
diff --git a/server/routes/providers.codexAccount.test.js b/server/routes/providers.codexAccount.test.js
index 59900138dc..7e1f29ce8e 100644
--- a/server/routes/providers.codexAccount.test.js
+++ b/server/routes/providers.codexAccount.test.js
@@ -13,6 +13,7 @@ vi.mock('../services/codexAppServer.js', () => ({
cancelCodexChatGptLogin: vi.fn(),
codexLogout: vi.fn(),
peekCodexAccountReadiness: vi.fn(() => null),
+ peekCodexModelCatalog: vi.fn(() => ({ models: null, fetchedAt: null, error: null })),
listCodexModels: vi.fn(),
}));
vi.mock('../services/providerRuntimeInstaller.js', async (importOriginal) => ({
@@ -52,6 +53,7 @@ const appWith = (providers = [CODEX, CLAUDE]) => {
beforeEach(() => {
vi.clearAllMocks();
codexAppServer.peekCodexAccountReadiness.mockReturnValue(null);
+ codexAppServer.peekCodexModelCatalog.mockReturnValue({ models: null, fetchedAt: null, error: null });
});
describe('GET /api/providers/codex/account', () => {
@@ -177,6 +179,30 @@ describe('GET /api/providers decorates the Codex cards', () => {
expect(cards['claude-code'].missingPrerequisites).toEqual([]);
});
+ it('publishes the model catalog as its three-state shape, on Codex cards only', async () => {
+ codexAppServer.peekCodexModelCatalog.mockReturnValue({
+ models: [{ id: 'gpt-5.6-terra' }],
+ fetchedAt: 1_700_000_000_000,
+ error: null,
+ });
+
+ const cards = byId(await request(appWith()).get('/api/providers'));
+
+ expect(cards.codex.codexModelCatalog.models).toEqual([{ id: 'gpt-5.6-terra' }]);
+ expect(cards['claude-code']).not.toHaveProperty('codexModelCatalog');
+ // Cache-only: rendering the list must not be what fetches a catalog.
+ expect(codexAppServer.listCodexModels).not.toHaveBeenCalled();
+ });
+
+ it('keeps a never-fetched catalog distinguishable from a fetched-empty one', async () => {
+ const cold = byId(await request(appWith()).get('/api/providers'));
+ expect(cold.codex.codexModelCatalog).toEqual({ models: null, fetchedAt: null, error: null });
+
+ codexAppServer.peekCodexModelCatalog.mockReturnValue({ models: [], fetchedAt: 1_700_000_000_000, error: null });
+ const empty = byId(await request(appWith()).get('/api/providers'));
+ expect(empty.codex.codexModelCatalog.models).toEqual([]);
+ });
+
it('does not turn an unknown verdict into a finding', async () => {
codexAppServer.peekCodexAccountReadiness.mockReturnValue({ ...READY, status: CODEX_ACCOUNT_STATUS.unknown, accountFetched: false, account: null });
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 2a3ae82acc..62013f6e6a 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -26,6 +26,7 @@ import { isCodexSubscriptionProvider } from '../lib/codexAccount.js';
import {
cancelCodexChatGptLogin,
peekCodexAccountReadiness,
+ peekCodexModelCatalog,
codexLogout,
listCodexModels,
getCodexAccountReadiness,
@@ -189,13 +190,18 @@ export function createPortOSProviderRoutes(aiToolkit) {
// `null` here means NOT PROBED, and the dedicated `/codex/account` fetch is
// what fills it — a card renders "unknown", never "signed out", until then.
const codexAccount = peekCodexAccountReadiness();
+ // Same cache-only contract, for the CoS/model pickers (#6306): the signed-in
+ // account's real catalog when one has been fetched, otherwise the three-state
+ // shape that tells the client to keep showing its shipped list. Rendering a
+ // picker must never be what starts `codex app-server`.
+ const codexModelCatalog = peekCodexModelCatalog();
res.json({
activeProvider: data.activeProvider,
providers: data.providers.map((provider) => ({
...presentProvider(provider, capabilities),
prerequisitesMet: prerequisites[provider.id]?.met ?? true,
missingPrerequisites: prerequisites[provider.id]?.missing ?? [],
- ...(isCodexSubscriptionProvider(provider) ? { codexAccount } : {}),
+ ...(isCodexSubscriptionProvider(provider) ? { codexAccount, codexModelCatalog } : {}),
})),
runnerAllowedCommands: RUNNER_ALLOWED_COMMANDS
});
diff --git a/server/services/codexAppServer.js b/server/services/codexAppServer.js
index df256e94e6..2838307fd3 100644
--- a/server/services/codexAppServer.js
+++ b/server/services/codexAppServer.js
@@ -110,6 +110,14 @@ const activeTurns = new Map();
* account has no models".
*/
let modelsCache = null;
+/**
+ * `{ code, message }` from the LAST `model/list` attempt, or `null` when the most
+ * recent attempt succeeded (or none has run). Cached beside — never inside —
+ * `modelsCache`, so a failed read stays distinguishable from a never-fetched
+ * one while the last-known-good list survives: a picker reading the peek can
+ * then say WHY it is showing the shipped list instead of the account's.
+ */
+let modelsError = null;
/** `{ until, category, message }` while the TEXT transport is benched. */
let textTransportBench = null;
/** The empty scratch directory generic text turns run in. Created lazily. */
@@ -222,6 +230,7 @@ const handleNotification = (method, params) => {
// completely as one PortOS started.
if (params?.success !== false) {
modelsCache = null;
+ modelsError = null;
clearCodexTextTransportBench();
}
const loginId = typeof params?.loginId === 'string' ? params.loginId : null;
@@ -610,6 +619,7 @@ export async function codexLogout() {
settleLogin('ended by sign-out');
readinessCache = null;
modelsCache = null;
+ modelsError = null;
// Signing out invalidates whatever the bench was waiting on, and signing back
// in must not inherit the previous account's cooldown.
clearCodexTextTransportBench();
@@ -729,13 +739,15 @@ export async function listCodexModels({ fresh = false } = {}) {
throw new Error(`model/list did not finish paginating within ${MODEL_LIST_MAX_PAGES} pages`);
}
modelsCache = { at: Date.now(), models };
+ modelsError = null;
return { models, fetchedAt: modelsCache.at, error: null };
} catch (err) {
console.error(`❌ Codex model/list failed: ${err.message}`);
+ modelsError = { code: err.code || CODEX_ERROR_CODES.protocol, message: err.message };
return {
models: modelsCache ? modelsCache.models : null,
fetchedAt: modelsCache ? modelsCache.at : null,
- error: { code: err.code || CODEX_ERROR_CODES.protocol, message: err.message },
+ error: modelsError,
};
}
}
@@ -745,6 +757,26 @@ export function peekCodexModels() {
return modelsCache ? { models: modelsCache.models, fetchedAt: modelsCache.at } : null;
}
+/**
+ * The cached catalog as the three-state shape a picker needs, without spawning
+ * anything. `models: null` = NEVER FETCHED, `[]` = fetched and genuinely empty,
+ * and a populated array is this account's real catalog; `error` is set when the
+ * last attempt failed, in which case `models` is the last-known-good list (or
+ * `null` if there never was one). A caller must fall back to its shipped list
+ * for every state except a successful read — that is the whole point of keeping
+ * the three apart.
+ *
+ * CACHE-ONLY, like `peekCodexAccountReadiness`: this is what the providers list
+ * may call on a render path, where spawning `codex app-server` is forbidden.
+ */
+export function peekCodexModelCatalog() {
+ return {
+ models: modelsCache ? modelsCache.models : null,
+ fetchedAt: modelsCache ? modelsCache.at : null,
+ error: modelsError,
+ };
+}
+
/** The catalog entry for `modelId`, or `null` when the catalog is unknown. */
const cachedModelEntry = (modelId) => {
if (!modelId || !modelsCache?.models) return null;
@@ -988,6 +1020,7 @@ export async function stopCodexAppServer() {
settleLogin(null);
readinessCache = null;
modelsCache = null;
+ modelsError = null;
// The child goes down BEFORE any await. `teardown` decides whether to fail
// live turns by comparing `connection` to the dying target, so `connection`
@@ -1035,6 +1068,7 @@ export function __resetCodexAppServer() {
connectingTarget = null;
activeTurns.clear();
modelsCache = null;
+ modelsError = null;
textTransportBench = null;
textTurnCwd = null;
creatingTextTurnCwd = null;
diff --git a/server/services/codexAppServer.turn.test.js b/server/services/codexAppServer.turn.test.js
index 2744f74ad9..cdbe7a017d 100644
--- a/server/services/codexAppServer.turn.test.js
+++ b/server/services/codexAppServer.turn.test.js
@@ -29,6 +29,7 @@ const {
listCodexModels,
codexLogout,
peekCodexModels,
+ peekCodexModelCatalog,
runCodexTextTurn,
stopCodexAppServer,
} = await import('./codexAppServer.js');
@@ -477,6 +478,28 @@ describe('a catalog that will not stop paginating', () => {
});
});
+describe('peekCodexModelCatalog', () => {
+ it('keeps never-fetched, fetched-empty, and failed apart for a picker', async () => {
+ // A picker that cannot tell these three apart either offers an empty
+ // dropdown to an offline user or claims a plan has no models (#6306).
+ expect(peekCodexModelCatalog()).toEqual({ models: null, fetchedAt: null, error: null });
+
+ const empty = listCodexModels();
+ await handshake();
+ await awaitRequest(child, 'model/list', { data: [] });
+ await empty;
+ expect(peekCodexModelCatalog()).toMatchObject({ models: [], error: null });
+ expect(peekCodexModelCatalog().fetchedAt).toEqual(expect.any(Number));
+
+ const failing = listCodexModels({ fresh: true });
+ await awaitRequest(child, 'model/list', (frame) => child.replyError(frame, { code: -32603, message: 'catalog unavailable' }));
+ await failing;
+ // The last-known-good list survives, and the error says it is not authoritative.
+ expect(peekCodexModelCatalog().models).toEqual([]);
+ expect(peekCodexModelCatalog().error.message).toMatch(/catalog unavailable/);
+ });
+});
+
describe('shutdown racing a connect', () => {
it('drops a handshake that lands mid-shutdown instead of leaving a dead handle', async () => {
// The published handle would be a CLOSED one, and the next call would see