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): keep background subagent wake-ups inside the run's reply (#21618)

AmAzing-f2c54b8546c4
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index a85839f783f..313f54cbb9d 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -68,6 +68,7 @@ the next free number of that prefix.
- **L-S24** Read the dev server's URL from its own log, and treat "ready" as any status but `000` — `/` answers `302` to `/signin` when signed out.
- **L-S25** `dev:static` 的 Electron 重启会清空 `dist/renderer`(renderer Vite dev server 启动即删 outDir);`start`/`restart` 后必须重建 renderer 再驱动,否则页面只有 Internal Server Error。
- **L-S26** 根 `.env` 起不来时不修它:开一个没有 `.env` 的 worktree,先按 L-S23 装依赖、L-S20 取端口、L-S9 建 per-run 库,再 `setup-db` → `migrate` → `seed-user` → `dev`。
+- **L-S27** A standalone `apps/cli` install relinks the shared `packages/*` it lists into its own store; before Web evidence in that worktree, rerun `pnpm install --force` at the root and restart the dev server.
## Entries
@@ -627,12 +628,30 @@ dev.mjs 每次启动都会拉起 renderer Vite dev server,而后者启动即
**Trap:** repo 根目录有 `.env`(Neon 口令已失效,或 `DATABASE_URL` 被指到本地库但 schema 落后、缺
`agent_history_jobs`),于是走「有 `.env` 就用现有配置」这条分支:`bun run dev` 起来但登录 500,
`setup-auth.sh` 又提示 `root .env exists; do not seed or modify this DB`。接下来会去改根 `.env`、改
-`node_modules` 里的依赖硬救——那都是别人的本地配置,救回来也只是这一轮能跑,下一轮照旧。
+`node_modules` 里的依赖硬救 —— 那都是别人的本地配置,救回来也只是这一轮能跑,下一轮照旧。
**Rule:** 根 `.env` 起不来就离开它:`git worktree add --detach /tmp/<slug> <ref-or-sha>` 开一棵没有
-根 `.env` 的树(`--detach`:正在检出的分支不能重复 checkout),再把这条路径走完整——按 L-S23 复制
+根 `.env` 的树(`--detach`:正在检出的分支不能重复 checkout),再把这条路径走完整 —— 按 L-S23 复制
一份可用的 `node_modules`(含各 package 自己的),按 L-S20 从 `docker ps` 取容器真实端口,按 L-S9
在容器里建 per-run 库并导出 `DATABASE_URL`,然后 `init-dev-env.sh setup-db` → `migrate` →
`seed-user` → `dev`(脚本一律用绝对路径,L-S21;端口从日志取,L-S24)。worktree 路径写进 report,
teardown 时 `clean` 停服、删掉这个库、`git worktree remove` 移除这棵树。不要在被改坏的根 `.env` 上
继续调试。
+
+### L-S27 — Taking Web evidence after a standalone `apps/cli` install
+
+`since 2026-10-25` · `holds-while: apps/cli/pnpm-workspace.yaml lists ../../packages/* as its own workspace projects`
+
+**Trap:** running `cd apps/cli && pnpm install` (PROJECT.md §6) in the worktree that also
+serves the Web surface. The CLI's workspace covers the shared packages, so the install
+rewrites their `packages/*/node_modules` links to point into `apps/cli/node_modules/.pnpm`.
+The server keeps working, but the SPA now loads a second React copy: routes fail with
+`The requested module '/apps/cli/node_modules/.pnpm/…' does not provide an export named
+'useSyncExternalStore'` and the page shows the error boundary, which reads like a broken
+build of the change under test.
+
+**Rule:** after a standalone CLI install, count the links that point into it
+(`find packages/*/node_modules -maxdepth 2 -type l -lname '*apps/cli/node_modules*'`).
+If any exist, run `pnpm install --force` at the root (a plain install reports "Already
+up to date" and leaves them), delete `node_modules/.vite`, and restart the dev server
+before capturing Web evidence.
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 76684a4a8cf..3623dbfd34a 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -659,6 +659,12 @@ data rather than an env leak.
standalone. Keep them for the final PRODUCTION publish of the verification round —
there the auto-attach to the current conversation is exactly what you want.
+The same leak hits a local `lh hetero exec --topic <t> --operation-id <op>` replay: the run
+also exports `LOBEHUB_ASSISTANT_MESSAGE_ID`, which the CLI forwards as the ingest's seeded
+assistant, so every batch fails with `Seeded assistantMessageId msg_… was not found for
+topic <t>`. Set it to the fixture's seeded assistant id and unset
+`LOBEHUB_HETERO_EXEC_INHERIT_PROCESS_GROUP` together with the ids above.
+
### Driving the UI
#### P21・Driving a 资源库 upload with agent-browser: use the Add-menu input, and a same-build A/B for the hashing thread
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts
index 44aa76c0794..17487215d83 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts
@@ -28,6 +28,7 @@ import { __resetOperationStatesForTesting, HeterogeneousPersistenceHandler } fro
interface FakeMessage {
content: string;
id: string;
+ metadata?: Record<string, any>;
parentId?: string | null;
role: 'user' | 'assistant' | 'tool';
seq: number;
@@ -76,6 +77,7 @@ const createHarness = () => {
const msg: FakeMessage = {
content: input.content ?? '',
id: msgId,
+ metadata: input.metadata,
parentId: input.parentId ?? null,
role: input.role!,
seq: seq++,
@@ -109,7 +111,7 @@ const createHarness = () => {
m.topicId === topicId &&
m.role !== 'tool' &&
m.threadId === (threadId ?? null) &&
- !(m as any).metadata?.signal,
+ !m.metadata?.signal,
)
.sort((a, b) => b.seq - a.seq)[0];
return match?.id;
@@ -224,3 +226,117 @@ describe('HeterogeneousPersistenceHandler — chain anchor survives a regressed
expect(a1AssistantChildren).toHaveLength(1);
});
});
+
+/**
+ * Regression observed in a production topic: the main agent launched background subagents,
+ * ended its turn with a toolless "still running" reply, and CC woke the LLM
+ * minutes later when each subagent finished. Those wake-up turns are signal
+ * turns and must hang off a tool so the read side folds them into the run's
+ * AssistantGroup. The batch carrying them reached a replica that had never
+ * reduced this run's tool batches, so the in-memory `lastToolMsgIdEver` was
+ * empty and both turns fell back onto the toolless spine reply — rendering as
+ * two extra top-level replies.
+ */
+describe('HeterogeneousPersistenceHandler — signal turn anchor on a cold replica', () => {
+ beforeEach(() => __resetOperationStatesForTesting());
+ afterEach(() => __resetOperationStatesForTesting());
+
+ const textStep = (stepIndex: number, ccMsgId: string, content: string): AgentStreamEvent[] => [
+ buildEvent('stream_start', stepIndex, {
+ messageId: ccMsgId,
+ newStep: true,
+ provider: 'claude-code',
+ }),
+ buildEvent('stream_chunk', stepIndex, { chunkType: 'text', content }),
+ ];
+
+ const signalStep = (stepIndex: number, ccMsgId: string): AgentStreamEvent[] => [
+ buildEvent('stream_start', stepIndex, {
+ externalSignal: {
+ sourceToolCallId: 'tc-A',
+ sourceToolName: 'Agent',
+ type: 'task-completion',
+ },
+ messageId: ccMsgId,
+ newStep: true,
+ provider: 'claude-code',
+ }),
+ buildEvent('stream_chunk', stepIndex, { chunkType: 'text', content: 'subagent finished' }),
+ ];
+
+ const signalTurn = (messages: Map<string, FakeMessage>) =>
+ [...messages.values()].find((m) => m.role === 'assistant' && m.metadata?.signal);
+
+ it("anchors the wake-up turn onto the run's last tool, not the toolless spine reply", async () => {
+ const h = createHarness();
+
+ // Warm replica: launch the background task, then end the turn without tools.
+ await h.handler.ingest({
+ assistantMessageId: SEED,
+ events: [...stepBatch(1, 'cc-A', 'tc-A'), ...textStep(2, 'cc-B', 'still running')],
+ operationId: OP,
+ topicId: TOPIC,
+ });
+ __resetOperationStatesForTesting();
+
+ // Cold replica: the task finished and CC woke the LLM.
+ await h.handler.ingest({
+ assistantMessageId: SEED,
+ events: signalStep(3, 'cc-C'),
+ operationId: OP,
+ topicId: TOPIC,
+ });
+
+ const launchTool = [...h.messages.values()].find(
+ (m) => m.role === 'tool' && m.tool_call_id === 'tc-A',
+ );
+ expect(launchTool).toBeDefined();
+ expect(signalTurn(h.messages)?.parentId).toBe(launchTool!.id);
+ });
+
+ it("does not anchor onto a previous run's tool when this run has none", async () => {
+ const h = createHarness();
+ // Seat SEED behind an earlier run: prevAsst (with a tool) → user → SEED.
+ h.messages.set('prev-asst', {
+ content: '',
+ id: 'prev-asst',
+ parentId: null,
+ role: 'assistant',
+ seq: -3,
+ threadId: null,
+ tools: [{ id: 'tc-prev', result_msg_id: 'prev-tool' }],
+ topicId: TOPIC,
+ });
+ h.messages.set('prev-tool', {
+ content: '',
+ id: 'prev-tool',
+ parentId: 'prev-asst',
+ role: 'tool',
+ seq: -2,
+ threadId: null,
+ tool_call_id: 'tc-prev',
+ topicId: TOPIC,
+ });
+ h.messages.set('user-1', {
+ content: 'next question',
+ id: 'user-1',
+ parentId: 'prev-asst',
+ role: 'user',
+ seq: -1,
+ threadId: null,
+ topicId: TOPIC,
+ });
+ h.messages.set(SEED, { ...h.messages.get(SEED)!, parentId: 'user-1', threadId: null });
+ h.messages.delete(T1);
+
+ await h.handler.ingest({
+ assistantMessageId: SEED,
+ events: signalStep(1, 'cc-A'),
+ operationId: OP,
+ topicId: TOPIC,
+ });
+
+ // No tool in this run: fall back to the spine, never cross the user turn.
+ expect(signalTurn(h.messages)?.parentId).toBe(SEED);
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
index b087dd170db..26758f844d4 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
@@ -17,6 +17,7 @@ import { applyMainIntent, applySubagentIntent } from './applyIntents';
import { eventKey, operationStates } from './operationState';
import {
loadOrCreateState,
+ recoverLastToolMessageFromDb,
refreshMainStateFromDb,
refreshSubagentRunsFromDb,
refreshToolMessageIndex,
@@ -31,6 +32,10 @@ const log = debug('lobe-server:hetero-agent:persistence');
const generateThreadId = () => `thd_${createNanoId(16)()}`;
+/** A `newStep` carrying `externalSignal` opens a signal turn (a background task's wake-up). */
+const opensSignalTurn = (event: AgentStreamEvent): boolean =>
+ event.type === 'stream_start' && !!event.data?.newStep && !!event.data?.externalSignal;
+
/** The raw text a CLI would have echoed into the answer for this failure. */
const errorEchoText = (error: { body?: Record<string, unknown>; message?: string }): string => {
const body = error.body ?? {};
@@ -117,6 +122,11 @@ export class HeterogeneousPersistenceHandler {
await refreshToolMessageIndex(this.deps, state);
await refreshMainStateFromDb(this.deps, state);
await refreshSubagentRunsFromDb(this.deps, state);
+ // Only a batch that opens a signal turn needs the tool anchor; skip the
+ // lookup for the rest.
+ if (params.events.some(opensSignalTurn)) {
+ await recoverLastToolMessageFromDb(this.deps, state);
+ }
for (const event of params.events) {
const key = eventKey(event);
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
index d1ef69d0a00..119da3dfbcb 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
@@ -415,6 +415,43 @@ export async function refreshMainStateFromDb(
if (spineId) state.main.lastSpineMessageId = spineId;
}
+/** Spine assistants walked back from the tip; a run's tools sit a hop or two behind it. */
+const MAX_SIGNAL_ANCHOR_HOPS = 50;
+
+/**
+ * Recover `lastToolMsgIdEver` — the anchor a signal turn (a background task's
+ * wake-up) parents off — on a replica that never reduced this run's tool
+ * batches. Without it the signal turn falls back onto the toolless spine reply,
+ * and the read side, which only collects signal turns under tools, renders it
+ * as a separate top-level reply.
+ *
+ * Walks the spine from its tip back through main-thread assistants and takes
+ * the last tool of the first one that called any. Stopping at the first
+ * non-assistant (the run's user message) keeps a previous run's tools out.
+ */
+export async function recoverLastToolMessageFromDb(
+ deps: HeterogeneousPersistenceHandlerDeps,
+ state: OperationState,
+): Promise<void> {
+ if (state.main.lastToolMsgIdEver) return;
+
+ const threadId = state.threadId ?? null;
+ let messageId: string | null | undefined = state.main.lastSpineMessageId;
+ for (let hop = 0; messageId && hop < MAX_SIGNAL_ANCHOR_HOPS; hop++) {
+ const message = await deps.messageModel.findById(messageId);
+ if (message?.role !== 'assistant' || (message.threadId ?? null) !== threadId) return;
+
+ const toolMessageId = ((message.tools ?? []) as ChatToolPayload[])
+ .map((tool) => tool.result_msg_id ?? state.toolMsgIdByCallId.get(tool.id))
+ .findLast(Boolean);
+ if (toolMessageId) {
+ state.main.lastToolMsgIdEver = toolMessageId;
+ return;
+ }
+ messageId = message.parentId;
+ }
+}
+
/**
* Rebuild the in-flight subagent runs (`state.main.subagents`) from DB.
*
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 4f81405d8f3..d0de2e9f7f5 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2310,6 +2310,8 @@
"taskCard.field.reviewRubrics": "Review rubrics",
"taskCard.field.subtasks": "Subtasks",
"taskCard.field.workspace": "Workspace",
+ "taskCompletion.title": "{{tool}} \"{{description}}\" finished",
+ "taskCompletion.titleWithoutDescription": "{{tool}} finished",
"taskDetail.acceptance.checklist": "Acceptance checklist",
"taskDetail.acceptance.closeDetail": "Close check detail",
"taskDetail.acceptance.collapseAll": "Collapse all groups",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 61a28064bd9..2573c42fbca 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2310,6 +2310,8 @@
"taskCard.field.reviewRubrics": "审核标准",
"taskCard.field.subtasks": "子任务",
"taskCard.field.workspace": "工作区",
+ "taskCompletion.title": "{{tool}}「{{description}}」已结束",
+ "taskCompletion.titleWithoutDescription": "{{tool}} 已结束",
"taskDetail.acceptance.checklist": "验收清单",
"taskDetail.acceptance.closeDetail": "关闭检查详情",
"taskDetail.acceptance.collapseAll": "折叠全部分组",
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.taskCompletions.test.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.taskCompletions.test.ts
new file mode 100644
index 00000000000..b67cbb61d2c
--- /dev/null
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.taskCompletions.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from 'vitest';
+
+import { parse } from '../parse';
+import type { Message } from '../types';
+
+const agentCall = (id: string, description: string) => ({
+ apiName: 'Agent',
+ arguments: JSON.stringify({ description, prompt: 'research' }),
+ id,
+ identifier: 'claude-code',
+ type: 'default' as const,
+});
+
+/**
+ * A run that launches two background subagents, ends its turn, and is woken
+ * once per finished subagent. Each wake-up hangs under the run's last tool row.
+ */
+const messages: Message[] = [
+ { content: 'plan it', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 },
+ {
+ content: '',
+ createdAt: 1,
+ id: 'a1',
+ parentId: 'u1',
+ role: 'assistant',
+ tools: [agentCall('call-srv', 'Server research'), agentCall('call-fe', 'Frontend research')],
+ updatedAt: 1,
+ },
+ {
+ content: 'launched',
+ createdAt: 2,
+ id: 't1',
+ parentId: 'a1',
+ role: 'tool',
+ tool_call_id: 'call-srv',
+ updatedAt: 2,
+ },
+ {
+ content: 'launched',
+ createdAt: 3,
+ id: 't2',
+ parentId: 'a1',
+ role: 'tool',
+ tool_call_id: 'call-fe',
+ updatedAt: 3,
+ },
+ {
+ content: 'Both still running.',
+ createdAt: 4,
+ id: 'a2',
+ parentId: 'a1',
+ role: 'assistant',
+ updatedAt: 4,
+ },
+ {
+ content: 'Server research is done.',
+ createdAt: 5,
+ id: 'w1',
+ metadata: {
+ signal: { sourceToolCallId: 'call-srv', sourceToolName: 'Agent', type: 'task-completion' },
+ },
+ parentId: 't2',
+ role: 'assistant',
+ updatedAt: 5,
+ },
+ {
+ content: 'Here is the plan.',
+ createdAt: 6,
+ id: 'w2',
+ metadata: {
+ signal: { sourceToolCallId: 'call-fe', sourceToolName: 'Agent', type: 'task-completion' },
+ },
+ parentId: 't2',
+ role: 'assistant',
+ updatedAt: 6,
+ },
+] as Message[];
+
+describe('FlatListBuilder — task-completion blocks', () => {
+ it('carries each wake-up turn’s signal lineage on its block', () => {
+ const { flatList } = parse(messages);
+
+ expect(flatList.map((m) => m.role)).toEqual(['user', 'assistantGroup']);
+ const group = flatList[1] as any;
+ expect(group.taskCompletions.map((b: any) => [b.id, b.metadata?.signal])).toEqual([
+ ['w1', { sourceToolCallId: 'call-srv', sourceToolName: 'Agent', type: 'task-completion' }],
+ ['w2', { sourceToolCallId: 'call-fe', sourceToolName: 'Agent', type: 'task-completion' }],
+ ]);
+ });
+});
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 6db87ca614e..803f908703f 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -1,12 +1,12 @@
import type { AssistantContentBlock, ChatToolPayloadWithResult } from '@lobechat/types';
-import { toTime } from '../utils/timestamp';
-
import { isInThreadScope } from '../indexing';
import type { Message, MessageGroupMetadata, ThreadScope } from '../types';
+import { toTime } from '../utils/timestamp';
import type { BranchResolver } from './BranchResolver';
import type { MessageCollector } from './MessageCollector';
import type { MessageTransformer } from './MessageTransformer';
+import { toTaskCompletionBlocks } from './taskCompletionBlocks';
/**
* Whether a message was authored by the group's supervisor agent.
@@ -1386,25 +1386,8 @@ export class FlatListBuilder {
}));
}
- // Snapshot post-task-summary turns as content blocks ().
- // They render after `<SignalCallbacks>` inside the same group, via
- // a second `<Group>` that pulls live content from the store using
- // the block id (no need to denormalize text here — keeps streaming
- // updates working without an extra refresh).
if (taskCompletionMessages && taskCompletionMessages.length > 0) {
- result.taskCompletions = taskCompletionMessages.map((m) => {
- const block: AssistantContentBlock = {
- content: m.content ?? '',
- id: m.id,
- };
- if (m.error) block.error = m.error;
- if (m.fileList && m.fileList.length > 0) block.fileList = m.fileList;
- if (m.imageList && m.imageList.length > 0) block.imageList = m.imageList;
- if (m.performance) block.performance = m.performance;
- if (m.reasoning) block.reasoning = m.reasoning;
- if (m.usage) block.usage = m.usage;
- return block;
- });
+ result.taskCompletions = toTaskCompletionBlocks(taskCompletionMessages);
}
return result;
diff --git a/packages/conversation-flow/src/transformation/taskCompletionBlocks.ts b/packages/conversation-flow/src/transformation/taskCompletionBlocks.ts
new file mode 100644
index 00000000000..97f41715497
--- /dev/null
+++ b/packages/conversation-flow/src/transformation/taskCompletionBlocks.ts
@@ -0,0 +1,28 @@
+import type { AssistantContentBlock } from '@lobechat/types';
+
+import type { Message } from '../types';
+
+/**
+ * Snapshot post-task-summary turns as content blocks for an AssistantGroup.
+ * They render after `<SignalCallbacks>` inside the same group, each through its
+ * own `<Group>` that pulls live content from the store by block id (no need to
+ * denormalize text here — keeps streaming updates working without an extra
+ * refresh). The block keeps the turn's signal lineage, so the renderer can mark
+ * which tool's completion woke it.
+ */
+export const toTaskCompletionBlocks = (messages: Message[]): AssistantContentBlock[] =>
+ messages.map((m) => {
+ const block: AssistantContentBlock = {
+ content: m.content ?? '',
+ id: m.id,
+ };
+ if (m.error) block.error = m.error;
+ if (m.fileList && m.fileList.length > 0) block.fileList = m.fileList;
+ if (m.imageList && m.imageList.length > 0) block.imageList = m.imageList;
+ if (m.performance) block.performance = m.performance;
+ if (m.reasoning) block.reasoning = m.reasoning;
+ if (m.usage) block.usage = m.usage;
+ const signal = (m.metadata as { signal?: unknown } | null | undefined)?.signal;
+ if (signal) block.metadata = { signal };
+ return block;
+ });
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.externalSignal.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.externalSignal.test.ts
new file mode 100644
index 00000000000..6cb2f577c68
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.externalSignal.test.ts
@@ -0,0 +1,463 @@
+import { describe, expect, it } from 'vitest';
+
+import { ClaudeCodeAdapter, ClaudeCodeSdkAdapter } from '.';
+
+describe('ClaudeCodeAdapter', () => {
+ // ────────────────────────────────────────────────────
+ // external signal detection (Monitor task callbacks)
+ // ────────────────────────────────────────────────────
+ describe('external signal detection ()', () => {
+ const init = (adapter: ClaudeCodeAdapter) => {
+ adapter.adapt({
+ model: 'claude-sonnet-4-6',
+ session_id: 'sess_1',
+ subtype: 'init',
+ type: 'system',
+ });
+ };
+
+ const ccUser = (toolCallId: string, content: string) => ({
+ message: {
+ content: [{ content, tool_use_id: toolCallId, type: 'tool_result' }],
+ },
+ type: 'user',
+ });
+ const ccMessageStart = (msgId: string) => ({
+ event: { message: { id: msgId, model: 'claude-sonnet-4-6' }, type: 'message_start' },
+ type: 'stream_event',
+ });
+ const ccTaskStarted = (taskId: string, toolUseId: string) => ({
+ session_id: 'sess_1',
+ subtype: 'task_started',
+ task_id: taskId,
+ tool_use_id: toolUseId,
+ type: 'system',
+ });
+ const ccTaskNotification = (taskId: string) => ({
+ session_id: 'sess_1',
+ subtype: 'task_notification',
+ task_id: taskId,
+ type: 'system',
+ });
+
+ /**
+ * Real-world Monitor flow recorded from `claude -p` against the
+ * Monitor skill:
+ * 1. LLM emits Monitor tool_use → adapter notes the name
+ * 2. CC emits `system task_started` (Monitor registers as a task)
+ * 3. user event with tool_result (initial "Monitor started" ack)
+ * 4. Assistant turn opens, LLM writes confirmation toolless reply
+ * 5. RESULT — turn ends, no new user input arrives
+ * 6. SYSTEM init + assistant message_start — Monitor's stdout
+ * pushed and CC re-invoked the LLM. THIS turn is a signal callback.
+ */
+ it('attaches externalSignal when a new turn opens without user input while a task is active', () => {
+ const adapter = new ClaudeCodeAdapter();
+ init(adapter);
+
+ // Step 0: Monitor tool_use
+ adapter.adapt({
+ message: {
+ content: [
+ { id: 'toolu_mon', input: { shell: 'every 1s' }, name: 'Monitor', type: 'tool_use' },
+ ],
+ id: 'msg_01',
+ },
+ type: 'assistant',
+ });
+
+ // CC registers the long-running task
+ adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
+
+ // Initial tool_result (LLM's natural follow-up turn — NOT a signal callback)
+ adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
+
+ // Step 1: natural confirmation turn — opens AFTER the user event,
+ // so it consumes `hasUnhandledUserInput` and is NOT signal-tagged.
+ const confirm = adapter.adapt(ccMessageStart('msg_02'));
+ const confirmStart = confirm.find((e) => e.type === 'stream_start' && e.data?.newStep);
+ expect(confirmStart!.data.externalSignal).toBeUndefined();
+
+ // Step 2: Monitor pushed an event → CC re-invokes the LLM without
+ // any new user message. A signal callback.
+ const cb1 = adapter.adapt(ccMessageStart('msg_03'));
+ const cb1Start = cb1.find((e) => e.type === 'stream_start' && e.data?.newStep);
+ expect(cb1Start!.data.externalSignal).toEqual({
+ sequence: 1,
+ sourceToolCallId: 'toolu_mon',
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout',
+ });
+ });
+
+ // Regression (P2): on the BATCH path, when the post-tool confirmation REUSES
+ // the Monitor tool's message.id, the forced split must still consume
+ // `hasUnhandledUserInput` (armed by the tool_result). Otherwise the stale
+ // flag survives and the next callback turn — opened while the task is active
+ // with no new user input — fails the `!hasUnhandledUserInput` signal check,
+ // leaving the first stdout callback untagged.
+ it('still tags the next callback after a forced post-tool split reuses the tool id (batch Monitor flow)', () => {
+ const adapter = new ClaudeCodeAdapter();
+ init(adapter);
+
+ // Monitor tool_use under msg_01 (batch: an `assistant` event, not a delta).
+ adapter.adapt({
+ message: {
+ content: [
+ { id: 'toolu_mon', input: { shell: 'every 1s' }, name: 'Monitor', type: 'tool_use' },
+ ],
+ id: 'msg_01',
+ },
+ type: 'assistant',
+ });
+ adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
+ // tool_result → arms hasUnhandledUserInput.
+ adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
+
+ // Confirmation turn REUSES msg_01 → forced post-tool split. It is the
+ // natural follow-up to the tool_result, so it carries no signal AND must
+ // consume hasUnhandledUserInput.
+ const confirm = adapter.adapt({
+ message: {
+ id: 'msg_01',
+ content: [{ text: 'mock monitoring confirmation', type: 'text' }],
+ },
+ type: 'assistant',
+ });
+ const confirmStart = confirm.find((e) => e.type === 'stream_start' && e.data?.newStep);
+ expect(confirmStart).toBeDefined();
+ expect(confirmStart!.data.externalSignal).toBeUndefined();
+
+ // Monitor pushes an event → CC re-invokes with a NEW id and no new user
+ // input. This callback must be signal-tagged — only true once the forced
+ // split cleared the stale flag.
+ const cb1 = adapter.adapt({
+ message: { id: 'msg_02', content: [{ text: 'mock callback turn', type: 'text' }] },
+ type: 'assistant',
+ });
+ const cb1Start = cb1.find((e) => e.type === 'stream_start' && e.data?.newStep);
+ expect(cb1Start!.data.externalSignal).toEqual({
+ sequence: 1,
+ sourceToolCallId: 'toolu_mon',
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout',
+ });
+ });
+
+ it('keeps tagging consecutive signal callbacks with incrementing sequence', () => {
+ const adapter = new ClaudeCodeAdapter();
+ init(adapter);
+
+ adapter.adapt({
+ message: {
+ content: [{ id: 'toolu_mon', input: {}, name: 'Monitor', type: 'tool_use' }],
+ id: 'msg_01',
+ },
+ type: 'assistant',
+ });
+ adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
+ adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
+ adapter.adapt(ccMessageStart('msg_02')); // confirmation turn (no signal)
+
+ const sequences: (number | undefined)[] = [];
+ for (let i = 3; i <= 5; i++) {
+ const ev = adapter.adapt(ccMessageStart(`msg_0${i}`));
+ const start = ev.find((e) => e.type === 'stream_start' && e.data?.newStep);
+ sequences.push(start!.data.externalSignal?.sequence);
+ }
+ expect(sequences).toEqual([1, 2, 3]);
+ });
+
+ it('tags the post-task summary turn with `task-completion` after `task_notification`', () => {
+ const adapter = new ClaudeCodeAdapter();
+ init(adapter);
+
+ adapter.adapt({
+ message: {
+ content: [{ id: 'toolu_mon', input: {}, name: 'Monitor', type: 'tool_use' }],
+ id: 'msg_01',
+ },
+ type: 'assistant',
+ });
+ adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
+ adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
+ adapter.adapt(ccMessageStart('msg_02')); // confirmation (no signal)
+
+ // One signal callback while task is alive
+ const cb1 = adapter.adapt(ccMessageStart('msg_03'));
+ expect(
+ cb1.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
+ ).toEqual({
+ sequence: 1,
+ sourceToolCallId: 'toolu_mon',
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout',
+ });
+
+ // Task ends
+ adapter.adapt(ccTaskNotification('task_1'));
+
+ // Next turn — task ended, but the post-task summary keeps the
+ // source-tool lineage so MessageCollector can render it inside
+ // the same AssistantGroup as the preceding callbacks.
+ const after = adapter.adapt(ccMessageStart('msg_04'));
+ expect(
+ after.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
+ ).toEqual({
+ sourceToolCallId: 'toolu_mon',
+ sourceToolName: 'Monitor',
+ type: 'task-completion',
+ });
+
+ // The completion tag is one-shot — a subsequent turn (e.g. if CC
+ // spawned another LLM call) must not inherit it.
+ const followUp = adapter.adapt(ccMessageStart('msg_05'));
+ expect(
+ followUp.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
+ ).toBeUndefined();
+ });
+
+ it('treats SDK background Bash completion notification as task-completion lineage', () => {
+ const adapter = new ClaudeCodeSdkAdapter();
+ init(adapter);
+
+ adapter.adapt({
+ message: {
+ content: [
+ {
+ id: 'toolu_bash',
+ input: { command: 'sleep 1 && echo done', run_in_background: true },
+ name: 'Bash',
+ type: 'tool_use',
+ },
+ ],
+ id: 'msg_01',
+ },
+ type: 'assistant',
+ });
+ adapter.adapt(ccTaskStarted('task_1', 'toolu_bash'));
+ adapter.adapt(ccUser('toolu_bash', 'Background command started'));
+
+ const firstResult = adapter.adapt({
+ is_error: false,
+ result: 'Background command started',
+ type: 'result',
+ });
+ expect(firstResult.map((e) => e.type)).toEqual(['stream_end']);
+
+ adapter.adapt(ccTaskNotification('task_1'));
+
+ const completion = adapter.adapt(ccMessageStart('msg_02'));
+ expect(
+ completion.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
+ ).toEqual({
+ sourceToolCallId: 'toolu_bash',
+ sourceToolName: 'Bash',
+ type: 'task-completion',
+ });
+ });
+
+ /**
+ * Real-world regression (a production topic): two background subagents ran at
+ * once. `Agent` runs in the background by default, so neither call carried
+ * `run_in_background`. When the first finished, its wake-up turn was tagged
+ * as a `tool-stdout` callback of the OTHER, still-running subagent.
+ */
+ it('attributes each background Agent wake-up to the subagent that finished', () => {
+ const adapter = new ClaudeCodeSdkAdapter();
+ init(adapter);
+
+ const agentCall = (id: string) => ({
+ id,
+ input: { description: id, prompt: 'research', subagent_type: 'Explore' },
+ name: 'Agent',
+ type: 'tool_use',
+ });
+ adapter.adapt({
+ message: { content: [agentCall('toolu_srv'), agentCall('toolu_fe')], id: 'msg_01' },
+ type: 'assistant',
+ });
+ adapter.adapt(ccTaskStarted('task_srv', 'toolu_srv'));
+ adapter.adapt(ccTaskStarted('task_fe', 'toolu_fe'));
+ adapter.adapt(ccUser('toolu_srv', 'Async agent launched successfully.'));
+ adapter.adapt(ccUser('toolu_fe', 'Async agent launched successfully.'));
+ adapter.adapt(ccMessageStart('msg_02')); // "both still running" reply
+ adapter.adapt({ is_error: false, result: 'running', type: 'result' });
+
+ const signalOf = (events: ReturnType<typeof adapter.adapt>) =>
+ events.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal;
+
+ adapter.adapt(ccTaskNotification('task_srv'));
+ expect(signalOf(adapter.adapt(ccMessageStart('msg_03')))).toEqual({
+ sourceToolCallId: 'toolu_srv',
+ sourceToolName: 'Agent',
+ type: 'task-completion',
+ });
+ adapter.adapt({ is_error: false, result: 'one done', type: 'result' });
+
+ adapter.adapt(ccTaskNotification('task_fe'));
+ expect(signalOf(adapter.adapt(ccMessageStart('msg_04')))).toEqual({
+ sourceToolCallId: 'toolu_fe',
+ sourceToolName: 'Agent',
+ type: 'task-completion',
+ });
+ });
+
+ it('drops a task completion the next natural turn already answered', () => {
+ const adapter = new ClaudeCodeSdkAdapter();
+ init(adapter);
+
+ // A Monitor stays alive for the whole run.
+ adapter.adapt({
+ message: {
+ content: [{ id: 'toolu_mon', input: {}, name: 'Monitor', type: 'tool_use' }],
+ id: 'msg_01',
+ },
+ type: 'assistant',
+ });
+ adapter.adapt(ccTaskStarted('task_mon', 'toolu_mon'));
+ adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
+
+ // A background Bash starts and finishes while the run is still busy.
+ adapter.adapt({
+ message: {
+ content: [
+ {
+ id: 'toolu_bg',
+ input: { command: 'sleep 1', run_in_background: true },
+ name: 'Bash',
+ type: 'tool_use',
+ },
+ ],
+ id: 'msg_02',
+ },
+ type: 'assistant',
+ });
+ adapter.adapt(ccTaskStarted('task_bg', 'toolu_bg'));
+ adapter.adapt(ccUser('toolu_bg', 'Background command started'));
+ adapter.adapt(ccTaskNotification('task_bg'));
+ // The tool_result follow-up delivers the finished task's notification.
+ adapter.adapt(ccMessageStart('msg_03'));
+
+ // The next wake-up comes from the Monitor, not the finished Bash.
+ const cb = adapter.adapt(ccMessageStart('msg_04'));
+ expect(
+ cb.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
+ ).toEqual({
+ sequence: 1,
+ sourceToolCallId: 'toolu_mon',
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout',
+ });
+ });
+
+ /**
+ * Real-world regression (recorded on tpc_joZS2mksoY5L): a slow `git commit`
+ * (running a lint-staged hook) makes CC track the Bash call as a task and
+ * emit `task_started` + `task_notification` back-to-back, with NO out-of-band
+ * callback turn in between, immediately followed by the tool_result. That is
+ * an inline synchronous tool, not a Monitor-style long-running task — the next
+ * turn is the normal main-chain continuation and must NOT be tagged
+ * `task-completion` (doing so mis-anchors it and drops it from the rendered
+ * chain).
+ */
+ it('does NOT tag the next turn when a task started and ended with no callbacks (inline tool)', () => {
+ const adapter = new ClaudeCodeAdapter();
+ init(adapter);
+
+ // A Bash `git commit` tool_use.
+ adapter.adapt({
+ message: {
+ content: [
+ {
+ id: 'toolu_commit',
+ input: { command: 'git commit' },
+ name: 'Bash',
+ type: 'tool_use',
+ },
+ ],
+ id: 'msg_01',
+ },
+ type: 'assistant',
+ });
+
+ // CC tracks the slow commit as a task, then notifies completion
+ // back-to-back — NO callback turn opened while it was alive.
+ adapter.adapt(ccTaskStarted('task_1', 'toolu_commit'));
+ adapter.adapt(ccTaskNotification('task_1'));
+
+ // The commit's tool_result is consumed inline by the next turn.
+ adapter.adapt(ccUser('toolu_commit', 'committed'));
+
+ // Next turn is plain continuation — must carry NO externalSignal.
+ const next = adapter.adapt(ccMessageStart('msg_02'));
+ expect(
+ next.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
+ ).toBeUndefined();
+ });
+
+ it('clears unconsumed task-completion lineage on `result`', () => {
+ const adapter = new ClaudeCodeAdapter();
+ init(adapter);
+
+ adapter.adapt({
+ message: {
+ content: [{ id: 'toolu_mon', input: {}, name: 'Monitor', type: 'tool_use' }],
+ id: 'msg_01',
+ },
+ type: 'assistant',
+ });
+ adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
+ adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
+ adapter.adapt(ccMessageStart('msg_02'));
+ // A signal callback fires while the task is alive (callbackCount > 0), so
+ // `task_notification` genuinely arms pendingTaskCompletion — otherwise (an
+ // inline tool with no callbacks) nothing is armed and this test would pass
+ // vacuously, no longer guarding the `result` clear path.
+ adapter.adapt(ccMessageStart('msg_03'));
+ adapter.adapt(ccTaskNotification('task_1'));
+ // Run ends before the summary turn fires (unusual but possible).
+ adapter.adapt({ result: 'ok', type: 'result', usage: undefined });
+
+ // A later turn (e.g. follow-up user message) must NOT inherit
+ // the unconsumed task-completion lineage — `result` dropped it.
+ const next = adapter.adapt(ccMessageStart('msg_04'));
+ expect(
+ next.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
+ ).toBeUndefined();
+ });
+
+ it('does NOT trigger from subagent inner user events', () => {
+ const adapter = new ClaudeCodeAdapter();
+ init(adapter);
+
+ // Main agent fires Monitor, then registers task
+ adapter.adapt({
+ message: {
+ content: [{ id: 'toolu_mon', input: {}, name: 'Monitor', type: 'tool_use' }],
+ id: 'msg_01',
+ },
+ type: 'assistant',
+ });
+ adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
+ adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
+ adapter.adapt(ccMessageStart('msg_02')); // confirmation (no signal)
+
+ // Subagent inner tool_result fires WITH parent_tool_use_id — must
+ // NOT reset hasUnhandledUserInput; the next main-chain turn is
+ // still a signal callback.
+ adapter.adapt({
+ message: {
+ content: [{ content: 'inner', tool_use_id: 'toolu_inner', type: 'tool_result' }],
+ },
+ parent_tool_use_id: 'toolu_other',
+ type: 'user',
+ });
+
+ const ev = adapter.adapt(ccMessageStart('msg_03'));
+ expect(
+ ev.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
+ ).toBeDefined();
+ });
+ });
+});
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
index 5d871d4c46e..51ea23ec6f4 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
@@ -3332,368 +3332,4 @@ describe('ClaudeCodeAdapter', () => {
expect(end!.data.subagent).toEqual({ parentToolCallId: 'toolu_task' });
});
});
-
- // ────────────────────────────────────────────────────
- // external signal detection (Monitor task callbacks)
- // ────────────────────────────────────────────────────
- describe('external signal detection ()', () => {
- const init = (adapter: ClaudeCodeAdapter) => {
- adapter.adapt({
- model: 'claude-sonnet-4-6',
- session_id: 'sess_1',
- subtype: 'init',
- type: 'system',
- });
- };
-
- const ccUser = (toolCallId: string, content: string) => ({
- message: {
- content: [{ content, tool_use_id: toolCallId, type: 'tool_result' }],
- },
- type: 'user',
- });
- const ccMessageStart = (msgId: string) => ({
- event: { message: { id: msgId, model: 'claude-sonnet-4-6' }, type: 'message_start' },
- type: 'stream_event',
- });
- const ccTaskStarted = (taskId: string, toolUseId: string) => ({
- session_id: 'sess_1',
- subtype: 'task_started',
- task_id: taskId,
- tool_use_id: toolUseId,
- type: 'system',
- });
- const ccTaskNotification = (taskId: string) => ({
- session_id: 'sess_1',
- subtype: 'task_notification',
- task_id: taskId,
- type: 'system',
- });
-
- /**
- * Real-world Monitor flow recorded from `claude -p` against the
- * Monitor skill:
- * 1. LLM emits Monitor tool_use → adapter notes the name
- * 2. CC emits `system task_started` (Monitor registers as a task)
- * 3. user event with tool_result (initial "Monitor started" ack)
- * 4. Assistant turn opens, LLM writes confirmation toolless reply
- * 5. RESULT — turn ends, no new user input arrives
- * 6. SYSTEM init + assistant message_start — Monitor's stdout
- * pushed and CC re-invoked the LLM. THIS turn is a signal callback.
- */
- it('attaches externalSignal when a new turn opens without user input while a task is active', () => {
- const adapter = new ClaudeCodeAdapter();
- init(adapter);
-
- // Step 0: Monitor tool_use
- adapter.adapt({
- message: {
- content: [
- { id: 'toolu_mon', input: { shell: 'every 1s' }, name: 'Monitor', type: 'tool_use' },
- ],
- id: 'msg_01',
- },
- type: 'assistant',
- });
-
- // CC registers the long-running task
- adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
-
- // Initial tool_result (LLM's natural follow-up turn — NOT a signal callback)
- adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
-
- // Step 1: natural confirmation turn — opens AFTER the user event,
- // so it consumes `hasUnhandledUserInput` and is NOT signal-tagged.
- const confirm = adapter.adapt(ccMessageStart('msg_02'));
- const confirmStart = confirm.find((e) => e.type === 'stream_start' && e.data?.newStep);
- expect(confirmStart!.data.externalSignal).toBeUndefined();
-
- // Step 2: Monitor pushed an event → CC re-invokes the LLM without
- // any new user message. A signal callback.
- const cb1 = adapter.adapt(ccMessageStart('msg_03'));
- const cb1Start = cb1.find((e) => e.type === 'stream_start' && e.data?.newStep);
- expect(cb1Start!.data.externalSignal).toEqual({
- sequence: 1,
- sourceToolCallId: 'toolu_mon',
- sourceToolName: 'Monitor',
- type: 'tool-stdout',
- });
- });
-
- // Regression (P2): on the BATCH path, when the post-tool confirmation REUSES
- // the Monitor tool's message.id, the forced split must still consume
- // `hasUnhandledUserInput` (armed by the tool_result). Otherwise the stale
- // flag survives and the next callback turn — opened while the task is active
- // with no new user input — fails the `!hasUnhandledUserInput` signal check,
- // leaving the first stdout callback untagged.
- it('still tags the next callback after a forced post-tool split reuses the tool id (batch Monitor flow)', () => {
- const adapter = new ClaudeCodeAdapter();
- init(adapter);
-
- // Monitor tool_use under msg_01 (batch: an `assistant` event, not a delta).
- adapter.adapt({
- message: {
- content: [
- { id: 'toolu_mon', input: { shell: 'every 1s' }, name: 'Monitor', type: 'tool_use' },
- ],
- id: 'msg_01',
- },
- type: 'assistant',
- });
- adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
- // tool_result → arms hasUnhandledUserInput.
- adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
-
- // Confirmation turn REUSES msg_01 → forced post-tool split. It is the
- // natural follow-up to the tool_result, so it carries no signal AND must
- // consume hasUnhandledUserInput.
- const confirm = adapter.adapt({
- message: {
- id: 'msg_01',
- content: [{ text: 'mock monitoring confirmation', type: 'text' }],
- },
- type: 'assistant',
- });
- const confirmStart = confirm.find((e) => e.type === 'stream_start' && e.data?.newStep);
- expect(confirmStart).toBeDefined();
- expect(confirmStart!.data.externalSignal).toBeUndefined();
-
- // Monitor pushes an event → CC re-invokes with a NEW id and no new user
- // input. This callback must be signal-tagged — only true once the forced
- // split cleared the stale flag.
- const cb1 = adapter.adapt({
- message: { id: 'msg_02', content: [{ text: 'mock callback turn', type: 'text' }] },
- type: 'assistant',
- });
- const cb1Start = cb1.find((e) => e.type === 'stream_start' && e.data?.newStep);
- expect(cb1Start!.data.externalSignal).toEqual({
- sequence: 1,
- sourceToolCallId: 'toolu_mon',
- sourceToolName: 'Monitor',
- type: 'tool-stdout',
- });
- });
-
- it('keeps tagging consecutive signal callbacks with incrementing sequence', () => {
- const adapter = new ClaudeCodeAdapter();
- init(adapter);
-
- adapter.adapt({
- message: {
- content: [{ id: 'toolu_mon', input: {}, name: 'Monitor', type: 'tool_use' }],
- id: 'msg_01',
- },
- type: 'assistant',
- });
- adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
- adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
- adapter.adapt(ccMessageStart('msg_02')); // confirmation turn (no signal)
-
- const sequences: (number | undefined)[] = [];
- for (let i = 3; i <= 5; i++) {
- const ev = adapter.adapt(ccMessageStart(`msg_0${i}`));
- const start = ev.find((e) => e.type === 'stream_start' && e.data?.newStep);
- sequences.push(start!.data.externalSignal?.sequence);
- }
- expect(sequences).toEqual([1, 2, 3]);
- });
-
- it('tags the post-task summary turn with `task-completion` after `task_notification`', () => {
- const adapter = new ClaudeCodeAdapter();
- init(adapter);
-
- adapter.adapt({
- message: {
- content: [{ id: 'toolu_mon', input: {}, name: 'Monitor', type: 'tool_use' }],
- id: 'msg_01',
- },
- type: 'assistant',
- });
- adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
- adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
- adapter.adapt(ccMessageStart('msg_02')); // confirmation (no signal)
-
- // One signal callback while task is alive
- const cb1 = adapter.adapt(ccMessageStart('msg_03'));
- expect(
- cb1.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
- ).toEqual({
- sequence: 1,
- sourceToolCallId: 'toolu_mon',
- sourceToolName: 'Monitor',
- type: 'tool-stdout',
- });
-
- // Task ends
- adapter.adapt(ccTaskNotification('task_1'));
-
- // Next turn — task ended, but the post-task summary keeps the
- // source-tool lineage so MessageCollector can render it inside
- // the same AssistantGroup as the preceding callbacks.
- const after = adapter.adapt(ccMessageStart('msg_04'));
- expect(
- after.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
- ).toEqual({
- sourceToolCallId: 'toolu_mon',
- sourceToolName: 'Monitor',
- type: 'task-completion',
- });
-
- // The completion tag is one-shot — a subsequent turn (e.g. if CC
- // spawned another LLM call) must not inherit it.
- const followUp = adapter.adapt(ccMessageStart('msg_05'));
- expect(
- followUp.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
- ).toBeUndefined();
- });
-
- it('treats SDK background Bash completion notification as task-completion lineage', () => {
- const adapter = new ClaudeCodeSdkAdapter();
- init(adapter);
-
- adapter.adapt({
- message: {
- content: [
- {
- id: 'toolu_bash',
- input: { command: 'sleep 1 && echo done', run_in_background: true },
- name: 'Bash',
- type: 'tool_use',
- },
- ],
- id: 'msg_01',
- },
- type: 'assistant',
- });
- adapter.adapt(ccTaskStarted('task_1', 'toolu_bash'));
- adapter.adapt(ccUser('toolu_bash', 'Background command started'));
-
- const firstResult = adapter.adapt({
- is_error: false,
- result: 'Background command started',
- type: 'result',
- });
- expect(firstResult.map((e) => e.type)).toEqual(['stream_end']);
-
- adapter.adapt(ccTaskNotification('task_1'));
-
- const completion = adapter.adapt(ccMessageStart('msg_02'));
- expect(
- completion.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
- ).toEqual({
- sourceToolCallId: 'toolu_bash',
- sourceToolName: 'Bash',
- type: 'task-completion',
- });
- });
-
- /**
- * Real-world regression (recorded on tpc_joZS2mksoY5L): a slow `git commit`
- * (running a lint-staged hook) makes CC track the Bash call as a task and
- * emit `task_started` + `task_notification` back-to-back, with NO out-of-band
- * callback turn in between, immediately followed by the tool_result. That is
- * an inline synchronous tool, not a Monitor-style long-running task — the next
- * turn is the normal main-chain continuation and must NOT be tagged
- * `task-completion` (doing so mis-anchors it and drops it from the rendered
- * chain).
- */
- it('does NOT tag the next turn when a task started and ended with no callbacks (inline tool)', () => {
- const adapter = new ClaudeCodeAdapter();
- init(adapter);
-
- // A Bash `git commit` tool_use.
- adapter.adapt({
- message: {
- content: [
- {
- id: 'toolu_commit',
- input: { command: 'git commit' },
- name: 'Bash',
- type: 'tool_use',
- },
- ],
- id: 'msg_01',
- },
- type: 'assistant',
- });
-
- // CC tracks the slow commit as a task, then notifies completion
- // back-to-back — NO callback turn opened while it was alive.
- adapter.adapt(ccTaskStarted('task_1', 'toolu_commit'));
- adapter.adapt(ccTaskNotification('task_1'));
-
- // The commit's tool_result is consumed inline by the next turn.
- adapter.adapt(ccUser('toolu_commit', 'committed'));
-
- // Next turn is plain continuation — must carry NO externalSignal.
- const next = adapter.adapt(ccMessageStart('msg_02'));
- expect(
- next.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
- ).toBeUndefined();
- });
-
- it('clears unconsumed task-completion lineage on `result`', () => {
- const adapter = new ClaudeCodeAdapter();
- init(adapter);
-
- adapter.adapt({
- message: {
- content: [{ id: 'toolu_mon', input: {}, name: 'Monitor', type: 'tool_use' }],
- id: 'msg_01',
- },
- type: 'assistant',
- });
- adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
- adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
- adapter.adapt(ccMessageStart('msg_02'));
- // A signal callback fires while the task is alive (callbackCount > 0), so
- // `task_notification` genuinely arms pendingTaskCompletion — otherwise (an
- // inline tool with no callbacks) nothing is armed and this test would pass
- // vacuously, no longer guarding the `result` clear path.
- adapter.adapt(ccMessageStart('msg_03'));
- adapter.adapt(ccTaskNotification('task_1'));
- // Run ends before the summary turn fires (unusual but possible).
- adapter.adapt({ result: 'ok', type: 'result', usage: undefined });
-
- // A later turn (e.g. follow-up user message) must NOT inherit
- // the unconsumed task-completion lineage — `result` dropped it.
- const next = adapter.adapt(ccMessageStart('msg_04'));
- expect(
- next.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
- ).toBeUndefined();
- });
-
- it('does NOT trigger from subagent inner user events', () => {
- const adapter = new ClaudeCodeAdapter();
- init(adapter);
-
- // Main agent fires Monitor, then registers task
- adapter.adapt({
- message: {
- content: [{ id: 'toolu_mon', input: {}, name: 'Monitor', type: 'tool_use' }],
- id: 'msg_01',
- },
- type: 'assistant',
- });
- adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
- adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
- adapter.adapt(ccMessageStart('msg_02')); // confirmation (no signal)
-
- // Subagent inner tool_result fires WITH parent_tool_use_id — must
- // NOT reset hasUnhandledUserInput; the next main-chain turn is
- // still a signal callback.
- adapter.adapt({
- message: {
- content: [{ content: 'inner', tool_use_id: 'toolu_inner', type: 'tool_result' }],
- },
- parent_tool_use_id: 'toolu_other',
- type: 'user',
- });
-
- const ev = adapter.adapt(ccMessageStart('msg_03'));
- expect(
- ev.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
- ).toBeDefined();
- });
- });
});
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
index e9dbc0ce7f5..989420c2601 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
@@ -58,6 +58,7 @@ import type {
ToolResultData,
UsageData,
} from '../types';
+import { ClaudeCodeTaskSignals } from './claudeCodeTaskSignals';
/**
* The CC tool_use `name` we synthesize `pluginState.todos` for. Inlined here
@@ -1180,25 +1181,8 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {
* not the main-agent signal detector.
*/
private mainToolNamesById = new Map<string, string>();
- /**
- * Active CC tasks (long-running tools registered via `system task_started`).
- * Keyed by `task_id`, carries the originating `tool_use_id`, the resolved
- * tool name, and a counter incremented for each signal callback turn
- * the adapter attributes to this task.
- *
- * A task lives from `task_started` until `task_notification` /
- * `task_completed`. While alive, any `message_start` that opens a turn
- * WITHOUT a preceding `user` event is a signal callback and gets tagged.
- */
- private activeTasks = new Map<
- string,
- {
- callbackCount: number;
- shouldSignalCompletion: boolean;
- sourceToolName: string;
- toolUseId: string;
- }
- >();
+ /** CC's long-running task lifecycle and the signal lineage it stamps on turns. */
+ private readonly taskSignals: ClaudeCodeTaskSignals;
/**
* True after a `user` event has been seen but the next turn hasn't yet
* opened (`message_start` not yet fired). Carries the "this next turn
@@ -1207,8 +1191,8 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {
* resulting assistant turn.
*
* Reset to `false` once a `message_start` consumes it. After that, any
- * further `message_start` that opens while {@link activeTasks} is
- * non-empty is treated as a signal callback (CC re-invoked the LLM
+ * further `message_start` is asked of {@link taskSignals} — a turn opened
+ * while a task is alive is a signal callback (CC re-invoked the LLM
* because a long-running tool pushed an update).
*/
private hasUnhandledUserInput = false;
@@ -1216,25 +1200,11 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {
* {@link ExternalSignalContext} to attach to the NEXT `stream_start(newStep)`.
*
* Armed by `message_start` when {@link hasUnhandledUserInput} is false
- * AND {@link activeTasks} is non-empty — i.e. CC opened a new turn
- * without fresh user input while a long-running tool is alive. Cleared
- * on the next `tool_use` (LLM is back on the main chain).
+ * and {@link taskSignals} attributes the turn to a task — i.e. CC opened a
+ * new turn without fresh user input. Cleared on the next `tool_use` (LLM is
+ * back on the main chain).
*/
private pendingExternalSignal: ExternalSignalContext | undefined;
- /**
- * Source-tool lineage of the most recently completed long-running task,
- * waiting to be stamped on the post-task summary turn with
- * `type: 'task-completion'`.
- *
- * Armed when `system task_notification` ends an active task; consumed
- * by the NEXT `message_start` that takes the natural-turn branch
- * (no other active task triggering a callback). Cleared on `result`
- * so it never leaks across LLM runs.
- *
- * Lets the renderer keep the summary inside the same AssistantGroup as
- * the preceding callbacks instead of letting it spawn a separate group.
- */
- private pendingTaskCompletion: { sourceToolCallId: string; sourceToolName: string } | undefined;
/**
* Map a raw per-turn usage object (from `message_delta.usage` in partial
@@ -1273,6 +1243,7 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {
) {
this.options = { ...DEFAULT_ADAPTER_OPTIONS, ...options };
this.profile = profile;
+ this.taskSignals = new ClaudeCodeTaskSignals(this.options.signalBackgroundTaskCompletion);
}
adapt(raw: any): HeterogeneousAgentEvent[] {
@@ -1328,49 +1299,19 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {
return [this.makeEvent('stream_retry', getApiRetryData(raw, this.profile.agentType))];
}
- // CC's long-running task lifecycle (Monitor, etc., ).
- // `task_started` registers a task that may fire callback turns;
- // `task_notification` (terminal) drops it. While a task is alive,
- // any new turn without preceding user input is treated as a signal
- // callback in `openMainMessage`.
+ // CC's long-running task lifecycle (Monitor, etc.) — see ClaudeCodeTaskSignals.
if (raw.subtype === 'task_started' && raw.task_id && raw.tool_use_id) {
const toolUseId: string = raw.tool_use_id;
- const toolInput = this.mainToolInputsById.get(toolUseId);
- const shouldSignalCompletion =
- this.options.signalBackgroundTaskCompletion && toolInput?.run_in_background === true;
- this.activeTasks.set(raw.task_id, {
- callbackCount: 0,
- shouldSignalCompletion,
- sourceToolName: this.mainToolNamesById.get(toolUseId) ?? 'unknown',
+ this.taskSignals.start(
+ raw.task_id,
toolUseId,
- });
+ this.mainToolNamesById.get(toolUseId) ?? 'unknown',
+ this.mainToolInputsById.get(toolUseId),
+ );
return [];
}
if (raw.subtype === 'task_notification' && raw.task_id) {
- // Capture lineage BEFORE deleting so the next natural turn (the
- // post-task summary, after CC re-invokes the LLM with a synthesized
- // task-ended notification) can be tagged with `task-completion`.
- // Last-task-wins if multiple tasks end before a summary fires — in
- // practice CC summarizes once per LLM call.
- //
- // Gate on `callbackCount > 0`: only a task that actually fired out-of-band
- // callback turns while alive is a genuine long-running task whose ending
- // produces a post-task summary (the summary "keeps it inside the same
- // AssistantGroup as the preceding callbacks" — so there must BE preceding
- // callbacks). A task that fires `task_started` and `task_notification`
- // back-to-back with no intervening callback turn was an inline synchronous
- // tool that CC merely tracked as a task (e.g. a slow `git commit` running a
- // lint-staged hook); its `tool_result` is consumed by the next turn in the
- // normal main chain. Tagging that turn `task-completion` mis-anchors it and
- // drops it from the rendered chain — so leave it untagged.
- const ending = this.activeTasks.get(raw.task_id);
- if (ending && (ending.callbackCount > 0 || ending.shouldSignalCompletion)) {
- this.pendingTaskCompletion = {
- sourceToolCallId: ending.toolUseId,
- sourceToolName: ending.sourceToolName,
- };
- }
- this.activeTasks.delete(raw.task_id);
+ this.taskSignals.end(raw.task_id);
return [];
}
// `task_updated` is a status patch (status: 'completed' fires
@@ -1907,6 +1848,7 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {
// signal pipeline.
if (!subagentCtx) {
this.hasUnhandledUserInput = true;
+ this.taskSignals.noteToolResult(toolCallId);
}
// `Read` on images yields `{type: 'image', source: {...}}` blocks. We
@@ -2198,11 +2140,11 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {
this.streamedThinkingByMessageId.clear();
// Drop any unconsumed task-completion lineage so the next LLM run doesn't
// inherit it; the next turn follows no tool_result of this one either.
- this.pendingTaskCompletion = undefined;
+ this.taskSignals.clearPendingCompletion();
this.hasUnhandledUserInput = false;
const shouldEmitVisibleOutputEnd =
- this.options.runtimeEndStrategy === 'on-result' || this.activeTasks.size === 0;
+ this.options.runtimeEndStrategy === 'on-result' || !this.taskSignals.hasActiveTasks;
return [
...events,
@@ -2335,7 +2277,7 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {
// turn opened while a task is active) would see a stale `true` and skip
// its external-signal tag.
this.hasUnhandledUserInput = false;
- this.pendingExternalSignal = undefined;
+ this.pendingExternalSignal = this.taskSignals.openTurn(true);
// Reusing the tool turn's message.id as the newStep id would make the
// reducer treat this as a REPLAY and drop it (it ignores a `newStep` whose
// id === currentMainMessageId). For any tool turn opened by a prior
@@ -2378,42 +2320,11 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {
this.currentMessageId = messageId;
this.currentTurnHadToolUse = false;
this.stepIndex++;
- // Signal-callback detection (): if this turn opened
- // WITHOUT a preceding `user` event AND a long-running task is
- // still active, the LLM was re-invoked by the task pushing an
- // update — tag the resulting assistant turn accordingly. Otherwise
- // it's a natural continuation (tool_result follow-up or
- // user-initiated turn).
- if (!this.hasUnhandledUserInput && this.activeTasks.size > 0) {
- // Pick the most recently registered active task. Multi-task
- // concurrency isn't expected in real Monitor flows but the Map
- // preserves insertion order so this still gives deterministic
- // behavior if it ever happens.
- const lastTaskKey = [...this.activeTasks.keys()].at(-1)!;
- const task = this.activeTasks.get(lastTaskKey)!;
- task.callbackCount += 1;
- this.pendingExternalSignal = {
- sequence: task.callbackCount,
- sourceToolCallId: task.toolUseId,
- sourceToolName: task.sourceToolName,
- type: 'tool-stdout',
- };
- } else if (this.pendingTaskCompletion && !this.hasUnhandledUserInput) {
- // Natural turn that follows a `task_notification` — this is the
- // post-task summary. Tag it with the source-tool lineage so the
- // collector keeps it inside the same AssistantGroup as the
- // preceding callbacks (rendered after the SignalCallbacks block).
- this.pendingExternalSignal = {
- sourceToolCallId: this.pendingTaskCompletion.sourceToolCallId,
- sourceToolName: this.pendingTaskCompletion.sourceToolName,
- type: 'task-completion',
- };
- this.pendingTaskCompletion = undefined;
- } else {
- // Natural turn boundary — clear any stale signal so the new
- // assistant joins the main chain.
- this.pendingExternalSignal = undefined;
- }
+ // Signal-callback detection: a turn opened WITHOUT a preceding `user` event
+ // was re-invoked by a long-running task — tag it with that task's lineage.
+ // Otherwise it's a natural continuation (tool_result follow-up or
+ // user-initiated turn) and joins the main chain.
+ this.pendingExternalSignal = this.taskSignals.openTurn(this.hasUnhandledUserInput);
this.hasUnhandledUserInput = false;
return [
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCodeTaskSignals.ts b/packages/heterogeneous-agents/src/adapters/claudeCodeTaskSignals.ts
new file mode 100644
index 00000000000..9e306ee4ec2
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/claudeCodeTaskSignals.ts
@@ -0,0 +1,151 @@
+import type { ExternalSignalContext } from '../types';
+
+interface ActiveTask {
+ callbackCount: number;
+ shouldSignalCompletion: boolean;
+ sourceToolName: string;
+ toolUseId: string;
+}
+
+/**
+ * CC's long-running task lifecycle (Monitor, background Bash, ...) and the
+ * external-signal lineage it stamps on turns CC opens WITHOUT fresh user input.
+ *
+ * `task_started` registers a task that may fire callback turns;
+ * `task_notification` (terminal) drops it. While a task is alive, a turn that
+ * opens without a preceding `user` event is a signal callback (CC re-invoked
+ * the LLM because the task pushed an update); the turn after a task ends is
+ * its post-task summary.
+ */
+export class ClaudeCodeTaskSignals {
+ /**
+ * Active CC tasks keyed by `task_id`, carrying the originating
+ * `tool_use_id`, the resolved tool name, and a counter incremented for each
+ * signal callback turn attributed to the task.
+ *
+ * A task lives from `task_started` until `task_notification`.
+ */
+ private activeTasks = new Map<string, ActiveTask>();
+ /**
+ * Source-tool lineage of the most recently completed long-running task,
+ * waiting to be stamped on the post-task summary turn with
+ * `type: 'task-completion'`.
+ *
+ * Armed when `task_notification` ends a background task; consumed by the
+ * NEXT turn that opens, which carries the tag only when it opened without
+ * user input. Cleared on `result` so it never leaks across LLM runs.
+ *
+ * Lets the renderer keep the summary inside the same AssistantGroup as
+ * the preceding callbacks instead of letting it spawn a separate group.
+ */
+ private pendingTaskCompletion: { sourceToolCallId: string; sourceToolName: string } | undefined;
+
+ constructor(private readonly signalBackgroundTaskCompletion: boolean) {}
+
+ get hasActiveTasks(): boolean {
+ return this.activeTasks.size > 0;
+ }
+
+ start(
+ taskId: string,
+ toolUseId: string,
+ sourceToolName: string,
+ toolInput: Record<string, any> | undefined,
+ ): void {
+ this.activeTasks.set(taskId, {
+ callbackCount: 0,
+ shouldSignalCompletion:
+ this.signalBackgroundTaskCompletion && toolInput?.run_in_background === true,
+ sourceToolName,
+ toolUseId,
+ });
+ }
+
+ /**
+ * A main-agent tool_result landed. If its task is still alive, the task
+ * outlived its own call — it runs in the background (`run_in_background`
+ * Bash, an `Agent` launched async, which is CC's default), so its
+ * `task_notification` wakes the LLM for a summary turn. An inline tool CC
+ * merely tracked as a task ends before its result arrives, so it never gets
+ * here.
+ */
+ noteToolResult(toolCallId: string): void {
+ if (!this.signalBackgroundTaskCompletion) return;
+ for (const task of this.activeTasks.values()) {
+ if (task.toolUseId === toolCallId) task.shouldSignalCompletion = true;
+ }
+ }
+
+ end(taskId: string): void {
+ // Capture lineage BEFORE deleting so the next turn (the post-task summary,
+ // after CC re-invokes the LLM with a synthesized task-ended notification)
+ // can be tagged with `task-completion`. Last-task-wins if multiple tasks end
+ // before a summary fires — in practice CC summarizes once per LLM call.
+ //
+ // Gate on `callbackCount > 0`: only a task that actually fired out-of-band
+ // callback turns while alive is a genuine long-running task whose ending
+ // produces a post-task summary (the summary "keeps it inside the same
+ // AssistantGroup as the preceding callbacks" — so there must BE preceding
+ // callbacks). A task that fires `task_started` and `task_notification`
+ // back-to-back with no intervening callback turn was an inline synchronous
+ // tool that CC merely tracked as a task (e.g. a slow `git commit` running a
+ // lint-staged hook); its `tool_result` is consumed by the next turn in the
+ // normal main chain. Tagging that turn `task-completion` mis-anchors it and
+ // drops it from the rendered chain — so leave it untagged. A background
+ // task (`shouldSignalCompletion`) wakes the LLM even with no callbacks.
+ const ending = this.activeTasks.get(taskId);
+ if (ending && (ending.callbackCount > 0 || ending.shouldSignalCompletion)) {
+ this.pendingTaskCompletion = {
+ sourceToolCallId: ending.toolUseId,
+ sourceToolName: ending.sourceToolName,
+ };
+ }
+ this.activeTasks.delete(taskId);
+ }
+
+ /**
+ * Lineage for a newly opened turn. `answersInput` is true when the turn
+ * follows a `tool_result` / user message — a natural main-chain turn that
+ * carries no signal. CC hands it any task notification that arrived
+ * meanwhile, so it also consumes the pending completion.
+ */
+ openTurn(answersInput: boolean): ExternalSignalContext | undefined {
+ if (answersInput) {
+ this.pendingTaskCompletion = undefined;
+ return undefined;
+ }
+
+ if (this.pendingTaskCompletion) {
+ // The turn that follows a `task_notification` is that task's post-task
+ // summary, even while other tasks are still alive. Tag it with the
+ // source-tool lineage so the collector keeps it inside the same
+ // AssistantGroup as the preceding callbacks (rendered after the
+ // SignalCallbacks block).
+ const completion = this.pendingTaskCompletion;
+ this.pendingTaskCompletion = undefined;
+ return { ...completion, type: 'task-completion' };
+ }
+
+ if (this.activeTasks.size > 0) {
+ // Pick the most recently registered active task. Multi-task
+ // concurrency isn't expected in real Monitor flows but the Map
+ // preserves insertion order so this still gives deterministic
+ // behavior if it ever happens.
+ const task = [...this.activeTasks.values()].at(-1)!;
+ task.callbackCount += 1;
+ return {
+ sequence: task.callbackCount,
+ sourceToolCallId: task.toolUseId,
+ sourceToolName: task.sourceToolName,
+ type: 'tool-stdout',
+ };
+ }
+
+ return undefined;
+ }
+
+ /** Drop unconsumed task-completion lineage so the next LLM run doesn't inherit it. */
+ clearPendingCompletion(): void {
+ this.pendingTaskCompletion = undefined;
+ }
+}
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 84903ce34fc..40d71c83010 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1871,6 +1871,8 @@ export default {
'signalCallbacks.empty': 'No callback messages',
'signalCallbacks.expand': 'Show details',
'signalCallbacks.title': '{{tool}} · {{count}} callback updates',
+ 'taskCompletion.title': '{{tool}} "{{description}}" finished',
+ 'taskCompletion.titleWithoutDescription': '{{tool}} finished',
'skillViewer.files': 'Files',
'skillViewer.foldFiles': 'Hide files',
'skillViewer.unfoldFiles': 'Show files',
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/TaskCompletionNotice.tsx b/src/features/Conversation/Messages/AssistantGroup/components/TaskCompletionNotice.tsx
new file mode 100644
index 00000000000..5be6273130d
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/components/TaskCompletionNotice.tsx
@@ -0,0 +1,41 @@
+import { Block, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Bell } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { getToolDisplayName } from '../toolDisplayNames';
+import type { TaskCompletionSource } from '../utils/taskCompletionSource';
+
+/**
+ * Marks where a long-running tool's completion woke the agent again, the way
+ * Claude Code's own `Agent "…" finished` notification separates the turns, so
+ * the reply that follows reads as a response to that event rather than as a
+ * continuation of the text above it.
+ */
+const TaskCompletionNotice = ({ description, toolName }: TaskCompletionSource) => {
+ const { t } = useTranslation('chat');
+ const tool = getToolDisplayName(toolName);
+
+ return (
+ <Flexbox horizontal align="center" gap={8} paddingBlock={4} paddingInline={4}>
+ <Block
+ horizontal
+ align="center"
+ flex="none"
+ height={24}
+ justify="center"
+ style={{ fontSize: 12 }}
+ variant="outlined"
+ width={24}
+ >
+ <Icon color={cssVar.colorTextSecondary} icon={Bell} />
+ </Block>
+ <Text ellipsis as="span" type="secondary">
+ {description
+ ? t('taskCompletion.title', { description, tool })
+ : t('taskCompletion.titleWithoutDescription', { tool })}
+ </Text>
+ </Flexbox>
+ );
+};
+
+export default TaskCompletionNotice;
diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsx
index 752ccb6f4e2..ac71e7cfc75 100644
--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx
@@ -4,7 +4,7 @@ import type { AssistantContentBlock, EmojiReaction, UISignalCallbacksBlock } fro
import { Flexbox, Tag } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import type { MouseEventHandler, ReactNode } from 'react';
-import { memo, Suspense, useCallback, useMemo } from 'react';
+import { Fragment, memo, Suspense, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES } from '@/const/messageActionPortal';
@@ -49,8 +49,10 @@ import SignalCallbacks from '../SignalCallbacks';
import FileListViewer from '../User/components/FileListViewer';
import Group from './components/Group';
import { resolveWorkflowExpandLevel } from './components/segments';
+import TaskCompletionNotice from './components/TaskCompletionNotice';
import type { WorkflowExpandLevelDefault } from './components/WorkflowCollapse';
import { buildContinuationChains, collectSignalCallbacks } from './utils/continuations';
+import { resolveTaskCompletionSource } from './utils/taskCompletionSource';
const EditState = dynamic(() => import('./components/EditState'), {
ssr: false,
@@ -145,6 +147,22 @@ const GroupMessage = memo<GroupMessageProps>(
() => [...(children ?? []), ...chains.flatMap((chain) => chain.blocks)],
[chains, children],
);
+ // One Group per wake-up turn, each preceded by a notice naming the tool
+ // whose completion woke it. The block arrays depend on the completions
+ // only, so the main chain streaming does not re-render those Groups.
+ const completionBlocks = useMemo(
+ () =>
+ ((taskCompletions as AssistantContentBlock[] | undefined) ?? []).map((block) => [block]),
+ [taskCompletions],
+ );
+ const completionItems = useMemo(
+ () =>
+ completionBlocks.map((blocks: AssistantContentBlock[]) => ({
+ blocks,
+ source: resolveTaskCompletionSource(blocks[0]!, allChildren),
+ })),
+ [allChildren, completionBlocks],
+ );
// Supervisor messages render the GROUP's identity (avatar + name + 主管 badge)
// rather than the supervisor agent's own bare meta (whose title is literally
@@ -407,16 +425,19 @@ const GroupMessage = memo<GroupMessageProps>(
{allSignalCallbacks.map((block) => (
<SignalCallbacks block={block} key={block.sourceToolMessageId} />
))}
- {taskCompletions && taskCompletions.length > 0 && (
- <Group
- blocks={taskCompletions}
- contentId={taskCompletions.at(-1)?.id}
- defaultWorkflowExpandLevel={workflowExpandLevel}
- disableEditing={disableEditing}
- id={id}
- messageIndex={index}
- />
- )}
+ {completionItems.map(({ blocks, source }) => (
+ <Fragment key={blocks[0]!.id}>
+ {source && <TaskCompletionNotice {...source} />}
+ <Group
+ blocks={blocks}
+ contentId={blocks[0]!.id}
+ defaultWorkflowExpandLevel={workflowExpandLevel}
+ disableEditing={disableEditing}
+ id={id}
+ messageIndex={index}
+ />
+ </Fragment>
+ ))}
</Flexbox>
{aggregatedFileList.length > 0 && (
diff --git a/src/features/Conversation/Messages/AssistantGroup/utils/taskCompletionSource.test.ts b/src/features/Conversation/Messages/AssistantGroup/utils/taskCompletionSource.test.ts
new file mode 100644
index 00000000000..fa7ae9d80ea
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/utils/taskCompletionSource.test.ts
@@ -0,0 +1,69 @@
+import type { AssistantContentBlock } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { resolveTaskCompletionSource } from './taskCompletionSource';
+
+const replyBlocks = [
+ {
+ content: '',
+ id: 'a1',
+ tools: [
+ {
+ apiName: 'Agent',
+ arguments: JSON.stringify({ description: ' Server research ', prompt: 'go' }),
+ id: 'call-srv',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ {
+ apiName: 'Bash',
+ arguments: '{"command":"sleep 1","run_in_background":true}',
+ id: 'call-bash',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ],
+ },
+] as AssistantContentBlock[];
+
+const wakeUp = (sourceToolCallId: string, type = 'task-completion') =>
+ ({
+ content: 'done',
+ id: 'w1',
+ metadata: { signal: { sourceToolCallId, sourceToolName: 'Agent', type } },
+ }) as AssistantContentBlock;
+
+describe('resolveTaskCompletionSource', () => {
+ it('names the finished tool and its description from the reply’s own call', () => {
+ expect(resolveTaskCompletionSource(wakeUp('call-srv'), replyBlocks)).toEqual({
+ description: 'Server research',
+ toolName: 'Agent',
+ });
+ });
+
+ it('omits the description when the source call has none', () => {
+ expect(resolveTaskCompletionSource(wakeUp('call-bash'), replyBlocks)).toEqual({
+ description: undefined,
+ toolName: 'Bash',
+ });
+ });
+
+ it('falls back to the signal’s tool name when the call is not in the reply', () => {
+ expect(resolveTaskCompletionSource(wakeUp('call-elsewhere'), replyBlocks)).toEqual({
+ description: undefined,
+ toolName: 'Agent',
+ });
+ });
+
+ it('ignores blocks that are not task-completion turns', () => {
+ expect(
+ resolveTaskCompletionSource(wakeUp('call-srv', 'tool-stdout'), replyBlocks),
+ ).toBeUndefined();
+ expect(
+ resolveTaskCompletionSource(
+ { content: 'x', id: 'plain' } as AssistantContentBlock,
+ replyBlocks,
+ ),
+ ).toBeUndefined();
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/utils/taskCompletionSource.ts b/src/features/Conversation/Messages/AssistantGroup/utils/taskCompletionSource.ts
new file mode 100644
index 00000000000..f38605f5c2c
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/utils/taskCompletionSource.ts
@@ -0,0 +1,40 @@
+import type { AssistantContentBlock, MessageSignal } from '@lobechat/types';
+
+export interface TaskCompletionSource {
+ /** The source call's `description` argument, e.g. a subagent's task title. */
+ description?: string;
+ /** API name of the tool whose completion woke the turn, e.g. `Agent`. */
+ toolName: string;
+}
+
+const readDescription = (args?: string): string | undefined => {
+ if (!args) return;
+ try {
+ const description = JSON.parse(args)?.description;
+ return typeof description === 'string' && description.trim() ? description.trim() : undefined;
+ } catch {
+ return;
+ }
+};
+
+/**
+ * The long-running tool (a background subagent, Bash, Monitor…) whose
+ * completion woke a task-completion turn, looked up among the reply's own
+ * tool calls so the notice can name it. Undefined for any other block.
+ */
+export const resolveTaskCompletionSource = (
+ block: AssistantContentBlock,
+ replyBlocks: AssistantContentBlock[],
+): TaskCompletionSource | undefined => {
+ const signal = block.metadata?.signal as MessageSignal | undefined;
+ if (signal?.type !== 'task-completion') return;
+
+ const sourceCall = replyBlocks
+ .flatMap((replyBlock) => replyBlock.tools ?? [])
+ .find((tool) => tool.id === signal.sourceToolCallId);
+
+ return {
+ description: readDescription(sourceCall?.arguments),
+ toolName: sourceCall?.apiName ?? signal.sourceToolName,
+ };
+};