🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent): follow parent model for sub-agents by default + thinking controls (#17938)
YuTengjingab0dfa8bc299
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.tsnew file mode 100644index 00000000000..5f986f04bfa--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts@@ -0,0 +1,83 @@+import { type AgentState } from '@lobechat/agent-runtime';+import { type ChatToolPayload } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { type RuntimeExecutorContext } from '../context';+import { buildServerVirtualSubAgentRunner } from '../executorHelpers';++/**+ * The parent model a spawned `callSubAgent` follows must be the model the+ * parent run ACTUALLY uses. `metadata.agentConfig` alone is not enough: when a+ * run continues a topic whose model was switched, execAgent keeps the+ * topic-pinned model only in `modelRuntimeConfig` while the metadata config+ * retains the agent default.+ */+describe('buildServerVirtualSubAgentRunner sub-agent model resolution', () => {+ const buildRunner = (state: Partial<AgentState>) => {+ const execVirtualSubAgent = vi.fn().mockResolvedValue({ operationId: 'child-op' });+ const ctx = {+ execVirtualSubAgent,+ messageModel: { create: vi.fn().mockResolvedValue({ id: 'placeholder-id' }) },+ operationId: 'parent-op',+ topicId: 'topic-1',+ } as unknown as RuntimeExecutorContext;++ const runner = buildServerVirtualSubAgentRunner(+ ctx,+ {+ metadata: { agentId: 'agent-1', topicId: 'topic-1' },+ operationId: 'parent-op',+ ...state,+ } as AgentState,+ { id: 'tool-call-1' } as ChatToolPayload,+ 'parent-message-1',+ );++ return { execVirtualSubAgent, runner };+ };++ it('follows the topic-pinned runtime model over the metadata agent default', async () => {+ const { execVirtualSubAgent, runner } = buildRunner({+ metadata: {+ agentConfig: { model: 'agent-default-model', provider: 'agent-default-provider' },+ agentId: 'agent-1',+ topicId: 'topic-1',+ },+ modelRuntimeConfig: { model: 'topic-pinned-model', provider: 'topic-pinned-provider' },+ });++ await runner!.run({ description: 'task', instruction: 'do it' });++ expect(execVirtualSubAgent).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'topic-pinned-model', provider: 'topic-pinned-provider' }),+ );+ });++ it('falls back to the metadata agent config when no runtime model exists', async () => {+ const { execVirtualSubAgent, runner } = buildRunner({+ metadata: {+ agentConfig: { model: 'agent-default-model', provider: 'agent-default-provider' },+ agentId: 'agent-1',+ topicId: 'topic-1',+ },+ });++ await runner!.run({ description: 'task', instruction: 'do it' });++ expect(execVirtualSubAgent).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'agent-default-model', provider: 'agent-default-provider' }),+ );+ });++ it('keeps a named callAgent target on its own model', async () => {+ const { execVirtualSubAgent, runner } = buildRunner({+ modelRuntimeConfig: { model: 'topic-pinned-model', provider: 'topic-pinned-provider' },+ });++ await runner!.run({ agentId: 'target-agent', description: 'task', instruction: 'do it' });++ expect(execVirtualSubAgent).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'target-agent', model: undefined, provider: undefined }),+ );+ });+});diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.tsindex 1dfdb38468b..6ac03bc04d0 100644--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts@@ -1,7 +1,7 @@import { type AgentState } from '@lobechat/agent-runtime';import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';import { dispatchWorkRegistrationIntent } from '@lobechat/builtin-tools/workRegistration';-import { resolveSubAgentModel } from '@lobechat/const';+import { getSubAgentChatConfigOverride, resolveSubAgentModel } from '@lobechat/const';import { type OperationToolSet } from '@lobechat/context-engine';import { type ToolType } from '@lobechat/observability-otel/modules/agent-runtime';import {@@ -205,12 +205,20 @@ export const buildServerVirtualSubAgentRunner = (if (!agentId || !topicId) return undefined;const parentAgentConfig = state.metadata?.agentConfig as LobeAgentConfig | undefined;+ // The model the parent run ACTUALLY uses. `metadata.agentConfig` alone is not+ // enough: when a run continues a topic whose model was switched, execAgent+ // keeps the topic-pinned model only in `modelRuntimeConfig` while the+ // metadata config retains the agent default.+ const parentEffectiveModel =+ state.modelRuntimeConfig ?? state.metadata?.modelRuntimeConfig ?? parentAgentConfig;return {run: async ({ agentId: targetAgentId, description, instruction, timeout }) => {// This runner serves two tools, and only one of them may swap the model:// - `callSubAgent` names no agent, so the child is an anonymous clone of- // the parent — it takes the parent's `agencyConfig.subagent` model.+ // the parent — it takes the parent's `agencyConfig.subagent` override,+ // or follows the parent's effective (topic-pinned) model when none is+ // configured.// - `callAgent` names an existing agent, which carries a model the user// configured on it. Overriding that would discard a deliberate choice,// the same way forcing a group member onto the sub-agent default would.@@ -218,7 +226,12 @@ export const buildServerVirtualSubAgentRunner = (// re-derive it from the parent config.const subAgentModel = targetAgentId? undefined- : resolveSubAgentModel(parentAgentConfig?.agencyConfig?.subagent);+ : resolveSubAgentModel(parentAgentConfig?.agencyConfig?.subagent, parentEffectiveModel);+ // Thinking / reasoning-effort overrides configured for the sub-agent+ // model; same callSubAgent-only carve-out as the model above.+ const subAgentChatConfig = targetAgentId+ ? undefined+ : getSubAgentChatConfigOverride(parentAgentConfig?.agencyConfig?.subagent);// 1. Create the pending placeholder tool message (mirrors the normal// tool-message shape in call_tool) that anchors the isolation thread@@ -241,6 +254,7 @@ export const buildServerVirtualSubAgentRunner = (// bridge that backfills this tool message and resumes the parent op.const result = (await execVirtualSubAgent({agentId: targetAgentId ?? agentId,+ chatConfig: subAgentChatConfig,groupId: state.metadata?.groupId ?? undefined,instruction,model: subAgentModel?.model,diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex addc88b197d..0e00b1dca1a 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -24,7 +24,11 @@ import {} from '@lobechat/builtin-tool-self-iteration';import { TaskIdentifier } from '@lobechat/builtin-tool-task';import { builtinTools, manualModeExcludeToolIds } from '@lobechat/builtin-tools';-import { isHeterogeneousAgentModelId, LOADING_FLAT } from '@lobechat/const';+import {+ isHeterogeneousAgentModelId,+ LOADING_FLAT,+ resolveSubAgentChatConfig,+} from '@lobechat/const';import {type AgentGroupConfig,type AgentManagementContext,@@ -53,6 +57,7 @@ import type {ExecSubAgentResult,ExecVirtualSubAgentParams,LobeAgentAgencyConfig,+ LobeAgentChatConfig,LobeAgentConfig,MessagePluginItem,RuntimeMentionedAgent,@@ -351,6 +356,12 @@ interface InternalExecAgentParams extends ExecAgentParams {botContext?: ChatTopicBotContext;/** Bot platform context for injecting platform capabilities (e.g. markdown support) */botPlatformContext?: BotPlatformContext;+ /**+ * chatConfig overrides (thinking / reasoning-effort extend params) merged over+ * the executing agent's own chatConfig, skipping nulled keys. Internal-only:+ * set by the callSubAgent thread-run path, never client-passable.+ */+ chatConfigOverride?: Partial<LobeAgentChatConfig> | null;/** Cron job ID that triggered this execution (if trigger is 'cron') */cronJobId?: string;/** Disable only local-system while preserving other tools. Useful for signal-only evals. */@@ -1193,6 +1204,7 @@ export class AiAgentService {functionTools,hooks,instructions,+ chatConfigOverride,model: modelOverride,provider: providerOverride,stream,@@ -1349,6 +1361,16 @@ export class AiAgentService {};}+ // callSubAgent thinking / reasoning-effort overrides. A virtual sub-agent+ // executes the same agent row, so `agentConfig.chatConfig` here IS the+ // parent's chatConfig — merging the `agencyConfig.subagent.chatConfig`+ // patch over it yields the sub-agent's effective config.+ if (chatConfigOverride) {+ agentConfig.chatConfig =+ resolveSubAgentChatConfig(agentConfig.chatConfig, chatConfigOverride) ??+ agentConfig.chatConfig;+ }+// Persistence-attribution agent id. Background Agent Signal runs (memory /// skill / self-reflection) execute under a builtin slug, so `resolvedAgentId`// is the builtin agent — but the run's persisted messages, like its operation@@ -4532,6 +4554,7 @@ export class AiAgentService {*/execVirtualSubAgent = async (params: ExecVirtualSubAgentParams): Promise<ExecSubAgentResult> =>this.execAgentThreadRun(params, {+ chatConfig: params.chatConfig,isSubAgent: true,logScope: 'execVirtualSubAgent',// Sub-agent model is resolved at the spawn site (callSubAgent runner) from@@ -4743,6 +4766,12 @@ export class AiAgentService {* `resumeParentOnComplete` is set.*/bridgeHookFactory?: (threadId: string) => AgentHook;+ /**+ * chatConfig overrides (thinking / reasoning-effort extend params) for+ * the spawned run, merged over the executing agent's own chatConfig.+ * Only set by the callSubAgent path.+ */+ chatConfig?: Partial<LobeAgentChatConfig> | null;isSubAgent: boolean;logScope: 'execSubAgent' | 'execVirtualSubAgent';/**@@ -4871,6 +4900,7 @@ export class AiAgentService {agentId,appContext,autoStart: true,+ chatConfigOverride: options.chatConfig,hooks,// Explicit sub-agent model override resolved at the spawn site.model: options.model,diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 90c592a15e7..14f099e335f 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -922,7 +922,8 @@"settingModel.reasoningEffort.options.low": "Low","settingModel.reasoningEffort.options.medium": "Medium","settingModel.reasoningEffort.title": "Reasoning Effort",- "settingModel.subAgentModel.desc": "The default model used by sub-agents this agent spawns. Sub-agents run on a lightweight model by default instead of inheriting this agent’s main model.",+ "settingModel.subAgentModel.desc": "The model used by sub-agents this agent spawns. By default sub-agents follow the main agent’s current model (same provider, same model); pick a model here to override, or clear the selection to follow again.",+ "settingModel.subAgentModel.followParent": "Follow main agent model","settingModel.submit": "Update Model Settings","settingModel.temperature.desc": "The higher the value, the more creative and imaginative the responses; the lower the value, the more rigorous the responses.","settingModel.temperature.title": "Creativity Level",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex a6abf091e13..b417bcf947d 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -922,7 +922,8 @@"settingModel.reasoningEffort.options.low": "低","settingModel.reasoningEffort.options.medium": "中","settingModel.reasoningEffort.title": "推理强度",- "settingModel.subAgentModel.desc": "该助手派生的子助手默认使用的模型。子助手默认运行在轻量模型上,而非继承本助手的主模型。",+ "settingModel.subAgentModel.desc": "该助手派生的子助手使用的模型。子助手默认跟随主助手当前模型(同供应商同模型);在此选择模型可覆盖默认行为,清除选择即恢复跟随。",+ "settingModel.subAgentModel.followParent": "跟随主助手模型","settingModel.submit": "更新模型设置","settingModel.temperature.desc": "数值越大,回答越有创意和想象力;数值越小,回答越严谨","settingModel.temperature.title": "创意活跃度",diff --git a/packages/const/src/settings/llm.ts b/packages/const/src/settings/llm.tsindex efa71a7710f..f566c966962 100644--- a/packages/const/src/settings/llm.ts+++ b/packages/const/src/settings/llm.ts@@ -1,14 +1,14 @@import { DEFAULT_PROVIDER } from '@lobechat/business-const';-import type { LobeAgentAgencyConfig } from '@lobechat/types';+import type { LobeAgentAgencyConfig, LobeAgentChatConfig } from '@lobechat/types';export { DEFAULT_MINI_MODEL, DEFAULT_MODEL } from '@lobechat/business-const';export const DEFAULT_EMBEDDING_MODEL = 'text-embedding-3-small';/**- * Default model for sub-agents spawned via `lobe-agent.callSubAgent`.- * Sub-agents run on a lightweight model by default instead of inheriting the- * parent agent's main model. Overridable per agent via `agencyConfig.subagent`.+ * Last-resort model for sub-agents spawned via `lobe-agent.callSubAgent`, used+ * only when neither an explicit `agencyConfig.subagent` override nor the+ * parent's effective model is available at the spawn site.** Paired with `DEFAULT_PROVIDER` rather than a dedicated sub-agent provider, so* a build that swaps `@lobechat/business-const` (the cloud one routes through@@ -18,18 +18,64 @@ export const DEFAULT_EMBEDDING_MODEL = 'text-embedding-3-small';export const DEFAULT_SUB_AGENT_MODEL = 'deepseek-v4-flash';/**- * Resolve the model a sub-agent runs on from the spawning agent's- * `agencyConfig.subagent`, falling back to the global default.+ * Resolve the model a sub-agent runs on, in precedence order:*- * Model and provider resolve as a pair: a config carrying a model but no- * provider would otherwise mix a custom model id with the default provider.+ * 1. Explicit `agencyConfig.subagent` override configured on the spawning agent.+ * 2. The parent run's effective model — same provider, same model. Multi-provider+ * setups otherwise strand sub-agents on a provider the user has moved away+ * from (Claude Code / Codex sub-agents inherit the parent model the same way).+ * 3. The global default, when the spawn site has no parent model at hand.+ *+ * Model and provider resolve as a pair: mixing one source's model id with+ * another source's provider would produce a `provider/model` combination the+ * user never configured.*/export const resolveSubAgentModel = (subagent: LobeAgentAgencyConfig['subagent'],-): { model: string; provider: string } =>- subagent?.model- ? { model: subagent.model, provider: subagent.provider || DEFAULT_PROVIDER }- : { model: DEFAULT_SUB_AGENT_MODEL, provider: DEFAULT_PROVIDER };+ parentModel?: { model?: string | null; provider?: string | null },+): { model: string; provider: string } => {+ if (subagent?.model)+ return { model: subagent.model, provider: subagent.provider || DEFAULT_PROVIDER };++ if (parentModel?.model)+ return { model: parentModel.model, provider: parentModel.provider || DEFAULT_PROVIDER };++ return { model: DEFAULT_SUB_AGENT_MODEL, provider: DEFAULT_PROVIDER };+};++/**+ * Resolve the effective chatConfig for a `callSubAgent` run: the parent's+ * chatConfig with the agent's `agencyConfig.subagent.chatConfig` overrides+ * (thinking / reasoning-effort extend params) merged on top.+ *+ * `null` / `undefined` override values are skipped rather than copied — a+ * cleared override falls back to the parent value, mirroring how a nulled+ * `subagent.model` falls back to following the parent model.+ */+/**+ * The chatConfig override to apply to a spawned sub-agent, gated on an explicit+ * `subagent.model`: the thinking / reasoning-effort overrides are configured in+ * the UI under the chosen override model, so once the model is cleared (back to+ * follow-parent) a stale `chatConfig` left behind by older writers must not+ * silently keep changing the sub-agent's behavior or cost.+ */+export const getSubAgentChatConfigOverride = (+ subagent: LobeAgentAgencyConfig['subagent'],+): Partial<LobeAgentChatConfig> | undefined =>+ subagent?.model ? (subagent.chatConfig ?? undefined) : undefined;++export const resolveSubAgentChatConfig = <T extends object>(+ parentChatConfig: T | null | undefined,+ override: Partial<T> | null | undefined,+): T | undefined => {+ if (!override) return parentChatConfig ?? undefined;++ const patch = Object.fromEntries(+ Object.entries(override).filter(([, value]) => value !== null && value !== undefined),+ );++ return { ...parentChatConfig, ...patch } as T;+};export const DEFAULT_RERANK_MODEL = 'rerank-english-v3.0';export const DEFAULT_RERANK_PROVIDER = 'cohere';diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 140b34bce5b..5a8fa5faf37 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1028,7 +1028,8 @@ export default {'settingModel.reasoningEffort.options.medium': 'Medium','settingModel.reasoningEffort.title': 'Reasoning Effort','settingModel.subAgentModel.desc':- 'The default model used by sub-agents this agent spawns. Sub-agents run on a lightweight model by default instead of inheriting this agent’s main model.',+ 'The model used by sub-agents this agent spawns. By default sub-agents follow the main agent’s current model (same provider, same model); pick a model here to override, or clear the selection to follow again.',+ 'settingModel.subAgentModel.followParent': 'Follow main agent model','settingModel.submit': 'Update Model Settings','settingModel.temperature.desc':'The higher the value, the more creative and imaginative the responses; the lower the value, the more rigorous the responses.',diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.tsindex dfdcd3fb575..f1ee4572d5a 100644--- a/packages/types/src/agent/agencyConfig.ts+++ b/packages/types/src/agent/agencyConfig.ts@@ -1,4 +1,5 @@import type { WorkingDirConfigValue } from '../device';+import type { LobeAgentChatConfig } from './chatConfig';/*** Selector value that means "do not override the underlying CLI".@@ -664,14 +665,24 @@ export interface LobeAgentAgencyConfig {*/modelSelectionPolicy?: AgentModelSelectionPolicy;/**- * Default model used by sub-agents this agent spawns via- * `lobe-agent.callSubAgent`. When unset, sub-agents fall back to the global- * default (`DEFAULT_SUB_AGENT_MODEL`, e.g. deepseek-v4-flash) rather than- * inheriting the parent agent's main model. Configurable in the params panel.+ * Model override for sub-agents this agent spawns via+ * `lobe-agent.callSubAgent`. When unset (or nulled to clear a previous+ * override), sub-agents follow the parent run's effective model — same+ * provider, same model. Configurable in the params panel; `null` rather than+ * `undefined` marks the cleared state because the config deep-merge skips+ * `undefined` and would resurrect the old override.*/subagent?: {- model?: string;- provider?: string;+ /**+ * chatConfig overrides (thinking / reasoning-effort extend params) for the+ * overridden sub-agent model, merged over the parent's chatConfig at spawn.+ * Only meaningful together with a `model` override — when sub-agents follow+ * the parent model they inherit the parent's chatConfig wholesale, so the+ * effort follows automatically.+ */+ chatConfig?: Partial<LobeAgentChatConfig> | null;+ model?: string | null;+ provider?: string | null;};/*** Ad-hoc verify criteria mounted directly on this agent, in addition to anydiff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex d64c283f677..1f23119d885 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -1,3 +1,4 @@+import type { LobeAgentChatConfig } from '../agent/chatConfig';import type { WorkingDirConfig } from '../device';import type { TaskDetail, UIChatMessage } from '../message';import type { ChatTopic } from '../topic';@@ -399,15 +400,21 @@ export interface ExecSubAgentParams {export interface ExecVirtualSubAgentParams {/** The agent ID to execute */agentId: string;+ /**+ * chatConfig overrides (thinking / reasoning-effort extend params) for the+ * sub-agent run, from the parent agent's `agencyConfig.subagent.chatConfig`.+ * Merged over the executing agent's own chatConfig, skipping nulled keys.+ */+ chatConfig?: Partial<LobeAgentChatConfig> | null;/** The Group ID inherited from the parent operation, when present */groupId?: string;/** Instruction/prompt for the virtual sub-agent */instruction: string;/*** Model the sub-agent should run on, resolved by the spawn site from the- * parent agent's `agencyConfig.subagent`. Passed explicitly so the execution- * side never re-reads the parent config. Falls back to the global default- * (`DEFAULT_SUB_AGENT_MODEL`) at the spawn site when unset.+ * parent agent's `agencyConfig.subagent` (explicit override or the parent's+ * effective model). Passed explicitly so the execution side never re-reads+ * the parent config.*/model?: string;/** The parent placeholder tool message ID */diff --git a/src/features/ChatInput/ActionBar/Params/Controls.tsx b/src/features/ChatInput/ActionBar/Params/Controls.tsxindex b3386af0549..5c2a50585f7 100644--- a/src/features/ChatInput/ActionBar/Params/Controls.tsx+++ b/src/features/ChatInput/ActionBar/Params/Controls.tsx@@ -1,4 +1,8 @@-import { DEFAULT_AGENT_CONFIG, resolveSubAgentModel } from '@lobechat/const';+import {+ DEFAULT_AGENT_CONFIG,+ resolveSubAgentChatConfig,+ resolveSubAgentModel,+} from '@lobechat/const';import { Flexbox, Icon, SliderWithInput, TextArea } from '@lobehub/ui';import { Select, Switch } from '@lobehub/ui/base-ui';import { Form as AntdForm } from 'antd';@@ -18,9 +22,10 @@ import ControlsForm from '@/features/ModelSwitchPanel/components/ControlsForm';import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';import { useUserStore } from '@/store/user';import { systemAgentSelectors } from '@/store/user/selectors';-import type { LobeAgentConfig } from '@/types/agent';+import type { LobeAgentChatConfig, LobeAgentConfig } from '@/types/agent';import { useAgentId } from '../../hooks/useAgentId';import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';@@ -616,10 +621,26 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove? t('settingModel.params.panel.agentTitle'): t('settingModel.params.panel.title');- // Model the sub-agents this agent spawns via callSubAgent run on. Resolved- // through the same helper the runtime uses, so the panel can't show a model- // the run won't actually use.- const subAgentModelValue = resolveSubAgentModel(config.agencyConfig?.subagent);+ // Explicit sub-agent model override, if any. When unset, sub-agents follow+ // the parent run's effective model — rendered as the select's empty state+ // (placeholder) rather than a concrete model, so the panel never shows a+ // model the run won't actually use.+ const subAgentModelValue = config.agencyConfig?.subagent?.model+ ? resolveSubAgentModel(config.agencyConfig.subagent)+ : undefined;+ // Effective sub-agent chatConfig: the parent's chatConfig with the+ // `agencyConfig.subagent.chatConfig` overrides merged on top — the exact+ // config the sub-agent run uses, so the controls below are WYSIWYG.+ const subAgentChatConfig = useMemo(+ () => resolveSubAgentChatConfig(config.chatConfig, config.agencyConfig?.subagent?.chatConfig),+ [config.chatConfig, config.agencyConfig?.subagent?.chatConfig],+ );+ const subAgentHasModelConfig = useAiInfraStore(+ aiModelSelectors.isModelHasExtendParams(+ subAgentModelValue?.model || '',+ subAgentModelValue?.provider || '',+ ),+ );const handleToggle = useCallback(async (key: ParamKey, enabled: boolean) => {@@ -722,6 +743,29 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove[canCreate, setUpdating, updateAgentConfig],);+ // Back to "follow the main agent model". `null` rather than `undefined`: the+ // config deep-merge skips `undefined` keys, which would keep the old override.+ // The thinking overrides are cleared along with the model they were set for.+ const handleSubAgentModelClear = useCallback(async () => {+ if (!canCreate) return;+ setUpdating(true);+ try {+ await updateAgentConfig({+ agencyConfig: { subagent: { chatConfig: null, model: null, provider: null } },+ });+ } finally {+ setUpdating(false);+ }+ }, [canCreate, setUpdating, updateAgentConfig]);++ const handleSubAgentChatConfigChange = useCallback(+ async (patch: Partial<LobeAgentChatConfig>) => {+ if (!canCreate) return;+ await updateAgentConfig({ agencyConfig: { subagent: { chatConfig: patch } } });+ },+ [canCreate, updateAgentConfig],+ );+const handleAdvancedOpenChange = useCallback(() => {setAdvancedOpen((open) => {const nextOpen = !open;@@ -864,11 +908,28 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popovetooltip={t('settingModel.subAgentModel.desc')}><ModelSelect+ allowCleardisabled={!canCreate}+ placeholder={t('settingModel.subAgentModel.followParent')}style={{ width: '100%' }}value={subAgentModelValue}onChange={handleSubAgentModelChange}+ onClear={handleSubAgentModelClear}/>+ {/* Thinking / reasoning-effort controls for the overridden+ * sub-agent model. Hidden while following the parent model —+ * the sub-agent then inherits the parent's chatConfig wholesale,+ * so the main panel's controls already describe it. */}+ {subAgentModelValue && subAgentHasModelConfig && (+ <ControlsForm+ chatConfig={subAgentChatConfig}+ disabled={!canCreate}+ model={subAgentModelValue.model}+ provider={subAgentModelValue.provider}+ onChatConfigChange={handleSubAgentChatConfigChange}+ onUpdatingChange={setUpdating}+ />+ )}</ControlRow>)}</div>diff --git a/src/features/ModelSelect/index.tsx b/src/features/ModelSelect/index.tsxindex dc3a1ec9c4a..1dbaf26555d 100644--- a/src/features/ModelSelect/index.tsx+++ b/src/features/ModelSelect/index.tsx@@ -79,15 +79,18 @@ interface ModelOption {interface ModelSelectProps extends Pick<SelectProps,- 'disabled' | 'loading' | 'size' | 'style' | 'variant'+ 'allowClear' | 'disabled' | 'loading' | 'placeholder' | 'size' | 'style' | 'variant'> {defaultValue?: { model: string; provider?: string };initialWidth?: boolean;modelType?: 'chat' | 'embedding';onChange?: (props: { model: string; provider: string }) => void;+ /** Fired when the selection is cleared via `allowClear`. */+ onClear?: () => void;popupWidth?: number;requiredAbilities?: (keyof EnabledProviderWithModels['children'][number]['abilities'])[];showAbility?: boolean;+ /** `undefined` renders the empty state (`placeholder`) instead of a selection. */value?: { model: string; provider?: string };}@@ -95,6 +98,9 @@ const ModelSelect = memo<ModelSelectProps>(({value,onChange,+ onClear,+ allowClear,+ placeholder,showAbility: _showAbility = true,requiredAbilities,loading,@@ -330,15 +336,17 @@ const ModelSelect = memo<ModelSelectProps>(return (<TooltipGroup><Select+ allowClear={allowClear}className={styles.select}- defaultValue={`${value?.provider}/${value?.model}`}+ defaultValue={value ? `${value.provider}/${value.model}` : null}disabled={disabled}loading={loading || enabling}options={finalOptions}+ placeholder={placeholder}popupClassName={styles.popup}popupMatchSelectWidth={popupWidth === undefined ? false : popupWidth}size={size}- value={`${value?.provider}/${value?.model}`}+ value={value ? `${value.provider}/${value.model}` : null}variant={variant}optionRender={(option) => {if ((option as unknown as { __stale?: boolean }).__stale) return option.label;@@ -357,6 +365,10 @@ const ModelSelect = memo<ModelSelectProps>(...style,}}onChange={(next, option) => {+ if (next == null) {+ onClear?.();+ return;+ }if (next === STALE_ACTION_VALUE) {if (staleState?.status === 'redirected' &&diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsxindex efce3044fe4..93e0db078cc 100644--- a/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx+++ b/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx@@ -55,8 +55,18 @@ import ThinkingLevelSlider from './ThinkingLevelSlider';import ThinkingSlider from './ThinkingSlider';interface ControlsFormProps {+ /**+ * Override the config source. Defaults to the agent's own chatConfig; the+ * sub-agent params panel passes the sub-agent's effective (merged) config.+ */+ chatConfig?: LobeAgentChatConfig;disabled?: boolean;model?: string;+ /**+ * Override the write sink. Defaults to updating the agent's chatConfig; the+ * sub-agent params panel redirects writes into `agencyConfig.subagent.chatConfig`.+ */+ onChatConfigChange?: (patch: Partial<LobeAgentChatConfig>) => Promise<void>;onUpdatingChange?: (updating: boolean) => void;provider?: string;}@@ -82,7 +92,14 @@ const resolveEnableAdaptiveThinkingInitialValue = (config: LobeAgentChatConfig,};const ControlsForm = memo<ControlsFormProps>(- ({ disabled, model: modelProp, onUpdatingChange, provider: providerProp }) => {+ ({+ chatConfig: chatConfigProp,+ disabled,+ model: modelProp,+ onChatConfigChange,+ onUpdatingChange,+ provider: providerProp,+ }) => {const { t } = useTranslation('chat');const agentId = useAgentId();const { updateAgentChatConfig } = useUpdateAgentConfig();@@ -94,10 +111,11 @@ const ControlsForm = memo<ControlsFormProps>(const provider = providerProp ?? agentProvider;const [form] = Form.useForm();- const config = useAgentStore(+ const storeConfig = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s),isEqual,);+ const config = chatConfigProp ?? storeConfig;const modelExtendParams = useAiInfraStore(aiModelSelectors.modelExtendParams(model, provider));const initialValues = useMemo(() => {@@ -555,7 +573,7 @@ const ControlsForm = memo<ControlsFormProps>(if (disabled) return;onUpdatingChange?.(true);try {- await updateAgentChatConfig(values);+ await (onChatConfigChange ?? updateAgentChatConfig)(values);} finally {onUpdatingChange?.(false);}diff --git a/src/store/chat/slices/agentRun/actions/__tests__/subAgentModel.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/subAgentModel.test.tsindex f92297602b9..f660a901753 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/subAgentModel.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/subAgentModel.test.ts@@ -1,4 +1,10 @@-import { DEFAULT_SUB_AGENT_MODEL, resolveSubAgentModel } from '@lobechat/const';+import { DEFAULT_PROVIDER } from '@lobechat/business-const';+import {+ DEFAULT_SUB_AGENT_MODEL,+ getSubAgentChatConfigOverride,+ resolveSubAgentChatConfig,+ resolveSubAgentModel,+} from '@lobechat/const';import { beforeEach, describe, expect, it, vi } from 'vitest';import * as agentConfigResolver from '@/services/chat/mecha/agentConfigResolver';@@ -69,24 +75,87 @@ describe('sub-agent model resolution', () => {});describe('resolveSubAgentModel', () => {- it('falls back to the global default when the agent has no subagent config', () => {+ const PARENT = { model: 'claude-sonnet-5', provider: 'anthropic' };++ it('follows the parent effective model when the agent has no subagent config', () => {+ expect(resolveSubAgentModel(undefined, PARENT)).toEqual(PARENT);+ });++ it('follows the parent after the override was cleared (nulled) in settings', () => {+ expect(resolveSubAgentModel({ model: null, provider: null }, PARENT)).toEqual(PARENT);+ });++ it('prefers the configured override over the parent model', () => {+ expect(resolveSubAgentModel({ model: 'gpt-5.4', provider: 'openai' }, PARENT)).toEqual({+ model: 'gpt-5.4',+ provider: 'openai',+ });+ });++ it('falls back to the global default when no override and no parent model exist', () => {expect(resolveSubAgentModel(undefined)).toEqual({model: DEFAULT_SUB_AGENT_MODEL,- provider: 'deepseek',+ provider: DEFAULT_PROVIDER,});});- it('uses the configured override', () => {- expect(resolveSubAgentModel({ model: 'gpt-5.4', provider: 'openai' })).toEqual({+ it('pairs a provider-less parent model with the default provider, not a foreign one', () => {+ // e.g. a legacy topic-pinned model whose provider column is empty+ expect(resolveSubAgentModel(undefined, { model: 'gpt-5.4', provider: '' })).toEqual({model: 'gpt-5.4',- provider: 'openai',+ provider: DEFAULT_PROVIDER,});});it('ignores a provider-only config rather than pairing it with a foreign model', () => {- expect(resolveSubAgentModel({ provider: 'openai' })).toEqual({- model: DEFAULT_SUB_AGENT_MODEL,- provider: 'deepseek',+ expect(resolveSubAgentModel({ provider: 'openai' }, PARENT)).toEqual(PARENT);+ });+});++describe('getSubAgentChatConfigOverride', () => {+ const CHAT_CONFIG = { thinkingLevel: 'low' } as any;++ it('forwards the chatConfig while an explicit sub-agent model is configured', () => {+ expect(getSubAgentChatConfigOverride({ chatConfig: CHAT_CONFIG, model: 'gpt-5.4' })).toEqual(+ CHAT_CONFIG,+ );+ });++ it('drops a stale chatConfig once the model override is cleared or absent', () => {+ // A follow-parent sub-agent must not silently keep old thinking overrides.+ expect(getSubAgentChatConfigOverride({ chatConfig: CHAT_CONFIG, model: null })).toBeUndefined();+ expect(getSubAgentChatConfigOverride({ chatConfig: CHAT_CONFIG })).toBeUndefined();+ expect(getSubAgentChatConfigOverride(undefined)).toBeUndefined();+ });+});++describe('resolveSubAgentChatConfig', () => {+ const PARENT_CHAT_CONFIG = { enableReasoning: true, thinkingLevel: 'high' };++ it('returns the parent chatConfig untouched when there is no override', () => {+ expect(resolveSubAgentChatConfig(PARENT_CHAT_CONFIG, undefined)).toBe(PARENT_CHAT_CONFIG);+ expect(resolveSubAgentChatConfig(PARENT_CHAT_CONFIG, null)).toBe(PARENT_CHAT_CONFIG);+ });++ it('merges override keys over the parent chatConfig', () => {+ expect(resolveSubAgentChatConfig(PARENT_CHAT_CONFIG, { thinkingLevel: 'minimal' })).toEqual({+ enableReasoning: true,+ thinkingLevel: 'minimal',+ });+ });++ it('skips nulled override keys so they fall back to the parent value', () => {+ expect(+ resolveSubAgentChatConfig(PARENT_CHAT_CONFIG, {+ enableReasoning: null as unknown as boolean,+ thinkingLevel: 'low',+ }),+ ).toEqual({ enableReasoning: true, thinkingLevel: 'low' });+ });++ it('builds a config from the override alone when the parent has none', () => {+ expect(resolveSubAgentChatConfig(undefined, { thinkingLevel: 'low' })).toEqual({+ thinkingLevel: 'low',});});});diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 07f7bff1cd5..a6ccfcf7bd7 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -15,11 +15,17 @@ import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';import { createPathScopeAudit } from '@lobechat/builtin-tool-local-system';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';-import { isDesktop, resolveSubAgentModel } from '@lobechat/const';+import {+ getSubAgentChatConfigOverride,+ isDesktop,+ resolveSubAgentChatConfig,+ resolveSubAgentModel,+} from '@lobechat/const';import { type ToolsEngine } from '@lobechat/context-engine';import { buildTaskDetailPrompt, buildTaskListPrompt } from '@lobechat/prompts';import {type ConversationContext,+ type LobeAgentChatConfig,type MessageMetadata,type RunSubAgentResult,type RuntimeInitialContext,@@ -120,6 +126,7 @@ export class StreamingExecutorActionImpl {subAgentId: paramSubAgentId,isSubAgent,modelOverride,+ chatConfigOverride,}: {messages: UIChatMessage[];parentMessageId: string;@@ -139,6 +146,8 @@ export class StreamingExecutorActionImpl {isSubAgent?: boolean;/** Model/provider the run is forced onto, resolved by the caller that spawns it. */modelOverride?: { model: string; provider: string };+ /** chatConfig patch merged over the resolved chatConfig (sub-agent thinking overrides). */+ chatConfigOverride?: Partial<LobeAgentChatConfig> | null;}): {state: AgentState;context: AgentRuntimeContext;@@ -186,10 +195,19 @@ export class StreamingExecutorActionImpl {const topicModel = topicId ? topicSelectors.getTopicModelById(topicId)(this.#get()) : undefined;const modelResolution = modelOverride ?? topicModel;const agentConfig: ResolvedAgentConfig =- modelResolution && resolvedAgentConfig.agentConfig+ (modelResolution || chatConfigOverride) && resolvedAgentConfig.agentConfig? {...resolvedAgentConfig,- agentConfig: { ...resolvedAgentConfig.agentConfig, ...modelResolution },+ ...(modelResolution+ ? { agentConfig: { ...resolvedAgentConfig.agentConfig, ...modelResolution } }+ : {}),+ ...(chatConfigOverride+ ? {+ chatConfig:+ resolveSubAgentChatConfig(resolvedAgentConfig.chatConfig, chatConfigOverride) ??+ resolvedAgentConfig.chatConfig,+ }+ : {}),}: resolvedAgentConfig;@@ -490,6 +508,12 @@ export class StreamingExecutorActionImpl {* keep their own model.*/modelOverride?: { model: string; provider: string };+ /**+ * chatConfig overrides (thinking / reasoning-effort extend params) merged+ * over the resolved chatConfig, skipping nulled keys. Passed by+ * `runClientSubAgent` from the parent's `agencyConfig.subagent.chatConfig`.+ */+ chatConfigOverride?: Partial<LobeAgentChatConfig> | null;userMessageId?: string;}): Promise<{ cost?: Cost; model?: string; provider?: string; usage?: Usage } | void> => {const {@@ -619,6 +643,7 @@ export class StreamingExecutorActionImpl {subAgentId, // Pass subAgentId for agent config retrieval (behavior depends on scope)isSubAgent, // Pass isSubAgent to filter out lobe-agent tool in sub-agent contextmodelOverride: params.modelOverride,+ chatConfigOverride: params.chatConfigOverride,});if (params.skipCreateFirstMessage) {@@ -1007,15 +1032,25 @@ export class StreamingExecutorActionImpl {}// 6. Run the sub-agent with the current client runtime.- // A sub-agent runs on its own model rather than inheriting the parent's- // main one, resolved here at the spawn site from the parent's- // `agencyConfig.subagent` (mirrors the server's callSubAgent runner).+ // The model is resolved here at the spawn site (mirrors the server's+ // callSubAgent runner): an explicit `agencyConfig.subagent` override+ // wins, otherwise the sub-agent follows the parent's *effective* model+ // — topic-pinned model over the agent default, the same precedence+ // internal_createAgentState applies to the parent run itself.const parentAgentConfig = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());+ const parentEffectiveModel =+ topicSelectors.getTopicModelById(topicId)(this.#get()) ?? parentAgentConfig;const runtimeResult = await this.#get().executeClientAgent({+ chatConfigOverride: getSubAgentChatConfigOverride(+ parentAgentConfig?.agencyConfig?.subagent,+ ),context: subContext,isSubAgent: true,messages: subMessages,- modelOverride: resolveSubAgentModel(parentAgentConfig?.agencyConfig?.subagent),+ modelOverride: resolveSubAgentModel(+ parentAgentConfig?.agencyConfig?.subagent,+ parentEffectiveModel,+ ),operationId: taskOperationId,parentMessageId: userMessageId,parentMessageType: 'user',