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.

πŸ› fix(hetero-agent): title subagent thread from a reasoning/text-first event (#16415)

Arvin Xucae8a8fa0388
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
index 41b0e963e1e..d65c05b5544 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
@@ -2493,6 +2493,97 @@ describe('ClaudeCodeAdapter', () => {
expect(secondChunk!.data.subagent.spawnMetadata).toBeUndefined();
});
+ it('stamps spawnMetadata on a reasoning-FIRST subagent event (titles the Thread correctly)', () => {
+ // A thinking Explore agent reasons before its first tool call. The
+ // executor lazy-creates + titles the Thread off the FIRST subagent event
+ // it sees, so the metadata must ride the reasoning chunk too β€” otherwise
+ // the Thread is born with the generic "Subagent" title.
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+ adapter.adapt(
+ mainAssistant('msg_main', {
+ id: 'toolu_agent',
+ input: {
+ description: 'Find git remote url lobe-chat',
+ prompt: 'locate the remote',
+ subagent_type: 'Explore',
+ },
+ name: 'Agent',
+ type: 'tool_use',
+ }),
+ );
+
+ // First subagent event is a reasoning block β€” no tool call yet.
+ const first = adapter.adapt(
+ subAgent('msg_sub_1', 'toolu_agent', { thinking: 'Let me look…', type: 'thinking' }),
+ );
+ const reasoningChunk = first.find(
+ (e) => e.type === 'stream_chunk' && e.data.chunkType === 'reasoning',
+ );
+ expect(reasoningChunk!.data.subagent.spawnMetadata).toEqual({
+ description: 'Find git remote url lobe-chat',
+ prompt: 'locate the remote',
+ subagentType: 'Explore',
+ });
+
+ // The later tool event for the same parent must NOT re-announce.
+ const second = adapter.adapt(
+ subAgent('msg_sub_2', 'toolu_agent', {
+ id: 'toolu_child',
+ input: {},
+ name: 'Bash',
+ type: 'tool_use',
+ }),
+ );
+ const toolChunk = second.find(
+ (e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
+ );
+ expect(toolChunk!.data.subagent.spawnMetadata).toBeUndefined();
+ });
+
+ it('does NOT burn the one-shot on a first event that emits no chunk', () => {
+ // The very first subagent event can carry nothing the reducer consumes β€”
+ // an empty text/thinking block or a usage-only `content: []`. That event
+ // never reaches `ensureRun` (no chunk), so it must NOT mark the parent
+ // announced; the metadata has to survive for the next REAL chunk, which is
+ // the one that actually lazy-creates + titles the Thread.
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt(init);
+ adapter.adapt(
+ mainAssistant('msg_main', {
+ id: 'toolu_agent',
+ input: {
+ description: 'Find git remote url lobe-chat',
+ prompt: 'locate the remote',
+ subagent_type: 'Explore',
+ },
+ name: 'Agent',
+ type: 'tool_use',
+ }),
+ );
+
+ // First subagent event: empty content + an empty text block β€” emits nothing.
+ const first = adapter.adapt({
+ message: { content: [{ text: '', type: 'text' }], id: 'msg_sub_0', usage: {} },
+ parent_tool_use_id: 'toolu_agent',
+ type: 'assistant',
+ });
+ expect(first.some((e) => e.type === 'stream_chunk')).toBe(false);
+
+ // Second event is the first REAL chunk β€” it must still carry spawnMetadata.
+ const second = adapter.adapt(
+ subAgent('msg_sub_1', 'toolu_agent', { thinking: 'Let me look…', type: 'thinking' }),
+ );
+ const reasoningChunk = second.find(
+ (e) => e.type === 'stream_chunk' && e.data.chunkType === 'reasoning',
+ );
+ expect(reasoningChunk!.data.subagent.spawnMetadata).toEqual({
+ description: 'Find git remote url lobe-chat',
+ prompt: 'locate the remote',
+ subagentType: 'Explore',
+ });
+ });
+
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
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
index b35d6e984ba..310d4633c8d 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
@@ -43,6 +43,7 @@ import type {
HeterogeneousTerminalErrorData,
StreamChunkData,
SubagentEventContext,
+ SubagentSpawnMetadata,
ToolCallPayload,
ToolResultData,
UsageData,
@@ -557,11 +558,32 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
/**
* 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
+ * exactly once per subagent run β€” on the first subagent event 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>();
+
+ /**
+ * Build the spawn metadata (`description` / `prompt` / `subagent_type`) for a
+ * subagent's parent tool_use from the cached Task/Agent input. Pure: it neither
+ * reads nor mutates {@link announcedSpawns} β€” the caller gates "exactly once"
+ * and only marks the parent announced when the metadata is actually attached to
+ * an EMITTED chunk (see `handleSubagentAssistant`). Returns undefined when the
+ * parent's args were never cached.
+ */
+ private buildSpawnMetadata(parentToolCallId: string): SubagentSpawnMetadata | undefined {
+ const args = this.mainToolInputsById.get(parentToolCallId);
+ if (!args) return undefined;
+ // CC's subagent-spawn tools (Task, Agent, ...) share the same input shape
+ // (`description`, `prompt`, `subagent_type`). Pull the fields defensively β€”
+ // any unknown spawn-tool variant matching this shape benefits automatically.
+ return {
+ 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,
+ };
+ }
/**
* Tool name keyed by main-agent `tool_use.id`. Used to label the
* resulting {@link ExternalSignalContext} when a Monitor-style task
@@ -943,11 +965,34 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
if (!Array.isArray(content)) return [];
const messageId: string | undefined = raw.message?.id;
- const subagentCtx = {
+ const baseCtx: SubagentEventContext = {
parentToolCallId: parentToolUseId,
subagentMessageId: messageId ?? '',
};
+ // Build spawn metadata once per parent and hand it to the FIRST chunk this
+ // event emits (reasoning, text, OR tool). The executor lazy-creates +
+ // titles the Thread off whichever subagent event it sees first, so a
+ // reasoning/text-first subagent must carry the metadata too β€” not just the
+ // tool path β€” or the Thread is born with the generic "Subagent" title.
+ //
+ // `announcedSpawns` is marked only when the metadata is ACTUALLY attached to
+ // an emitted chunk (inside `nextSubagentCtx`), not merely built here. A first
+ // event that emits nothing the reducer consumes (empty text/thinking block,
+ // an unsupported block, or a usage-only `content: []`) must NOT burn the
+ // one-shot β€” otherwise the next real chunk would create the Thread with the
+ // fallback title, the exact bug this guards against.
+ let pendingSpawnMetadata = this.announcedSpawns.has(parentToolUseId)
+ ? undefined
+ : this.buildSpawnMetadata(parentToolUseId);
+ const nextSubagentCtx = (): SubagentEventContext => {
+ if (!pendingSpawnMetadata) return baseCtx;
+ const ctx: SubagentEventContext = { ...baseCtx, spawnMetadata: pendingSpawnMetadata };
+ pendingSpawnMetadata = undefined;
+ this.announcedSpawns.add(parentToolUseId);
+ return ctx;
+ };
+
const textParts: string[] = [];
const reasoningParts: string[] = [];
const newToolCalls: ToolCallPayload[] = [];
@@ -995,7 +1040,7 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
this.makeChunkEvent({
chunkType: 'reasoning',
reasoning: reasoningParts.join(''),
- subagent: subagentCtx,
+ subagent: nextSubagentCtx(),
}),
);
}
@@ -1004,11 +1049,19 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
this.makeChunkEvent({
chunkType: 'text',
content: textParts.join(''),
- subagent: subagentCtx,
+ subagent: nextSubagentCtx(),
}),
);
}
- events.push(...this.emitToolChunk(newToolCalls, messageId, subagentCtx));
+ // Only consume the pending spawn metadata for the tool chunk when this
+ // event actually carries tools (else it would be lost on the no-op chunk).
+ events.push(
+ ...this.emitToolChunk(
+ newToolCalls,
+ messageId,
+ newToolCalls.length > 0 ? nextSubagentCtx() : baseCtx,
+ ),
+ );
const usage = toUsageData(raw.message?.usage);
if (usage) {
@@ -1017,7 +1070,7 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
model: raw.message?.model,
phase: 'turn_metadata',
provider: 'claude-code',
- subagent: subagentCtx,
+ subagent: baseCtx,
usage,
}),
);
@@ -1038,15 +1091,14 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
* 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.
+ * gets the context stamped as a peer field β€” including any `spawnMetadata`
+ * the caller already attached (`handleSubagentAssistant` builds it once per
+ * parent and hands it to the first emitted chunk, tool or otherwise).
*/
private emitToolChunk(
newToolCalls: ToolCallPayload[],
messageId: string | undefined,
- subagentCtx?: { parentToolCallId: string; subagentMessageId: string },
+ subagentCtx?: SubagentEventContext,
): HeterogeneousAgentEvent[] {
if (newToolCalls.length === 0) return [];
@@ -1057,30 +1109,10 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
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);
- }
+ // The `subagent` peer field β€” stamped on the chunk + each tool_start β€”
+ // is passed through verbatim (carrying `spawnMetadata` when the caller
+ // designated this the first emission for the parent).
+ const subagent: SubagentEventContext | undefined = subagentCtx;
const chunkData: StreamChunkData = {
chunkType: 'tools_calling',