🤯 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
⚡️ perf(conversation-flow): keep parse linear and stack-safe on long agent topics (#20242)
Tsukie9d5e47844e7
diff --git a/packages/conversation-flow/src/__tests__/deepChain.test.ts b/packages/conversation-flow/src/__tests__/deepChain.test.tsindex 739eaac891b..79bbf6fe891 100644--- a/packages/conversation-flow/src/__tests__/deepChain.test.ts+++ b/packages/conversation-flow/src/__tests__/deepChain.test.ts@@ -67,9 +67,9 @@ const buildChain = (rounds: number, stepsPerRound: number, withTools = false): Mreturn messages;};-// These assert stack depth, not speed: parse still rescans the transcript per-// chain step, so a loaded parallel run can take several seconds here.-describe('parse on deep message chains', { timeout: 30_000 }, () => {+// These assert stack depth. Chain collection looks steps up through per-parse+// indexes rather than rescanning the transcript, so they also stay fast.+describe('parse on deep message chains', () => {// The recursive walk overflowed Node's stack from ~2,000 plain / ~3,000// tool-call messages; browsers hit it near 1,200 inside a React render.it('parses a 4,000-message plain chain without overflowing the stack', () => {@@ -94,4 +94,15 @@ describe('parse on deep message chains', { timeout: 30_000 }, () => {);expect(result.flatList.at(-1)?.children).toHaveLength(10);});++ it('parses one agent run of 3,000 tool steps without overflowing the stack', () => {+ // A single run keeps every step inside one assistant group, so the group's+ // own chain walks see the whole depth, not just one round of it.+ const messages = buildChain(1, 3000, true);++ const result = parse(messages);++ expect(result.flatList.map((m) => m.role)).toEqual(['user', 'assistantGroup']);+ expect(result.flatList.at(-1)?.children).toHaveLength(3000);+ });});diff --git a/packages/conversation-flow/src/transformation/BranchResolver.ts b/packages/conversation-flow/src/transformation/BranchResolver.tsindex 57dc747561e..8209f459188 100644--- a/packages/conversation-flow/src/transformation/BranchResolver.ts+++ b/packages/conversation-flow/src/transformation/BranchResolver.ts@@ -40,6 +40,10 @@ export class BranchResolver {// Invalid index (> children.length), ignore and continue to other strategies}+ // A lone child is the answer every strategy below lands on; skip their+ // subtree walks, which made long single-path chains quadratic.+ if (idNode.children.length === 1) return idNode.children[0].id;+// Priority 2: A persisted user descendant proves which historical branch the// user actually continued. Prefer the newest such descendant before the// generic "has children" fallback, which otherwise selects an older retried@@ -94,6 +98,10 @@ export class BranchResolver {// Invalid index (> metadataBranchIds.length), ignore and continue to other strategies}+ // A lone child is the answer every strategy below lands on; skip their+ // subtree walks, which made long single-path chains quadratic.+ if (childIds.length === 1) return childIds[0];+// Priority 2: Prefer the branch that the user most recently continued.const latestUserBranchId = this.findBranchContainingLatestUser(childIds,diff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.tsindex bf74a8461cb..9a554d4662f 100644--- a/packages/conversation-flow/src/transformation/MessageCollector.ts+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts@@ -51,6 +51,16 @@ const isCallbackSignal = (sig: MessageSignal | undefined): boolean =>const isTaskCompletionSignal = (sig: MessageSignal | undefined): boolean =>sig?.type === 'task-completion';+/** Lookups over one message array, each list in that array's order. */+interface MessageArrayIndex {+ /** Keyed by the raw `parentId` (not `childrenMap`, which remaps orphans and compressed groups). */+ childrenByParentId: Map<string, Message[]>;+ position: Map<string, number>;+ toolById: Map<string, Message>;+}++const EMPTY_MESSAGES: readonly Message[] = [];+/*** MessageCollector - Handles collection of related messages*@@ -69,6 +79,15 @@ export class MessageCollector {private threadScope: ThreadScope = undefined,) {}+ private scopedMessagesCache?: Message[];++ /**+ * Message arrays handed to the collector are never mutated during a parse, so+ * index each once. Rescanning the whole array per chain step made parse+ * quadratic: a 2,883-message agent topic took 30x longer than with these indexes.+ */+ private readonly arrayIndexes = new WeakMap<readonly Message[], MessageArrayIndex>();+/*** Every message the current scope may walk.*@@ -78,10 +97,36 @@ export class MessageCollector {* group instead of its own bubble.*/private scopedMessages(): Message[] {- const messages = [...this.messageMap.values()];- if (this.threadScope === undefined) return messages;+ this.scopedMessagesCache ??= [...this.messageMap.values()].filter(+ (message) => this.threadScope === undefined || isInThreadScope(message, this.threadScope),+ );+ return this.scopedMessagesCache;+ }++ private messageIndex(messages: readonly Message[]): MessageArrayIndex {+ const cached = this.arrayIndexes.get(messages);+ if (cached) return cached;++ const index: MessageArrayIndex = {+ childrenByParentId: new Map(),+ position: new Map(),+ toolById: new Map(),+ };+ messages.forEach((message, i) => {+ index.position.set(message.id, i);+ if (message.role === 'tool') index.toolById.set(message.id, message);+ if (message.parentId == null) return;++ const siblings = index.childrenByParentId.get(message.parentId);+ if (siblings) siblings.push(message);+ else index.childrenByParentId.set(message.parentId, [message]);+ });+ this.arrayIndexes.set(messages, index);+ return index;+ }- return messages.filter((message) => isInThreadScope(message, this.threadScope));+ private childrenOf(messages: readonly Message[], parentId: string): readonly Message[] {+ return this.messageIndex(messages).childrenByParentId.get(parentId) ?? EMPTY_MESSAGES;}/**@@ -98,9 +143,7 @@ export class MessageCollector {const tools = assistant.tools || [];if (tools.length === 0) return [];- const toolMessagesById = new Map(- messages.filter((m) => m.role === 'tool').map((m) => [m.id, m]),- );+ const toolMessagesById = this.messageIndex(messages).toolById;const collected: Message[] = [];const collectedIds = new Set<string>();@@ -118,8 +161,8 @@ export class MessageCollector {continue;}- const fallbackToolMessage = messages.find(- (m) => m.role === 'tool' && m.parentId === assistant.id && m.tool_call_id === tool.id,+ const fallbackToolMessage = this.childrenOf(messages, assistant.id).find(+ (m) => m.role === 'tool' && m.tool_call_id === tool.id,);if (fallbackToolMessage && !collectedIds.has(fallbackToolMessage.id)) {@@ -297,8 +340,7 @@ export class MessageCollector {let hasFanOutTool = false;for (const toolMsg of toolMessages) {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');+ const hasTaskChild = this.childrenOf(allMessages, toolMsg.id).some((m) => m.role === 'task');if (isCouncil || hasTaskChild) {hasFanOutTool = true;continue;@@ -308,11 +350,14 @@ export class MessageCollector {// Assistant-anchored continuation only counts when this step did not fan out.if (!hasFanOutTool) candidateParentIds.add(currentAssistant.id);- const candidates = allMessages- .filter((m) => m.parentId != null && candidateParentIds.has(m.parentId))+ // Equal timestamps fall back to array order, as a stable sort of the+ // whole array did before the index.+ const { position } = this.messageIndex(allMessages);+ 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))- .sort((a, b) => a.createdAt - b.createdAt);+ .sort((a, b) => a.createdAt - b.createdAt || position.get(a.id)! - position.get(b.id)!);const activeId = this.resolveActiveContinuationId(candidates, currentAssistant);if (!activeId) {@@ -443,7 +488,7 @@ export class MessageCollector {}[] = [];for (const toolMsg of allToolMessages) {- const children = allMessages.filter((m) => m.parentId === toolMsg.id);+ const children = this.childrenOf(allMessages, toolMsg.id);const callbacks: Message[] = [];for (const child of children) {if (!isCallbackSignal(getMessageSignal(child))) continue;@@ -483,7 +528,7 @@ export class MessageCollector {collectFlatTaskCompletions(allToolMessages: Message[], allMessages: Message[]): Message[] {const completions: Message[] = [];for (const toolMsg of allToolMessages) {- const children = allMessages.filter((m) => m.parentId === toolMsg.id);+ const children = this.childrenOf(allMessages, toolMsg.id);for (const child of children) {if (!isTaskCompletionSignal(getMessageSignal(child))) continue;completions.push(child);@@ -598,6 +643,50 @@ export class MessageCollector {return activeId ? eligible.find((c) => c.node.id === activeId)?.node : undefined;}+ /**+ * Visit, in order, every tool result along a group's main chain: each tool+ * child of a step, then the steps under its first same-agent, non-signal+ * follower before the next sibling tool. Walked with an explicit stack: one+ * agent run can chain thousands of steps.+ */+ private forEachMainChainTool(+ idNode: IdNode,+ groupAgentId: string | undefined,+ visit: (toolNode: IdNode) => void,+ ): void {+ const visited = new Set<string>();+ // Each frame resumes a step's children where its last descent left off.+ const stack: { children: IdNode[]; index: number }[] = [];+ const enter = (node: IdNode) => {+ if (visited.has(node.id)) return;+ visited.add(node.id);+ stack.push({ children: node.children, index: 0 });+ };++ enter(idNode);+ while (stack.length > 0) {+ const frame = stack.at(-1)!;+ if (frame.index >= frame.children.length) {+ stack.pop();+ continue;+ }++ const child = frame.children[frame.index++];+ if (this.messageMap.get(child.id)?.role !== 'tool') continue;++ visit(child);+ const follower = child.children.find((next) => {+ const nextMsg = this.messageMap.get(next.id);+ return (+ nextMsg?.role === 'assistant' &&+ nextMsg.agentId === groupAgentId &&+ !getMessageSignal(nextMsg)+ );+ });+ if (follower) enter(follower);+ }+ }+/*** Collect signal-callback blocks for an AssistantGroup — one* SignalCallbacksNode per source tool that fired signals (Monitor@@ -614,62 +703,38 @@ export class MessageCollector {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;- }+ this.forEachMainChainTool(idNode, groupAgentId, (child) => {+ // 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);}- };- walk(idNode);+ 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',+ });+ }+ });return blocks;}@@ -693,39 +758,15 @@ export class MessageCollector {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;- }+ 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' });}- };-- walk(idNode);+ });return nodes;}diff --git a/packages/conversation-flow/src/transformation/__tests__/BranchResolver.test.ts b/packages/conversation-flow/src/transformation/__tests__/BranchResolver.test.tsindex 1b66abe0210..a86be33f5d6 100644--- a/packages/conversation-flow/src/transformation/__tests__/BranchResolver.test.ts+++ b/packages/conversation-flow/src/transformation/__tests__/BranchResolver.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import type { IdNode, Message } from '../../types';import { BranchResolver } from '../BranchResolver';@@ -260,5 +260,25 @@ describe('BranchResolver', () => {// activeBranchIndex > childIds.length should be ignored, fallback to defaultexpect(resolver.getActiveBranchIdFromMetadata(message, childIds, childrenMap)).toBe('msg-2');});++ it('returns a lone child without walking its subtree', () => {+ // Every step of a long single-path chain resolves its one continuation+ // here; walking the subtree each time made parse quadratic.+ const message: Message = {+ content: '',+ createdAt: 0,+ id: 'tool-1',+ role: 'tool',+ updatedAt: 0,+ };+ const childrenMap = new Map<string | null, string[]>([['ast-2', ['tool-2']]]);+ const lookup = vi.spyOn(childrenMap, 'get');+ const resolverWithMessages = new BranchResolver(new Map([['tool-1', message]]));++ expect(+ resolverWithMessages.getActiveBranchIdFromMetadata(message, ['ast-2'], childrenMap),+ ).toBe('ast-2');+ expect(lookup).not.toHaveBeenCalled();+ });});});diff --git a/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts b/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.tsindex 3757b2a66b0..39cf10edb68 100644--- a/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts+++ b/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts@@ -592,6 +592,25 @@ describe('MessageCollector', () => {expect(allToolMessages.map((m) => m.id)).toEqual(['tool-1', 'tool-2']);});+ it('breaks a createdAt tie between continuation parents by message order', () => {+ const astRoot = mkAssistant('ast-root', { parentId: 'user-1', tools: [bashTool('tc-1')] });+ const tool = mkTool('tool-1', { parentId: 'ast-root', tool_call_id: 'tc-1' });+ // Same timestamp, one assistant-anchored and one tool-anchored: the one+ // earlier in the message list wins, whichever parent it hangs off.+ const astAnchored = mkAssistant('ast-anchored', { createdAt: 5, parentId: 'ast-root' });+ const toolAnchored = mkAssistant('ast-tool-anchored', { createdAt: 5, parentId: 'tool-1' });++ const allMessages: Message[] = [astRoot, tool, astAnchored, toolAnchored];+ const collector = new MessageCollector(new Map(), new Map());++ const assistantChain: Message[] = [];+ const processedIds = new Set<string>();+ collector.collectAssistantChain(astRoot, allMessages, assistantChain, [], processedIds);++ expect(assistantChain.map((m) => m.id)).toEqual(['ast-root', 'ast-anchored']);+ expect(processedIds.has('ast-tool-anchored')).toBe(true);+ });+it('uses the latest user descendant when the default resolver selects a continuation', () => {const astRoot = mkAssistant('ast-root', {parentId: 'user-root',