Skip to content

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

✨ feat(agent): add configurable default model for sub-agents (#16552)

Arvin Xu711297cf55ff
diff --git a/.agents/skills/agent-testing/references/common-mistakes.md b/.agents/skills/agent-testing/references/common-mistakes.md
index cade14941f8..4a107b6c563 100644
--- a/.agents/skills/agent-testing/references/common-mistakes.md
+++ b/.agents/skills/agent-testing/references/common-mistakes.md
@@ -624,3 +624,46 @@ tree, confirmed via one structured question and labeled as a guess (never
executed on unconfirmed — Case 3) > an open question only as last resort. Read
the living logs once the target is known, and never narrate skill-internal
setup — the first visible message is about the user's test.
+
+---
+
+## Case 23 — Building an elaborate mock before checking whether the env already has the real thing
+
+**Wrong approach**: needing a working LLM for an agent-runtime test and finding no provider key in
+the shell env, I built an OpenAI-compatible mock server, wrote a key-vault encryption script, and
+seeded `user_settings.key_vaults` to point `deepseek` at it — then ran the agent and watched the
+mock receive **zero** requests while the run produced real, rich LLM output.
+
+**Why it's wrong**: the seeded test user _already had a real DeepSeek key_ configured — in
+`ai_providers`, which is what the runtime actually reads (not `user_settings.keyVaults`). Two
+wasted assumptions stacked: that no credential existed, and that I knew which table supplies it.
+Neither was measured; both were inferred from an `env | grep`.
+
+**What it breaks**: a chunk of the run spent building an apparatus the test didn't need, plus a
+fixture (mock server + an encrypted row) that had to be torn down afterwards. Worse, had the mock
+_partially_ worked, the run would have silently verified a fake path.
+
+**Correct approach**: before constructing any mock, **probe the env for the real capability** —
+query the provider tables (`select id, key_vaults is not null from ai_providers where user_id=…`),
+or just fire one cheap real turn and see whether it completes. Only mock what is provably absent.
+And when a mock records nothing while the feature clearly works, do not shrug — that is the signal
+that the mock is _not in the path_, and everything you "verified" through it is unverified.
+
+---
+
+## Case 24 — Asserting a fixture landed because the DB write succeeded
+
+**Wrong approach**: writing `agents.agency_config = NULL` directly in Postgres, reloading the page,
+and reading the "sub-agent model" the UI displayed — then treating the stale value it showed as a
+product bug in the fallback logic.
+
+**Why it's wrong**: the client's persisted SWR cache (IndexedDB + localStorage) kept serving the old
+`agencyConfig`, and even `internal_refreshAgentConfig` did not dislodge it. `UPDATE 1` in psql proves
+the row changed; it proves nothing about what the app _is running on_. A fixture bug in
+product-bug costume is the most expensive kind — I nearly filed my own fixture as a regression.
+
+**Correct approach**: after any direct-DB fixture write, cold-load (clear localStorage /
+sessionStorage / IndexedDB / caches, re-seed auth, reopen) and then **assert the fixture in the store
+before asserting anything downstream of it** (`__LOBE_STORES.agent().agentMap[id]`). See
+probe-mock-patterns C11. Rule of thumb: the DB is where you _wrote_ it; the store is where the
+behavior _reads_ it — verify at the layer the behavior reads.
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index ab2f59098f8..9bcbc960de5 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -1371,3 +1371,28 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h
clearing with `undefined` is a **no-op** and the field must be set to `null`.
- **Test for it**: assert the field is `null` (not `undefined`) after the consume action; a test that
only checks "the request was acted on" passes in both the broken and fixed versions.
+
+### E30. ✅ "Failed to fetch dynamically imported module" points at the WRONG file — the failure is downstream
+
+- **Situation**: the SPA renders as a Case-1 blank page; console names a dynamic-import route module.
+- **Doesn't work**: investigating only the named module. It may return 200 because the actual failure
+ is in its transitive import graph; changing `?t=` values are ordinary HMR invalidation.
+- **Works**: take and read a screenshot. Vite's HMR overlay contains the real transform/import error.
+ After a rebase or pull, refresh dependencies and restart before treating the blank SPA as a code bug.
+
+### C11. Persisted SWR cache serves a STALE agent config after a direct DB write
+
+- **Situation**: seeding `agents.agency_config` or `agents.model` directly in Postgres, then using
+ the app to drive an assertion.
+- **Doesn't work**: reload or `internal_refreshAgentConfig`; IndexedDB/localStorage can retain the
+ previous config and make a fixture issue look like a product regression.
+- **Works**: cold-load by clearing browser storage/caches, re-seed auth, reopen, and assert the
+ fixture in `__LOBE_STORES.agent().agentMap[id]` before testing downstream behavior.
+
+### E31. Web agent turns run the CLIENT runtime — no `agent_operations` row will appear
+
+- **Situation**: driving a real web turn and polling `agent_operations` for the run.
+- **Doesn't work**: waiting for a server operation when the web surface dispatched the client runtime.
+- **Works**: use client observables (`messages.model`, thread ids, and chat-store operations) for web;
+ use CLI/server execution and `agent_operations` for the server runtime. A change affecting both paths
+ needs evidence from both paths.
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
index c1d1a4c99c1..cf183495d5c 100644
--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
@@ -1,8 +1,9 @@
import { type AgentState } from '@lobechat/agent-runtime';
import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';
+import { resolveSubAgentModel } from '@lobechat/const';
import { type OperationToolSet } from '@lobechat/context-engine';
import { type ToolType } from '@lobechat/observability-otel/modules/agent-runtime';
-import { type ChatToolPayload } from '@lobechat/types';
+import { type ChatToolPayload, type LobeAgentConfig } from '@lobechat/types';
import debug from 'debug';
import { type LobeChatDatabase } from '@/database/type';
@@ -115,8 +116,22 @@ export const buildServerVirtualSubAgentRunner = (
const topicId = ctx.topicId ?? state.metadata?.topicId;
if (!agentId || !topicId) return undefined;
+ const parentAgentConfig = state.metadata?.agentConfig as LobeAgentConfig | undefined;
+
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.
+ // - `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.
+ // Resolved here at the spawn site so the execution side never has to
+ // re-derive it from the parent config.
+ const subAgentModel = targetAgentId
+ ? undefined
+ : resolveSubAgentModel(parentAgentConfig?.agencyConfig?.subagent);
+
// 1. Create the pending placeholder tool message (mirrors the normal
// tool-message shape in call_tool) that anchors the isolation thread
// and renders a loading state until the bridge backfills it.
@@ -140,8 +155,10 @@ export const buildServerVirtualSubAgentRunner = (
agentId: targetAgentId ?? agentId,
groupId: state.metadata?.groupId ?? undefined,
instruction,
+ model: subAgentModel?.model,
parentMessageId: placeholder.id,
parentOperationId: ctx.operationId,
+ provider: subAgentModel?.provider,
timeout,
title: description,
topicId,
diff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts
index 233ca13bd12..bf7081d1ff8 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts
@@ -177,6 +177,9 @@ beforeEach(async () => {
const [agent] = await serverDB
.insert(agents)
.values({
+ agencyConfig: {
+ subagent: { model: 'gpt-5-pro', provider: 'openai' },
+ },
chatConfig: {},
model: 'gpt-5-pro',
plugins: [],
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index f118fdaf8f9..f17626dcd1e 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1217,7 +1217,10 @@ export class AiAgentService {
// documents stay keyed on `resolvedAgentId`.
const persistAgentId = appContext?.agentSignal?.agentId ?? resolvedAgentId;
- // Apply per-call model/provider overrides (e.g. from task.config)
+ // Apply per-call model/provider overrides. Sources include task.config and
+ // the callSubAgent spawn site, which resolves the sub-agent's default model
+ // from the parent agent's `agencyConfig.subagent` and passes it explicitly —
+ // so this execution path never has to special-case sub-agents.
if (modelOverride) agentConfig.model = modelOverride;
if (providerOverride) agentConfig.provider = providerOverride;
@@ -4091,6 +4094,11 @@ export class AiAgentService {
this.execAgentThreadRun(params, {
isSubAgent: true,
logScope: 'execVirtualSubAgent',
+ // Sub-agent model is resolved at the spawn site (callSubAgent runner) from
+ // the parent agent's `agencyConfig.subagent` and threaded through here as an
+ // explicit override, so execAgent never re-reads the parent config.
+ model: params.model,
+ provider: params.provider,
resumeParentOnComplete: true,
});
@@ -4297,6 +4305,14 @@ export class AiAgentService {
bridgeHookFactory?: (threadId: string) => AgentHook;
isSubAgent: boolean;
logScope: 'execSubAgent' | 'execVirtualSubAgent';
+ /**
+ * Explicit model/provider override for the spawned run. The callSubAgent
+ * spawn site resolves the sub-agent model from the parent agent's config
+ * and passes it here; left undefined for group members (they keep their
+ * own model).
+ */
+ model?: string;
+ provider?: string;
/**
* Marks the run's orchestration role on its operation metadata. Isolated
* group members pass `'member'` so the inactivity-watchdog abandon path can
@@ -4416,8 +4432,11 @@ export class AiAgentService {
appContext,
autoStart: true,
hooks,
+ // Explicit sub-agent model override resolved at the spawn site.
+ model: options.model,
parentOperationId,
prompt: instruction,
+ provider: options.provider,
trigger: inheritedTrigger,
userInterventionConfig: { approvalMode: 'headless' },
});
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index c90caeada78..6f780fd51fa 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -816,6 +816,7 @@
"settingModel.params.panel.historyLimit": "Limit History Messages",
"settingModel.params.panel.openness": "Openness",
"settingModel.params.panel.responseLength": "Limit Response Length",
+ "settingModel.params.panel.subAgentModel": "Sub-Agent Model",
"settingModel.params.panel.tab": "Params",
"settingModel.params.panel.title": "Chat Parameter Settings",
"settingModel.params.panel.topicDivergence": "Topic Divergence",
@@ -828,6 +829,7 @@
"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.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.json
index 4a1fb83d11d..895e8c2fbf7 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -816,6 +816,7 @@
"settingModel.params.panel.historyLimit": "限制历史消息",
"settingModel.params.panel.openness": "开放性",
"settingModel.params.panel.responseLength": "限制回复长度",
+ "settingModel.params.panel.subAgentModel": "子助手模型",
"settingModel.params.panel.tab": "参数",
"settingModel.params.panel.title": "聊天参数设置",
"settingModel.params.panel.topicDivergence": "话题发散",
@@ -828,6 +829,7 @@
"settingModel.reasoningEffort.options.low": "低",
"settingModel.reasoningEffort.options.medium": "中",
"settingModel.reasoningEffort.title": "推理强度",
+ "settingModel.subAgentModel.desc": "该助手派生的子助手默认使用的模型。子助手默认运行在轻量模型上,而非继承本助手的主模型。",
"settingModel.submit": "更新模型设置",
"settingModel.temperature.desc": "数值越大,回答越有创意和想象力;数值越小,回答越严谨",
"settingModel.temperature.title": "创意活跃度",
diff --git a/packages/const/src/settings/llm.ts b/packages/const/src/settings/llm.ts
index 863e71afd25..efa71a7710f 100644
--- a/packages/const/src/settings/llm.ts
+++ b/packages/const/src/settings/llm.ts
@@ -1,7 +1,36 @@
+import { DEFAULT_PROVIDER } from '@lobechat/business-const';
+import type { LobeAgentAgencyConfig } 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`.
+ *
+ * Paired with `DEFAULT_PROVIDER` rather than a dedicated sub-agent provider, so
+ * a build that swaps `@lobechat/business-const` (the cloud one routes through
+ * its own official provider) moves the sub-agent along with the main model
+ * instead of leaving it pointed at a provider that build doesn't serve.
+ */
+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.
+ *
+ * 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.
+ */
+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 };
+
export const DEFAULT_RERANK_MODEL = 'rerank-english-v3.0';
export const DEFAULT_RERANK_PROVIDER = 'cohere';
export const DEFAULT_RERANK_QUERY_MODE = 'full_text';
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index bb464ea8f47..b0731dfd074 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -907,6 +907,7 @@ export default {
'settingModel.params.panel.historyLimit': 'Limit History Messages',
'settingModel.params.panel.openness': 'Openness',
'settingModel.params.panel.responseLength': 'Limit Response Length',
+ 'settingModel.params.panel.subAgentModel': 'Sub-Agent Model',
'settingModel.params.panel.tab': 'Params',
'settingModel.params.panel.title': 'Chat Parameter Settings',
'settingModel.params.panel.topicDivergence': 'Topic Divergence',
@@ -920,6 +921,8 @@ export default {
'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.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.ts
index 45002ed0004..9c14e2a77b4 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -532,6 +532,16 @@ export interface LobeAgentAgencyConfig {
*/
executionTarget?: DeviceExecutionTarget;
heterogeneousProvider?: HeterogeneousProviderConfig;
+ /**
+ * 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.
+ */
+ subagent?: {
+ model?: string;
+ provider?: string;
+ };
/**
* Ad-hoc verify criteria mounted directly on this agent, in addition to any
* `verifyRubricId`. Use for one-off checks that don't warrant a reusable
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 4bca61a449a..572e8a2a757 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -367,10 +367,19 @@ export interface ExecVirtualSubAgentParams {
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.
+ */
+ model?: string;
/** The parent placeholder tool message ID */
parentMessageId: string;
/** Parent operation ID to bridge and resume on completion */
parentOperationId: string;
+ /** Provider for {@link model}. */
+ provider?: string;
/** Timeout in milliseconds (optional) */
timeout?: number;
/** Thread title shown in UI */
diff --git a/src/features/ChatInput/ActionBar/Params/Controls.tsx b/src/features/ChatInput/ActionBar/Params/Controls.tsx
index 58a3f3a6e1a..ea613bd0dd3 100644
--- a/src/features/ChatInput/ActionBar/Params/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/Params/Controls.tsx
@@ -1,4 +1,4 @@
-import { DEFAULT_AGENT_CONFIG } from '@lobechat/const';
+import { DEFAULT_AGENT_CONFIG, 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';
@@ -13,6 +13,7 @@ import type { PartialDeep } from 'type-fest';
import InfoTooltip from '@/components/InfoTooltip';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import ModelSelect from '@/features/ModelSelect';
import ControlsForm from '@/features/ModelSwitchPanel/components/ControlsForm';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
@@ -624,6 +625,11 @@ 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);
+
const handleToggle = useCallback(
async (key: ParamKey, enabled: boolean) => {
if (!canCreate) return;
@@ -712,6 +718,19 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
[canCreate, form, handleValuesChange, refreshFormValues],
);
+ const handleSubAgentModelChange = useCallback(
+ async ({ model, provider }: { model: string; provider: string }) => {
+ if (!canCreate) return;
+ setUpdating(true);
+ try {
+ await updateAgentConfig({ agencyConfig: { subagent: { model, provider } } });
+ } finally {
+ setUpdating(false);
+ }
+ },
+ [canCreate, setUpdating, updateAgentConfig],
+ );
+
const handleAdvancedOpenChange = useCallback(() => {
setAdvancedOpen((open) => {
const nextOpen = !open;
@@ -847,6 +866,20 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
}}
/>
</ControlRow>
+ {enableAgentMode && (
+ <ControlRow
+ tag="subAgentModel"
+ title={t('settingModel.params.panel.subAgentModel')}
+ tooltip={t('settingModel.subAgentModel.desc')}
+ >
+ <ModelSelect
+ disabled={!canCreate}
+ style={{ width: '100%' }}
+ value={subAgentModelValue}
+ onChange={handleSubAgentModelChange}
+ />
+ </ControlRow>
+ )}
</div>
{hasModelConfig && (
<>
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/subAgentModel.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/subAgentModel.test.ts
new file mode 100644
index 00000000000..f92297602b9
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/subAgentModel.test.ts
@@ -0,0 +1,92 @@
+import { DEFAULT_SUB_AGENT_MODEL, resolveSubAgentModel } from '@lobechat/const';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import * as agentConfigResolver from '@/services/chat/mecha/agentConfigResolver';
+
+import { useChatStore } from '../../../../store';
+import {
+ createMockAgentConfig,
+ createMockChatConfig,
+ createMockMessage,
+ TEST_IDS,
+} from './fixtures';
+import { resetTestEnvironment } from './helpers';
+
+/**
+ * The model a `callSubAgent` sub-agent runs on is resolved at the *spawn site*
+ * and handed to the run as an explicit override. It must not be re-derived from
+ * `isSubAgent`: isolated group members carry that flag too (it disables the
+ * lobe-agent tool) and have to keep the model configured on the member agent.
+ */
+describe('sub-agent model resolution', () => {
+ const OWN = { model: 'gpt-5.4', provider: 'openai' };
+
+ const createAgentState = (params: {
+ isSubAgent?: boolean;
+ modelOverride?: { model: string; provider: string };
+ }) =>
+ useChatStore.getState().internal_createAgentState({
+ agentId: TEST_IDS.SESSION_ID,
+ messages: [createMockMessage()],
+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ ...params,
+ });
+
+ beforeEach(() => {
+ resetTestEnvironment();
+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
+ agentConfig: createMockAgentConfig(OWN),
+ chatConfig: createMockChatConfig(),
+ isBuiltinAgent: false,
+ plugins: [],
+ });
+ });
+
+ it('runs a spawned sub-agent on the model the spawn site resolved', () => {
+ const { agentConfig } = createAgentState({
+ isSubAgent: true,
+ modelOverride: { model: DEFAULT_SUB_AGENT_MODEL, provider: 'deepseek' },
+ });
+
+ expect(agentConfig.agentConfig).toMatchObject({
+ model: DEFAULT_SUB_AGENT_MODEL,
+ provider: 'deepseek',
+ });
+ });
+
+ it('keeps a group member on its own model — isSubAgent alone must not override it', () => {
+ const { agentConfig } = createAgentState({ isSubAgent: true });
+
+ expect(agentConfig.agentConfig).toMatchObject(OWN);
+ });
+
+ it('keeps an ordinary run on its own model', () => {
+ const { agentConfig } = createAgentState({});
+
+ expect(agentConfig.agentConfig).toMatchObject(OWN);
+ });
+});
+
+describe('resolveSubAgentModel', () => {
+ it('falls back to the global default when the agent has no subagent config', () => {
+ expect(resolveSubAgentModel(undefined)).toEqual({
+ model: DEFAULT_SUB_AGENT_MODEL,
+ provider: 'deepseek',
+ });
+ });
+
+ it('uses the configured override', () => {
+ expect(resolveSubAgentModel({ model: 'gpt-5.4', provider: 'openai' })).toEqual({
+ model: 'gpt-5.4',
+ provider: 'openai',
+ });
+ });
+
+ 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',
+ });
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index b364c0af99f..bb2c5c2a946 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -15,7 +15,7 @@ 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 } from '@lobechat/const';
+import { isDesktop, resolveSubAgentModel } from '@lobechat/const';
import { type ToolsEngine } from '@lobechat/context-engine';
import { buildTaskDetailPrompt, buildTaskListPrompt } from '@lobechat/prompts';
import {
@@ -118,6 +118,7 @@ export class StreamingExecutorActionImpl {
operationId,
subAgentId: paramSubAgentId,
isSubAgent,
+ modelOverride,
}: {
messages: UIChatMessage[];
parentMessageId: string;
@@ -135,6 +136,8 @@ export class StreamingExecutorActionImpl {
*/
subAgentId?: string;
isSubAgent?: boolean;
+ /** Model/provider the run is forced onto, resolved by the caller that spawns it. */
+ modelOverride?: { model: string; provider: string };
}): {
state: AgentState;
context: AgentRuntimeContext;
@@ -161,7 +164,7 @@ export class StreamingExecutorActionImpl {
// This ensures runtime plugins (e.g., 'lobe-agent-builder' for Agent Builder) are included
// - isSubAgent: filters out lobe-agent tool to prevent nested sub-agent creation
// - disableTools: clears all plugins for broadcast scenarios
- const agentConfig = resolveAgentConfig({
+ const resolvedAgentConfig = resolveAgentConfig({
agentId: effectiveAgentId || '',
disableTools, // Clear plugins for broadcast scenarios
groupId, // Pass groupId for supervisor detection
@@ -169,6 +172,19 @@ export class StreamingExecutorActionImpl {
scope, // Pass scope from operation context
});
+ // A model/provider override resolved by the spawn site (see runClientSubAgent),
+ // not re-derived here: `isSubAgent` is also set for isolated group members —
+ // which must keep their own model — so it cannot gate this on its own.
+ // resolveAgentConfig returns an immer-frozen config, so build a new object
+ // rather than mutating in place.
+ const agentConfig: ResolvedAgentConfig =
+ modelOverride && resolvedAgentConfig.agentConfig
+ ? {
+ ...resolvedAgentConfig,
+ agentConfig: { ...resolvedAgentConfig.agentConfig, ...modelOverride },
+ }
+ : resolvedAgentConfig;
+
const { agentConfig: agentConfigData, plugins: pluginIds } = agentConfig;
const selectedToolIds = initialContext?.initialContext?.selectedTools?.map(
(tool) => tool.identifier,
@@ -457,6 +473,13 @@ export class StreamingExecutorActionImpl {
parentOperationId?: string;
skipCreateFirstMessage?: boolean;
isSubAgent?: boolean;
+ /**
+ * Forces the run onto a specific model, overriding the resolved agent config.
+ * Resolved by the spawn site — `runClientSubAgent` passes the parent's
+ * `agencyConfig.subagent` here. Group members deliberately don't, so they
+ * keep their own model.
+ */
+ modelOverride?: { model: string; provider: string };
}): Promise<{ cost?: Cost; model?: string; provider?: string; usage?: Usage } | void> => {
const {
disableTools,
@@ -584,6 +607,7 @@ export class StreamingExecutorActionImpl {
operationId,
subAgentId, // Pass subAgentId for agent config retrieval (behavior depends on scope)
isSubAgent, // Pass isSubAgent to filter out lobe-agent tool in sub-agent context
+ modelOverride: params.modelOverride,
});
if (params.skipCreateFirstMessage) {
@@ -972,11 +996,16 @@ export class StreamingExecutorActionImpl {
this.#get().replaceMessages(subMessages, { context: subContext });
}
- // 6. Run the sub-agent with the current client runtime
+ // 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).
+ const parentAgentConfig = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());
const runtimeResult = await this.#get().executeClientAgent({
context: subContext,
isSubAgent: true,
messages: subMessages,
+ modelOverride: resolveSubAgentModel(parentAgentConfig?.agencyConfig?.subagent),
operationId: taskOperationId,
parentMessageId: userMessageId,
parentMessageType: 'user',