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(heterogeneous-agent): support CC subagent rendering (#14001)

Arvin Xub02b72726117
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index b7a7f9a51c5..c9f96efc2ea 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -243,8 +243,9 @@
"operation.contextCompression": "Context too long, compressing history...",
"operation.execAgentRuntime": "Preparing response",
"operation.execClientTask": "Executing task",
- "operation.execHeterogeneousAgent": "External agent running",
+ "operation.execHeterogeneousAgent": "{{name}} is running",
"operation.execServerAgentRuntime": "Task is running in the server. You are safe to leave this page",
+ "operation.heterogeneousAgentFallback": "External agent",
"operation.sendMessage": "Sending message",
"owner": "Group owner",
"pageCopilot.title": "Page Agent",
@@ -399,7 +400,10 @@
"task.status.initializing": "Initializing task...",
"task.subtask": "Subtask",
"task.title": "Tasks",
+ "thread.closeSubagentThread": "Collapse subagent conversation",
"thread.divider": "Subtopic",
+ "thread.openSubagentThread": "View full subagent conversation",
+ "thread.subagentBadge": "Subagent",
"thread.threadMessageCount": "{{messageCount}} messages",
"thread.title": "Subtopic",
"todoProgress.allCompleted": "All tasks completed",
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 75236f784a2..f00312e743c 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -65,6 +65,8 @@
"builtins.lobe-agent-management.render.installPlugin.plugin": "Plugin",
"builtins.lobe-agent-management.render.installPlugin.success": "Installed successfully",
"builtins.lobe-agent-management.title": "Agent Manager",
+ "builtins.lobe-claude-code.agent.instruction": "Instruction",
+ "builtins.lobe-claude-code.agent.result": "Result",
"builtins.lobe-claude-code.todoWrite.allDone": "All tasks completed",
"builtins.lobe-claude-code.todoWrite.currentStep": "Current step",
"builtins.lobe-claude-code.todoWrite.todos": "Todos",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 38e53e7d6a1..f6e98153d27 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -243,8 +243,9 @@
"operation.contextCompression": "ไธŠไธ‹ๆ–‡่ฟ‡้•ฟ๏ผŒๆญฃๅœจๅŽ‹็ผฉๅކๅฒ่ฎฐๅฝ•โ€ฆโ€ฆ",
"operation.execAgentRuntime": "ๅ‡†ๅค‡ๅ“ๅบ”ไธญ",
"operation.execClientTask": "ๆ‰ง่กŒไปปๅŠกไธญ",
- "operation.execHeterogeneousAgent": "ๅค–้ƒจไปฃ็†่ฟ่กŒไธญ",
+ "operation.execHeterogeneousAgent": "{{name}} ่ฟ่กŒไธญ",
"operation.execServerAgentRuntime": "ไปปๅŠกๆญฃๅœจๆœๅŠกๅ™จ่ฟ่กŒ๏ผŒๆ‚จๅฏไปฅๆ”พๅฟƒ็ฆปๅผ€ๆญค้กต้ข",
+ "operation.heterogeneousAgentFallback": "ๆ™บ่ƒฝไฝ“",
"operation.sendMessage": "ๆถˆๆฏๅ‘้€ไธญ",
"owner": "็พคไธป",
"pageCopilot.title": "ๆ–‡็จฟๅŠฉ็†",
@@ -399,7 +400,10 @@
"task.status.initializing": "ไปปๅŠกๅฏๅŠจไธญโ€ฆ",
"task.subtask": "ๅญไปปๅŠก",
"task.title": "ไปปๅŠก",
+ "thread.closeSubagentThread": "ๆ”ถ่ตทๅญๅฏน่ฏ",
"thread.divider": "ๅญ่ฏ้ข˜",
+ "thread.openSubagentThread": "ๆŸฅ็œ‹ๅฎŒๆ•ดๅญๅฏน่ฏ",
+ "thread.subagentBadge": "ๅญๆ™บ่ƒฝไฝ“",
"thread.threadMessageCount": "{{messageCount}} ๆกๆถˆๆฏ",
"thread.title": "ๅญ่ฏ้ข˜",
"todoProgress.allCompleted": "ๅทฒๅฎŒๆˆๆ‰€ๆœ‰ไปปๅŠก",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 0d15b3859cb..ef2a1549e82 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -65,6 +65,8 @@
"builtins.lobe-agent-management.render.installPlugin.plugin": "ๆ’ไปถ",
"builtins.lobe-agent-management.render.installPlugin.success": "ๅฎ‰่ฃ…ๆˆๅŠŸ",
"builtins.lobe-agent-management.title": "ไปฃ็†็ฎก็†ๅ™จ",
+ "builtins.lobe-claude-code.agent.instruction": "ๆŒ‡ไปค",
+ "builtins.lobe-claude-code.agent.result": "็ป“ๆžœ",
"builtins.lobe-claude-code.todoWrite.allDone": "ๅ…จ้ƒจไปปๅŠกๅทฒๅฎŒๆˆ",
"builtins.lobe-claude-code.todoWrite.currentStep": "ๅฝ“ๅ‰ๆญฅ้ชค",
"builtins.lobe-claude-code.todoWrite.todos": "ๅพ…ๅŠž",
diff --git a/package.json b/package.json
index 954fab7a016..92199ce7871 100644
--- a/package.json
+++ b/package.json
@@ -211,6 +211,7 @@
"@lobechat/builtin-tool-agent-management": "workspace:*",
"@lobechat/builtin-tool-brief": "workspace:*",
"@lobechat/builtin-tool-calculator": "workspace:*",
+ "@lobechat/builtin-tool-claude-code": "workspace:*",
"@lobechat/builtin-tool-cloud-sandbox": "workspace:*",
"@lobechat/builtin-tool-creds": "workspace:*",
"@lobechat/builtin-tool-cron": "workspace:*",
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/Agent.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/Agent.tsx
new file mode 100644
index 00000000000..aa1986b6f8c
--- /dev/null
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/Agent.tsx
@@ -0,0 +1,85 @@
+'use client';
+
+import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { GroupBotIcon } from '@lobehub/ui/icons';
+import { createStaticStyles, cx } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { type AgentArgs, ClaudeCodeApiName } from '../../types';
+import { resolveCCSubagentType } from '../subagentTypes';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ chip: css`
+ overflow: hidden;
+ display: inline-flex;
+ flex-shrink: 1;
+ align-items: center;
+
+ min-width: 0;
+ max-width: 60%;
+ margin-inline-start: 6px;
+ padding-block: 2px;
+ padding-inline: 10px;
+ border-radius: 999px;
+
+ background: ${cssVar.colorFillTertiary};
+ `,
+ chipText: css`
+ overflow: hidden;
+
+ min-width: 0;
+
+ font-size: 12px;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ icon: css`
+ flex-shrink: 0;
+ margin-inline-end: 6px;
+ color: ${cssVar.colorTextDescription};
+ `,
+ label: css`
+ color: ${cssVar.colorText};
+ `,
+}));
+
+/**
+ * CC's subagent-spawn tool. `subagent_type` is the template ("Explore",
+ * "general-purpose", ...) and becomes the primary label โ€” saying "Agent"
+ * is redundant once we're already rendering inside the Agent inspector.
+ * `description` is the 3-5 word title the model writes ("Run pwd command")
+ * and goes in the chip; the full `prompt` is too long for a collapsed header.
+ */
+export const AgentInspector = memo<BuiltinInspectorProps<AgentArgs>>(
+ ({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
+ const { t } = useTranslation('plugin');
+ const fallbackLabel = t(ClaudeCodeApiName.Agent as any);
+
+ const source = args ?? partialArgs;
+ const description = source?.description?.trim();
+ const subagentType = source?.subagent_type?.trim();
+
+ const isShiny = isArgumentsStreaming || isLoading;
+
+ const resolved = resolveCCSubagentType(subagentType);
+ const Icon = resolved?.icon ?? GroupBotIcon;
+ const labelText = resolved?.label ?? fallbackLabel;
+
+ return (
+ <div className={cx(inspectorTextStyles.root, isShiny && shinyTextStyles.shinyText)}>
+ <Icon className={styles.icon} size={14} />
+ <span className={styles.label}>{labelText}</span>
+ {description && (
+ <span className={styles.chip}>
+ <span className={styles.chipText}>{description}</span>
+ </span>
+ )}
+ </div>
+ );
+ },
+);
+
+AgentInspector.displayName = 'ClaudeCodeAgentInspector';
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/index.ts b/packages/builtin-tool-claude-code/src/client/Inspector/index.ts
index afdd34704bc..e5a2e80344e 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/index.ts
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/index.ts
@@ -7,6 +7,7 @@ import {
} from '@lobechat/shared-tool-ui/inspectors';
import { ClaudeCodeApiName } from '../../types';
+import { AgentInspector } from './Agent';
import { EditInspector } from './Edit';
import { ReadInspector } from './Read';
import { SkillInspector } from './Skill';
@@ -23,6 +24,7 @@ import { WriteInspector } from './Write';
// need `pattern`. Edit / Read / Write need arg mapping (or synthesized plugin
// state for diff stats), so they live in their own sibling files.
export const ClaudeCodeInspectors = {
+ [ClaudeCodeApiName.Agent]: AgentInspector,
[ClaudeCodeApiName.Bash]: createRunCommandInspector(ClaudeCodeApiName.Bash),
[ClaudeCodeApiName.Edit]: EditInspector,
[ClaudeCodeApiName.Glob]: createGlobLocalFilesInspector(ClaudeCodeApiName.Glob),
diff --git a/packages/builtin-tool-claude-code/src/client/Render/Agent/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/Agent/index.tsx
new file mode 100644
index 00000000000..f6011ca1fa6
--- /dev/null
+++ b/packages/builtin-tool-claude-code/src/client/Render/Agent/index.tsx
@@ -0,0 +1,151 @@
+'use client';
+
+import type { BuiltinRenderProps } from '@lobechat/types';
+import { Button, Flexbox, Markdown, Text } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+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 { AgentArgs } from '../../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ padding-block: 4px;
+ `,
+ label: css`
+ padding-inline-start: 4px;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ labelRow: css`
+ margin-block-end: 4px;
+ `,
+ 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};
+ `,
+ resultBox: css`
+ padding-block: 8px;
+ padding-inline: 12px;
+ border-radius: ${cssVar.borderRadiusLG};
+ background: ${cssVar.colorBgContainer};
+ `,
+}));
+
+/**
+ * Render for CC's `Agent` (subagent-spawn) tool.
+ *
+ * The Inspector row already shows `[icon] subagent_type [chip: description]`,
+ * so this view skips the header and goes straight to the two blocks the
+ * Inspector can't fit: the full `prompt` and the subagent's closing summary
+ * (`content`) โ€” both as Markdown because CC routinely passes multi-paragraph
+ * or code-fenced prompts and the summary is prose. Each block is labelled
+ * since the two Markdown bubbles are otherwise indistinguishable once the
+ * subagent's reply happens to use the same tone as the prompt.
+ *
+ * Each subagent spawn also persists as a Thread linked by
+ * `metadata.sourceToolCallId = toolCallId`; when that Thread exists, the
+ * result-label row exposes a toggle to open / collapse it in the portal
+ * (clicking again while already open closes it rather than acting as a
+ * dead-end disabled state). The executor creates the Thread lazily on the
+ * first subagent event, so the lookup can briefly return `undefined` โ€” the
+ * button is hidden in that window instead of faked into a no-op.
+ */
+const Agent = memo<BuiltinRenderProps<AgentArgs, unknown, string>>(
+ ({ args, content, toolCallId }) => {
+ const { t } = useTranslation('plugin');
+ const { t: tChat } = useTranslation('chat');
+ const prompt = args?.prompt?.trim();
+ const result = typeof content === 'string' ? content.trim() : '';
+
+ const subagentThread = useChatStore((s) =>
+ toolCallId
+ ? (threadSelectors.currentTopicThreads(s) ?? []).find(
+ (thread) => thread.metadata?.sourceToolCallId === toolCallId,
+ )
+ : 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;
+
+ 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>
+ )}
+
+ {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>
+ );
+ },
+);
+
+Agent.displayName = 'ClaudeCodeAgent';
+
+export default Agent;
diff --git a/packages/builtin-tool-claude-code/src/client/Render/Edit/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/Edit/index.tsx
index cda1c76260e..7d62ac07d84 100644
--- a/packages/builtin-tool-claude-code/src/client/Render/Edit/index.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Render/Edit/index.tsx
@@ -20,7 +20,7 @@ const Edit = memo<BuiltinRenderProps<EditArgs>>(({ args }) => {
const ext = filePath ? path.extname(filePath).slice(1).toLowerCase() : '';
return (
- <Flexbox gap={12}>
+ <Flexbox gap={12} paddingInline={8}>
<CodeDiff
fileName={fileName || filePath}
language={ext || undefined}
diff --git a/packages/builtin-tool-claude-code/src/client/Render/index.ts b/packages/builtin-tool-claude-code/src/client/Render/index.ts
index acf493de78f..aa343d71aba 100644
--- a/packages/builtin-tool-claude-code/src/client/Render/index.ts
+++ b/packages/builtin-tool-claude-code/src/client/Render/index.ts
@@ -2,6 +2,7 @@ import { RunCommandRender } from '@lobechat/shared-tool-ui/renders';
import type { RenderDisplayControl } from '@lobechat/types';
import { ClaudeCodeApiName } from '../../types';
+import Agent from './Agent';
import Edit from './Edit';
import Glob from './Glob';
import Grep from './Grep';
@@ -17,6 +18,7 @@ import Write from './Write';
* visualizations, keyed so `getBuiltinRender('claude-code', apiName)` resolves.
*/
export const ClaudeCodeRenders = {
+ [ClaudeCodeApiName.Agent]: Agent,
// RunCommand already renders `args.command` + combined output the way CC emits โ€”
// use the shared component directly instead of wrapping it in a re-export file.
[ClaudeCodeApiName.Bash]: RunCommandRender,
diff --git a/packages/builtin-tool-claude-code/src/client/index.ts b/packages/builtin-tool-claude-code/src/client/index.ts
index 45ec0b4d439..c2f4d31bea7 100644
--- a/packages/builtin-tool-claude-code/src/client/index.ts
+++ b/packages/builtin-tool-claude-code/src/client/index.ts
@@ -1,3 +1,4 @@
export { ClaudeCodeApiName, ClaudeCodeIdentifier } from '../types';
export { ClaudeCodeInspectors } from './Inspector';
export { ClaudeCodeRenderDisplayControls, ClaudeCodeRenders } from './Render';
+export { CC_SUBAGENT_TYPES, type CCSubagentTypeInfo, resolveCCSubagentType } from './subagentTypes';
diff --git a/packages/builtin-tool-claude-code/src/client/subagentTypes.ts b/packages/builtin-tool-claude-code/src/client/subagentTypes.ts
new file mode 100644
index 00000000000..2f6a9ba0d0e
--- /dev/null
+++ b/packages/builtin-tool-claude-code/src/client/subagentTypes.ts
@@ -0,0 +1,40 @@
+import { GroupBotIcon } from '@lobehub/ui/icons';
+import { Compass, type LucideIcon, Search, Settings } from 'lucide-react';
+import type { FC } from 'react';
+
+type IconComponent = LucideIcon | FC<{ className?: string; size?: number }>;
+
+export interface CCSubagentTypeInfo {
+ icon: IconComponent;
+ label: string;
+}
+
+/**
+ * Known subagent templates shipped with CC. `subagent_type` on the Agent
+ * tool call is matched against this map; unknown values fall through to
+ * the raw string plus a generic bot icon so user-defined subagents still
+ * render sensibly.
+ *
+ * UI-level (icons are React components) so it lives in the CC client entry
+ * rather than `@lobechat/heterogeneous-agents` โ€” that package stays a
+ * pure-data home for adapter orchestration.
+ */
+export const CC_SUBAGENT_TYPES: Record<string, CCSubagentTypeInfo> = {
+ 'Explore': { icon: Search, label: 'Explore' },
+ 'Plan': { icon: Compass, label: 'Plan' },
+ 'general-purpose': { icon: GroupBotIcon, label: 'General purpose' },
+ 'statusline-setup': { icon: Settings, label: 'Statusline setup' },
+};
+
+/**
+ * Resolve a `subagent_type` string to `{ icon, label }`. Returns `undefined`
+ * when the input is empty/whitespace so callers can distinguish "no value"
+ * from "unknown value" โ€” the latter gets a synthesized fallback.
+ */
+export const resolveCCSubagentType = (
+ subagentType: string | undefined | null,
+): CCSubagentTypeInfo | undefined => {
+ const trimmed = subagentType?.trim();
+ if (!trimmed) return undefined;
+ return CC_SUBAGENT_TYPES[trimmed] ?? { icon: GroupBotIcon, label: trimmed };
+};
diff --git a/packages/builtin-tool-claude-code/src/index.ts b/packages/builtin-tool-claude-code/src/index.ts
index 389c3ba352d..53d1afe0290 100644
--- a/packages/builtin-tool-claude-code/src/index.ts
+++ b/packages/builtin-tool-claude-code/src/index.ts
@@ -1,7 +1,10 @@
export {
+ type AgentArgs,
ClaudeCodeApiName,
ClaudeCodeIdentifier,
type ClaudeCodeTodoItem,
type ClaudeCodeTodoStatus,
+ type SkillArgs,
type TodoWriteArgs,
+ type ToolSearchArgs,
} from './types';
diff --git a/packages/builtin-tool-claude-code/src/types.ts b/packages/builtin-tool-claude-code/src/types.ts
index 9b8993c9912..18cc6c9ea51 100644
--- a/packages/builtin-tool-claude-code/src/types.ts
+++ b/packages/builtin-tool-claude-code/src/types.ts
@@ -7,16 +7,10 @@ export const ClaudeCodeIdentifier = 'claude-code';
/**
* Canonical Claude Code tool names (the `name` field on `tool_use` blocks).
- * Kept as string literals so future additions (WebSearch, Task, etc.) can be
+ * Kept as string literals so future additions (WebSearch, etc.) can be
* wired in without downstream enum migrations.
*/
export enum ClaudeCodeApiName {
- Bash = 'Bash',
- Edit = 'Edit',
- Glob = 'Glob',
- Grep = 'Grep',
- Read = 'Read',
- Skill = 'Skill',
/**
* Spawns a subagent. CC emits this as a regular `tool_use`; downstream
* events for the subagent's internal turns are tagged with
@@ -24,9 +18,17 @@ export enum ClaudeCodeApiName {
* subagent's final answer arrives as the `tool_result` for this id.
* The executor turns this into a Thread (linked via
* `metadata.sourceToolCallId = tool_use.id`) instead of a separate
- * `role: 'task'` message.
+ * `role: 'task'` message. We keep CC's own name (`Agent`) rather than
+ * remapping to our internal "task" vocabulary, which is reserved for a
+ * different concept.
*/
- Task = 'Task',
+ Agent = 'Agent',
+ Bash = 'Bash',
+ Edit = 'Edit',
+ Glob = 'Glob',
+ Grep = 'Grep',
+ Read = 'Read',
+ Skill = 'Skill',
TodoWrite = 'TodoWrite',
ToolSearch = 'ToolSearch',
Write = 'Write',
@@ -72,12 +74,12 @@ export interface ToolSearchArgs {
}
/**
- * Arguments for CC's built-in `Task` tool. The model fills these in when it
+ * Arguments for CC's built-in `Agent` tool. The model fills these in when it
* decides to delegate work to a subagent: the description shows up in the
* folded header, the prompt becomes the subagent's initial user message, and
* `subagent_type` selects which subagent template handles it.
*/
-export interface TaskArgs {
+export interface AgentArgs {
description?: string;
prompt?: string;
subagent_type?: string;
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
index bb7f6106a72..75318d5bd97 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
@@ -1165,4 +1165,395 @@ describe('ClaudeCodeAdapter', () => {
expect(adapter.adapt({ event: null, type: 'stream_event' })).toEqual([]);
});
});
+
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ // Subagent lineage (Claude Code Agent-tool spawned flows)
+ // Shape reference: .heerogeneous-tracing/cc-streaming.json
+ // main agent emits tool_use {name:'Agent', id:'toolu_parent'}
+ // subagent events carry raw.parent_tool_use_id = 'toolu_parent'
+ // subagent message.id differs from main agent's per turn
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ describe('subagent lineage', () => {
+ const init = { subtype: 'init' as const, type: 'system' as const };
+ const mainAssistant = (id: string, toolUse: any) => ({
+ message: { content: [toolUse], id },
+ type: 'assistant',
+ });
+ const subAgent = (id: string, parent: string, block: any) => ({
+ message: { content: [block], id },
+ parent_tool_use_id: parent,
+ type: 'assistant',
+ });
+
+ it('emits subagent context as peer field on the chunk (NOT on ToolCallPayload)', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+ adapter.adapt(
+ mainAssistant('msg_main', {
+ id: 'toolu_parent',
+ input: {},
+ name: 'Task',
+ type: 'tool_use',
+ }),
+ );
+
+ const events = adapter.adapt(
+ subAgent('msg_sub_1', 'toolu_parent', {
+ id: 'toolu_child',
+ input: { command: 'ls' },
+ name: 'Bash',
+ type: 'tool_use',
+ }),
+ );
+
+ const toolsChunk = events.find(
+ (e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
+ );
+ expect(toolsChunk).toBeDefined();
+ // Peer field on chunk data โ€” describes the whole chunk's origin
+ expect(toolsChunk!.data.subagent).toMatchObject({
+ parentToolCallId: 'toolu_parent',
+ subagentMessageId: 'msg_sub_1',
+ });
+ // Payload stays minimal โ€” no lineage inside the tool call
+ const tool = toolsChunk!.data.toolsCalling[0];
+ expect(tool.id).toBe('toolu_child');
+ expect(tool).not.toHaveProperty('parentToolCallId');
+ expect(tool).not.toHaveProperty('subagentSpawn');
+ });
+
+ it('does NOT emit stream_end / newStep when subagent introduces new message.id', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+ adapter.adapt(
+ mainAssistant('msg_main', {
+ id: 'toolu_parent',
+ input: {},
+ name: 'Agent',
+ type: 'tool_use',
+ }),
+ );
+
+ const events = adapter.adapt(
+ subAgent('msg_sub_1', 'toolu_parent', {
+ id: 'toolu_child',
+ input: {},
+ name: 'Read',
+ type: 'tool_use',
+ }),
+ );
+
+ expect(events.some((e) => e.type === 'stream_end')).toBe(false);
+ const starts = events.filter((e) => e.type === 'stream_start');
+ // No newStep stream_start for subagent turn transitions
+ expect(starts.some((e) => e.data?.newStep)).toBe(false);
+ });
+
+ it('does NOT emit turn_metadata step_complete for subagent events', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+ adapter.adapt(
+ mainAssistant('msg_main', {
+ id: 'toolu_parent',
+ input: {},
+ name: 'Agent',
+ type: 'tool_use',
+ }),
+ );
+
+ const events = adapter.adapt({
+ message: {
+ content: [{ id: 'toolu_child', input: {}, name: 'Bash', type: 'tool_use' }],
+ id: 'msg_sub',
+ model: 'claude-sonnet-4-6',
+ usage: { input_tokens: 5, output_tokens: 10 },
+ },
+ parent_tool_use_id: 'toolu_parent',
+ type: 'assistant',
+ });
+
+ const meta = events.find(
+ (e) => e.type === 'step_complete' && e.data?.phase === 'turn_metadata',
+ );
+ expect(meta).toBeUndefined();
+ });
+
+ it('emits subagent text/reasoning as chunks with subagent peer (NOT into main bubble)', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+ adapter.adapt(
+ mainAssistant('msg_main', {
+ id: 'toolu_parent',
+ input: {},
+ name: 'Agent',
+ type: 'tool_use',
+ }),
+ );
+
+ const events = adapter.adapt(
+ subAgent('msg_sub', 'toolu_parent', { text: 'sub summary', type: 'text' }),
+ );
+
+ const textChunks = events.filter(
+ (e) => e.type === 'stream_chunk' && e.data.chunkType === 'text',
+ );
+ // Text is now emitted so the thread view can show the subagent's
+ // closing summary. Critically, each chunk carries the `subagent`
+ // peer field โ€” the executor routes these to the in-thread
+ // assistant's content, NOT to the main assistant's accumulator.
+ expect(textChunks).toHaveLength(1);
+ expect(textChunks[0].data.content).toBe('sub summary');
+ expect(textChunks[0].data.subagent).toMatchObject({
+ parentToolCallId: 'toolu_parent',
+ subagentMessageId: 'msg_sub',
+ });
+ });
+
+ it('emits subagent reasoning (thinking) with subagent peer', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+ adapter.adapt(
+ mainAssistant('msg_main', {
+ id: 'toolu_parent',
+ input: {},
+ name: 'Agent',
+ type: 'tool_use',
+ }),
+ );
+
+ const events = adapter.adapt(
+ subAgent('msg_sub', 'toolu_parent', {
+ thinking: 'weighing the options',
+ type: 'thinking',
+ }),
+ );
+
+ const reasoningChunks = events.filter(
+ (e) => e.type === 'stream_chunk' && e.data.chunkType === 'reasoning',
+ );
+ expect(reasoningChunks).toHaveLength(1);
+ expect(reasoningChunks[0].data.reasoning).toBe('weighing the options');
+ expect(reasoningChunks[0].data.subagent?.parentToolCallId).toBe('toolu_parent');
+ });
+
+ it('resumes main-agent step boundary AFTER subagent completes', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+ adapter.adapt(
+ mainAssistant('msg_main_1', {
+ id: 'toolu_parent',
+ input: {},
+ name: 'Agent',
+ type: 'tool_use',
+ }),
+ );
+ // Subagent runs (no step boundaries)
+ adapter.adapt(
+ subAgent('msg_sub_1', 'toolu_parent', {
+ id: 'toolu_child_1',
+ input: {},
+ name: 'Bash',
+ type: 'tool_use',
+ }),
+ );
+ adapter.adapt(
+ subAgent('msg_sub_2', 'toolu_parent', {
+ id: 'toolu_child_2',
+ input: {},
+ name: 'Read',
+ type: 'tool_use',
+ }),
+ );
+
+ // Main agent resumes with a new message.id and no parent โ€” SHOULD fire newStep
+ const events = adapter.adapt({
+ message: {
+ content: [{ text: 'follow-up', type: 'text' }],
+ id: 'msg_main_2',
+ },
+ type: 'assistant',
+ });
+
+ expect(events.some((e) => e.type === 'stream_end')).toBe(true);
+ expect(events.some((e) => e.type === 'stream_start' && e.data?.newStep)).toBe(true);
+ });
+
+ it('tool_result events for subagent tools still propagate to executor', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+ adapter.adapt(
+ mainAssistant('msg_main', {
+ id: 'toolu_parent',
+ input: {},
+ name: 'Agent',
+ type: 'tool_use',
+ }),
+ );
+ adapter.adapt(
+ subAgent('msg_sub', 'toolu_parent', {
+ id: 'toolu_child',
+ input: {},
+ name: 'Bash',
+ type: 'tool_use',
+ }),
+ );
+
+ const events = adapter.adapt({
+ message: {
+ content: [{ content: 'ok', tool_use_id: 'toolu_child', type: 'tool_result' }],
+ },
+ parent_tool_use_id: 'toolu_parent',
+ type: 'user',
+ });
+
+ const result = events.find((e) => e.type === 'tool_result');
+ expect(result).toBeDefined();
+ expect(result!.data.toolCallId).toBe('toolu_child');
+ });
+
+ it('stamps spawnMetadata on the FIRST subagent event only (lazy Thread create)', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+ // Main agent emits the Task tool_use โ€” adapter caches its args
+ // for the upcoming subagent announcement.
+ adapter.adapt(
+ mainAssistant('msg_main', {
+ id: 'toolu_task',
+ input: {
+ description: 'Find failing tests',
+ prompt: 'run the suite and list failures',
+ subagent_type: 'Explore',
+ },
+ name: 'Task',
+ type: 'tool_use',
+ }),
+ );
+
+ // First subagent event โ€” carries spawnMetadata
+ const first = adapter.adapt(
+ subAgent('msg_sub_1', 'toolu_task', {
+ id: 'toolu_child_1',
+ input: {},
+ name: 'Bash',
+ type: 'tool_use',
+ }),
+ );
+ const firstChunk = first.find(
+ (e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
+ );
+ expect(firstChunk!.data.subagent.spawnMetadata).toEqual({
+ description: 'Find failing tests',
+ prompt: 'run the suite and list failures',
+ subagentType: 'Explore',
+ });
+
+ // Second subagent event for same parent โ€” lineage preserved, but
+ // spawnMetadata is absent (executor already created the Thread).
+ const second = adapter.adapt(
+ subAgent('msg_sub_2', 'toolu_task', {
+ id: 'toolu_child_2',
+ input: {},
+ name: 'Read',
+ type: 'tool_use',
+ }),
+ );
+ const secondChunk = second.find(
+ (e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
+ );
+ expect(secondChunk!.data.subagent.parentToolCallId).toBe('toolu_task');
+ expect(secondChunk!.data.subagent.spawnMetadata).toBeUndefined();
+ });
+
+ it('extracts spawnMetadata from the `Agent` spawn-tool variant too (not just Task)', () => {
+ // Real CC traces emit `Agent` for general-purpose subagents, not just
+ // `Task` โ€” the adapter should cache input for ANY main-agent tool and
+ // build spawnMetadata off whichever spawn-tool variant was used.
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+ adapter.adapt(
+ mainAssistant('msg_main', {
+ id: 'toolu_agent',
+ input: {
+ description: 'lookup the pwd',
+ prompt: 'run pwd and report it back',
+ subagent_type: 'general-purpose',
+ },
+ name: 'Agent',
+ type: 'tool_use',
+ }),
+ );
+
+ const first = adapter.adapt(
+ subAgent('msg_sub_1', 'toolu_agent', {
+ id: 'toolu_child',
+ input: {},
+ name: 'Bash',
+ type: 'tool_use',
+ }),
+ );
+ const firstChunk = first.find(
+ (e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
+ );
+ expect(firstChunk!.data.subagent.spawnMetadata).toEqual({
+ description: 'lookup the pwd',
+ prompt: 'run pwd and report it back',
+ subagentType: 'general-purpose',
+ });
+ });
+
+ it('does NOT stamp subagent context on non-subagent (main-agent) tool_uses', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+
+ const events = adapter.adapt(
+ mainAssistant('msg_main', {
+ id: 'toolu_read',
+ input: { file_path: '/a.ts' },
+ name: 'Read',
+ type: 'tool_use',
+ }),
+ );
+
+ const toolsChunk = events.find(
+ (e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
+ );
+ expect(toolsChunk!.data.subagent).toBeUndefined();
+ });
+
+ it('stamps subagent context on tool_result for subagent inner tools', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+ adapter.adapt(
+ mainAssistant('msg_main', {
+ id: 'toolu_task',
+ input: { description: 'x' },
+ name: 'Task',
+ type: 'tool_use',
+ }),
+ );
+ adapter.adapt(
+ subAgent('msg_sub', 'toolu_task', {
+ id: 'toolu_child',
+ input: {},
+ name: 'Bash',
+ type: 'tool_use',
+ }),
+ );
+
+ // Subagent's tool_result arrives in a `user` event with parent_tool_use_id.
+ const events = adapter.adapt({
+ message: {
+ content: [{ content: 'ok', tool_use_id: 'toolu_child', type: 'tool_result' }],
+ },
+ parent_tool_use_id: 'toolu_task',
+ type: 'user',
+ });
+
+ const result = events.find((e) => e.type === 'tool_result');
+ expect(result!.data.subagent).toEqual({ parentToolCallId: 'toolu_task' });
+ const end = events.find((e) => e.type === 'tool_end');
+ expect(end!.data.subagent).toEqual({ parentToolCallId: 'toolu_task' });
+ });
+ });
});
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
index 8e208bebeab..fb9690c89f0 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
@@ -45,6 +45,7 @@ import type {
AgentEventAdapter,
HeterogeneousAgentEvent,
StreamChunkData,
+ SubagentEventContext,
ToolCallPayload,
ToolResultData,
UsageData,
@@ -174,6 +175,27 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
* bounded.
*/
private todoWriteInputs = new Map<string, TodoWriteArgs>();
+ /**
+ * Cached inputs for main-agent tool_uses keyed by their tool_use.id.
+ * Populated for every main-agent tool_use (not just `Task`) because
+ * CC uses multiple tool names for subagent delegation โ€” real traces
+ * emit `Agent` for general-purpose subagents while the spec documents
+ * `Task`. Keying on "any main-agent tool" and looking up by
+ * `parent_tool_use_id` on the FIRST subagent event lets us extract
+ * `description` / `prompt` / `subagent_type` regardless of which
+ * spawn-tool variant the model used. Kept adapter-internal โ€” the
+ * executor never reads this map; it only sees the normalized
+ * `SubagentSpawnMetadata`.
+ */
+ private mainToolInputsById = new Map<string, Record<string, any>>();
+ /**
+ * Set of parent tool_use ids whose spawn metadata has already been
+ * announced on a subagent event. Guarantees `spawnMetadata` appears
+ * exactly once per subagent run โ€” on the first subagent chunk for that
+ * parent โ€” so the executor's lazy-create logic isn't tempted to
+ * recreate the Thread on every chunk.
+ */
+ private announcedSpawns = new Set<string>();
adapt(raw: any): HeterogeneousAgentEvent[] {
if (!raw || typeof raw !== 'object') return [];
@@ -227,6 +249,15 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
const content = raw.message?.content;
if (!Array.isArray(content)) return [];
+ // CC tags subagent events (Agent / Task tool spawned flows) with
+ // `parent_tool_use_id` pointing back at the outer tool_use. These are a
+ // side-channel of the main agent's stream โ€” they must not advance the
+ // main step tracker, emit text into the main bubble, or double-count
+ // usage. Route them through a dedicated handler so the main-agent flow
+ // below stays free of subagent special cases.
+ const parentToolUseId: string | undefined = raw.parent_tool_use_id;
+ if (parentToolUseId) return this.handleSubagentAssistant(raw, parentToolUseId);
+
const events: HeterogeneousAgentEvent[] = [];
const messageId = raw.message?.id;
@@ -257,15 +288,20 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
break;
}
case 'tool_use': {
- const toolPayload: ToolCallPayload = {
+ newToolCalls.push({
apiName: block.name,
arguments: JSON.stringify(block.input || {}),
id: block.id,
identifier: 'claude-code',
type: 'default',
- };
- newToolCalls.push(toolPayload);
+ });
this.pendingToolCalls.add(block.id);
+ // Cache EVERY main-agent tool_use input so the subagent-spawn
+ // handler (`emitToolChunk`) can look up the parent's args on
+ // first subagent event regardless of which spawn-tool name CC
+ // used (`Task`, `Agent`, etc.). Non-spawn tools occupy a tiny
+ // amount of memory and get pruned naturally when the run ends.
+ if (block.input) this.mainToolInputsById.set(block.id, block.input);
if (block.name === ClaudeCodeApiName.TodoWrite && block.input) {
this.todoWriteInputs.set(block.id, block.input as TodoWriteArgs);
}
@@ -287,22 +323,171 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
this.makeChunkEvent({ chunkType: 'reasoning', reasoning: reasoningParts.join('') }),
);
}
- if (newToolCalls.length > 0) {
- const msgKey = messageId ?? '';
- const existing = this.toolCallsByMessageId.get(msgKey) ?? [];
- const existingIds = new Set(existing.map((t) => t.id));
- const freshTools = newToolCalls.filter((t) => !existingIds.has(t.id));
- const cumulative = [...existing, ...freshTools];
- this.toolCallsByMessageId.set(msgKey, cumulative);
-
- events.push(this.makeChunkEvent({ chunkType: 'tools_calling', toolsCalling: cumulative }));
- // tool_start fires only for newly-seen ids so an echoed tool_use does
- // not re-open a closed lifecycle.
- for (const t of freshTools) {
- events.push(this.makeEvent('tool_start', { toolCalling: t }));
+ events.push(...this.emitToolChunk(newToolCalls, messageId));
+
+ return events;
+ }
+
+ /**
+ * Handle a subagent assistant event (tagged with `parent_tool_use_id`).
+ *
+ * Subagent events are a side-channel of the main agent's stream and have
+ * two hard constraints:
+ * - no main-agent step boundary (each subagent turn introduces a new
+ * `message.id`; flushing that as a newStep would orphan main-agent
+ * bubbles)
+ * - no model / usage tracking on the main agent (CC's `result` event
+ * carries the authoritative grand total; re-summing per-turn deltas
+ * here would double-count against the main agent)
+ *
+ * Text / reasoning from subagent events ARE emitted โ€” as `stream_chunk`
+ * events tagged with the `subagent` peer field โ€” so the executor can
+ * accumulate them into the in-thread assistant's content, giving the
+ * Thread view a readable subagent conversation (user โ†’ assistant text
+ * โ†’ tools โ†’ assistant text โ†’ ...). Without this the thread only ever
+ * shows tool calls with no closing reasoning / summary.
+ *
+ * Subagent lineage lives as event-level **peer fields** on each chunk
+ * (`subagent.parentToolCallId` + `subagent.subagentMessageId`), not on
+ * individual `ToolCallPayload` items โ€” tool payloads stay minimal and
+ * persistence-safe.
+ */
+ private handleSubagentAssistant(raw: any, parentToolUseId: string): HeterogeneousAgentEvent[] {
+ const content = raw.message?.content;
+ if (!Array.isArray(content)) return [];
+
+ const messageId: string | undefined = raw.message?.id;
+ const subagentCtx = {
+ parentToolCallId: parentToolUseId,
+ subagentMessageId: messageId ?? '',
+ };
+
+ const textParts: string[] = [];
+ const reasoningParts: string[] = [];
+ const newToolCalls: ToolCallPayload[] = [];
+ for (const block of content) {
+ switch (block.type) {
+ case 'text': {
+ if (block.text) textParts.push(block.text);
+ break;
+ }
+ case 'thinking': {
+ if (block.thinking) reasoningParts.push(block.thinking);
+ break;
+ }
+ case 'tool_use': {
+ newToolCalls.push({
+ apiName: block.name,
+ arguments: JSON.stringify(block.input || {}),
+ id: block.id,
+ identifier: 'claude-code',
+ type: 'default',
+ });
+ this.pendingToolCalls.add(block.id);
+ if (block.name === ClaudeCodeApiName.TodoWrite && block.input) {
+ this.todoWriteInputs.set(block.id, block.input as TodoWriteArgs);
+ }
+ break;
+ }
+ }
+ }
+
+ const events: HeterogeneousAgentEvent[] = [];
+
+ // Subagent text / reasoning chunks โ€” NOT deduped against
+ // `messagesWithStreamedText` (unlike the main-agent path) because
+ // subagent events don't arrive via `stream_event` partial-messages
+ // deltas; the full block IS the only emission.
+ if (textParts.length > 0) {
+ events.push(
+ this.makeChunkEvent({
+ chunkType: 'text',
+ content: textParts.join(''),
+ subagent: subagentCtx,
+ }),
+ );
+ }
+ if (reasoningParts.length > 0) {
+ events.push(
+ this.makeChunkEvent({
+ chunkType: 'reasoning',
+ reasoning: reasoningParts.join(''),
+ subagent: subagentCtx,
+ }),
+ );
+ }
+ events.push(...this.emitToolChunk(newToolCalls, messageId, subagentCtx));
+ return events;
+ }
+
+ /**
+ * Accumulate new tool_use blocks for a message.id and emit the
+ * `tools_calling` chunk + `tool_start` lifecycle events.
+ *
+ * CC streams each tool_use in its OWN assistant event and the downstream
+ * handler's in-memory `assistant.tools` update uses a REPLACING array
+ * merge โ€” so the chunk must carry every tool seen on this turn, not just
+ * the latest, or prior tools render as orphans until the next
+ * `fetchAndReplaceMessages`. `tool_start` fires only for newly-seen ids
+ * so an echoed tool_use does not re-open a closed lifecycle.
+ *
+ * When `subagentCtx` is provided, the chunk + each tool_start event
+ * gets the context stamped as a peer field. The FIRST chunk for a new
+ * parent (tracked via `announcedSpawns`) also carries `spawnMetadata`
+ * built from the cached Task args, so the executor can lazy-create
+ * the Thread without knowing about CC-specific argument shapes.
+ */
+ private emitToolChunk(
+ newToolCalls: ToolCallPayload[],
+ messageId: string | undefined,
+ subagentCtx?: { parentToolCallId: string; subagentMessageId: string },
+ ): HeterogeneousAgentEvent[] {
+ if (newToolCalls.length === 0) return [];
+
+ const msgKey = messageId ?? '';
+ const existing = this.toolCallsByMessageId.get(msgKey) ?? [];
+ const existingIds = new Set(existing.map((t) => t.id));
+ const freshTools = newToolCalls.filter((t) => !existingIds.has(t.id));
+ const cumulative = [...existing, ...freshTools];
+ this.toolCallsByMessageId.set(msgKey, cumulative);
+
+ // Build the `subagent` peer field โ€” stamped on the chunk + each
+ // tool_start. Only the first emission for a new parent carries
+ // spawnMetadata; subsequent ones carry just the lineage ids.
+ const subagent: SubagentEventContext | undefined = subagentCtx
+ ? {
+ parentToolCallId: subagentCtx.parentToolCallId,
+ subagentMessageId: subagentCtx.subagentMessageId,
+ }
+ : undefined;
+ if (subagent && !this.announcedSpawns.has(subagent.parentToolCallId)) {
+ const args = this.mainToolInputsById.get(subagent.parentToolCallId);
+ if (args) {
+ // CC's subagent-spawn tools (Task, Agent, ...) share the same
+ // input shape (`description`, `prompt`, `subagent_type`). We pull
+ // the fields defensively โ€” any unknown spawn-tool variant that
+ // happens to match this shape benefits automatically.
+ subagent.spawnMetadata = {
+ description: typeof args.description === 'string' ? args.description : undefined,
+ prompt: typeof args.prompt === 'string' ? args.prompt : undefined,
+ subagentType: typeof args.subagent_type === 'string' ? args.subagent_type : undefined,
+ };
}
+ this.announcedSpawns.add(subagent.parentToolCallId);
}
+ const chunkData: StreamChunkData = {
+ chunkType: 'tools_calling',
+ toolsCalling: cumulative,
+ };
+ if (subagent) chunkData.subagent = subagent;
+
+ const events: HeterogeneousAgentEvent[] = [this.makeChunkEvent(chunkData)];
+ for (const t of freshTools) {
+ const startData: Record<string, any> = { toolCalling: t };
+ if (subagent) startData.subagent = subagent;
+ events.push(this.makeEvent('tool_start', startData));
+ }
return events;
}
@@ -310,11 +495,21 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
* Handle user events โ€” these contain tool_result blocks.
* NOTE: In Claude Code, tool results are emitted as `type: 'user'` events
* (representing the synthetic user turn that feeds results back to the LLM).
+ *
+ * When the user event carries `parent_tool_use_id`, the tool_result is
+ * for a SUBAGENT inner tool. We stamp that as the `subagent` peer field
+ * on both the `tool_result` and `tool_end` events so the executor routes
+ * the update to the right Thread / tool message (subagent-turn-scoped,
+ * not main-agent-scoped).
*/
private handleUser(raw: any): HeterogeneousAgentEvent[] {
const content = raw.message?.content;
if (!Array.isArray(content)) return [];
+ const subagentCtx: SubagentEventContext | undefined = raw.parent_tool_use_id
+ ? { parentToolCallId: raw.parent_tool_use_id }
+ : undefined;
+
const events: HeterogeneousAgentEvent[] = [];
for (const block of content) {
@@ -363,6 +558,7 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
content: resultContent,
isError: !!block.is_error,
pluginState,
+ subagent: subagentCtx,
toolCallId,
} satisfies ToolResultData),
);
@@ -370,7 +566,13 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
// Then emit tool_end (signals handler to refresh tool result UI)
if (this.pendingToolCalls.has(toolCallId)) {
this.pendingToolCalls.delete(toolCallId);
- events.push(this.makeEvent('tool_end', { isSuccess: !block.is_error, toolCallId }));
+ events.push(
+ this.makeEvent('tool_end', {
+ isSuccess: !block.is_error,
+ subagent: subagentCtx,
+ toolCallId,
+ }),
+ );
}
}
diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.ts
index 3aee0a4ab62..745e43a197a 100644
--- a/packages/heterogeneous-agents/src/index.ts
+++ b/packages/heterogeneous-agents/src/index.ts
@@ -1,4 +1,5 @@
export { ClaudeCodeAdapter, claudeCodePreset } from './adapters';
+export { HETEROGENEOUS_TYPE_LABELS } from './labels';
export { createAdapter, getPreset, listAgentTypes } from './registry';
export type {
AgentCLIPreset,
@@ -9,6 +10,8 @@ export type {
StreamChunkData,
StreamChunkType,
StreamStartData,
+ SubagentEventContext,
+ SubagentSpawnMetadata,
ToolCallPayload,
ToolEndData,
ToolResultData,
diff --git a/packages/heterogeneous-agents/src/labels.ts b/packages/heterogeneous-agents/src/labels.ts
new file mode 100644
index 00000000000..fd6e85f1758
--- /dev/null
+++ b/packages/heterogeneous-agents/src/labels.ts
@@ -0,0 +1,11 @@
+/**
+ * Display-name mapping for heterogeneous agent types.
+ *
+ * Keys mirror the registry keys in `registry.ts` (adapter type). UI layers
+ * use this to render user-facing names (e.g. "Claude Code is running")
+ * without knowing adapter-specific branding.
+ */
+export const HETEROGENEOUS_TYPE_LABELS: Record<string, string> = {
+ 'claude-code': 'Claude Code',
+ 'codex': 'Codex',
+};
diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.ts
index 1e02f27a053..5cb18663e21 100644
--- a/packages/heterogeneous-agents/src/types.ts
+++ b/packages/heterogeneous-agents/src/types.ts
@@ -47,17 +47,85 @@ export interface StreamStartData {
provider?: string;
}
+/**
+ * Adapter-extracted spawn metadata, attached to the FIRST event the
+ * adapter emits for a new subagent run (keyed by `parentToolCallId`).
+ * Lets the executor lazy-create the subagent Thread on first sight
+ * without needing to know about adapter-specific tool names (CC `Task`,
+ * Codex subtask, ...) or parse `tool_use.input`.
+ *
+ * Absent on subsequent events for the same parent.
+ */
+export interface SubagentSpawnMetadata {
+ /** Short label / title for the spawn (CC Task's `description`). */
+ description?: string;
+ /**
+ * Initial user-message content for the subagent Thread (CC Task's
+ * `prompt`). The executor writes this as the Thread's `role:'user'`
+ * message so the subagent's conversation is reconstructable as a
+ * standalone chat.
+ */
+ prompt?: string;
+ /** Subagent template label (CC Task's `subagent_type`). */
+ subagentType?: string;
+}
+
+/**
+ * Subagent-origination context, carried as a peer field on event `data`
+ * (NOT on `ToolCallPayload`). A stream event originating from a subagent
+ * turn โ€” CC `Task` spawn, Codex subtask, ... โ€” stamps this on the chunk
+ * so the executor can route the batch of tools / the tool_result into the
+ * right Thread + subagent assistant message. Per-event scope: all tools
+ * in the same chunk share the same parent / turn ids, so the info
+ * describes the containing chunk, not individual payloads.
+ *
+ * Main-agent events leave `subagent` undefined.
+ */
+export interface SubagentEventContext {
+ /**
+ * The main-agent tool_use id that spawned this subagent (CC Task's
+ * tool_use.id). Persistent across the entire subagent run; used by the
+ * executor to look up the Thread for this spawn.
+ */
+ parentToolCallId: string;
+ /**
+ * Spawn metadata โ€” present only on the FIRST event the adapter emits
+ * for a given `parentToolCallId`, absent on subsequent events. The
+ * executor uses this to create the subagent Thread + seed its
+ * `role:'user'` message the moment it first sees subagent activity,
+ * without re-parsing the Task tool_use input or knowing CC-specific
+ * argument shapes.
+ */
+ spawnMetadata?: SubagentSpawnMetadata;
+ /**
+ * The subagent CLI's message.id for THIS turn. Set on `tools_calling`
+ * / `tool_start` chunks where the executor needs to detect turn
+ * boundaries (change triggers a new assistant message inside the
+ * Thread). Omitted on `tool_result` / `tool_end` where the turn is
+ * already established by the corresponding tool_use.
+ */
+ subagentMessageId?: string;
+}
+
/** Data shape for stream_chunk events */
export interface StreamChunkData {
chunkType: StreamChunkType;
content?: string;
reasoning?: string;
+ /**
+ * Subagent context for the entire chunk โ€” peer to `toolsCalling`,
+ * `content`, and `reasoning`. Stream-state info (parent spawn id,
+ * subagent turn id) belongs on the event, not inside the payloads.
+ */
+ subagent?: SubagentEventContext;
toolsCalling?: ToolCallPayload[];
}
/** Data shape for tool_end events */
export interface ToolEndData {
isSuccess: boolean;
+ /** Subagent context if this tool_end belongs to a subagent inner tool. */
+ subagent?: SubagentEventContext;
toolCallId: string;
}
@@ -72,10 +140,19 @@ export interface ToolResultData {
* without each consumer re-parsing tool args.
*/
pluginState?: Record<string, any>;
+ /** Subagent context if this tool_result belongs to a subagent inner tool. */
+ subagent?: SubagentEventContext;
toolCallId: string;
}
-/** Tool call payload (matches ChatToolPayload shape) */
+/**
+ * Tool call payload (matches ChatToolPayload shape).
+ *
+ * Kept minimal and stream/persistence-agnostic: no subagent lineage,
+ * no turn ids, no spawn markers. Those live on the containing event's
+ * `subagent` peer field ({@link SubagentEventContext}) because they
+ * describe the chunk's origin, not the tool call itself.
+ */
export interface ToolCallPayload {
apiName: string;
arguments: string;
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx
index 1565bed87d1..a71a1fdf79d 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx
@@ -17,12 +17,37 @@ vi.mock('@lobehub/ui', () => ({
{children}
</div>
),
- AccordionItem: ({ children, title }: { children?: ReactNode; title?: ReactNode }) => (
+ AccordionItem: ({
+ action,
+ children,
+ title,
+ }: {
+ action?: ReactNode;
+ children?: ReactNode;
+ title?: ReactNode;
+ }) => (
<div>
<div>{title}</div>
+ <div>{action}</div>
<div>{children}</div>
</div>
),
+ // Needs to resolve to a `button` with an accessible name that matches the
+ // `title` prop so the tests' `getByRole('button', { name: 'Expand fully' })`
+ // assertions can find the expand toggle.
+ ActionIcon: ({
+ icon: IconComponent,
+ onClick,
+ title,
+ }: {
+ icon?: ComponentType;
+ onClick?: (e: unknown) => void;
+ title?: string;
+ }) => (
+ <button aria-label={title} type="button" onClick={onClick}>
+ {IconComponent ? <IconComponent /> : null}
+ </button>
+ ),
Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
Icon: ({ icon: IconComponent }: { icon?: ComponentType }) =>
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx
index 645dee49f3d..aecd4471701 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx
@@ -1,5 +1,5 @@
import { type ChatToolPayloadWithResult } from '@lobechat/types';
-import { Accordion, AccordionItem, Block, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Accordion, AccordionItem, ActionIcon, Block, Flexbox, Icon, Text } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { AlertTriangle, Check, HandIcon, Maximize2, Minimize2, X } from 'lucide-react';
import { AnimatePresence, m as motion } from 'motion/react';
@@ -317,8 +317,7 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
const expandToggleIcon = expandLevel === 'semi' ? Maximize2 : Minimize2;
- const handleToggleExpand = (e: React.MouseEvent | React.KeyboardEvent) => {
- e.stopPropagation();
+ const handleToggleExpand = () => {
if (expandLevel === 'semi') {
setExpandLevel('full');
userOpenedRef.current = true;
@@ -327,15 +326,29 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
}
};
- const handleToggleKeyDown = (e: React.KeyboardEvent) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- handleToggleExpand(e);
- }
- };
+ const expandToggleNode = (
+ <AnimatePresence initial={false}>
+ {showExpandToggle && (
+ <motion.div
+ animate={{ opacity: 1, scale: 1 }}
+ exit={{ opacity: 0, scale: 0.9 }}
+ initial={{ opacity: 0, scale: 0.9 }}
+ style={{ display: 'flex' }}
+ transition={WORKFLOW_EXPAND_TOGGLE_TRANSITION}
+ >
+ <ActionIcon
+ icon={expandToggleIcon}
+ size={{ blockSize: 24, size: WORKFLOW_EXPAND_TOGGLE_ICON_SIZE }}
+ title={expandToggleLabel}
+ onClick={handleToggleExpand}
+ />
+ </motion.div>
+ )}
+ </AnimatePresence>
+ );
const title = (
- <Flexbox horizontal align="center" gap={6} width="100%">
+ <Flexbox horizontal align="center" gap={6} style={{ minWidth: 0 }}>
<Block
horizontal
align="center"
@@ -352,9 +365,12 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
<Flexbox
horizontal
align="center"
- flex={1}
gap={6}
- style={{ minHeight: WORKFLOW_STREAMING_TITLE_MIN_HEIGHT_PX, minWidth: 0 }}
+ style={{
+ minHeight: WORKFLOW_STREAMING_TITLE_MIN_HEIGHT_PX,
+ minWidth: 0,
+ overflow: 'hidden',
+ }}
>
<div style={{ minWidth: 0, overflow: 'hidden' }}>
<AnimatePresence initial={false} mode="wait">
@@ -392,13 +408,7 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
)}
</Flexbox>
) : (
- <Flexbox
- horizontal
- align="center"
- flex={1}
- gap={6}
- style={{ minWidth: 0, overflow: 'hidden' }}
- >
+ <Flexbox horizontal align="center" gap={6} style={{ minWidth: 0, overflow: 'hidden' }}>
<Text
type="secondary"
style={{
@@ -417,46 +427,6 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
)}
</Flexbox>
)}
- <AnimatePresence initial={false}>
- {showExpandToggle && (
- <motion.div
- animate={{ opacity: 1, scale: 1, x: 0 }}
- aria-label={expandToggleLabel}
- exit={{ opacity: 0, scale: 0.9, x: 4 }}
- initial={{ opacity: 0, scale: 0.9, x: 4 }}
- role="button"
- tabIndex={0}
- title={expandToggleLabel}
- transition={WORKFLOW_EXPAND_TOGGLE_TRANSITION}
- style={{
- cursor: 'pointer',
- flex: 'none',
- marginInlineStart: 8,
- outline: 'none',
- padding: 2,
- }}
- onClick={handleToggleExpand}
- onKeyDown={handleToggleKeyDown}
- >
- <AnimatePresence initial={false} mode="wait">
- <motion.span
- animate={{ opacity: 1, rotate: 0, scale: 1 }}
- exit={{ opacity: 0, rotate: 60, scale: 0.85 }}
- initial={{ opacity: 0, rotate: -60, scale: 0.85 }}
- key={expandLevel}
- style={{ display: 'flex' }}
- transition={WORKFLOW_EXPAND_TOGGLE_TRANSITION}
- >
- <Icon
- color={cssVar.colorTextSecondary}
- icon={expandToggleIcon}
- size={WORKFLOW_EXPAND_TOGGLE_ICON_SIZE}
- />
- </motion.span>
- </AnimatePresence>
- </motion.div>
- )}
- </AnimatePresence>
</Flexbox>
);
@@ -466,7 +436,14 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
variant="borderless"
onExpandedChange={handleExpandedChange}
>
- <AccordionItem itemKey="workflow" paddingBlock={4} paddingInline={4} title={title}>
+ <AccordionItem
+ alwaysShowAction
+ action={expandToggleNode}
+ itemKey="workflow"
+ paddingBlock={4}
+ paddingInline={4}
+ title={title}
+ >
<WorkflowExpandedList
assistantId={assistantMessageId}
blocks={blocks}
diff --git a/src/features/Conversation/Messages/components/ContentLoading.tsx b/src/features/Conversation/Messages/components/ContentLoading.tsx
index aafdfbf6093..e6f0d4c1f70 100644
--- a/src/features/Conversation/Messages/components/ContentLoading.tsx
+++ b/src/features/Conversation/Messages/components/ContentLoading.tsx
@@ -1,3 +1,4 @@
+import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';
import { Flexbox, Text } from '@lobehub/ui';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -49,10 +50,20 @@ const ContentLoading = memo<ContentLoadingProps>(({ id }) => {
setStartTime(Date.now());
}, [operationType, id]);
- // Get localized label based on operation type
- const operationLabel = operationType
- ? (t(`operation.${operationType}` as any) as string)
- : undefined;
+ // Heterogeneous agents interpolate their display name (e.g. "Claude Code is running")
+ // so the user can tell which external agent is working.
+ const getOperationLabel = () => {
+ if (!operationType) return undefined;
+ if (operationType !== 'execHeterogeneousAgent') {
+ return t(`operation.${operationType}` as any) as string;
+ }
+ const heterogeneousType = runningOp?.metadata?.heterogeneousType as string | undefined;
+ const name = heterogeneousType
+ ? (HETEROGENEOUS_TYPE_LABELS[heterogeneousType] ?? heterogeneousType)
+ : t('operation.heterogeneousAgentFallback');
+ return t('operation.execHeterogeneousAgent', { name });
+ };
+ const operationLabel = getOperationLabel();
const showElapsedTime = elapsedSeconds >= ELAPSED_TIME_THRESHOLD / 1000;
diff --git a/src/features/Portal/Thread/Chat/index.tsx b/src/features/Portal/Thread/Chat/index.tsx
index 9572fb49d9f..ce2189c52ac 100644
--- a/src/features/Portal/Thread/Chat/index.tsx
+++ b/src/features/Portal/Thread/Chat/index.tsx
@@ -15,7 +15,7 @@ import {
import SkeletonList from '@/features/Conversation/components/SkeletonList';
import { useOperationState } from '@/hooks/useOperationState';
import { useChatStore } from '@/store/chat';
-import { threadSelectors } from '@/store/chat/selectors';
+import { portalThreadSelectors, threadSelectors } from '@/store/chat/selectors';
import { type MessageMapKeyInput } from '@/store/chat/utils/messageMapKey';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
@@ -26,7 +26,11 @@ import { useThreadActionsBarConfig } from './useThreadActionsBarConfig';
* Inner component that uses ConversationStore for message rendering
* Must be inside ConversationProvider to access the store
*/
-const ThreadChatContent = memo(() => {
+interface ThreadChatContentProps {
+ isSubagentThread: boolean;
+}
+
+const ThreadChatContent = memo<ThreadChatContentProps>(({ isSubagentThread }) => {
// Get display messages from ConversationStore to determine thread divider position
// With the new backend API, parent messages have threadId === null
// and thread messages have threadId === context.threadId
@@ -62,14 +66,14 @@ const ThreadChatContent = memo(() => {
return (
<MessageItem
inPortalThread
- disableEditing={isParentMessage}
+ disableEditing={isSubagentThread || isParentMessage}
endRender={enableThreadDivider ? <ThreadDivider /> : undefined}
id={id}
index={index}
/>
);
},
- [threadSourceInfo.sourceMessageId, threadSourceInfo.sourceMessageIndex],
+ [threadSourceInfo.sourceMessageId, threadSourceInfo.sourceMessageIndex, isSubagentThread],
);
return (
@@ -93,7 +97,7 @@ const ThreadChatContent = memo(() => {
<ChatList itemContent={itemContent} />
</Flexbox>
</Suspense>
- <ChatInput leftActions={['typo', 'stt', 'portalToken']} />
+ {!isSubagentThread && <ChatInput leftActions={['typo', 'stt', 'portalToken']} />}
</>
);
});
@@ -118,8 +122,18 @@ const ThreadChat = memo(() => {
s.newThreadMode,
]);
+ // Subagent threads are auto-spawned by a parent tool call (CC's `Agent`
+ // tool etc.); the external CLI owns the session so the user can't inject
+ // new turns or mutate existing ones. `sourceToolCallId` is set by the
+ // executor on every spawn โ€” unambiguous marker to flip the thread into a
+ // read-only record (hides composer, wipes per-message actions, disables
+ // double-click editing).
+ const isSubagentThread = useChatStore(
+ (s) => !!portalThreadSelectors.portalCurrentThread(s)?.metadata?.sourceToolCallId,
+ );
+
// Get thread-specific actionsBar config
- const actionsBarConfig = useThreadActionsBarConfig();
+ const actionsBarConfig = useThreadActionsBarConfig({ readonly: isSubagentThread });
// Build ConversationContext for thread
// When creating new thread (!portalThreadId), use isNew + scope: 'thread'
@@ -210,7 +224,7 @@ const ThreadChat = memo(() => {
replaceMessages(msgs, { context: ctx });
}}
>
- <ThreadChatContent />
+ <ThreadChatContent isSubagentThread={isSubagentThread} />
</ConversationProvider>
);
});
diff --git a/src/features/Portal/Thread/Chat/useThreadActionsBarConfig.ts b/src/features/Portal/Thread/Chat/useThreadActionsBarConfig.ts
index cf77126ca20..ddbe72aab51 100644
--- a/src/features/Portal/Thread/Chat/useThreadActionsBarConfig.ts
+++ b/src/features/Portal/Thread/Chat/useThreadActionsBarConfig.ts
@@ -2,7 +2,21 @@
import { useMemo } from 'react';
-import { type ActionsBarConfig } from '@/features/Conversation';
+import { type ActionsBarConfig, type MessageActionsConfig } from '@/features/Conversation';
+
+interface UseThreadActionsBarConfigOptions {
+ /**
+ * When true, every role's bar+menu is wiped so the thread renders as a
+ * read-only record. Used for subagent Threads whose contents are owned
+ * by the external CLI โ€” edit / regenerate / delete would mutate state
+ * the user can't meaningfully re-drive.
+ */
+ readonly?: boolean;
+}
+
+// Empty arrays (not `undefined`) so the underlying `actionsConfig?.bar ?? DEFAULT_BAR`
+// fallback doesn't fill them back in with the default set.
+const EMPTY_MESSAGE_ACTIONS: MessageActionsConfig = { bar: [], menu: [] };
/**
* Hook to create thread-specific actionsBar configuration
@@ -10,19 +24,27 @@ import { type ActionsBarConfig } from '@/features/Conversation';
* In thread mode:
* - Parent messages (before thread divider) should be read-only (handled via disableEditing prop)
* - Thread messages can be edited/deleted normally
+ * - Subagent threads (`readonly: true`) hide the whole action bar across roles
*
* Note: Parent message disabling is now handled directly in the itemContent renderer
* via the disableEditing prop, rather than through actionsBar config.
*/
-export const useThreadActionsBarConfig = (): ActionsBarConfig => {
- // For thread mode, we return a minimal config
- // Parent message editing is handled via disableEditing prop in itemContent
+export const useThreadActionsBarConfig = ({
+ readonly = false,
+}: UseThreadActionsBarConfigOptions = {}): ActionsBarConfig => {
return useMemo(
- () => ({
- // Thread-specific actions can be added here if needed
- assistant: {},
- user: {},
- }),
- [],
+ () =>
+ readonly
+ ? {
+ assistant: EMPTY_MESSAGE_ACTIONS,
+ assistantGroup: EMPTY_MESSAGE_ACTIONS,
+ user: EMPTY_MESSAGE_ACTIONS,
+ }
+ : {
+ // Thread-specific actions can be added here if needed
+ assistant: {},
+ user: {},
+ },
+ [readonly],
);
};
diff --git a/src/features/Portal/Thread/Header/Active.tsx b/src/features/Portal/Thread/Header/Active.tsx
index 6e4275fdf7a..cc2e291afe2 100644
--- a/src/features/Portal/Thread/Header/Active.tsx
+++ b/src/features/Portal/Thread/Header/Active.tsx
@@ -1,4 +1,5 @@
-import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { resolveCCSubagentType } from '@lobechat/builtin-tool-claude-code/client';
+import { Flexbox, Icon, Tag, Text } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import isEqual from 'fast-deep-equal';
import { ListTree } from 'lucide-react';
@@ -13,25 +14,43 @@ import { oneLineEllipsis } from '@/styles';
const Active = memo(() => {
const currentThread = useChatStore(portalThreadSelectors.portalCurrentThread, isEqual);
+ if (!currentThread) return null;
+
+ // Subagent spawn โ†’ show the specific template (e.g. "Explore",
+ // "General purpose") as a chip next to the title. Sidebar only marks
+ // "Subagent" generically; the header is where the detail belongs.
+ const subagentTypeInfo = resolveCCSubagentType(currentThread.metadata?.subagentType);
+
return (
- currentThread && (
- <Flexbox horizontal align={'center'} gap={8} style={{ marginInlineStart: 4 }}>
- <Icon color={cssVar.colorTextSecondary} icon={ListTree} size={18} />
- <Text
- className={oneLineEllipsis}
- ellipsis={true}
- style={{ color: cssVar.colorTextSecondary, fontSize: 14 }}
+ <Flexbox horizontal align={'center'} gap={8} style={{ marginInlineStart: 4 }}>
+ <Icon color={cssVar.colorTextSecondary} icon={ListTree} size={18} />
+ <Text
+ className={oneLineEllipsis}
+ ellipsis={true}
+ style={{ color: cssVar.colorTextSecondary, fontSize: 14 }}
+ >
+ {currentThread.title === LOADING_FLAT ? (
+ <Flexbox flex={1} height={30} justify={'center'}>
+ <BubblesLoading />
+ </Flexbox>
+ ) : (
+ currentThread.title
+ )}
+ </Text>
+ {subagentTypeInfo && (
+ <Tag
+ icon={<Icon icon={subagentTypeInfo.icon} />}
+ size={'small'}
+ style={{
+ color: cssVar.colorTextDescription,
+ flexShrink: 0,
+ fontSize: 11,
+ }}
>
- {currentThread?.title === LOADING_FLAT ? (
- <Flexbox flex={1} height={30} justify={'center'}>
- <BubblesLoading />
- </Flexbox>
- ) : (
- currentThread?.title
- )}
- </Text>
- </Flexbox>
- )
+ {subagentTypeInfo.label}
+ </Tag>
+ )}
+ </Flexbox>
);
});
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 79e3f2303f4..9e5dfe76207 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -265,7 +265,8 @@ export default {
'operation.contextCompression': 'Context too long, compressing history...',
'operation.execAgentRuntime': 'Preparing response',
'operation.execClientTask': 'Executing task',
- 'operation.execHeterogeneousAgent': 'External agent running',
+ 'operation.execHeterogeneousAgent': '{{name}} is running',
+ 'operation.heterogeneousAgentFallback': 'External agent',
'operation.execServerAgentRuntime':
'Task is running in the server. You are safe to leave this page',
'operation.sendMessage': 'Sending message',
@@ -436,7 +437,10 @@ export default {
'task.status.fetchingDetails': 'Fetching details...',
'task.status.initializing': 'Initializing task...',
'task.subtask': 'Subtask',
+ 'thread.closeSubagentThread': 'Collapse subagent conversation',
'thread.divider': 'Subtopic',
+ 'thread.openSubagentThread': 'View full subagent conversation',
+ 'thread.subagentBadge': 'Subagent',
'thread.threadMessageCount': '{{messageCount}} messages',
'thread.title': 'Subtopic',
'todoProgress.allCompleted': 'All tasks completed',
diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.ts
index 721a0b10b4e..e4544e874a9 100644
--- a/src/locales/default/plugin.ts
+++ b/src/locales/default/plugin.ts
@@ -51,6 +51,8 @@ export default {
'builtins.lobe-agent-management.render.installPlugin.plugin': 'Plugin',
'builtins.lobe-agent-management.render.installPlugin.success': 'Installed successfully',
'builtins.lobe-agent-management.title': 'Agent Manager',
+ 'builtins.lobe-claude-code.agent.instruction': 'Instruction',
+ 'builtins.lobe-claude-code.agent.result': 'Result',
'builtins.lobe-claude-code.todoWrite.allDone': 'All tasks completed',
'builtins.lobe-claude-code.todoWrite.currentStep': 'Current step',
'builtins.lobe-claude-code.todoWrite.todos': 'Todos',
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
index 3016b6fa214..408a221abf6 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
@@ -1,7 +1,8 @@
-import { Icon } from '@lobehub/ui';
+import { Flexbox, Icon, Tag } from '@lobehub/ui';
import { TreeDownRightIcon } from '@lobehub/ui/icons';
import { cssVar } from 'antd-style';
import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
import NavItem from '@/features/NavPanel/components/NavItem';
import { useChatStore } from '@/store/chat';
@@ -14,10 +15,12 @@ import { useThreadItemDropdownMenu } from './useDropdownMenu';
export interface ThreadItemProps {
id: string;
index: number;
+ isSubagent?: boolean;
title: string;
}
-const ThreadItem = memo<ThreadItemProps>(({ title, id }) => {
+const ThreadItem = memo<ThreadItemProps>(({ title, id, isSubagent }) => {
+ const { t } = useTranslation('chat');
const [editing, activeThreadId] = useChatStore((s) => [
s.threadRenamingId === id,
s.activeThreadId,
@@ -44,6 +47,9 @@ const ThreadItem = memo<ThreadItemProps>(({ title, id }) => {
const active = id === activeThreadId;
+ // Subagent threads (spawned by an external agent's subagent tool call)
+ // only get a plain "Subagent" badge โ€” the specific template name is
+ // surfaced on the Thread header instead, where there's room for it.
return (
<>
<NavItem
@@ -52,7 +58,23 @@ const ThreadItem = memo<ThreadItemProps>(({ title, id }) => {
contextMenuItems={dropdownMenu}
disabled={editing}
icon={<Icon color={cssVar.colorTextDescription} icon={TreeDownRightIcon} size={'small'} />}
- title={title}
+ title={
+ isSubagent ? (
+ <Flexbox horizontal align={'center'} flex={1} gap={6}>
+ <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ {title}
+ </span>
+ <Tag
+ size={'small'}
+ style={{ color: cssVar.colorTextDescription, flexShrink: 0, fontSize: 10 }}
+ >
+ {t('thread.subagentBadge')}
+ </Tag>
+ </Flexbox>
+ ) : (
+ title
+ )
+ }
onClick={handleClick}
/>
<Editing id={id} title={title} toggleEditing={toggleEditing} />
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.tsx
index d3adf890756..e63f2a99e6e 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
@@ -18,7 +18,13 @@ const ThreadList = memo(() => {
return (
<Flexbox gap={1} paddingBlock={1}>
{threads?.map((item, index) => (
- <ThreadItem id={item.id} index={index} key={item.id} title={item.title} />
+ <ThreadItem
+ id={item.id}
+ index={index}
+ isSubagent={!!item.metadata?.subagentType}
+ key={item.id}
+ title={item.title}
+ />
))}
</Flexbox>
);
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
index 3016b6fa214..c4f2710125f 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
@@ -1,7 +1,8 @@
-import { Icon } from '@lobehub/ui';
+import { Flexbox, Icon, Tag } from '@lobehub/ui';
import { TreeDownRightIcon } from '@lobehub/ui/icons';
import { cssVar } from 'antd-style';
import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
import NavItem from '@/features/NavPanel/components/NavItem';
import { useChatStore } from '@/store/chat';
@@ -14,10 +15,12 @@ import { useThreadItemDropdownMenu } from './useDropdownMenu';
export interface ThreadItemProps {
id: string;
index: number;
+ isSubagent?: boolean;
title: string;
}
-const ThreadItem = memo<ThreadItemProps>(({ title, id }) => {
+const ThreadItem = memo<ThreadItemProps>(({ title, id, isSubagent }) => {
+ const { t } = useTranslation('chat');
const [editing, activeThreadId] = useChatStore((s) => [
s.threadRenamingId === id,
s.activeThreadId,
@@ -52,7 +55,23 @@ const ThreadItem = memo<ThreadItemProps>(({ title, id }) => {
contextMenuItems={dropdownMenu}
disabled={editing}
icon={<Icon color={cssVar.colorTextDescription} icon={TreeDownRightIcon} size={'small'} />}
- title={title}
+ title={
+ isSubagent ? (
+ <Flexbox horizontal align={'center'} flex={1} gap={6}>
+ <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ {title}
+ </span>
+ <Tag
+ size={'small'}
+ style={{ color: cssVar.colorTextDescription, flexShrink: 0, fontSize: 10 }}
+ >
+ {t('thread.subagentBadge')}
+ </Tag>
+ </Flexbox>
+ ) : (
+ title
+ )
+ }
onClick={handleClick}
/>
<Editing id={id} title={title} toggleEditing={toggleEditing} />
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.tsx
index d3adf890756..e63f2a99e6e 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
@@ -18,7 +18,13 @@ const ThreadList = memo(() => {
return (
<Flexbox gap={1} paddingBlock={1}>
{threads?.map((item, index) => (
- <ThreadItem id={item.id} index={index} key={item.id} title={item.title} />
+ <ThreadItem
+ id={item.id}
+ index={index}
+ isSubagent={!!item.metadata?.subagentType}
+ key={item.id}
+ title={item.title}
+ />
))}
</Flexbox>
);
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
index db41aebef68..652dcbc9dab 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
@@ -1,4 +1,5 @@
import { SESSION_CHAT_URL } from '@lobechat/const';
+import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';
import { type SidebarAgentItem } from '@lobechat/types';
import { ActionIcon, Flexbox, Icon, Tag } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
@@ -21,11 +22,6 @@ import Actions from '../Item/Actions';
import Avatar from './Avatar';
import { useAgentDropdownMenu } from './useDropdownMenu';
-const HETEROGENEOUS_TYPE_LABELS: Record<string, string> = {
- 'claude-code': 'Claude Code',
- 'codex': 'Codex',
-};
-
const styles = createStaticStyles(({ css, cssVar }) => ({
badge: css`
pointer-events: none;
diff --git a/src/services/thread/index.ts b/src/services/thread/index.ts
index 310182d5c33..9de031d3d4a 100644
--- a/src/services/thread/index.ts
+++ b/src/services/thread/index.ts
@@ -23,6 +23,10 @@ export class ThreadService {
});
};
+ createThread = async (params: CreateThreadParams): Promise<string> => {
+ return lambdaClient.thread.createThread.mutate(params);
+ };
+
updateThread = async (id: string, data: Partial<ThreadItem>) => {
return lambdaClient.thread.updateThread.mutate({ id, value: data });
};
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
index 78a03ca2268..029c859c9ba 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -30,6 +30,14 @@ vi.mock('@/services/message', () => ({
},
}));
+// threadService โ€” subagent Thread creation (CC `Task` tool_use)
+const mockCreateThread = vi.fn();
+vi.mock('@/services/thread', () => ({
+ threadService: {
+ createThread: (...args: any[]) => mockCreateThread(...args),
+ },
+}));
+
// heterogeneousAgentService โ€” IPC to Electron main
const mockStartSession = vi.fn();
const mockSendPrompt = vi.fn();
@@ -88,13 +96,15 @@ function setupIpcCapture() {
};
}
-function createMockStore() {
+function createMockStore(overrides: Record<string, any> = {}) {
return {
associateMessageWithOperation: vi.fn(),
completeOperation: vi.fn(),
internal_dispatchMessage: vi.fn(),
internal_toggleToolCallingStreaming: vi.fn(),
+ refreshThreads: vi.fn(async () => {}),
replaceMessages: vi.fn(),
+ ...overrides,
} as any;
}
@@ -142,6 +152,47 @@ const ccAssistant = (msgId: string, content: any[], extra?: { model?: string; us
const ccToolUse = (msgId: string, toolId: string, name: string, input: any = {}) =>
ccAssistant(msgId, [{ id: toolId, input, name, type: 'tool_use' }]);
+/**
+ * CC subagent assistant event โ€” carries `parent_tool_use_id` pointing back at
+ * the outer `Task` tool_use. The adapter routes these through its subagent
+ * handler which stamps `parentToolCallId` onto each tool payload.
+ */
+const ccSubagentToolUse = (
+ msgId: string,
+ parentToolUseId: string,
+ toolId: string,
+ name: string,
+ input: any = {},
+) => ({
+ message: {
+ content: [{ id: toolId, input, name, type: 'tool_use' }],
+ id: msgId,
+ role: 'assistant',
+ },
+ parent_tool_use_id: parentToolUseId,
+ type: 'assistant',
+});
+
+/** Subagent assistant event with text content (closing summary-style turn). */
+const ccSubagentText = (msgId: string, parentToolUseId: string, text: string) => ({
+ message: {
+ content: [{ text, type: 'text' }],
+ id: msgId,
+ role: 'assistant',
+ },
+ parent_tool_use_id: parentToolUseId,
+ type: 'assistant',
+});
+
+/** The main-agent tool_result for a spawn tool_use (end of a subagent run). */
+const ccSubagentSpawnResult = (spawnToolUseId: string, finalText: string) => ({
+ message: {
+ content: [{ content: finalText, tool_use_id: spawnToolUseId, type: 'tool_result' }],
+ role: 'user',
+ },
+ type: 'user',
+});
+
const ccText = (msgId: string, text: string) => ccAssistant(msgId, [{ text, type: 'text' }]);
const ccThinking = (msgId: string, thinking: string) =>
@@ -204,6 +255,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
}));
mockUpdateMessage.mockResolvedValue(undefined);
mockUpdateToolMessage.mockResolvedValue(undefined);
+ mockCreateThread.mockImplementation(async (params: any) => params.id || 'thread-generated');
});
afterEach(() => {
@@ -1214,4 +1266,333 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(finalContentWrite).toBeDefined();
});
});
+
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ // CC subagent thread-container model (LOBE-7392 / LOBE-7319)
+ //
+ // A subagent Thread is shaped as a nested conversation:
+ // user (prompt) โ†’ assistant#1 (tools[]) โ†’ tool โ†’ assistant#2 (tools[]) โ†’ tool โ†’ ...
+ //
+ // The executor creates the Thread lazily on the FIRST subagent event
+ // (the adapter announces spawn metadata on that chunk), seeds it with
+ // a `role:'user'` message from the Task prompt, then appends an
+ // `assistant` message per subagent turn boundary (new `subagentMessageId`).
+ //
+ // Main assistant.tools[] only ever carries the outer Task tool_use โ€”
+ // subagent inner tools live on the in-thread assistants' tools[].
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ describe('CC subagent thread-container', () => {
+ it('does NOT create a Thread on Task tool_use alone (lazy creation)', async () => {
+ // Task tool_use without any subagent events should NOT trigger
+ // Thread creation โ€” we only know the spawn is real once the
+ // adapter starts announcing subagent events.
+ await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'Find failing tests',
+ prompt: 'run the suite',
+ subagent_type: 'Explore',
+ }),
+ ccResult(),
+ ]);
+
+ expect(mockCreateThread).not.toHaveBeenCalled();
+ });
+
+ it('creates Thread + user + assistant messages on FIRST subagent event', async () => {
+ await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'Find failing tests',
+ prompt: 'run the suite and list failures',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentToolUse('msg_sub_1', 'toolu_task', 'toolu_child', 'Bash'),
+ ccResult(),
+ ]);
+
+ // Thread row seeded with adapter-supplied metadata.
+ expect(mockCreateThread).toHaveBeenCalledTimes(1);
+ expect(mockCreateThread).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: expect.stringMatching(/^thd_/),
+ metadata: expect.objectContaining({
+ sourceToolCallId: 'toolu_task',
+ subagentType: 'Explore',
+ startedAt: expect.any(String),
+ }),
+ sourceMessageId: 'ast-initial',
+ title: 'Find failing tests',
+ topicId: 'topic-1',
+ type: 'isolation',
+ }),
+ );
+ const threadId = mockCreateThread.mock.calls[0][0].id;
+
+ // Thread gets a `role:'user'` message seeded with the Task prompt.
+ const userMsg = mockCreateMessage.mock.calls.find(
+ ([p]: any) => p.role === 'user' && p.threadId === threadId,
+ );
+ expect(userMsg).toBeDefined();
+ expect(userMsg![0]).toMatchObject({
+ content: 'run the suite and list failures',
+ parentId: 'ast-initial',
+ threadId,
+ });
+
+ // Thread gets at least one `role:'assistant'` message scoped to
+ // the subagent's first turn.
+ const subAssistant = mockCreateMessage.mock.calls.find(
+ ([p]: any) => p.role === 'assistant' && p.threadId === threadId,
+ );
+ expect(subAssistant).toBeDefined();
+ });
+
+ it('chains subagent inner tool messages to the in-thread assistant', async () => {
+ await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'inspect',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentToolUse('msg_sub_1', 'toolu_task', 'toolu_child', 'Bash', { command: 'ls' }),
+ ccResult(),
+ ]);
+
+ const threadId = mockCreateThread.mock.calls[0][0].id;
+ const subAssistantMsg = mockCreateMessage.mock.calls.find(
+ ([p]: any) => p.role === 'assistant' && p.threadId === threadId,
+ );
+ const subAssistantId = subAssistantMsg?.[0];
+
+ const subToolCreate = mockCreateMessage.mock.calls.find(
+ ([p]: any) => p.role === 'tool' && p.tool_call_id === 'toolu_child',
+ );
+ expect(subToolCreate).toBeDefined();
+ expect(subToolCreate![0]).toMatchObject({
+ role: 'tool',
+ threadId,
+ tool_call_id: 'toolu_child',
+ plugin: expect.objectContaining({ apiName: 'Bash' }),
+ });
+ // Tool messages chain under the in-thread assistant (not the main one).
+ expect(subToolCreate![0].parentId).not.toBe('ast-initial');
+ // The in-thread assistant + tool messages share the same threadId.
+ expect(subAssistantMsg![0]).toMatchObject({ threadId });
+ });
+
+ it('opens a NEW in-thread assistant when subagentMessageId changes (turn boundary)', async () => {
+ await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', { description: 'x', subagent_type: 'Plan' }),
+ // Turn 1
+ ccSubagentToolUse('msg_sub_1', 'toolu_task', 'toolu_child_1', 'Read'),
+ // Turn 2 โ€” new message.id for subagent
+ ccSubagentToolUse('msg_sub_2', 'toolu_task', 'toolu_child_2', 'Write'),
+ ccResult(),
+ ]);
+
+ const threadId = mockCreateThread.mock.calls[0][0].id;
+ const threadAssistants = mockCreateMessage.mock.calls.filter(
+ ([p]: any) => p.role === 'assistant' && p.threadId === threadId,
+ );
+ // One assistant per subagent turn โ€” same shape as the main topic.
+ expect(threadAssistants.length).toBeGreaterThanOrEqual(2);
+ });
+
+ it('records subagent tool_uses on IN-THREAD assistant tools[], not on main', async () => {
+ await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', { description: 'x', subagent_type: 'Plan' }),
+ ccSubagentToolUse('msg_sub_1', 'toolu_task', 'toolu_child', 'Read'),
+ ccResult(),
+ ]);
+
+ // Main assistant.tools[] only ever carries the outer Task tool_use.
+ const mainAssistantToolWrites = mockUpdateMessage.mock.calls.filter(
+ ([id, val]: any) => id === 'ast-initial' && val.tools?.length > 0,
+ );
+ for (const [, val] of mainAssistantToolWrites) {
+ const ids = val.tools.map((t: any) => t.id);
+ expect(ids).toContain('toolu_task');
+ expect(ids).not.toContain('toolu_child');
+ }
+
+ // In-thread assistant should receive an updateMessage whose tools[]
+ // includes the subagent's inner tool_use.
+ const threadAssistantIds = new Set(
+ mockCreateMessage.mock.calls
+ .filter(
+ ([p]: any) =>
+ p.role === 'assistant' &&
+ typeof p.threadId === 'string' &&
+ p.threadId.startsWith('thd_'),
+ )
+ .map(([, returnValue]: any) => returnValue?.id),
+ );
+ // The mock returns a generated id โ€” we can't match exactly, but we
+ // can assert SOME update carried toolu_child on a non-main assistant.
+ const subToolUpdateLanded = mockUpdateMessage.mock.calls.some(
+ ([id, val]: any) =>
+ id !== 'ast-initial' && val.tools?.some((t: any) => t.id === 'toolu_child'),
+ );
+ expect(subToolUpdateLanded).toBe(true);
+ // (threadAssistantIds unused here but kept to document the intent.)
+ expect(threadAssistantIds.size).toBeGreaterThan(0);
+ });
+
+ it('does NOT create a Thread when topicId is missing (non-topic-scoped run)', async () => {
+ await runWithEvents(
+ [
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'x',
+ subagent_type: 'Plan',
+ }),
+ ccSubagentToolUse('msg_sub', 'toolu_task', 'toolu_child', 'Read'),
+ ccResult(),
+ ],
+ {
+ params: {
+ context: { ...defaultContext, topicId: undefined as any },
+ },
+ },
+ );
+
+ expect(mockCreateThread).not.toHaveBeenCalled();
+ });
+
+ it('persists the subagent Thread user message content from spawnMetadata.prompt', async () => {
+ // Real CC uses `Agent` for general-purpose subagents โ€” the adapter
+ // should still extract `prompt` from the input and seed the user
+ // message content with it (earlier bug: user msg content empty).
+ await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Agent', {
+ description: 'lookup pwd',
+ prompt: 'run pwd and summarize',
+ subagent_type: 'general-purpose',
+ }),
+ ccSubagentToolUse('msg_sub', 'toolu_task', 'toolu_child', 'Bash'),
+ ccResult(),
+ ]);
+
+ const threadId = mockCreateThread.mock.calls[0][0].id;
+ const threadUser = mockCreateMessage.mock.calls.find(
+ ([p]: any) => p.role === 'user' && p.threadId === threadId,
+ );
+ expect(threadUser).toBeDefined();
+ expect(threadUser![0].content).toBe('run pwd and summarize');
+ });
+
+ it('accumulates subagent text into the in-thread assistant content', async () => {
+ // Subagent emits a closing summary text turn after its tool work.
+ // The thread should reflect it as the assistant's content so the
+ // Thread view reads as a complete conversation.
+ await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'x',
+ prompt: 'go',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentToolUse('msg_sub_1', 'toolu_task', 'toolu_child', 'Bash'),
+ ccSubagentText('msg_sub_2', 'toolu_task', 'Here is the summary.'),
+ ccSubagentSpawnResult('toolu_task', 'Final answer to main.'),
+ ccResult(),
+ ]);
+
+ const threadId = mockCreateThread.mock.calls[0][0].id;
+ // At least one updateMessage on a subagent-thread assistant with
+ // content = "Here is the summary." should have landed.
+ const threadAssistantContentWrites = mockUpdateMessage.mock.calls.filter(
+ ([id, val]: any) => id !== 'ast-initial' && val.content === 'Here is the summary.',
+ );
+ expect(threadAssistantContentWrites.length).toBeGreaterThan(0);
+ expect(threadAssistantContentWrites[0][2]).toMatchObject({ topicId: 'topic-1' });
+ // Sanity โ€” the in-thread assistants exist under the right thread.
+ const threadAssistants = mockCreateMessage.mock.calls.filter(
+ ([p]: any) => p.role === 'assistant' && p.threadId === threadId,
+ );
+ expect(threadAssistants.length).toBeGreaterThanOrEqual(1);
+ });
+
+ it('does NOT leak subagent text into main assistant accumulatedContent', async () => {
+ await runWithEvents([
+ ccInit(),
+ ccText('msg_main_pre', 'I will delegate.'),
+ ccToolUse('msg_main_pre', 'toolu_task', 'Task', {
+ description: 'x',
+ prompt: 'go',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentText('msg_sub', 'toolu_task', 'Subagent saying things'),
+ ccSubagentSpawnResult('toolu_task', 'done'),
+ ccResult(),
+ ]);
+
+ // Main assistant content writes should contain "I will delegate."
+ // but NEVER "Subagent saying things".
+ const mainContentWrites = mockUpdateMessage.mock.calls.filter(
+ ([id, val]: any) => id === 'ast-initial' && typeof val.content === 'string',
+ );
+ for (const [, val] of mainContentWrites) {
+ expect(val.content).not.toContain('Subagent saying things');
+ }
+ });
+
+ it('finalizes subagent content when the spawn tool_result lands on main', async () => {
+ // Subagent emits text but no subsequent event โ€” normally content
+ // only hits DB on the next persist or at onComplete. The spawn
+ // tool_result arriving on main should trigger an explicit flush
+ // so the final text lands in DB before fetchAndReplace.
+ await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'x',
+ prompt: 'go',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentText('msg_sub', 'toolu_task', 'final summary text'),
+ ccSubagentSpawnResult('toolu_task', 'returned to main'),
+ ccResult(),
+ ]);
+
+ const finalizeWrite = mockUpdateMessage.mock.calls.find(
+ ([id, val]: any) => id !== 'ast-initial' && val.content === 'final summary text',
+ );
+ expect(finalizeWrite).toBeDefined();
+ });
+
+ it('invokes store.refreshThreads on lazy Thread creation (sidebar auto-refresh)', async () => {
+ // Without this hook the new subagent Thread is only visible in the
+ // sidebar after the user navigates topics / refreshes โ€” an earlier
+ // Electron E2E repro had the Thread land in DB but stay invisible
+ // in the list until manual `refreshThreads()` call.
+ const { store } = await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'x',
+ prompt: 'go',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentToolUse('msg_sub', 'toolu_task', 'toolu_child', 'Bash'),
+ ccResult(),
+ ]);
+
+ expect(store.refreshThreads).toHaveBeenCalledTimes(1);
+ });
+
+ it('does NOT call refreshThreads when no subagent events land', async () => {
+ const { store } = await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_1', 'Read', { file_path: '/a.ts' }),
+ ccToolResult('toolu_1', 'content'),
+ ccResult(),
+ ]);
+
+ expect(store.refreshThreads).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index dff0796c831..561a9fcc55d 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -453,6 +453,7 @@ export class ConversationLifecycleActionImpl {
const { operationId: heteroOpId } = this.#get().startOperation({
context: heteroContext,
label: 'Heterogeneous Agent Execution',
+ metadata: { heterogeneousType: heterogeneousProvider.type },
parentOperationId: operationId,
type: 'execHeterogeneousAgent',
});
diff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
index e0a5368f9cb..80d60f5f5bf 100644
--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
@@ -1,21 +1,31 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { isDesktop } from '@lobechat/const';
-import type { HeterogeneousAgentEvent, ToolCallPayload } from '@lobechat/heterogeneous-agents';
+import type {
+ HeterogeneousAgentEvent,
+ SubagentEventContext,
+ ToolCallPayload,
+} from '@lobechat/heterogeneous-agents';
import { createAdapter } from '@lobechat/heterogeneous-agents';
import type {
ChatToolPayload,
ConversationContext,
HeterogeneousProviderConfig,
} from '@lobechat/types';
+import { ThreadStatus, ThreadType } from '@lobechat/types';
+import { createNanoId } from '@lobechat/utils';
import { t } from 'i18next';
import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
import { messageService } from '@/services/message';
+import { threadService } from '@/services/thread';
import type { ChatStore } from '@/store/chat/store';
import { markdownToTxt } from '@/utils/markdownToTxt';
import { createGatewayEventHandler } from './gatewayEventHandler';
+/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */
+const generateThreadId = () => `thd_${createNanoId(16)()}`;
+
/**
* Fire desktop notification + dock badge when a CC/Codex/ACP run finishes.
* Notification only shows when the window is hidden (enforced in main); the
@@ -112,40 +122,60 @@ const subscribeBroadcasts = (
};
/**
- * Persisted tool-call registry for a single ACP execution.
- *
- * Tracks which tool_use ids have been persisted to avoid duplicates,
- * and holds the enriched payload (with result_msg_id) that gets written
- * back to the assistant message's tools JSONB.
+ * Per-assistant-message persistence state โ€” covers ONE assistant row's
+ * `tools[]` JSONB and the de-dupe set for its tool_uses. Main-agent
+ * and subagent-thread assistants each have their own instance; the
+ * `tool_use.id โ†’ tool message DB id` lookup is SHARED globally across
+ * all scopes (see `toolMsgIdByCallId` in `executeHeterogeneousAgent`)
+ * because `tool_result` events identify the target by id alone.
*/
interface ToolPersistenceState {
- /** Ordered list of ChatToolPayload[] written to assistant.tools */
+ /** Ordered list of ChatToolPayload[] written to this assistant's tools JSONB */
payloads: ChatToolPayload[];
/** Set of tool_use.id that have been persisted (de-dupe guard) */
persistedIds: Set<string>;
- /** Map tool_use.id โ†’ tool message DB id (for later content update on tool_result) */
- toolMsgIdByCallId: Map<string, string>;
}
/**
- * Persist any newly-seen tool calls and update the assistant message's tools JSONB.
+ * Runs the 3-phase tool persistence flow for ONE assistant message โ€”
+ * either the main-agent assistant or a subagent-thread-scoped assistant.
+ * Same ordering guarantee in both scopes:
+ *
+ * 1. Pre-register tools[] on the assistant (no result_msg_id yet), so
+ * LobeHub's conversation-flow parser finds matching ids the moment
+ * tool messages land in DB โ€” no orphan window.
+ * 2. Create `role:'tool'` messages, one per fresh tool_use. `threadId`
+ * is only set for subagent scope (so the tool messages stay inside
+ * the subagent Thread and don't leak into the main topic).
+ * 3. Re-write assistant.tools[] with the backfilled `result_msg_id`
+ * so the UI can hydrate tool results.
+ *
+ * Carries the latest accumulated text/reasoning into Phases 1+3 so DB
+ * stays in sync with streamed content. Without this, the gateway
+ * handler's `tool_end โ†’ fetchAndReplaceMessages` would read a
+ * tools-only row and clobber in-memory streamed text in the UI.
*
- * Guarantees:
- * - One tool message per unique tool_use.id (idempotent against re-processing)
- * - assistant.tools[].result_msg_id is set to the created tool message id, so
- * the UI's parse() step can link tool messages back to the assistant turn
- * (otherwise they render as orphan warnings).
- * - Carries the latest accumulated text/reasoning into the same UPDATE, so DB
- * stays in sync with what's been streamed. Without this, gateway handler's
- * `tool_end โ†’ fetchAndReplaceMessages` would read a tools-only/no-content
- * row and clobber the in-memory streamed text in the UI.
+ * Idempotent against re-processing: tool_use ids already in
+ * `state.persistedIds` are skipped.
*/
-const persistNewToolCalls = async (
+const persistToolBatch = async (
incoming: ToolCallPayload[],
state: ToolPersistenceState,
assistantMessageId: string,
context: ConversationContext,
snapshot: { content: string; reasoning: string },
+ /**
+ * Global `tool_use.id โ†’ tool message DB id` map, populated by every
+ * call (main + every subagent run) so a later `tool_result` lookup
+ * finds its row without needing to know which scope created it.
+ */
+ toolMsgIdByCallId: Map<string, string>,
+ /**
+ * When set, tool messages are scoped to this thread (subagent mode) and
+ * Phase 1 / 3 target the subagent-thread assistant. Undefined = main
+ * agent scope (tools live under the main topic, threadId stays null).
+ */
+ threadId?: string,
) => {
const freshTools = incoming.filter((t) => !state.persistedIds.has(t.id));
if (freshTools.length === 0) return;
@@ -161,16 +191,7 @@ const persistNewToolCalls = async (
return update;
};
- // โ”€โ”€โ”€ PHASE 1: Write tools[] to assistant FIRST, WITHOUT result_msg_id โ”€โ”€โ”€
- //
- // LobeHub's conversation-flow parser filters tool messages by matching
- // `tool.tool_call_id` against `assistant.tools[].id`. If a tool message
- // exists in DB but no matching entry exists in assistant.tools[], the UI
- // renders an "orphan" warning telling the user to delete it.
- //
- // By writing assistant.tools[] FIRST (with the tool ids but no result_msg_id
- // yet), the match works from the moment tool messages get created in DB.
- // No orphan window.
+ // โ”€โ”€โ”€ PHASE 1: pre-register tools[] on the assistant row โ”€โ”€โ”€
for (const tool of freshTools) state.payloads.push({ ...tool } as ChatToolPayload);
try {
await messageService.updateMessage(assistantMessageId, buildUpdate(), {
@@ -181,9 +202,7 @@ const persistNewToolCalls = async (
console.error('[HeterogeneousAgent] Failed to pre-register assistant tools:', err);
}
- // โ”€โ”€โ”€ PHASE 2: Create the tool messages in DB โ”€โ”€โ”€
- // Each tool message's tool_call_id matches an already-registered tool id
- // in assistant.tools[], so UI never sees orphan state.
+ // โ”€โ”€โ”€ PHASE 2: create the tool messages โ”€โ”€โ”€
for (const tool of freshTools) {
try {
const result = await messageService.createMessage({
@@ -197,11 +216,11 @@ const persistNewToolCalls = async (
type: tool.type as ChatToolPayload['type'],
},
role: 'tool',
+ threadId,
tool_call_id: tool.id,
topicId: context.topicId ?? undefined,
});
- state.toolMsgIdByCallId.set(tool.id, result.id);
- // Back-fill result_msg_id onto the payload we pushed in PHASE 1
+ toolMsgIdByCallId.set(tool.id, result.id);
const entry = state.payloads.find((p) => p.id === tool.id);
if (entry) entry.result_msg_id = result.id;
} catch (err) {
@@ -209,8 +228,7 @@ const persistNewToolCalls = async (
}
}
- // โ”€โ”€โ”€ PHASE 3: Re-write assistant.tools[] with the result_msg_ids โ”€โ”€โ”€
- // Without this, the UI can't hydrate tool results back into the inspector.
+ // โ”€โ”€โ”€ PHASE 3: backfill result_msg_id on assistant.tools[] โ”€โ”€โ”€
try {
await messageService.updateMessage(assistantMessageId, buildUpdate(), {
agentId: context.agentId,
@@ -221,6 +239,342 @@ const persistNewToolCalls = async (
}
};
+/**
+ * Per-subagent-spawn state tracking the current Thread + current
+ * subagent assistant message for a given parent Task tool_use. One entry
+ * per `parentToolCallId`, created lazily on the first subagent event.
+ *
+ * `subagentMessageId` mirrors main-agent turn tracking: when the
+ * adapter-reported subagent message.id changes, the executor cuts a new
+ * subagent assistant message inside the Thread (same-shaped recursion
+ * as the main agent's step boundary โ€” `user โ†’ assistant โ†’ tool โ†’ assistant`).
+ */
+interface SubagentRunState {
+ /**
+ * Accumulated text content for the CURRENT in-thread assistant turn.
+ * Mirrors the main agent's `accumulatedContent`: subagent text chunks
+ * append while the turn streams, the value travels alongside tools[]
+ * in each persist batch update so DB sees content + tools in one go,
+ * and is flushed on turn change / subagent finalization.
+ */
+ accumulatedContent: string;
+ /** Accumulated reasoning (thinking) content for the current turn. */
+ accumulatedReasoning: string;
+ /** The in-thread assistant message currently being appended to. */
+ currentAssistantMsgId: string;
+ /** Adapter's `subagentMessageId` for the current turn (change = new assistant). */
+ currentSubagentMessageId: string;
+ /**
+ * Tools created in the most recent persist batch, keyed by tool_use.id
+ * โ†’ tool message DB id. Used to chain the NEXT turn's assistant off the
+ * last tool message (mirrors main agent's step-boundary parentId logic).
+ * Populated after each persist from the caller-provided global map.
+ */
+ lastBatchToolMsgIds: string[];
+ /**
+ * Most recent parentId in the thread's chain. Flows like the main
+ * topic: `user โ†’ assistant#1 โ†’ tool โ†’ assistant#2 โ†’ tool โ†’ ...`.
+ * Updated as new tool messages / assistant messages are created so
+ * the next write lands on the end of the chain.
+ */
+ lastChainParentId: string;
+ /**
+ * Per-subagent-assistant persistence state (tools[] payloads +
+ * dedupe). Reset on every turn boundary so each in-thread assistant
+ * has its own tools[].
+ */
+ state: ToolPersistenceState;
+ /** The subagent Thread this spawn's messages belong to. */
+ threadId: string;
+}
+
+/**
+ * Handle a subagent `tools_calling` chunk: ensure Thread + current
+ * subagent assistant exist, then run the shared 3-phase persist
+ * targeting the in-thread assistant.
+ *
+ * Lazy Thread creation: the FIRST subagent chunk for a given parent
+ * carries `spawnMetadata` (title / prompt / subagentType) on the
+ * event's `subagent` peer. That's when we create the Thread row + the
+ * `role:'user'` seed message. Subsequent chunks omit `spawnMetadata`
+ * and just append to the existing Thread.
+ *
+ * Turn tracking: when `subagent.subagentMessageId` differs from the
+ * stored `currentSubagentMessageId`, we cut a new in-thread assistant
+ * and reset per-turn state. Chain parenting mirrors main-agent step
+ * handling: `user โ†’ asst#1 โ†’ tool โ†’ asst#2 โ†’ tool โ†’ ...`.
+ */
+/**
+ * Ensure a `SubagentRunState` exists for the given spawn + its current
+ * turn matches `subagentMessageId`. Handles two lazy actions:
+ *
+ * 1. **First event for a new parent** โ†’ create the Thread row, seed
+ * its `role:'user'` prompt message, open the first in-thread
+ * `role:'assistant'`.
+ * 2. **Turn boundary** (new `subagentMessageId`) โ†’ flush the prior
+ * turn's accumulated content to DB, then open the next in-thread
+ * assistant chained off the last tool message (same shape as
+ * main-agent step boundaries).
+ *
+ * Returns the run or `undefined` if any of the creates failed (the
+ * caller drops the event gracefully).
+ *
+ * Shared by `persistSubagentToolChunk` and `persistSubagentTextChunk`
+ * so text-only turns (e.g. the subagent's closing summary) and
+ * tool-only turns both flow through the same Thread-lifecycle code.
+ */
+const ensureSubagentRun = async (
+ subagentCtx: SubagentEventContext,
+ mainAssistantMessageId: string,
+ context: ConversationContext,
+ subagentRuns: Map<string, SubagentRunState>,
+ /**
+ * Invoked once per Thread creation (the lazy-create path) so the
+ * caller can invalidate SWR caches / push the new thread into any
+ * in-memory list the UI is rendering. Fire-and-forget; the executor
+ * shouldn't block persistence on UI-side cache refresh.
+ */
+ onThreadCreated?: (threadId: string) => void,
+): Promise<SubagentRunState | undefined> => {
+ if (!context.topicId) {
+ // Without a topicId we can't create a Thread โ€” drop silently (same
+ // fallback as the main path; a non-topic-scoped test harness).
+ return undefined;
+ }
+
+ let run = subagentRuns.get(subagentCtx.parentToolCallId);
+
+ // โ”€โ”€โ”€ First subagent event for this parent โ†’ lazy-create Thread โ”€โ”€โ”€
+ if (!run) {
+ const { spawnMetadata } = subagentCtx;
+ const threadId = generateThreadId();
+ const title =
+ spawnMetadata?.description?.slice(0, 80) || spawnMetadata?.subagentType || 'Subagent';
+
+ try {
+ await threadService.createThread({
+ id: threadId,
+ metadata: {
+ sourceToolCallId: subagentCtx.parentToolCallId,
+ startedAt: new Date().toISOString(),
+ subagentType: spawnMetadata?.subagentType,
+ },
+ sourceMessageId: mainAssistantMessageId,
+ status: ThreadStatus.Processing,
+ title,
+ topicId: context.topicId,
+ type: ThreadType.Isolation,
+ });
+ onThreadCreated?.(threadId);
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to create subagent thread:', err);
+ return undefined;
+ }
+
+ let userMsgId: string | undefined;
+ try {
+ const userMsg = await messageService.createMessage({
+ agentId: context.agentId,
+ content: spawnMetadata?.prompt ?? '',
+ parentId: mainAssistantMessageId,
+ role: 'user',
+ threadId,
+ topicId: context.topicId,
+ });
+ userMsgId = userMsg.id;
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to create subagent user message:', err);
+ return undefined;
+ }
+
+ let firstAssistantId: string;
+ try {
+ const firstAssistant = await messageService.createMessage({
+ agentId: context.agentId,
+ content: '',
+ parentId: userMsgId,
+ role: 'assistant',
+ threadId,
+ topicId: context.topicId,
+ });
+ firstAssistantId = firstAssistant.id;
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to create subagent assistant message:', err);
+ return undefined;
+ }
+
+ run = {
+ accumulatedContent: '',
+ accumulatedReasoning: '',
+ currentAssistantMsgId: firstAssistantId,
+ currentSubagentMessageId: subagentCtx.subagentMessageId ?? '',
+ lastBatchToolMsgIds: [],
+ lastChainParentId: firstAssistantId,
+ state: { payloads: [], persistedIds: new Set() },
+ threadId,
+ };
+ subagentRuns.set(subagentCtx.parentToolCallId, run);
+ return run;
+ }
+
+ // โ”€โ”€โ”€ New subagent turn โ†’ flush old content, cut a new assistant โ”€โ”€โ”€
+ if (
+ subagentCtx.subagentMessageId &&
+ subagentCtx.subagentMessageId !== run.currentSubagentMessageId
+ ) {
+ // Flush accumulated content for the PRIOR turn before it loses its
+ // assistant reference. We rely on persistToolBatch to also keep
+ // content+tools in sync during the turn, but a turn with NO tool
+ // calls (e.g. the subagent's final text-only summary) would never
+ // hit that path otherwise.
+ if (run.accumulatedContent || run.accumulatedReasoning) {
+ try {
+ const update: Record<string, any> = {};
+ if (run.accumulatedContent) update.content = run.accumulatedContent;
+ if (run.accumulatedReasoning) update.reasoning = { content: run.accumulatedReasoning };
+ await messageService.updateMessage(run.currentAssistantMsgId, update, {
+ agentId: context.agentId,
+ topicId: context.topicId,
+ });
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to flush subagent turn content:', err);
+ }
+ }
+ try {
+ const nextAssistant = await messageService.createMessage({
+ agentId: context.agentId,
+ content: '',
+ parentId: run.lastChainParentId,
+ role: 'assistant',
+ threadId: run.threadId,
+ topicId: context.topicId,
+ });
+ run.currentAssistantMsgId = nextAssistant.id;
+ run.currentSubagentMessageId = subagentCtx.subagentMessageId;
+ run.lastChainParentId = nextAssistant.id;
+ run.state = { payloads: [], persistedIds: new Set() };
+ run.lastBatchToolMsgIds = [];
+ run.accumulatedContent = '';
+ run.accumulatedReasoning = '';
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to create subagent turn assistant:', err);
+ return undefined;
+ }
+ }
+
+ return run;
+};
+
+/**
+ * Handle a subagent `tools_calling` chunk: ensure Thread + current
+ * subagent assistant exist, then run the shared 3-phase persist
+ * targeting the in-thread assistant. Accumulated text/reasoning rides
+ * along in the update so DB sees content + tools in one write.
+ */
+const persistSubagentToolChunk = async (
+ tools: ToolCallPayload[],
+ subagentCtx: SubagentEventContext,
+ mainAssistantMessageId: string,
+ context: ConversationContext,
+ subagentRuns: Map<string, SubagentRunState>,
+ toolMsgIdByCallId: Map<string, string>,
+ onThreadCreated?: (threadId: string) => void,
+) => {
+ const run = await ensureSubagentRun(
+ subagentCtx,
+ mainAssistantMessageId,
+ context,
+ subagentRuns,
+ onThreadCreated,
+ );
+ if (!run) return;
+
+ // Snapshot the tool id set BEFORE the batch so we can compute which
+ // ids this call added (for chain-parent advancement below).
+ const preBatchIds = new Set(toolMsgIdByCallId.keys());
+
+ await persistToolBatch(
+ tools,
+ run.state,
+ run.currentAssistantMsgId,
+ context,
+ { content: run.accumulatedContent, reasoning: run.accumulatedReasoning },
+ toolMsgIdByCallId,
+ run.threadId,
+ );
+
+ // Update chain parent to the last tool message THIS batch created so
+ // the NEXT turn's assistant chains off a tool (same shape as main).
+ const newIds = [...toolMsgIdByCallId.entries()]
+ .filter(([id]) => !preBatchIds.has(id))
+ .map(([, msgId]) => msgId);
+ run.lastBatchToolMsgIds.push(...newIds);
+ const lastToolMsgId = newIds.at(-1);
+ if (lastToolMsgId) run.lastChainParentId = lastToolMsgId;
+};
+
+/**
+ * Handle a subagent text/reasoning chunk: accumulate the content onto
+ * the run state. The actual DB write happens either on the next
+ * `persistToolBatch` (content rides along with tools[]) or at turn /
+ * finalization flush (`ensureSubagentRun` / `finalizeSubagentRun`).
+ *
+ * Keeping the write batched โ€” instead of writing on every chunk โ€”
+ * matches the main agent's content handling and avoids one DB round
+ * trip per streamed token.
+ */
+const persistSubagentTextChunk = async (
+ kind: 'text' | 'reasoning',
+ chunk: string,
+ subagentCtx: SubagentEventContext,
+ mainAssistantMessageId: string,
+ context: ConversationContext,
+ subagentRuns: Map<string, SubagentRunState>,
+ onThreadCreated?: (threadId: string) => void,
+) => {
+ const run = await ensureSubagentRun(
+ subagentCtx,
+ mainAssistantMessageId,
+ context,
+ subagentRuns,
+ onThreadCreated,
+ );
+ if (!run) return;
+ if (kind === 'text') run.accumulatedContent += chunk;
+ else run.accumulatedReasoning += chunk;
+};
+
+/**
+ * Flush any pending content/reasoning on the in-thread assistant for a
+ * completed subagent run. Called when the main-agent receives the
+ * `tool_result` for the subagent's spawn tool_use (the run's
+ * `parentToolCallId`) โ€” at that point the subagent is done and its
+ * last turn's summary text needs to land in DB before the UI refreshes.
+ *
+ * Pure DB write; does not mutate `subagentRuns` (we don't delete the
+ * entry so late/out-of-order chunks still have a target if they arrive).
+ */
+const finalizeSubagentRun = async (
+ parentToolCallId: string,
+ context: ConversationContext,
+ subagentRuns: Map<string, SubagentRunState>,
+) => {
+ const run = subagentRuns.get(parentToolCallId);
+ if (!run) return;
+ if (!run.accumulatedContent && !run.accumulatedReasoning) return;
+ const update: Record<string, any> = {};
+ if (run.accumulatedContent) update.content = run.accumulatedContent;
+ if (run.accumulatedReasoning) update.reasoning = { content: run.accumulatedReasoning };
+ try {
+ await messageService.updateMessage(run.currentAssistantMsgId, update, {
+ agentId: context.agentId,
+ topicId: context.topicId,
+ });
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to finalize subagent run:', err);
+ }
+};
+
/**
* Update a tool message's content in DB when tool_result arrives.
*
@@ -233,11 +587,11 @@ const persistToolResult = async (
toolCallId: string,
content: string,
isError: boolean,
- state: ToolPersistenceState,
+ toolMsgIdByCallId: Map<string, string>,
context: ConversationContext,
pluginState?: Record<string, any>,
) => {
- const toolMsgId = state.toolMsgIdByCallId.get(toolCallId);
+ const toolMsgId = toolMsgIdByCallId.get(toolCallId);
if (!toolMsgId) {
console.warn('[HeterogeneousAgent] tool_result for unknown toolCallId:', toolCallId);
return;
@@ -301,12 +655,31 @@ export const executeHeterogeneousAgent = async (
let unsubscribe: (() => void) | undefined;
let completed = false;
- // Track state for DB persistence
+ // Track state for DB persistence (main-agent scope)
const toolState: ToolPersistenceState = {
payloads: [],
persistedIds: new Set(),
- toolMsgIdByCallId: new Map(),
};
+ /**
+ * Global `tool_use.id โ†’ tool message DB id` lookup, shared across the
+ * main agent and every subagent run. `tool_result` events identify
+ * the target row by `toolCallId` alone (no scope context needed), so
+ * one flat map keeps the lookup trivial. Populated by every
+ * `persistToolBatch` call.
+ */
+ const toolMsgIdByCallId: Map<string, string> = new Map();
+ /**
+ * Per-subagent-spawn runtime state, keyed by the main-agent Task
+ * tool_use id (`SubagentEventContext.parentToolCallId`). One entry per
+ * spawn, carrying the Thread id + current in-thread assistant + that
+ * assistant's per-turn `ToolPersistenceState`. Lazy-created on the
+ * first subagent event from `persistSubagentToolChunk`.
+ *
+ * Lives at executor scope (not on main `toolState`) because
+ * `toolState` resets on every main-agent step boundary, whereas a
+ * subagent spawn can emit events before and after a step cut.
+ */
+ const subagentRuns: Map<string, SubagentRunState> = new Map();
/** Serializes async persist operations so ordering is stable. */
let persistQueue: Promise<void> = Promise.resolve();
/** Tracks the current assistant message being written to (switches on new steps) */
@@ -339,6 +712,23 @@ export const executeHeterogeneousAgent = async (
const abortSignal = get().operations?.[operationId]?.abortController?.signal;
const isAborted = () => !!abortSignal?.aborted;
+ /**
+ * Invoked by `ensureSubagentRun` once per lazy Thread creation so the
+ * UI's thread-list SWR cache refreshes mid-stream. Without this, a new
+ * subagent Thread born during an in-flight CC run stays invisible in
+ * the sidebar until the user navigates topics / refreshes โ€” they see
+ * the main-agent Agent tool_use but no Thread entry linking to the
+ * subagent conversation.
+ *
+ * Fire-and-forget: `refreshThreads` is a no-op when the user has
+ * navigated away from the topic, so there's no need to block persist
+ * on this call.
+ */
+ const onSubagentThreadCreated = () => {
+ const refresh = get().refreshThreads;
+ if (typeof refresh === 'function') refresh().catch(console.error);
+ };
+
try {
// Start session (pass resumeSessionId for multi-turn --resume)
const result = await heterogeneousAgentService.startSession({
@@ -388,11 +778,31 @@ export const executeHeterogeneousAgent = async (
content: string;
isError?: boolean;
pluginState?: Record<string, any>;
+ subagent?: SubagentEventContext;
toolCallId: string;
};
+ // Subagent vs main lookup is transparent โ€” one global
+ // `toolMsgIdByCallId` map spans both scopes.
persistQueue = persistQueue.then(() =>
- persistToolResult(toolCallId, content, !!isError, toolState, context, pluginState),
+ persistToolResult(
+ toolCallId,
+ content,
+ !!isError,
+ toolMsgIdByCallId,
+ context,
+ pluginState,
+ ),
);
+ // If this tool_result IS for a subagent's spawning tool_use
+ // (tool_result lands on the MAIN side but its toolCallId
+ // matches a subagent run's parent), the subagent run just
+ // ended โ€” flush any pending in-thread assistant content so
+ // the final summary lands in DB before fetchAndReplace.
+ if (subagentRuns.has(toolCallId)) {
+ persistQueue = persistQueue.then(() =>
+ finalizeSubagentRun(toolCallId, context, subagentRuns),
+ );
+ }
// Don't forward โ€” the tool_end that follows triggers fetchAndReplaceMessages
// which reads the updated content from DB.
continue;
@@ -470,8 +880,14 @@ export const executeHeterogeneousAgent = async (
// parentId should point to the last tool message from the previous step
// (if any), forming the chain: assistant โ†’ tool โ†’ assistant โ†’ tool โ†’ ...
// If no tool was used, fall back to the previous assistant message.
- // Read toolMsgIdByCallId HERE (async) because it's populated by prior persists.
- const lastToolMsgId = [...toolState.toolMsgIdByCallId.values()].pop();
+ //
+ // Read from `toolState.payloads` (not the global
+ // `toolMsgIdByCallId`) so we only pick up MAIN-agent tools โ€”
+ // the global map also holds subagent tool msg ids which
+ // would break the main-agent step chain.
+ const lastToolMsgId = [...toolState.payloads]
+ .reverse()
+ .find((p) => !!p.result_msg_id)?.result_msg_id;
const stepParentId = lastToolMsgId || currentAssistantMessageId;
const newMsg = await messageService.createMessage({
@@ -492,7 +908,9 @@ export const executeHeterogeneousAgent = async (
// AFTER this handler, so they'll write to the clean state.
toolState.payloads = [];
toolState.persistedIds.clear();
- toolState.toolMsgIdByCallId.clear();
+ // toolMsgIdByCallId is NOT cleared โ€” it's the global
+ // idโ†’row lookup and subagent tool_results from a previous
+ // step may still land after the step boundary.
});
// Update the stream_start event to carry the new message ID
@@ -517,33 +935,88 @@ export const executeHeterogeneousAgent = async (
// โ”€โ”€โ”€ stream_chunk: accumulate content + persist tool_use โ”€โ”€โ”€
if (event.type === 'stream_chunk') {
const chunk = event.data;
+ const chunkSubagentCtx = chunk?.subagent as SubagentEventContext | undefined;
if (chunk?.chunkType === 'text' && chunk.content) {
- accumulatedContent += chunk.content;
+ if (chunkSubagentCtx) {
+ // Subagent text โ†’ accumulates on the run's in-thread
+ // assistant, NOT on the main assistant's content.
+ const mainAsstId = currentAssistantMessageId;
+ persistQueue = persistQueue.then(() =>
+ persistSubagentTextChunk(
+ 'text',
+ chunk.content,
+ chunkSubagentCtx,
+ mainAsstId,
+ context,
+ subagentRuns,
+ onSubagentThreadCreated,
+ ),
+ );
+ } else {
+ accumulatedContent += chunk.content;
+ }
}
if (chunk?.chunkType === 'reasoning' && chunk.reasoning) {
- accumulatedReasoning += chunk.reasoning;
- }
- if (chunk?.chunkType === 'tools_calling') {
- const tools = chunk.toolsCalling as ToolCallPayload[];
- if (tools?.length) {
- // Snapshot accumulators sync โ€” must travel with the same step's
- // assistantMessageId. A late-bound getter would read NEW step's
- // content if a step transition lands between scheduling and
- // execution, while assistantMessageId would still be the OLD
- // one (also captured sync) โ†’ cross-step contamination.
- const snapshot = {
- content: accumulatedContent,
- reasoning: accumulatedReasoning,
- };
+ if (chunkSubagentCtx) {
+ const mainAsstId = currentAssistantMessageId;
persistQueue = persistQueue.then(() =>
- persistNewToolCalls(
- tools,
- toolState,
- currentAssistantMessageId,
+ persistSubagentTextChunk(
+ 'reasoning',
+ chunk.reasoning,
+ chunkSubagentCtx,
+ mainAsstId,
context,
- snapshot,
+ subagentRuns,
+ onSubagentThreadCreated,
),
);
+ } else {
+ accumulatedReasoning += chunk.reasoning;
+ }
+ }
+ if (chunk?.chunkType === 'tools_calling') {
+ const tools = chunk.toolsCalling as ToolCallPayload[];
+ const subagentCtx = chunk.subagent as SubagentEventContext | undefined;
+ if (tools?.length) {
+ if (subagentCtx) {
+ // Subagent chunk โ†’ lazy-create Thread + in-thread
+ // assistant, then persist into that scope. Kept off the
+ // main path so main-agent snapshot logic stays untouched.
+ const mainAsstId = currentAssistantMessageId;
+ persistQueue = persistQueue.then(() =>
+ persistSubagentToolChunk(
+ tools,
+ subagentCtx,
+ mainAsstId,
+ context,
+ subagentRuns,
+ toolMsgIdByCallId,
+ onSubagentThreadCreated,
+ ),
+ );
+ } else {
+ // Main-agent chunk โ€” existing path.
+ // Snapshot accumulators sync โ€” must travel with the
+ // same step's assistantMessageId. A late-bound getter
+ // would read NEW step's content if a step transition
+ // lands between scheduling and execution, while
+ // assistantMessageId would still be the OLD one (also
+ // captured sync) โ†’ cross-step contamination.
+ const snapshot = {
+ content: accumulatedContent,
+ reasoning: accumulatedReasoning,
+ };
+ persistQueue = persistQueue.then(() =>
+ persistToolBatch(
+ tools,
+ toolState,
+ currentAssistantMessageId,
+ context,
+ snapshot,
+ toolMsgIdByCallId,
+ ),
+ );
+ }
}
}
}
@@ -580,6 +1053,14 @@ export const executeHeterogeneousAgent = async (
// Wait for all tool persistence to finish before writing final state
await persistQueue.catch(console.error);
+ // Flush any subagent runs that didn't see their parent's
+ // tool_result (e.g. CLI crashed mid-subagent, or CC emitted the
+ // spawn's tool_result after the stream closed). Ensures the
+ // in-thread assistant has its final text before fetchAndReplace.
+ for (const parentId of subagentRuns.keys()) {
+ await finalizeSubagentRun(parentId, context, subagentRuns).catch(console.error);
+ }
+
// Persist final content + reasoning + model for the last step BEFORE the
// terminal event triggers fetchAndReplaceMessages. Usage for this step
// was already written per-turn via the turn_metadata branch.