π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(conversation-flow): role-aware dual-form message-chain reader (#15908)
Arvin Xub6ad1ed4be92
diff --git a/packages/conversation-flow/src/__tests__/dualForm.test.ts b/packages/conversation-flow/src/__tests__/dualForm.test.tsnew file mode 100644index 00000000000..48109a5cc1c--- /dev/null+++ b/packages/conversation-flow/src/__tests__/dualForm.test.ts@@ -0,0 +1,455 @@+import { describe, expect, it } from 'vitest';++import { parse } from '../parse';+import type { Message } from '../types/shared';++/**+ * Dual-form message-chain reader (LOBE-10445, phase 1)+ *+ * Two persisted chain shapes must parse to equivalent display output:+ *+ * - **tool-anchored (old)**: the next step's assistant hangs off the+ * previous step's *last tool result* (`assistant.parent = lastToolMsgIdEver`).+ * - **assistant-anchored (new)**: the next step's assistant hangs off the+ * *most recent non-tool message* (`assistant.parent = prev assistant/user`),+ * so a tool result and the next assistant are siblings under one assistant.+ *+ * Invariants the role-aware reader enforces:+ * 1. a `tool` message is always inline data of its assistant (both forms).+ * 2. a branch is β₯2 *non-tool* siblings under one parent.+ *+ * Under both invariants the five fixture classes below β old, new, mixed,+ * parallel-tool, regenerate-branch β must produce the same active flatList.+ */++interface StepSpec {+ content?: string;+ id: string;+ /** tool_call_ids; each spawns a tool-result message `${id}__${tc}` */+ tools?: string[];+}++type Form = 'old' | 'new';++/**+ * Build a single linear multi-step assistant turn in either chain form.+ * Tool-result messages always parent to their calling assistant; only the+ * *next assistant's* parent differs between forms.+ */+const buildTurn = (+ userId: string,+ steps: StepSpec[],+ form: Form,+ agentId = 'agent-a',+): Message[] => {+ const msgs: Message[] = [];+ let clock = 0;++ msgs.push({ content: 'q', createdAt: clock++, id: userId, role: 'user', updatedAt: 0 });++ let prevNonToolId = userId; // new-form anchor: most recent non-tool message+ let lastToolIdEver: string | undefined; // old-form anchor: lastToolMsgIdEver++ steps.forEach((step, i) => {+ const parentId =+ i === 0 ? userId : form === 'old' ? (lastToolIdEver ?? prevNonToolId) : prevNonToolId;++ const assistant: Message = {+ agentId,+ content: step.content ?? '',+ createdAt: clock++,+ id: step.id,+ parentId,+ role: 'assistant',+ updatedAt: 0,+ };+ if (step.tools?.length) {+ assistant.tools = step.tools.map((tc) => ({+ apiName: 'x',+ arguments: '{}',+ id: tc,+ identifier: 'x',+ result_msg_id: `${step.id}__${tc}`,+ type: 'default',+ }));+ }+ msgs.push(assistant);++ for (const tc of step.tools ?? []) {+ const toolId = `${step.id}__${tc}`;+ msgs.push({+ content: 'r',+ createdAt: clock++,+ id: toolId,+ parentId: step.id,+ role: 'tool',+ tool_call_id: tc,+ updatedAt: 0,+ });+ lastToolIdEver = toolId;+ }++ prevNonToolId = step.id;+ });++ return msgs;+};++/** Normalize a flatList into a render-shape comparable across chain forms. */+const shape = (flatList: Message[]) =>+ flatList.map((m) => ({+ childIds: (m as any).children?.map((c: any) => ({+ id: c.id,+ tools: (c.tools ?? []).map((t: any) => t.result_msg_id),+ })),+ id: m.id,+ role: m.role,+ }));++describe('dual-form message chain (LOBE-10445)', () => {+ // Canonical turn: u1 β a1(tc1) β a2(tc2) β a3(final, no tool)+ const canonical: StepSpec[] = [+ { content: 'step1', id: 'a1', tools: ['tc1'] },+ { content: 'step2', id: 'a2', tools: ['tc2'] },+ { content: 'final', id: 'a3' },+ ];++ // Expected: user + one merged assistantGroup holding the whole chain.+ const expectedCanonical = [+ { childIds: undefined, id: 'u1', role: 'user' },+ {+ childIds: [+ { id: 'a1', tools: ['a1__tc1'] },+ { id: 'a2', tools: ['a2__tc2'] },+ { id: 'a3', tools: [] },+ ],+ id: 'a1',+ role: 'assistantGroup',+ },+ ];++ it('β tool-anchored (old) β single merged group', () => {+ const result = parse(buildTurn('u1', canonical, 'old'));+ expect(shape(result.flatList)).toEqual(expectedCanonical);+ });++ it('β‘ assistant-anchored (new) β single merged group', () => {+ const result = parse(buildTurn('u1', canonical, 'new'));+ expect(shape(result.flatList)).toEqual(expectedCanonical);+ });++ it('β‘ new form parses equivalent to old form (flatList + contextTree)', () => {+ const oldR = parse(buildTurn('u1', canonical, 'old'));+ const newR = parse(buildTurn('u1', canonical, 'new'));+ expect(shape(newR.flatList)).toEqual(shape(oldR.flatList));+ // contextTree must also collapse to [message(u1), assistantGroup(a1)] in both forms+ expect(newR.contextTree).toEqual(oldR.contextTree);+ expect(newR.contextTree.map((n) => ({ id: n.id, type: n.type }))).toEqual([+ { id: 'u1', type: 'message' },+ { id: 'a1', type: 'assistantGroup' },+ ]);+ });++ it('β’ mixed forms inside one turn β single merged group', () => {+ // a2 attaches old-style (under a1's tool); a3 attaches new-style (under a2)+ const msgs: Message[] = [+ { content: 'q', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 },+ {+ agentId: 'agent-a',+ content: 'step1',+ createdAt: 1,+ id: 'a1',+ parentId: 'u1',+ role: 'assistant',+ tools: [+ {+ apiName: 'x',+ arguments: '{}',+ id: 'tc1',+ identifier: 'x',+ result_msg_id: 'a1__tc1',+ type: 'default',+ },+ ],+ updatedAt: 0,+ },+ {+ content: 'r',+ createdAt: 2,+ id: 'a1__tc1',+ parentId: 'a1',+ role: 'tool',+ tool_call_id: 'tc1',+ updatedAt: 0,+ },+ {+ agentId: 'agent-a',+ content: 'step2',+ createdAt: 3,+ id: 'a2',+ parentId: 'a1__tc1', // OLD-style: under the tool+ role: 'assistant',+ tools: [+ {+ apiName: 'x',+ arguments: '{}',+ id: 'tc2',+ identifier: 'x',+ result_msg_id: 'a2__tc2',+ type: 'default',+ },+ ],+ updatedAt: 0,+ },+ {+ content: 'r',+ createdAt: 4,+ id: 'a2__tc2',+ parentId: 'a2',+ role: 'tool',+ tool_call_id: 'tc2',+ updatedAt: 0,+ },+ {+ agentId: 'agent-a',+ content: 'final',+ createdAt: 5,+ id: 'a3',+ parentId: 'a2', // NEW-style: under the assistant (sibling of a2__tc2)+ role: 'assistant',+ updatedAt: 0,+ },+ ];+ const result = parse(msgs);+ expect(shape(result.flatList)).toEqual(expectedCanonical);+ });++ it('β£ parallel tools then continuation β merged group (both forms)', () => {+ const steps: StepSpec[] = [+ { content: 'step1', id: 'a1', tools: ['tc1', 'tc2'] },+ { content: 'final', id: 'a2' },+ ];+ const expected = [+ { childIds: undefined, id: 'u1', role: 'user' },+ {+ childIds: [+ { id: 'a1', tools: ['a1__tc1', 'a1__tc2'] },+ { id: 'a2', tools: [] },+ ],+ id: 'a1',+ role: 'assistantGroup',+ },+ ];+ expect(shape(parse(buildTurn('u1', steps, 'old')).flatList)).toEqual(expected);+ expect(shape(parse(buildTurn('u1', steps, 'new')).flatList)).toEqual(expected);+ });++ it('β€ regenerate branch: tool siblings do not inflate branch count', () => {+ // user has TWO assistant branches (regenerate). Branch a-x is a tool group;+ // branch a-y is a plain reply. activeBranchIndex picks a-y.+ const msgs: Message[] = [+ {+ content: 'q',+ createdAt: 0,+ id: 'u1',+ metadata: { activeBranchIndex: 1 },+ role: 'user',+ updatedAt: 0,+ },+ {+ agentId: 'agent-a',+ content: 'branch x',+ createdAt: 1,+ id: 'a-x',+ parentId: 'u1',+ role: 'assistant',+ tools: [+ {+ apiName: 'x',+ arguments: '{}',+ id: 'tcx',+ identifier: 'x',+ result_msg_id: 'a-x__tcx',+ type: 'default',+ },+ ],+ updatedAt: 0,+ },+ {+ content: 'r',+ createdAt: 2,+ id: 'a-x__tcx',+ parentId: 'a-x',+ role: 'tool',+ tool_call_id: 'tcx',+ updatedAt: 0,+ },+ {+ agentId: 'agent-a',+ content: 'branch y',+ createdAt: 3,+ id: 'a-y',+ parentId: 'u1',+ role: 'assistant',+ updatedAt: 0,+ },+ ];+ const result = parse(msgs);+ const ids = result.flatList.map((m) => m.id);+ // active branch is a-y (index 1); a-x's tool result must NOT appear as a peer entry+ expect(ids).toEqual(['u1', 'a-y']);+ });++ // A regenerated continuation in the new form: the tool-using assistant a1 has+ // its tool result PLUS two non-tool assistant children (a2a, a2b). These are a+ // branch, so the active one must be chosen via activeBranchIndex β not the+ // earliest β and the inactive one must not leak into the merged group chain.+ const regenContinuation = (activeBranchIndex: number): Message[] => [+ { content: 'q', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 },+ {+ agentId: 'agent-a',+ content: 'step1',+ createdAt: 1,+ id: 'a1',+ metadata: { activeBranchIndex },+ parentId: 'u1',+ role: 'assistant',+ tools: [+ {+ apiName: 'x',+ arguments: '{}',+ id: 'tc1',+ identifier: 'x',+ result_msg_id: 'a1__tc1',+ type: 'default',+ },+ ],+ updatedAt: 0,+ },+ {+ content: 'r',+ createdAt: 2,+ id: 'a1__tc1',+ parentId: 'a1',+ role: 'tool',+ tool_call_id: 'tc1',+ updatedAt: 0,+ },+ // two regenerated continuations, both children of a1 (siblings of the tool)+ {+ agentId: 'agent-a',+ content: 'cont A',+ createdAt: 3,+ id: 'a2a',+ parentId: 'a1',+ role: 'assistant',+ updatedAt: 0,+ },+ {+ agentId: 'agent-a',+ content: 'cont B',+ createdAt: 4,+ id: 'a2b',+ parentId: 'a1',+ role: 'assistant',+ updatedAt: 0,+ },+ ];++ it('β₯ assistant-anchored regenerated continuation follows activeBranchIndex', () => {+ // activeBranchIndex 1 β a2b is the active continuation merged into the group+ const r1 = parse(regenContinuation(1));+ expect(shape(r1.flatList)).toEqual([+ { childIds: undefined, id: 'u1', role: 'user' },+ {+ childIds: [+ { id: 'a1', tools: ['a1__tc1'] },+ { id: 'a2b', tools: [] },+ ],+ id: 'a1',+ role: 'assistantGroup',+ },+ ]);+ expect(r1.flatList.map((m) => m.id)).not.toContain('a2a');++ // activeBranchIndex 0 β the OTHER branch (a2a) is active; not blindly earliest-by-rule+ const r0 = parse(regenContinuation(0));+ expect((r0.flatList[1] as any).children.map((c: any) => c.id)).toEqual(['a1', 'a2a']);+ expect(r0.flatList.map((m) => m.id)).not.toContain('a2b');+ });++ it('β¦ async-task summary with assistant-anchored parent stays out of the group', () => {+ // a1 spawns async tasks under its tool; the follow-up summary uses the NEW+ // assistant-anchored parent (summary.parentId === a1). It must render after+ // the tasks aggregation (group β tasks β summary), NOT inside the group.+ const msgs: Message[] = [+ { content: 'q', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 },+ {+ agentId: 'agent-a',+ content: 'spawning',+ createdAt: 1,+ id: 'a1',+ parentId: 'u1',+ role: 'assistant',+ tools: [+ {+ apiName: 'dispatch',+ arguments: '{}',+ id: 'tc1',+ identifier: 'x',+ result_msg_id: 'a1__tc1',+ type: 'default',+ },+ ],+ updatedAt: 0,+ },+ {+ content: 'r',+ createdAt: 2,+ id: 'a1__tc1',+ parentId: 'a1',+ role: 'tool',+ tool_call_id: 'tc1',+ updatedAt: 0,+ },+ {+ agentId: 'agent-a',+ content: 'task 1',+ createdAt: 3,+ id: 'task-1',+ parentId: 'a1__tc1',+ role: 'task',+ updatedAt: 0,+ },+ {+ agentId: 'agent-a',+ content: 'task 2',+ createdAt: 4,+ id: 'task-2',+ parentId: 'a1__tc1',+ role: 'task',+ updatedAt: 0,+ },+ // assistant-anchored post-task summary+ {+ agentId: 'agent-a',+ content: 'summary',+ createdAt: 5,+ id: 'summary',+ parentId: 'a1',+ role: 'assistant',+ updatedAt: 0,+ },+ ];+ const result = parse(msgs);+ const rows = result.flatList.map((m) => ({ id: m.id, role: m.role }));+ expect(rows).toEqual([+ { id: 'u1', role: 'user' },+ { id: 'a1', role: 'assistantGroup' },+ { id: result.flatList[2].id, role: 'tasks' },+ { id: 'summary', role: 'assistant' },+ ]);+ // the group must contain ONLY a1 β the summary must not be folded inside it+ expect((result.flatList[1] as any).children.map((c: any) => c.id)).toEqual(['a1']);+ });+});diff --git a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts b/packages/conversation-flow/src/transformation/ContextTreeBuilder.tsindex 5c3718ff2a8..39107c796bb 100644--- a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts+++ b/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts@@ -156,8 +156,13 @@ export class ContextTreeBuilder {return;}- // Priority 6: Branch (multiple children)- if (idNode.children.length > 1) {+ // Priority 6: Branch β multiple NON-TOOL children (LOBE-10445 invariant 2).+ // Tool children are inline data of their assistant (handled by Priority 4),+ // never branch candidates.+ const nonToolChildren = idNode.children.filter(+ (child) => this.messageMap.get(child.id)?.role !== 'tool',+ );+ if (nonToolChildren.length > 1) {// Add current message nodeconst messageNode = this.createMessageNode(message);contextTree.push(messageNode);@@ -201,13 +206,13 @@ export class ContextTreeBuilder {private isAssistantGroupNode(message: Message, idNode: IdNode): boolean {if (message.role !== 'assistant') return false;- return (- idNode.children.length > 0 &&- idNode.children.every((child) => {- const childMsg = this.messageMap.get(child.id);- return childMsg?.role === 'tool';- })- );+ // Role-aware (LOBE-10445): an assistant heads a group when it has ANY tool+ // child β not only when ALL children are tools. In the assistant-anchored+ // form the next step's assistant is a sibling of the tool results, so a+ // group head legitimately has a mix of tool + assistant children. (In the+ // old tool-anchored form a tool-using assistant only ever had tool children,+ // so this stays a no-op for legacy data.)+ return idNode.children.some((child) => this.messageMap.get(child.id)?.role === 'tool');}/**diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.tsindex 4c1dc9df21a..20cf7921017 100644--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts@@ -290,6 +290,11 @@ export class FlatListBuilder {// Priority 3a: Compare mode from user message metadataconst childMessages = this.childrenMap.get(message.id) ?? [];+ // Non-tool children only are branch candidates (LOBE-10445 invariant 2):+ // a tool child is inline data of its assistant, never a sibling branch.+ const nonToolChildMessages = childMessages.filter(+ (childId) => this.messageMap.get(childId)?.role !== 'tool',+ );if (this.isCompareMode(message) && childMessages.length > 1) {// Add user messageflatList.push(message);@@ -334,10 +339,10 @@ export class FlatListBuilder {// Priority 3d: User message with branches (multiple assistant children)// Branch indicator should be on the active assistant child message- if (message.role === 'user' && childMessages.length > 1) {+ if (message.role === 'user' && nonToolChildMessages.length > 1) {const activeBranchId = this.branchResolver.getActiveBranchIdFromMetadata(message,- childMessages,+ nonToolChildMessages,this.childrenMap,);@@ -353,7 +358,7 @@ export class FlatListBuilder {flatList.push(message);processedIds.add(message.id);- const activeBranchIndex = childMessages.indexOf(activeBranchId);+ const activeBranchIndex = nonToolChildMessages.indexOf(activeBranchId);// Continue with active branch - check if it's an assistantGroupconst activeBranchMsg = this.messageMap.get(activeBranchId);@@ -384,7 +389,7 @@ export class FlatListBuilder {// Add branch info to the assistantGroup messageconst groupMessageWithBranches = this.createMessageWithBranches(groupMessage,- childMessages.length,+ nonToolChildMessages.length,activeBranchIndex,);flatList.push(groupMessageWithBranches);@@ -404,7 +409,7 @@ export class FlatListBuilder {// Regular assistant message (not assistantGroup) - add branch infoconst activeBranchWithBranches = this.createMessageWithBranches(activeBranchMsg,- childMessages.length,+ nonToolChildMessages.length,activeBranchIndex,);flatList.push(activeBranchWithBranches);@@ -419,10 +424,10 @@ export class FlatListBuilder {// Priority 3e: Assistant message with branches (multiple user children)// Branch indicator should be on the active user child message- if (message.role === 'assistant' && childMessages.length > 1) {+ if (message.role === 'assistant' && nonToolChildMessages.length > 1) {const activeBranchId = this.branchResolver.getActiveBranchIdFromMetadata(message,- childMessages,+ nonToolChildMessages,this.childrenMap,);@@ -438,7 +443,7 @@ export class FlatListBuilder {flatList.push(message);processedIds.add(message.id);- const activeBranchIndex = childMessages.indexOf(activeBranchId);+ const activeBranchIndex = nonToolChildMessages.indexOf(activeBranchId);// Continue with active branch and add branch info to the user childconst activeBranchMsg = this.messageMap.get(activeBranchId);@@ -446,7 +451,7 @@ export class FlatListBuilder {// Add branch info to the active user child messageconst activeBranchWithBranches = this.createMessageWithBranches(activeBranchMsg,- childMessages.length,+ nonToolChildMessages.length,activeBranchIndex,);flatList.push(activeBranchWithBranches);diff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.tsindex 79a3e3cc3a9..77148661911 100644--- a/packages/conversation-flow/src/transformation/MessageCollector.ts+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts@@ -1,4 +1,5 @@import type { ContextNode, IdNode, Message, MessageNode, SignalCallbacksNode } from '../types';+import { BranchResolver } from './BranchResolver';/*** Persisted external-signal lineage on `message.metadata.signal` β@@ -55,6 +56,8 @@ export class MessageCollector {constructor(private messageMap: Map<string, Message>,private childrenMap: Map<string | null, string[]>,+ // BranchResolver is stateless; default keeps existing 2-arg call sites working.+ private branchResolver: BranchResolver = new BranchResolver(),) {}/**@@ -132,59 +135,114 @@ export class MessageCollector {const toolMessages = this.collectToolMessages(currentAssistant, allMessages);allToolMessages.push(...toolMessages);- // Find next assistant after tools+ // Find the next step's assistant. Role-aware dual-form walk (LOBE-10445):+ // the continuation may hang off this assistant directly (assistant-anchored+ // / new form) OR off one of its tool results (tool-anchored / old form).+ const continuation = this.findFlatChainContinuation(+ currentAssistant,+ toolMessages,+ allMessages,+ processedIds,+ groupAgentId,+ );+ if (!continuation) return;++ if (continuation.tools && continuation.tools.length > 0) {+ // Continue the chain (recursion marks it processed at the top)+ this.collectAssistantChain(+ continuation,+ allMessages,+ assistantChain,+ allToolMessages,+ processedIds,+ );+ } else {+ // Final assistant without tools β caller marks the whole chain processed+ assistantChain.push(continuation);+ }+ }++ /**+ * Find the next assistant in a tool-using step's chain (flat variant).+ *+ * Dual-form aware: candidates are gathered from BOTH the assistant's own+ * non-tool children (new assistant-anchored form, where the next assistant is+ * a sibling of the tool results) AND each tool result's children (old+ * tool-anchored form).+ *+ * Two guards keep the assistant-anchored candidate honest:+ * - **Fan-out guard**: if any tool hosts an AgentCouncil or spawned async+ * tasks, the chain does NOT continue linearly through this step β neither+ * through that tool's children nor through an assistant-anchored follow-up+ * (a post-task summary whose `parentId === currentAssistant.id`). Those are+ * emitted by the council/tasks flow AFTER the group, so the assistant seed+ * is dropped and the chain ends here.+ * - **Branch resolution**: when >1 non-tool same-agent continuations share a+ * parent (e.g. a regenerated continuation), pick the active one via+ * `activeBranchIndex` instead of blindly taking the earliest.+ */+ private findFlatChainContinuation(+ currentAssistant: Message,+ toolMessages: Message[],+ allMessages: Message[],+ processedIds: Set<string>,+ groupAgentId: string | undefined,+ ): Message | undefined {+ const candidateParentIds = new Set<string>();+ let hasFanOutTool = false;for (const toolMsg of toolMessages) {- // Stop if tool message has agentCouncil mode - its children belong to AgentCouncil- if ((toolMsg.metadata as any)?.agentCouncil === true) {+ const isCouncil = (toolMsg.metadata as any)?.agentCouncil === true;+ const toolChildren = allMessages.filter((m) => m.parentId === toolMsg.id);+ const hasTaskChild = toolChildren.some((m) => m.role === 'task');+ if (isCouncil || hasTaskChild) {+ hasFanOutTool = true;continue;}+ candidateParentIds.add(toolMsg.id);+ }+ // Assistant-anchored continuation only counts when this step did not fan out.+ if (!hasFanOutTool) candidateParentIds.add(currentAssistant.id);- const nextMessages = allMessages.filter((m) => m.parentId === toolMsg.id);+ const candidates = allMessages+ .filter((m) => m.parentId != null && candidateParentIds.has(m.parentId))+ .filter((m) => m.role !== 'tool' && !processedIds.has(m.id))+ .filter((m) => m.role === 'assistant' && m.agentId === groupAgentId && !getMessageSignal(m))+ .sort((a, b) => a.createdAt - b.createdAt);- // Stop if there are task children - they should be handled separately, not part of AssistantGroup- // This ensures that messages after a task are not merged into the AssistantGroup before the task- const taskChildren = nextMessages.filter((m) => m.role === 'task');- if (taskChildren.length > 0) {- continue;- }+ const activeId = this.resolveActiveContinuationId(candidates);+ return activeId ? candidates.find((m) => m.id === activeId) : undefined;+ }- for (const nextMsg of nextMessages) {- // Skip an already-collected follower: a duplicated tool_call_id can make- // collectToolMessages surface an earlier turn's tool result first, and- // returning after that no-op recursion would drop this assistant's real- // continuation under a later tool.- if (processedIds.has(nextMsg.id)) continue;- // 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 () β they're a- // side-channel under the same parent tool and get collected- // separately by `collectFlatSignalCallbacks`.- if (getMessageSignal(nextMsg)) continue;-- if (- nextMsg.role === 'assistant' &&- nextMsg.tools &&- nextMsg.tools.length > 0 &&- isSameAgent- ) {- // Continue the chain only for same agent- this.collectAssistantChain(- nextMsg,- allMessages,- assistantChain,- allToolMessages,- processedIds,- );- return;- } else if (nextMsg.role === 'assistant' && isSameAgent) {- // Final assistant without tools (same agent)- assistantChain.push(nextMsg);- return;- }- // If different agentId, don't add to chain - let it be processed separately- }- }+ /**+ * Pick the active continuation among same-step candidates (sorted by+ * createdAt). One candidate β a linear continuation. >1 non-tool siblings+ * under a single parent β a branch (e.g. a regenerated continuation), so+ * consult the parent's `activeBranchIndex` via BranchResolver instead of+ * blindly taking the earliest β otherwise the inactive branch is silently+ * chosen and the active one dropped. Returns undefined when there is no+ * continuation, or the active branch is an optimistic not-yet-created one.+ */+ private resolveActiveContinuationId(sortedCandidates: Message[]): string | undefined {+ if (sortedCandidates.length === 0) return undefined;+ const earliest = sortedCandidates[0];+ const parentId = earliest.parentId;+ if (parentId == null) return earliest.id;++ // Branch siblings share one parent; only those under the earliest+ // candidate's parent participate in this branch decision. Use childrenMap+ // (creation) order so it lines up with how activeBranchIndex is assigned.+ const eligibleIds = new Set(sortedCandidates.map((m) => m.id));+ const siblingIds = (this.childrenMap.get(parentId) ?? []).filter((id) => eligibleIds.has(id));+ if (siblingIds.length <= 1) return earliest.id;++ const parentMsg = this.messageMap.get(parentId);+ if (!parentMsg) return earliest.id;++ return this.branchResolver.getActiveBranchIdFromMetadata(+ parentMsg,+ siblingIds,+ this.childrenMap,+ );}/**@@ -296,41 +354,61 @@ export class MessageCollector {}children.push(messageNode);- // Find next assistant message after tools+ // Find the next step's assistant (dual-form aware, see findChainContinuationNode)+ const nextNode = this.findChainContinuationNode(idNode, agentId);+ if (nextNode) {+ const nextMsg = this.messageMap.get(nextNode.id)!;+ this.collectAssistantGroupMessages(nextMsg, nextNode, children, agentId);+ }+ }++ /**+ * Find the IdNode of the next assistant in a tool-using step's chain+ * (contextTree variant of {@link findFlatChainContinuation}). Same fan-out+ * 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.+ */+ private findChainContinuationNode(idNode: IdNode, groupAgentId?: string): IdNode | undefined {+ const candidateNodes: IdNode[] = [];+ let hasFanOutTool = false;++ // (b) each tool result's children (old form); detect fan-out toolsfor (const toolNode of idNode.children) {const toolMsg = this.messageMap.get(toolNode.id);if (toolMsg?.role !== 'tool') continue;-- // Stop if tool message has agentCouncil mode - its children belong to AgentCouncil- if ((toolMsg.metadata as any)?.agentCouncil === true) {- continue;- }-- // Stop if there are ANY task children - they should be processed separately, not part of AssistantGroup- // This ensures that messages after a task are not merged into the AssistantGroup before the task- const taskChildren = toolNode.children.filter((child) => {- const childMsg = this.messageMap.get(child.id);- return childMsg?.role === 'task';- });- if (taskChildren.length > 0) {+ const isCouncil = (toolMsg.metadata as any)?.agentCouncil === true;+ const hasTaskChild = toolNode.children.some(+ (child) => this.messageMap.get(child.id)?.role === 'task',+ );+ if (isCouncil || hasTaskChild) {+ hasFanOutTool = true;continue;}+ candidateNodes.push(...toolNode.children);+ }- // Find the next main-chain assistant under this tool. Signal-tagged- // toolless siblings (Monitor callbacks etc., ) 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+ // (a) the assistant's own non-tool children (new form) β only when the step+ // did not fan out (otherwise they are post-fan-out summaries, not inline)+ if (!hasFanOutTool) {+ for (const child of idNode.children) {+ if (this.messageMap.get(child.id)?.role === 'tool') continue;+ candidateNodes.push(child);}}++ 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),+ )+ .sort((a, b) => a.msg!.createdAt - b.msg!.createdAt);++ const activeId = this.resolveActiveContinuationId(eligible.map((c) => c.msg!));+ return activeId ? eligible.find((c) => c.node.id === activeId)?.node : undefined;}/**@@ -503,51 +581,21 @@ export class MessageCollector {* Only follows messages from the SAME agent (matching agentId)*/findLastNodeInAssistantGroup(idNode: IdNode, groupAgentId?: string): IdNode | null {- // Check if has tool children- const toolChildren = idNode.children.filter((child) => {- const childMsg = this.messageMap.get(child.id);- return childMsg?.role === 'tool';- });+ // Walk the chain to its next step (dual-form aware, see findChainContinuationNode)+ const nextNode = this.findChainContinuationNode(idNode, groupAgentId);+ if (nextNode) {+ return this.findLastNodeInAssistantGroup(nextNode, groupAgentId);+ }+ // No further same-agent assistant. If this step still owns tool results+ // (e.g. the last tool hosts an AgentCouncil / tasks), return the last tool+ // node so findNextAfterTools can inspect it; otherwise this node is the tail.+ const toolChildren = idNode.children.filter(+ (child) => this.messageMap.get(child.id)?.role === 'tool',+ );if (toolChildren.length === 0) {return idNode;}-- // Check if any tool has an assistant child with the same agentId- for (const toolNode of toolChildren) {- const toolMsg = this.messageMap.get(toolNode.id);-- // Stop if tool message has agentCouncil mode - its children belong to AgentCouncil- if ((toolMsg?.metadata as any)?.agentCouncil === true) {- continue;- }-- // Stop if there are ANY task children - they should be processed separately, not part of AssistantGroup- // This ensures that messages after a task are not merged into the AssistantGroup before the task- const taskNodes = toolNode.children.filter((child) => {- const childMsg = this.messageMap.get(child.id);- return childMsg?.role === 'task';- });- if (taskNodes.length > 0) {- continue;- }-- // Pick the next main-chain assistant under this tool. Mirror the- // skip rule used by `collectAssistantGroupMessages`: signal-tagged- // toolless siblings (Monitor callbacks etc., ) 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);- if (nextMsg?.role !== 'assistant') continue;- if (nextMsg.agentId !== groupAgentId) continue;- if (getMessageSignal(nextMsg)) continue;- return this.findLastNodeInAssistantGroup(nextChild, groupAgentId);- }- }-- // No more assistant messages from the same agent, return the last tool nodereturn toolChildren.at(-1) ?? null;}}diff --git a/packages/conversation-flow/src/transformation/index.ts b/packages/conversation-flow/src/transformation/index.tsindex 52053091b91..0fb091a3273 100644--- a/packages/conversation-flow/src/transformation/index.ts+++ b/packages/conversation-flow/src/transformation/index.ts@@ -31,7 +31,11 @@ export class Transformer {// Initialize utility classesthis.branchResolver = new BranchResolver();- this.messageCollector = new MessageCollector(this.messageMap, helperMaps.childrenMap);+ this.messageCollector = new MessageCollector(+ this.messageMap,+ helperMaps.childrenMap,+ this.branchResolver,+ );this.messageTransformer = new MessageTransformer();// Initialize builder classes