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.

♻️ refactor(hetero-agent): drive the model selector from a capability table (#18214)

Innei371140dae3ec
diff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.ts
index f365796918b..cff3d7c4abb 100644
--- a/packages/types/src/agent/agencyConfig.test.ts
+++ b/packages/types/src/agent/agencyConfig.test.ts
@@ -4,20 +4,21 @@ import type { HeterogeneousProviderConfig } from './agencyConfig';
import {
buildHeteroExecArgs,
buildHeteroSpawnArgs,
- codexModelSupportsFastSpeed,
- codexModelSupportsReasoningEffort,
- getCodexReasoningEffortLevels,
- HETEROGENEOUS_AGENT_DEFAULT_SELECTION,
normalizeHeterogeneousProviderConfig,
pruneWorkingDirByDeviceDeletes,
resolveAgencyConfig,
resolveAgentAgencyConfig,
+} from './agencyConfig';
+import {
+ codexModelSupportsFastSpeed,
+ getCodexReasoningEffortLevels,
+ HETEROGENEOUS_AGENT_DEFAULT_SELECTION,
resolveClaudeCodeModel,
resolveClaudeCodeReasoningEffort,
resolveCodexModel,
resolveCodexReasoningEffort,
resolveCodexSpeedMode,
-} from './agencyConfig';
+} from './heteroSelectorCapabilities';
describe('normalizeHeterogeneousProviderConfig', () => {
it('recovers a legacy adapterType before considering the command', () => {
@@ -461,14 +462,6 @@ describe('codex reasoning effort capabilities', () => {
expect(getCodexReasoningEffortLevels('gpt-5.6-luna')).toEqual(maxLevels);
});
- it('reports model-specific Max and Ultra support', () => {
- expect(codexModelSupportsReasoningEffort('gpt-5.6', 'ultra')).toBe(true);
- expect(codexModelSupportsReasoningEffort('gpt-5.6-sol', 'ultra')).toBe(true);
- expect(codexModelSupportsReasoningEffort('gpt-5.6-terra', 'ultra')).toBe(true);
- expect(codexModelSupportsReasoningEffort('gpt-5.6-luna', 'max')).toBe(true);
- expect(codexModelSupportsReasoningEffort('gpt-5.6-luna', 'ultra')).toBe(false);
- });
-
it('uses conservative common levels for old, unknown, and default models', () => {
expect(getCodexReasoningEffortLevels('gpt-5.5')).toEqual(commonLevels);
expect(getCodexReasoningEffortLevels('gpt-5.4-mini')).toEqual(commonLevels);
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index a68a2072d65..f711099e4a8 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -1,20 +1,31 @@
import type { WorkingDirConfigValue } from '../device';
import type { LobeAgentChatConfig } from './chatConfig';
+import { hasAnyCliFlag, hasCliConfigKey, hasCliFlag } from './heteroCliArgs';
import type { HeterogeneousAgentType, LocalHeterogeneousAgentType } from './heterogeneousAgent';
import {
HETEROGENEOUS_AGENT_CONFIGS,
REMOTE_HETEROGENEOUS_AGENT_CONFIGS,
} from './heterogeneousAgent';
-
-/**
- * Selector value that means "do not override the underlying CLI".
- *
- * When persisted, it intentionally does not translate into CLI flags; the
- * underlying CLI keeps using its own settings, env vars, and account defaults.
- */
-export const HETEROGENEOUS_AGENT_DEFAULT_SELECTION = 'default' as const;
-
-export type HeterogeneousAgentDefaultSelection = typeof HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+import type {
+ ClaudeCodeReasoningEffort,
+ CodexReasoningEffort,
+ CodexSpeedMode,
+ HeteroCliEncoding,
+ HeterogeneousReasoningEffort,
+ HeterogeneousSpeedMode,
+ QoderReasoningEffort,
+} from './heteroSelectorCapabilities';
+import {
+ CODEX_REASONING_EFFORT_CONFIG_KEY,
+ CODEX_SERVICE_TIER_CONFIG_KEY,
+ HETERO_SELECTOR_CAPABILITIES,
+ HETEROGENEOUS_AGENT_DEFAULT_SELECTION,
+ isClaudeCodeReasoningEffort,
+ isCodexFastServiceTier,
+ isCodexReasoningEffort,
+ isQoderReasoningEffort,
+ QODER_REASONING_EFFORT_FLAG,
+} from './heteroSelectorCapabilities';
export type HeterogeneousAgentModelCatalogErrorCode =
'cli_not_found' | 'command_failed' | 'device_unavailable' | 'timeout' | 'unsupported_client';
@@ -56,100 +67,6 @@ export interface HeterogeneousAgentModelCatalogFailure {
export type HeterogeneousAgentModelCatalog =
HeterogeneousAgentModelCatalogFailure | HeterogeneousAgentModelCatalogSuccess;
-/**
- * Claude Code reasoning-effort levels, mirrored 1:1 with the CLI's
- * `--effort <level>` flag.
- */
-export const CLAUDE_CODE_REASONING_EFFORT_LEVELS = [
- 'low',
- 'medium',
- 'high',
- 'xhigh',
- 'max',
-] as const;
-
-export type ClaudeCodeReasoningEffort = (typeof CLAUDE_CODE_REASONING_EFFORT_LEVELS)[number];
-
-export const CLAUDE_CODE_DEFAULT_MODEL = 'sonnet';
-export const CLAUDE_CODE_DEFAULT_REASONING_EFFORT = 'high' satisfies ClaudeCodeReasoningEffort;
-
-/**
- * Codex reasoning-effort levels, mirrored to the CLI config key
- * `model_reasoning_effort`.
- */
-export const CODEX_COMMON_REASONING_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh'] as const;
-
-export const CODEX_REASONING_EFFORT_LEVELS = [
- ...CODEX_COMMON_REASONING_EFFORT_LEVELS,
- 'max',
- 'ultra',
-] as const;
-
-export type CodexReasoningEffort = (typeof CODEX_REASONING_EFFORT_LEVELS)[number];
-
-export const CODEX_DEFAULT_MODEL = 'gpt-5.6-sol';
-export const CODEX_DEFAULT_REASONING_EFFORT = 'medium' satisfies CodexReasoningEffort;
-export const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';
-
-const CODEX_MAX_REASONING_EFFORT_LEVELS = [
- ...CODEX_COMMON_REASONING_EFFORT_LEVELS,
- 'max',
-] as const satisfies readonly CodexReasoningEffort[];
-
-const CODEX_ULTRA_REASONING_MODELS = ['gpt-5.6', 'gpt-5.6-sol', 'gpt-5.6-terra'] as const;
-const CODEX_MAX_REASONING_MODELS = ['gpt-5.6-luna'] as const;
-
-/**
- * Qoder reasoning-effort levels, mirrored 1:1 with the CLI's
- * `--reasoning-effort <level>` flag.
- */
-export const QODER_REASONING_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'] as const;
-
-export type QoderReasoningEffort = (typeof QODER_REASONING_EFFORT_LEVELS)[number];
-
-export const QODER_REASONING_EFFORT_FLAG = '--reasoning-effort';
-
-export type HeterogeneousReasoningEffort =
- | ClaudeCodeReasoningEffort
- | CodexReasoningEffort
- | QoderReasoningEffort
- | HeterogeneousAgentDefaultSelection;
-
-/**
- * Codex speed modes, mirrored to the CLI config key `service_tier`.
- *
- * `fast` maps to the Fast service tier (request value `priority`): ~1.5x
- * faster inference at a higher credit-consumption rate. Requires ChatGPT
- * sign-in; the Codex CLI silently omits the tier for unsupported models, so
- * passing it is always safe.
- */
-export const CODEX_SPEED_MODES = ['fast'] as const;
-
-export type CodexSpeedMode = (typeof CODEX_SPEED_MODES)[number];
-
-export type HeterogeneousSpeedMode = CodexSpeedMode | HeterogeneousAgentDefaultSelection;
-
-export const CODEX_SERVICE_TIER_CONFIG_KEY = 'service_tier';
-
-/**
- * Codex models whose catalog exposes the Fast (`priority`) service tier.
- * Sourced from the model catalog embedded in codex-cli.
- */
-export const CODEX_FAST_SPEED_MODELS = [
- 'gpt-5.6',
- 'gpt-5.6-sol',
- 'gpt-5.6-terra',
- 'gpt-5.6-luna',
- 'gpt-5.5',
- 'gpt-5.4',
-] as const;
-
-/**
- * `service_tier` values the Codex CLI resolves to the Fast tier
- * (`ServiceTier::from_request_value` accepts both spellings).
- */
-const CODEX_FAST_SERVICE_TIER_VALUES = ['fast', 'priority'] as const;
-
/**
* Heterogeneous agent provider configuration.
* When set, the assistant delegates execution to an external agent runtime
@@ -298,146 +215,17 @@ interface QoderSelectionSource {
model?: string | null;
}
-const CODEX_CONFIG_FLAGS = ['-c', '--config'] as const;
-const CODEX_MODEL_FLAGS = ['-m', '--model'] as const;
const HETERO_EXEC_AGENT_ARG_FLAG = '--agent-arg';
-const OPENCODE_MODEL_FLAGS = ['-m', '--model'] as const;
-const PI_MODEL_FLAGS = ['--model'] as const;
-const QODER_MODEL_FLAGS = ['-m', '--model'] as const;
-
-const hasCliFlag = (args: string[], flag: string): boolean =>
- args.some((arg) => arg === flag || arg.startsWith(`${flag}=`));
-
-const hasAnyCliFlag = (args: string[], flags: readonly string[]): boolean =>
- flags.some((flag) => hasCliFlag(args, flag));
-
-const getCliFlagValue = (args: string[] | undefined, flag: string): string | undefined => {
- if (!args) return undefined;
-
- for (let index = 0; index < args.length; index += 1) {
- const arg = args[index];
- if (arg === flag) {
- const next = args[index + 1]?.trim();
- if (next && !next.startsWith('-')) return next;
- }
-
- const prefix = `${flag}=`;
- if (arg.startsWith(prefix)) {
- const value = arg.slice(prefix.length).trim();
- if (value) return value;
- }
- }
-
- return undefined;
-};
-
-const getAnyCliFlagValue = (
- args: string[] | undefined,
- flags: readonly string[],
-): string | undefined => {
- for (const flag of flags) {
- const value = getCliFlagValue(args, flag);
- if (value) return value;
- }
-};
-
-const unquoteCliConfigValue = (value: string): string => {
- const trimmed = value.trim();
- const quote = trimmed[0];
- if ((quote === '"' || quote === "'") && trimmed.at(-1) === quote) {
- return trimmed.slice(1, -1);
- }
-
- return trimmed;
-};
-
-const escapeRegExp = (value: string): string => value.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');
-
-const parseCliConfigAssignment = (assignment: string, key: string): string | undefined => {
- const match = assignment.match(new RegExp(`^\\s*${escapeRegExp(key)}\\s*=\\s*(.+?)\\s*$`));
- if (!match?.[1]) return undefined;
-
- const value = unquoteCliConfigValue(match[1]);
- return value || undefined;
-};
+const modelFlagsOf = (type: 'codex' | 'opencode' | 'pi' | 'qoder'): readonly string[] =>
+ HETERO_SELECTOR_CAPABILITIES[type].model.encodings.flatMap((encoding: HeteroCliEncoding) =>
+ encoding.kind === 'flag' ? encoding.flags : [],
+ );
-const getCliConfigValue = (args: string[] | undefined, key: string): string | undefined => {
- if (!args) return undefined;
-
- for (let index = 0; index < args.length; index += 1) {
- const arg = args[index];
-
- if (CODEX_CONFIG_FLAGS.includes(arg as (typeof CODEX_CONFIG_FLAGS)[number])) {
- const next = args[index + 1];
- if (next) {
- const value = parseCliConfigAssignment(next, key);
- if (value) return value;
- index += 1;
- }
- continue;
- }
-
- const configFlag = CODEX_CONFIG_FLAGS.find((flag) => arg.startsWith(`${flag}=`));
- if (configFlag) {
- const value = parseCliConfigAssignment(arg.slice(configFlag.length + 1), key);
- if (value) return value;
- }
- }
-};
-
-const hasCliConfigKey = (args: string[], key: string): boolean => !!getCliConfigValue(args, key);
-
-const isClaudeCodeReasoningEffort = (
- value: string | undefined,
-): value is ClaudeCodeReasoningEffort =>
- !!value && CLAUDE_CODE_REASONING_EFFORT_LEVELS.includes(value as ClaudeCodeReasoningEffort);
-
-const isCodexReasoningEffort = (value: string | undefined): value is CodexReasoningEffort =>
- !!value && CODEX_REASONING_EFFORT_LEVELS.includes(value as CodexReasoningEffort);
-
-const isQoderReasoningEffort = (value: string | undefined): value is QoderReasoningEffort =>
- !!value && QODER_REASONING_EFFORT_LEVELS.includes(value as QoderReasoningEffort);
-
-/**
- * Reasoning-effort levels exposed by a Codex model. Unknown and default model
- * selections use the conservative common set because their actual capability
- * cannot be known until the CLI resolves the model.
- */
-export const getCodexReasoningEffortLevels = (model: string): readonly CodexReasoningEffort[] => {
- if (
- CODEX_ULTRA_REASONING_MODELS.includes(model as (typeof CODEX_ULTRA_REASONING_MODELS)[number])
- ) {
- return CODEX_REASONING_EFFORT_LEVELS;
- }
-
- if (CODEX_MAX_REASONING_MODELS.includes(model as (typeof CODEX_MAX_REASONING_MODELS)[number])) {
- return CODEX_MAX_REASONING_EFFORT_LEVELS;
- }
-
- return CODEX_COMMON_REASONING_EFFORT_LEVELS;
-};
-
-export const codexModelSupportsReasoningEffort = (
- model: string,
- effort: CodexReasoningEffort,
-): boolean => getCodexReasoningEffortLevels(model).includes(effort);
-
-export const resolveClaudeCodeModel = (
- source: ClaudeCodeSelectionSource | null | undefined,
-): string => {
- const model = (getCliFlagValue(source?.args, '--model') ?? source?.model)?.trim();
- return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION
- ? model
- : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
-};
-
-export const resolveClaudeCodeReasoningEffort = (
- source: ClaudeCodeSelectionSource | null | undefined,
-): ClaudeCodeReasoningEffort | HeterogeneousAgentDefaultSelection => {
- const effort = (getCliFlagValue(source?.args, '--effort') ?? source?.effort)?.trim();
- return isClaudeCodeReasoningEffort(effort) ? effort : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
-};
+const CODEX_MODEL_FLAGS = modelFlagsOf('codex');
+const OPENCODE_MODEL_FLAGS = modelFlagsOf('opencode');
+const PI_MODEL_FLAGS = modelFlagsOf('pi');
+const QODER_MODEL_FLAGS = modelFlagsOf('qoder');
const getExplicitClaudeCodeModel = (
source: ClaudeCodeSelectionSource | null | undefined,
@@ -453,28 +241,6 @@ const getExplicitClaudeCodeReasoningEffort = (
return isClaudeCodeReasoningEffort(effort) ? effort : undefined;
};
-export const resolveCodexModel = (source: CodexSelectionSource | null | undefined): string => {
- const model = (
- getAnyCliFlagValue(source?.args, CODEX_MODEL_FLAGS) ??
- getCliConfigValue(source?.args, 'model') ??
- source?.model
- )?.trim();
-
- return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION
- ? model
- : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
-};
-
-export const resolveCodexReasoningEffort = (
- source: CodexSelectionSource | null | undefined,
-): CodexReasoningEffort | HeterogeneousAgentDefaultSelection => {
- const effort = (
- getCliConfigValue(source?.args, CODEX_REASONING_EFFORT_CONFIG_KEY) ?? source?.effort
- )?.trim();
-
- return isCodexReasoningEffort(effort) ? effort : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
-};
-
const getExplicitCodexModel = (
source: CodexSelectionSource | null | undefined,
): string | undefined => {
@@ -489,15 +255,6 @@ const getExplicitCodexReasoningEffort = (
return isCodexReasoningEffort(effort) ? effort : undefined;
};
-export const resolveQoderReasoningEffort = (
- source: QoderSelectionSource | null | undefined,
-): QoderReasoningEffort | HeterogeneousAgentDefaultSelection => {
- const effort = (
- getCliFlagValue(source?.args, QODER_REASONING_EFFORT_FLAG) ?? source?.effort
- )?.trim();
- return isQoderReasoningEffort(effort) ? effort : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
-};
-
const getExplicitQoderReasoningEffort = (
source: QoderSelectionSource | null | undefined,
): QoderReasoningEffort | undefined => {
@@ -505,20 +262,6 @@ const getExplicitQoderReasoningEffort = (
return isQoderReasoningEffort(effort) ? effort : undefined;
};
-const isCodexFastServiceTier = (value: string | undefined): boolean =>
- !!value &&
- CODEX_FAST_SERVICE_TIER_VALUES.includes(value as (typeof CODEX_FAST_SERVICE_TIER_VALUES)[number]);
-
-export const resolveCodexSpeedMode = (
- source: CodexSelectionSource | null | undefined,
-): HeterogeneousSpeedMode => {
- const tier = (
- getCliConfigValue(source?.args, CODEX_SERVICE_TIER_CONFIG_KEY) ?? source?.speed
- )?.trim();
-
- return isCodexFastServiceTier(tier) ? 'fast' : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
-};
-
const getExplicitCodexSpeedMode = (
source: CodexSelectionSource | null | undefined,
): CodexSpeedMode | undefined => {
@@ -526,15 +269,6 @@ const getExplicitCodexSpeedMode = (
return isCodexFastServiceTier(speed) ? 'fast' : undefined;
};
-/**
- * Whether the Fast speed toggle applies to a selector model value. `default`
- * counts as supported so the CLI remains free to resolve its own model; an
- * unsupported resolved model simply ignores the tier.
- */
-export const codexModelSupportsFastSpeed = (model: string): boolean =>
- model === HETEROGENEOUS_AGENT_DEFAULT_SELECTION ||
- CODEX_FAST_SPEED_MODELS.includes(model as (typeof CODEX_FAST_SPEED_MODELS)[number]);
-
/**
* Resolve the effective native CLI args for a heterogeneous spawn.
*
diff --git a/packages/types/src/agent/heteroCliArgs.ts b/packages/types/src/agent/heteroCliArgs.ts
new file mode 100644
index 00000000000..827debf74ae
--- /dev/null
+++ b/packages/types/src/agent/heteroCliArgs.ts
@@ -0,0 +1,156 @@
+/**
+ * CLI argument syntax primitives shared by the heterogeneous-agent selector.
+ *
+ * Every helper here is provider-agnostic: it knows how `--flag value`,
+ * `--flag=value` and `-c key="value"` are spelled, never which provider spells
+ * them. Provider knowledge lives in `heteroSelectorCapabilities`.
+ */
+
+const CLI_CONFIG_FLAGS = ['-c', '--config'] as const;
+
+export const hasCliFlag = (args: string[], flag: string): boolean =>
+ args.some((arg) => arg === flag || arg.startsWith(`${flag}=`));
+
+export const hasAnyCliFlag = (args: string[], flags: readonly string[]): boolean =>
+ flags.some((flag) => hasCliFlag(args, flag));
+
+export const getCliFlagValue = (args: string[] | undefined, flag: string): string | undefined => {
+ if (!args) return undefined;
+
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+ if (arg === flag) {
+ const next = args[index + 1]?.trim();
+ if (next && !next.startsWith('-')) return next;
+ }
+
+ const prefix = `${flag}=`;
+ if (arg.startsWith(prefix)) {
+ const value = arg.slice(prefix.length).trim();
+ if (value) return value;
+ }
+ }
+
+ return undefined;
+};
+
+export const getAnyCliFlagValue = (
+ args: string[] | undefined,
+ flags: readonly string[],
+): string | undefined => {
+ for (const flag of flags) {
+ const value = getCliFlagValue(args, flag);
+ if (value) return value;
+ }
+};
+
+const unquoteCliConfigValue = (value: string): string => {
+ const trimmed = value.trim();
+ const quote = trimmed[0];
+
+ if ((quote === '"' || quote === "'") && trimmed.at(-1) === quote) {
+ return trimmed.slice(1, -1);
+ }
+
+ return trimmed;
+};
+
+const escapeRegExp = (value: string): string => value.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+const parseCliConfigAssignment = (assignment: string, key: string): string | undefined => {
+ const match = assignment.match(new RegExp(`^\\s*${escapeRegExp(key)}\\s*=\\s*(.+?)\\s*$`));
+ if (!match?.[1]) return undefined;
+
+ const value = unquoteCliConfigValue(match[1]);
+ return value || undefined;
+};
+
+const matchesCliConfigKey = (assignment: string, key: string): boolean =>
+ new RegExp(`^\\s*${escapeRegExp(key)}\\s*=`).test(assignment);
+
+const findConfigFlagPrefix = (arg: string): (typeof CLI_CONFIG_FLAGS)[number] | undefined =>
+ CLI_CONFIG_FLAGS.find((flag) => arg.startsWith(`${flag}=`));
+
+const isConfigFlag = (arg: string): boolean =>
+ CLI_CONFIG_FLAGS.includes(arg as (typeof CLI_CONFIG_FLAGS)[number]);
+
+export const getCliConfigValue = (args: string[] | undefined, key: string): string | undefined => {
+ if (!args) return undefined;
+
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+
+ if (isConfigFlag(arg)) {
+ const next = args[index + 1];
+ if (next) {
+ const value = parseCliConfigAssignment(next, key);
+ if (value) return value;
+ index += 1;
+ }
+ continue;
+ }
+
+ const configFlag = findConfigFlagPrefix(arg);
+ if (configFlag) {
+ const value = parseCliConfigAssignment(arg.slice(configFlag.length + 1), key);
+ if (value) return value;
+ }
+ }
+};
+
+export const hasCliConfigKey = (args: string[], key: string): boolean =>
+ !!getCliConfigValue(args, key);
+
+export const stripCliFlags = (
+ args: string[] | undefined,
+ flags: readonly string[],
+): string[] | undefined => {
+ if (!args) return undefined;
+
+ const next: string[] = [];
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+
+ if (flags.includes(arg)) {
+ const value = args[index + 1];
+ if (value && !value.startsWith('-')) index += 1;
+ continue;
+ }
+
+ if (flags.some((flag) => arg.startsWith(`${flag}=`))) continue;
+
+ next.push(arg);
+ }
+
+ return next;
+};
+
+export const stripCliConfigKey = (
+ args: string[] | undefined,
+ key: string,
+): string[] | undefined => {
+ if (!args) return undefined;
+
+ const next: string[] = [];
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+
+ if (isConfigFlag(arg)) {
+ const value = args[index + 1];
+ if (value && matchesCliConfigKey(value, key)) {
+ index += 1;
+ continue;
+ }
+
+ next.push(arg);
+ continue;
+ }
+
+ const configFlag = findConfigFlagPrefix(arg);
+ if (configFlag && matchesCliConfigKey(arg.slice(configFlag.length + 1), key)) continue;
+
+ next.push(arg);
+ }
+
+ return next;
+};
diff --git a/packages/types/src/agent/heteroSelectorCapabilities.test.ts b/packages/types/src/agent/heteroSelectorCapabilities.test.ts
new file mode 100644
index 00000000000..7efc705343b
--- /dev/null
+++ b/packages/types/src/agent/heteroSelectorCapabilities.test.ts
@@ -0,0 +1,171 @@
+import { describe, expect, it } from 'vitest';
+
+import type { HeterogeneousProviderConfig } from './agencyConfig';
+import { buildHeteroSpawnArgs } from './agencyConfig';
+import {
+ applyHeteroSelection,
+ getHeteroSelectorCapability,
+ HETEROGENEOUS_AGENT_DEFAULT_SELECTION,
+ isHeteroSelectorAvailable,
+} from './heteroSelectorCapabilities';
+
+describe('selector availability', () => {
+ it('derives the selectable provider set from the model dimension', () => {
+ expect(isHeteroSelectorAvailable('claude-code')).toBe(true);
+ expect(isHeteroSelectorAvailable('codex')).toBe(true);
+ expect(isHeteroSelectorAvailable('opencode')).toBe(true);
+ expect(isHeteroSelectorAvailable('pi')).toBe(true);
+ expect(isHeteroSelectorAvailable('qoder')).toBe(true);
+
+ expect(isHeteroSelectorAvailable('amp')).toBe(false);
+ expect(isHeteroSelectorAvailable('openclaw')).toBe(false);
+ expect(isHeteroSelectorAvailable(undefined)).toBe(false);
+ });
+
+ it('exposes the dimensions each provider actually supports', () => {
+ expect(getHeteroSelectorCapability('claude-code')?.speed).toBeUndefined();
+ expect(getHeteroSelectorCapability('codex')?.speed).toBeDefined();
+ expect(getHeteroSelectorCapability('opencode')?.effort).toBeUndefined();
+ expect(getHeteroSelectorCapability('qoder')?.effort).toBeDefined();
+ expect(getHeteroSelectorCapability('codex')?.model?.source).toBe('static');
+ expect(getHeteroSelectorCapability('qoder')?.model?.source).toBe('catalog');
+ });
+
+ it('reports codex effort levels per model', () => {
+ const levels = getHeteroSelectorCapability('codex')?.effort?.levels;
+
+ expect(levels?.('gpt-5.6-sol')).toContain('ultra');
+ expect(levels?.('gpt-5.6-luna')).toContain('max');
+ expect(levels?.('gpt-5.6-luna')).not.toContain('ultra');
+ expect(levels?.('gpt-5.4')).not.toContain('max');
+ });
+});
+
+describe('applyHeteroSelection', () => {
+ it('passes the selection through untouched for providers with no selector', () => {
+ expect(applyHeteroSelection({ args: ['--model', 'x'], type: 'amp' }, { model: 'y' })).toEqual({
+ model: 'y',
+ });
+ });
+
+ it('leaves args alone when the provider is unknown', () => {
+ expect(applyHeteroSelection(undefined, { model: 'y' })).toEqual({ model: 'y' });
+ });
+
+ it('clears the claude-code model flag without touching unrelated args', () => {
+ expect(
+ applyHeteroSelection(
+ { args: ['--verbose', '--model', 'sonnet', '--foo=bar'], type: 'claude-code' },
+ { model: 'opus' },
+ ),
+ ).toEqual({ args: ['--verbose', '--foo=bar'], model: 'opus' });
+ });
+
+ it('clears the claude-code effort flag in its joined spelling', () => {
+ expect(
+ applyHeteroSelection(
+ { args: ['--effort=high', '-p'], type: 'claude-code' },
+ { effort: 'low' },
+ ),
+ ).toEqual({ args: ['-p'], effort: 'low' });
+ });
+
+ it('clears both codex model spellings at once', () => {
+ expect(
+ applyHeteroSelection(
+ { args: ['-m', 'gpt-5.5', '-c', 'model="gpt-5.4"', '--sandbox', 'danger'], type: 'codex' },
+ { model: 'gpt-5.6-sol' },
+ ),
+ ).toEqual({ args: ['--sandbox', 'danger'], model: 'gpt-5.6-sol' });
+ });
+
+ it('clears the codex effort config key but keeps other config overrides', () => {
+ expect(
+ applyHeteroSelection(
+ {
+ args: ['-c', 'model_reasoning_effort="high"', '-c', 'sandbox_mode="read-only"'],
+ type: 'codex',
+ },
+ { effort: 'low' },
+ ),
+ ).toEqual({ args: ['-c', 'sandbox_mode="read-only"'], effort: 'low' });
+ });
+
+ it('clears the codex service tier in the joined --config spelling', () => {
+ expect(
+ applyHeteroSelection(
+ { args: ['--config=service_tier="priority"', '--full-auto'], type: 'codex' },
+ { speed: HETEROGENEOUS_AGENT_DEFAULT_SELECTION },
+ ),
+ ).toEqual({ args: ['--full-auto'], speed: HETEROGENEOUS_AGENT_DEFAULT_SELECTION });
+ });
+
+ it('clears every dimension named in a combined patch', () => {
+ expect(
+ applyHeteroSelection(
+ {
+ args: [
+ '--model',
+ 'gpt-5.5',
+ '-c',
+ 'model_reasoning_effort="max"',
+ '-c',
+ 'service_tier="fast"',
+ ],
+ type: 'codex',
+ },
+ { effort: HETEROGENEOUS_AGENT_DEFAULT_SELECTION, model: 'gpt-5.4', speed: 'default' },
+ ),
+ ).toEqual({
+ args: [],
+ effort: HETEROGENEOUS_AGENT_DEFAULT_SELECTION,
+ model: 'gpt-5.4',
+ speed: 'default',
+ });
+ });
+
+ it('clears the qoder reasoning-effort flag', () => {
+ expect(
+ applyHeteroSelection(
+ { args: ['--reasoning-effort', 'high', '-p'], type: 'qoder' },
+ { effort: 'low' },
+ ),
+ ).toEqual({ args: ['-p'], effort: 'low' });
+ });
+
+ it('clears pi provider alongside the model so a stale half cannot survive', () => {
+ expect(
+ applyHeteroSelection(
+ { args: ['--provider', 'anthropic', '--model', 'old'], type: 'pi' },
+ { model: 'openai/gpt-5' },
+ ),
+ ).toEqual({ args: [], model: 'openai/gpt-5' });
+ });
+
+ it('ignores dimensions the provider does not expose', () => {
+ expect(
+ applyHeteroSelection({ args: ['--model', 'x'], type: 'qoder' }, { speed: 'fast' }),
+ ).toEqual({ speed: 'fast' });
+ });
+
+ it('returns undefined args when the provider had none', () => {
+ expect(applyHeteroSelection({ type: 'codex' }, { model: 'gpt-5.4' })).toEqual({
+ args: undefined,
+ model: 'gpt-5.4',
+ });
+ });
+
+ it('makes the selection observable to the spawn args builder', () => {
+ const stale: HeterogeneousProviderConfig = {
+ args: ['--model', 'sonnet'],
+ model: 'sonnet',
+ type: 'claude-code',
+ };
+
+ expect(buildHeteroSpawnArgs({ ...stale, model: 'opus' })).toEqual(['--model', 'sonnet']);
+
+ const patched = { ...stale, ...applyHeteroSelection(stale, { model: 'opus' }) };
+
+ expect(buildHeteroSpawnArgs(patched)).toEqual(['--model', 'opus']);
+ });
+});
diff --git a/packages/types/src/agent/heteroSelectorCapabilities.ts b/packages/types/src/agent/heteroSelectorCapabilities.ts
new file mode 100644
index 00000000000..96d230c26de
--- /dev/null
+++ b/packages/types/src/agent/heteroSelectorCapabilities.ts
@@ -0,0 +1,403 @@
+import {
+ getAnyCliFlagValue,
+ getCliConfigValue,
+ getCliFlagValue,
+ stripCliConfigKey,
+ stripCliFlags,
+} from './heteroCliArgs';
+import type { LocalHeterogeneousAgentType } from './heterogeneousAgent';
+
+/**
+ * Selector value that means "do not override the underlying CLI".
+ *
+ * When persisted, it intentionally does not translate into CLI flags; the
+ * underlying CLI keeps using its own settings, env vars, and account defaults.
+ */
+export const HETEROGENEOUS_AGENT_DEFAULT_SELECTION = 'default' as const;
+
+export type HeterogeneousAgentDefaultSelection = typeof HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+
+/**
+ * Claude Code reasoning-effort levels, mirrored 1:1 with the CLI's
+ * `--effort <level>` flag.
+ */
+const CLAUDE_CODE_REASONING_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'] as const;
+
+export type ClaudeCodeReasoningEffort = (typeof CLAUDE_CODE_REASONING_EFFORT_LEVELS)[number];
+
+/**
+ * Codex reasoning-effort levels, mirrored to the CLI config key
+ * `model_reasoning_effort`.
+ */
+const CODEX_COMMON_REASONING_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh'] as const;
+
+const CODEX_REASONING_EFFORT_LEVELS = [
+ ...CODEX_COMMON_REASONING_EFFORT_LEVELS,
+ 'max',
+ 'ultra',
+] as const;
+
+export type CodexReasoningEffort = (typeof CODEX_REASONING_EFFORT_LEVELS)[number];
+
+export const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';
+
+const CODEX_MAX_REASONING_EFFORT_LEVELS = [
+ ...CODEX_COMMON_REASONING_EFFORT_LEVELS,
+ 'max',
+] as const satisfies readonly CodexReasoningEffort[];
+
+const CODEX_ULTRA_REASONING_MODELS = ['gpt-5.6', 'gpt-5.6-sol', 'gpt-5.6-terra'] as const;
+const CODEX_MAX_REASONING_MODELS = ['gpt-5.6-luna'] as const;
+
+/**
+ * Qoder reasoning-effort levels, mirrored 1:1 with the CLI's
+ * `--reasoning-effort <level>` flag.
+ */
+const QODER_REASONING_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'] as const;
+
+export type QoderReasoningEffort = (typeof QODER_REASONING_EFFORT_LEVELS)[number];
+
+export const QODER_REASONING_EFFORT_FLAG = '--reasoning-effort';
+
+export type HeterogeneousReasoningEffortLevel =
+ ClaudeCodeReasoningEffort | CodexReasoningEffort | QoderReasoningEffort;
+
+export type HeterogeneousReasoningEffort =
+ HeterogeneousReasoningEffortLevel | HeterogeneousAgentDefaultSelection;
+
+/**
+ * Codex speed modes, mirrored to the CLI config key `service_tier`.
+ *
+ * `fast` maps to the Fast service tier (request value `priority`): ~1.5x
+ * faster inference at a higher credit-consumption rate. Requires ChatGPT
+ * sign-in; the Codex CLI silently omits the tier for unsupported models, so
+ * passing it is always safe.
+ */
+const CODEX_SPEED_MODES = ['fast'] as const;
+
+export type CodexSpeedMode = (typeof CODEX_SPEED_MODES)[number];
+
+export type HeterogeneousSpeedMode = CodexSpeedMode | HeterogeneousAgentDefaultSelection;
+
+export const CODEX_SERVICE_TIER_CONFIG_KEY = 'service_tier';
+
+/**
+ * Codex models whose catalog exposes the Fast (`priority`) service tier.
+ * Sourced from the model catalog embedded in codex-cli.
+ */
+const CODEX_FAST_SPEED_MODELS = [
+ 'gpt-5.6',
+ 'gpt-5.6-sol',
+ 'gpt-5.6-terra',
+ 'gpt-5.6-luna',
+ 'gpt-5.5',
+ 'gpt-5.4',
+] as const;
+
+/**
+ * `service_tier` values the Codex CLI resolves to the Fast tier
+ * (`ServiceTier::from_request_value` accepts both spellings).
+ */
+const CODEX_FAST_SERVICE_TIER_VALUES = ['fast', 'priority'] as const;
+
+export const isClaudeCodeReasoningEffort = (
+ value: string | undefined,
+): value is ClaudeCodeReasoningEffort =>
+ !!value && CLAUDE_CODE_REASONING_EFFORT_LEVELS.includes(value as ClaudeCodeReasoningEffort);
+
+export const isCodexReasoningEffort = (value: string | undefined): value is CodexReasoningEffort =>
+ !!value && CODEX_REASONING_EFFORT_LEVELS.includes(value as CodexReasoningEffort);
+
+export const isQoderReasoningEffort = (value: string | undefined): value is QoderReasoningEffort =>
+ !!value && QODER_REASONING_EFFORT_LEVELS.includes(value as QoderReasoningEffort);
+
+export const isCodexFastServiceTier = (value: string | undefined): boolean =>
+ !!value &&
+ CODEX_FAST_SERVICE_TIER_VALUES.includes(value as (typeof CODEX_FAST_SERVICE_TIER_VALUES)[number]);
+
+/**
+ * Reasoning-effort levels exposed by a Codex model. Unknown and default model
+ * selections use the conservative common set because their actual capability
+ * cannot be known until the CLI resolves the model.
+ */
+export const getCodexReasoningEffortLevels = (model: string): readonly CodexReasoningEffort[] => {
+ if (
+ CODEX_ULTRA_REASONING_MODELS.includes(model as (typeof CODEX_ULTRA_REASONING_MODELS)[number])
+ ) {
+ return CODEX_REASONING_EFFORT_LEVELS;
+ }
+
+ if (CODEX_MAX_REASONING_MODELS.includes(model as (typeof CODEX_MAX_REASONING_MODELS)[number])) {
+ return CODEX_MAX_REASONING_EFFORT_LEVELS;
+ }
+
+ return CODEX_COMMON_REASONING_EFFORT_LEVELS;
+};
+
+/**
+ * Whether the Fast speed toggle applies to a selector model value. `default`
+ * counts as supported so the CLI remains free to resolve its own model; an
+ * unsupported resolved model simply ignores the tier.
+ */
+export const codexModelSupportsFastSpeed = (model: string): boolean =>
+ model === HETEROGENEOUS_AGENT_DEFAULT_SELECTION ||
+ CODEX_FAST_SPEED_MODELS.includes(model as (typeof CODEX_FAST_SPEED_MODELS)[number]);
+
+export interface HeteroSelectionSource {
+ args?: string[];
+ effort?: string | null;
+ model?: string | null;
+ speed?: string | null;
+}
+
+const CODEX_MODEL_FLAGS = ['-m', '--model'] as const;
+
+export const resolveClaudeCodeModel = (
+ source: HeteroSelectionSource | null | undefined,
+): string => {
+ const model = (getCliFlagValue(source?.args, '--model') ?? source?.model)?.trim();
+ return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION
+ ? model
+ : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+};
+
+export const resolveClaudeCodeReasoningEffort = (
+ source: HeteroSelectionSource | null | undefined,
+): ClaudeCodeReasoningEffort | HeterogeneousAgentDefaultSelection => {
+ const effort = (getCliFlagValue(source?.args, '--effort') ?? source?.effort)?.trim();
+ return isClaudeCodeReasoningEffort(effort) ? effort : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+};
+
+export const resolveCodexModel = (source: HeteroSelectionSource | null | undefined): string => {
+ const model = (
+ getAnyCliFlagValue(source?.args, CODEX_MODEL_FLAGS) ??
+ getCliConfigValue(source?.args, 'model') ??
+ source?.model
+ )?.trim();
+
+ return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION
+ ? model
+ : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+};
+
+export const resolveCodexReasoningEffort = (
+ source: HeteroSelectionSource | null | undefined,
+): CodexReasoningEffort | HeterogeneousAgentDefaultSelection => {
+ const effort = (
+ getCliConfigValue(source?.args, CODEX_REASONING_EFFORT_CONFIG_KEY) ?? source?.effort
+ )?.trim();
+
+ return isCodexReasoningEffort(effort) ? effort : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+};
+
+export const resolveCodexSpeedMode = (
+ source: HeteroSelectionSource | null | undefined,
+): HeterogeneousSpeedMode => {
+ const tier = (
+ getCliConfigValue(source?.args, CODEX_SERVICE_TIER_CONFIG_KEY) ?? source?.speed
+ )?.trim();
+
+ return isCodexFastServiceTier(tier) ? 'fast' : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+};
+
+const resolveQoderReasoningEffort = (
+ source: HeteroSelectionSource | null | undefined,
+): QoderReasoningEffort | HeterogeneousAgentDefaultSelection => {
+ const effort = (
+ getCliFlagValue(source?.args, QODER_REASONING_EFFORT_FLAG) ?? source?.effort
+ )?.trim();
+ return isQoderReasoningEffort(effort) ? effort : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+};
+
+/**
+ * Catalog providers persist the picked model id verbatim and never read it back
+ * out of `args`. Widening them to the arg-first order that `buildHeteroSpawnArgs`
+ * uses would change what the selector displays for hand-authored configs, so the
+ * asymmetry is deliberate rather than an oversight.
+ */
+const resolvePersistedModel = (source: HeteroSelectionSource | null | undefined): string => {
+ const model = source?.model?.trim();
+ return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION
+ ? model
+ : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+};
+
+export type HeteroCliEncoding =
+ { flags: readonly string[]; kind: 'flag' } | { key: string; kind: 'config' };
+
+export interface HeteroSelectorModelCapability {
+ encodings: readonly HeteroCliEncoding[];
+ /**
+ * Flags cleared together with the model but never read back as its value.
+ * Pi spells the provider half of a fully-qualified model id separately, so a
+ * stale `--provider` would contradict a freshly picked model.
+ */
+ extraStripFlags?: readonly string[];
+ resolve: (source: HeteroSelectionSource | null | undefined) => string;
+ /**
+ * `catalog` providers enumerate models through a device-local CLI call;
+ * `static` providers accept a small fixed set of aliases and must keep
+ * working with no device attached.
+ */
+ source: 'catalog' | 'static';
+}
+
+export interface HeteroSelectorEffortCapability {
+ encodings: readonly HeteroCliEncoding[];
+ levels: (model: string) => readonly HeterogeneousReasoningEffortLevel[];
+ resolve: (source: HeteroSelectionSource | null | undefined) => HeterogeneousReasoningEffort;
+}
+
+export interface HeteroSelectorSpeedCapability {
+ encodings: readonly HeteroCliEncoding[];
+ resolve: (source: HeteroSelectionSource | null | undefined) => HeterogeneousSpeedMode;
+ supported: (model: string) => boolean;
+}
+
+export interface HeteroSelectorCapability {
+ effort?: HeteroSelectorEffortCapability;
+ model?: HeteroSelectorModelCapability;
+ speed?: HeteroSelectorSpeedCapability;
+}
+
+const MODEL_FLAGS_ENCODING = { flags: ['-m', '--model'], kind: 'flag' } as const;
+
+/**
+ * Which selector dimensions each CLI agent exposes, and how each dimension is
+ * spelled on its command line.
+ *
+ * This is the single source of truth for both directions: the chat-input
+ * selector reads it to render dimensions and to clear contradicting args when
+ * the user picks a value, and `buildHeteroSpawnArgs` reads it to decide whether
+ * user-authored args already cover a dimension.
+ */
+export const HETERO_SELECTOR_CAPABILITIES = {
+ 'amp': {},
+ 'claude-code': {
+ effort: {
+ encodings: [{ flags: ['--effort'], kind: 'flag' }],
+ levels: () => CLAUDE_CODE_REASONING_EFFORT_LEVELS,
+ resolve: resolveClaudeCodeReasoningEffort,
+ },
+ model: {
+ encodings: [{ flags: ['--model'], kind: 'flag' }],
+ resolve: resolveClaudeCodeModel,
+ source: 'static',
+ },
+ },
+ 'codex': {
+ effort: {
+ encodings: [{ key: CODEX_REASONING_EFFORT_CONFIG_KEY, kind: 'config' }],
+ levels: getCodexReasoningEffortLevels,
+ resolve: resolveCodexReasoningEffort,
+ },
+ model: {
+ encodings: [MODEL_FLAGS_ENCODING, { key: 'model', kind: 'config' }],
+ resolve: resolveCodexModel,
+ source: 'static',
+ },
+ speed: {
+ encodings: [{ key: CODEX_SERVICE_TIER_CONFIG_KEY, kind: 'config' }],
+ resolve: resolveCodexSpeedMode,
+ supported: codexModelSupportsFastSpeed,
+ },
+ },
+ 'opencode': {
+ model: { encodings: [MODEL_FLAGS_ENCODING], resolve: resolvePersistedModel, source: 'catalog' },
+ },
+ 'pi': {
+ model: {
+ encodings: [{ flags: ['--model'], kind: 'flag' }],
+ extraStripFlags: ['--provider'],
+ resolve: resolvePersistedModel,
+ source: 'catalog',
+ },
+ },
+ 'qoder': {
+ effort: {
+ encodings: [{ flags: [QODER_REASONING_EFFORT_FLAG], kind: 'flag' }],
+ levels: () => QODER_REASONING_EFFORT_LEVELS,
+ resolve: resolveQoderReasoningEffort,
+ },
+ model: { encodings: [MODEL_FLAGS_ENCODING], resolve: resolvePersistedModel, source: 'catalog' },
+ },
+} satisfies Record<LocalHeterogeneousAgentType, HeteroSelectorCapability>;
+
+export const getHeteroSelectorCapability = (
+ type: string | undefined,
+): HeteroSelectorCapability | undefined =>
+ HETERO_SELECTOR_CAPABILITIES[type as LocalHeterogeneousAgentType];
+
+export const isHeteroSelectorAvailable = (type: string | undefined): boolean =>
+ !!getHeteroSelectorCapability(type)?.model;
+
+export interface HeteroSelection {
+ effort?: HeterogeneousReasoningEffort;
+ model?: string;
+ speed?: HeterogeneousSpeedMode;
+}
+
+export interface HeteroSelectionPatch extends HeteroSelection {
+ args?: string[];
+}
+
+interface HeteroSelectionTarget {
+ args?: string[];
+ type?: string;
+}
+
+const clearEncodings = (
+ args: string[] | undefined,
+ encodings: readonly HeteroCliEncoding[],
+ extraStripFlags?: readonly string[],
+): string[] | undefined => {
+ let next = args;
+
+ for (const encoding of encodings) {
+ next =
+ encoding.kind === 'flag'
+ ? stripCliFlags(next, encoding.flags)
+ : stripCliConfigKey(next, encoding.key);
+ }
+
+ return extraStripFlags?.length ? stripCliFlags(next, extraStripFlags) : next;
+};
+
+/**
+ * Translate a selector pick into a provider-config patch.
+ *
+ * `buildHeteroSpawnArgs` treats user-authored `args` as winning over the
+ * structured fields, so a pick that left a contradicting flag in `args` would
+ * silently never take effect. Clearing the flags this dimension is spelled with
+ * is what makes the selection observable.
+ */
+export const applyHeteroSelection = (
+ provider: HeteroSelectionTarget | null | undefined,
+ selection: HeteroSelection,
+): HeteroSelectionPatch => {
+ const patch: HeteroSelectionPatch = { ...selection };
+ const capability = getHeteroSelectorCapability(provider?.type);
+ if (!capability) return patch;
+
+ let args = provider?.args;
+ let cleared = false;
+
+ if ('model' in selection && capability.model) {
+ args = clearEncodings(args, capability.model.encodings, capability.model.extraStripFlags);
+ cleared = true;
+ }
+
+ if ('effort' in selection && capability.effort) {
+ args = clearEncodings(args, capability.effort.encodings);
+ cleared = true;
+ }
+
+ if ('speed' in selection && capability.speed) {
+ args = clearEncodings(args, capability.speed.encodings);
+ cleared = true;
+ }
+
+ if (cleared) patch.args = args;
+
+ return patch;
+};
diff --git a/packages/types/src/agent/index.ts b/packages/types/src/agent/index.ts
index 2b071b24b43..90ef57d2b8e 100644
--- a/packages/types/src/agent/index.ts
+++ b/packages/types/src/agent/index.ts
@@ -4,7 +4,9 @@ export * from './chatConfig';
export * from './displayName';
export * from './document';
export * from './graph';
+export * from './heteroCliArgs';
export * from './heterogeneousAgent';
+export * from './heteroSelectorCapabilities';
export * from './item';
export * from './modelSelection';
export * from './pluginConfig';
diff --git a/src/features/ChatInput/ControlBar/HeteroModel.tsx b/src/features/ChatInput/ControlBar/HeteroModel.tsx
deleted file mode 100644
index a312fc81824..00000000000
--- a/src/features/ChatInput/ControlBar/HeteroModel.tsx
+++ /dev/null
@@ -1,756 +0,0 @@
-'use client';
-
-import type {
- ClaudeCodeReasoningEffort,
- CodexReasoningEffort,
- HeterogeneousAgentDefaultSelection,
- HeterogeneousProviderConfig,
- HeterogeneousSpeedMode,
- QoderReasoningEffort,
-} from '@lobechat/types';
-import {
- CLAUDE_CODE_REASONING_EFFORT_LEVELS,
- CODEX_REASONING_EFFORT_CONFIG_KEY,
- CODEX_SERVICE_TIER_CONFIG_KEY,
- codexModelSupportsFastSpeed,
- codexModelSupportsReasoningEffort,
- getCodexReasoningEffortLevels,
- HETEROGENEOUS_AGENT_DEFAULT_SELECTION,
- QODER_REASONING_EFFORT_FLAG,
- QODER_REASONING_EFFORT_LEVELS,
- resolveClaudeCodeModel,
- resolveClaudeCodeReasoningEffort,
- resolveCodexModel,
- resolveCodexReasoningEffort,
- resolveCodexSpeedMode,
- resolveQoderReasoningEffort,
-} from '@lobechat/types';
-import { Icon } from '@lobehub/ui';
-import {
- DropdownMenuItem,
- DropdownMenuItemContent,
- DropdownMenuItemExtra,
- DropdownMenuItemLabel,
- DropdownMenuPopup,
- DropdownMenuPortal,
- DropdownMenuPositioner,
- DropdownMenuRoot,
- DropdownMenuSubmenuArrow,
- DropdownMenuSubmenuRoot,
- DropdownMenuSubmenuTrigger,
- DropdownMenuTrigger,
-} from '@lobehub/ui/base-ui';
-import { createStaticStyles, cssVar } from 'antd-style';
-import isEqual from 'fast-deep-equal';
-import { CheckIcon, ChevronDownIcon, ChevronRightIcon, ZapIcon } from 'lucide-react';
-import type { ReactNode } from 'react';
-import { memo, useCallback, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { usePermission } from '@/hooks/usePermission';
-import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors } from '@/store/agent/selectors';
-
-import { useAgentId } from '../hooks/useAgentId';
-import { useChatInputResourceAccess } from '../hooks/useChatInputResourceAccess';
-import { HeterogeneousAgentModelSelector } from './HeterogeneousAgentModelSelector';
-
-type HeteroReasoningEffort =
- | ClaudeCodeReasoningEffort
- | CodexReasoningEffort
- | QoderReasoningEffort
- | HeterogeneousAgentDefaultSelection;
-
-type SelectableHeteroProviderType = 'claude-code' | 'codex' | 'opencode' | 'pi' | 'qoder';
-
-const CLAUDE_CODE_MODEL_OPTIONS = [
- { label: 'Fable 5', value: 'fable' },
- { label: 'Opus 4.8', value: 'opus' },
- { label: 'Sonnet 4.6', value: 'sonnet' },
- { label: 'Haiku 4.5', value: 'haiku' },
-] as const;
-
-const CODEX_MODEL_OPTIONS = [
- { 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' },
-] as const;
-
-const MODEL_LABELS: Record<string, string> = {
- 'gpt-5.6': 'GPT-5.6',
- ...Object.fromEntries(
- [...CLAUDE_CODE_MODEL_OPTIONS, ...CODEX_MODEL_OPTIONS].map((option) => [
- option.value,
- option.label,
- ]),
- ),
-};
-
-const EFFORT_LABEL_KEYS = {
- [HETEROGENEOUS_AGENT_DEFAULT_SELECTION]: 'heteroAgent.modelSelector.default',
- high: 'heteroAgent.modelSelector.reasoning.high',
- low: 'heteroAgent.modelSelector.reasoning.low',
- max: 'heteroAgent.modelSelector.reasoning.max',
- medium: 'heteroAgent.modelSelector.reasoning.medium',
- ultra: 'heteroAgent.modelSelector.reasoning.ultra',
- xhigh: 'heteroAgent.modelSelector.reasoning.xhigh',
-} as const satisfies Record<HeteroReasoningEffort, string>;
-
-/**
- * Codex renames the `low` effort to "Light" in its official app UI while the
- * CLI value stays `low`; Claude Code keeps the plain "Low" wording.
- */
-const CODEX_EFFORT_LABEL_KEYS = {
- ...EFFORT_LABEL_KEYS,
- low: 'heteroAgent.modelSelector.reasoning.light',
-} as const satisfies Record<HeteroReasoningEffort, string>;
-
-const styles = createStaticStyles(({ css }) => ({
- check: css`
- flex: none;
- color: ${cssVar.colorTextSecondary};
- `,
- label: css`
- overflow: hidden;
- max-width: 150px;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- option: css`
- cursor: pointer;
-
- display: flex;
- gap: 18px;
- align-items: center;
- justify-content: space-between;
-
- min-height: 34px;
- padding-inline: 10px;
- border-radius: 8px;
-
- font-size: 14px;
- line-height: 1.2;
- color: ${cssVar.colorText};
-
- transition: background-color 0.2s;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
- optionBody: css`
- overflow: hidden;
- display: flex;
- flex: 1;
- flex-direction: column;
- gap: 3px;
-
- min-width: 0;
- padding-block: 7px;
- `,
- optionDesc: css`
- overflow: hidden;
-
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- optionIcon: css`
- flex: none;
- color: ${cssVar.colorTextSecondary};
- `,
- optionLabel: css`
- overflow: hidden;
- flex: 1;
-
- min-width: 0;
-
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- optionTitle: css`
- display: flex;
- gap: 6px;
- align-items: center;
- white-space: nowrap;
- `,
- popup: css`
- padding: 8px;
- border-radius: 16px;
- background: ${cssVar.colorBgElevated};
- box-shadow:
- 0 0 0 1px ${cssVar.colorBorderSecondary},
- 0 12px 32px rgb(0 0 0 / 10%),
- 0 4px 12px rgb(0 0 0 / 8%);
- `,
- scroll: css`
- overflow-y: auto;
- display: flex;
- flex-direction: column;
- max-height: 250px;
- `,
- sectionTitle: css`
- padding-block: 0 8px;
- padding-inline: 10px;
-
- font-size: 13px;
- line-height: 1.2;
- color: ${cssVar.colorTextQuaternary};
- `,
- submenuTrigger: css`
- min-height: 36px;
- padding-inline: 10px;
- `,
- submenuMeta: css`
- overflow: hidden;
- display: inline-flex;
- flex: none;
- gap: 4px;
- align-items: center;
-
- min-width: 0;
- max-width: 150px;
- padding-inline-start: 16px;
-
- font-family: inherit;
- font-size: 14px;
- color: ${cssVar.colorTextSecondary};
- `,
- submenuMetaLabel: css`
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- trigger: css`
- cursor: pointer;
-
- display: flex;
- flex: none;
- gap: 6px;
- align-items: center;
-
- height: 28px;
- padding-inline: 8px;
- border-radius: 6px;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- white-space: nowrap;
-
- transition: all 0.2s;
-
- &:hover {
- color: ${cssVar.colorText};
- background: ${cssVar.colorFillSecondary};
- }
- `,
-}));
-
-interface SelectorSubmenuProps {
- children: ReactNode;
- currentValue: string;
- icon?: typeof ZapIcon;
- label: string;
- popupWidth?: number;
-}
-
-const SelectorSubmenu = ({
- children,
- currentValue,
- icon,
- label,
- popupWidth = 220,
-}: SelectorSubmenuProps) => (
- <DropdownMenuSubmenuRoot>
- <DropdownMenuSubmenuTrigger className={styles.submenuTrigger} label={label} openOnHover={false}>
- <DropdownMenuItemContent>
- <DropdownMenuItemLabel>{label}</DropdownMenuItemLabel>
- <DropdownMenuItemExtra className={styles.submenuMeta}>
- {icon && <Icon className={styles.optionIcon} icon={icon} size={12} />}
- <span className={styles.submenuMetaLabel}>{currentValue}</span>
- </DropdownMenuItemExtra>
- <DropdownMenuSubmenuArrow>
- <Icon icon={ChevronRightIcon} size={12} />
- </DropdownMenuSubmenuArrow>
- </DropdownMenuItemContent>
- </DropdownMenuSubmenuTrigger>
- <DropdownMenuPortal>
- <DropdownMenuPositioner alignOffset={-4} anchor={null} placement="right" sideOffset={8}>
- <DropdownMenuPopup className={styles.popup} style={{ minWidth: popupWidth }}>
- <div className={styles.sectionTitle}>{label}</div>
- <div className={styles.scroll}>{children}</div>
- </DropdownMenuPopup>
- </DropdownMenuPositioner>
- </DropdownMenuPortal>
- </DropdownMenuSubmenuRoot>
-);
-
-const stripCliFlags = (
- args: string[] | undefined,
- flags: readonly string[],
-): string[] | undefined => {
- if (!args) return undefined;
-
- const next: string[] = [];
- for (let index = 0; index < args.length; index += 1) {
- const arg = args[index];
- if (flags.includes(arg)) {
- const value = args[index + 1];
- if (value && !value.startsWith('-')) index += 1;
- continue;
- }
- if (flags.some((flag) => arg.startsWith(`${flag}=`))) continue;
-
- next.push(arg);
- }
-
- return next;
-};
-
-const parseCliConfigKey = (assignment: string): string | undefined => {
- const match = assignment.match(/^\s*([\w.-]+)\s*=/);
- return match?.[1];
-};
-
-const stripCodexConfigKey = (args: string[] | undefined, key: string): string[] | undefined => {
- if (!args) return undefined;
-
- const next: string[] = [];
- for (let index = 0; index < args.length; index += 1) {
- const arg = args[index];
-
- if (arg === '-c' || arg === '--config') {
- const value = args[index + 1];
- if (value && parseCliConfigKey(value) === key) {
- index += 1;
- continue;
- }
-
- next.push(arg);
- continue;
- }
-
- if (arg.startsWith('-c=') || arg.startsWith('--config=')) {
- const value = arg.slice(arg.indexOf('=') + 1);
- if (parseCliConfigKey(value) === key) continue;
- }
-
- next.push(arg);
- }
-
- return next;
-};
-
-const isSelectableProviderType = (
- type: HeterogeneousProviderConfig['type'] | undefined,
-): type is SelectableHeteroProviderType =>
- type === 'claude-code' ||
- type === 'codex' ||
- type === 'opencode' ||
- type === 'pi' ||
- type === 'qoder';
-
-const getModelLabel = (model: string, defaultLabel: string) => {
- if (model === HETEROGENEOUS_AGENT_DEFAULT_SELECTION) return defaultLabel;
-
- const aliasLabel = MODEL_LABELS[model];
- if (aliasLabel) return aliasLabel;
-
- const match = /^claude-(opus|sonnet|haiku)-(\d+)-(\d+)/.exec(model);
- if (!match) return model;
-
- const [, family, major, minor] = match;
- return `${family[0].toUpperCase()}${family.slice(1)} ${major}.${minor}`;
-};
-
-const getTriggerText = ({
- defaultConfigLabel,
- defaultModelLabel,
- defaultReasoningLabel,
- effort,
- effortLabel,
- model,
- modelLabel,
-}: {
- defaultConfigLabel: string;
- defaultModelLabel: string;
- defaultReasoningLabel: string;
- effort: HeteroReasoningEffort;
- effortLabel: string;
- model: string;
- modelLabel: string;
-}) => {
- const isDefaultModel = model === HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
- const isDefaultEffort = effort === HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
-
- if (isDefaultModel && isDefaultEffort) return defaultConfigLabel;
- const resolvedModelLabel = isDefaultModel ? defaultModelLabel : modelLabel;
- const resolvedEffortLabel = isDefaultEffort ? defaultReasoningLabel : effortLabel;
-
- return `${resolvedModelLabel} ${resolvedEffortLabel}`;
-};
-
-const HeteroModel = memo(() => {
- const { t } = useTranslation('chat');
- const agentId = useAgentId();
- const provider = useAgentStore(
- (s) => agentByIdSelectors.getAgencyConfigById(agentId)(s)?.heterogeneousProvider,
- isEqual,
- );
- const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
- const { allowed: canCreateContent, reason } = usePermission('create_content');
- // Model/effort picks write the shared heterogeneous-provider config. Hide
- // the selector when this caller cannot configure that shared resource.
- const { canConfigureResource } = useChatInputResourceAccess();
- const enabled = canCreateContent && canConfigureResource;
- const [open, setOpen] = useState(false);
-
- const patchProvider = useCallback(
- async (patch: Partial<Pick<HeterogeneousProviderConfig, 'effort' | 'model' | 'speed'>>) => {
- if (!enabled || !agentId) return;
-
- const nextPatch: Partial<HeterogeneousProviderConfig> = { ...patch };
- const providerType = provider?.type;
-
- if (providerType === 'codex') {
- if ('model' in patch) {
- const args = stripCliFlags(provider?.args, ['--model', '-m']);
- nextPatch.args = stripCodexConfigKey(args, 'model');
- }
- if ('effort' in patch) {
- const sourceArgs = nextPatch.args ?? provider?.args;
- nextPatch.args = stripCodexConfigKey(sourceArgs, CODEX_REASONING_EFFORT_CONFIG_KEY);
- }
- if ('speed' in patch) {
- const sourceArgs = nextPatch.args ?? provider?.args;
- nextPatch.args = stripCodexConfigKey(sourceArgs, CODEX_SERVICE_TIER_CONFIG_KEY);
- }
- } else if (providerType === 'qoder') {
- if ('model' in patch) {
- nextPatch.args = stripCliFlags(provider?.args, ['--model', '-m']);
- }
- if ('effort' in patch) {
- const sourceArgs = nextPatch.args ?? provider?.args;
- nextPatch.args = stripCliFlags(sourceArgs, [QODER_REASONING_EFFORT_FLAG]);
- }
- } else if (providerType === 'opencode' || providerType === 'pi') {
- if ('model' in patch) {
- nextPatch.args = stripCliFlags(
- provider?.args,
- providerType === 'pi' ? ['--model', '--provider'] : ['--model', '-m'],
- );
- }
- } else {
- if ('model' in patch) {
- nextPatch.args = stripCliFlags(provider?.args, ['--model']);
- }
- if ('effort' in patch) {
- const sourceArgs = nextPatch.args ?? provider?.args;
- nextPatch.args = stripCliFlags(sourceArgs, ['--effort']);
- }
- }
-
- await updateAgentConfigById(agentId, {
- agencyConfig: { heterogeneousProvider: nextPatch },
- });
- },
- [agentId, enabled, provider?.args, provider?.type, updateAgentConfigById],
- );
- const closeMenu = useCallback(() => {
- setOpen(false);
- }, []);
- const selectModel = useCallback(
- (value: string) => {
- closeMenu();
- // Fast speed only applies to supported Codex models — reset it when the
- // user switches away so the selector never claims a speed the run ignores.
- const resetSpeed =
- provider?.type === 'codex' &&
- resolveCodexSpeedMode(provider) === 'fast' &&
- !codexModelSupportsFastSpeed(value);
- const currentEffort =
- provider?.type === 'codex' ? resolveCodexReasoningEffort(provider) : undefined;
- const resetEffort =
- currentEffort !== undefined &&
- currentEffort !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !codexModelSupportsReasoningEffort(value, currentEffort);
-
- void patchProvider({
- ...(resetEffort ? { effort: HETEROGENEOUS_AGENT_DEFAULT_SELECTION } : {}),
- model: value,
- ...(resetSpeed ? { speed: HETEROGENEOUS_AGENT_DEFAULT_SELECTION } : {}),
- });
- },
- [closeMenu, patchProvider, provider],
- );
- const selectReasoningEffort = useCallback(
- (value: HeteroReasoningEffort) => {
- closeMenu();
- void patchProvider({ effort: value });
- },
- [closeMenu, patchProvider],
- );
- const selectSpeedMode = useCallback(
- (value: HeterogeneousSpeedMode) => {
- closeMenu();
- void patchProvider({ speed: value });
- },
- [closeMenu, patchProvider],
- );
-
- if (!isSelectableProviderType(provider?.type)) return null;
- if (!enabled) return null;
-
- if (provider.type === 'qoder') {
- const model =
- provider.model && provider.model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION
- ? provider.model
- : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
- const effort = resolveQoderReasoningEffort(provider);
- const defaultLabel = t('heteroAgent.modelSelector.default');
- const modelLabel = getModelLabel(model, defaultLabel);
- const effortLabel = t(EFFORT_LABEL_KEYS[effort]);
- const triggerText = getTriggerText({
- defaultConfigLabel: t('heteroAgent.modelSelector.defaultConfig'),
- defaultModelLabel: t('heteroAgent.modelSelector.defaultModel'),
- defaultReasoningLabel: t('heteroAgent.modelSelector.defaultReasoning'),
- effort,
- effortLabel,
- model,
- modelLabel,
- });
- const effortOptions: { label: string; value: HeteroReasoningEffort }[] = [
- { label: defaultLabel, value: HETEROGENEOUS_AGENT_DEFAULT_SELECTION },
- ...QODER_REASONING_EFFORT_LEVELS.map((level) => ({
- label: t(EFFORT_LABEL_KEYS[level]),
- value: level,
- })),
- ];
-
- return (
- <DropdownMenuRoot open={open} onOpenChange={setOpen}>
- <DropdownMenuTrigger nativeButton={false}>
- <div
- className={styles.trigger}
- aria-label={t('heteroAgent.modelSelector.ariaLabel', {
- model: modelLabel,
- reasoning: effortLabel,
- })}
- >
- <span className={styles.label}>{triggerText}</span>
- <Icon icon={ChevronDownIcon} size={12} />
- </div>
- </DropdownMenuTrigger>
- <DropdownMenuPortal>
- <DropdownMenuPositioner placement="topLeft" sideOffset={8}>
- <DropdownMenuPopup className={styles.popup} style={{ width: 240 }}>
- <HeterogeneousAgentModelSelector
- agentId={agentId}
- disabled={false}
- model={model}
- permissionReason={reason}
- type={provider.type}
- variant="submenu"
- onSelect={selectModel}
- />
- <SelectorSubmenu
- currentValue={effortLabel}
- label={t('heteroAgent.modelSelector.reasoning')}
- >
- {effortOptions.map((option) => (
- <DropdownMenuItem
- className={styles.option}
- data-selected={effort === option.value ? 'true' : undefined}
- key={`effort-${option.value}`}
- onClick={() => selectReasoningEffort(option.value)}
- >
- <span className={styles.optionLabel}>{option.label}</span>
- {effort === option.value && (
- <Icon className={styles.check} icon={CheckIcon} size={16} />
- )}
- </DropdownMenuItem>
- ))}
- </SelectorSubmenu>
- </DropdownMenuPopup>
- </DropdownMenuPositioner>
- </DropdownMenuPortal>
- </DropdownMenuRoot>
- );
- }
-
- if (provider.type === 'opencode' || provider.type === 'pi') {
- const model =
- provider.model && provider.model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION
- ? provider.model
- : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
-
- return (
- <HeterogeneousAgentModelSelector
- agentId={agentId}
- disabled={false}
- model={model}
- permissionReason={reason}
- type={provider.type}
- onSelect={(value) => void patchProvider({ model: value })}
- />
- );
- }
-
- const providerType = provider.type;
- const model =
- providerType === 'codex' ? resolveCodexModel(provider) : resolveClaudeCodeModel(provider);
- const effort =
- providerType === 'codex'
- ? resolveCodexReasoningEffort(provider)
- : resolveClaudeCodeReasoningEffort(provider);
- // Fast speed is a per-model capability: hide the whole Speed UI (submenu +
- // lightning icons) for models without the Fast tier. A stale persisted
- // `fast` on an unsupported model is ignored by the Codex CLI and cleared by
- // the selector on the next model switch.
- const supportsFastSpeed = providerType === 'codex' && codexModelSupportsFastSpeed(model);
- const speed = supportsFastSpeed
- ? resolveCodexSpeedMode(provider)
- : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
- const isFastSpeed = speed === 'fast';
- const defaultLabel = t('heteroAgent.modelSelector.default');
- const modelLabel = getModelLabel(model, defaultLabel);
- const effortLabelKeys = providerType === 'codex' ? CODEX_EFFORT_LABEL_KEYS : EFFORT_LABEL_KEYS;
- const effortLabel = t(effortLabelKeys[effort]);
- const reasoningLevels =
- providerType === 'codex'
- ? getCodexReasoningEffortLevels(model)
- : CLAUDE_CODE_REASONING_EFFORT_LEVELS;
- const providerModelOptions =
- providerType === 'codex' ? CODEX_MODEL_OPTIONS : CLAUDE_CODE_MODEL_OPTIONS;
- const effortOptions: { label: string; value: HeteroReasoningEffort }[] = [
- { label: defaultLabel, value: HETEROGENEOUS_AGENT_DEFAULT_SELECTION },
- ...reasoningLevels.map((level) => ({
- label: t(effortLabelKeys[level]),
- value: level,
- })),
- ];
- const baseModelOptions: { label: string; value: string }[] = [
- { label: defaultLabel, value: HETEROGENEOUS_AGENT_DEFAULT_SELECTION },
- ...providerModelOptions,
- ];
- const modelOptions = baseModelOptions.some((option) => option.value === model)
- ? baseModelOptions
- : [{ label: model, value: model }, ...baseModelOptions];
- const speedOptions: {
- description: string;
- icon?: typeof ZapIcon;
- label: string;
- value: HeterogeneousSpeedMode;
- }[] = [
- {
- description: t('heteroAgent.modelSelector.speed.standardDesc'),
- label: t('heteroAgent.modelSelector.speed.standard'),
- value: HETEROGENEOUS_AGENT_DEFAULT_SELECTION,
- },
- {
- description: t('heteroAgent.modelSelector.speed.fastDesc'),
- icon: ZapIcon,
- label: t('heteroAgent.modelSelector.speed.fast'),
- value: 'fast',
- },
- ];
- const speedLabel =
- speed === 'fast'
- ? t('heteroAgent.modelSelector.speed.fast')
- : t('heteroAgent.modelSelector.speed.standard');
- const triggerText = getTriggerText({
- defaultConfigLabel: t('heteroAgent.modelSelector.defaultConfig'),
- defaultModelLabel: t('heteroAgent.modelSelector.defaultModel'),
- defaultReasoningLabel: t('heteroAgent.modelSelector.defaultReasoning'),
- effort,
- effortLabel,
- model,
- modelLabel,
- });
-
- const trigger = (
- <div
- className={styles.trigger}
- aria-label={t('heteroAgent.modelSelector.ariaLabel', {
- model: modelLabel,
- reasoning: effortLabel,
- })}
- >
- {isFastSpeed && <Icon icon={ZapIcon} size={12} />}
- <span className={styles.label}>{triggerText}</span>
- <Icon icon={ChevronDownIcon} size={12} />
- </div>
- );
-
- const renderOption = <T extends string>(
- title: string,
- options: readonly { description?: string; icon?: typeof ZapIcon; label: string; value: T }[],
- current: T,
- onSelect: (value: T) => void,
- ) =>
- options.map((option) => (
- <DropdownMenuItem
- className={styles.option}
- data-selected={current === option.value ? 'true' : undefined}
- key={`${title}-${option.value}`}
- onClick={() => void onSelect(option.value)}
- >
- {option.description ? (
- <div className={styles.optionBody}>
- <span className={styles.optionTitle}>
- {option.icon && <Icon className={styles.optionIcon} icon={option.icon} size={14} />}
- {option.label}
- </span>
- <span className={styles.optionDesc}>{option.description}</span>
- </div>
- ) : (
- <span className={styles.optionLabel}>{option.label}</span>
- )}
- {current === option.value && <Icon className={styles.check} icon={CheckIcon} size={16} />}
- </DropdownMenuItem>
- ));
-
- return (
- <DropdownMenuRoot open={open} onOpenChange={setOpen}>
- <DropdownMenuTrigger nativeButton={false}>{trigger}</DropdownMenuTrigger>
- <DropdownMenuPortal>
- <DropdownMenuPositioner placement="topLeft" sideOffset={8}>
- <DropdownMenuPopup className={styles.popup} style={{ width: 240 }}>
- <SelectorSubmenu
- currentValue={modelLabel}
- label={t('heteroAgent.modelSelector.model')}
- popupWidth={240}
- >
- {renderOption('model', modelOptions, model, selectModel)}
- </SelectorSubmenu>
- <SelectorSubmenu
- currentValue={effortLabel}
- label={t('heteroAgent.modelSelector.reasoning')}
- >
- {renderOption('reasoning', effortOptions, effort, selectReasoningEffort)}
- </SelectorSubmenu>
- {supportsFastSpeed && (
- <SelectorSubmenu
- currentValue={speedLabel}
- icon={isFastSpeed ? ZapIcon : undefined}
- label={t('heteroAgent.modelSelector.speed')}
- popupWidth={240}
- >
- {renderOption('speed', speedOptions, speed, selectSpeedMode)}
- </SelectorSubmenu>
- )}
- </DropdownMenuPopup>
- </DropdownMenuPositioner>
- </DropdownMenuPortal>
- </DropdownMenuRoot>
- );
-});
-
-HeteroModel.displayName = 'HeteroModel';
-
-export default HeteroModel;
diff --git a/src/features/ChatInput/ControlBar/HeterogeneousAgentModelSelector.tsx b/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx
similarity index 74%
rename from src/features/ChatInput/ControlBar/HeterogeneousAgentModelSelector.tsx
rename to src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx
index e46f2845c32..9899cda7f32 100644
--- a/src/features/ChatInput/ControlBar/HeterogeneousAgentModelSelector.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx
@@ -5,14 +5,20 @@ import { HETEROGENEOUS_AGENT_DEFAULT_SELECTION } from '@lobechat/types';
import { ActionIcon, Icon, Input, Tooltip } from '@lobehub/ui';
import {
Button,
+ DropdownMenuGroup,
+ DropdownMenuGroupLabel,
+ DropdownMenuHeader,
DropdownMenuItem,
DropdownMenuItemContent,
+ DropdownMenuItemDesc,
DropdownMenuItemExtra,
DropdownMenuItemLabel,
+ DropdownMenuItemLabelGroup,
DropdownMenuPopup,
DropdownMenuPortal,
DropdownMenuPositioner,
DropdownMenuRoot,
+ DropdownMenuScrollViewport,
DropdownMenuSubmenuArrow,
DropdownMenuSubmenuRoot,
DropdownMenuSubmenuTrigger,
@@ -40,22 +46,14 @@ import { useElectronStore } from '@/store/electron';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
-import { useHeterogeneousAgentModelCatalog } from './useHeterogeneousAgentModelCatalog';
-import { useMenuContentLifecycle } from './useMenuContentLifecycle';
+import { useMenuContentLifecycle } from '../useMenuContentLifecycle';
+import { useModelCatalog } from './useModelCatalog';
const styles = createStaticStyles(({ css }) => ({
check: css`
flex: none;
color: ${cssVar.colorPrimary};
`,
- container: css`
- display: flex;
- flex-direction: column;
-
- width: 340px;
- max-height: 430px;
- margin: -4px;
- `,
empty: css`
padding-block: 24px;
padding-inline: 16px;
@@ -64,61 +62,21 @@ const styles = createStaticStyles(({ css }) => ({
color: ${cssVar.colorTextTertiary};
text-align: center;
`,
- group: css`
- padding-block: 8px 3px;
- padding-inline: 10px;
-
- font-size: 11px;
- font-weight: 500;
- color: ${cssVar.colorTextTertiary};
- `,
item: css`
- display: flex;
- gap: 10px;
- align-items: center;
-
- width: calc(100% - 8px);
min-height: 42px;
- margin-inline: 4px;
- padding-block: 5px;
- padding-inline: 8px;
- border-radius: 6px;
- `,
- itemBody: css`
- overflow: hidden;
- flex: 1;
- min-width: 0;
- `,
- itemSubtitle: css`
- overflow: hidden;
-
- font-size: 11px;
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- white-space: nowrap;
`,
- itemTitle: css`
+ popup: css`
overflow: hidden;
+ display: flex;
+ flex-direction: column;
- font-size: 13px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- list: css`
- overflow-y: auto;
- flex: 1;
- min-height: 0;
- padding-block-end: 4px;
+ width: 340px;
+ max-height: 430px;
`,
search: css`
display: flex;
gap: 6px;
align-items: center;
-
- padding-block: 6px;
- padding-inline: 10px;
- border-block-end: 1px solid ${cssVar.colorSplit};
`,
spinning: css`
animation: heterogeneous-agent-model-spin 0.8s linear infinite;
@@ -134,26 +92,13 @@ const styles = createStaticStyles(({ css }) => ({
`,
submenuMeta: css`
overflow: hidden;
- display: inline-flex;
- flex: none;
- align-items: center;
- min-width: 0;
max-width: 150px;
- padding-inline-start: 16px;
- font-size: 14px;
- color: ${cssVar.colorTextSecondary};
- `,
- submenuMetaLabel: css`
- overflow: hidden;
+ font-family: inherit;
text-overflow: ellipsis;
white-space: nowrap;
`,
- submenuTrigger: css`
- min-height: 36px;
- padding-inline: 10px;
- `,
trigger: css`
cursor: pointer;
@@ -203,7 +148,7 @@ const getCatalogErrorKey = (name: string) => {
}
};
-interface HeterogeneousAgentModelSelectorProps {
+interface ModelCatalogSelectorProps {
agentId?: string;
disabled: boolean;
model: string;
@@ -213,7 +158,7 @@ interface HeterogeneousAgentModelSelectorProps {
variant?: 'standalone' | 'submenu';
}
-export const HeterogeneousAgentModelSelector = memo<HeterogeneousAgentModelSelectorProps>(
+export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(
({ agentId, disabled, model, onSelect, permissionReason, type, variant = 'standalone' }) => {
const { t } = useTranslation('chat');
const agentName = type === 'pi' ? 'Pi' : type === 'qoder' ? 'Qoder' : 'OpenCode';
@@ -249,7 +194,7 @@ export const HeterogeneousAgentModelSelector = memo<HeterogeneousAgentModelSelec
model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION
? model
: HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
- const { data, error, isLoading, isValidating, mutate } = useHeterogeneousAgentModelCatalog({
+ const { data, error, isLoading, isValidating, mutate } = useModelCatalog({
cwd,
deviceId: rpcDeviceId,
isDeviceListLoading,
@@ -334,8 +279,8 @@ export const HeterogeneousAgentModelSelector = memo<HeterogeneousAgentModelSelec
const handleModelSelect = variant === 'submenu' ? onSelect : handleSelect;
const menu = (
- <div className={styles.container}>
- <div className={styles.search}>
+ <>
+ <DropdownMenuHeader className={styles.search}>
<Input
autoFocus
placeholder={t('heteroAgent.cliModel.search')}
@@ -355,21 +300,27 @@ export const HeterogeneousAgentModelSelector = memo<HeterogeneousAgentModelSelec
title={t('heteroAgent.cliModel.reload')}
onClick={() => void mutate()}
/>
- </div>
- <div className={styles.list}>
+ </DropdownMenuHeader>
+ <DropdownMenuScrollViewport>
<DropdownMenuItem
className={styles.item}
onClick={() => handleModelSelect(HETEROGENEOUS_AGENT_DEFAULT_SELECTION)}
>
- <div className={styles.itemBody}>
- <div className={styles.itemTitle}>{t('heteroAgent.modelSelector.default')}</div>
- <div className={styles.itemSubtitle}>
- {t('heteroAgent.cliModel.defaultDesc', { name: agentName })}
- </div>
- </div>
- {currentModel === HETEROGENEOUS_AGENT_DEFAULT_SELECTION && (
- <Icon className={styles.check} icon={CheckIcon} size={14} />
- )}
+ <DropdownMenuItemContent>
+ <DropdownMenuItemLabelGroup>
+ <DropdownMenuItemLabel>
+ {t('heteroAgent.modelSelector.default')}
+ </DropdownMenuItemLabel>
+ <DropdownMenuItemDesc>
+ {t('heteroAgent.cliModel.defaultDesc', { name: agentName })}
+ </DropdownMenuItemDesc>
+ </DropdownMenuItemLabelGroup>
+ {currentModel === HETEROGENEOUS_AGENT_DEFAULT_SELECTION && (
+ <DropdownMenuItemExtra className={styles.check}>
+ <Icon icon={CheckIcon} size={14} />
+ </DropdownMenuItemExtra>
+ )}
+ </DropdownMenuItemContent>
</DropdownMenuItem>
{isLoading && !data && (
@@ -397,37 +348,38 @@ export const HeterogeneousAgentModelSelector = memo<HeterogeneousAgentModelSelec
</div>
)}
{Object.entries(groups).map(([providerId, models]) => (
- <div key={providerId}>
- <div className={styles.group}>{providerId}</div>
- {models.map((item) => (
- <DropdownMenuItem
- className={styles.item}
- key={item.id}
- onClick={() => handleModelSelect(item.id)}
- >
- <div className={styles.itemBody}>
- <div className={styles.itemTitle}>{item.label ?? item.modelId}</div>
- <div
- className={cx(
- styles.itemSubtitle,
- selectedIsStale && item.id === currentModel && styles.stale,
+ <DropdownMenuGroup key={providerId}>
+ <DropdownMenuGroupLabel>{providerId}</DropdownMenuGroupLabel>
+ {models.map((item) => {
+ const isStale = selectedIsStale && item.id === currentModel;
+
+ return (
+ <DropdownMenuItem
+ className={styles.item}
+ key={item.id}
+ onClick={() => handleModelSelect(item.id)}
+ >
+ <DropdownMenuItemContent>
+ <DropdownMenuItemLabelGroup>
+ <DropdownMenuItemLabel>{item.label ?? item.modelId}</DropdownMenuItemLabel>
+ <DropdownMenuItemDesc className={cx(isStale && styles.stale)}>
+ {item.id}
+ {isStale ? ` · ${t('heteroAgent.cliModel.stale')}` : ''}
+ </DropdownMenuItemDesc>
+ </DropdownMenuItemLabelGroup>
+ {item.id === currentModel && (
+ <DropdownMenuItemExtra className={styles.check}>
+ <Icon icon={CheckIcon} size={14} />
+ </DropdownMenuItemExtra>
)}
- >
- {item.id}
- {selectedIsStale && item.id === currentModel
- ? ` · ${t('heteroAgent.cliModel.stale')}`
- : ''}
- </div>
- </div>
- {item.id === currentModel && (
- <Icon className={styles.check} icon={CheckIcon} size={14} />
- )}
- </DropdownMenuItem>
- ))}
- </div>
+ </DropdownMenuItemContent>
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuGroup>
))}
- </div>
- </div>
+ </DropdownMenuScrollViewport>
+ </>
);
if (variant === 'submenu') {
@@ -438,18 +390,15 @@ export const HeterogeneousAgentModelSelector = memo<HeterogeneousAgentModelSelec
onOpenChangeComplete={handleOpenChangeComplete}
>
<DropdownMenuSubmenuTrigger
- className={styles.submenuTrigger}
label={t('heteroAgent.modelSelector.model')}
openOnHover={false}
>
<DropdownMenuItemContent>
<DropdownMenuItemLabel>{t('heteroAgent.modelSelector.model')}</DropdownMenuItemLabel>
<DropdownMenuItemExtra className={styles.submenuMeta}>
- <span className={styles.submenuMetaLabel}>
- {currentModel === HETEROGENEOUS_AGENT_DEFAULT_SELECTION
- ? t('heteroAgent.modelSelector.default')
- : currentModel}
- </span>
+ {currentModel === HETEROGENEOUS_AGENT_DEFAULT_SELECTION
+ ? t('heteroAgent.modelSelector.default')
+ : currentModel}
</DropdownMenuItemExtra>
<DropdownMenuSubmenuArrow>
<Icon icon={ChevronRightIcon} size={12} />
@@ -458,7 +407,9 @@ export const HeterogeneousAgentModelSelector = memo<HeterogeneousAgentModelSelec
</DropdownMenuSubmenuTrigger>
<DropdownMenuPortal>
<DropdownMenuPositioner alignOffset={-4} anchor={null} placement="right" sideOffset={8}>
- <DropdownMenuPopup>{menu}</DropdownMenuPopup>
+ <DropdownMenuPopup className={styles.popup} data-has-header="">
+ {menu}
+ </DropdownMenuPopup>
</DropdownMenuPositioner>
</DropdownMenuPortal>
</DropdownMenuSubmenuRoot>
@@ -474,7 +425,9 @@ export const HeterogeneousAgentModelSelector = memo<HeterogeneousAgentModelSelec
<DropdownMenuTrigger nativeButton={false}>{trigger}</DropdownMenuTrigger>
<DropdownMenuPortal>
<DropdownMenuPositioner placement="topLeft" sideOffset={8}>
- <DropdownMenuPopup>{menu}</DropdownMenuPopup>
+ <DropdownMenuPopup className={styles.popup} data-has-header="">
+ {menu}
+ </DropdownMenuPopup>
</DropdownMenuPositioner>
</DropdownMenuPortal>
</DropdownMenuRoot>
@@ -482,4 +435,4 @@ export const HeterogeneousAgentModelSelector = memo<HeterogeneousAgentModelSelec
},
);
-HeterogeneousAgentModelSelector.displayName = 'HeterogeneousAgentModelSelector';
+ModelCatalogSelector.displayName = 'ModelCatalogSelector';
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/SelectorMenu.tsx b/src/features/ChatInput/ControlBar/HeteroModel/SelectorMenu.tsx
new file mode 100644
index 00000000000..8519c8b75dc
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroModel/SelectorMenu.tsx
@@ -0,0 +1,106 @@
+import type {
+ HeterogeneousProviderConfig,
+ HeterogeneousReasoningEffort,
+ HeterogeneousSpeedMode,
+ HeteroSelection,
+ ListHeterogeneousAgentModelsParams,
+} from '@lobechat/types';
+import {
+ DropdownMenuPopup,
+ DropdownMenuPortal,
+ DropdownMenuPositioner,
+ DropdownMenuRoot,
+ DropdownMenuTrigger,
+ renderDropdownMenuItems,
+} from '@lobehub/ui/base-ui';
+import { memo, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { buildSelectorSubmenu } from './buildSelectorSubmenu';
+import { ModelCatalogSelector } from './ModelCatalogSelector';
+import type { ModelCapability } from './selectorView';
+import { buildSelectorView, resolveModelSwitchSelection } from './selectorView';
+import Trigger from './Trigger';
+
+interface SelectorMenuProps {
+ agentId?: string;
+ capability: ModelCapability;
+ patch: (selection: HeteroSelection) => Promise<void>;
+ permissionReason?: string;
+ provider: HeterogeneousProviderConfig;
+}
+
+const SelectorMenu = memo<SelectorMenuProps>(
+ ({ agentId, capability, patch, permissionReason, provider }) => {
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(false);
+
+ const view = useMemo(
+ () => buildSelectorView({ capability, provider, t }),
+ [capability, provider, t],
+ );
+
+ const select = useCallback(
+ (key: string, value: string) => {
+ setOpen(false);
+
+ if (key === 'model')
+ return void patch(
+ resolveModelSwitchSelection({
+ capability,
+ effort: capability.effort?.resolve(provider),
+ isFastSpeed: view.isFastSpeed,
+ value,
+ }),
+ );
+
+ void patch(
+ key === 'speed'
+ ? { speed: value as HeterogeneousSpeedMode }
+ : { effort: value as HeterogeneousReasoningEffort },
+ );
+ },
+ [capability, patch, provider, view.isFastSpeed],
+ );
+
+ const items = view.dimensions.map((dimension) =>
+ buildSelectorSubmenu({
+ current: dimension.current,
+ label: dimension.label,
+ onSelect: (value: string) => select(dimension.key, value),
+ options: dimension.options,
+ valueLabel: dimension.valueLabel,
+ }),
+ );
+
+ return (
+ <DropdownMenuRoot open={open} onOpenChange={setOpen}>
+ <DropdownMenuTrigger nativeButton={false}>
+ <Trigger ariaLabel={view.ariaLabel} fast={view.isFastSpeed} text={view.triggerText} />
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuPositioner placement="topLeft" sideOffset={8}>
+ <DropdownMenuPopup style={{ width: 240 }}>
+ {view.isCatalogModel && (
+ <ModelCatalogSelector
+ agentId={agentId}
+ disabled={false}
+ model={view.model}
+ permissionReason={permissionReason}
+ type={provider.type as ListHeterogeneousAgentModelsParams['type']}
+ variant="submenu"
+ onSelect={(value) => select('model', value)}
+ />
+ )}
+ {renderDropdownMenuItems(items)}
+ </DropdownMenuPopup>
+ </DropdownMenuPositioner>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+ );
+ },
+);
+
+SelectorMenu.displayName = 'HeteroModelSelectorMenu';
+
+export default SelectorMenu;
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/Trigger.tsx b/src/features/ChatInput/ControlBar/HeteroModel/Trigger.tsx
new file mode 100644
index 00000000000..2868c5ac244
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroModel/Trigger.tsx
@@ -0,0 +1,60 @@
+import { Icon } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { ChevronDownIcon, ZapIcon } from 'lucide-react';
+import type { ComponentPropsWithRef } from 'react';
+import { memo } from 'react';
+
+const styles = createStaticStyles(({ css }) => ({
+ label: css`
+ overflow: hidden;
+ max-width: 150px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ trigger: css`
+ cursor: pointer;
+
+ display: flex;
+ flex: none;
+ gap: 6px;
+ align-items: center;
+
+ height: 28px;
+ padding-inline: 8px;
+ border-radius: 6px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+
+ transition: all 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+}));
+
+/**
+ * `DropdownMenuTrigger` clones its child to inject the open handler, ref and
+ * `aria-haspopup`/`aria-expanded`. Swallowing the rest props here leaves a
+ * chip that renders correctly and never opens, so they must reach the element.
+ */
+interface TriggerProps extends ComponentPropsWithRef<'div'> {
+ ariaLabel: string;
+ fast?: boolean;
+ text: string;
+}
+
+const Trigger = memo<TriggerProps>(({ ariaLabel, className, fast, text, ...rest }) => (
+ <div {...rest} aria-label={ariaLabel} className={cx(styles.trigger, className)}>
+ {fast && <Icon icon={ZapIcon} size={12} />}
+ <span className={styles.label}>{text}</span>
+ <Icon icon={ChevronDownIcon} size={12} />
+ </div>
+));
+
+Trigger.displayName = 'HeteroModelTrigger';
+
+export default Trigger;
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/buildSelectorSubmenu.tsx b/src/features/ChatInput/ControlBar/HeteroModel/buildSelectorSubmenu.tsx
new file mode 100644
index 00000000000..12dc7c40bbe
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroModel/buildSelectorSubmenu.tsx
@@ -0,0 +1,54 @@
+import { Icon } from '@lobehub/ui';
+import type { DropdownItem } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { CheckIcon } from 'lucide-react';
+import type { ReactNode } from 'react';
+
+const styles = createStaticStyles(({ css }) => ({
+ // The packaged `extra` slot is styled for keyboard hints, so it defaults to the
+ // code font. This one carries a model name, which belongs in the UI font — and
+ // `inherit` cannot express that, since this span sits inside that slot.
+ value: css`
+ font-family: ${cssVar.fontFamily};
+ `,
+}));
+
+const checkIcon = <Icon icon={CheckIcon} size={16} />;
+
+export interface SelectorOption<T extends string> {
+ desc?: string;
+ label: string;
+ value: T;
+}
+
+/**
+ * `renderDropdownMenuItems` renders `extra` on submenu rows too, but @lobehub/ui
+ * only declares it on leaf items — widen it so the current-value column stays typed.
+ */
+type SelectorSubmenuItem = DropdownItem & { extra?: ReactNode };
+
+export const buildSelectorSubmenu = <T extends string>({
+ current,
+ label,
+ onSelect,
+ options,
+ valueLabel,
+}: {
+ current: T;
+ label: string;
+ onSelect: (value: T) => void;
+ options: readonly SelectorOption<T>[];
+ valueLabel: string;
+}): SelectorSubmenuItem => ({
+ children: options.map((option) => ({
+ desc: option.desc,
+ extra: current === option.value ? checkIcon : undefined,
+ key: `${label}-${option.value}`,
+ label: option.label,
+ onClick: () => onSelect(option.value),
+ })),
+ extra: <span className={styles.value}>{valueLabel}</span>,
+ key: label,
+ label,
+ type: 'submenu',
+});
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/index.tsx b/src/features/ChatInput/ControlBar/HeteroModel/index.tsx
new file mode 100644
index 00000000000..37510a4b821
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroModel/index.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import type { ListHeterogeneousAgentModelsParams } from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
+import { memo } from 'react';
+
+import { usePermission } from '@/hooks/usePermission';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
+import { ModelCatalogSelector } from './ModelCatalogSelector';
+import SelectorMenu from './SelectorMenu';
+import { resolveSelectorShape } from './selectorView';
+import { useHeteroProviderPatch } from './useHeteroProviderPatch';
+
+const HeteroModel = memo(() => {
+ const agentId = useAgentId();
+ const provider = useAgentStore(
+ (s) => agentByIdSelectors.getAgencyConfigById(agentId)(s)?.heterogeneousProvider,
+ isEqual,
+ );
+ const { allowed: canCreateContent, reason } = usePermission('create_content');
+ // Model/effort picks write the shared heterogeneous-provider config. Hide
+ // the selector when this caller cannot configure that shared resource.
+ const { canConfigureResource } = useChatInputResourceAccess();
+ const enabled = canCreateContent && canConfigureResource;
+ const patch = useHeteroProviderPatch({ agentId, enabled, provider });
+
+ const shape = resolveSelectorShape(provider, enabled);
+
+ if (shape.kind === 'none' || !provider) return null;
+
+ if (shape.kind === 'catalog')
+ return (
+ <ModelCatalogSelector
+ agentId={agentId}
+ disabled={false}
+ model={shape.capability.model.resolve(provider)}
+ permissionReason={reason}
+ type={provider.type as ListHeterogeneousAgentModelsParams['type']}
+ onSelect={(value) => void patch({ model: value })}
+ />
+ );
+
+ return (
+ <SelectorMenu
+ agentId={agentId}
+ capability={shape.capability}
+ patch={patch}
+ permissionReason={reason}
+ provider={provider}
+ />
+ );
+});
+
+HeteroModel.displayName = 'HeteroModel';
+
+export default HeteroModel;
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/labels.ts b/src/features/ChatInput/ControlBar/HeteroModel/labels.ts
new file mode 100644
index 00000000000..31c36d82fff
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroModel/labels.ts
@@ -0,0 +1,75 @@
+import type { HeterogeneousReasoningEffort } from '@lobechat/types';
+import { HETEROGENEOUS_AGENT_DEFAULT_SELECTION } from '@lobechat/types';
+
+import { MODEL_LABELS } from './modelOptions';
+
+const EFFORT_LABEL_KEYS = {
+ [HETEROGENEOUS_AGENT_DEFAULT_SELECTION]: 'heteroAgent.modelSelector.default',
+ high: 'heteroAgent.modelSelector.reasoning.high',
+ low: 'heteroAgent.modelSelector.reasoning.low',
+ max: 'heteroAgent.modelSelector.reasoning.max',
+ medium: 'heteroAgent.modelSelector.reasoning.medium',
+ ultra: 'heteroAgent.modelSelector.reasoning.ultra',
+ xhigh: 'heteroAgent.modelSelector.reasoning.xhigh',
+} as const satisfies Record<HeterogeneousReasoningEffort, string>;
+
+/**
+ * Codex renames the `low` effort to "Light" in its official app UI while the
+ * CLI value stays `low`; Claude Code keeps the plain "Low" wording.
+ */
+const CODEX_EFFORT_LABEL_KEYS = {
+ ...EFFORT_LABEL_KEYS,
+ low: 'heteroAgent.modelSelector.reasoning.light',
+} as const satisfies Record<HeterogeneousReasoningEffort, string>;
+
+type EffortLabelKey =
+ | (typeof CODEX_EFFORT_LABEL_KEYS)[HeterogeneousReasoningEffort]
+ | (typeof EFFORT_LABEL_KEYS)[HeterogeneousReasoningEffort];
+
+export const getEffortLabelKeys = (
+ type: string | undefined,
+): Record<HeterogeneousReasoningEffort, EffortLabelKey> =>
+ type === 'codex' ? CODEX_EFFORT_LABEL_KEYS : EFFORT_LABEL_KEYS;
+
+export const getModelLabel = (model: string, defaultLabel: string) => {
+ if (model === HETEROGENEOUS_AGENT_DEFAULT_SELECTION) return defaultLabel;
+
+ const aliasLabel = MODEL_LABELS[model];
+ if (aliasLabel) return aliasLabel;
+
+ const match = /^claude-(opus|sonnet|haiku)-(\d+)-(\d+)/.exec(model);
+ if (!match) return model;
+
+ const [, family, major, minor] = match;
+ return `${family[0].toUpperCase()}${family.slice(1)} ${major}.${minor}`;
+};
+
+export const getTriggerText = ({
+ defaultConfigLabel,
+ defaultModelLabel,
+ defaultReasoningLabel,
+ effort,
+ effortLabel,
+ model,
+ modelLabel,
+}: {
+ defaultConfigLabel: string;
+ defaultModelLabel: string;
+ defaultReasoningLabel: string;
+ effort?: HeterogeneousReasoningEffort;
+ effortLabel?: string;
+ model: string;
+ modelLabel: string;
+}) => {
+ const isDefaultModel = model === HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+ const resolvedModelLabel = isDefaultModel ? defaultModelLabel : modelLabel;
+
+ if (!effort) return isDefaultModel ? defaultConfigLabel : resolvedModelLabel;
+
+ const isDefaultEffort = effort === HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+ if (isDefaultModel && isDefaultEffort) return defaultConfigLabel;
+
+ const resolvedEffortLabel = isDefaultEffort ? defaultReasoningLabel : effortLabel;
+
+ return `${resolvedModelLabel} ${resolvedEffortLabel}`;
+};
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/modelOptions.ts b/src/features/ChatInput/ControlBar/HeteroModel/modelOptions.ts
new file mode 100644
index 00000000000..ee39df3d63f
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroModel/modelOptions.ts
@@ -0,0 +1,43 @@
+export interface StaticModelOption {
+ label: string;
+ value: string;
+}
+
+const CLAUDE_CODE_MODEL_OPTIONS: StaticModelOption[] = [
+ { label: 'Fable 5', value: 'fable' },
+ { label: 'Opus 4.8', value: 'opus' },
+ { label: 'Sonnet 4.6', value: 'sonnet' },
+ { label: 'Haiku 4.5', value: 'haiku' },
+];
+
+const CODEX_MODEL_OPTIONS: StaticModelOption[] = [
+ { 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
+ * `@lobechat/types` alongside the capability table.
+ */
+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]) || [];
+
+export const MODEL_LABELS: Record<string, string> = {
+ 'gpt-5.6': 'GPT-5.6',
+ ...Object.fromEntries(
+ Object.values(STATIC_MODEL_OPTIONS)
+ .flat()
+ .map((option) => [option.value, option.label]),
+ ),
+};
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts b/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts
new file mode 100644
index 00000000000..936f5626500
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts
@@ -0,0 +1,238 @@
+import type { HeterogeneousProviderConfig } from '@lobechat/types';
+import { applyHeteroSelection, getHeteroSelectorCapability } from '@lobechat/types';
+import type { TFunction } from 'i18next';
+import { describe, expect, it } from 'vitest';
+
+import type { ModelCapability } from './selectorView';
+import {
+ buildSelectorView,
+ resolveModelSwitchSelection,
+ resolveSelectorShape,
+} from './selectorView';
+
+const t = ((key: string) => key) as unknown as TFunction<'chat'>;
+
+const capabilityOf = (type: string): ModelCapability => {
+ const capability = getHeteroSelectorCapability(type);
+ if (!capability?.model) throw new Error(`no selector capability for ${type}`);
+
+ return { ...capability, model: capability.model };
+};
+
+const viewOf = (provider: HeterogeneousProviderConfig) =>
+ buildSelectorView({ capability: capabilityOf(provider.type), provider, t });
+
+const dimensionKeys = (provider: HeterogeneousProviderConfig) =>
+ viewOf(provider).dimensions.map((dimension) => dimension.key);
+
+describe('resolveSelectorShape', () => {
+ it('renders nothing for providers with no selector', () => {
+ expect(resolveSelectorShape({ type: 'amp' }, true).kind).toBe('none');
+ expect(resolveSelectorShape(undefined, true).kind).toBe('none');
+ });
+
+ it('renders nothing when the caller cannot configure the shared provider', () => {
+ expect(resolveSelectorShape({ model: 'opus', type: 'claude-code' }, false).kind).toBe('none');
+ });
+
+ it('gives catalog-only providers the bare picker', () => {
+ expect(resolveSelectorShape({ type: 'opencode' }, true).kind).toBe('catalog');
+ expect(resolveSelectorShape({ type: 'pi' }, true).kind).toBe('catalog');
+ });
+
+ it('gives a catalog provider with another dimension the full menu', () => {
+ expect(resolveSelectorShape({ type: 'qoder' }, true).kind).toBe('menu');
+ });
+
+ it('gives static providers the full menu', () => {
+ expect(resolveSelectorShape({ type: 'claude-code' }, true).kind).toBe('menu');
+ expect(resolveSelectorShape({ type: 'codex' }, true).kind).toBe('menu');
+ });
+});
+
+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('hides speed for codex models without a fast tier', () => {
+ expect(dimensionKeys({ model: 'gpt-5.3-codex-spark', type: 'codex' })).toEqual([
+ 'model',
+ 'reasoning',
+ ]);
+ });
+
+ it('offers model and reasoning but never speed for claude-code', () => {
+ expect(dimensionKeys({ model: 'opus', type: 'claude-code' })).toEqual(['model', 'reasoning']);
+ });
+
+ it('leaves the model dimension to the catalog picker for qoder', () => {
+ const view = viewOf({ model: 'qwen3-coder', type: 'qoder' });
+
+ expect(view.isCatalogModel).toBe(true);
+ expect(view.dimensions.map((dimension) => dimension.key)).toEqual(['reasoning']);
+ });
+
+ 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;
+
+ expect(solLevels.map((option) => option.value)).toContain('ultra');
+ expect(lunaLevels.map((option) => option.value)).toContain('max');
+ expect(lunaLevels.map((option) => option.value)).not.toContain('ultra');
+ });
+
+ 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;
+
+ expect(options[0]).toEqual({ label: 'gpt-4o-legacy', value: 'gpt-4o-legacy' });
+ });
+});
+
+describe('current value surfaced on each dimension', () => {
+ it('shows the resolved model and effort labels', () => {
+ const view = viewOf({ effort: 'high', model: 'opus', type: 'claude-code' });
+
+ expect(view.dimensions[0].valueLabel).toBe('Opus 4.8');
+ expect(view.dimensions[1].valueLabel).toBe('heteroAgent.modelSelector.reasoning.high');
+ });
+
+ it('prefers a contradicting arg over the persisted field, matching spawn behaviour', () => {
+ const view = viewOf({ args: ['--model', 'haiku'], model: 'opus', type: 'claude-code' });
+
+ expect(view.dimensions[0].valueLabel).toBe('Haiku 4.5');
+ });
+
+ 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');
+ });
+
+ it('keeps the plain Low wording for claude-code', () => {
+ const view = viewOf({ effort: 'low', model: 'opus', type: 'claude-code' });
+
+ expect(view.dimensions[1].valueLabel).toBe('heteroAgent.modelSelector.reasoning.low');
+ });
+
+ it('flags fast speed so the trigger can badge it', () => {
+ expect(viewOf({ model: 'gpt-5.6-sol', speed: 'fast', type: 'codex' }).isFastSpeed).toBe(true);
+ expect(viewOf({ model: 'gpt-5.6-sol', type: 'codex' }).isFastSpeed).toBe(false);
+ });
+
+ it('ignores a fast speed the current model cannot serve', () => {
+ expect(viewOf({ model: 'gpt-5.3-codex-spark', speed: 'fast', type: 'codex' }).isFastSpeed).toBe(
+ false,
+ );
+ });
+
+ it('collapses the trigger to one label when nothing is overridden', () => {
+ expect(viewOf({ type: 'claude-code' }).triggerText).toBe(
+ 'heteroAgent.modelSelector.defaultConfig',
+ );
+ });
+
+ it('names both halves in the trigger once either is overridden', () => {
+ expect(viewOf({ model: 'opus', type: 'claude-code' }).triggerText).toBe(
+ 'Opus 4.8 heteroAgent.modelSelector.defaultReasoning',
+ );
+ });
+});
+
+describe('resolveModelSwitchSelection', () => {
+ it('resets a fast speed the newly picked codex model cannot serve', () => {
+ expect(
+ resolveModelSwitchSelection({
+ capability: capabilityOf('codex'),
+ isFastSpeed: true,
+ value: 'gpt-5.3-codex-spark',
+ }),
+ ).toEqual({ model: 'gpt-5.3-codex-spark', speed: 'default' });
+ });
+
+ it('keeps a fast speed the newly picked codex model still serves', () => {
+ expect(
+ resolveModelSwitchSelection({
+ capability: capabilityOf('codex'),
+ isFastSpeed: true,
+ value: 'gpt-5.5',
+ }),
+ ).toEqual({ model: 'gpt-5.5' });
+ });
+
+ it('resets an effort level the newly picked codex model cannot serve', () => {
+ expect(
+ resolveModelSwitchSelection({
+ capability: capabilityOf('codex'),
+ effort: 'ultra',
+ isFastSpeed: false,
+ value: 'gpt-5.4',
+ }),
+ ).toEqual({ effort: 'default', model: 'gpt-5.4' });
+ });
+
+ it('never resets effort for providers whose levels do not depend on the model', () => {
+ expect(
+ resolveModelSwitchSelection({
+ capability: capabilityOf('claude-code'),
+ effort: 'max',
+ isFastSpeed: false,
+ value: 'haiku',
+ }),
+ ).toEqual({ model: 'haiku' });
+ });
+});
+
+describe('what a pick persists', () => {
+ it('clears the contradicting claude-code arg', () => {
+ const provider: HeterogeneousProviderConfig = {
+ args: ['--verbose', '--model', 'haiku'],
+ type: 'claude-code',
+ };
+
+ expect(
+ applyHeteroSelection(
+ provider,
+ resolveModelSwitchSelection({
+ capability: capabilityOf('claude-code'),
+ isFastSpeed: false,
+ value: 'opus',
+ }),
+ ),
+ ).toEqual({ args: ['--verbose'], model: 'opus' });
+ });
+
+ it('clears both codex model spellings', () => {
+ const provider: HeterogeneousProviderConfig = {
+ args: ['-m', 'gpt-5.5', '-c', 'model="gpt-5.4"'],
+ type: 'codex',
+ };
+
+ expect(
+ applyHeteroSelection(
+ provider,
+ resolveModelSwitchSelection({
+ capability: capabilityOf('codex'),
+ isFastSpeed: false,
+ value: 'gpt-5.6-sol',
+ }),
+ ),
+ ).toEqual({ args: [], model: 'gpt-5.6-sol' });
+ });
+
+ it('clears the qoder reasoning-effort flag', () => {
+ const provider: HeterogeneousProviderConfig = {
+ args: ['--reasoning-effort', 'high', '-p'],
+ type: 'qoder',
+ };
+
+ expect(applyHeteroSelection(provider, { effort: 'low' })).toEqual({
+ args: ['-p'],
+ effort: 'low',
+ });
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/selectorView.ts b/src/features/ChatInput/ControlBar/HeteroModel/selectorView.ts
new file mode 100644
index 00000000000..2949bc07293
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroModel/selectorView.ts
@@ -0,0 +1,201 @@
+import type {
+ HeterogeneousProviderConfig,
+ HeterogeneousReasoningEffort,
+ HeterogeneousSpeedMode,
+ HeteroSelection,
+ HeteroSelectorCapability,
+} from '@lobechat/types';
+import {
+ getHeteroSelectorCapability,
+ HETEROGENEOUS_AGENT_DEFAULT_SELECTION,
+} from '@lobechat/types';
+import type { TFunction } from 'i18next';
+
+import { getEffortLabelKeys, getModelLabel, getTriggerText } from './labels';
+import { getStaticModelOptions } from './modelOptions';
+
+type Translate = TFunction<'chat'>;
+
+export type ModelCapability = Required<Pick<HeteroSelectorCapability, 'model'>> &
+ HeteroSelectorCapability;
+
+export interface SelectorDimensionOption {
+ desc?: string;
+ label: string;
+ value: string;
+}
+
+export interface SelectorDimension {
+ current: string;
+ key: 'model' | 'reasoning' | 'speed';
+ label: string;
+ options: SelectorDimensionOption[];
+ valueLabel: string;
+}
+
+export interface SelectorView {
+ ariaLabel: string;
+ dimensions: SelectorDimension[];
+ isCatalogModel: boolean;
+ isFastSpeed: boolean;
+ model: string;
+ triggerText: string;
+}
+
+export type SelectorShape =
+ { capability: ModelCapability; kind: 'catalog' | 'menu' } | { kind: 'none' };
+
+/**
+ * Which of the three selector presentations a provider gets: nothing, the bare
+ * catalog picker, or the multi-dimension menu. A catalog provider with no other
+ * dimension has nothing to wrap, so it renders its picker directly.
+ */
+export const resolveSelectorShape = (
+ provider: HeterogeneousProviderConfig | undefined,
+ enabled: boolean,
+): SelectorShape => {
+ const capability = getHeteroSelectorCapability(provider?.type);
+ if (!provider || !enabled || !capability?.model) return { kind: 'none' };
+
+ const modelCapability = { ...capability, model: capability.model };
+ const hasOtherDimensions = !!capability.effort || !!capability.speed;
+
+ return {
+ capability: modelCapability,
+ kind: capability.model.source === 'catalog' && !hasOtherDimensions ? 'catalog' : 'menu',
+ };
+};
+
+/**
+ * A dimension the newly picked model cannot serve would otherwise stay persisted
+ * and be silently dropped by the CLI, leaving the menu claiming a setting the
+ * run never used.
+ */
+export const resolveModelSwitchSelection = ({
+ capability,
+ effort,
+ isFastSpeed,
+ value,
+}: {
+ capability: ModelCapability;
+ effort?: HeterogeneousReasoningEffort;
+ isFastSpeed: boolean;
+ value: string;
+}): HeteroSelection => {
+ const resetSpeed = isFastSpeed && !!capability.speed && !capability.speed.supported(value);
+ const resetEffort =
+ !!effort &&
+ effort !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !!capability.effort &&
+ !capability.effort.levels(value).includes(effort);
+
+ return {
+ ...(resetEffort ? { effort: HETEROGENEOUS_AGENT_DEFAULT_SELECTION } : {}),
+ model: value,
+ ...(resetSpeed ? { speed: HETEROGENEOUS_AGENT_DEFAULT_SELECTION } : {}),
+ };
+};
+
+export const buildSelectorView = ({
+ capability,
+ provider,
+ t,
+}: {
+ capability: ModelCapability;
+ provider: HeterogeneousProviderConfig;
+ t: Translate;
+}): SelectorView => {
+ const model = capability.model.resolve(provider);
+ const effort = capability.effort?.resolve(provider);
+ const speedSupported = capability.speed?.supported(model) ?? false;
+ const speed: HeterogeneousSpeedMode = speedSupported
+ ? capability.speed!.resolve(provider)
+ : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+ const isFastSpeed = speed === 'fast';
+
+ const defaultLabel = t('heteroAgent.modelSelector.default');
+ const modelLabel = getModelLabel(model, defaultLabel);
+ const effortLabelKeys = getEffortLabelKeys(provider.type);
+ const effortLabel = effort ? t(effortLabelKeys[effort]) : undefined;
+ const isCatalogModel = capability.model.source === 'catalog';
+
+ const dimensions: SelectorDimension[] = [];
+
+ if (!isCatalogModel) {
+ const baseOptions: SelectorDimensionOption[] = [
+ { label: defaultLabel, value: HETEROGENEOUS_AGENT_DEFAULT_SELECTION },
+ ...getStaticModelOptions(provider.type),
+ ];
+
+ dimensions.push({
+ current: model,
+ key: 'model',
+ label: t('heteroAgent.modelSelector.model'),
+ options: baseOptions.some((option) => option.value === model)
+ ? baseOptions
+ : [{ label: model, value: model }, ...baseOptions],
+ valueLabel: modelLabel,
+ });
+ }
+
+ if (capability.effort && effort) {
+ dimensions.push({
+ current: effort,
+ key: 'reasoning',
+ label: t('heteroAgent.modelSelector.reasoning'),
+ options: [
+ { label: defaultLabel, value: HETEROGENEOUS_AGENT_DEFAULT_SELECTION },
+ ...capability.effort.levels(model).map((level) => ({
+ label: t(effortLabelKeys[level]),
+ value: level,
+ })),
+ ],
+ valueLabel: effortLabel!,
+ });
+ }
+
+ if (speedSupported) {
+ dimensions.push({
+ current: speed,
+ key: 'speed',
+ label: t('heteroAgent.modelSelector.speed'),
+ options: [
+ {
+ desc: t('heteroAgent.modelSelector.speed.standardDesc'),
+ label: t('heteroAgent.modelSelector.speed.standard'),
+ value: HETEROGENEOUS_AGENT_DEFAULT_SELECTION,
+ },
+ {
+ desc: t('heteroAgent.modelSelector.speed.fastDesc'),
+ label: t('heteroAgent.modelSelector.speed.fast'),
+ value: 'fast',
+ },
+ ],
+ valueLabel: t(
+ isFastSpeed
+ ? 'heteroAgent.modelSelector.speed.fast'
+ : 'heteroAgent.modelSelector.speed.standard',
+ ),
+ });
+ }
+
+ return {
+ ariaLabel: t('heteroAgent.modelSelector.ariaLabel', {
+ model: modelLabel,
+ reasoning: effortLabel ?? defaultLabel,
+ }),
+ dimensions,
+ isCatalogModel,
+ isFastSpeed,
+ model,
+ triggerText: getTriggerText({
+ defaultConfigLabel: t('heteroAgent.modelSelector.defaultConfig'),
+ defaultModelLabel: t('heteroAgent.modelSelector.defaultModel'),
+ defaultReasoningLabel: t('heteroAgent.modelSelector.defaultReasoning'),
+ effort,
+ effortLabel,
+ model,
+ modelLabel,
+ }),
+ };
+};
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.ts b/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.ts
new file mode 100644
index 00000000000..c88158ce607
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.ts
@@ -0,0 +1,28 @@
+import type { HeterogeneousProviderConfig, HeteroSelection } from '@lobechat/types';
+import { applyHeteroSelection } from '@lobechat/types';
+import { useCallback } from 'react';
+
+import { useAgentStore } from '@/store/agent';
+
+export const useHeteroProviderPatch = ({
+ agentId,
+ enabled,
+ provider,
+}: {
+ agentId?: string;
+ enabled: boolean;
+ provider: HeterogeneousProviderConfig | undefined;
+}) => {
+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
+
+ return useCallback(
+ async (selection: HeteroSelection) => {
+ if (!enabled || !agentId) return;
+
+ await updateAgentConfigById(agentId, {
+ agencyConfig: { heterogeneousProvider: applyHeteroSelection(provider, selection) },
+ });
+ },
+ [agentId, enabled, provider, updateAgentConfigById],
+ );
+};
diff --git a/src/features/ChatInput/ControlBar/useHeterogeneousAgentModelCatalog.test.ts b/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalog.test.ts
similarity index 93%
rename from src/features/ChatInput/ControlBar/useHeterogeneousAgentModelCatalog.test.ts
rename to src/features/ChatInput/ControlBar/HeteroModel/useModelCatalog.test.ts
index 97afc056e73..66bc46e8800 100644
--- a/src/features/ChatInput/ControlBar/useHeterogeneousAgentModelCatalog.test.ts
+++ b/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalog.test.ts
@@ -6,7 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { heterogeneousAgentCatalogService } from '@/services/heterogeneousAgent';
-import { useHeterogeneousAgentModelCatalog } from './useHeterogeneousAgentModelCatalog';
+import { useModelCatalog } from './useModelCatalog';
const createWrapper = () => {
const value = { provider: () => new Map() };
@@ -16,7 +16,7 @@ const createWrapper = () => {
};
};
-describe('useHeterogeneousAgentModelCatalog', () => {
+describe('useModelCatalog', () => {
afterEach(() => {
vi.restoreAllMocks();
});
@@ -33,7 +33,7 @@ describe('useHeterogeneousAgentModelCatalog', () => {
const { result } = renderHook(
() =>
- useHeterogeneousAgentModelCatalog({
+ useModelCatalog({
isDeviceListLoading: false,
isPreferenceLoading: false,
open: false,
@@ -54,7 +54,7 @@ describe('useHeterogeneousAgentModelCatalog', () => {
const { result } = renderHook(
() =>
- useHeterogeneousAgentModelCatalog({
+ useModelCatalog({
isDeviceListLoading: false,
isPreferenceLoading: true,
open: false,
@@ -85,7 +85,7 @@ describe('useHeterogeneousAgentModelCatalog', () => {
const { rerender } = renderHook(
({ cwd, isDeviceListLoading }: { cwd?: string; isDeviceListLoading: boolean }) =>
- useHeterogeneousAgentModelCatalog({
+ useModelCatalog({
cwd,
deviceId: 'device-1',
isDeviceListLoading,
@@ -117,7 +117,7 @@ describe('useHeterogeneousAgentModelCatalog', () => {
renderHook(
() =>
- useHeterogeneousAgentModelCatalog({
+ useModelCatalog({
isDeviceListLoading: false,
isPreferenceLoading: false,
open: false,
@@ -155,7 +155,7 @@ describe('useHeterogeneousAgentModelCatalog', () => {
const { rerender, result } = renderHook(
({ open }) =>
- useHeterogeneousAgentModelCatalog({
+ useModelCatalog({
isDeviceListLoading: false,
isPreferenceLoading: false,
open,
diff --git a/src/features/ChatInput/ControlBar/useHeterogeneousAgentModelCatalog.ts b/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalog.ts
similarity index 97%
rename from src/features/ChatInput/ControlBar/useHeterogeneousAgentModelCatalog.ts
rename to src/features/ChatInput/ControlBar/HeteroModel/useModelCatalog.ts
index b5dead7d3d8..e7a28e97921 100644
--- a/src/features/ChatInput/ControlBar/useHeterogeneousAgentModelCatalog.ts
+++ b/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalog.ts
@@ -38,7 +38,7 @@ interface UseHeterogeneousAgentModelCatalogParams {
* revalidate a failed preload if the user opens the selector after the target
* becomes available.
*/
-export const useHeterogeneousAgentModelCatalog = ({
+export const useModelCatalog = ({
cwd,
deviceId,
isDeviceListLoading,
diff --git a/src/features/ChatInput/ControlBar/__tests__/useMenuContentLifecycle.test.ts b/src/features/ChatInput/ControlBar/__tests__/useMenuContentLifecycle.test.ts
index 838f6fec3da..3a71e7f604d 100644
--- a/src/features/ChatInput/ControlBar/__tests__/useMenuContentLifecycle.test.ts
+++ b/src/features/ChatInput/ControlBar/__tests__/useMenuContentLifecycle.test.ts
@@ -4,27 +4,23 @@ import { describe, expect, it, vi } from 'vitest';
import { useMenuContentLifecycle } from '../useMenuContentLifecycle';
describe('useMenuContentLifecycle', () => {
- it('keeps content active and commits a selection after the close animation', () => {
+ it('commits a selection only after the close animation completes', () => {
const onSelect = vi.fn();
const { result } = renderHook(() => useMenuContentLifecycle(onSelect));
act(() => result.current.handleOpenChange(true));
expect(result.current.open).toBe(true);
- expect(result.current.contentActive).toBe(true);
act(() => result.current.deferSelection('provider/model'));
expect(result.current.open).toBe(false);
- expect(result.current.contentActive).toBe(true);
expect(onSelect).not.toHaveBeenCalled();
act(() => result.current.handleOpenChangeComplete(true));
- expect(result.current.contentActive).toBe(true);
expect(onSelect).not.toHaveBeenCalled();
act(() => result.current.handleOpenChangeComplete(false));
- expect(result.current.contentActive).toBe(false);
expect(onSelect).toHaveBeenCalledOnce();
expect(onSelect).toHaveBeenCalledWith('provider/model');
@@ -40,7 +36,6 @@ describe('useMenuContentLifecycle', () => {
act(() => result.current.handleOpenChange(false));
act(() => result.current.handleOpenChangeComplete(false));
- expect(result.current.contentActive).toBe(false);
expect(onSelect).not.toHaveBeenCalled();
});
});
diff --git a/src/features/ChatInput/ControlBar/useMenuContentLifecycle.ts b/src/features/ChatInput/ControlBar/useMenuContentLifecycle.ts
index c4e9785e926..a9c95ed413b 100644
--- a/src/features/ChatInput/ControlBar/useMenuContentLifecycle.ts
+++ b/src/features/ChatInput/ControlBar/useMenuContentLifecycle.ts
@@ -1,15 +1,9 @@
import { useCallback, useRef, useState } from 'react';
export const useMenuContentLifecycle = <T>(onSelect: (value: T) => void) => {
- const [contentActive, setContentActive] = useState(false);
const [open, setOpen] = useState(false);
const pendingSelectionRef = useRef<T | undefined>(undefined);
- const handleOpenChange = useCallback((nextOpen: boolean) => {
- setOpen(nextOpen);
- if (nextOpen) setContentActive(true);
- }, []);
-
const deferSelection = useCallback((value: T) => {
pendingSelectionRef.current = value;
setOpen(false);
@@ -18,8 +12,6 @@ export const useMenuContentLifecycle = <T>(onSelect: (value: T) => void) => {
const handleOpenChangeComplete = useCallback(
(nextOpen: boolean) => {
if (nextOpen) return;
-
- setContentActive(false);
if (pendingSelectionRef.current === undefined) return;
const value = pendingSelectionRef.current;
@@ -30,9 +22,8 @@ export const useMenuContentLifecycle = <T>(onSelect: (value: T) => void) => {
);
return {
- contentActive,
deferSelection,
- handleOpenChange,
+ handleOpenChange: setOpen,
handleOpenChangeComplete,
open,
};
diff --git a/src/features/ChatTerminal/index.test.tsx b/src/features/ChatTerminal/index.test.tsx
index 860346e628b..6e264b4b938 100644
--- a/src/features/ChatTerminal/index.test.tsx
+++ b/src/features/ChatTerminal/index.test.tsx
@@ -20,6 +20,10 @@ vi.mock('@lobehub/ui', () => ({
),
}));
+vi.mock('@/hooks/useHotkeys', () => ({
+ useToggleTerminalPanelHotkey: vi.fn(),
+}));
+
vi.mock('./Content', () => ({
default: () => <div data-testid="terminal-content" />,
}));
diff --git a/src/hooks/useHotkeys/chatScope.test.ts b/src/hooks/useHotkeys/chatScope.test.ts
index d12f9595d91..fe198b7c531 100644
--- a/src/hooks/useHotkeys/chatScope.test.ts
+++ b/src/hooks/useHotkeys/chatScope.test.ts
@@ -24,9 +24,9 @@ vi.mock('@/store/global', () => ({
}));
vi.mock('./useHotkeyById', () => ({
- useHotkeyById: (id: HotkeyId, callback: () => void) => {
+ useHotkeyById: (id: HotkeyId, callback: () => void, options?: unknown) => {
mocks.hotkeyCallback = callback;
- mocks.useHotkeyById(id, callback);
+ mocks.useHotkeyById(id, callback, options);
return { id };
},
}));
diff --git a/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx
index c8588b2f4fc..f7e0c66d106 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx
@@ -66,7 +66,7 @@ describe('TerminalPanelToggle', () => {
expect(mocks.toggleTerminalPanel).toHaveBeenCalledWith();
mocks.showTerminalPanel = true;
- rerender(<TerminalPanelToggle />);
+ rerender(<TerminalPanelToggle key="open" />);
expect(screen.getByTestId('terminal-panel-toggle')).toHaveAttribute('data-active', 'true');
});
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
index 8b77e304604..7a9a9b78e97 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
@@ -1,6 +1,7 @@
'use client';
import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';
+import { isHeteroSelectorAvailable } from '@lobechat/types';
import { type ChatInputActionsProps } from '@lobehub/editor/react';
import { Alert, Flexbox } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
@@ -105,17 +106,8 @@ const HeterogeneousChatInput = memo(() => {
!isHeterogeneousSandboxExecutionAvailable(providerType) &&
executionTarget === 'none';
- // OpenCode, Pi, and Qoder discover models on a concrete runtime; Claude Code and
- // Codex show the selector on every execution path (local / sandbox / device)
- // since dispatch forwards --model/--effort everywhere.
- const isSelectableHeteroProvider =
- providerType === 'claude-code' ||
- providerType === 'codex' ||
- providerType === 'opencode' ||
- providerType === 'pi' ||
- providerType === 'qoder';
const showHeteroModel =
- isSelectableHeteroProvider &&
+ isHeteroSelectorAvailable(providerType) &&
shouldShowHeteroModelSelector({
boundDeviceId: agencyConfig?.boundDeviceId,
executionTarget,
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts
index f6ac1adab0f..62deb2ba3de 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts
@@ -1,4 +1,5 @@
import type { DeviceExecutionTarget, HeterogeneousProviderConfig } from '@lobechat/types';
+import { getHeteroSelectorCapability } from '@lobechat/types';
interface ShouldShowHeteroModelSelectorParams {
boundDeviceId?: string;
@@ -13,10 +14,10 @@ export const shouldShowHeteroModelSelector = ({
isDesktopClient,
providerType,
}: ShouldShowHeteroModelSelectorParams): boolean => {
- // OpenCode, Pi, and Qoder have no cloud-side model list — their selectors need
- // a concrete runtime to discover models from: the desktop itself, or an explicit
+ // 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.
- if (providerType === 'opencode' || providerType === 'pi' || providerType === 'qoder') {
+ if (getHeteroSelectorCapability(providerType)?.model?.source === 'catalog') {
if (executionTarget === 'local') return isDesktopClient;
return executionTarget === 'device' && !!boundDeviceId;
}