Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(codex): discover models from the execution device (#20425)

AmAzing-6f7c3c07019f
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 94f0703eeef..cfa78912308 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -429,6 +429,7 @@ export const deviceRouter = router({
env: z.record(z.string(), z.string()).optional(),
type: z.enum([
'codebuddy',
+ 'codex',
'cursor',
'droid',
'devin',
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 603b8d61295..37dfea9324d 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -674,6 +674,7 @@ export class DeviceGateway {
timeout?: number;
type:
| 'codebuddy'
+ | 'codex'
| 'cursor'
| 'devin'
| 'droid'
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 6005d934715..e7424349caa 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1145,6 +1145,7 @@
"heteroAgent.cliModel.targetUnavailable": "The target device is unavailable.",
"heteroAgent.cliModel.timeout": "Model discovery timed out.",
"heteroAgent.cliModel.unsupportedClient": "Update the target device client to discover CLI models.",
+ "heteroAgent.cliModel.unsupportedConfiguration": "Model discovery is unavailable for this CLI configuration. You can still use the current model.",
"heteroAgent.cloudNotConfigured.action": "Configure",
"heteroAgent.cloudNotConfigured.desc": "Configure your Claude Code token in agent profile to start sending messages.",
"heteroAgent.cloudNotConfigured.title": "Cloud credentials required",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 59226083146..1986308ac97 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1145,6 +1145,7 @@
"heteroAgent.cliModel.targetUnavailable": "目标设备不可用。",
"heteroAgent.cliModel.timeout": "模型发现超时。",
"heteroAgent.cliModel.unsupportedClient": "请更新目标设备客户端以发现 CLI 模型。",
+ "heteroAgent.cliModel.unsupportedConfiguration": "当前 CLI 配置不支持动态获取模型,仍可使用当前模型。",
"heteroAgent.cloudNotConfigured.action": "立即配置",
"heteroAgent.cloudNotConfigured.desc": "请在 Agent 资料中配置 Claude Code Token,以开始发送消息。",
"heteroAgent.cloudNotConfigured.title": "需要配置云端凭证",
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index 749f87727b0..c7a485ea644 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -362,6 +362,7 @@ export interface ListHeterogeneousAgentModelsParams {
env?: Record<string, string>;
type:
| 'codebuddy'
+ | 'codex'
| 'cursor'
| 'devin'
| 'droid'
@@ -388,7 +389,8 @@ export type HeterogeneousAgentModelCatalog =
| 'command_failed'
| 'device_unavailable'
| 'timeout'
- | 'unsupported_client';
+ | 'unsupported_client'
+ | 'unsupported_configuration';
message: string;
};
status: 'error';
diff --git a/packages/heterogeneous-agents/src/models/codex.test.ts b/packages/heterogeneous-agents/src/models/codex.test.ts
new file mode 100644
index 00000000000..964e3b39b34
--- /dev/null
+++ b/packages/heterogeneous-agents/src/models/codex.test.ts
@@ -0,0 +1,164 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as CodexClientModule from '../codex/CodexAppServerClient';
+import { CodexAppServerRpcError } from '../codex/CodexAppServerClient';
+import { listCodexModels } from './codex';
+
+const { close, construct, request } = vi.hoisted(() => ({
+ close: vi.fn(),
+ construct: vi.fn(),
+ request: vi.fn(),
+}));
+
+vi.mock('../codex/CodexAppServerClient', async (importOriginal) => {
+ const actual = await importOriginal<typeof CodexClientModule>();
+ return {
+ ...actual,
+ CodexAppServerClient: class {
+ close = close;
+ request = request;
+ constructor(options: unknown) {
+ construct(options);
+ }
+ },
+ };
+});
+
+const options = {
+ commandPath: '/custom/codex',
+ cwd: '/repo',
+ env: { CODEX_HOME: '/custom/config' },
+ timeoutMs: 100,
+};
+
+describe('Codex model discovery', () => {
+ beforeEach(() => vi.resetAllMocks());
+ afterEach(() => vi.useRealTimers());
+
+ it('reads all pages without creating a task and returns CLI model values, labels and ordering', async () => {
+ request
+ .mockResolvedValueOnce({
+ data: [
+ { displayName: 'Future model', id: 'catalog-entry', model: 'future-model' },
+ { hidden: true, model: 'hidden-model' },
+ ],
+ nextCursor: 'next',
+ })
+ .mockResolvedValueOnce({
+ data: [{ model: 'future-model' }, { model: 'provider/another-model' }],
+ nextCursor: null,
+ });
+
+ await expect(listCodexModels(options)).resolves.toEqual([
+ { id: 'future-model', label: 'Future model', modelId: 'future-model', providerId: 'codex' },
+ { id: 'provider/another-model', modelId: 'provider/another-model', providerId: 'codex' },
+ ]);
+ expect(request.mock.calls).toEqual([
+ ['model/list', { includeHidden: false, limit: 100 }],
+ ['model/list', { cursor: 'next', includeHidden: false, limit: 100 }],
+ ]);
+ expect(construct).toHaveBeenCalledWith(
+ expect.objectContaining({
+ commandPath: options.commandPath,
+ cwd: options.cwd,
+ env: options.env,
+ reconnectMaxAttempts: 0,
+ }),
+ );
+ expect(close).toHaveBeenCalledOnce();
+ });
+
+ it('preserves configuration but does not forward exec-only switches', async () => {
+ request.mockResolvedValue({ data: [], nextCursor: null });
+ await listCodexModels({
+ ...options,
+ args: [
+ '--full-auto',
+ '--json',
+ '-m',
+ 'future-model',
+ '-c',
+ 'model_provider="custom"',
+ '--config=model_catalog_json="catalog.json"',
+ '--cd',
+ 'subdir',
+ '--enable',
+ 'feature_name',
+ ],
+ });
+ expect(construct).toHaveBeenCalledWith(
+ expect.objectContaining({
+ args: [
+ '-c',
+ 'model_provider="custom"',
+ '--config',
+ 'model_catalog_json="catalog.json"',
+ '--enable',
+ 'feature_name',
+ ],
+ cwd: '/repo/subdir',
+ }),
+ );
+ });
+
+ it('preserves compact config and working-directory flags', async () => {
+ request.mockResolvedValue({ data: [], nextCursor: null });
+ await listCodexModels({ ...options, args: ['-cmodel_provider="custom"', '-Csubdir'] });
+ expect(construct).toHaveBeenCalledWith(
+ expect.objectContaining({
+ args: ['-c', 'model_provider="custom"'],
+ cwd: '/repo/subdir',
+ }),
+ );
+ });
+
+ it.each(['--oss', '--profile=team', '-p', '-pteam', '--ignore-user-config'])(
+ 'does not query the wrong provider for unsupported %s',
+ async (flag) => {
+ await expect(listCodexModels({ ...options, args: [flag] })).rejects.toMatchObject({
+ code: 'unsupported_configuration',
+ });
+ expect(construct).not.toHaveBeenCalled();
+ },
+ );
+
+ it('reports unsupported model/list and closes the connection', async () => {
+ request.mockRejectedValue(new CodexAppServerRpcError('Unknown method', -32_601));
+ await expect(listCodexModels(options)).rejects.toMatchObject({ code: 'unsupported_client' });
+ expect(close).toHaveBeenCalledOnce();
+ });
+
+ it('closes on process failure', async () => {
+ request.mockRejectedValue(new Error('Process exited'));
+ await expect(listCodexModels(options)).rejects.toThrow('Process exited');
+ expect(close).toHaveBeenCalledOnce();
+ });
+
+ it('bounds the entire query even when a later page hangs', async () => {
+ vi.useFakeTimers();
+ request
+ .mockResolvedValueOnce({ data: [], nextCursor: 'next' })
+ .mockImplementationOnce(() => new Promise(() => {}));
+ const result = expect(listCodexModels(options)).rejects.toMatchObject({ code: 'ETIMEDOUT' });
+ await vi.advanceTimersByTimeAsync(options.timeoutMs);
+ await result;
+ expect(request).toHaveBeenCalledTimes(2);
+ expect(close).toHaveBeenCalledOnce();
+ });
+
+ it.each([{}, { data: [{ id: 'id-without-model' }] }, { data: [], nextCursor: 123 }])(
+ 'rejects a malformed catalog instead of reporting a successful empty list: %j',
+ async (page) => {
+ request.mockResolvedValue(page);
+ await expect(listCodexModels(options)).rejects.toThrow('Invalid Codex model catalog');
+ expect(close).toHaveBeenCalledOnce();
+ },
+ );
+
+ it('rejects repeated cursors instead of looping forever', async () => {
+ request.mockResolvedValue({ data: [], nextCursor: 'repeat' });
+ await expect(listCodexModels(options)).rejects.toThrow('cursor');
+ expect(request).toHaveBeenCalledTimes(2);
+ expect(close).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/models/codex.ts b/packages/heterogeneous-agents/src/models/codex.ts
new file mode 100644
index 00000000000..b92874b7f2e
--- /dev/null
+++ b/packages/heterogeneous-agents/src/models/codex.ts
@@ -0,0 +1,132 @@
+import path from 'node:path';
+
+import type { HeterogeneousAgentModel } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
+
+import { CodexAppServerClient, CodexAppServerRpcError } from '../codex/CodexAppServerClient';
+
+interface CodexModelCatalogOptions {
+ args?: string[];
+ commandPath: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+ timeoutMs: number;
+}
+
+/** Discovery has no thread: provider overrides must be applied at process startup. */
+const catalogConfig = (source: string[], initialCwd: string) => {
+ const args: string[] = [];
+ let cwd = initialCwd;
+ const valueFlags = ['-c', '--config', '-C', '--cd', '--enable', '--disable'];
+
+ for (let index = 0; index < source.length; index += 1) {
+ const arg = source[index];
+ if (arg === '--') break;
+ // app-server does not support runtime profiles or exec's local-provider selection.
+ // Falling back is safer than advertising a different provider's catalog.
+ if (
+ ['-p', '--profile', '--oss', '--local-provider', '--ignore-user-config'].some(
+ (flag) =>
+ arg === flag || arg.startsWith(`${flag}=`) || (flag === '-p' && arg.startsWith('-p')),
+ )
+ ) {
+ throw Object.assign(new Error('Unsupported Codex catalog configuration'), {
+ code: 'unsupported_configuration',
+ });
+ }
+ const flag = valueFlags.find(
+ (candidate) =>
+ arg === candidate ||
+ arg.startsWith(`${candidate}=`) ||
+ (candidate.length === 2 && arg.startsWith(candidate)),
+ );
+ if (!flag) continue;
+ const value = arg === flag ? source[++index] : arg.slice(flag.length).replace(/^=/, '');
+ if (!value) throw new Error(`Missing value for Codex ${flag}`);
+
+ if (flag === '-C' || flag === '--cd') cwd = path.resolve(initialCwd, value);
+ else args.push(flag, value);
+ }
+
+ return { args, cwd };
+};
+
+/** A short-lived catalog connection, independent of the exec/app-server task transport. */
+export const listCodexModels = async ({
+ args = [],
+ commandPath,
+ cwd,
+ env,
+ timeoutMs,
+}: CodexModelCatalogOptions): Promise<HeterogeneousAgentModel[]> => {
+ const config = catalogConfig(args, cwd);
+ const client = new CodexAppServerClient({
+ ...config,
+ clientVersion: '1.0.0',
+ commandPath,
+ env,
+ reconnectMaxAttempts: 0,
+ });
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ const readPages = async () => {
+ const models = new Map<string, HeterogeneousAgentModel>();
+ const cursors = new Set<string>();
+ let cursor: string | undefined;
+ do {
+ const page = await client.request<unknown>('model/list', {
+ ...(cursor ? { cursor } : {}),
+ includeHidden: false,
+ limit: 100,
+ });
+ if (!isRecord(page) || !Array.isArray(page.data)) {
+ throw new Error('Invalid Codex model catalog');
+ }
+ for (const item of page.data) {
+ if (!isRecord(item) || typeof item.model !== 'string' || !item.model.trim()) {
+ throw new Error('Invalid Codex model catalog entry');
+ }
+ if (item.hidden === true || models.has(item.model)) continue;
+ // `model`, not the catalog entry's `id`, is accepted by codex exec --model.
+ models.set(item.model, {
+ id: item.model,
+ ...(typeof item.displayName === 'string' && item.displayName.trim()
+ ? { label: item.displayName }
+ : {}),
+ modelId: item.model,
+ providerId: 'codex',
+ });
+ }
+ if (page.nextCursor == null) break;
+ if (typeof page.nextCursor !== 'string' || !page.nextCursor || cursors.has(page.nextCursor)) {
+ throw new Error('Invalid Codex model catalog cursor');
+ }
+ cursor = page.nextCursor;
+ cursors.add(cursor);
+ } while (cursor);
+ return [...models.values()];
+ };
+
+ try {
+ return await Promise.race([
+ readPages(),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ reject(
+ Object.assign(new Error('Codex model discovery timed out'), { code: 'ETIMEDOUT' }),
+ );
+ }, timeoutMs);
+ }),
+ ]);
+ } catch (error) {
+ if (error instanceof CodexAppServerRpcError && error.code === -32_601) {
+ throw Object.assign(new Error('Codex model discovery is not supported'), {
+ code: 'unsupported_client',
+ });
+ }
+ throw error;
+ } finally {
+ clearTimeout(timer);
+ client.close();
+ }
+};
diff --git a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts
index ffef2c834a1..94507fa383c 100644
--- a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts
+++ b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts
@@ -4,7 +4,8 @@ import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-const { listDroidAcpModelsMock, listTraeAcpModelsMock } = vi.hoisted(() => ({
+const { listCodexModelsMock, listDroidAcpModelsMock, listTraeAcpModelsMock } = vi.hoisted(() => ({
+ listCodexModelsMock: vi.fn(),
listDroidAcpModelsMock: vi.fn(),
listTraeAcpModelsMock: vi.fn(),
}));
@@ -27,6 +28,8 @@ vi.mock('../spawn/droidAcpSession', () => ({
listDroidAcpModels: listDroidAcpModelsMock,
}));
+vi.mock('./codex', () => ({ listCodexModels: listCodexModelsMock }));
+
const execFileMock = vi.mocked(childProcess.execFile);
const resolveExecFile = (stdout: string, stderr = '') => {
@@ -48,6 +51,7 @@ const importModule = () => import('./listHeterogeneousAgentModels');
describe('heterogeneous agent model discovery', () => {
beforeEach(() => {
execFileMock.mockReset();
+ listCodexModelsMock.mockReset();
listDroidAcpModelsMock.mockReset();
listTraeAcpModelsMock.mockReset();
});
@@ -56,6 +60,41 @@ describe('heterogeneous agent model discovery', () => {
vi.resetModules();
});
+ it('queries Codex independently of task transport and forwards the target configuration', async () => {
+ const models = [{ id: 'future-model', modelId: 'future-model', providerId: 'codex' }];
+ listCodexModelsMock.mockResolvedValue(models);
+ const { listHeterogeneousAgentModels } = await importModule();
+ await expect(
+ listHeterogeneousAgentModels({
+ args: ['--profile', 'team'],
+ command: '/custom/codex',
+ cwd: '/repo',
+ env: { CODEX_HOME: '/config' },
+ type: 'codex',
+ }),
+ ).resolves.toMatchObject({ models, status: 'success' });
+ expect(listCodexModelsMock).toHaveBeenCalledWith({
+ args: ['--profile', 'team'],
+ commandPath: '/custom/codex',
+ cwd: '/repo',
+ env: { CODEX_HOME: '/config' },
+ timeoutMs: 15_000,
+ });
+ expect(execFileMock).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['unsupported_client', 'unsupported_client'],
+ ['unsupported_configuration', 'unsupported_configuration'],
+ ['ETIMEDOUT', 'timeout'],
+ ])('returns a catalog error for Codex %s so the picker can fall back', async (code, expected) => {
+ listCodexModelsMock.mockRejectedValue(Object.assign(new Error('failure'), { code }));
+ const { listHeterogeneousAgentModels } = await importModule();
+ await expect(
+ listHeterogeneousAgentModels({ command: '/custom/codex', type: 'codex' }),
+ ).resolves.toMatchObject({ error: { code: expected }, status: 'error' });
+ });
+
it('parses opaque model ids, splitting only at the first slash and preserving order', async () => {
const { parseOpenCodeModelCatalog } = await importModule();
diff --git a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts
index 68a09f8a5c3..0acdfe3a4f6 100644
--- a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts
+++ b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts
@@ -15,6 +15,7 @@ import { resolveCliSpawnPlan } from '../spawn/cliSpawn';
import { listDroidAcpModels } from '../spawn/droidAcpSession';
import { resolveHeteroSpawnCommand } from '../spawn/resolveCliCommand';
import { listTraeAcpModels } from '../spawn/traeAcpSession';
+import { listCodexModels } from './codex';
const execFilePromise = promisify(execFile);
// Large catalogs (including Devin's model variants and metadata) exceed 256 KiB.
@@ -261,8 +262,12 @@ const getErrorRecord = (error: unknown) =>
};
const classifyCatalogError = (error: unknown): HeterogeneousAgentModelCatalogErrorCode => {
+ // The app-server client wraps spawn errors with their original cause.
+ if (error instanceof Error && error.cause) return classifyCatalogError(error.cause);
const { code, killed, signal } = getErrorRecord(error);
if (code === 'ENOENT') return 'cli_not_found';
+ if (code === 'unsupported_client') return 'unsupported_client';
+ if (code === 'unsupported_configuration') return 'unsupported_configuration';
if (code === 'ETIMEDOUT' || killed || signal === 'SIGTERM') return 'timeout';
return 'command_failed';
};
@@ -305,6 +310,17 @@ export const listHeterogeneousAgentModels = async (
};
try {
+ if (params.type === 'codex') {
+ const models = await listCodexModels({
+ args: params.args,
+ commandPath: resolved.command,
+ cwd: params.cwd ?? process.cwd(),
+ env: env as NodeJS.ProcessEnv,
+ timeoutMs: MODEL_CATALOG_TIMEOUT_MS,
+ });
+ return { models, status: 'success', updatedAt };
+ }
+
if (params.type === 'droid') {
const models = await listDroidAcpModels({
args: params.args,
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index b16d75d3818..edc38171550 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -619,6 +619,8 @@ export default {
'heteroAgent.cliModel.defaultDesc': 'Use the default model configured in {{name}}',
'heteroAgent.cliModel.empty': '{{name}} did not report any models.',
'heteroAgent.cliModel.error': 'Could not load models from the CLI.',
+ 'heteroAgent.cliModel.unsupportedConfiguration':
+ 'Model discovery is unavailable for this CLI configuration. You can still use the current model.',
'heteroAgent.cliModel.loading': 'Loading {{name}} models…',
'heteroAgent.cliModel.noMatch': 'No models match your search.',
'heteroAgent.cliModel.reload': 'Reload models',
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index d3437b18766..6ba50361103 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -37,7 +37,12 @@ import {
} from './heteroSelectorCapabilities';
export type HeterogeneousAgentModelCatalogErrorCode =
- 'cli_not_found' | 'command_failed' | 'device_unavailable' | 'timeout' | 'unsupported_client';
+ | 'cli_not_found'
+ | 'command_failed'
+ | 'device_unavailable'
+ | 'timeout'
+ | 'unsupported_client'
+ | 'unsupported_configuration';
/** One model reported by a heterogeneous CLI's device-local model catalog. */
export interface HeterogeneousAgentModel {
@@ -58,6 +63,7 @@ export interface ListHeterogeneousAgentModelsParams {
env?: Record<string, string>;
type:
| 'codebuddy'
+ | 'codex'
| 'cursor'
| 'devin'
| 'droid'
diff --git a/packages/types/src/agent/heteroSelectorCapabilities.test.ts b/packages/types/src/agent/heteroSelectorCapabilities.test.ts
index 790b8dd7734..799ad755982 100644
--- a/packages/types/src/agent/heteroSelectorCapabilities.test.ts
+++ b/packages/types/src/agent/heteroSelectorCapabilities.test.ts
@@ -54,7 +54,7 @@ describe('selector availability', () => {
]);
expect(getHeteroSelectorCapability('opencode')?.effort).toBeUndefined();
expect(getHeteroSelectorCapability('qoder')?.effort).toBeDefined();
- expect(getHeteroSelectorCapability('codex')?.model?.source).toBe('static');
+ expect(getHeteroSelectorCapability('codex')?.model?.source).toBe('catalog');
expect(getHeteroSelectorCapability('codebuddy')?.model?.source).toBe('catalog');
expect(getHeteroSelectorCapability('qoder')?.model?.source).toBe('catalog');
expect(getHeteroSelectorCapability('trae')?.model?.source).toBe('catalog');
diff --git a/packages/types/src/agent/heteroSelectorCapabilities.ts b/packages/types/src/agent/heteroSelectorCapabilities.ts
index 9d8748c8ab7..cb6ecf191bd 100644
--- a/packages/types/src/agent/heteroSelectorCapabilities.ts
+++ b/packages/types/src/agent/heteroSelectorCapabilities.ts
@@ -392,7 +392,7 @@ export const HETERO_SELECTOR_CAPABILITIES = {
model: {
encodings: [MODEL_FLAGS_ENCODING, { key: 'model', kind: 'config' }],
resolve: resolveCodexModel,
- source: 'static',
+ source: 'catalog',
},
speed: {
encodings: [{ key: CODEX_SERVICE_TIER_CONFIG_KEY, kind: 'config' }],
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx b/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx
index c18b53ce347..85096c981f5 100644
--- a/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx
@@ -1,7 +1,7 @@
'use client';
import { getHeterogeneousTypeLabel } from '@lobechat/heterogeneous-agents';
-import type { HeterogeneousAgentModel, ListHeterogeneousAgentModelsParams } from '@lobechat/types';
+import type { ListHeterogeneousAgentModelsParams } from '@lobechat/types';
import { HETEROGENEOUS_AGENT_DEFAULT_SELECTION } from '@lobechat/types';
import { Icon, Tooltip } from '@lobehub/ui';
import {
@@ -36,7 +36,7 @@ import {
RefreshCwIcon,
SearchIcon,
} from 'lucide-react';
-import { memo, useCallback, useMemo, useState } from 'react';
+import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { isDesktop } from '@/const/version';
@@ -51,6 +51,7 @@ import { authSelectors } from '@/store/user/selectors';
import { useMenuContentLifecycle } from '../useMenuContentLifecycle';
import { useModelCatalog } from './useModelCatalog';
+import { useModelCatalogView } from './useModelCatalogView';
const styles = createStaticStyles(({ css }) => ({
check: css`
@@ -150,6 +151,9 @@ const getCatalogErrorKey = (name: string) => {
case 'unsupported_client': {
return 'heteroAgent.cliModel.unsupportedClient';
}
+ case 'unsupported_configuration': {
+ return 'heteroAgent.cliModel.unsupportedConfiguration';
+ }
default: {
return 'heteroAgent.cliModel.error';
}
@@ -213,41 +217,12 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(
type,
});
- const catalogModels = useMemo(() => data?.models ?? [], [data]);
- const selectedIsStale =
- currentModel !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !!data &&
- !catalogModels.some((item) => item.id === currentModel);
- const rows = useMemo(() => {
- const all: HeterogeneousAgentModel[] = selectedIsStale
- ? [
- {
- id: currentModel,
- modelId: currentModel.includes('/')
- ? currentModel.slice(currentModel.indexOf('/') + 1)
- : currentModel,
- providerId: t('heteroAgent.cliModel.saved'),
- },
- ...catalogModels,
- ]
- : catalogModels;
- const query = search.trim().toLowerCase();
- return query
- ? all.filter((item) =>
- [item.id, item.label, item.providerId, item.modelId].some(
- (value) => value && value.toLowerCase().includes(query),
- ),
- )
- : all;
- }, [catalogModels, currentModel, search, selectedIsStale, t]);
- const groups = useMemo(
- () =>
- rows.reduce<Record<string, HeterogeneousAgentModel[]>>((result, item) => {
- (result[item.providerId] ||= []).push(item);
- return result;
- }, {}),
- [rows],
- );
+ const { groups, rows, selectedIsStale } = useModelCatalogView({
+ currentModel,
+ data,
+ savedLabel: t('heteroAgent.cliModel.saved'),
+ search,
+ });
const handleOpenChangeComplete = useCallback(
(nextOpen: boolean) => {
@@ -350,7 +325,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(
</Button>
</div>
)}
- {data && rows.length === 0 && (
+ {data && !error && rows.length === 0 && (
<div className={styles.empty}>
{search.trim()
? t('heteroAgent.cliModel.noMatch')
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/modelOptions.ts b/src/features/ChatInput/ControlBar/HeteroModel/modelOptions.ts
index 8169a409f74..b5e3ce07baa 100644
--- a/src/features/ChatInput/ControlBar/HeteroModel/modelOptions.ts
+++ b/src/features/ChatInput/ControlBar/HeteroModel/modelOptions.ts
@@ -11,17 +11,6 @@ const CLAUDE_CODE_MODEL_OPTIONS: StaticModelOption[] = [
{ label: 'Haiku', value: 'haiku' },
];
-const CODEX_MODEL_OPTIONS: StaticModelOption[] = [
- { label: 'GPT-6 Astra', value: 'gpt-6-astra' },
- { label: 'GPT-5.6 Sol', value: 'gpt-5.6-sol' },
- { label: 'GPT-5.6 Terra', value: 'gpt-5.6-terra' },
- { label: 'GPT-5.6 Luna', value: 'gpt-5.6-luna' },
- { label: 'GPT-5.5', value: 'gpt-5.5' },
- { label: 'GPT-5.4', value: 'gpt-5.4' },
- { label: 'GPT-5.4 Mini', value: 'gpt-5.4-mini' },
- { label: 'GPT-5.3 Codex Spark', value: 'gpt-5.3-codex-spark' },
-];
-
/**
* Display names for the aliases `static` providers accept. These track CLI
* releases rather than the provider contract, so they stay out of
@@ -29,14 +18,22 @@ const CODEX_MODEL_OPTIONS: StaticModelOption[] = [
*/
const STATIC_MODEL_OPTIONS: Record<string, StaticModelOption[]> = {
'claude-code': CLAUDE_CODE_MODEL_OPTIONS,
- 'codex': CODEX_MODEL_OPTIONS,
};
export const getStaticModelOptions = (type: string | undefined): StaticModelOption[] =>
(type && STATIC_MODEL_OPTIONS[type]) || [];
+// Display aliases only; catalog providers never use these as selectable options.
export const MODEL_LABELS: Record<string, string> = {
+ 'gpt-5.3-codex-spark': 'GPT-5.3 Codex Spark',
+ 'gpt-5.4': 'GPT-5.4',
+ 'gpt-5.4-mini': 'GPT-5.4 Mini',
+ 'gpt-5.5': 'GPT-5.5',
'gpt-5.6': 'GPT-5.6',
+ 'gpt-5.6-luna': 'GPT-5.6 Luna',
+ 'gpt-5.6-sol': 'GPT-5.6 Sol',
+ 'gpt-5.6-terra': 'GPT-5.6 Terra',
+ 'gpt-6-astra': 'GPT-6 Astra',
...Object.fromEntries(
Object.values(STATIC_MODEL_OPTIONS)
.flat()
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts b/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts
index 8ace78a1ca6..15abea6b1a8 100644
--- a/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts
+++ b/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts
@@ -52,23 +52,22 @@ describe('resolveSelectorShape', () => {
it('gives a catalog provider with another dimension the full menu', () => {
expect(resolveSelectorShape({ type: 'codebuddy' }, true).kind).toBe('menu');
+ expect(resolveSelectorShape({ type: 'codex' }, true).kind).toBe('menu');
expect(resolveSelectorShape({ type: 'qoder' }, true).kind).toBe('menu');
});
it('gives static providers the full menu', () => {
expect(resolveSelectorShape({ type: 'amp' }, true).kind).toBe('menu');
expect(resolveSelectorShape({ type: 'claude-code' }, true).kind).toBe('menu');
- expect(resolveSelectorShape({ type: 'codex' }, true).kind).toBe('menu');
});
});
describe('dimensions per provider', () => {
- it('offers Astra before older Codex models with five reasoning levels through max', () => {
- const options = viewOf({ type: 'codex' }).dimensions[0].options;
- expect(options[1]).toEqual({ label: 'GPT-6 Astra', value: 'gpt-6-astra' });
+ it('uses the Codex catalog while preserving reasoning levels through max', () => {
+ expect(viewOf({ type: 'codex' }).isCatalogModel).toBe(true);
const view = viewOf({ effort: 'max', model: 'gpt-6-astra', type: 'codex' });
- expect(view.dimensions[1].options.map((option) => option.value)).toEqual([
+ expect(view.dimensions[0].options.map((option) => option.value)).toEqual([
'default',
'low',
'medium',
@@ -106,19 +105,12 @@ describe('dimensions per provider', () => {
]);
});
- it('offers model, reasoning and speed for a fast-capable codex model', () => {
- expect(dimensionKeys({ model: 'gpt-5.6-sol', type: 'codex' })).toEqual([
- 'model',
- 'reasoning',
- 'speed',
- ]);
+ it('keeps reasoning and speed beside the catalog for a fast-capable codex model', () => {
+ expect(dimensionKeys({ model: 'gpt-5.6-sol', type: 'codex' })).toEqual(['reasoning', 'speed']);
});
it('hides speed for codex models without a fast tier', () => {
- expect(dimensionKeys({ model: 'gpt-5.3-codex-spark', type: 'codex' })).toEqual([
- 'model',
- 'reasoning',
- ]);
+ expect(dimensionKeys({ model: 'gpt-5.3-codex-spark', type: 'codex' })).toEqual(['reasoning']);
});
it('offers model and reasoning but never speed for claude-code', () => {
@@ -140,8 +132,8 @@ describe('dimensions per provider', () => {
});
it('narrows codex reasoning levels to what the model serves', () => {
- const solLevels = viewOf({ model: 'gpt-5.6-sol', type: 'codex' }).dimensions[1].options;
- const lunaLevels = viewOf({ model: 'gpt-5.6-luna', type: 'codex' }).dimensions[1].options;
+ const solLevels = viewOf({ model: 'gpt-5.6-sol', type: 'codex' }).dimensions[0].options;
+ const lunaLevels = viewOf({ model: 'gpt-5.6-luna', type: 'codex' }).dimensions[0].options;
expect(solLevels.map((option) => option.value)).toContain('ultra');
expect(lunaLevels.map((option) => option.value)).toContain('max');
@@ -149,9 +141,9 @@ describe('dimensions per provider', () => {
});
it('keeps an off-catalog model pickable so the menu never drops the current value', () => {
- const options = viewOf({ model: 'gpt-4o-legacy', type: 'codex' }).dimensions[0].options;
+ const options = viewOf({ model: 'custom-claude', type: 'claude-code' }).dimensions[0].options;
- expect(options[0]).toEqual({ label: 'gpt-4o-legacy', value: 'gpt-4o-legacy' });
+ expect(options[0]).toEqual({ label: 'custom-claude', value: 'custom-claude' });
});
});
@@ -187,7 +179,7 @@ describe('current value surfaced on each dimension', () => {
it('renames codex low effort to Light', () => {
const view = viewOf({ effort: 'low', model: 'gpt-5.4', type: 'codex' });
- expect(view.dimensions[1].valueLabel).toBe('heteroAgent.modelSelector.reasoning.light');
+ expect(view.dimensions[0].valueLabel).toBe('heteroAgent.modelSelector.reasoning.light');
});
it('keeps the plain Low wording for claude-code', () => {
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalog.test.ts b/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalog.test.ts
index 2b1ddfe5dd7..2a9679bb42a 100644
--- a/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalog.test.ts
+++ b/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalog.test.ts
@@ -23,6 +23,7 @@ describe('useModelCatalog', () => {
it.each([
'codebuddy',
+ 'codex',
'cursor',
'droid',
'grok-build',
@@ -209,4 +210,37 @@ describe('useModelCatalog', () => {
await waitFor(() => expect(result.current.data).toEqual(loadedCatalog));
});
+
+ it('retains the Codex catalog when a refresh fails', async () => {
+ const loadedCatalog = {
+ models: [{ id: 'future-model', modelId: 'future-model', providerId: 'codex' }],
+ status: 'success' as const,
+ updatedAt: 1,
+ };
+ vi.spyOn(heterogeneousAgentCatalogService, 'listModels')
+ .mockResolvedValueOnce(loadedCatalog)
+ .mockResolvedValueOnce({
+ error: { code: 'timeout', message: 'Discovery timed out' },
+ status: 'error',
+ updatedAt: 2,
+ });
+ const { result } = renderHook(
+ () =>
+ useModelCatalog({
+ isDeviceListLoading: false,
+ isPreferenceLoading: false,
+ open: false,
+ provider: { type: 'codex' },
+ targetReady: true,
+ type: 'codex',
+ }),
+ { wrapper: createWrapper() },
+ );
+ await waitFor(() => expect(result.current.data).toEqual(loadedCatalog));
+ await act(async () => {
+ await result.current.mutate().catch(() => {});
+ });
+ expect(result.current.error?.name).toBe('timeout');
+ expect(result.current.data).toEqual(loadedCatalog);
+ });
});
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalogView.test.ts b/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalogView.test.ts
new file mode 100644
index 00000000000..884ab5389f6
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalogView.test.ts
@@ -0,0 +1,78 @@
+import type { HeterogeneousAgentModelCatalogSuccess } from '@lobechat/types';
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { useModelCatalogView } from './useModelCatalogView';
+
+const loaded: HeterogeneousAgentModelCatalogSuccess = {
+ models: [
+ { id: 'future-model', label: 'Future model', modelId: 'future-model', providerId: 'codex' },
+ ],
+ status: 'success',
+ updatedAt: 1,
+};
+const defaults = {
+ currentModel: 'default',
+ savedLabel: 'Saved',
+ search: '',
+};
+
+describe('Model catalog view', () => {
+ it('uses new CLI models without mixing in built-in choices', () => {
+ const { result } = renderHook(() => useModelCatalogView({ ...defaults, data: loaded }));
+ expect(result.current.rows).toEqual(loaded.models);
+ });
+
+ it('keeps only the saved model when no catalog is available', () => {
+ const { result } = renderHook(() =>
+ useModelCatalogView({ ...defaults, currentModel: 'custom-model' }),
+ );
+ expect(result.current.rows.map((model) => model.id)).toEqual(['custom-model']);
+ expect(result.current.groups.Saved[0].id).toBe('custom-model');
+ expect(result.current.selectedIsStale).toBe(false);
+ });
+
+ it('renders the last successful catalog supplied by the shared cache', () => {
+ const { result } = renderHook(() => useModelCatalogView({ ...defaults, data: loaded }));
+ expect(result.current.rows).toEqual(loaded.models);
+ });
+
+ it('keeps off-catalog saved models pickable and marks them as stale only after discovery', () => {
+ const { result, rerender } = renderHook(
+ ({ data }) => useModelCatalogView({ ...defaults, currentModel: 'custom-model', data }),
+ {
+ initialProps: { data: undefined as HeterogeneousAgentModelCatalogSuccess | undefined },
+ },
+ );
+ expect(result.current.rows[0].id).toBe('custom-model');
+ expect(result.current.selectedIsStale).toBe(false);
+ rerender({ data: loaded });
+ expect(result.current.rows.map((model) => model.id)).toEqual(['custom-model', 'future-model']);
+ expect(result.current.selectedIsStale).toBe(true);
+ });
+
+ it('does not replace an intentionally empty catalog with built-in models', () => {
+ const { result } = renderHook(() =>
+ useModelCatalogView({ ...defaults, data: { ...loaded, models: [] } }),
+ );
+ expect(result.current.rows).toEqual([]);
+ });
+
+ it('searches dynamic model names and saved values', () => {
+ const { result } = renderHook(() =>
+ useModelCatalogView({
+ ...defaults,
+ data: loaded,
+ currentModel: 'saved-model',
+ search: 'FUTURE',
+ }),
+ );
+ expect(result.current.rows).toEqual(loaded.models);
+ });
+
+ it('does not invent model choices before a catalog is available', () => {
+ const { result } = renderHook(() => useModelCatalogView(defaults));
+ expect(result.current.rows).toEqual([]);
+ expect(result.current.groups).toEqual({});
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalogView.ts b/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalogView.ts
new file mode 100644
index 00000000000..86997635456
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalogView.ts
@@ -0,0 +1,52 @@
+import type {
+ HeterogeneousAgentModel,
+ HeterogeneousAgentModelCatalogSuccess,
+} from '@lobechat/types';
+import { HETEROGENEOUS_AGENT_DEFAULT_SELECTION } from '@lobechat/types';
+import { useMemo } from 'react';
+
+interface ModelCatalogViewParams {
+ currentModel: string;
+ data?: HeterogeneousAgentModelCatalogSuccess;
+ savedLabel: string;
+ search: string;
+}
+
+/** Keep saved selections and successful catalogs usable through loading and discovery failures. */
+export const useModelCatalogView = ({
+ currentModel,
+ data,
+ savedLabel,
+ search,
+}: ModelCatalogViewParams) =>
+ useMemo(() => {
+ const catalogModels = data?.models ?? [];
+ const selectedIsMissing =
+ currentModel !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !catalogModels.some((item) => item.id === currentModel);
+ const all: HeterogeneousAgentModel[] = selectedIsMissing
+ ? [
+ {
+ id: currentModel,
+ modelId: currentModel.includes('/')
+ ? currentModel.slice(currentModel.indexOf('/') + 1)
+ : currentModel,
+ providerId: savedLabel,
+ },
+ ...catalogModels,
+ ]
+ : catalogModels;
+ const query = search.trim().toLowerCase();
+ const rows = query
+ ? all.filter((item) =>
+ [item.id, item.label, item.providerId, item.modelId].some(
+ (value) => value && value.toLowerCase().includes(query),
+ ),
+ )
+ : all;
+ const groups = rows.reduce<Record<string, HeterogeneousAgentModel[]>>((result, item) => {
+ (result[item.providerId] ||= []).push(item);
+ return result;
+ }, {});
+ return { groups, rows, selectedIsStale: selectedIsMissing && !!data };
+ }, [currentModel, data, savedLabel, search]);
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.test.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.test.ts
index aedec421a59..96a9eb393bd 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.test.ts
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.test.ts
@@ -3,6 +3,19 @@ import { describe, expect, it } from 'vitest';
import { shouldShowHeteroModelSelector } from './shouldShowHeteroModelSelector';
describe('shouldShowHeteroModelSelector', () => {
+ it.each(['auto', 'sandbox', 'none', 'local', 'device'] as const)(
+ 'keeps Codex model and effort controls available on %s even without a catalog target',
+ (executionTarget) => {
+ expect(
+ shouldShowHeteroModelSelector({
+ executionTarget,
+ isDesktopClient: false,
+ providerType: 'codex',
+ }),
+ ).toBe(true);
+ },
+ );
+
it('shows for sandbox-backed web runs', () => {
expect(
shouldShowHeteroModelSelector({
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts
index 62deb2ba3de..bac4a12fbff 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts
@@ -14,6 +14,10 @@ export const shouldShowHeteroModelSelector = ({
isDesktopClient,
providerType,
}: ShouldShowHeteroModelSelectorParams): boolean => {
+ // Codex keeps its saved/built-in model fallback and effort controls even when
+ // discovery has no concrete target (for example auto routing or a sandbox).
+ if (providerType === 'codex') return true;
+
// Catalog providers have no cloud-side model list — their selectors need a
// concrete runtime to discover models from: the desktop itself, or an explicit
// bound device that answers listHeterogeneousAgentModels.