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(hetero-agent): support Monitor-style signal callbacks in AssistantGroup (#14859)

Arvin Xufbc42b725e97
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/Monitor.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/Monitor.tsx
new file mode 100644
index 00000000000..526cc12c5ae
--- /dev/null
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/Monitor.tsx
@@ -0,0 +1,135 @@
+'use client';
+
+import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Check, Monitor as MonitorIcon, X } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { ClaudeCodeApiName, type MonitorArgs } from '../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ chip: css`
+ overflow: hidden;
+ display: inline-flex;
+ flex-shrink: 1;
+ gap: 6px;
+ align-items: center;
+
+ min-width: 0;
+ margin-inline-start: 6px;
+ padding-block: 2px;
+ padding-inline: 10px;
+ border-radius: 999px;
+
+ background: ${cssVar.colorFillTertiary};
+ `,
+ command: css`
+ overflow: hidden;
+
+ min-width: 0;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ description: css`
+ overflow: hidden;
+
+ min-width: 0;
+
+ font-size: 12px;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ monitorIcon: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextDescription};
+ `,
+ statusIcon: css`
+ margin-inline-start: 4px;
+ `,
+ timeout: css`
+ flex-shrink: 0;
+ margin-inline-start: 8px;
+ font-feature-settings: 'tnum';
+ color: ${cssVar.colorTextDescription};
+ `,
+}));
+
+const formatTimeout = (ms: number | undefined): string | undefined => {
+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0) return undefined;
+ const seconds = Math.round(ms / 1000);
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ const remSeconds = seconds % 60;
+ if (minutes < 60) {
+ return remSeconds > 0 ? `${minutes}m ${remSeconds}s` : `${minutes}m`;
+ }
+ const hours = Math.floor(minutes / 60);
+ const remMinutes = minutes % 60;
+ return remMinutes > 0 ? `${hours}h ${remMinutes}m` : `${hours}h`;
+};
+
+/**
+ * Dedicated inspector for CC's long-running `Monitor` tool (LOBE-8998).
+ *
+ * Visual contract:
+ * [Monitor] <MonitorIcon> <description-or-command> ยท <timeout> [โœ“/โœ—]
+ *
+ * Uses the lucide `Monitor` (screen) icon so the chip iconography matches
+ * the tool name. Falls back to `command` when the model omits
+ * `description`; renders a code-styled chip in that case to make the
+ * shell snippet recognizable.
+ */
+export const MonitorInspector = memo<BuiltinInspectorProps<MonitorArgs>>(
+ ({ args, partialArgs, isArgumentsStreaming, pluginState, isLoading }) => {
+ const { t } = useTranslation('plugin');
+ const label = t(ClaudeCodeApiName.Monitor as any);
+
+ const source = args ?? partialArgs;
+ const description = source?.description?.trim();
+ const command = source?.command?.trim();
+ const timeoutLabel = formatTimeout(source?.timeout_ms);
+
+ const isShiny = isArgumentsStreaming || isLoading;
+
+ // Nothing useful to show yet โ€” keep the spinner-y label only.
+ if (isArgumentsStreaming && !description && !command) {
+ return <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>{label}</div>;
+ }
+
+ // Prefer description; fall back to command (rendered monospace).
+ const showAsCommand = !description && !!command;
+ const chipText = description || command;
+
+ const success = (pluginState as { success?: boolean } | undefined)?.success;
+ const exitCode = (pluginState as { exitCode?: number } | undefined)?.exitCode;
+ const isSuccess = success === true || exitCode === 0;
+ const isError = success === false || (typeof exitCode === 'number' && exitCode !== 0);
+
+ return (
+ <div className={cx(inspectorTextStyles.root, isShiny && shinyTextStyles.shinyText)}>
+ <span>{label}:</span>
+ {chipText && (
+ <span className={styles.chip}>
+ <MonitorIcon className={styles.monitorIcon} size={12} />
+ <span className={showAsCommand ? styles.command : styles.description}>{chipText}</span>
+ </span>
+ )}
+ {timeoutLabel && <span className={styles.timeout}>ยท {timeoutLabel}</span>}
+ {isLoading ? null : isSuccess ? (
+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ ) : isError ? (
+ <X className={styles.statusIcon} color={cssVar.colorError} size={14} />
+ ) : null}
+ </div>
+ );
+ },
+);
+
+MonitorInspector.displayName = 'ClaudeCodeMonitorInspector';
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 74280b13e65..5f3a087ac69 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/index.ts
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/index.ts
@@ -11,6 +11,7 @@ import { AgentInspector } from './Agent';
import { AskUserQuestionInspector } from './AskUserQuestion';
import { EditInspector } from './Edit';
import { LinearMcpInspectors } from './LinearMcp';
+import { MonitorInspector } from './Monitor';
import { ReadInspector } from './Read';
import { ScheduleWakeupInspector } from './ScheduleWakeup';
import { SkillInspector } from './Skill';
@@ -40,6 +41,10 @@ export const ClaudeCodeInspectors = {
noResultsKey: 'No results',
translationKey: ClaudeCodeApiName.Grep,
}),
+ // Monitor is a long-running tracked tool โ€” its turns drive a SignalCallbacks
+ // accordion below the AssistantGroup (LOBE-8998). The dedicated inspector
+ // uses the lucide `Monitor` (screen) icon to match the tool name.
+ [ClaudeCodeApiName.Monitor]: MonitorInspector,
[ClaudeCodeApiName.Read]: ReadInspector,
[ClaudeCodeApiName.ScheduleWakeup]: ScheduleWakeupInspector,
[ClaudeCodeApiName.Skill]: SkillInspector,
diff --git a/packages/builtin-tool-claude-code/src/types.ts b/packages/builtin-tool-claude-code/src/types.ts
index 8025637e012..f9295b2dd5d 100644
--- a/packages/builtin-tool-claude-code/src/types.ts
+++ b/packages/builtin-tool-claude-code/src/types.ts
@@ -34,6 +34,15 @@ export enum ClaudeCodeApiName {
Edit = 'Edit',
Glob = 'Glob',
Grep = 'Grep',
+ /**
+ * Long-running command monitor (CC 2.1+). Spawns `command` as a tracked
+ * background task; CC re-invokes the LLM each time the task pushes new
+ * stdout (`system task_started` registers the task, `task_notification`
+ * terminates it โ€” see LOBE-8998 in the adapter). Rendered by a dedicated
+ * `MonitorInspector` so the chip iconography matches the SignalCallbacks
+ * accordion underneath.
+ */
+ Monitor = 'Monitor',
Read = 'Read',
ScheduleWakeup = 'ScheduleWakeup',
Skill = 'Skill',
@@ -74,6 +83,27 @@ export interface SkillArgs {
skill?: string;
}
+/**
+ * Arguments for CC's built-in `Monitor` tool โ€” long-running command monitor.
+ * CC spawns `command` as a tracked background task; `system task_started`
+ * registers it and `system task_notification` ends it (see LOBE-8998 in the
+ * CC adapter). Each stdout push between those two lifecycle events fires a
+ * new LLM turn that's surfaced as a SignalCallbacks entry in the UI.
+ *
+ * - `description` โ€” one-line summary for the inspector chip (model-written).
+ * - `command` โ€” shell snippet to run; falls back to the chip label when
+ * `description` is empty.
+ * - `timeout_ms` โ€” wall-clock cap on the monitor; advisory in the UI.
+ * - `persistent` โ€” `true` keeps the task alive across the next LLM
+ * re-invocation; `false` (default) means single-run.
+ */
+export interface MonitorArgs {
+ command?: string;
+ description?: string;
+ persistent?: boolean;
+ timeout_ms?: number;
+}
+
/**
* Arguments for CC's built-in `ToolSearch` tool. CC invokes this to load
* schemas for deferred tools before calling them. `query` is either
diff --git a/packages/conversation-flow/src/index.ts b/packages/conversation-flow/src/index.ts
index f2cedba09a2..06926457884 100644
--- a/packages/conversation-flow/src/index.ts
+++ b/packages/conversation-flow/src/index.ts
@@ -8,6 +8,7 @@ export type {
CompareNode,
ContextNode,
MessageNode,
+ SignalCallbacksNode,
} from './types';
// Flat Message List Types - for virtual list rendering
diff --git a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts b/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
index e5b8c88eb64..55cc1f71783 100644
--- a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
+++ b/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
@@ -231,6 +231,24 @@ export class ContextTreeBuilder {
// Recursively collect all assistant messages in this group
this.messageCollector.collectAssistantGroupMessages(message, idNode, children);
+ // Append external-signal callback blocks (LOBE-8998) at the END of
+ // children โ€” one block per source tool that fired callbacks. They
+ // ride INSIDE the AssistantGroup but BELOW the main-chain zigzag,
+ // since the toolless reactive replies aren't part of the
+ // assistant โ†’ tool โ†’ assistant chain MessageCollector walks.
+ const signalCallbacks = this.messageCollector.collectSignalCallbacks(message, idNode);
+ children.push(...signalCallbacks);
+
+ // After the callbacks block, append the post-task-summary turns
+ // (LOBE-8998) โ€” toolless assistants tagged with
+ // `signal.type === 'task-completion'`, fired by the LLM after CC's
+ // `task_notification` ended a long-running tool. They're peers of
+ // the callbacks under the same tool_result; collecting them here
+ // keeps the natural narrative inside ONE AssistantGroup:
+ // initial reply โ†’ SignalCallbacks (collapsible) โ†’ summary.
+ const taskCompletions = this.messageCollector.collectTaskCompletions(message, idNode);
+ children.push(...taskCompletions);
+
return {
children,
id: message.id,
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 8798a248202..b9782317a9a 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -223,17 +223,44 @@ export class FlatListBuilder {
processedIds,
);
+ // Gather external-signal callback blocks (LOBE-8998) for any
+ // tool in the chain that fired toolless reactive replies
+ // (Monitor stdout pushes, etc.). Snapshot now so the UI doesn't
+ // need to query messageMap; mark callback messages as processed
+ // so they don't render as separate top-level bubbles.
+ const signalBlocks = this.messageCollector.collectFlatSignalCallbacks(
+ allToolMessages,
+ allMessages,
+ );
+
+ // Post-task-summary turns (LOBE-8998) โ€” toolless siblings of
+ // the callbacks under the same tool_result, tagged with
+ // `signal.type === 'task-completion'`. Belong inside the same
+ // AssistantGroup, rendered AFTER the SignalCallbacks accordion.
+ const taskCompletionMessages = this.messageCollector.collectFlatTaskCompletions(
+ allToolMessages,
+ allMessages,
+ );
+
// Create assistantGroup virtual message
const groupMessage = this.createAssistantGroupMessage(
assistantChain[0],
assistantChain,
allToolMessages,
+ signalBlocks,
+ taskCompletionMessages,
);
flatList.push(groupMessage);
// Mark all as processed
assistantChain.forEach((m) => processedIds.add(m.id));
allToolMessages.forEach((m) => processedIds.add(m.id));
+ for (const block of signalBlocks) {
+ for (const cb of block.callbacks) processedIds.add(cb.id);
+ }
+ for (const completion of taskCompletionMessages) {
+ processedIds.add(completion.id);
+ }
// Continue after the assistant chain
// Priority 1: If last assistant has non-tool children, continue from it
@@ -748,6 +775,13 @@ export class FlatListBuilder {
firstAssistant: Message,
assistantChain: Message[],
allToolMessages: Message[],
+ signalCallbackBlocks?: {
+ callbacks: Message[];
+ sourceToolCallId: string;
+ sourceToolMessageId: string;
+ sourceToolName: string;
+ }[],
+ taskCompletionMessages?: Message[],
): Message {
const children: AssistantContentBlock[] = [];
@@ -907,6 +941,47 @@ export class FlatListBuilder {
result.metadata = { ...result.metadata, isSupervisor: true };
}
+ // Snapshot signal-callback blocks onto the virtual group message
+ // (LOBE-8998) so AssistantGroupMessage can render `<SignalCallbacks>`
+ // without re-querying the store. Each callback Message becomes a
+ // compact UISignalCallback with content + model/provider/sequence.
+ if (signalCallbackBlocks && signalCallbackBlocks.length > 0) {
+ result.signalCallbacks = signalCallbackBlocks.map((block) => ({
+ callbacks: block.callbacks.map((m) => ({
+ content: m.content ?? '',
+ id: m.id,
+ model: m.model ?? undefined,
+ provider: m.provider ?? undefined,
+ sequence: (m.metadata as { signal?: { sequence?: number } } | null | undefined)?.signal
+ ?.sequence,
+ })),
+ sourceToolCallId: block.sourceToolCallId,
+ sourceToolMessageId: block.sourceToolMessageId,
+ sourceToolName: block.sourceToolName,
+ }));
+ }
+
+ // Snapshot post-task-summary turns as content blocks (LOBE-8998).
+ // 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;
+ });
+ }
+
return result;
}
diff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.ts
index e4e9c39fdb5..0ef09df9ee5 100644
--- a/packages/conversation-flow/src/transformation/MessageCollector.ts
+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts
@@ -1,4 +1,46 @@
-import type { ContextNode, IdNode, Message, MessageNode } from '../types';
+import type { ContextNode, IdNode, Message, MessageNode, SignalCallbacksNode } from '../types';
+
+/**
+ * Persisted external-signal lineage on `message.metadata.signal` โ€”
+ * mirrors `MessageSignal` in `@lobechat/types/message/common/metadata.ts`.
+ * Locally duplicated to avoid a cross-package import for a single
+ * structural type.
+ *
+ * Phase 2 (LOBE-8999) promotes this to a dedicated `messages.signal`
+ * jsonb column. To migrate, swap the `metadata?.signal` lookup in
+ * `getMessageSignal` below for `(msg as any).signal ?? msg.metadata?.signal`
+ * โ€” UI and node shape are unchanged.
+ */
+interface MessageSignal {
+ sequence?: number;
+ sourceToolCallId: string;
+ sourceToolName: string;
+ type: 'tool-stdout' | 'tool-callback' | 'task-completion';
+}
+
+/**
+ * Read the external-signal lineage from a message. Returns undefined
+ * when the message has tools (LLM was on the main chain, not reacting
+ * to a signal) โ€” the writer attaches the tag at stream_start before it
+ * knows whether the step will end up using tools, so the collector
+ * must defang that mismatch here.
+ *
+ * Phase 2 compat seam (LOBE-8999): when the `messages.signal` column
+ * lands, prefer it over `metadata.signal`.
+ */
+const getMessageSignal = (msg: Message): MessageSignal | undefined => {
+ if (msg.role !== 'assistant') return undefined;
+ if (msg.tools && msg.tools.length > 0) return undefined;
+ return (msg.metadata as { signal?: MessageSignal } | undefined | null)?.signal;
+};
+
+/** `tool-stdout` / `tool-callback` โ€” reactive callback turns rendered inside the SignalCallbacks accordion. */
+const isCallbackSignal = (sig: MessageSignal | undefined): boolean =>
+ sig?.type === 'tool-stdout' || sig?.type === 'tool-callback';
+
+/** `task-completion` โ€” post-task summary, rendered as a plain message AFTER the SignalCallbacks block. */
+const isTaskCompletionSignal = (sig: MessageSignal | undefined): boolean =>
+ sig?.type === 'task-completion';
/**
* MessageCollector - Handles collection of related messages
@@ -76,6 +118,10 @@ export class MessageCollector {
// Only continue if the next assistant has the SAME agentId
// Different agentId means it's a different agent responding (e.g., via speak tool)
const isSameAgent = nextMsg.agentId === groupAgentId;
+ // Skip signal-tagged toolless callbacks (LOBE-8998) โ€” they're a
+ // side-channel under the same parent tool and get collected
+ // separately by `collectFlatSignalCallbacks`.
+ if (getMessageSignal(nextMsg)) continue;
if (
nextMsg.role === 'assistant' &&
@@ -102,6 +148,84 @@ export class MessageCollector {
}
}
+ /**
+ * Flat-list variant of {@link collectSignalCallbacks} โ€” finds signal
+ * callback blocks (Monitor stdout pushes, etc.) for an assistant
+ * chain that's already been collected from the flat messages array.
+ *
+ * Returns one entry per source tool that fired callbacks, in source
+ * tool encounter order. Each entry's `callbacks` are ordered by
+ * `metadata.signal.sequence`.
+ *
+ * Caller is responsible for marking returned messages as processed.
+ */
+ collectFlatSignalCallbacks(
+ allToolMessages: Message[],
+ allMessages: Message[],
+ ): {
+ callbacks: Message[];
+ sourceToolCallId: string;
+ sourceToolMessageId: string;
+ sourceToolName: string;
+ }[] {
+ const blocks: {
+ callbacks: Message[];
+ sourceToolCallId: string;
+ sourceToolMessageId: string;
+ sourceToolName: string;
+ }[] = [];
+
+ for (const toolMsg of allToolMessages) {
+ const children = allMessages.filter((m) => m.parentId === toolMsg.id);
+ const callbacks: Message[] = [];
+ for (const child of children) {
+ if (!isCallbackSignal(getMessageSignal(child))) continue;
+ callbacks.push(child);
+ }
+ if (callbacks.length === 0) continue;
+ // (task-completion siblings are emitted separately by
+ // `collectFlatTaskCompletions` so they land in the parent
+ // AssistantGroup after the callbacks accordion.)
+
+ callbacks.sort((a, b) => {
+ const sa = getMessageSignal(a)?.sequence ?? Number.POSITIVE_INFINITY;
+ const sb = getMessageSignal(b)?.sequence ?? Number.POSITIVE_INFINITY;
+ return sa - sb;
+ });
+ const first = getMessageSignal(callbacks[0])!;
+ blocks.push({
+ callbacks,
+ sourceToolCallId: first.sourceToolCallId,
+ sourceToolMessageId: toolMsg.id,
+ sourceToolName: first.sourceToolName,
+ });
+ }
+ return blocks;
+ }
+
+ /**
+ * Flat-list variant โ€” find post-task-summary assistants (LOBE-8998),
+ * i.e. toolless assistants tagged with
+ * `metadata.signal.type === 'task-completion'`, fired by the LLM after
+ * CC delivers `task_notification` for a long-running tool.
+ *
+ * Returns them in createdAt order; the caller is responsible for
+ * marking returned messages as processed so they don't render as
+ * separate top-level groups.
+ */
+ collectFlatTaskCompletions(allToolMessages: Message[], allMessages: Message[]): Message[] {
+ const completions: Message[] = [];
+ for (const toolMsg of allToolMessages) {
+ const children = allMessages.filter((m) => m.parentId === toolMsg.id);
+ for (const child of children) {
+ if (!isTaskCompletionSignal(getMessageSignal(child))) continue;
+ completions.push(child);
+ }
+ }
+ completions.sort((a, b) => a.createdAt - b.createdAt);
+ return completions;
+ }
+
/**
* Recursively collect assistant messages for an AssistantGroup (contextTree version)
* Only collects messages from the SAME agent (matching agentId)
@@ -153,19 +277,152 @@ export class MessageCollector {
continue;
}
- // Check if tool has an assistant child
- if (toolNode.children.length > 0) {
- const nextChild = toolNode.children[0];
+ // Find the next main-chain assistant under this tool. Signal-tagged
+ // toolless siblings (Monitor callbacks etc., LOBE-8998) share the
+ // same parent tool but live on a side-channel โ€” skip them here so
+ // the main chain still walks the real follower. The signal blocks
+ // are emitted separately by `collectSignalCallbacks`.
+ for (const nextChild of toolNode.children) {
const nextMsg = this.messageMap.get(nextChild.id);
+ if (nextMsg?.role !== 'assistant') continue;
+ if (nextMsg.agentId !== agentId) continue;
+ if (getMessageSignal(nextMsg)) continue; // skip signal callbacks
+ // Recursively collect this assistant and its descendants (same agent only)
+ this.collectAssistantGroupMessages(nextMsg, nextChild, children, agentId);
+ return; // Only follow one path
+ }
+ }
+ }
- // Only continue if the next assistant has the SAME agentId
- if (nextMsg?.role === 'assistant' && nextMsg.agentId === agentId) {
- // Recursively collect this assistant and its descendants (same agent only)
- this.collectAssistantGroupMessages(nextMsg, nextChild, children, agentId);
- return; // Only follow one path
+ /**
+ * Collect signal-callback blocks for an AssistantGroup โ€” one
+ * SignalCallbacksNode per source tool that fired signals (Monitor
+ * stdout pushes triggering toolless follow-up turns, etc.).
+ *
+ * Walks the same main-chain as `collectAssistantGroupMessages` and,
+ * for each tool encountered, looks at its children for assistants
+ * carrying `metadata.signal`. Multiple source tools in the same
+ * group produce multiple blocks, in source-tool encounter order.
+ *
+ * Blocks are emitted at the END of `AssistantGroupNode.children`
+ * after the main-chain zigzag โ€” see ContextTreeBuilder.
+ */
+ collectSignalCallbacks(message: Message, idNode: IdNode): SignalCallbacksNode[] {
+ const groupAgentId = message.agentId;
+ const blocks: SignalCallbacksNode[] = [];
+ const visited = new Set<string>();
+
+ const walk = (node: IdNode): void => {
+ if (visited.has(node.id)) return;
+ visited.add(node.id);
+
+ for (const child of node.children) {
+ const childMsg = this.messageMap.get(child.id);
+ if (childMsg?.role !== 'tool') continue;
+
+ // Gather callback-typed signal toolless siblings among this
+ // tool's children. `getMessageSignal` already returns undefined
+ // for tool-using assistants and non-assistants; `task-completion`
+ // turns are excluded here so they render outside the accordion
+ // (see `collectTaskCompletions`).
+ const callbacks: Message[] = [];
+ for (const toolChild of child.children) {
+ const toolChildMsg = this.messageMap.get(toolChild.id);
+ if (!toolChildMsg) continue;
+ if (!isCallbackSignal(getMessageSignal(toolChildMsg))) continue;
+ callbacks.push(toolChildMsg);
+ }
+
+ if (callbacks.length > 0) {
+ // Sort by sequence; missing sequence sorts to the end.
+ callbacks.sort((a, b) => {
+ const sa = getMessageSignal(a)?.sequence ?? Number.POSITIVE_INFINITY;
+ const sb = getMessageSignal(b)?.sequence ?? Number.POSITIVE_INFINITY;
+ return sa - sb;
+ });
+ const first = getMessageSignal(callbacks[0])!;
+ blocks.push({
+ callbacks: callbacks.map((m) => ({ id: m.id, type: 'message' as const })),
+ id: `signalCallbacks-${child.id}`,
+ sourceToolCallId: first.sourceToolCallId,
+ sourceToolMessageId: child.id,
+ sourceToolName: first.sourceToolName,
+ type: 'signalCallbacks',
+ });
+ }
+
+ // Continue walking the main chain โ€” recurse into the next
+ // main-chain follower under this tool (skipping signal
+ // callbacks, just like `collectAssistantGroupMessages` does).
+ for (const nextChild of child.children) {
+ const nextMsg = this.messageMap.get(nextChild.id);
+ if (nextMsg?.role !== 'assistant') continue;
+ if (nextMsg.agentId !== groupAgentId) continue;
+ if (getMessageSignal(nextMsg)) continue;
+ walk(nextChild);
+ break;
}
}
- }
+ };
+
+ walk(idNode);
+ return blocks;
+ }
+
+ /**
+ * Collect post-task-summary toolless siblings (LOBE-8998) โ€” assistants
+ * tagged with `metadata.signal.type === 'task-completion'`, fired by
+ * the LLM after CC delivers `system task_notification` for a long-
+ * running tool (Monitor, etc.). Each one belongs inside the same
+ * AssistantGroup as the preceding SignalCallbacks block, rendered as
+ * a plain message AFTER the accordion.
+ *
+ * Walks the same main-chain as `collectAssistantGroupMessages` so the
+ * lookup tracks signal-tagged toolless siblings exactly where they
+ * live in the parentId tree (children of the source tool's
+ * tool_result, alongside the callbacks).
+ *
+ * Returned in creation order. Multiple completions per group are rare
+ * but supported (e.g. two long-running tools both summarized in one
+ * LLM call).
+ */
+ collectTaskCompletions(message: Message, idNode: IdNode): MessageNode[] {
+ const groupAgentId = message.agentId;
+ const nodes: MessageNode[] = [];
+ const visited = new Set<string>();
+
+ const walk = (node: IdNode): void => {
+ if (visited.has(node.id)) return;
+ visited.add(node.id);
+
+ for (const child of node.children) {
+ const childMsg = this.messageMap.get(child.id);
+ if (childMsg?.role !== 'tool') continue;
+
+ for (const toolChild of child.children) {
+ const toolChildMsg = this.messageMap.get(toolChild.id);
+ if (!toolChildMsg) continue;
+ if (toolChildMsg.agentId !== groupAgentId) continue;
+ if (!isTaskCompletionSignal(getMessageSignal(toolChildMsg))) continue;
+ nodes.push({ id: toolChildMsg.id, type: 'message' });
+ }
+
+ // Continue walking the main chain into the next non-signal
+ // follower under this tool (same skip rule as
+ // `collectAssistantGroupMessages`).
+ for (const nextChild of child.children) {
+ const nextMsg = this.messageMap.get(nextChild.id);
+ if (nextMsg?.role !== 'assistant') continue;
+ if (nextMsg.agentId !== groupAgentId) continue;
+ if (getMessageSignal(nextMsg)) continue;
+ walk(nextChild);
+ break;
+ }
+ }
+ };
+
+ walk(idNode);
+ return nodes;
}
/**
@@ -236,15 +493,18 @@ export class MessageCollector {
continue;
}
- if (toolNode.children.length > 0) {
- const nextChild = toolNode.children[0];
+ // Pick the next main-chain assistant under this tool. Mirror the
+ // skip rule used by `collectAssistantGroupMessages`: signal-tagged
+ // toolless siblings (Monitor callbacks etc., LOBE-8998) share the
+ // parent tool but live on a side-channel โ€” if they appear before
+ // the real follower, blindly taking children[0] would end the
+ // walk on a callback node and truncate the AssistantGroup tail.
+ for (const nextChild of toolNode.children) {
const nextMsg = this.messageMap.get(nextChild.id);
-
- // Only continue if the next assistant has the SAME agentId
- if (nextMsg?.role === 'assistant' && nextMsg.agentId === groupAgentId) {
- // Continue following the assistant chain (same agent only)
- return this.findLastNodeInAssistantGroup(nextChild, groupAgentId);
- }
+ if (nextMsg?.role !== 'assistant') continue;
+ if (nextMsg.agentId !== groupAgentId) continue;
+ if (getMessageSignal(nextMsg)) continue;
+ return this.findLastNodeInAssistantGroup(nextChild, groupAgentId);
}
}
diff --git a/packages/conversation-flow/src/transformation/__tests__/ContextTreeBuilder.test.ts b/packages/conversation-flow/src/transformation/__tests__/ContextTreeBuilder.test.ts
index 13ed0fc396a..32a3e5a158f 100644
--- a/packages/conversation-flow/src/transformation/__tests__/ContextTreeBuilder.test.ts
+++ b/packages/conversation-flow/src/transformation/__tests__/ContextTreeBuilder.test.ts
@@ -427,4 +427,133 @@ describe('ContextTreeBuilder', () => {
expect(result[2]).toEqual({ id: 'msg-4', type: 'message' });
});
});
+
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ // LOBE-8998: AssistantGroupNode embeds SignalCallbacksNode children
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ describe('AssistantGroup with signal callbacks (LOBE-8998)', () => {
+ it('appends SignalCallbacksNode at the end of AssistantGroup children', () => {
+ const signalMeta = (sequence: number) => ({
+ signal: {
+ sequence,
+ sourceToolCallId: 'toolu_mon',
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout' as const,
+ },
+ });
+
+ const messageMap = new Map<string, Message>([
+ [
+ 'ast-0',
+ {
+ agentId: 'agent-x',
+ content: '',
+ createdAt: 0,
+ id: 'ast-0',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'Monitor',
+ arguments: '{}',
+ id: 'toolu_mon',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ],
+ updatedAt: 0,
+ },
+ ],
+ [
+ 'tool-1',
+ {
+ content: 'started',
+ createdAt: 0,
+ id: 'tool-1',
+ parentId: 'ast-0',
+ role: 'tool',
+ tool_call_id: 'toolu_mon',
+ updatedAt: 0,
+ },
+ ],
+ [
+ 'cb-1',
+ {
+ agentId: 'agent-x',
+ content: '็ญ‰ list ๅฎŒใ€‚',
+ createdAt: 0,
+ id: 'cb-1',
+ metadata: signalMeta(1) as any,
+ parentId: 'tool-1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ],
+ [
+ 'cb-2',
+ {
+ agentId: 'agent-x',
+ content: '84842 ๅˆ—ๅฎŒ๏ผŒๅผ€ๅนฒใ€‚',
+ createdAt: 0,
+ id: 'cb-2',
+ metadata: signalMeta(2) as any,
+ parentId: 'tool-1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ],
+ [
+ 'ast-4',
+ {
+ agentId: 'agent-x',
+ content: '',
+ createdAt: 0,
+ id: 'ast-4',
+ parentId: 'tool-1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ],
+ ]);
+
+ const builder = createBuilder(messageMap);
+ const idNodes: IdNode[] = [
+ {
+ children: [
+ {
+ children: [
+ { children: [], id: 'cb-1' },
+ { children: [], id: 'cb-2' },
+ { children: [], id: 'ast-4' },
+ ],
+ id: 'tool-1',
+ },
+ ],
+ id: 'ast-0',
+ },
+ ];
+
+ const result = builder.transformAll(idNodes);
+ // One AssistantGroup node at the top
+ expect(result).toHaveLength(1);
+ const group = result[0] as any;
+ expect(group.type).toBe('assistantGroup');
+
+ // Main chain assistants then signalCallbacks block at the end
+ expect(group.children.map((c: any) => c.type)).toEqual([
+ 'message', // ast-0
+ 'message', // ast-4
+ 'signalCallbacks',
+ ]);
+ expect(group.children[0].id).toBe('ast-0');
+ expect(group.children[0].tools).toEqual(['tool-1']);
+ expect(group.children[1].id).toBe('ast-4');
+ expect(group.children[2]).toMatchObject({
+ sourceToolCallId: 'toolu_mon',
+ sourceToolMessageId: 'tool-1',
+ sourceToolName: 'Monitor',
+ type: 'signalCallbacks',
+ });
+ expect(group.children[2].callbacks.map((c: any) => c.id)).toEqual(['cb-1', 'cb-2']);
+ });
+ });
});
diff --git a/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts b/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
index af84ef5fd68..8943f2a9cd9 100644
--- a/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
+++ b/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
@@ -705,4 +705,111 @@ describe('FlatListBuilder', () => {
expect(groupTasksMsg!.updatedAt).toBe(300);
});
});
+
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ // LOBE-8998: signal callbacks attached on virtual AssistantGroup
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ describe('signal callbacks (LOBE-8998)', () => {
+ it('attaches signalCallbacks to the virtual group and processes callback messages', () => {
+ const signalMeta = (sequence: number) =>
+ ({
+ signal: {
+ sequence,
+ sourceToolCallId: 'toolu_mon_0',
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout' as const,
+ },
+ }) as any;
+
+ const messages: Message[] = [
+ // User
+ { content: 'go', createdAt: 0, id: 'u-1', role: 'user', updatedAt: 0 },
+ // Step 0: assistant with Monitor tool
+ {
+ agentId: 'a',
+ content: 'starting',
+ createdAt: 0,
+ id: 'ast-0',
+ parentId: 'u-1',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'Monitor',
+ arguments: '{}',
+ id: 'toolu_mon_0',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ],
+ updatedAt: 0,
+ },
+ // Tool result
+ {
+ content: 'started',
+ createdAt: 0,
+ id: 'tool-1',
+ parentId: 'ast-0',
+ role: 'tool',
+ tool_call_id: 'toolu_mon_0',
+ updatedAt: 0,
+ },
+ // 3 signal callbacks under tool-1
+ {
+ agentId: 'a',
+ content: '็ญ‰ list ๅฎŒใ€‚',
+ createdAt: 0,
+ id: 'cb-1',
+ metadata: signalMeta(1),
+ model: 'claude-opus-4-7',
+ parentId: 'tool-1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ {
+ agentId: 'a',
+ content: '84842 ๅˆ—ๅฎŒ๏ผŒๅผ€ๅนฒใ€‚',
+ createdAt: 0,
+ id: 'cb-2',
+ metadata: signalMeta(2),
+ model: 'claude-opus-4-7',
+ parentId: 'tool-1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ {
+ agentId: 'a',
+ content: '100/84842 ๅ…จ skipโ€ฆ',
+ createdAt: 0,
+ id: 'cb-3',
+ metadata: signalMeta(3),
+ model: 'claude-opus-4-7',
+ parentId: 'tool-1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ];
+
+ const builder = createBuilder(messages);
+ const result = builder.flatten(messages);
+
+ // Expect: user msg + one assistantGroup virtual message. NO standalone
+ // bubbles for cb-1/cb-2/cb-3 โ€” they belong to the group.
+ const ids = result.map((m) => m.id);
+ expect(ids).not.toContain('cb-1');
+ expect(ids).not.toContain('cb-2');
+ expect(ids).not.toContain('cb-3');
+ const group = result.find((m) => m.role === ('assistantGroup' as any));
+ expect(group).toBeDefined();
+ expect(group!.signalCallbacks).toHaveLength(1);
+ const block = group!.signalCallbacks![0];
+ expect(block).toMatchObject({
+ sourceToolCallId: 'toolu_mon_0',
+ sourceToolMessageId: 'tool-1',
+ sourceToolName: 'Monitor',
+ });
+ expect(block.callbacks.map((c) => c.id)).toEqual(['cb-1', 'cb-2', 'cb-3']);
+ expect(block.callbacks.map((c) => c.sequence)).toEqual([1, 2, 3]);
+ expect(block.callbacks[0].content).toBe('็ญ‰ list ๅฎŒใ€‚');
+ });
+ });
});
diff --git a/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts b/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts
index ec52e41ea83..31b63cff2c4 100644
--- a/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts
+++ b/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts
@@ -204,5 +204,409 @@ describe('MessageCollector', () => {
expect(result?.id).toBe('msg-2');
});
+
+ it('skips signal-tagged callbacks when locating the group tail', () => {
+ // LOBE-8998: when [signal callback, next tool-using assistant]
+ // both live under the same tool, the tail finder must follow the
+ // real main-chain assistant โ€” taking children[0] blindly lands on
+ // the callback (which is a leaf) and truncates the AssistantGroup.
+ const messageMap = new Map<string, Message>([
+ [
+ 'ast-0',
+ {
+ agentId: 'agent-x',
+ content: '',
+ createdAt: 0,
+ id: 'ast-0',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ],
+ [
+ 'tool-1',
+ {
+ content: '',
+ createdAt: 0,
+ id: 'tool-1',
+ parentId: 'ast-0',
+ role: 'tool',
+ tool_call_id: 'toolu_mon',
+ updatedAt: 0,
+ },
+ ],
+ [
+ 'cb-1',
+ {
+ agentId: 'agent-x',
+ content: '',
+ createdAt: 0,
+ id: 'cb-1',
+ metadata: {
+ signal: {
+ sequence: 1,
+ sourceToolCallId: 'toolu_mon',
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout',
+ },
+ } as any,
+ parentId: 'tool-1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ],
+ [
+ 'ast-4',
+ {
+ agentId: 'agent-x',
+ content: '',
+ createdAt: 0,
+ id: 'ast-4',
+ parentId: 'tool-1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ],
+ [
+ 'tool-2',
+ {
+ content: '',
+ createdAt: 0,
+ id: 'tool-2',
+ parentId: 'ast-4',
+ role: 'tool',
+ updatedAt: 0,
+ },
+ ],
+ ]);
+ const collector = new MessageCollector(messageMap, new Map());
+
+ const idNode: IdNode = {
+ children: [
+ {
+ children: [
+ { children: [], id: 'cb-1' },
+ {
+ children: [{ children: [], id: 'tool-2' }],
+ id: 'ast-4',
+ },
+ ],
+ id: 'tool-1',
+ },
+ ],
+ id: 'ast-0',
+ };
+
+ const result = collector.findLastNodeInAssistantGroup(idNode, 'agent-x');
+
+ // Tail must be tool-2 (descended through ast-4), NOT cb-1.
+ expect(result?.id).toBe('tool-2');
+ });
+ });
+
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ // LOBE-8998: external signal callback collection
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ describe('collectSignalCallbacks', () => {
+ const mkAssistant = (id: string, opts?: Partial<Message>): Message => ({
+ agentId: 'agent-x',
+ content: '',
+ createdAt: 0,
+ id,
+ role: 'assistant',
+ updatedAt: 0,
+ ...opts,
+ });
+ const mkTool = (id: string, opts?: Partial<Message>): Message => ({
+ content: '',
+ createdAt: 0,
+ id,
+ role: 'tool',
+ updatedAt: 0,
+ ...opts,
+ });
+ const mkSignalCallback = (id: string, sourceToolCallId: string, sequence: number): Message =>
+ mkAssistant(id, {
+ metadata: {
+ signal: {
+ sequence,
+ sourceToolCallId,
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout',
+ },
+ } as any,
+ });
+
+ it('groups toolless signal-tagged children under one block per source tool', () => {
+ const messageMap = new Map<string, Message>([
+ ['ast-0', mkAssistant('ast-0')],
+ [
+ 'tool-1',
+ mkTool('tool-1', {
+ parentId: 'ast-0',
+ tool_call_id: 'toolu_mon_0',
+ }),
+ ],
+ ['cb-1', mkSignalCallback('cb-1', 'toolu_mon_0', 1)],
+ ['cb-2', mkSignalCallback('cb-2', 'toolu_mon_0', 2)],
+ ['cb-3', mkSignalCallback('cb-3', 'toolu_mon_0', 3)],
+ ]);
+ const collector = new MessageCollector(messageMap, new Map());
+
+ const idNode: IdNode = {
+ children: [
+ {
+ children: [
+ { children: [], id: 'cb-1' },
+ { children: [], id: 'cb-2' },
+ { children: [], id: 'cb-3' },
+ ],
+ id: 'tool-1',
+ },
+ ],
+ id: 'ast-0',
+ };
+
+ const blocks = collector.collectSignalCallbacks(messageMap.get('ast-0')!, idNode);
+ expect(blocks).toHaveLength(1);
+ expect(blocks[0]).toMatchObject({
+ sourceToolCallId: 'toolu_mon_0',
+ sourceToolMessageId: 'tool-1',
+ sourceToolName: 'Monitor',
+ type: 'signalCallbacks',
+ });
+ expect(blocks[0].callbacks.map((c) => c.id)).toEqual(['cb-1', 'cb-2', 'cb-3']);
+ });
+
+ it('orders callbacks by sequence even when discovered out-of-order', () => {
+ const messageMap = new Map<string, Message>([
+ ['ast-0', mkAssistant('ast-0')],
+ ['tool-1', mkTool('tool-1', { parentId: 'ast-0', tool_call_id: 'toolu_a' })],
+ ['cb-c', mkSignalCallback('cb-c', 'toolu_a', 3)],
+ ['cb-a', mkSignalCallback('cb-a', 'toolu_a', 1)],
+ ['cb-b', mkSignalCallback('cb-b', 'toolu_a', 2)],
+ ]);
+ const collector = new MessageCollector(messageMap, new Map());
+
+ const idNode: IdNode = {
+ children: [
+ {
+ children: [
+ { children: [], id: 'cb-c' },
+ { children: [], id: 'cb-a' },
+ { children: [], id: 'cb-b' },
+ ],
+ id: 'tool-1',
+ },
+ ],
+ id: 'ast-0',
+ };
+
+ const [block] = collector.collectSignalCallbacks(messageMap.get('ast-0')!, idNode);
+ expect(block.callbacks.map((c) => c.id)).toEqual(['cb-a', 'cb-b', 'cb-c']);
+ });
+
+ it('emits one block per source tool when multiple tools fired callbacks in the same chain', () => {
+ const messageMap = new Map<string, Message>([
+ ['ast-0', mkAssistant('ast-0')],
+ ['tool-1', mkTool('tool-1', { parentId: 'ast-0', tool_call_id: 'toolu_mon_0' })],
+ ['cb-1', mkSignalCallback('cb-1', 'toolu_mon_0', 1)],
+ // Main chain continues: ast-4 follows tool-1 (parentId = tool-1)
+ ['ast-4', mkAssistant('ast-4', { parentId: 'tool-1' })],
+ ['tool-2', mkTool('tool-2', { parentId: 'ast-4', tool_call_id: 'toolu_mon_1' })],
+ ['cb-2a', mkSignalCallback('cb-2a', 'toolu_mon_1', 1)],
+ ['cb-2b', mkSignalCallback('cb-2b', 'toolu_mon_1', 2)],
+ ]);
+ const collector = new MessageCollector(messageMap, new Map());
+
+ const idNode: IdNode = {
+ children: [
+ {
+ children: [
+ { children: [], id: 'cb-1' },
+ {
+ children: [
+ {
+ children: [
+ { children: [], id: 'cb-2a' },
+ { children: [], id: 'cb-2b' },
+ ],
+ id: 'tool-2',
+ },
+ ],
+ id: 'ast-4',
+ },
+ ],
+ id: 'tool-1',
+ },
+ ],
+ id: 'ast-0',
+ };
+
+ const blocks = collector.collectSignalCallbacks(messageMap.get('ast-0')!, idNode);
+ expect(blocks).toHaveLength(2);
+ expect(blocks[0].sourceToolMessageId).toBe('tool-1');
+ expect(blocks[0].callbacks.map((c) => c.id)).toEqual(['cb-1']);
+ expect(blocks[1].sourceToolMessageId).toBe('tool-2');
+ expect(blocks[1].callbacks.map((c) => c.id)).toEqual(['cb-2a', 'cb-2b']);
+ });
+
+ it('returns empty array when no signal-tagged children exist', () => {
+ const messageMap = new Map<string, Message>([
+ ['ast-0', mkAssistant('ast-0')],
+ ['tool-1', mkTool('tool-1', { parentId: 'ast-0', tool_call_id: 'toolu' })],
+ // Plain main-chain follower (no metadata.signal) โ€” must NOT be grouped
+ ['ast-4', mkAssistant('ast-4', { parentId: 'tool-1' })],
+ ]);
+ const collector = new MessageCollector(messageMap, new Map());
+
+ const idNode: IdNode = {
+ children: [
+ {
+ children: [{ children: [], id: 'ast-4' }],
+ id: 'tool-1',
+ },
+ ],
+ id: 'ast-0',
+ };
+
+ const blocks = collector.collectSignalCallbacks(messageMap.get('ast-0')!, idNode);
+ expect(blocks).toEqual([]);
+ });
+
+ it('ignores signal tag on assistants that DID use tools (back on main chain)', () => {
+ // Adapter stamps externalSignal at stream_start (before it knows
+ // the step will emit tool_use). The collector must defang this
+ // mismatch โ€” a tool-using assistant is NOT a signal callback.
+ const messageMap = new Map<string, Message>([
+ ['ast-0', mkAssistant('ast-0')],
+ ['tool-1', mkTool('tool-1', { parentId: 'ast-0', tool_call_id: 'toolu_mon' })],
+ [
+ 'ast-tools',
+ mkAssistant('ast-tools', {
+ metadata: {
+ signal: {
+ sequence: 1,
+ sourceToolCallId: 'toolu_mon',
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout',
+ },
+ } as any,
+ parentId: 'tool-1',
+ tools: [
+ {
+ apiName: 'Bash',
+ arguments: '{}',
+ id: 'toolu_bash',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ],
+ }),
+ ],
+ ]);
+ const collector = new MessageCollector(messageMap, new Map());
+
+ const idNode: IdNode = {
+ children: [
+ {
+ children: [{ children: [], id: 'ast-tools' }],
+ id: 'tool-1',
+ },
+ ],
+ id: 'ast-0',
+ };
+
+ const blocks = collector.collectSignalCallbacks(messageMap.get('ast-0')!, idNode);
+ expect(blocks).toEqual([]);
+ });
+ });
+
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ // LOBE-8998: collectAssistantGroupMessages skips signal-tagged children
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ describe('collectAssistantGroupMessages with signal callbacks', () => {
+ it('skips signal-tagged callbacks when picking the main-chain follower', () => {
+ const messageMap = new Map<string, Message>([
+ [
+ 'ast-0',
+ {
+ agentId: 'agent-x',
+ content: '',
+ createdAt: 0,
+ id: 'ast-0',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ],
+ [
+ 'tool-1',
+ {
+ content: '',
+ createdAt: 0,
+ id: 'tool-1',
+ parentId: 'ast-0',
+ role: 'tool',
+ tool_call_id: 'toolu_mon',
+ updatedAt: 0,
+ },
+ ],
+ // Signal callback โ€” listed FIRST in tool-1's children. Without
+ // the skip logic, the collector would recurse into this and
+ // miss the real follower.
+ [
+ 'cb-1',
+ {
+ agentId: 'agent-x',
+ content: '',
+ createdAt: 0,
+ id: 'cb-1',
+ metadata: {
+ signal: {
+ sequence: 1,
+ sourceToolCallId: 'toolu_mon',
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout',
+ },
+ } as any,
+ parentId: 'tool-1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ],
+ // Real main-chain follower.
+ [
+ 'ast-4',
+ {
+ agentId: 'agent-x',
+ content: '',
+ createdAt: 0,
+ id: 'ast-4',
+ parentId: 'tool-1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ],
+ ]);
+ const collector = new MessageCollector(messageMap, new Map());
+
+ const idNode: IdNode = {
+ children: [
+ {
+ children: [
+ { children: [], id: 'cb-1' },
+ { children: [], id: 'ast-4' },
+ ],
+ id: 'tool-1',
+ },
+ ],
+ id: 'ast-0',
+ };
+
+ const children: any[] = [];
+ collector.collectAssistantGroupMessages(messageMap.get('ast-0')!, idNode, children);
+
+ // Main chain: ast-0 โ†’ ast-4 (cb-1 is skipped, handled separately).
+ expect(children.map((c) => c.id)).toEqual(['ast-0', 'ast-4']);
+ });
});
});
diff --git a/packages/conversation-flow/src/types/contextTree.ts b/packages/conversation-flow/src/types/contextTree.ts
index 356542e473c..a3b58b80a85 100644
--- a/packages/conversation-flow/src/types/contextTree.ts
+++ b/packages/conversation-flow/src/types/contextTree.ts
@@ -20,7 +20,8 @@ interface BaseNode {
| 'agentCouncil'
| 'tasks'
| 'compressedGroup'
- | 'compareGroup';
+ | 'compareGroup'
+ | 'signalCallbacks';
}
/**
@@ -139,6 +140,30 @@ export interface CompareGroupNode extends BaseNode {
type: 'compareGroup';
}
+/**
+ * Signal callbacks node โ€” toolless assistant messages produced as
+ * reactive replies to an external signal (e.g. Monitor stdout pushes
+ * triggering CC follow-up turns). Rendered as an independent block
+ * inside `AssistantGroupNode.children`, NOT folded into the main
+ * `assistant โ†’ tool โ†’ assistant` zigzag.
+ *
+ * Each block belongs to one source tool โ€” the tool whose repeat
+ * `tool_result` (CC `tool_use.id`) fired the signal. Multiple source
+ * tools in the same AssistantGroup produce multiple SignalCallbacks
+ * blocks, one per source.
+ */
+export interface SignalCallbacksNode extends BaseNode {
+ /** Toolless assistant messages, ordered by `metadata.signal.sequence`. */
+ callbacks: MessageNode[];
+ /** Source tool's `tool_call_id` (CC `tool_use.id`). */
+ sourceToolCallId: string;
+ /** Source tool message's db id. */
+ sourceToolMessageId: string;
+ /** Tool name for UI labelling, e.g. `Monitor`. */
+ sourceToolName: string;
+ type: 'signalCallbacks';
+}
+
/**
* Union type of all display nodes
*/
@@ -150,4 +175,5 @@ export type ContextNode =
| AgentCouncilNode
| TasksNode
| CompressedGroupNode
- | CompareGroupNode;
+ | CompareGroupNode
+ | SignalCallbacksNode;
diff --git a/packages/conversation-flow/src/types/index.ts b/packages/conversation-flow/src/types/index.ts
index f509754931b..976ee3c6f64 100644
--- a/packages/conversation-flow/src/types/index.ts
+++ b/packages/conversation-flow/src/types/index.ts
@@ -21,6 +21,7 @@ export type {
ContextNode,
MessageNode,
PinnedMessage,
+ SignalCallbacksNode,
TasksNode,
} from './contextTree';
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
index 1acfa1e589c..c896240b096 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
@@ -1790,4 +1790,256 @@ describe('ClaudeCodeAdapter', () => {
expect(end!.data.subagent).toEqual({ parentToolCallId: 'toolu_task' });
});
});
+
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ // LOBE-8998: external signal detection (Monitor task callbacks)
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ describe('external signal detection (LOBE-8998)', () => {
+ 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',
+ });
+ });
+
+ 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('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'));
+ 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.
+ const next = adapter.adapt(ccMessageStart('msg_03'));
+ expect(
+ next.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
+ ).toBeUndefined();
+ });
+
+ it('does NOT tag turns that follow a user/tool_result event', () => {
+ 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)
+
+ // LLM emits Bash mid-task โ†’ Bash's tool_result arrives โ†’ next turn
+ // is a natural follow-up to Bash, NOT a Monitor callback.
+ adapter.adapt({
+ message: {
+ content: [{ id: 'toolu_bash', input: {}, name: 'Bash', type: 'tool_use' }],
+ id: 'msg_03',
+ },
+ type: 'assistant',
+ });
+ adapter.adapt(ccUser('toolu_bash', 'bash ok'));
+
+ const ev = adapter.adapt(ccMessageStart('msg_04'));
+ expect(
+ ev.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 c0a4e3acdc4..058e2ad921c 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
@@ -37,6 +37,7 @@
import type {
AgentCLIPreset,
AgentEventAdapter,
+ ExternalSignalContext,
HeterogeneousAgentEvent,
HeterogeneousRateLimitInfo,
HeterogeneousTerminalErrorData,
@@ -329,6 +330,66 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
* recreate the Thread on every chunk.
*/
private announcedSpawns = new Set<string>();
+ /**
+ * Tool name keyed by main-agent `tool_use.id`. Used to label the
+ * resulting {@link ExternalSignalContext} when a Monitor-style task
+ * fires a callback turn.
+ *
+ * Populated for every main-agent tool_use; subagent inner tools are
+ * excluded because their tool_results route through `subagent.parentToolCallId`,
+ * 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; sourceToolName: string; toolUseId: string }
+ >();
+ /**
+ * 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
+ * is a natural follow-up to a tool_result, not a signal callback"
+ * intent across the gap between the tool_result event and the
+ * 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
+ * because a long-running tool pushed an update).
+ */
+ private hasUnhandledUserInput = false;
+ /**
+ * {@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).
+ */
+ 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;
adapt(raw: any): HeterogeneousAgentEvent[] {
if (!raw || typeof raw !== 'object') return [];
@@ -370,6 +431,41 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
// โ”€โ”€โ”€ Private handlers โ”€โ”€โ”€
private handleSystem(raw: any): HeterogeneousAgentEvent[] {
+ // CC's long-running task lifecycle (Monitor, etc., LOBE-8998).
+ // `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`.
+ if (raw.subtype === 'task_started' && raw.task_id && raw.tool_use_id) {
+ const toolUseId: string = raw.tool_use_id;
+ this.activeTasks.set(raw.task_id, {
+ callbackCount: 0,
+ sourceToolName: this.mainToolNamesById.get(toolUseId) ?? 'unknown',
+ 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.
+ const ending = this.activeTasks.get(raw.task_id);
+ if (ending) {
+ this.pendingTaskCompletion = {
+ sourceToolCallId: ending.toolUseId,
+ sourceToolName: ending.sourceToolName,
+ };
+ }
+ this.activeTasks.delete(raw.task_id);
+ return [];
+ }
+ // `task_updated` is a status patch (status: 'completed' fires
+ // alongside `task_notification`). Drop it โ€” we drive lifecycle off
+ // task_started / task_notification only.
+ if (raw.subtype === 'task_updated') return [];
+
if (raw.subtype !== 'init') return [];
this.sessionId = raw.session_id;
this.started = true;
@@ -449,6 +545,11 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
// 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);
+ // Cache the raw CC tool name (NOT the rewritten apiName) so a
+ // later repeat tool_result on this id can label its
+ // ExternalSignalContext with the actual tool โ€” Monitor shows
+ // up as `Monitor`, not the apiName remap.
+ if (block.name) this.mainToolNamesById.set(block.id, block.name);
if (block.name === CC_TODO_WRITE_TOOL_NAME && block.input) {
this.todoWriteInputs.set(block.id, block.input as TodoWriteArgs);
}
@@ -457,6 +558,15 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
}
}
+ // Any main-agent tool_use means the LLM has acted again โ€” the
+ // reactive "signal-driven step" phase ends. Drop any pending signal
+ // so future stream_starts go back on the main chain. The CURRENT
+ // step's stream_start may have already shipped with the signal tag
+ // (since it fires on `message_start`, before tool_use blocks
+ // arrive); MessageCollector ignores `metadata.signal` on messages
+ // with `tools.length > 0` so that mismatch is benign.
+ if (newToolCalls.length > 0) this.pendingExternalSignal = undefined;
+
// Under `--include-partial-messages`, CC may emit deltas first and then a
// final full assistant block for the SAME message.id. If the full block is
// longer than the streamed deltas, emit only the missing suffix so the
@@ -687,6 +797,15 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
const toolCallId: string | undefined = block.tool_use_id;
if (!toolCallId) continue;
+ // Main-agent `user` events carrying tool_result mean the NEXT
+ // assistant turn is a natural follow-up to that tool โ€” not a
+ // signal callback. Subagent inner tool_results don't count
+ // (they have their own routing) and never block the main-agent
+ // signal pipeline.
+ if (!subagentCtx) {
+ this.hasUnhandledUserInput = true;
+ }
+
const resultContent =
typeof block.content === 'string'
? block.content
@@ -794,6 +913,10 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
this.pendingRateLimitInfo = undefined;
this.streamedTextByMessageId.clear();
this.streamedThinkingByMessageId.clear();
+ // Drop any unconsumed task-completion lineage so the next LLM run
+ // doesn't inherit it (e.g. a follow-up user turn would otherwise
+ // wrongly inherit the previous run's task-completion tag).
+ this.pendingTaskCompletion = undefined;
return [...events, this.makeEvent('stream_end', {}), finalEvent];
}
@@ -900,9 +1023,52 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
this.currentMessageId = messageId;
this.stepIndex++;
+ // Signal-callback detection (LOBE-8998): 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) {
+ // 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;
+ }
+ this.hasUnhandledUserInput = false;
+
return [
this.makeEvent('stream_end', {}),
- this.makeEvent('stream_start', { model, newStep: true, provider: 'claude-code' }),
+ this.makeEvent('stream_start', {
+ externalSignal: this.pendingExternalSignal,
+ model,
+ newStep: true,
+ provider: 'claude-code',
+ }),
];
}
diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.ts
index 5a44cff015e..4c348233022 100644
--- a/packages/heterogeneous-agents/src/types.ts
+++ b/packages/heterogeneous-agents/src/types.ts
@@ -43,10 +43,65 @@ export interface HeterogeneousAgentEvent {
/** Data shape for stream_start events */
export interface StreamStartData {
assistantMessage?: { id: string };
+ /**
+ * External-trigger context for the step opened by this stream_start.
+ * Set when the new step was opened in response to a repeated tool
+ * result on the same `tool_use.id` (Monitor stdout push pattern) or
+ * other out-of-band callback โ€” i.e. NOT a fresh user message.
+ *
+ * Executor stamps this onto the new assistant message's
+ * `metadata.signal` so MessageCollector can collect signal-tagged
+ * toolless assistants into a SignalCallbacksNode.
+ *
+ * Phase 2 (LOBE-8999) promotes the persisted shape to a dedicated
+ * `messages.signal` column; the event peer field name stays
+ * `externalSignal` regardless.
+ */
+ externalSignal?: ExternalSignalContext;
model?: string;
provider?: string;
}
+/**
+ * Carried as a peer field on stream events when the LLM turn was
+ * triggered by an external signal rather than a fresh user message.
+ *
+ * Canonical case: CC's Monitor tool keeps pushing additional stdout
+ * lines as `tool_result` blocks on the SAME `tool_use.id`, each push
+ * driving a new assistant turn. Future variants will cover webhook
+ * callbacks, scheduled triggers, and agent-signal sources.
+ *
+ * The adapter detects these patterns by counting tool_results per
+ * `tool_use.id`; the executor writes the context to
+ * `message.metadata.signal`; the conversation-flow collector groups
+ * signal-tagged toolless assistants into a SignalCallbacksNode.
+ */
+export interface ExternalSignalContext {
+ /** Nth push from the same source (1 = first repeat result). */
+ sequence?: number;
+ /** Source `tool_use.id` (CC) / function call id whose repeat fired this signal. */
+ sourceToolCallId: string;
+ /** Tool name for UI labelling, e.g. `Monitor`. */
+ sourceToolName: string;
+ /**
+ * Discriminator for the trigger source โ€” wire-stable.
+ *
+ * - `tool-stdout`: Monitor / long-running-tool stdout push pattern โ€”
+ * each turn is a reactive reply to a stdout event.
+ * - `tool-callback`: (future) one-shot async callback variant.
+ * - `task-completion`: the post-task summary turn โ€” fired by the LLM
+ * after CC delivers `system task_notification` (and the implicit
+ * "task ended" user event). Carries the same `sourceTool*` lineage
+ * as the preceding callbacks so the renderer can keep the summary
+ * inside the same AssistantGroup (appended after the SignalCallbacks
+ * block), instead of letting it spawn a separate group.
+ *
+ * Future webhook / scheduled / agent-signal-source variants land
+ * here as the pipeline absorbs more upstreams.
+ */
+ type: 'tool-stdout' | 'tool-callback' | 'task-completion';
+}
+
/**
* Adapter-extracted spawn metadata, attached to the FIRST event the
* adapter emits for a new subagent run (keyed by `parentToolCallId`).
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index 485e12604e0..9c86a44acc4 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -160,6 +160,13 @@ export const EmojiReactionSchema = z.object({
users: z.array(z.string()),
});
+export const MessageSignalSchema = z.object({
+ sequence: z.number().optional(),
+ sourceToolCallId: z.string(),
+ sourceToolName: z.string(),
+ type: z.enum(['tool-stdout', 'tool-callback', 'task-completion']),
+});
+
export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSchema).extend({
collapsed: z.boolean().optional(),
inspectExpanded: z.boolean().optional(),
@@ -173,6 +180,8 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSche
performance: ModelPerformanceSchema.optional(),
reactions: z.array(EmojiReactionSchema).optional(),
scope: z.string().optional(),
+ // External-signal lineage for Monitor-style callback turns (LOBE-8998).
+ signal: MessageSignalSchema.optional(),
subAgentId: z.string().optional(),
toolExecutionTimeMs: z.number().optional(),
trigger: z.nativeEnum(RequestTrigger).optional(),
@@ -310,6 +319,24 @@ export interface MessageMetadata {
* See MessageMapScope for available values
*/
scope?: string;
+ /**
+ * External-signal lineage for messages produced as reactive replies
+ * to an out-of-band trigger (Monitor stdout push, webhook callback,
+ * scheduled tick, โ€ฆ) rather than a fresh user turn. Phase-1 storage โ€”
+ * Phase 2 (LOBE-8999) promotes this to a dedicated `messages.signal`
+ * jsonb column.
+ *
+ * Conversation-flow groups signal-tagged TOOLLESS assistants into a
+ * SignalCallbacksNode under the source tool. Tool-using assistants
+ * may still carry this tag (the adapter clears the pending signal AT
+ * tool_use time, but the stream_start tag fired one event earlier);
+ * collectors must ignore the tag when `tools.length > 0`.
+ *
+ * Shape mirrors `ExternalSignalContext` in
+ * `packages/heterogeneous-agents/src/types.ts` โ€” duplicated here so
+ * `@lobechat/types` stays free of an adapter-package dependency.
+ */
+ signal?: MessageSignal;
/**
* Sub Agent ID - behavior depends on scope
* - scope: 'sub_agent': conversation-flow will transform message.agentId to this value for display
@@ -340,3 +367,30 @@ export interface MessageMetadata {
ttft?: number;
usage?: ModelUsage;
}
+
+/**
+ * Persisted form of an external-signal trigger context โ€” stamped on
+ * messages produced as reactive replies to out-of-band events.
+ *
+ * Phase 1 lives under `MessageMetadata.signal`; Phase 2 (LOBE-8999)
+ * promotes to a dedicated `messages.signal` column with the same
+ * shape (plus `rootSourceId` / `scopeKey` for agent-signal alignment).
+ */
+export interface MessageSignal {
+ /** Nth push from the same source (1 = first repeat result). */
+ sequence?: number;
+ /** Source `tool_use.id` (CC) / function call id whose repeat fired this signal. */
+ sourceToolCallId: string;
+ /** Tool name for UI labelling, e.g. `Monitor`. */
+ sourceToolName: string;
+ /**
+ * Discriminator for the trigger source.
+ *
+ * - `tool-stdout`: reactive turn driven by a long-running tool's stdout push.
+ * - `tool-callback`: (future) one-shot async callback variant.
+ * - `task-completion`: post-task summary turn after the long-running tool
+ * ended; keeps the summary inside the same AssistantGroup as the
+ * preceding callbacks.
+ */
+ type: 'tool-stdout' | 'tool-callback' | 'task-completion';
+}
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index 843f2cf05d3..d051a3fe37c 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -108,6 +108,34 @@ interface UIMessageBranch {
count: number;
}
+/**
+ * Snapshot of a single toolless assistant callback inside a
+ * {@link UISignalCallbacksBlock}. The snapshot is denormalized at
+ * FlatListBuilder time so the renderer doesn't have to round-trip
+ * through the messages map.
+ */
+export interface UISignalCallback {
+ content: string;
+ id: string;
+ model?: string | null;
+ provider?: string | null;
+ /** Nth push from the same source (1-based, matches metadata.signal.sequence). */
+ sequence?: number;
+}
+
+/**
+ * Group of callback turns attached to one source tool, denormalized
+ * onto a virtual `assistantGroup` message by FlatListBuilder. One
+ * block per source tool โ€” multiple callback-firing tools in the same
+ * group produce multiple blocks.
+ */
+export interface UISignalCallbacksBlock {
+ callbacks: UISignalCallback[];
+ sourceToolCallId: string;
+ sourceToolMessageId: string;
+ sourceToolName: string;
+}
+
/**
* Task execution details for role='task' messages
* Retrieved from the associated Thread via sourceMessageId
@@ -224,10 +252,34 @@ export interface UIChatMessage {
role: UIMessageRoleType;
search?: GroundingSearch | null;
sessionId?: string;
+ /**
+ * External-signal callback blocks (LOBE-8998). Set on virtual
+ * assistantGroup messages built by FlatListBuilder when the chain
+ * contains toolless assistants triggered by repeated tool_results
+ * (Monitor stdout push pattern). Rendered as `<SignalCallbacks>`
+ * blocks inside the AssistantGroup, separate from the main chain.
+ *
+ * Each entry corresponds to one source tool; multiple source tools
+ * in the same group produce multiple entries.
+ */
+ signalCallbacks?: UISignalCallbacksBlock[];
/**
* target member ID for DM messages in group chat
*/
targetId?: string | null;
+ /**
+ * Post-task summary blocks (LOBE-8998). Set on virtual assistantGroup
+ * messages by FlatListBuilder when the chain contains toolless
+ * assistants tagged with `signal.type === 'task-completion'` โ€” the
+ * final-summary turn the LLM emits after CC delivers
+ * `system task_notification` for a long-running tool (Monitor, etc.).
+ *
+ * Rendered after `<SignalCallbacks>` so the natural narrative inside
+ * the same AssistantGroup reads: initial reply โ†’ callback accordion โ†’
+ * summary. Multiple entries are possible (rare) if several tools
+ * completed within one LLM run.
+ */
+ taskCompletions?: AssistantContentBlock[];
/**
* Task execution details for role='task' messages
* Retrieved from the associated Thread via sourceMessageId
diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsx
index 35877617e32..c650a309ba7 100644
--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx
@@ -1,6 +1,7 @@
'use client';
-import type { AssistantContentBlock, EmojiReaction } from '@lobechat/types';
+import type { AssistantContentBlock, EmojiReaction, UISignalCallbacksBlock } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import type { MouseEventHandler, ReactNode } from 'react';
import { memo, Suspense, useCallback, useMemo } from 'react';
@@ -25,6 +26,7 @@ import {
useSetMessageItemActionElementPortialContext,
useSetMessageItemActionTypeContext,
} from '../Contexts/message-action-context';
+import SignalCallbacks from '../SignalCallbacks';
import FileListViewer from '../User/components/FileListViewer';
import Group from './components/Group';
import type { WorkflowExpandLevelDefault } from './components/WorkflowCollapse';
@@ -53,8 +55,19 @@ const GroupMessage = memo<GroupMessageProps>(
// Get message and actionsConfig from ConversationStore
const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual)!;
- const { agentId, usage, createdAt, children, performance, model, provider, branch, metadata } =
- item;
+ const {
+ agentId,
+ usage,
+ createdAt,
+ children,
+ performance,
+ model,
+ provider,
+ branch,
+ metadata,
+ signalCallbacks,
+ taskCompletions,
+ } = item;
const avatar = useAgentMeta(agentId);
// Collect fileList from all children blocks
@@ -162,17 +175,41 @@ const GroupMessage = memo<GroupMessageProps>(
onAvatarClick={onAvatarClick}
onMouseEnter={onMouseEnter}
>
- {children && children.length > 0 && (
- <Group
- blocks={children}
- content={lastAssistantMsg?.content}
- contentId={contentId}
- defaultWorkflowExpandLevel={defaultWorkflowExpandLevel}
- disableEditing={disableEditing}
- id={id}
- messageIndex={index}
- />
- )}
+ {/*
+ Wrap main chain + signal callbacks + post-task summary in a tight
+ flex stack so the SignalCallbacks accordion sits visually inside
+ the same "agent reply" block. The ChatItem body gap (16px) would
+ otherwise stretch them apart and the natural narrative โ€” initial
+ reply โ†’ callbacks โ†’ summary โ€” reads as three disconnected
+ sections (LOBE-8998).
+ */}
+ <Flexbox gap={4}>
+ {children && children.length > 0 && (
+ <Group
+ blocks={children}
+ content={lastAssistantMsg?.content}
+ contentId={contentId}
+ defaultWorkflowExpandLevel={defaultWorkflowExpandLevel}
+ disableEditing={disableEditing}
+ id={id}
+ messageIndex={index}
+ />
+ )}
+ {(signalCallbacks as UISignalCallbacksBlock[] | undefined)?.map((block) => (
+ <SignalCallbacks block={block} key={block.sourceToolMessageId} />
+ ))}
+ {taskCompletions && taskCompletions.length > 0 && (
+ <Group
+ blocks={taskCompletions}
+ contentId={taskCompletions.at(-1)?.id}
+ defaultWorkflowExpandLevel={defaultWorkflowExpandLevel}
+ disableEditing={disableEditing}
+ id={id}
+ messageIndex={index}
+ />
+ )}
+ </Flexbox>
+
{aggregatedFileList.length > 0 && (
<div style={{ marginTop: 8 }}>
<FileListViewer items={aggregatedFileList} />
diff --git a/src/features/Conversation/Messages/SignalCallbacks/index.tsx b/src/features/Conversation/Messages/SignalCallbacks/index.tsx
new file mode 100644
index 00000000000..b184786a4d7
--- /dev/null
+++ b/src/features/Conversation/Messages/SignalCallbacks/index.tsx
@@ -0,0 +1,107 @@
+'use client';
+
+import { type UISignalCallbacksBlock } from '@lobechat/types';
+import { Accordion, AccordionItem, Block, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { Radio } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = createStaticStyles(({ css }) => ({
+ callbackBody: css`
+ overflow: auto;
+ max-height: 360px;
+ `,
+ callbackItem: css`
+ padding-block: 4px;
+
+ &:not(:last-child) {
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ }
+ `,
+ sequence: css`
+ flex: none;
+
+ min-width: 20px;
+
+ font-size: 11px;
+ font-feature-settings: 'tnum';
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+const SignalCallbacks = memo<{ block: UISignalCallbacksBlock }>(({ block }) => {
+ const { t } = useTranslation('chat');
+ const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
+
+ return (
+ <Accordion
+ expandedKeys={expandedKeys}
+ gap={4}
+ onExpandedChange={(keys) => setExpandedKeys(keys as string[])}
+ >
+ <AccordionItem
+ itemKey="signal-callbacks"
+ paddingBlock={4}
+ paddingInline={4}
+ title={
+ <Flexbox horizontal align="center" gap={8}>
+ <Block
+ horizontal
+ align="center"
+ flex="none"
+ gap={4}
+ height={24}
+ justify="center"
+ style={{ fontSize: 12 }}
+ variant="outlined"
+ width={24}
+ >
+ <Icon color={cssVar.colorTextSecondary} icon={Radio} />
+ </Block>
+ <Text as="span" type="secondary">
+ {t('signalCallbacks.title', {
+ count: block.callbacks.length,
+ tool: block.sourceToolName,
+ })}
+ </Text>
+ </Flexbox>
+ }
+ >
+ <Block
+ className={styles.callbackBody}
+ padding={12}
+ style={{ marginBlock: 8 }}
+ variant={'outlined'}
+ >
+ {block.callbacks.length === 0 ? (
+ <Text type="secondary">{t('signalCallbacks.empty')}</Text>
+ ) : (
+ <Flexbox gap={4}>
+ {block.callbacks.map((cb) => (
+ <Flexbox
+ horizontal
+ align="flex-start"
+ className={styles.callbackItem}
+ gap={8}
+ key={cb.id}
+ >
+ {typeof cb.sequence === 'number' && (
+ <span className={styles.sequence}>#{cb.sequence}</span>
+ )}
+ <Flexbox flex={1}>
+ <Markdown variant="chat">{cb.content}</Markdown>
+ </Flexbox>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ )}
+ </Block>
+ </AccordionItem>
+ </Accordion>
+ );
+});
+
+SignalCallbacks.displayName = 'SignalCallbacks';
+
+export default SignalCallbacks;
diff --git a/src/features/Conversation/store/slices/data/selectors.ts b/src/features/Conversation/store/slices/data/selectors.ts
index 539a748cb53..af968befcbc 100644
--- a/src/features/Conversation/store/slices/data/selectors.ts
+++ b/src/features/Conversation/store/slices/data/selectors.ts
@@ -160,6 +160,16 @@ const findBlockById = (
const block = message.children.find((child) => child.id === blockId);
if (block) return block;
}
+ // Post-task summary blocks live in a separate field on virtual
+ // assistantGroup messages so they render AFTER `<SignalCallbacks>`
+ // (LOBE-8998). Same lookup contract as `children` โ€” the renderer
+ // identifies blocks by id regardless of which slot they came from.
+ if ((message as { taskCompletions?: AssistantContentBlock[] }).taskCompletions) {
+ const block = (
+ message as { taskCompletions?: AssistantContentBlock[] }
+ ).taskCompletions!.find((child) => child.id === blockId);
+ if (block) return block;
+ }
if (message.compressedMessages) {
const inCompressedMessages = findBlockById(blockId, message.compressedMessages);
if (inCompressedMessages) return inCompressedMessages;
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 1fa5f5f75ec..61faaa669fa 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -514,6 +514,10 @@ export default {
'sharePage.error.unauthorized.title': 'Sign In Required',
'sharePageDisclaimer':
'This content is shared by a user and does not represent the views of LobeHub. LobeHub is not responsible for any consequences arising from this shared content.',
+ 'signalCallbacks.collapse': 'Hide details',
+ 'signalCallbacks.empty': 'No callback messages',
+ 'signalCallbacks.expand': 'Show details',
+ 'signalCallbacks.title': '{{tool}} ยท {{count}} callback updates',
'stt.action': 'Voice Input',
'stt.loading': 'Recognizing...',
'stt.prettifying': 'Polishing...',
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 54b6a4de66f..063f4f1b3b7 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -2959,12 +2959,11 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
/**
- * Hypothesis 2 from the issue: a toolless step in the middle.
- * If Monitor's stdout triggers CC to respond with only text (no tool_use),
- * the next step must still chain through. This test documents current
- * behavior: toolless step breaks tool โ†’ next-tool chain.
+ * LOBE-8993 regression: a toolless step in the middle must NOT break the
+ * zigzag chain. The next step should chain back to the most recent tool
+ * result ever produced in the run, not to the toolless assistant.
*/
- it('toolless middle step: chain visibly breaks at text-only step', async () => {
+ it('toolless middle step: next step chains back to last real tool', async () => {
const idCounter = { tool: 0, assistant: 0 };
mockCreateMessage.mockImplementation(async (params: any) => {
if (params.role === 'tool') {
@@ -2993,15 +2992,61 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
);
expect(assistantCreates.length).toBe(2);
- // Step 1 parent = Monitor tool from step 0 โ†’ this IS correct (tool-1)
+ // Step 1 parent = Monitor tool from step 0 (tool-1)
expect(assistantCreates[0][0].parentId).toBe('tool-1');
- // Step 2 parent: step 1 had NO tools, so toolState.payloads is empty.
- // Code falls back to currentAssistantMessageId (= step 1 assistant).
- // BUG: this breaks the assistantGroup chain because collectAssistantChain
- // only walks tool โ†’ assistant, never assistant โ†’ assistant.
- expect(assistantCreates[1][0].parentId).toBe('ast-new-1');
- // ^ If this assertion passes, the chain IS broken.
+ // Step 2 parent: step 1 was toolless, but the chain must skip back to
+ // step 0's Monitor (tool-1) so MessageCollector's assistant โ†’ tool โ†’
+ // assistant walk keeps every assistant in the same group.
+ expect(assistantCreates[1][0].parentId).toBe('tool-1');
+ });
+
+ /**
+ * LOBE-8993 follow-up: N consecutive toolless steps (Monitor pushing
+ * stdout line by line, each line triggering a new LLM call that only
+ * answers with text). All toolless assistants must chain back to the
+ * same originating tool result; otherwise the UI splits one bubble per
+ * Monitor line.
+ */
+ it('consecutive toolless steps: all parents resolve to the originating tool', async () => {
+ const idCounter = { tool: 0, assistant: 0 };
+ mockCreateMessage.mockImplementation(async (params: any) => {
+ if (params.role === 'tool') {
+ idCounter.tool++;
+ return { id: `tool-${idCounter.tool}` };
+ }
+ idCounter.assistant++;
+ return { id: `ast-new-${idCounter.assistant}` };
+ });
+
+ await runWithEvents([
+ ccInit(),
+ // Step 0: Monitor kicks off the long-running task
+ ccToolUse('msg_01', 'toolu_mon_0', 'Monitor', { shell: 'tail -f log' }),
+ ccToolResult('toolu_mon_0', 'Monitor started'),
+ // Step 1, 2, 3: each Monitor stdout line drives a toolless reply
+ ccText('msg_02', '็ญ‰ list ๅฎŒใ€‚'),
+ ccText('msg_03', '84842 ๅˆ—ๅฎŒ๏ผŒๅผ€ๅนฒใ€‚'),
+ ccText('msg_04', '100/84842 ๅ…จ skipโ€ฆ'),
+ // Step 4: CC finally reacts with a Bash tool
+ ccToolUse('msg_05', 'toolu_bash_1', 'Bash', { command: 'echo ack' }),
+ ccToolResult('toolu_bash_1', 'ack'),
+ ccResult(),
+ ]);
+
+ const assistantCreates = mockCreateMessage.mock.calls.filter(
+ ([p]: any) => p.role === 'assistant',
+ );
+ // 4 new assistants (steps 1โ€“4); step 0 reuses ast-initial
+ expect(assistantCreates.length).toBe(4);
+
+ // All toolless steps chain back to the Monitor tool from step 0
+ expect(assistantCreates[0][0].parentId).toBe('tool-1');
+ expect(assistantCreates[1][0].parentId).toBe('tool-1');
+ expect(assistantCreates[2][0].parentId).toBe('tool-1');
+ // Step 4 also chains to tool-1 โ€” its own step had no tools yet at
+ // step_start, the Bash tool only persists after stream_start fires.
+ expect(assistantCreates[3][0].parentId).toBe('tool-1');
});
/**
@@ -3049,6 +3094,145 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
});
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ // LOBE-8998: external signal stamping on Monitor-driven follow-up steps
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ describe('LOBE-8998 external signal (metadata.signal)', () => {
+ const ccTaskStarted = (taskId: string, toolUseId: string) => ({
+ session_id: 'cc-sess-1',
+ subtype: 'task_started',
+ task_id: taskId,
+ tool_use_id: toolUseId,
+ type: 'system',
+ });
+ const ccTaskNotification = (taskId: string) => ({
+ session_id: 'cc-sess-1',
+ subtype: 'task_notification',
+ task_id: taskId,
+ type: 'system',
+ });
+
+ it('stamps metadata.signal on assistant turns CC opens without user input while a task is active', async () => {
+ const idCounter = { tool: 0, assistant: 0 };
+ mockCreateMessage.mockImplementation(async (params: any) => {
+ if (params.role === 'tool') {
+ idCounter.tool++;
+ return { id: `tool-${idCounter.tool}` };
+ }
+ idCounter.assistant++;
+ return { id: `ast-new-${idCounter.assistant}` };
+ });
+
+ await runWithEvents([
+ ccInit(),
+ // Step 0: LLM calls Monitor; CC registers it as a long-running
+ // task; Monitor's initial "started" tool_result lands as a user
+ // event โ€” so the FOLLOW-UP turn is a natural confirmation, NOT
+ // a signal callback.
+ ccMessageStart('msg_01'),
+ ccToolUse('msg_01', 'toolu_mon_0', 'Monitor', { shell: 'every 1s' }),
+ ccTaskStarted('task_a', 'toolu_mon_0'),
+ ccToolResult('toolu_mon_0', 'Monitor started'),
+ // Step 1: natural confirmation turn โ€” NO signal tag.
+ ccMessageStart('msg_02'),
+ ccText('msg_02', 'Monitor ๅทฒๅฏๅŠจใ€‚'),
+ // Step 2: Monitor pushed stdout โ†’ CC re-invokes LLM. No new
+ // user event was emitted between msg_02 end and msg_03 start.
+ // This IS a signal callback.
+ ccMessageStart('msg_03'),
+ ccText('msg_03', '็ฌฌ 1 ๆฌก๏ผš12:00:01'),
+ // Step 3: another Monitor push โ†’ another signal callback.
+ ccMessageStart('msg_04'),
+ ccText('msg_04', '็ฌฌ 2 ๆฌก๏ผš12:00:02'),
+ // Task ends; Step 4 is a natural summary turn, NOT signal.
+ ccTaskNotification('task_a'),
+ ccMessageStart('msg_05'),
+ ccText('msg_05', 'Monitor ไปปๅŠกๅทฒๅฎŒๆˆใ€‚'),
+ ccResult(),
+ ]);
+
+ const assistantCreates = mockCreateMessage.mock.calls.filter(
+ ([p]: any) => p.role === 'assistant',
+ );
+ // Step 0 reuses ast-initial; steps 1..4 โ†’ 4 fresh creates.
+ expect(assistantCreates.length).toBe(4);
+
+ // Step 1 confirmation: no signal
+ expect(assistantCreates[0][0].metadata?.signal).toBeUndefined();
+ // Step 2 first signal callback
+ expect(assistantCreates[1][0].metadata?.signal).toEqual({
+ sequence: 1,
+ sourceToolCallId: 'toolu_mon_0',
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout',
+ });
+ // Step 3 second signal callback, sequence advances
+ expect(assistantCreates[2][0].metadata?.signal).toEqual({
+ sequence: 2,
+ sourceToolCallId: 'toolu_mon_0',
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout',
+ });
+ // Step 4 post-task summary: tagged with `task-completion` (LOBE-8998)
+ // so MessageCollector renders it inside the same AssistantGroup,
+ // after the SignalCallbacks accordion.
+ expect(assistantCreates[3][0].metadata?.signal).toEqual({
+ sourceToolCallId: 'toolu_mon_0',
+ sourceToolName: 'Monitor',
+ type: 'task-completion',
+ });
+ });
+
+ it('does NOT stamp metadata.signal on turns following a tool_result (main-chain follow-up)', async () => {
+ const idCounter = { tool: 0, assistant: 0 };
+ mockCreateMessage.mockImplementation(async (params: any) => {
+ if (params.role === 'tool') {
+ idCounter.tool++;
+ return { id: `tool-${idCounter.tool}` };
+ }
+ idCounter.assistant++;
+ return { id: `ast-new-${idCounter.assistant}` };
+ });
+
+ await runWithEvents([
+ ccInit(),
+ ccMessageStart('msg_01'),
+ ccToolUse('msg_01', 'toolu_mon_0', 'Monitor', {}),
+ ccTaskStarted('task_a', 'toolu_mon_0'),
+ ccToolResult('toolu_mon_0', 'Monitor started'),
+ // Step 1: Monitor confirmation โ€” main chain, no signal.
+ ccMessageStart('msg_02'),
+ ccText('msg_02', 'ok'),
+ // Step 2: LLM emits Bash. Adapter can't know about tool_use at
+ // stream_start time, so the signal tag IS stamped (Monitor is
+ // active and no user input arrived). Reader-side
+ // (`MessageCollector.getMessageSignal`) ignores the tag when
+ // `tools.length > 0`, so the mismatch is benign.
+ ccMessageStart('msg_03'),
+ ccToolUse('msg_03', 'toolu_bash_0', 'Bash', { command: 'echo' }),
+ ccToolResult('toolu_bash_0', 'echo result'),
+ // Step 3: post-Bash continuation โ€” adapter saw the tool_result,
+ // so the next turn is a natural follow-up, no signal.
+ ccMessageStart('msg_04'),
+ ccText('msg_04', 'bash done'),
+ ccResult(),
+ ]);
+
+ const assistantCreates = mockCreateMessage.mock.calls.filter(
+ ([p]: any) => p.role === 'assistant',
+ );
+ expect(assistantCreates.length).toBe(3);
+ // Step 1 confirmation โ€” no signal
+ expect(assistantCreates[0][0].metadata?.signal).toBeUndefined();
+ // Step 2 with Bash tool โ€” signal IS stamped at stream_start, but
+ // collector defangs it (tools.length > 0).
+ expect(assistantCreates[1][0].metadata?.signal?.sourceToolCallId).toBe('toolu_mon_0');
+ // Step 3 post-Bash continuation โ€” no signal.
+ expect(assistantCreates[2][0].metadata?.signal).toBeUndefined();
+ });
+ });
+
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Parallel main tool batch: tool_end must not race ahead of persistQueue
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
diff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
index 675267cbd1e..cf0630a3b01 100644
--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
@@ -1142,6 +1142,23 @@ export const executeHeterogeneousAgent = async (
let lastModel: string | undefined;
/** Adapter/CLI provider (e.g. `claude-code`) โ€” carried on every turn_metadata. */
let lastProvider: string | undefined;
+ /**
+ * Most recent tool `result_msg_id` seen across step boundaries โ€” survives the
+ * `toolState.payloads` reset that happens on every new step.
+ *
+ * Required for the **toolless middle step** case (LOBE-8993): when a step
+ * produces only text (e.g. Monitor stdout drives Claude to reply "็ญ‰ไธ€ไธ‹โ€ฆ"
+ * without invoking a tool), `toolState.payloads` is empty at the next step
+ * boundary. Without this tracker, `stepParentId` would fall back to
+ * `currentAssistantMessageId` (= the toolless assistant), forming an
+ * `assistant โ†’ assistant` link. `MessageCollector.collectAssistantChain`
+ * only walks the `assistant โ†’ tool โ†’ assistant` zigzag, so the UI splits
+ * into one bubble per Monitor stdout line.
+ *
+ * Scope: executor lifetime (one user run). A new user message spawns a
+ * new executor, so this resets implicitly at run boundaries.
+ */
+ let lastToolMsgIdEver: string | undefined;
/**
* Deferred terminal event (agent_runtime_end or error). We don't forward
* these to the gateway handler immediately because handler triggers
@@ -1513,6 +1530,17 @@ export const executeHeterogeneousAgent = async (
const prevReasoning = accumulatedReasoning;
const prevModel = lastModel;
const prevProvider = lastProvider;
+ // External-signal context (LOBE-8998): set when the adapter
+ // detected a repeated tool_result on the same tool_use.id
+ // (Monitor stdout push, etc.). Stamp on the new message's
+ // `metadata.signal` so MessageCollector can route toolless
+ // signal-tagged assistants into a SignalCallbacksNode.
+ //
+ // Phase 1 lives in metadata; Phase 2 (LOBE-8999) promotes to a
+ // dedicated `messages.signal` column โ€” to migrate, change THIS
+ // assignment and the `getMessageSignal()` helper in
+ // conversation-flow, nothing else.
+ const externalSignal = event.data.externalSignal;
// Reset content accumulators synchronously so new-step chunks go to fresh state
accumulatedContent = '';
@@ -1552,11 +1580,16 @@ export const executeHeterogeneousAgent = async (
const lastToolMsgId = [...toolState.payloads]
.reverse()
.find((p) => !!p.result_msg_id)?.result_msg_id;
- const stepParentId = lastToolMsgId || currentAssistantMessageId;
+ if (lastToolMsgId) lastToolMsgIdEver = lastToolMsgId;
+ // Prefer this step's last tool, then the most recent tool ever seen
+ // in the run (rescues toolless middle steps โ€” see LOBE-8993), then
+ // the previous assistant as a last resort.
+ const stepParentId = lastToolMsgId ?? lastToolMsgIdEver ?? currentAssistantMessageId;
const newMsg = await messageService.createMessage({
agentId: context.agentId,
content: '',
+ ...(externalSignal ? { metadata: { signal: externalSignal } } : {}),
model: lastModel,
parentId: stepParentId,
provider: lastProvider,