diff --git a/cli/src/modules/common/codexModels.test.ts b/cli/src/modules/common/codexModels.test.ts index 759254d8..25c62c94 100644 --- a/cli/src/modules/common/codexModels.test.ts +++ b/cli/src/modules/common/codexModels.test.ts @@ -1,7 +1,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -const { constructorOptions } = vi.hoisted(() => ({ - constructorOptions: [] as unknown[] +const { constructorOptions, listModelsMock } = vi.hoisted(() => ({ + constructorOptions: [] as unknown[], + listModelsMock: vi.fn() })); vi.mock('node:os', async () => { @@ -18,22 +19,104 @@ vi.mock('@/codex/codexAppServerClient', () => ({ async connect(): Promise {} async initialize(): Promise {} async listModels(): Promise<{ data: unknown[] }> { - return { data: [] }; + return listModelsMock(); } async disconnect(): Promise {} } })); -import { listCodexModels } from './codexModels'; +import { listCodexModels, _resetCodexModelsCacheForTests } from './codexModels'; describe('listCodexModels cwd', () => { beforeEach(() => { constructorOptions.length = 0; + listModelsMock.mockReset(); + _resetCodexModelsCacheForTests(); }); it('starts discovery from the user home instead of the caller cwd', async () => { + listModelsMock.mockResolvedValue({ data: [] }); + await listCodexModels(); expect(constructorOptions).toEqual([{ cwd: '/neutral-home' }]); }); + + it('caches the model list within the TTL so repeat calls skip the app-server spawn', async () => { + listModelsMock.mockResolvedValue({ + data: [{ id: 'gpt-5.6-sol', displayName: 'GPT-5.6-Sol', isDefault: true }] + }); + + const first = await listCodexModels(); + const second = await listCodexModels(); + + expect(first).toEqual([expect.objectContaining({ + id: 'gpt-5.6-sol', + displayName: 'GPT-5.6-Sol', + isDefault: true + })]); + expect(second).toEqual(first); + expect(constructorOptions).toHaveLength(1); + expect(listModelsMock).toHaveBeenCalledTimes(1); + }); + + it('keeps visible and hidden model lists in separate cache slots', async () => { + listModelsMock.mockResolvedValue({ data: [{ id: 'gpt-5.6-sol', displayName: 'GPT-5.6-Sol' }] }); + + await listCodexModels(false); + await listCodexModels(false); + await listCodexModels(true); + await listCodexModels(true); + + expect(constructorOptions).toHaveLength(2); + }); + + it('coalesces concurrent requests into a single app-server spawn', async () => { + let resolveList: (value: { data: unknown[] }) => void = () => undefined; + listModelsMock.mockImplementationOnce( + () => new Promise((res) => { resolveList = res; }) + ); + + const inflight1 = listCodexModels(); + const inflight2 = listCodexModels(); + + // Allow the microtasks to schedule the first request before resolving it. + await new Promise((resolve) => setImmediate(resolve)); + resolveList({ data: [{ id: 'gpt-5.6-sol', displayName: 'GPT-5.6-Sol' }] }); + + const [first, second] = await Promise.all([inflight1, inflight2]); + + expect(constructorOptions).toHaveLength(1); + expect(listModelsMock).toHaveBeenCalledTimes(1); + expect(first).toEqual(second); + expect(first).toHaveLength(1); + }); + + it('expires the cache after the TTL so a later call respawns the app-server', async () => { + vi.useFakeTimers(); + try { + listModelsMock.mockResolvedValue({ data: [{ id: 'gpt-5.6-sol', displayName: 'GPT-5.6-Sol' }] }); + + await listCodexModels(); + expect(constructorOptions).toHaveLength(1); + + vi.advanceTimersByTime(5 * 60_000 + 1); + await listCodexModels(); + expect(constructorOptions).toHaveLength(2); + } finally { + vi.useRealTimers(); + } + }); + + it('does not cache empty or failed results', async () => { + listModelsMock.mockResolvedValue({ data: [] }); + await listCodexModels(); + await listCodexModels(); + expect(constructorOptions).toHaveLength(2); + + listModelsMock.mockRejectedValue(new Error('app-server exploded')); + await expect(listCodexModels()).rejects.toThrow('app-server exploded'); + await expect(listCodexModels()).rejects.toThrow('app-server exploded'); + expect(constructorOptions).toHaveLength(4); + }); }); diff --git a/cli/src/modules/common/codexModels.ts b/cli/src/modules/common/codexModels.ts index 6d42872a..2ee774fe 100644 --- a/cli/src/modules/common/codexModels.ts +++ b/cli/src/modules/common/codexModels.ts @@ -81,7 +81,50 @@ function normalizeModel(entry: unknown): CodexModelSummary | null { }; } +interface CacheEntry { + expiresAt: number; + models: CodexModelSummary[]; +} + +// The Codex catalog is account-scoped and changes rarely. Each uncached call +// spawns a fresh `codex app-server` subprocess and validates the ChatGPT +// session, which can take 2-30s when a token refresh or network round trip is +// involved. Cache successful lists for 5 minutes (same shape as the opencode +// model cache) and coalesce concurrent requests into a single spawn. +const CACHE_TTL_MS = 5 * 60_000; +const cache = new Map(); +const inflight = new Map>(); + export async function listCodexModels(includeHidden: boolean = false): Promise { + const cached = cache.get(includeHidden); + if (cached && cached.expiresAt > Date.now()) { + return cached.models; + } + + const existing = inflight.get(includeHidden); + if (existing) { + return existing; + } + + const promise = fetchCodexModelsFromAppServer(includeHidden) + .then((models) => { + if (models.length > 0) { + cache.set(includeHidden, { + expiresAt: Date.now() + CACHE_TTL_MS, + models + }); + } + return models; + }) + .finally(() => { + inflight.delete(includeHidden); + }); + + inflight.set(includeHidden, promise); + return promise; +} + +async function fetchCodexModelsFromAppServer(includeHidden: boolean): Promise { // Model discovery is account-scoped. Never inherit a session/runner cwd: // project config or a deleted worktree must not alter or break the catalog. const client = new CodexAppServerClient({ cwd: homedir() }); @@ -99,14 +142,20 @@ export async function listCodexModels(includeHidden: boolean = false): Promise model !== null) : []; - - return models; } catch (error) { throw new Error(getErrorMessage(error, 'Failed to list Codex models')); } finally { await client.disconnect().catch(() => undefined); } } + +/** + * Clear the in-process cache and any in-flight probe. Exposed for tests. + */ +export function _resetCodexModelsCacheForTests(): void { + cache.clear(); + inflight.clear(); +}