🤯 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
♻️ refactor(agent): run client sub-agent as a normal tool call (#15281)
Arvin Xu8949e8953534
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 4b556bc074d..290dc2d839e 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -763,9 +763,9 @@"taskSchedule.weekdays.thu": "Thu","taskSchedule.weekdays.tue": "Tue","taskSchedule.weekdays.wed": "Wed",- "thread.closeSubagentThread": "Collapse SubAgent conversation",+ "thread.closeSubagentThread": "Hide Detail","thread.divider": "Subtopic",- "thread.openSubagentThread": "View full SubAgent conversation",+ "thread.openSubagentThread": "View Detail","thread.subagentReadOnlyHint": "SubAgent conversations are read-only — execution is driven by the parent agent.","thread.threadMessageCount": "{{messageCount}} messages","thread.title": "Subtopic",@@ -875,8 +875,8 @@"workflow.toolDisplayName.addPreferenceMemory": "Saved memory","workflow.toolDisplayName.calculate": "Calculated","workflow.toolDisplayName.callAgent": "Called an agent",- "workflow.toolDisplayName.callSubAgent": "Dispatched a sub-agent",- "workflow.toolDisplayName.callSubAgents": "Dispatched sub-agents",+ "workflow.toolDisplayName.callSubAgent": "Call SubAgent",+ "workflow.toolDisplayName.callSubAgents": "Call SubAgents","workflow.toolDisplayName.clearTodos": "Cleared todos","workflow.toolDisplayName.copyDocument": "Copied a document","workflow.toolDisplayName.crawlMultiPages": "Crawled pages",diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex d3eda4f0173..964aeaa9189 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -72,10 +72,9 @@"builtins.lobe-agent.apiName.analyzeVisualMedia": "Analyze visual media","builtins.lobe-agent.apiName.analyzeVisualMedia.mediaCount": "{{count}} media","builtins.lobe-agent.apiName.analyzeVisualMedia.result": "Analyze visual media: <question>{{question}}</question>",- "builtins.lobe-agent.apiName.callSubAgent": "Call sub-agent",- "builtins.lobe-agent.apiName.callSubAgent.completed": "Sub-agent dispatched: ",- "builtins.lobe-agent.apiName.callSubAgent.loading": "Dispatching sub-agent: ",- "builtins.lobe-agent.apiName.callSubAgents": "Call sub-agents",+ "builtins.lobe-agent.apiName.callSubAgent": "Call SubAgent",+ "builtins.lobe-agent.apiName.callSubAgents": "Call SubAgents",+ "builtins.lobe-agent.apiName.callSubAgents.more": "{{count}} in total","builtins.lobe-agent.apiName.clearTodos": "Clear todos","builtins.lobe-agent.apiName.clearTodos.modeAll": "all","builtins.lobe-agent.apiName.clearTodos.modeCompleted": "completed",@@ -87,6 +86,8 @@"builtins.lobe-agent.apiName.updatePlan.completed": "Completed","builtins.lobe-agent.apiName.updatePlan.modified": "Modified","builtins.lobe-agent.apiName.updateTodos": "Update todos",+ "builtins.lobe-agent.subAgent.stats.tokens": "{{count}} tokens",+ "builtins.lobe-agent.subAgent.stats.tools": "{{count}} tools","builtins.lobe-agent.title": "Lobe Agent","builtins.lobe-claude-code.agent.instruction": "Instruction","builtins.lobe-claude-code.agent.result": "Result",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 93014bcc1d1..13410589db0 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -763,9 +763,9 @@"taskSchedule.weekdays.thu": "四","taskSchedule.weekdays.tue": "二","taskSchedule.weekdays.wed": "三",- "thread.closeSubagentThread": "收起 SubAgent 对话",+ "thread.closeSubagentThread": "隐藏详情","thread.divider": "子话题",- "thread.openSubagentThread": "查看完整 SubAgent 对话",+ "thread.openSubagentThread": "查看详情","thread.subagentReadOnlyHint": "SubAgent 对话仅可查看,由父智能体驱动执行","thread.threadMessageCount": "{{messageCount}} 条消息","thread.title": "子话题",@@ -875,8 +875,8 @@"workflow.toolDisplayName.addPreferenceMemory": "保存了记忆","workflow.toolDisplayName.calculate": "完成了计算","workflow.toolDisplayName.callAgent": "调用了助理",- "workflow.toolDisplayName.callSubAgent": "派发了子代理",- "workflow.toolDisplayName.callSubAgents": "派发了多个子代理",+ "workflow.toolDisplayName.callSubAgent": "Call SubAgent",+ "workflow.toolDisplayName.callSubAgents": "Call SubAgents","workflow.toolDisplayName.clearTodos": "清空了待办","workflow.toolDisplayName.copyDocument": "复制了文档","workflow.toolDisplayName.crawlMultiPages": "抓取了多个页面",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 6fa5c659d54..264ce2571ed 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -72,10 +72,9 @@"builtins.lobe-agent.apiName.analyzeVisualMedia": "分析视觉媒体","builtins.lobe-agent.apiName.analyzeVisualMedia.mediaCount": "{{count}} 个媒体","builtins.lobe-agent.apiName.analyzeVisualMedia.result": "分析视觉媒体:<question>{{question}}</question>",- "builtins.lobe-agent.apiName.callSubAgent": "调用子代理",- "builtins.lobe-agent.apiName.callSubAgent.completed": "已派发子代理:",- "builtins.lobe-agent.apiName.callSubAgent.loading": "正在派发子代理:",- "builtins.lobe-agent.apiName.callSubAgents": "调用多个子代理",+ "builtins.lobe-agent.apiName.callSubAgent": "Call SubAgent",+ "builtins.lobe-agent.apiName.callSubAgents": "Call SubAgents",+ "builtins.lobe-agent.apiName.callSubAgents.more": "等 {{count}} 个","builtins.lobe-agent.apiName.clearTodos": "清除待办","builtins.lobe-agent.apiName.clearTodos.modeAll": "全部","builtins.lobe-agent.apiName.clearTodos.modeCompleted": "已完成",@@ -87,6 +86,8 @@"builtins.lobe-agent.apiName.updatePlan.completed": "已完成","builtins.lobe-agent.apiName.updatePlan.modified": "已修改","builtins.lobe-agent.apiName.updateTodos": "更新待办",+ "builtins.lobe-agent.subAgent.stats.tokens": "{{count}} tokens",+ "builtins.lobe-agent.subAgent.stats.tools": "{{count}} 个工具","builtins.lobe-agent.title": "Lobe Agent","builtins.lobe-claude-code.agent.instruction": "指令","builtins.lobe-claude-code.agent.result": "结果",diff --git a/packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgent/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgent/index.tsxindex 65592bf8d3f..3ded38320cd 100644--- a/packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgent/index.tsx+++ b/packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgent/index.tsx@@ -1,53 +1,76 @@'use client';import type { BuiltinInspectorProps } from '@lobechat/types';-import { cx } from 'antd-style';+import { GroupBotIcon } from '@lobehub/ui/icons';+import { createStaticStyles, cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';+import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { CallSubAgentParams, CallSubAgentState } from '../../../types';+import { SubAgentStats } from '../../components/SubAgentStats';+const styles = createStaticStyles(({ css, cssVar }) => ({+ chip: css`+ overflow: hidden;+ display: inline-flex;+ flex-shrink: 1;+ align-items: center;++ min-width: 0;+ padding-block: 2px;+ padding-inline: 10px;+ border-radius: 999px;++ font-size: 12px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;++ background: ${cssVar.colorFillTertiary};+ `,+ icon: css`+ flex-shrink: 0;+ color: ${cssVar.colorTextDescription};+ `,+ label: css`+ flex-shrink: 0;+ color: ${cssVar.colorText};+ `,+ root: css`+ gap: 6px;+ `,+}));++/**+ * Collapsed row for lobe-agent's `callSubAgent`. Mirrors the Claude Code Agent+ * tool: leading bot icon + "Call SubAgent" label + the description in a chip.+ * Once the run finishes, the persisted state feeds a compact stats tail+ * (tool count · model · tokens).+ */export const CallSubAgentInspector = memo<BuiltinInspectorProps<CallSubAgentParams, CallSubAgentState>->(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {+>(({ args, partialArgs, pluginState, isArgumentsStreaming, isLoading }) => {const { t } = useTranslation('plugin');- const description = args?.description || partialArgs?.description;-- if (isArgumentsStreaming) {- if (!description)- return (- <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>- <span>{t('builtins.lobe-agent.apiName.callSubAgent')}</span>- </div>- );-- return (- <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>- <span>{t('builtins.lobe-agent.apiName.callSubAgent.loading')}</span>- <span className={highlightTextStyles.primary}>{description}</span>- </div>- );- }-- if (description) {- return (- <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>- <span>- {isLoading- ? t('builtins.lobe-agent.apiName.callSubAgent.loading')- : t('builtins.lobe-agent.apiName.callSubAgent.completed')}- </span>- <span className={highlightTextStyles.primary}>{description}</span>- </div>- );- }+ const description = (args?.description || partialArgs?.description)?.trim();+ const isShiny = isArgumentsStreaming || isLoading;return (- <div className={inspectorTextStyles.root}>- <span>{t('builtins.lobe-agent.apiName.callSubAgent')}</span>+ <div+ className={cx(inspectorTextStyles.root, styles.root, isShiny && shinyTextStyles.shinyText)}+ >+ <GroupBotIcon className={styles.icon} size={14} />+ <span className={styles.label}>{t('builtins.lobe-agent.apiName.callSubAgent')}</span>+ {description && <span className={styles.chip}>{description}</span>}+ {!isShiny && pluginState && (+ <SubAgentStats+ model={pluginState.model}+ totalTokens={pluginState.totalTokens}+ totalToolCalls={pluginState.totalToolCalls}+ />+ )}</div>);});diff --git a/packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgents/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgents/index.tsxindex 6b0592d49d0..bf7f3805f24 100644--- a/packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgents/index.tsx+++ b/packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgents/index.tsx@@ -1,69 +1,87 @@'use client';import type { BuiltinInspectorProps } from '@lobechat/types';-import { Icon } from '@lobehub/ui';+import { GroupBotIcon } from '@lobehub/ui/icons';import { createStaticStyles, cx } from 'antd-style';-import { ListTodo } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, shinyTextStyles } from '@/styles';+import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { CallSubAgentsParams, CallSubAgentsState } from '../../../types';const styles = createStaticStyles(({ css, cssVar }) => ({- count: css`- flex-shrink: 0;- margin-inline-start: 4px;- color: ${cssVar.colorTextSecondary};- `,- description: css`+ chip: css`overflow: hidden;+ display: inline-flex;+ flex-shrink: 1;+ align-items: center;++ min-width: 0;+ padding-block: 2px;+ padding-inline: 10px;+ border-radius: 999px;++ font-size: 12px;+ color: ${cssVar.colorText};text-overflow: ellipsis;white-space: nowrap;++ background: ${cssVar.colorFillTertiary};`,- root: css`- overflow: hidden;- display: flex;- gap: 4px;- align-items: center;+ icon: css`+ flex-shrink: 0;+ color: ${cssVar.colorTextDescription};`,- title: css`+ label: css`flex-shrink: 0;color: ${cssVar.colorText};`,+ more: css`+ flex-shrink: 0;+ color: ${cssVar.colorTextTertiary};+ `,+ root: css`+ gap: 6px;+ `,}));+/** Show every description when there are at most this many; otherwise collapse. */+const MAX_VISIBLE = 2;++/**+ * Collapsed row for lobe-agent's `callSubAgents`. Leading bot icon + "Call+ * SubAgents" label, then each sub-agent description as a chip when there are+ * few (<= 2). Beyond that, only the first is shown followed by a "{{count}} in+ * total" tail to keep the row compact.+ */export const CallSubAgentsInspector = memo<BuiltinInspectorProps<CallSubAgentsParams, CallSubAgentsState>>(({ args, partialArgs, isArgumentsStreaming }) => {const { t } = useTranslation('plugin');const tasks = args?.tasks || partialArgs?.tasks || [];- const count = tasks.length;- const firstTask = tasks[0];+ const descriptions = tasks.map((task) => task?.description?.trim()).filter(Boolean) as string[];+ const count = descriptions.length;- if (isArgumentsStreaming && count === 0) {- return (- <div className={cx(styles.root, shinyTextStyles.shinyText)}>- <span>{t('builtins.lobe-agent.apiName.callSubAgents')}</span>- </div>- );- }+ const isShiny = isArgumentsStreaming;+ const visible = count > MAX_VISIBLE ? descriptions.slice(0, 1) : descriptions;+ const showMore = count > MAX_VISIBLE;return (- <div className={styles.root}>- <span className={cx(styles.title, isArgumentsStreaming && shinyTextStyles.shinyText)}>- {t('builtins.lobe-agent.apiName.callSubAgents')}:- </span>- {firstTask?.description && (- <span className={cx(styles.description, highlightTextStyles.primary)}>- {firstTask.description}+ <div+ className={cx(inspectorTextStyles.root, styles.root, isShiny && shinyTextStyles.shinyText)}+ >+ <GroupBotIcon className={styles.icon} size={14} />+ <span className={styles.label}>{t('builtins.lobe-agent.apiName.callSubAgents')}</span>+ {visible.map((description, index) => (+ <span className={styles.chip} key={index}>+ {description}</span>- )}- {count > 1 && (- <span className={styles.count}>- <Icon icon={ListTodo} size={14} /> {count}+ ))}+ {showMore && (+ <span className={styles.more}>+ {t('builtins.lobe-agent.apiName.callSubAgents.more', { count })}</span>)}</div>diff --git a/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsxindex 46c2230fd1e..2ac000657e6 100644--- a/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx+++ b/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx@@ -1,64 +1,140 @@'use client';import type { BuiltinRenderProps } from '@lobechat/types';-import { Block } from '@lobehub/ui';+import { Button, Flexbox, Markdown, Text } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';-import { memo } from 'react';+import { ListTree } from 'lucide-react';+import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';+import { portalThreadSelectors, threadSelectors } from '@/store/chat/selectors';import type { CallSubAgentParams, CallSubAgentState } from '../../../types';const styles = createStaticStyles(({ css, cssVar }) => ({- instruction: css`- overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 2;-+ container: css`+ padding-block: 4px;+ `,+ label: css`+ padding-inline-start: 4px;font-size: 12px;- line-height: 1.5;color: ${cssVar.colorTextTertiary};`,- taskContent: css`- display: flex;- flex: 1;- flex-direction: column;- gap: 2px;-- min-width: 0;+ labelRow: css`+ margin-block-end: 4px;`,- taskItem: css`- display: flex;- gap: 8px;- align-items: flex-start;-- padding-block: 10px;+ openThread: css`+ height: 22px;+ padding-inline: 6px;+ font-size: 12px;+ `,+ promptBox: css`+ padding-block: 8px;padding-inline: 12px;+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorFillTertiary};`,- title: css`- font-size: 13px;- line-height: 1.4;- color: ${cssVar.colorText};+ resultBox: css`+ padding-block: 8px;+ padding-inline: 12px;+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorBgContainer};`,}));-export const CallSubAgentRender = memo<BuiltinRenderProps<CallSubAgentParams, CallSubAgentState>>(- ({ pluginState }) => {- const { task } = pluginState || {};+/**+ * Render for lobe-agent's `callSubAgent` tool.+ *+ * A sub-agent runs in an isolated Thread via the current runtime, so this view+ * shows the instruction sent to it plus its closing summary (the tool result),+ * and exposes a toggle to open / collapse that Thread in the portal. The Thread+ * is located by the `threadId` persisted in tool state; while the run is still+ * starting the lookup can return `undefined`, so the button is hidden rather+ * than rendered as a dead no-op.+ */+export const CallSubAgentRender = memo<+ BuiltinRenderProps<CallSubAgentParams, CallSubAgentState, string>+>(({ args, content, pluginState }) => {+ const { t } = useTranslation('plugin');+ const { t: tChat } = useTranslation('chat');+ const prompt = args?.instruction?.trim();+ const result = typeof content === 'string' ? content.trim() : '';+ const threadId = pluginState?.threadId;++ const subagentThread = useChatStore((s) =>+ threadId+ ? (threadSelectors.currentTopicThreads(s) ?? []).find((thread) => thread.id === threadId)+ : undefined,+ );+ const openThreadInPortal = useChatStore((s) => s.openThreadInPortal);+ const closeThreadPortal = useChatStore((s) => s.closeThreadPortal);+ const portalThreadId = useChatStore(portalThreadSelectors.portalThreadId);+ const isOpenInPortal = !!subagentThread && portalThreadId === subagentThread.id;++ const handleToggleThread = useCallback(() => {+ if (!subagentThread) return;+ if (isOpenInPortal) {+ closeThreadPortal();+ } else {+ openThreadInPortal(subagentThread.id, subagentThread.sourceMessageId);+ }+ }, [subagentThread, isOpenInPortal, openThreadInPortal, closeThreadPortal]);++ if (!prompt && !result && !subagentThread) return null;++ const showResultSection = !!result || !!subagentThread;- if (!task) return null;+ return (+ <Flexbox className={styles.container} gap={12}>+ {prompt && (+ <Flexbox>+ <Text className={styles.label} style={{ marginBlockEnd: 4 }}>+ {t('builtins.lobe-claude-code.agent.instruction')}+ </Text>+ <Flexbox className={styles.promptBox}>+ <Markdown style={{ maxHeight: 240, overflow: 'auto' }} variant={'chat'}>+ {prompt}+ </Markdown>+ </Flexbox>+ </Flexbox>+ )}- return (- <Block variant={'outlined'} width="100%">- <div className={styles.taskItem}>- <div className={styles.taskContent}>- {task.description && <div className={styles.title}>{task.description}</div>}- {task.instruction && <div className={styles.instruction}>{task.instruction}</div>}- </div>- </div>- </Block>- );- },-);+ {showResultSection && (+ <Flexbox>+ <Flexbox+ horizontal+ align={'center'}+ className={styles.labelRow}+ justify={'space-between'}+ >+ <Text className={styles.label}>{t('builtins.lobe-claude-code.agent.result')}</Text>+ {subagentThread && (+ <Button+ className={styles.openThread}+ icon={ListTree}+ size={'small'}+ type={'text'}+ onClick={handleToggleThread}+ >+ {isOpenInPortal+ ? tChat('thread.closeSubagentThread')+ : tChat('thread.openSubagentThread')}+ </Button>+ )}+ </Flexbox>+ {result && (+ <Flexbox className={styles.resultBox}>+ <Markdown style={{ maxHeight: 320, overflow: 'auto' }} variant={'chat'}>+ {result}+ </Markdown>+ </Flexbox>+ )}+ </Flexbox>+ )}+ </Flexbox>+ );+});CallSubAgentRender.displayName = 'CallSubAgentRender';diff --git a/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgents/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgents/index.tsxindex 77773c6d8eb..669bae6b3bd 100644--- a/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgents/index.tsx+++ b/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgents/index.tsx@@ -1,11 +1,17 @@'use client';import type { BuiltinRenderProps } from '@lobechat/types';-import { Block, Text } from '@lobehub/ui';+import { Block, Button, Flexbox } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';-import { memo } from 'react';+import { ListTree } from 'lucide-react';+import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';-import type { CallSubAgentsParams, CallSubAgentsState } from '../../../types';+import { useChatStore } from '@/store/chat';+import { portalThreadSelectors, threadSelectors } from '@/store/chat/selectors';++import type { CallSubAgentsParams, CallSubAgentsState, SubAgentRunStats } from '../../../types';+import { SubAgentStats } from '../../components/SubAgentStats';const styles = createStaticStyles(({ css, cssVar }) => ({index: css`@@ -13,13 +19,18 @@ const styles = createStaticStyles(({ css, cssVar }) => ({font-size: 12px;color: ${cssVar.colorTextQuaternary};`,-- taskItem: css`+ openThread: css`+ height: 22px;+ padding-inline: 6px;+ font-size: 12px;+ `,+ row: css`display: flex;gap: 8px;- align-items: flex-start;+ align-items: center;+ justify-content: space-between;- padding-block: 12px;+ padding-block: 10px;padding-inline: 12px;border-block-end: 1px dashed ${cssVar.colorBorderSecondary};@@ -27,33 +38,93 @@ const styles = createStaticStyles(({ css, cssVar }) => ({border-block-end: none;}`,+ title: css`+ overflow: hidden;++ font-size: 13px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,}));+interface SubAgentRowProps extends SubAgentRunStats {+ description: string;+ index: number;+ threadId: string;+}++const SubAgentRow = memo<SubAgentRowProps>(+ ({ description, index, threadId, model, totalToolCalls, totalTokens }) => {+ const { t: tChat } = useTranslation('chat');++ const subagentThread = useChatStore((s) =>+ threadId+ ? (threadSelectors.currentTopicThreads(s) ?? []).find((thread) => thread.id === threadId)+ : undefined,+ );+ const openThreadInPortal = useChatStore((s) => s.openThreadInPortal);+ const closeThreadPortal = useChatStore((s) => s.closeThreadPortal);+ const portalThreadId = useChatStore(portalThreadSelectors.portalThreadId);+ const isOpenInPortal = !!subagentThread && portalThreadId === subagentThread.id;++ const handleToggleThread = useCallback(() => {+ if (!subagentThread) return;+ if (isOpenInPortal) {+ closeThreadPortal();+ } else {+ openThreadInPortal(subagentThread.id, subagentThread.sourceMessageId);+ }+ }, [subagentThread, isOpenInPortal, openThreadInPortal, closeThreadPortal]);++ return (+ <div className={styles.row}>+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>+ <span className={styles.index}>{index + 1}.</span>+ <span className={styles.title}>{description}</span>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={12} style={{ flexShrink: 0 }}>+ <SubAgentStats model={model} totalTokens={totalTokens} totalToolCalls={totalToolCalls} />+ {subagentThread && (+ <Button+ className={styles.openThread}+ icon={ListTree}+ size={'small'}+ type={'text'}+ onClick={handleToggleThread}+ >+ {isOpenInPortal+ ? tChat('thread.closeSubagentThread')+ : tChat('thread.openSubagentThread')}+ </Button>+ )}+ </Flexbox>+ </div>+ );+ },+);++SubAgentRow.displayName = 'CallSubAgentsRow';+export const CallSubAgentsRender = memo<BuiltinRenderProps<CallSubAgentsParams, CallSubAgentsState>>(({ pluginState }) => {- const { tasks } = pluginState || {};+ const subAgents = pluginState?.subAgents;- if (!tasks || tasks.length === 0) return null;+ if (!subAgents || subAgents.length === 0) return null;return (<Block variant={'outlined'} width="100%">- {tasks.map((task, index) => (- <div className={styles.taskItem} key={index}>- <div className={styles.index}>{index + 1}.</div>- <div>- {task.description && (- <Text as={'h4'} fontSize={14} weight={500}>- {task.description}- </Text>- )}- {task.instruction && (- <Text as={'p'} ellipsis={{ rows: 2 }} fontSize={12} type={'secondary'}>- {task.instruction}- </Text>- )}- </div>- </div>+ {subAgents.map((subAgent, index) => (+ <SubAgentRow+ description={subAgent.description}+ index={index}+ key={subAgent.threadId || index}+ model={subAgent.model}+ threadId={subAgent.threadId}+ totalTokens={subAgent.totalTokens}+ totalToolCalls={subAgent.totalToolCalls}+ />))}</Block>);diff --git a/packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsx b/packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsxnew file mode 100644index 00000000000..3c09ecc5c63--- /dev/null+++ b/packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsx@@ -0,0 +1,52 @@+'use client';++import { createStaticStyles } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { SubAgentRunStats } from '../../types';++const styles = createStaticStyles(({ css, cssVar }) => ({+ root: css`+ overflow: hidden;+ flex-shrink: 0;++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));++const formatTokens = (n: number): string => {+ if (n < 1000) return String(n);+ if (n < 1_000_000) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k`;+ return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}m`;+};++/**+ * Compact one-line sub-agent run stats: tool count · model · token count.+ * Renders nothing when no stat is available (e.g. while the run is still in+ * flight, before the tool result state is persisted).+ */+export const SubAgentStats = memo<SubAgentRunStats>(({ model, totalToolCalls, totalTokens }) => {+ const { t } = useTranslation('plugin');++ const items = [+ model || null,+ typeof totalToolCalls === 'number' && totalToolCalls > 0+ ? t('builtins.lobe-agent.subAgent.stats.tools', { count: totalToolCalls })+ : null,+ typeof totalTokens === 'number' && totalTokens > 0+ ? t('builtins.lobe-agent.subAgent.stats.tokens', { count: formatTokens(totalTokens) })+ : null,+ ].filter(Boolean);++ if (items.length === 0) return null;++ return <span className={styles.root}>{items.join(' · ')}</span>;+});++SubAgentStats.displayName = 'SubAgentStats';++export default SubAgentStats;diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts b/packages/builtin-tool-lobe-agent/src/client/executor/index.tsindex 166244aa83f..72450bc81d1 100644--- a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts+++ b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts@@ -359,28 +359,41 @@ class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {// ==================== Sub-Agent ====================//- // The executor only constructs the state payload that bridges the tool call- // to the agent-runtime instruction layer. The actual sub-agent dispatch is- // handled by `createAgentExecutors.ts` which reads `state.type` to emit the- // matching `exec_sub_agent` / `exec_client_sub_agent(s)` instruction.+ // A sub-agent call is a normal tool call: the executor runs the sub-agent in+ // an isolated Thread via `ctx.subAgent` (the current runtime, injected by the+ // client) and returns the sub-agent's final output as the tool result. The+ // Thread id is persisted in state so the Render can open it in the portal.callSubAgent = async (params: CallSubAgentParams,ctx: BuiltinToolContext,): Promise<BuiltinToolResult> => {- const { description, instruction, inheritMessages, timeout, runInClient } = params;+ const { description, instruction, inheritMessages, timeout } = params;if (!description || !instruction) {return { content: 'Sub-agent description and instruction are required.', success: false };}- const task = { description, inheritMessages, instruction, runInClient, timeout };- const stateType = runInClient ? 'execClientSubAgent' : 'execSubAgent';+ if (!ctx.subAgent) {+ return { content: 'Sub-agent execution is not available in this runtime.', success: false };+ }++ const { result, threadId, success, error, model, totalToolCalls, totalTokens } =+ await ctx.subAgent.run({+ description,+ inheritMessages,+ instruction,+ timeout,+ toolMessageId: ctx.messageId,+ });++ if (!success) {+ return { content: error ?? 'Sub-agent execution failed.', success: false };+ }return {- content: `🚀 Dispatched sub-agent for ${runInClient ? 'client-side' : ''} execution:\n- ${description}`,- state: { parentMessageId: ctx.messageId ?? '', task, type: stateType },- stop: true,+ content: result,+ state: { model, threadId, totalToolCalls, totalTokens },success: true,};};@@ -395,16 +408,38 @@ class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {return { content: 'No sub-agents provided to dispatch.', success: false };}- const taskCount = tasks.length;- const taskList = tasks.map((t, i) => `${i + 1}. ${t.description}`).join('\n');- const hasClientTasks = tasks.some((t) => t.runInClient);- const stateType = hasClientTasks ? 'execClientSubAgents' : 'execSubAgents';- const executionMode = hasClientTasks ? 'client-side' : '';+ if (!ctx.subAgent) {+ return { content: 'Sub-agent execution is not available in this runtime.', success: false };+ }++ const subAgent = ctx.subAgent;+ const results = await Promise.all(+ tasks.map((task) =>+ subAgent.run({+ description: task.description,+ inheritMessages: task.inheritMessages,+ instruction: task.instruction,+ timeout: task.timeout,+ toolMessageId: ctx.messageId,+ }),+ ),+ );++ const content = results+ .map((r, i) => `${i + 1}. ${tasks[i].description}\n${r.success ? r.result : `❌ ${r.error}`}`)+ .join('\n\n');return {- content: `🚀 Dispatched ${taskCount} sub-agent${taskCount > 1 ? 's' : ''} for ${executionMode} execution:\n${taskList}`,- state: { parentMessageId: ctx.messageId ?? '', tasks, type: stateType },- stop: true,+ content,+ state: {+ subAgents: results.map((r, i) => ({+ description: tasks[i].description,+ model: r.model,+ threadId: r.threadId,+ totalToolCalls: r.totalToolCalls,+ totalTokens: r.totalTokens,+ })),+ },success: true,};};diff --git a/packages/builtin-tool-lobe-agent/src/types.ts b/packages/builtin-tool-lobe-agent/src/types.tsindex 417dbb3b167..0a14e07b9e7 100644--- a/packages/builtin-tool-lobe-agent/src/types.ts+++ b/packages/builtin-tool-lobe-agent/src/types.ts@@ -82,38 +82,30 @@ export interface CallSubAgentsParams {tasks: SubAgentTask[];}+/** Execution stats reported back by a finished sub-agent run. */+export interface SubAgentRunStats {+ /** Model the sub-agent ran on */+ model?: string;+ /** Total tokens consumed by the sub-agent run */+ totalTokens?: number;+ /** Number of tool calls the sub-agent made */+ totalToolCalls?: number;+}+/**- * State returned after dispatching a server-side sub-agent.+ * State persisted on the callSubAgent tool message.*- * The `type` value is the wire-level discriminator the `agent-runtime`- * layer (`GeneralChatAgent.tool_result`) inspects to emit the matching- * `exec_sub_agent` / `exec_client_sub_agent` instruction.+ * The sub-agent runs in an isolated Thread via the current runtime; the Render+ * uses `threadId` to open that Thread in the portal, and the stats feed the+ * Inspector row.*/-export interface CallSubAgentState {- parentMessageId: string;- task: SubAgentTask;- type: 'execSubAgent';+export interface CallSubAgentState extends SubAgentRunStats {+ threadId: string;}-/** State returned after dispatching multiple server-side sub-agents. */+/** State persisted on the callSubAgents tool message (one entry per sub-agent). */export interface CallSubAgentsState {- parentMessageId: string;- tasks: SubAgentTask[];- type: 'execSubAgents';-}--/** State returned after dispatching a desktop-only client-side sub-agent. */-export interface CallClientSubAgentState {- parentMessageId: string;- task: SubAgentTask;- type: 'execClientSubAgent';-}--/** State returned after dispatching multiple desktop-only client-side sub-agents. */-export interface CallClientSubAgentsState {- parentMessageId: string;- tasks: SubAgentTask[];- type: 'execClientSubAgents';+ subAgents: ({ description: string; threadId: string } & SubAgentRunStats)[];}// ==================== Todo Item ====================diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex 3c28cada09e..d58ad996c7c 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -485,6 +485,14 @@ export interface BuiltinToolContext {*/stepContext?: RuntimeStepContext;+ /**+ * Sub-agent execution callback injected by the client runtime.+ * Lets a tool (e.g. lobe-agent.callSubAgent) recursively run a sub-agent in+ * an isolated thread using the *current* runtime, then resume as a normal+ * tool result. Only present during client-mode tool execution.+ */+ subAgent?: SubAgentCallbacks;+/*** Current task identifier or database id when the conversation is scoped to a task detail page.*/@@ -684,6 +692,51 @@ export interface GroupOrchestrationCallbacks {triggerSpeak: (params: TriggerSpeakParams) => Promise<void>;}+/**+ * Params for running a single sub-agent via the injected runtime callback.+ */+export interface RunSubAgentParams {+ /** Brief description of what this sub-agent does (used as thread title / UI) */+ description: string;+ /** Whether to inherit context messages from the parent conversation */+ inheritMessages?: boolean;+ /** Detailed instruction/prompt for the sub-agent execution */+ instruction: string;+ /** Optional timeout in milliseconds */+ timeout?: number;+ /** The tool message ID that spawned this sub-agent (anchors the isolation thread) */+ toolMessageId: string;+}++/**+ * Result of a sub-agent run, fed back to the caller as a normal tool result.+ */+export interface RunSubAgentResult {+ /** Error message when the sub-agent failed */+ error?: string;+ /** Model the sub-agent ran on (e.g. "deepseek-v4-pro") */+ model?: string;+ /** Final assistant output of the sub-agent run */+ result: string;+ /** Whether the run succeeded */+ success: boolean;+ /** The isolation thread holding the sub-agent's full message trace */+ threadId: string;+ /** Total tokens consumed by the sub-agent run */+ totalTokens?: number;+ /** Number of tool calls the sub-agent made */+ totalToolCalls?: number;+}++/**+ * Sub-agent execution callback injected by the runtime into tool context.+ * Runs the sub-agent in an isolated thread using the current runtime and+ * resolves once it finishes, so the calling tool can return a normal result.+ */+export interface SubAgentCallbacks {+ run: (params: RunSubAgentParams) => Promise<RunSubAgentResult>;+}+/*** Builtin tool executor function type*/diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex 8bdde0f4417..b04b2113ead 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -839,9 +839,9 @@ export default {'taskList.view.board': 'Board','taskList.view.list': 'List','taskList.viewAll': 'View all',- 'thread.closeSubagentThread': 'Collapse SubAgent conversation',+ 'thread.closeSubagentThread': 'Hide Detail','thread.divider': 'Subtopic',- 'thread.openSubagentThread': 'View full SubAgent conversation',+ 'thread.openSubagentThread': 'View Detail','thread.subagentReadOnlyHint':'SubAgent conversations are read-only — execution is driven by the parent agent.','thread.threadMessageCount': '{{messageCount}} messages',@@ -960,8 +960,8 @@ export default {'workflow.toolDisplayName.addPreferenceMemory': 'Saved memory','workflow.toolDisplayName.calculate': 'Calculated','workflow.toolDisplayName.callAgent': 'Called an agent',- 'workflow.toolDisplayName.callSubAgent': 'Dispatched a sub-agent',- 'workflow.toolDisplayName.callSubAgents': 'Dispatched sub-agents',+ 'workflow.toolDisplayName.callSubAgent': 'Call SubAgent',+ 'workflow.toolDisplayName.callSubAgents': 'Call SubAgents','workflow.toolDisplayName.clearTodos': 'Cleared todos','workflow.toolDisplayName.copyDocument': 'Copied a document','workflow.toolDisplayName.crawlMultiPages': 'Crawled pages',diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.tsindex 99be8f1e4c3..ce810502d0a 100644--- a/src/locales/default/plugin.ts+++ b/src/locales/default/plugin.ts@@ -55,10 +55,11 @@ export default {'builtins.lobe-agent.apiName.analyzeVisualMedia.mediaCount': '{{count}} media','builtins.lobe-agent.apiName.analyzeVisualMedia.result':'Analyze visual media: <question>{{question}}</question>',- 'builtins.lobe-agent.apiName.callSubAgent': 'Call sub-agent',- 'builtins.lobe-agent.apiName.callSubAgent.completed': 'Sub-agent dispatched: ',- 'builtins.lobe-agent.apiName.callSubAgent.loading': 'Dispatching sub-agent: ',- 'builtins.lobe-agent.apiName.callSubAgents': 'Call sub-agents',+ 'builtins.lobe-agent.apiName.callSubAgent': 'Call SubAgent',+ 'builtins.lobe-agent.apiName.callSubAgents': 'Call SubAgents',+ 'builtins.lobe-agent.apiName.callSubAgents.more': '{{count}} in total',+ 'builtins.lobe-agent.subAgent.stats.tokens': '{{count}} tokens',+ 'builtins.lobe-agent.subAgent.stats.tools': '{{count}} tools','builtins.lobe-agent.title': 'Lobe Agent','builtins.lobe-claude-code.agent.instruction': 'Instruction','builtins.lobe-claude-code.agent.result': 'Result',diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsxindex ec61d694def..776f379ac9e 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx@@ -1,3 +1,4 @@+import { ThreadType } from '@lobechat/types';import { Flexbox } from '@lobehub/ui';import { memo } from 'react';@@ -20,7 +21,7 @@ const ThreadList = memo(({ topicId }: { topicId: string }) => {<ThreadItemid={item.id}index={index}- isSubagent={!!item.metadata?.subagentType}+ isSubagent={item.type === ThreadType.Isolation}key={item.id}title={item.title}/>diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsxindex e63f2a99e6e..fcd01364e5e 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx@@ -1,3 +1,4 @@+import { ThreadType } from '@lobechat/types';import { Flexbox } from '@lobehub/ui';import { memo } from 'react';@@ -21,7 +22,7 @@ const ThreadList = memo(() => {<ThreadItemid={item.id}index={index}- isSubagent={!!item.metadata?.subagentType}+ isSubagent={item.type === ThreadType.Isolation}key={item.id}title={item.title}/>diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.tsindex 5f2fa0cfbcc..36448e5c163 100644--- a/src/store/chat/agents/createAgentExecutors.ts+++ b/src/store/chat/agents/createAgentExecutors.ts@@ -4,8 +4,6 @@ import type {AgentInstructionCallLlm,AgentInstructionCallTool,AgentInstructionCompressContext,- AgentInstructionExecClientSubAgent,- AgentInstructionExecClientSubAgents,AgentInstructionExecSubAgent,AgentInstructionExecSubAgents,AgentRuntimeContext,@@ -19,13 +17,11 @@ import type {SubAgentsBatchResultPayload,} from '@lobechat/agent-runtime';import { UsageCounter } from '@lobechat/agent-runtime';-import { isDesktop } from '@lobechat/const';import { countContextTokens, type ToolsEngine } from '@lobechat/context-engine';import { chainCompressContext } from '@lobechat/prompts';import {type ChatMessageError,type ChatToolPayload,- type ConversationContext,type CreateMessageParams,type MessageMetadata,type MessageToolCall,@@ -42,11 +38,8 @@ import { aiAgentService } from '@/services/aiAgent';import { chatService } from '@/services/chat';import { type ResolvedAgentConfig } from '@/services/chat/mecha';import { messageService } from '@/services/message';-import { agentByIdSelectors } from '@/store/agent/selectors';-import { getAgentStoreState } from '@/store/agent/store';import { type ChatStore } from '@/store/chat/store';import { getCompressionCandidateMessageIds } from '@/store/chat/utils/compression';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { getFileStoreState } from '@/store/file/store';import { sleep } from '@/utils/sleep';@@ -2013,647 +2006,6 @@ export const createAgentExecutors = (context: {};},- /**- * exec_client_sub_agent executor- * Dispatches a single sub-agent on the client side (desktop only)- * Used when the sub-agent requires local tools like file system or shell commands- *- * Flow:- * 1. Create a task message (role: 'task') as placeholder- * 2. Create Thread via API (for isolation)- * 3. Execute using executeClientAgent (client-side)- * 4. Update Thread status via API on completion- * 5. Update task message content with result- * 6. Return sub_agent_result phase with result- */- exec_client_sub_agent: async (instruction, state) => {- const { parentMessageId, task } = (instruction as AgentInstructionExecClientSubAgent).payload;-- const events: AgentEvent[] = [];- const sessionLogId = `${state.operationId}:${state.stepCount}`;-- log(- '[%s][exec_client_sub_agent] Starting client-side execution of task: %s',- sessionLogId,- task.description,- );-- // Check if we're on desktop - if not, this executor shouldn't have been called- if (!isDesktop) {- log(- '[%s][exec_client_sub_agent] ERROR: Not on desktop, cannot execute client-side task',- sessionLogId,- );- return {- events,- newState: state,- nextContext: {- payload: {- parentMessageId,- result: {- error: 'Client-side task execution is only available on desktop',- success: false,- taskMessageId: '',- threadId: '',- },- } as SubAgentResultPayload,- phase: 'sub_agent_result',- session: {- messageCount: state.messages.length,- sessionId: state.operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- } as AgentRuntimeContext,- };- }-- // Get context from operation- const opContext = getOperationContext();- const { agentId, topicId } = opContext;-- if (!agentId || !topicId) {- log('[%s][exec_client_sub_agent] No valid context, cannot execute task', sessionLogId);- return {- events,- newState: state,- nextContext: {- payload: {- parentMessageId,- result: {- error: 'No valid context available',- success: false,- taskMessageId: '',- threadId: '',- },- } as SubAgentResultPayload,- phase: 'sub_agent_result',- session: {- messageCount: state.messages.length,- sessionId: state.operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- } as AgentRuntimeContext,- };- }-- const taskLogId = `${sessionLogId}:client-task`;-- // Get agent's model and provider configuration- const agentState = getAgentStoreState();- const taskModel = agentByIdSelectors.getAgentModelById(agentId)(agentState);- const taskProvider = agentByIdSelectors.getAgentModelProviderById(agentId)(agentState);-- try {- // 1. Create task message as placeholder with model/provider- const taskMessageResult = await context.get().optimisticCreateMessage(- {- agentId,- content: '',- metadata: { instruction: task.instruction, taskTitle: task.description },- model: taskModel,- parentId: parentMessageId,- provider: taskProvider,- role: 'task',- topicId,- },- { operationId: state.operationId },- );-- if (!taskMessageResult) {- log('[%s] Failed to create task message', taskLogId);- return {- events,- newState: state,- nextContext: {- payload: {- parentMessageId,- result: {- error: 'Failed to create task message',- success: false,- taskMessageId: '',- threadId: '',- },- } as SubAgentResultPayload,- phase: 'sub_agent_result',- session: {- messageCount: state.messages.length,- sessionId: state.operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- } as AgentRuntimeContext,- };- }-- const taskMessageId = taskMessageResult.id;- log('[%s][exec_client_sub_agent] Created task message: %s', taskLogId, taskMessageId);-- // 2. Create Thread via API first (to get threadId for operation context)- const threadResult = await aiAgentService.createClientTaskThread({- agentId,- instruction: task.instruction,- parentMessageId: taskMessageId,- title: task.description,- topicId,- });-- if (!threadResult.success) {- log('[%s][exec_client_sub_agent] Failed to create client task thread', taskLogId);- await context- .get()- .optimisticUpdateMessageContent(- taskMessageId,- 'Failed to create task thread',- undefined,- { operationId: state.operationId },- );- return {- events,- newState: state,- nextContext: {- payload: {- parentMessageId,- result: {- error: 'Failed to create client task thread',- success: false,- taskMessageId,- threadId: '',- },- } as SubAgentResultPayload,- phase: 'sub_agent_result',- session: {- messageCount: state.messages.length,- sessionId: state.operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- } as AgentRuntimeContext,- };- }-- const { threadId, userMessageId, threadMessages, messages } = threadResult;-- // 3. Build sub-task ConversationContext (uses threadId for isolation)- const subContext: ConversationContext = {- agentId,- topicId,- threadId,- scope: 'thread',- };-- // 4. Create a child operation for task execution (now with threadId)- const { operationId: taskOperationId } = context.get().startOperation({- type: 'execClientSubAgent',- context: subContext,- parentOperationId: state.operationId,- metadata: {- startTime: Date.now(),- taskDescription: task.description,- taskMessageId,- executionMode: 'client',- },- });- log(- '[%s][exec_client_sub_agent] Created thread: %s, userMessageId: %s, threadMessages: %d',- taskLogId,- threadId,- userMessageId,- threadMessages.length,- );-- // 5. Sync messages to store- // Update main chat messages with latest taskDetail status- context.get().replaceMessages(messages, { operationId: state.operationId });- // Update thread messages- context.get().replaceMessages(threadMessages, { context: subContext });-- // 6. Use server-returned thread messages (already persisted)- let subMessages = [...threadMessages];-- // Optionally inherit messages from parent conversation- if (task.inheritMessages) {- const parentMessages = state.messages.filter((m) => m.role !== 'task');- subMessages = [...parentMessages, ...subMessages];- // Re-sync with inherited messages- context.get().replaceMessages(subMessages, { context: subContext });- }-- // 7. Execute using executeClientAgent (client-side with local tools access)- log('[%s][exec_client_sub_agent] Starting client-side AgentRuntime execution', taskLogId);-- const runtimeResult = await context.get().executeClientAgent({- context: subContext,- messages: subMessages,- parentMessageId: userMessageId, // Use server-returned userMessageId- parentMessageType: 'user',- operationId: taskOperationId,- parentOperationId: state.operationId,- isSubAgent: true, // Disable lobe-agent tool to prevent nested sub-agents- });-- log('[%s][exec_client_sub_agent] Client-side AgentRuntime execution completed', taskLogId);-- // 8. Get execution result from sub-task messages- const subMessageKey = messageMapKey(subContext);- const subTaskMessages = context.get().dbMessagesMap[subMessageKey] || [];- const lastAssistant = subTaskMessages.findLast((m) => m.role === 'assistant');- const resultContent = lastAssistant?.content || 'Task completed';-- log(- '[%s][exec_client_sub_agent] Got result from sub-task: %d chars',- taskLogId,- resultContent.length,- );-- // Count tool calls- const totalToolCalls = subTaskMessages.filter((m) => m.role === 'tool').length;-- // Get usage data from runtime result- const { usage, cost } = runtimeResult || {};-- log(- '[%s][exec_client_sub_agent] Runtime usage: tokens=%d, cost=%s, model=%s',- taskLogId,- usage?.llm?.tokens?.total,- cost?.total,- taskModel,- );-- // 9. Update task message with result and usage (model/provider already set at creation)- await context.get().optimisticUpdateMessageContent(- taskMessageId,- resultContent,- {- metadata: {- cost: cost?.total,- duration: usage?.llm?.processingTimeMs,- totalInputTokens: usage?.llm?.tokens?.input,- totalOutputTokens: usage?.llm?.tokens?.output,- totalTokens: usage?.llm?.tokens?.total,- },- },- { operationId: state.operationId },- );-- // 10. Update Thread status via API with metadata- await aiAgentService.updateClientTaskThreadStatus({- threadId,- completionReason: 'done',- resultContent,- metadata: {- totalCost: cost?.total,- totalMessages: subTaskMessages.length,- totalTokens: usage?.llm?.tokens?.total,- totalToolCalls,- },- });-- // 11. Complete operation- context.get().completeOperation(taskOperationId);-- // 12. Return success result- const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];- return {- events,- newState: { ...state, messages: updatedMessages },- nextContext: {- payload: {- // Use taskMessageId as parent so subsequent messages are created after the task- parentMessageId: taskMessageId,- result: {- result: resultContent,- success: true,- taskMessageId,- threadId,- },- } as SubAgentResultPayload,- phase: 'sub_agent_result',- session: {- messageCount: updatedMessages.length,- sessionId: state.operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- } as AgentRuntimeContext,- };- } catch (error) {- log('[%s][exec_client_sub_agent] Error executing client task: %O', taskLogId, error);-- // Update task message with error- // Note: taskMessageId may not exist if error occurred before message creation- const errorMessage = error instanceof Error ? error.message : 'Unknown error';-- return {- events,- newState: state,- nextContext: {- payload: {- parentMessageId,- result: {- error: errorMessage,- success: false,- taskMessageId: '',- threadId: '',- },- } as SubAgentResultPayload,- phase: 'sub_agent_result',- session: {- messageCount: state.messages.length,- sessionId: state.operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- } as AgentRuntimeContext,- };- }- },-- /**- * exec_client_sub_agents executor- * Dispatches multiple sub-agents on the client side in parallel (desktop only)- * Used when sub-agents require local tools like file system or shell commands- *- * Flow:- * 1. For each sub-agent, create a task message (role: 'task') as placeholder- * 2. Create Thread via API (for isolation)- * 3. Execute using executeClientAgent (client-side)- * 4. Update Thread status via API on completion- * 5. Update task message content with result- * 6. Return sub_agents_batch_result phase with all results- */- exec_client_sub_agents: async (instruction, state) => {- const { parentMessageId, tasks } = (instruction as AgentInstructionExecClientSubAgents)- .payload;-- const events: AgentEvent[] = [];- const sessionLogId = `${state.operationId}:${state.stepCount}`;-- log(- '[%s][exec_client_sub_agents] Starting client-side execution of %d tasks',- sessionLogId,- tasks.length,- );-- // Check if we're on desktop - if not, this executor shouldn't have been called- if (!isDesktop) {- log(- '[%s][exec_client_sub_agents] ERROR: Not on desktop, cannot execute client-side tasks',- sessionLogId,- );- return {- events,- newState: state,- nextContext: {- payload: {- parentMessageId,- results: tasks.map(() => ({- error: 'Client-side task execution is only available on desktop',- success: false,- taskMessageId: '',- threadId: '',- })),- } as SubAgentsBatchResultPayload,- phase: 'sub_agents_batch_result',- session: {- messageCount: state.messages.length,- sessionId: state.operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- } as AgentRuntimeContext,- };- }-- // Get context from operation- const opContext = getOperationContext();- const { agentId, topicId } = opContext;-- if (!agentId || !topicId) {- log('[%s][exec_client_sub_agents] No valid context, cannot execute tasks', sessionLogId);- return {- events,- newState: state,- nextContext: {- payload: {- parentMessageId,- results: tasks.map(() => ({- error: 'No valid context available',- success: false,- taskMessageId: '',- threadId: '',- })),- } as SubAgentsBatchResultPayload,- phase: 'sub_agents_batch_result',- session: {- messageCount: state.messages.length,- sessionId: state.operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- } as AgentRuntimeContext,- };- }-- // Execute all tasks in parallel- const results = await pMap(- tasks,- async (task, taskIndex) => {- const taskLogId = `${sessionLogId}:client-task-${taskIndex}`;- log('[%s] Starting client task: %s', taskLogId, task.description);-- try {- // 1. Create task message as placeholder- const taskMessageResult = await context.get().optimisticCreateMessage(- {- agentId,- content: '',- createdAt: Date.now() + taskIndex,- metadata: { instruction: task.instruction, taskTitle: task.description },- parentId: parentMessageId,- role: 'task',- topicId,- },- { operationId: state.operationId },- );-- if (!taskMessageResult) {- log('[%s] Failed to create task message', taskLogId);- return {- error: 'Failed to create task message',- success: false,- taskMessageId: '',- threadId: '',- };- }-- const taskMessageId = taskMessageResult.id;- log('[%s] Created task message: %s', taskLogId, taskMessageId);-- // 2. Create Thread via API first (to get threadId for operation context)- const threadResult = await aiAgentService.createClientTaskThread({- agentId,- instruction: task.instruction,- parentMessageId: taskMessageId,- title: task.description,- topicId,- });-- if (!threadResult.success) {- log('[%s] Failed to create client task thread', taskLogId);- await context- .get()- .optimisticUpdateMessageContent(- taskMessageId,- 'Failed to create task thread',- undefined,- { operationId: state.operationId },- );- return {- error: 'Failed to create client task thread',- success: false,- taskMessageId,- threadId: '',- };- }-- const { threadId, userMessageId, threadMessages, messages } = threadResult;- log(- '[%s] Created thread: %s, userMessageId: %s, threadMessages: %d',- taskLogId,- threadId,- userMessageId,- threadMessages.length,- );-- // 3. Build sub-task ConversationContext (uses threadId for isolation)- const subContext: ConversationContext = {- agentId,- topicId,- threadId,- scope: 'thread',- };-- // 4. Create a child operation for task execution (now with threadId)- const { operationId: taskOperationId } = context.get().startOperation({- type: 'execClientSubAgent',- context: subContext,- parentOperationId: state.operationId,- metadata: {- startTime: Date.now(),- taskDescription: task.description,- taskIndex,- taskMessageId,- executionMode: 'client',- },- });-- // 5. Sync messages to store- // Update main chat messages with latest taskDetail status- context.get().replaceMessages(messages, { operationId: state.operationId });- // Update thread messages- context.get().replaceMessages(threadMessages, { context: subContext });-- // 6. Use server-returned thread messages (already persisted)- let subMessages = [...threadMessages];-- // Optionally inherit messages from parent conversation- if (task.inheritMessages) {- const parentMessages = state.messages.filter((m) => m.role !== 'task');- subMessages = [...parentMessages, ...subMessages];- // Re-sync with inherited messages- context.get().replaceMessages(subMessages, { context: subContext });- }-- // 7. Execute using executeClientAgent (client-side with local tools access)- log('[%s] Starting client-side AgentRuntime execution', taskLogId);-- await context.get().executeClientAgent({- context: subContext,- messages: subMessages,- parentMessageId: userMessageId, // Use server-returned userMessageId- parentMessageType: 'user',- operationId: taskOperationId,- parentOperationId: state.operationId,- isSubAgent: true, // Disable lobe-agent tool to prevent nested sub-agents- });-- log('[%s] Client-side AgentRuntime execution completed', taskLogId);-- // 7. Get execution result from sub-task messages- const subMessageKey = messageMapKey(subContext);- const subTaskMessages = context.get().dbMessagesMap[subMessageKey] || [];- const lastAssistant = subTaskMessages.findLast((m) => m.role === 'assistant');- const resultContent = lastAssistant?.content || 'Task completed';-- log('[%s] Got result from sub-task: %d chars', taskLogId, resultContent.length);-- // 8. Update task message with result- await context- .get()- .optimisticUpdateMessageContent(taskMessageId, resultContent, undefined, {- operationId: state.operationId,- });-- // 9. Update Thread status via API- await aiAgentService.updateClientTaskThreadStatus({- threadId,- completionReason: 'done',- resultContent,- });-- // 10. Complete operation- context.get().completeOperation(taskOperationId);-- return {- result: resultContent,- success: true,- taskMessageId,- threadId,- };- } catch (error) {- log('[%s] Error executing client task: %O', taskLogId, error);- return {- error: error instanceof Error ? error.message : 'Unknown error',- success: false,- taskMessageId: '',- threadId: '',- };- }- },- { concurrency: 15 },- );-- log('[%s][exec_client_sub_agents] All tasks completed, results: %O', sessionLogId, results);-- // Get latest messages from store- const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];- const newState = { ...state, messages: updatedMessages };-- // Use the last successful task's message ID as parent for subsequent messages- const lastSuccessfulTaskId = results.findLast((r) => r.success)?.taskMessageId;-- return {- events,- newState,- nextContext: {- payload: {- // Use last task message as parent so subsequent messages are created after the tasks- parentMessageId: lastSuccessfulTaskId || parentMessageId,- results,- } as SubAgentsBatchResultPayload,- phase: 'sub_agents_batch_result',- session: {- messageCount: newState.messages.length,- sessionId: state.operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- } as AgentRuntimeContext,- };- },-/*** Context compression executor* Compresses ALL messages into a single MessageGroup summary to reduce token usagediff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex 6fbfefe2158..cc953728592 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -16,6 +16,7 @@ import { buildTaskDetailPrompt, buildTaskListPrompt } from '@lobechat/prompts';import {type ConversationContext,type MessageMetadata,+ type RunSubAgentResult,type RuntimeInitialContext,type UIChatMessage,} from '@lobechat/types';@@ -23,6 +24,7 @@ import debug from 'debug';import { t } from 'i18next';import { createAgentToolsEngine } from '@/helpers/toolEngineering';+import { aiAgentService } from '@/services/aiAgent';import { isCanUseVideo, isCanUseVision } from '@/services/chat/helper';import { type ResolvedAgentConfig } from '@/services/chat/mecha';import { composeEnabledTools, resolveAgentConfig } from '@/services/chat/mecha';@@ -482,7 +484,7 @@ export class StreamingExecutorActionImpl {parentOperationId?: string;skipCreateFirstMessage?: boolean;isSubAgent?: boolean;- }): Promise<{ cost?: Cost; usage?: Usage } | void> => {+ }): Promise<{ cost?: Cost; model?: string; provider?: string; usage?: Usage } | void> => {const {disableTools,messages: originalMessages,@@ -977,7 +979,137 @@ export class StreamingExecutorActionImpl {}// Return usage and cost data for caller to use- return { cost: state.cost, usage: state.usage };+ return { cost: state.cost, model, provider: provider ?? undefined, usage: state.usage };+ };++ /**+ * Run a sub-agent inside an isolated thread using the *current* client+ * runtime, then resolve with its final output so the calling tool can return+ * a normal tool result. This is the client-side implementation behind+ * `BuiltinToolContext.subAgent.run` — a sub-agent run is just a regular+ * `executeClientAgent` invocation scoped to a fresh Thread, with+ * `isSubAgent` set so the sub-agent can't recursively spawn more sub-agents.+ */+ runClientSubAgent = async (params: {+ agentId: string;+ description: string;+ inheritMessages?: boolean;+ instruction: string;+ parentOperationId?: string;+ toolMessageId: string;+ topicId: string;+ }): Promise<RunSubAgentResult> => {+ const {+ agentId,+ topicId,+ instruction,+ description,+ inheritMessages,+ toolMessageId,+ parentOperationId,+ } = params;++ const logId = `runClientSubAgent:${toolMessageId}`;++ try {+ // 1. Create the isolation Thread (persists thread + initial user message)+ const threadResult = await aiAgentService.createClientTaskThread({+ agentId,+ instruction,+ parentMessageId: toolMessageId,+ title: description,+ topicId,+ });++ if (!threadResult.success) {+ log('[%s] Failed to create client task thread', logId);+ return {+ error: 'Failed to create sub-agent thread',+ result: 'Failed to create sub-agent thread',+ success: false,+ threadId: '',+ };+ }++ const { threadId, userMessageId, threadMessages } = threadResult;+ log('[%s] Created thread %s, userMessage %s', logId, threadId, userMessageId);++ // Register the freshly-created isolation thread in the client thread list+ // so the tool Render can locate it (the "View Detail" button) and it shows+ // in the sidebar without waiting for a topic switch to re-fetch threads.+ void this.#get().refreshThreads();++ // 2. Build the sub-agent ConversationContext (threadId provides isolation)+ const subContext: ConversationContext = { agentId, scope: 'thread', threadId, topicId };++ // 3. Create a child operation chained to the parent runtime operation+ const { operationId: taskOperationId } = this.#get().startOperation({+ context: subContext,+ metadata: { executionMode: 'client', startTime: Date.now(), taskDescription: description },+ parentOperationId,+ type: 'execClientSubAgent',+ });++ // 4. Seed the thread message map so the persisted user message renders+ this.#get().replaceMessages(threadMessages, { context: subContext });++ // 5. Optionally inherit the parent conversation messages+ let subMessages = [...threadMessages];+ if (inheritMessages) {+ const parentMessages = (+ this.#get().dbMessagesMap[messageMapKey({ agentId, topicId })] || []+ ).filter((m) => m.role !== 'task');+ subMessages = [...parentMessages, ...subMessages];+ this.#get().replaceMessages(subMessages, { context: subContext });+ }++ // 6. Run the sub-agent with the current client runtime+ const runtimeResult = await this.#get().executeClientAgent({+ context: subContext,+ isSubAgent: true,+ messages: subMessages,+ operationId: taskOperationId,+ parentMessageId: userMessageId,+ parentMessageType: 'user',+ parentOperationId,+ });++ // 7. Extract the sub-agent's final assistant output as the tool result+ const subMessageKey = messageMapKey(subContext);+ const subTaskMessages = this.#get().dbMessagesMap[subMessageKey] || [];+ const lastAssistant = subTaskMessages.findLast((m) => m.role === 'assistant');+ const resultContent = lastAssistant?.content || 'Task completed';+ const totalToolCalls = subTaskMessages.filter((m) => m.role === 'tool').length;+ const { usage, cost, model } = runtimeResult || {};+ const totalTokens = usage?.llm?.tokens?.total;++ // 8. Persist final Thread status + metadata+ await aiAgentService.updateClientTaskThreadStatus({+ completionReason: 'done',+ metadata: {+ totalCost: cost?.total,+ totalMessages: subTaskMessages.length,+ totalTokens,+ totalToolCalls,+ },+ resultContent,+ threadId,+ });++ this.#get().completeOperation(taskOperationId);++ log('[%s] Completed, result %d chars', logId, resultContent.length);+ return { model, result: resultContent, success: true, threadId, totalToolCalls, totalTokens };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';+ log('[%s] Error: %O', logId, error);+ return {+ error: errorMessage,+ result: `Sub-agent execution failed: ${errorMessage}`,+ success: false,+ threadId: '',+ };+ }};}diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.tsindex 7470cccc247..84921eb67b2 100644--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts@@ -1,4 +1,8 @@-import { type ChatToolPayload, type RuntimeStepContext } from '@lobechat/types';+import {+ type ChatToolPayload,+ type RuntimeStepContext,+ type SubAgentCallbacks,+} from '@lobechat/types';import debug from 'debug';import { type MCPToolCallResult } from '@/libs/mcp';@@ -111,6 +115,29 @@ export class PluginTypesActionImpl {// Get group orchestration callbacks if available (for group management tools)const groupOrchestration = this.#get().getGroupOrchestrationCallbacks?.();+ // Sub-agent runner injected for sub-agent-spawning tools (lobe-agent.callSubAgent).+ // Runs the sub-agent in an isolated thread using the current client runtime+ // and resolves with its output, so the tool returns a normal tool result.+ const subAgentParentOperationId = rootRuntimeOperationId ?? operationId;+ const subAgent: SubAgentCallbacks = {+ run: (runParams) => {+ if (!agentId || !topicId) {+ return Promise.resolve({+ error: 'No agent context available for sub-agent execution',+ result: 'No agent context available for sub-agent execution',+ success: false,+ threadId: '',+ });+ }+ return this.#get().runClientSubAgent({+ ...runParams,+ agentId,+ parentOperationId: subAgentParentOperationId,+ topicId,+ });+ },+ };+// Create registerAfterCompletion function that registers callback to root runtime operationconst registerAfterCompletion = rootRuntimeOperationId? (callback: Parameters<typeof registerAfterCompletionCallback>[1]) => {@@ -161,6 +188,7 @@ export class PluginTypesActionImpl {rootRuntimeOperationContext?.sourceMessageId ??rootRuntimeOperationContext?.messageId,stepContext,+ subAgent,taskId,toolCallId: payload.id,topicId,diff --git a/src/store/chat/slices/thread/selectors/index.ts b/src/store/chat/slices/thread/selectors/index.tsindex 7e8bfdfba3a..6991544bef1 100644--- a/src/store/chat/slices/thread/selectors/index.ts+++ b/src/store/chat/slices/thread/selectors/index.ts@@ -1,4 +1,4 @@-import { type ThreadItem, type UIChatMessage } from '@lobechat/types';+import { type ThreadItem, ThreadType, type UIChatMessage } from '@lobechat/types';import { useAgentStore } from '@/store/agent';import { agentChatConfigSelectors } from '@/store/agent/selectors';@@ -34,7 +34,9 @@ const currentActiveThread = (s: ChatStoreState): ThreadItem | undefined => {const isActiveThreadSubagent = (s: ChatStoreState): boolean => {const thread = currentActiveThread(s);- return !!thread?.metadata?.subagentType;+ // Isolation threads (CC subagents + lobe-agent sub-agents) are driven by the+ // parent agent, so the thread view is read-only regardless of origin.+ return thread?.type === ThreadType.Isolation;};const getThreadsByTopic = (topicId?: string) => (s: ChatStoreState) => {