Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(hetero): render text-only subagent wake-ups in creation order (#22138)

AmAzing-9a594a658a4a
diff --git a/apps/server/src/routers/lambda/_helpers/projectSharedTopicMessages.test.ts b/apps/server/src/routers/lambda/_helpers/projectSharedTopicMessages.test.ts
index cdbc4623122..dd4666964c1 100644
--- a/apps/server/src/routers/lambda/_helpers/projectSharedTopicMessages.test.ts
+++ b/apps/server/src/routers/lambda/_helpers/projectSharedTopicMessages.test.ts
@@ -58,7 +58,6 @@ describe('projectSharedTopicMessages', () => {
error: rawError,
members: [message('member', { error: rawError })],
pluginError: { message: 'internal plugin failure' },
- taskCompletions: [{ content: 'Done', error: rawError, id: 'completion' }],
tasks: [message('nested-task', { error: rawError })],
}),
];
@@ -75,7 +74,6 @@ describe('projectSharedTopicMessages', () => {
expect(result[0].compressedMessages?.[0].error).toEqual(safeError);
expect(result[0].members?.[0].error).toEqual(safeError);
expect(result[0].tasks?.[0].error).toEqual(safeError);
- expect(result[0].taskCompletions?.[0].error).toEqual(safeError);
expect(result[0].children?.[0].tools?.[0].result).toMatchObject({
content: 'Public result',
error: undefined,
diff --git a/apps/server/src/routers/lambda/_helpers/projectSharedTopicMessages.ts b/apps/server/src/routers/lambda/_helpers/projectSharedTopicMessages.ts
index 2331aa3deb0..4b4fd288959 100644
--- a/apps/server/src/routers/lambda/_helpers/projectSharedTopicMessages.ts
+++ b/apps/server/src/routers/lambda/_helpers/projectSharedTopicMessages.ts
@@ -37,7 +37,6 @@ const projectMessage = (message: UIChatMessage): UIChatMessage => ({
error: projectError(message.error),
members: message.members?.map(projectMessage),
pluginError: undefined,
- taskCompletions: message.taskCompletions?.map(projectAssistantContentBlock),
tasks: message.tasks?.map(projectMessage),
});
diff --git a/apps/server/src/routers/lambda/_helpers/sharedTopicText.ts b/apps/server/src/routers/lambda/_helpers/sharedTopicText.ts
index be081c81036..2e210cbb8cc 100644
--- a/apps/server/src/routers/lambda/_helpers/sharedTopicText.ts
+++ b/apps/server/src/routers/lambda/_helpers/sharedTopicText.ts
@@ -19,7 +19,7 @@ export const sharedTopicText = (messages: UIChatMessage[]): string => {
else if (message.compressedMessages) collect(parse(message.compressedMessages).flatList);
else if (message.role === 'user') append('User', message.content);
else if (message.role === 'assistantGroup') {
- const blocks = message.taskCompletions?.length ? message.taskCompletions : message.children;
+ const blocks = message.children;
// Never fall back to pre-tool narration when a run has no final answer.
const lastToolIndex = blocks?.findLastIndex((block) => !!block.tools?.length) ?? -1;
const { segments } = partitionAssistantGroupBlocks(blocks?.slice(lastToolIndex + 1) ?? [], {
diff --git a/apps/server/src/routers/lambda/_helpers/topicPreviews.ts b/apps/server/src/routers/lambda/_helpers/topicPreviews.ts
index adef508e5e9..fb8c29ae3d1 100644
--- a/apps/server/src/routers/lambda/_helpers/topicPreviews.ts
+++ b/apps/server/src/routers/lambda/_helpers/topicPreviews.ts
@@ -118,12 +118,7 @@ const readTopicPreview = async (
const message = page.messages.find((item) => item.id === finalId);
if (!isFinalAnswer(message) || !message) return skipped(topic.id, 'notFinalAnswer');
- const taskCompletions = tail.message.taskCompletions as AssistantContentBlock[] | undefined;
- const workRootOperationId = findLatestWorkRootOperationId(
- tail.message.metadata,
- children,
- taskCompletions,
- );
+ const workRootOperationId = findLatestWorkRootOperationId(tail.message.metadata, children);
return {
blocks: children,
diff --git a/packages/context-engine/src/tokenAccounting/index.ts b/packages/context-engine/src/tokenAccounting/index.ts
index 99d6d2806c4..ca85829a507 100644
--- a/packages/context-engine/src/tokenAccounting/index.ts
+++ b/packages/context-engine/src/tokenAccounting/index.ts
@@ -122,10 +122,9 @@ type AssistantTokenBlock =
* `editorData`, `extra`, `metadata`
* (other than `metadata.usage.totalOutputTokens` shortcut for assistant and
* `metadata.instruction` for `task` messages, which ship in the template)
- * Also NOT counted: in-bubble `council` blocks (`AssistantContentBlock.council`)
- * and `taskCompletions` on group wrappers — both are UI-only denormalizations
- * (broadcast member replies / folded subagent completions) that GroupMessageFlatten
- * drops and never reach the provider. Counting them would over-estimate and
+ * Also NOT counted: in-bubble `council` blocks (`AssistantContentBlock.council`) —
+ * a UI-only denormalization (broadcast member replies) that GroupMessageFlatten
+ * drops and never reaches the provider. Counting them would over-estimate and
* trigger compression too early.
*
* **Token estimation accuracy**
diff --git a/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts b/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts
index 22076773911..df5747602e2 100644
--- a/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts
+++ b/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts
@@ -33,16 +33,12 @@ const workflowSegment = (id: string): AssistantGroupWorkflowSegment => ({
kind: 'workflow',
});
-const group = (
- children: AssistantContentBlock[],
- taskCompletions?: AssistantContentBlock[],
-): UIChatMessage => ({
+const group = (children: AssistantContentBlock[]): UIChatMessage => ({
children,
content: '',
createdAt: 0,
id: 'assistant-group',
role: 'assistantGroup',
- taskCompletions,
updatedAt: 0,
});
@@ -343,15 +339,6 @@ describe('resolveAssistantGroupFinalContent', () => {
expect(resolveAssistantGroupFinalContent(message)).toBe(detailedAnswer);
});
- it('prefers the last post-task summary over the main assistant chain', () => {
- const message = group(
- [block('main-answer', 'Initial answer')],
- [block('summary-1', 'First task summary'), block('summary-2', 'Final task summary')],
- );
-
- expect(resolveAssistantGroupFinalContent(message)).toBe('Final task summary');
- });
-
it('falls back to the latest authored status for a status-only group', () => {
const message = group([
block('status-1', 'Checking the repository.', { tools: [tool('search-call')] }),
diff --git a/packages/conversation-flow/src/assistantGroupContent.ts b/packages/conversation-flow/src/assistantGroupContent.ts
index d81681c6c83..bcece90e22f 100644
--- a/packages/conversation-flow/src/assistantGroupContent.ts
+++ b/packages/conversation-flow/src/assistantGroupContent.ts
@@ -418,22 +418,18 @@ const resolveLatestAuthoredContent = (blocks?: AssistantContentBlock[]): string
/**
* Resolve the authored text that best represents a parsed assistant group.
*
- * Both the main chain and post-task summaries use the same settled semantic
- * segmentation as the renderer. A textless final run (for example, an error-only
- * block) falls back through earlier answer segments before raw block content so
- * workflow narration cannot replace an authored answer in the preview.
+ * The main chain uses the same settled semantic segmentation as the renderer.
+ * A textless final run (for example, an error-only block) falls back through
+ * earlier answer segments before raw block content so workflow narration cannot
+ * replace an authored answer in the preview.
*/
export const resolveAssistantGroupFinalContent = (message?: UIChatMessage): string | undefined => {
- const taskContent = resolveSegmentedAuthoredContent(message?.taskCompletions);
const childContent = resolveSegmentedAuthoredContent(message?.children);
return (
- taskContent.finalAnswer ??
childContent.finalAnswer ??
normalizeAuthoredContent(message?.content) ??
- taskContent.answer ??
childContent.answer ??
- resolveLatestAuthoredContent(message?.taskCompletions) ??
resolveLatestAuthoredContent(message?.children)
);
};
diff --git a/packages/conversation-flow/src/doctor/diagnose.ts b/packages/conversation-flow/src/doctor/diagnose.ts
index e408d1644a2..a1fd1213781 100644
--- a/packages/conversation-flow/src/doctor/diagnose.ts
+++ b/packages/conversation-flow/src/doctor/diagnose.ts
@@ -1,14 +1,14 @@
import { parse } from '../parse';
-import { toTime } from '../utils/timestamp';
import type { Message, MessageGroupMetadata } from '../types';
+import { toTime } from '../utils/timestamp';
import type { RepairOp, TopicDiagnosis, TopicIssue } from './types';
/**
* Every message id referenced anywhere in the rendered payload.
*
* The renderer does not emit one flat entry per message: tool results live in
- * `children[].tools[].result_msg_id`, signal turns in `signalCallbacks[]`, post-task
- * summaries in `taskCompletions[]`, and so on. Rather than mirror each nesting site
+ * `children[].tools[].result_msg_id`, signal turns in `signalCallbacks[]`, and so on.
+ * Rather than mirror each nesting site
* (and silently start over-reporting whenever a new one is added), walk the payload
* generically and collect anything that could be a message id. Ids that are not
* messages (tool_call ids) fall out when the set is intersected with the topic.
@@ -175,7 +175,10 @@ export const diagnoseTopic = (
// a message inside this very section can't anchor it.
const sectionIds = new Set(section.map((m) => m.id));
const anchor = sorted
- .filter((m) => canAnchor(m) && toTime(m.createdAt) < toTime(root.createdAt) && !sectionIds.has(m.id))
+ .filter(
+ (m) =>
+ canAnchor(m) && toTime(m.createdAt) < toTime(root.createdAt) && !sectionIds.has(m.id),
+ )
.sort((a, b) => toTime(b.createdAt) - toTime(a.createdAt))[0];
if (!anchor) continue;
@@ -257,7 +260,8 @@ export const diagnoseTopic = (
const ownIds = new Set(ownSubtree.map((m) => m.id));
const candidates = sorted.filter(
- (m) => m.role === 'tool' && toTime(m.createdAt) < toTime(message.createdAt) && !ownIds.has(m.id),
+ (m) =>
+ m.role === 'tool' && toTime(m.createdAt) < toTime(message.createdAt) && !ownIds.has(m.id),
);
// The signal names the tool call it is reacting to; fall back to the most recent tool
// result only when that call cannot be found.
diff --git a/packages/conversation-flow/src/tail/index.ts b/packages/conversation-flow/src/tail/index.ts
index 61ac3f08a05..74003b14706 100644
--- a/packages/conversation-flow/src/tail/index.ts
+++ b/packages/conversation-flow/src/tail/index.ts
@@ -25,12 +25,9 @@ export const getOperationFinalRootId = (
export const findLatestWorkRootOperationId = (
metadata?: { work?: { rootOperationId?: unknown } } | null,
children?: AssistantContentBlock[],
- taskCompletions?: AssistantContentBlock[],
) => {
- const blocks = [...(children ?? []), ...(taskCompletions ?? [])];
-
- for (let index = blocks.length - 1; index >= 0; index -= 1) {
- const rootOperationId = getOperationFinalRootId(blocks[index]?.metadata);
+ for (let index = (children?.length ?? 0) - 1; index >= 0; index -= 1) {
+ const rootOperationId = getOperationFinalRootId(children?.[index]?.metadata);
if (rootOperationId) return rootOperationId;
}
diff --git a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts b/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
index 1108649fb18..525f9b6db72 100644
--- a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
+++ b/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
@@ -270,16 +270,6 @@ export class ContextTreeBuilder {
const signalCallbacks = this.messageCollector.collectSignalCallbacks(message, idNode);
children.push(...signalCallbacks);
- // After the callbacks block, append the post-task-summary turns
- // () — 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.taskCompletions.test.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.taskCompletions.test.ts
index b67cbb61d2c..165232429b2 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.taskCompletions.test.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.taskCompletions.test.ts
@@ -76,13 +76,15 @@ const messages: Message[] = [
},
] as Message[];
-describe('FlatListBuilder — task-completion blocks', () => {
- it('carries each wake-up turn’s signal lineage on its block', () => {
+describe('FlatListBuilder — task-completion turns', () => {
+ it('renders each wake-up as a step of the reply, carrying its own signal lineage', () => {
const { flatList } = parse(messages);
expect(flatList.map((m) => m.role)).toEqual(['user', 'assistantGroup']);
const group = flatList[1] as any;
- expect(group.taskCompletions.map((b: any) => [b.id, b.metadata?.signal])).toEqual([
+ expect(group.children.map((b: any) => [b.id, b.metadata?.signal])).toEqual([
+ ['a1', undefined],
+ ['a2', undefined],
['w1', { sourceToolCallId: 'call-srv', sourceToolName: 'Agent', type: 'task-completion' }],
['w2', { sourceToolCallId: 'call-fe', sourceToolName: 'Agent', type: 'task-completion' }],
]);
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index b2df2289f26..91b87b6e11d 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -5,8 +5,16 @@ import type { Message, MessageGroupMetadata, ThreadScope } from '../types';
import { toTime } from '../utils/timestamp';
import type { BranchResolver } from './BranchResolver';
import type { MessageCollector } from './MessageCollector';
+import { isToollessSignalTurn } from './MessageCollector';
import type { MessageTransformer } from './MessageTransformer';
-import { toTaskCompletionBlocks } from './taskCompletionBlocks';
+
+/**
+ * Metadata that describes one step rather than the whole group: a finish
+ * reason belongs to its own response block, and a wake-up's signal names the
+ * task that woke that step. Hoisting either to the first block would show a
+ * terminal notice or a task-completion notice beside the wrong step.
+ */
+const PER_BLOCK_METADATA_KEYS = new Set(['finishType', 'signal']);
/**
* Whether a message was authored by the group's supervisor agent.
@@ -330,15 +338,6 @@ export class FlatListBuilder {
allMessages,
);
- // Post-task-summary turns () — 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,
- );
-
// A broadcast turn renders its members as one in-bubble council block.
// Gather them before building the group so they embed inside it.
const council = this.collectCouncilMembers(allToolMessages, allMessages, processedIds);
@@ -349,7 +348,6 @@ export class FlatListBuilder {
assistantChain,
allToolMessages,
signalBlocks,
- taskCompletionMessages,
council?.members,
);
flatList.push(groupMessage);
@@ -360,9 +358,6 @@ export class FlatListBuilder {
for (const block of signalBlocks) {
for (const cb of block.callbacks) processedIds.add(cb.id);
}
- for (const completion of taskCompletionMessages) {
- processedIds.add(completion.id);
- }
// Surface the supervisor's post-council reply (attached to one member).
if (council) {
@@ -593,7 +588,6 @@ export class FlatListBuilder {
assistantChain,
allToolMessages,
undefined,
- undefined,
council?.members,
);
flatList.push(groupMessage);
@@ -624,7 +618,11 @@ export class FlatListBuilder {
processedIds: Set<string>,
allMessages: Message[],
): FlatListWork {
- const lastAssistant = assistantChain.at(-1);
+ // A text-only wake-up never hosts a follow-up, so a run ending on one is
+ // continued from the step before it.
+ const lastAssistant =
+ assistantChain.findLast((assistant) => !isToollessSignalTurn(assistant)) ??
+ assistantChain.at(-1);
if (lastAssistant) {
this.suppressInactiveExplicitContinuations(lastAssistant, allToolMessages, processedIds);
}
@@ -1143,7 +1141,6 @@ export class FlatListBuilder {
sourceToolMessageId: string;
sourceToolName: string;
}[],
- taskCompletionMessages?: Message[],
councilMembers?: Message[],
): Message {
const children: AssistantContentBlock[] = [];
@@ -1291,13 +1288,11 @@ export class FlatListBuilder {
const aggregated = this.messageTransformer.aggregateMetadata(children);
- // Finish reasons belong to their own response block; moving one to the first block can
- // display a terminal notice beside an earlier tool step.
const groupMetadata: Record<string, any> = {};
children.forEach((child) => {
if ((child as any).metadata) {
Object.entries((child as any).metadata).forEach(([key, value]) => {
- if (key !== 'finishType') groupMetadata[key] = value;
+ if (!PER_BLOCK_METADATA_KEYS.has(key)) groupMetadata[key] = value;
});
}
});
@@ -1310,11 +1305,15 @@ export class FlatListBuilder {
}
Object.assign((children[0] as any).metadata, groupMetadata);
- // Keep each child's finish reason while collecting shared metadata on the first child.
+ // Keep each child's per-block metadata while collecting shared metadata on the first child.
for (let i = 1; i < children.length; i++) {
- const finishType = (children[i] as any).metadata?.finishType;
- if (finishType === undefined) delete (children[i] as any).metadata;
- else (children[i] as any).metadata = { finishType };
+ const ownMetadata = Object.fromEntries(
+ Object.entries((children[i] as any).metadata ?? {}).filter(
+ ([key, value]) => PER_BLOCK_METADATA_KEYS.has(key) && value !== undefined,
+ ),
+ );
+ if (Object.keys(ownMetadata).length === 0) delete (children[i] as any).metadata;
+ else (children[i] as any).metadata = ownMetadata;
}
}
@@ -1382,10 +1381,6 @@ export class FlatListBuilder {
}));
}
- if (taskCompletionMessages && taskCompletionMessages.length > 0) {
- result.taskCompletions = toTaskCompletionBlocks(taskCompletionMessages);
- }
-
return result;
}
diff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.ts
index 42f5969e091..a68d6cc630c 100644
--- a/packages/conversation-flow/src/transformation/MessageCollector.ts
+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts
@@ -48,20 +48,31 @@ const getMessageSignal = (msg: Message): MessageSignal | undefined => {
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';
+/**
+ * A toolless signal turn. The writer never anchors a later turn to one, so it
+ * cannot be the step a follow-up hangs off.
+ */
+export const isToollessSignalTurn = (msg: Message): boolean => !!getMessageSignal(msg);
/**
- * A signal-tagged turn that called tools: a background task woke the LLM and it
- * went back to work on the main chain. `getMessageSignal` hides its tag so the
- * chain walks it, but it is a later step, never a regenerated branch, so it must
- * not compete with the step's other continuations in branch resolution.
+ * A turn a finished background task woke: either it went back to work with
+ * tools, or (`task-completion`) it only replied. Either way it is a later step
+ * of the run, never a regenerated branch, so it must not compete with the
+ * step's other continuations in branch resolution. The writer parents every
+ * wake-up off the run's latest tool result, so several can share one parent
+ * and sit next to the reply that ended the turn; they are ordered by creation.
*/
-const isWakeUpTurn = (msg: Message): boolean =>
- msg.role === 'assistant' &&
- !!msg.tools?.length &&
- !!(msg.metadata as { signal?: MessageSignal } | undefined | null)?.signal;
+const isWakeUpTurn = (msg: Message): boolean => {
+ if (msg.role !== 'assistant') return false;
+ const signal = (msg.metadata as { signal?: MessageSignal } | undefined | null)?.signal;
+ return !!signal && (!!msg.tools?.length || signal.type === 'task-completion');
+};
+
+/** Whether a same-agent assistant may continue the main chain (callback turns render in their accordion). */
+const isChainCandidate = (msg: Message | undefined, groupAgentId: string | undefined): boolean =>
+ msg?.role === 'assistant' &&
+ msg.agentId === groupAgentId &&
+ !isCallbackSignal(getMessageSignal(msg));
/** Lookups over one message array, each list in that array's order. */
interface MessageArrayIndex {
@@ -355,11 +366,10 @@ export class MessageCollector {
* continuations under different tool results), then resolve regenerated
* siblings under that child.
*
- * Wake-up turns ({@link isWakeUpTurn}) skip branch resolution. The writer
- * parents them off the run's latest tool result, so they sit next to the
- * toolless reply that ended the turn, and two of them can share one tool.
- * They join `pending` with the active continuation, and the earliest pending
- * one becomes the next step, so every turn renders in creation order.
+ * Wake-up turns ({@link isWakeUpTurn}) skip branch resolution. They join
+ * `pending` with the active continuation, and the earliest pending one
+ * becomes the next step, so every turn renders in creation order — a
+ * text-only wake-up included, even when a later wake-up continues the run.
*/
private findFlatChainContinuation(
currentAssistant: Message,
@@ -390,8 +400,7 @@ export class MessageCollector {
toTime(a.createdAt) - toTime(b.createdAt) || position.get(a.id)! - position.get(b.id)!;
const candidates = [...candidateParentIds]
.flatMap((parentId) => this.childrenOf(allMessages, parentId))
- .filter((m) => m.role !== 'tool' && !processedIds.has(m.id))
- .filter((m) => m.role === 'assistant' && m.agentId === groupAgentId && !getMessageSignal(m))
+ .filter((m) => !processedIds.has(m.id) && isChainCandidate(m, groupAgentId))
.sort(byCreation);
const wakeUps = candidates.filter(isWakeUpTurn);
const branchCandidates = candidates.filter((m) => !isWakeUpTurn(m));
@@ -535,9 +544,6 @@ export class MessageCollector {
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;
@@ -555,29 +561,6 @@ export class MessageCollector {
return blocks;
}
- /**
- * Flat-list variant — find post-task-summary assistants (),
- * 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 = this.childrenOf(allMessages, toolMsg.id);
- for (const child of children) {
- if (!isTaskCompletionSignal(getMessageSignal(child))) continue;
- completions.push(child);
- }
- }
- completions.sort((a, b) => toTime(a.createdAt) - toTime(b.createdAt));
- return completions;
- }
-
/**
* User turns that interrupted a folded group at `assistant`, an intermediate
* step whose next step in the chain is `next`. Branch selection among them
@@ -679,9 +662,9 @@ export class MessageCollector {
* guard (AgentCouncil / async tasks end the chain — including any
* assistant-anchored post-task summary) and branch resolution (>1 non-tool
* siblings under one parent ⇒ pick the active branch) as the flat variant.
- * Signal-tagged toolless siblings (Monitor callbacks etc.) are skipped so the
- * main chain walks the real follower, and wake-up turns queue in `pending`
- * outside branch resolution, as in the flat variant.
+ * Callback turns (Monitor stdout etc.) are skipped so the main chain walks
+ * the real follower, and wake-up turns queue in `pending` outside branch
+ * resolution, as in the flat variant.
*/
private findChainContinuationNode(
idNode: IdNode,
@@ -717,10 +700,7 @@ export class MessageCollector {
const eligible = candidateNodes
.map((node) => ({ msg: this.messageMap.get(node.id), node }))
- .filter(
- (c) =>
- c.msg?.role === 'assistant' && c.msg.agentId === groupAgentId && !getMessageSignal(c.msg),
- )
+ .filter((c) => isChainCandidate(c.msg, groupAgentId))
.sort((a, b) => toTime(a.msg!.createdAt) - toTime(b.msg!.createdAt));
const wakeUps = eligible.filter((c) => isWakeUpTurn(c.msg!)).map((c) => c.node);
const branchCandidates = eligible.filter((c) => !isWakeUpTurn(c.msg!));
@@ -805,8 +785,7 @@ export class MessageCollector {
// 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`).
+ // turns are main-chain steps, not callbacks.
const callbacks: Message[] = [];
for (const toolChild of child.children) {
const toolChildMsg = this.messageMap.get(toolChild.id);
@@ -836,38 +815,6 @@ export class MessageCollector {
return blocks;
}
- /**
- * Collect post-task-summary toolless siblings () — 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[] = [];
- this.forEachMainChainTool(idNode, groupAgentId, (child) => {
- 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' });
- }
- });
- return nodes;
- }
-
/**
* Find next message after tools in an assistant group
*/
@@ -899,9 +846,11 @@ export class MessageCollector {
}
/**
- * Return the final same-agent assistant that belongs inside this group. The
- * child selected after that assistant can be either a tool-hosted legacy
- * continuation or a direct non-tool continuation in the current storage form.
+ * Return the final same-agent assistant that belongs inside this group and
+ * can host what follows it. The child selected after that assistant can be
+ * either a tool-hosted legacy continuation or a direct non-tool continuation
+ * in the current storage form. A text-only wake-up never hosts a follow-up,
+ * so a run ending on one keeps the step before it.
*/
private findLastAssistantNodeInGroup(idNode: IdNode, groupAgentId?: string): IdNode {
// Iterative: a group's chain can be thousands of steps long.
@@ -909,8 +858,9 @@ export class MessageCollector {
let current = idNode;
let nextNode = this.findChainContinuationNode(current, groupAgentId, pending);
while (nextNode) {
- current = nextNode;
- nextNode = this.findChainContinuationNode(current, groupAgentId, pending);
+ const nextMessage = this.messageMap.get(nextNode.id);
+ if (!nextMessage || !isToollessSignalTurn(nextMessage)) current = nextNode;
+ nextNode = this.findChainContinuationNode(nextNode, groupAgentId, pending);
}
return current;
}
diff --git a/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts b/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts
index 3b05d5dbe4a..c1c007bef77 100644
--- a/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts
+++ b/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts
@@ -316,3 +316,172 @@ describe('wake-up turns that call tools after a toolless closing reply', () => {
expect(flat.map((m) => m.id)).toEqual(['u1', 'RUN', 'u2', 'a2']);
});
});
+
+/**
+ * Observed in a production topic: three background subagents. The first wake-up called a tool,
+ * the second only replied ("one more to go"), the third called a tool and then
+ * wrote the final summary. Both later wake-ups hang off the first wake-up's tool
+ * result. The text-only wake-up rendered below the final summary.
+ */
+describe('a text-only wake-up between wake-ups that call tools', () => {
+ const signal = (sourceToolCallId: string) =>
+ ({ signal: { sourceToolCallId, sourceToolName: 'Agent', type: 'task-completion' } }) as any;
+
+ const messages: Message[] = [
+ { content: 'go', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 },
+ {
+ agentId: 'a',
+ content: '',
+ createdAt: 100,
+ id: 'RUN',
+ parentId: 'u1',
+ role: 'assistant',
+ tools: [...toolArr('agentA'), ...toolArr('agentB'), ...toolArr('agentC')],
+ updatedAt: 100,
+ },
+ ...['agentA', 'agentB', 'agentC'].map(
+ (callId, index) =>
+ ({
+ content: 'launched',
+ createdAt: 101 + index,
+ id: `tool_${callId}`,
+ parentId: 'RUN',
+ role: 'tool',
+ tool_call_id: callId,
+ updatedAt: 101 + index,
+ }) as any,
+ ),
+ {
+ agentId: 'a',
+ content: 'launched three subagents',
+ createdAt: 110,
+ id: 'REPLY',
+ parentId: 'RUN',
+ role: 'assistant',
+ updatedAt: 110,
+ },
+ {
+ agentId: 'a',
+ content: '',
+ createdAt: 120,
+ id: 'WAKE_A',
+ metadata: signal('agentA'),
+ parentId: 'tool_agentC',
+ role: 'assistant',
+ tools: toolArr('readA'),
+ updatedAt: 120,
+ },
+ {
+ content: 'source',
+ createdAt: 121,
+ id: 'toolReadA',
+ parentId: 'WAKE_A',
+ role: 'tool',
+ tool_call_id: 'readA',
+ updatedAt: 121,
+ } as any,
+ {
+ agentId: 'a',
+ content: 'A checked, two still running',
+ createdAt: 125,
+ id: 'WAKE_A_REPLY',
+ parentId: 'WAKE_A',
+ role: 'assistant',
+ updatedAt: 125,
+ },
+ {
+ agentId: 'a',
+ content: 'C is done, waiting on B',
+ createdAt: 130,
+ id: 'DONE_C',
+ metadata: signal('agentC'),
+ parentId: 'toolReadA',
+ role: 'assistant',
+ updatedAt: 130,
+ },
+ {
+ agentId: 'a',
+ content: '',
+ createdAt: 140,
+ id: 'WAKE_B',
+ metadata: signal('agentB'),
+ parentId: 'toolReadA',
+ role: 'assistant',
+ tools: toolArr('readB'),
+ updatedAt: 140,
+ },
+ {
+ content: 'source',
+ createdAt: 141,
+ id: 'toolReadB',
+ parentId: 'WAKE_B',
+ role: 'tool',
+ tool_call_id: 'readB',
+ updatedAt: 141,
+ } as any,
+ {
+ agentId: 'a',
+ content: 'final summary',
+ createdAt: 150,
+ id: 'FINAL',
+ parentId: 'WAKE_B',
+ role: 'assistant',
+ updatedAt: 150,
+ },
+ ];
+
+ const everyStep = ['RUN', 'REPLY', 'WAKE_A', 'WAKE_A_REPLY', 'DONE_C', 'WAKE_B', 'FINAL'];
+
+ it('renders every turn in creation order', () => {
+ expect(groupStepIds(flatten(messages))).toEqual(everyStep);
+
+ const groups = parse(messages).contextTree.filter((n) => n.type === 'assistantGroup') as any[];
+ expect(groups).toHaveLength(1);
+ expect(groups[0].children.map((step: { id: string }) => step.id)).toEqual(everyStep);
+ });
+
+ it('keeps each wake-up’s own signal on its block', () => {
+ const group = flatten(messages).find((m) => m.role === ('assistantGroup' as any)) as any;
+ const signals = Object.fromEntries(
+ group.children.map((block: any) => [block.id, block.metadata?.signal?.sourceToolCallId]),
+ );
+
+ expect(signals).toEqual({
+ DONE_C: 'agentC',
+ FINAL: undefined,
+ REPLY: undefined,
+ RUN: undefined,
+ WAKE_A: 'agentA',
+ WAKE_A_REPLY: undefined,
+ WAKE_B: 'agentB',
+ });
+ expect(group.metadata?.signal).toBeUndefined();
+ });
+
+ it('keeps a follow-up sent to the spine tail when the text-only wake-up ends the run', () => {
+ const run = messages.filter((m) => !['WAKE_B', 'toolReadB', 'FINAL'].includes(m.id));
+ const flat = flatten([
+ ...run,
+ {
+ content: 'follow-up',
+ createdAt: 200,
+ id: 'u2',
+ parentId: 'WAKE_A_REPLY',
+ role: 'user',
+ updatedAt: 200,
+ },
+ {
+ agentId: 'a',
+ content: 'answer',
+ createdAt: 210,
+ id: 'a2',
+ parentId: 'u2',
+ role: 'assistant',
+ updatedAt: 210,
+ },
+ ]);
+
+ expect(groupStepIds(flat)).toEqual(['RUN', 'REPLY', 'WAKE_A', 'WAKE_A_REPLY', 'DONE_C']);
+ expect(flat.map((m) => m.id)).toEqual(['u1', 'RUN', 'u2', 'a2']);
+ });
+});
diff --git a/packages/conversation-flow/src/transformation/taskCompletionBlocks.ts b/packages/conversation-flow/src/transformation/taskCompletionBlocks.ts
deleted file mode 100644
index 97f41715497..00000000000
--- a/packages/conversation-flow/src/transformation/taskCompletionBlocks.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import type { AssistantContentBlock } from '@lobechat/types';
-
-import type { Message } from '../types';
-
-/**
- * Snapshot post-task-summary turns as content blocks for an AssistantGroup.
- * They render after `<SignalCallbacks>` inside the same group, each through its
- * own `<Group>` that pulls live content from the store by block id (no need to
- * denormalize text here — keeps streaming updates working without an extra
- * refresh). The block keeps the turn's signal lineage, so the renderer can mark
- * which tool's completion woke it.
- */
-export const toTaskCompletionBlocks = (messages: Message[]): AssistantContentBlock[] =>
- messages.map((m) => {
- const block: AssistantContentBlock = {
- content: m.content ?? '',
- id: m.id,
- };
- if (m.error) block.error = m.error;
- if (m.fileList && m.fileList.length > 0) block.fileList = m.fileList;
- if (m.imageList && m.imageList.length > 0) block.imageList = m.imageList;
- if (m.performance) block.performance = m.performance;
- if (m.reasoning) block.reasoning = m.reasoning;
- if (m.usage) block.usage = m.usage;
- const signal = (m.metadata as { signal?: unknown } | null | undefined)?.signal;
- if (signal) block.metadata = { signal };
- return block;
- });
diff --git a/packages/database/src/models/__tests__/messages/visitor.projection.test.ts b/packages/database/src/models/__tests__/messages/visitor.projection.test.ts
index eb9f528ca4f..f2cb01a85af 100644
--- a/packages/database/src/models/__tests__/messages/visitor.projection.test.ts
+++ b/packages/database/src/models/__tests__/messages/visitor.projection.test.ts
@@ -102,7 +102,6 @@ describe('toVisitorMessage', () => {
pluginError: { body: 'x', provider: 'openai' },
pluginState: { model: 'gpt-4o', tool: { name: 'search', usage: {} } },
provider: 'openai',
- taskCompletions: [{ content: 'done', id: 'tc-1', usage: { totalTokens: 5 } }],
taskDetail: {
id: 'td-1',
status: 'success',
@@ -123,7 +122,6 @@ describe('toVisitorMessage', () => {
expect(visitor.pluginError).toEqual({ body: 'x' });
expect(visitor.pluginState).toEqual({ tool: { name: 'search' } });
expect(visitor.taskDetail).toEqual({ id: 'td-1', status: 'success' });
- expect(asRecords(visitor.taskCompletions)[0]).toEqual({ content: 'done', id: 'tc-1' });
});
it('keeps the model snapshot when the share opts in', () => {
diff --git a/packages/database/src/models/message/visitor.ts b/packages/database/src/models/message/visitor.ts
index 58f0603a872..74e458e8a93 100644
--- a/packages/database/src/models/message/visitor.ts
+++ b/packages/database/src/models/message/visitor.ts
@@ -1,5 +1,4 @@
import type {
- AssistantContentBlock,
ChatMessageError,
ChatMessageExtra,
MessageMetadata,
@@ -265,16 +264,6 @@ const sanitizeVisitorSignalCallbacks = (
})),
}));
-/**
- * `taskCompletions[]` blocks are denormalized post-task-summary snapshots built
- * by `FlatListBuilder`, each carrying its own `usage` — the same class of
- * creator spend data as the top-level `usage` field.
- */
-const sanitizeVisitorTaskCompletions = (
- taskCompletions: AssistantContentBlock[] | undefined,
-): AssistantContentBlock[] | undefined =>
- taskCompletions?.map(({ usage: _usage, ...rest }) => rest);
-
/**
* `metadata.usage` / `metadata.cost` are the pre-migration duplicates of the
* (denied) top-level `usage` field — kept on the type only so legacy rows
@@ -358,7 +347,6 @@ export const toVisitorMessage = (
model: undefined,
provider: undefined,
signalCallbacks: sanitizeVisitorSignalCallbacks(message.signalCallbacks),
- taskCompletions: sanitizeVisitorTaskCompletions(message.taskCompletions),
taskDetail: sanitizeVisitorTaskDetail(message.taskDetail),
usage: undefined,
}
@@ -366,7 +354,6 @@ export const toVisitorMessage = (
model: message.model,
provider: message.provider,
signalCallbacks: message.signalCallbacks,
- taskCompletions: message.taskCompletions,
taskDetail: message.taskDetail,
usage: message.usage,
}),
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index c31be19122d..3d12ea6d96b 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -345,19 +345,6 @@ export interface UIChatMessage {
* target member ID for DM messages in group chat
*/
targetId?: string | null;
- /**
- * Post-task summary blocks (). 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/ChatList/utils/messageDeepLink.ts b/src/features/Conversation/ChatList/utils/messageDeepLink.ts
index 7c27b7fafea..f64380eb02f 100644
--- a/src/features/Conversation/ChatList/utils/messageDeepLink.ts
+++ b/src/features/Conversation/ChatList/utils/messageDeepLink.ts
@@ -29,8 +29,6 @@ function messageContainsMessage(message: UIChatMessage, messageId: string): bool
message.id === messageId ||
toolsContainMessage(message.tools, messageId) ||
message.children?.some((block) => assistantBlockContainsMessage(block, messageId)) === true ||
- message.taskCompletions?.some((block) => assistantBlockContainsMessage(block, messageId)) ===
- true ||
message.compressedMessages?.some((child) => messageContainsMessage(child, messageId)) ===
true ||
// Compression members the read path did not hydrate still belong to the group row.
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx
index 531469deaf4..a51468ded7d 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx
@@ -131,7 +131,19 @@ vi.mock('../../../store', () => ({
continueHeteroAfterError: continueHeteroAfterErrorMock,
deleteDBMessage: deleteDBMessageMock,
retryFailedAssistantStep: retryFailedAssistantStepMock,
- dbMessages: [{ id: 'block-1', metadata: { finishType: persistedFinishTypeMock } }],
+ dbMessages: [
+ { id: 'block-1', metadata: { finishType: persistedFinishTypeMock } },
+ {
+ id: 'launcher',
+ tools: [
+ {
+ apiName: 'Agent',
+ arguments: JSON.stringify({ description: 'Outbound audit' }),
+ id: 'call-agent',
+ },
+ ],
+ },
+ ],
heteroOverloadRetryAttempts: {},
internal_beginHeteroOverloadWait: vi.fn(),
internal_endHeteroOverloadWait: vi.fn(),
@@ -153,6 +165,35 @@ describe('AssistantGroup ContentBlock', () => {
persistedFinishTypeMock = undefined;
});
+ it('names the finished task above a wake-up step', () => {
+ const metadata = {
+ signal: { sourceToolCallId: 'call-agent', sourceToolName: 'Agent', type: 'task-completion' },
+ } as any;
+
+ const { rerender } = render(
+ <ContentBlock
+ showTaskCompletionNotice
+ assistantId="assistant-1"
+ content="C is done"
+ id="wake-1"
+ metadata={metadata}
+ />,
+ );
+
+ expect(screen.getByText('taskCompletion.title')).toBeInTheDocument();
+
+ rerender(
+ <ContentBlock
+ assistantId="assistant-1"
+ content="C is done"
+ id="wake-1"
+ metadata={metadata}
+ />,
+ );
+
+ expect(screen.queryByText('taskCompletion.title')).not.toBeInTheDocument();
+ });
+
it('reads the persisted finish reason when the grouped block projection is stale', () => {
persistedFinishTypeMock = 'refusal';
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
index 781eea460bb..4cce33886da 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
@@ -1,4 +1,5 @@
import { Flexbox } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
import { memo, useCallback } from 'react';
import AssistantMessageNotice from '@/business/client/components/AssistantMessageNotice';
@@ -11,7 +12,9 @@ import { dataSelectors, messageStateSelectors, useConversationStore } from '../.
import ImageFileListViewer from '../../components/ImageFileListViewer';
import Reasoning, { hasRenderableReasoning } from '../../components/Reasoning';
import { Tools } from '../Tools';
+import { resolveTaskCompletionSource } from '../utils/taskCompletionSource';
import MessageContent from './MessageContent';
+import TaskCompletionNotice from './TaskCompletionNotice';
import type { RenderableAssistantContentBlock } from './types';
interface ContentBlockProps extends RenderableAssistantContentBlock {
@@ -34,6 +37,7 @@ const ContentBlock = memo<ContentBlockProps>(
hasToolsOverride,
metadata,
projectionKey,
+ showTaskCompletionNotice,
}) => {
const errorContent = useErrorContent(error);
const showImageItems = !!imageList && imageList.length > 0;
@@ -51,6 +55,18 @@ const ContentBlock = memo<ContentBlockProps>(
(s) => s.dbMessages.find((message) => message.id === id)?.metadata?.finishType,
);
const finishType = metadata?.finishType ?? persistedFinishType;
+ // The call that launched the finished task can sit in an earlier step or
+ // an earlier steered turn, so look it up across the topic's messages.
+ const taskCompletionSource = useConversationStore(
+ (s) =>
+ showTaskCompletionNotice
+ ? resolveTaskCompletionSource({ metadata }, s.dbMessages)
+ : undefined,
+ isEqual,
+ );
+ const taskCompletionNotice = taskCompletionSource && (
+ <TaskCompletionNotice {...taskCompletionSource} />
+ );
const hasTools = !!tools?.length;
const showReasoning = hasRenderableReasoning(reasoning) || (!reasoning && isReasoning);
const hasContent = !!content && content !== LOADING_FLAT;
@@ -86,7 +102,14 @@ const ContentBlock = memo<ContentBlockProps>(
// Nothing was streamed before the turn died: the error stands in for the
// whole block.
if (error && (content === LOADING_FLAT || !content)) {
- return errorBlock;
+ return taskCompletionNotice ? (
+ <Flexbox gap={8}>
+ {taskCompletionNotice}
+ {errorBlock}
+ </Flexbox>
+ ) : (
+ errorBlock
+ );
}
// A freshly created step block can mount before anything about it is
@@ -100,6 +123,8 @@ const ContentBlock = memo<ContentBlockProps>(
return (
<Flexbox gap={8} id={domId ?? id}>
+ {taskCompletionNotice}
+
{showReasoning && (
<SafeBoundary>
<Reasoning {...reasoning} id={id} />
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/groupChain.test.ts b/src/features/Conversation/Messages/AssistantGroup/components/groupChain.test.ts
index 977bd4e94ad..7b28cdfe921 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/groupChain.test.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/components/groupChain.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest';
import type { AssistantContentBlock } from '@/types/index';
-import { getChainDurationsMs } from './groupChain';
+import { buildChainView, getChainDurationsMs } from './groupChain';
const blk = (id: string) => ({ content: '', id }) as AssistantContentBlock;
@@ -50,3 +50,47 @@ describe('getChainDurationsMs', () => {
).toEqual([1500, 0]);
});
});
+
+describe('buildChainView task-completion notices', () => {
+ const tool = (id: string) => ({
+ apiName: 'Bash',
+ arguments: '{}',
+ id,
+ identifier: 'claude-code',
+ type: 'default' as const,
+ });
+ const signal = (sourceToolCallId: string) => ({
+ signal: { sourceToolCallId, sourceToolName: 'Agent', type: 'task-completion' },
+ });
+
+ it('marks each wake-up step once, on its first rendered projection', () => {
+ const view = buildChainView(
+ {
+ blocks: [
+ { content: '', id: 'run', tools: [tool('a'), tool('b')] },
+ {
+ content: 'The first subagent is back. Its findings hold up after a spot-check.',
+ id: 'wake',
+ metadata: signal('a'),
+ tools: [tool('c')],
+ },
+ { content: 'B is done, one to go', id: 'done', metadata: signal('b') },
+ { content: '', id: 'wake2', metadata: signal('x'), tools: [tool('d')] },
+ { content: 'final summary', id: 'final' },
+ ] as AssistantContentBlock[],
+ id: 'group',
+ },
+ { hasActiveOperation: false, isGenerating: false },
+ );
+
+ const rendered = view.segments.flatMap((segment) =>
+ segment.kind === 'answer' ? [segment.block] : segment.blocks,
+ );
+
+ expect(rendered.filter((block) => block.id === 'wake')).toHaveLength(2);
+ expect(
+ rendered.filter((block) => block.showTaskCompletionNotice).map((block) => block.id),
+ ).toEqual(['wake', 'done', 'wake2']);
+ expect(rendered.find((block) => block.id === 'wake')?.showTaskCompletionNotice).toBe(true);
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/groupChain.ts b/src/features/Conversation/Messages/AssistantGroup/components/groupChain.ts
index 2b41e8693b8..5a177792ee2 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/groupChain.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/components/groupChain.ts
@@ -5,7 +5,7 @@ import type {
import { partitionAssistantGroupBlocks } from '@lobechat/conversation-flow';
import { LOADING_FLAT } from '@/const/message';
-import type { AssistantContentBlock } from '@/types/index';
+import type { AssistantContentBlock, MessageSignal } from '@/types/index';
import { areWorkflowToolsComplete } from '../toolDisplayNames';
import { isImageBearingTool } from '../toolRenderRules';
@@ -193,11 +193,35 @@ const toRenderableBlock = (block: AssistantGroupSemanticBlock): RenderableAssist
};
};
-const toRenderSegments = (segments: AssistantGroupSegment[]): GroupRenderSegment[] =>
- segments.map((segment) =>
+/**
+ * A step a finished background task woke is preceded by a notice naming that
+ * task. One step can render as several projections (answer + workflow, or one
+ * per tool run), so only the first one in render order carries the notice.
+ */
+const markTaskCompletionNotices = (segments: GroupRenderSegment[]): GroupRenderSegment[] => {
+ const noticed = new Set<string>();
+ const mark = (block: RenderableAssistantContentBlock): RenderableAssistantContentBlock => {
+ const signal = block.metadata?.signal as MessageSignal | undefined;
+ if (signal?.type !== 'task-completion' || noticed.has(block.id)) return block;
+
+ noticed.add(block.id);
+ return { ...block, showTaskCompletionNotice: true };
+ };
+
+ return segments.map((segment) =>
segment.kind === 'answer'
- ? { block: toRenderableBlock(segment.block), kind: 'answer' }
- : { ...segment, blocks: segment.blocks.map(toRenderableBlock) },
+ ? { ...segment, block: mark(segment.block) }
+ : { ...segment, blocks: segment.blocks.map(mark) },
+ );
+};
+
+const toRenderSegments = (segments: AssistantGroupSegment[]): GroupRenderSegment[] =>
+ markTaskCompletionNotices(
+ segments.map((segment) =>
+ segment.kind === 'answer'
+ ? { block: toRenderableBlock(segment.block), kind: 'answer' }
+ : { ...segment, blocks: segment.blocks.map(toRenderableBlock) },
+ ),
);
export const withMarkdownStreamingState = (
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/types.ts b/src/features/Conversation/Messages/AssistantGroup/components/types.ts
index 93ef10c3e88..4129123f8f2 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/types.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/components/types.ts
@@ -6,4 +6,6 @@ export interface RenderableAssistantContentBlock extends AssistantGroupSemanticB
domId?: string;
hasToolsOverride?: boolean;
renderKey?: string;
+ /** Set on the first rendered projection of a wake-up step, so its notice shows once. */
+ showTaskCompletionNotice?: boolean;
}
diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsx
index 69c500e54f8..7193634a6e2 100644
--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx
@@ -5,7 +5,7 @@ import type { AssistantContentBlock, EmojiReaction, UISignalCallbacksBlock } fro
import { Flexbox, Tag } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import type { MouseEventHandler, ReactNode } from 'react';
-import { Fragment, memo, Suspense, useCallback, useMemo } from 'react';
+import { memo, Suspense, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES } from '@/const/messageActionPortal';
@@ -49,10 +49,8 @@ import SignalCallbacks from '../SignalCallbacks';
import FileListViewer from '../User/components/FileListViewer';
import Group from './components/Group';
import { resolveWorkflowExpandLevel } from './components/segments';
-import TaskCompletionNotice from './components/TaskCompletionNotice';
import type { WorkflowExpandLevelDefault } from './components/WorkflowCollapse';
import { buildContinuationChains, collectSignalCallbacks } from './utils/continuations';
-import { resolveTaskCompletionSource } from './utils/taskCompletionSource';
const EditState = dynamic(() => import('./components/EditState'), {
ssr: false,
@@ -102,7 +100,6 @@ const GroupMessage = memo<GroupMessageProps>(
branch,
metadata,
signalCallbacks,
- taskCompletions,
} = item;
const children = useMemo(
() =>
@@ -132,23 +129,6 @@ const GroupMessage = memo<GroupMessageProps>(
() => [...(children ?? []), ...chains.flatMap((chain) => chain.blocks)],
[chains, children],
);
- // One Group per wake-up turn, each preceded by a notice naming the tool
- // whose completion woke it. The block arrays depend on the completions
- // only, so the main chain streaming does not re-render those Groups.
- const completionBlocks = useMemo(
- () =>
- ((taskCompletions as AssistantContentBlock[] | undefined) ?? []).map((block) => [block]),
- [taskCompletions],
- );
- const completionItems = useMemo(
- () =>
- completionBlocks.map((blocks: AssistantContentBlock[]) => ({
- blocks,
- source: resolveTaskCompletionSource(blocks[0]!, allChildren),
- })),
- [allChildren, completionBlocks],
- );
-
// Supervisor messages render the GROUP's identity (avatar + name + 主管 badge)
// rather than the supervisor agent's own bare meta (whose title is literally
// "Supervisor" with no avatar). The flag is a persisted snapshot on the
@@ -177,8 +157,8 @@ const GroupMessage = memo<GroupMessageProps>(
[allChildren],
);
const workRootOperationId = useMemo(
- () => findLatestWorkRootOperationId(metadata, allChildren, taskCompletions),
- [allChildren, metadata, taskCompletions],
+ () => findLatestWorkRootOperationId(metadata, allChildren),
+ [allChildren, metadata],
);
// Codex-style aggregate of files edited this round. Purely derived from the
// group's tool calls (entity-format files are excluded — they surface as
@@ -384,12 +364,11 @@ const GroupMessage = memo<GroupMessageProps>(
onMouseEnter={onMouseEnter}
>
{/*
- 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 ().
+ Wrap main chain + signal callbacks 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 into disconnected sections. Wake-up turns are steps of
+ the main chain, each marked by its own task-completion notice.
*/}
<Flexbox gap={4}>
{children && children.length > 0 && (
@@ -411,19 +390,6 @@ const GroupMessage = memo<GroupMessageProps>(
{allSignalCallbacks.map((block) => (
<SignalCallbacks block={block} key={block.sourceToolMessageId} />
))}
- {completionItems.map(({ blocks, source }) => (
- <Fragment key={blocks[0]!.id}>
- {source && <TaskCompletionNotice {...source} />}
- <Group
- blocks={blocks}
- contentId={blocks[0]!.id}
- defaultWorkflowExpandLevel={workflowExpandLevel}
- disableEditing={disableEditing}
- id={id}
- messageIndex={index}
- />
- </Fragment>
- ))}
</Flexbox>
{aggregatedFileList.length > 0 && (
diff --git a/src/features/Conversation/Messages/AssistantGroup/utils/continuations.test.ts b/src/features/Conversation/Messages/AssistantGroup/utils/continuations.test.ts
index 3fd3655c2d6..009931d7ef3 100644
--- a/src/features/Conversation/Messages/AssistantGroup/utils/continuations.test.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/utils/continuations.test.ts
@@ -21,15 +21,14 @@ const message = (input: Partial<UIChatMessage> & { id: string; role: UIChatMessa
}) as UIChatMessage;
describe('assistant group continuations', () => {
- it('keeps task completion summaries in continuation chains', () => {
+ it('uses a group continuation’s blocks as its chain', () => {
const chains = buildContinuationChains(
[{ groupId: 'group-2', steerUserId: 'steer-1' }],
[
message({
- children: [block('child-1')],
+ children: [block('child-1'), block('task-summary-1')],
id: 'group-2',
role: 'assistantGroup',
- taskCompletions: [block('task-summary-1')],
}),
],
);
diff --git a/src/features/Conversation/Messages/AssistantGroup/utils/continuations.ts b/src/features/Conversation/Messages/AssistantGroup/utils/continuations.ts
index c1b67f637c9..74ed08131b4 100644
--- a/src/features/Conversation/Messages/AssistantGroup/utils/continuations.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/utils/continuations.ts
@@ -16,7 +16,7 @@ export const buildContinuationChains = (
const blocks =
message.role === 'assistant'
? [message as unknown as AssistantContentBlock]
- : [...(message.children ?? []), ...(message.taskCompletions ?? [])];
+ : (message.children ?? []);
return [
{
diff --git a/src/features/Conversation/Messages/AssistantGroup/utils/taskCompletionSource.ts b/src/features/Conversation/Messages/AssistantGroup/utils/taskCompletionSource.ts
index f38605f5c2c..d8e8cb08ce8 100644
--- a/src/features/Conversation/Messages/AssistantGroup/utils/taskCompletionSource.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/utils/taskCompletionSource.ts
@@ -1,4 +1,4 @@
-import type { AssistantContentBlock, MessageSignal } from '@lobechat/types';
+import type { AssistantContentBlock, ChatToolPayload, MessageSignal } from '@lobechat/types';
export interface TaskCompletionSource {
/** The source call's `description` argument, e.g. a subagent's task title. */
@@ -7,6 +7,11 @@ export interface TaskCompletionSource {
toolName: string;
}
+/** Anything that carries tool calls: reply blocks or raw messages. */
+interface ToolCallHost {
+ tools?: Pick<ChatToolPayload, 'apiName' | 'arguments' | 'id'>[] | null;
+}
+
const readDescription = (args?: string): string | undefined => {
if (!args) return;
try {
@@ -17,21 +22,26 @@ const readDescription = (args?: string): string | undefined => {
}
};
+const findToolCall = (hosts: ToolCallHost[], toolCallId: string) => {
+ for (const host of hosts) {
+ const call = host.tools?.find((tool) => tool.id === toolCallId);
+ if (call) return call;
+ }
+};
+
/**
* The long-running tool (a background subagent, Bash, Monitor…) whose
- * completion woke a task-completion turn, looked up among the reply's own
- * tool calls so the notice can name it. Undefined for any other block.
+ * completion woke a task-completion turn, looked up among the given tool-call
+ * hosts so the notice can name it. Undefined for any other block.
*/
export const resolveTaskCompletionSource = (
- block: AssistantContentBlock,
- replyBlocks: AssistantContentBlock[],
+ block: Pick<AssistantContentBlock, 'metadata'>,
+ hosts: ToolCallHost[],
): TaskCompletionSource | undefined => {
const signal = block.metadata?.signal as MessageSignal | undefined;
if (signal?.type !== 'task-completion') return;
- const sourceCall = replyBlocks
- .flatMap((replyBlock) => replyBlock.tools ?? [])
- .find((tool) => tool.id === signal.sourceToolCallId);
+ const sourceCall = findToolCall(hosts, signal.sourceToolCallId);
return {
description: readDescription(sourceCall?.arguments),
diff --git a/src/features/Conversation/Messages/index.tsx b/src/features/Conversation/Messages/index.tsx
index 546dd8c9dfc..38782dd0019 100644
--- a/src/features/Conversation/Messages/index.tsx
+++ b/src/features/Conversation/Messages/index.tsx
@@ -191,7 +191,7 @@ const MessageItem = memo<MessageItemProps>(
case 'supervisor': {
// Supervisor messages render through the rich AssistantGroup component
- // (workflow collapse / taskCompletions / signalCallbacks) — it swaps in
+ // (workflow collapse / signalCallbacks) — it swaps in
// the group's avatar + name + 主管 badge when the message is a supervisor
// turn. Keeps a single code path instead of a thinner duplicate.
return (
diff --git a/src/features/Conversation/store/slices/data/selectors.ts b/src/features/Conversation/store/slices/data/selectors.ts
index adec0d9d6cb..05ff9ad631b 100644
--- a/src/features/Conversation/store/slices/data/selectors.ts
+++ b/src/features/Conversation/store/slices/data/selectors.ts
@@ -259,16 +259,6 @@ 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>`
- // (). 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;