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(conversation-flow): iterative message-tree traversal to avoid mobile stack overflow (#17457)

Tsukia4cc9bbe6d16
diff --git a/packages/conversation-flow/src/__tests__/deepChain.test.ts b/packages/conversation-flow/src/__tests__/deepChain.test.ts
new file mode 100644
index 00000000000..ba17c43e23c
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/deepChain.test.ts
@@ -0,0 +1,237 @@
+import { describe, expect, it } from 'vitest';
+
+import { parse } from '../parse';
+import type { Message } from '../types';
+
+/**
+ * Production topology: every user turn chains off the previous assistant
+ * (publicApi.ts sets parentId = lastDisplayMessageId), so the message "tree" is
+ * really a linked list whose depth equals the conversation length. Traversal
+ * must not consume stack proportional to that depth.
+ */
+const linkedChain = (turns: number, opts: { tools?: boolean } = {}): Message[] => {
+ const messages: Message[] = [];
+ let previousAssistantId: string | undefined;
+
+ for (let turn = 0; turn < turns; turn++) {
+ const userId = `u-${turn}`;
+ const assistantId = `a-${turn}`;
+
+ messages.push({
+ content: `question ${turn}`,
+ createdAt: turn * 10,
+ id: userId,
+ parentId: previousAssistantId ?? null,
+ role: 'user',
+ updatedAt: turn * 10,
+ } as Message);
+
+ const assistant = {
+ content: `answer ${turn}`,
+ createdAt: turn * 10 + 1,
+ id: assistantId,
+ parentId: userId,
+ role: 'assistant',
+ updatedAt: turn * 10 + 1,
+ } as Message;
+
+ if (opts.tools && turn % 4 === 0) {
+ const toolCallId = `call-${turn}`;
+ const toolMessageId = `t-${turn}`;
+ (assistant as any).tools = [
+ {
+ apiName: 'search',
+ arguments: '{}',
+ id: toolCallId,
+ identifier: 'bench-plugin',
+ result_msg_id: toolMessageId,
+ type: 'default',
+ },
+ ];
+ messages.push(assistant, {
+ content: `tool result ${turn}`,
+ createdAt: turn * 10 + 2,
+ id: toolMessageId,
+ parentId: assistantId,
+ role: 'tool',
+ tool_call_id: toolCallId,
+ updatedAt: turn * 10 + 2,
+ } as Message);
+ } else {
+ messages.push(assistant);
+ }
+
+ previousAssistantId = assistantId;
+ }
+
+ return messages;
+};
+
+/**
+ * 3000 turns / 6000 rows sits well clear of every stack ceiling this engine has
+ * had: the fully recursive walk died around 1.6k rows, and converting only
+ * FlatListBuilder moved that to roughly 2.4k. Anything that reintroduces
+ * depth-per-message in any of the three walks (structuring, contextTree,
+ * flatList) fails here.
+ */
+const TURNS = 3000;
+
+/**
+ * A single unbroken agent run: every step calls a tool and the next step hangs
+ * off that tool's result, so the whole thing collapses into ONE assistant group.
+ * Chain collection walks step by step, so its cost must not be stack depth.
+ */
+const singleToolChain = (steps: number): Message[] => {
+ const messages: Message[] = [
+ {
+ content: 'do the long thing',
+ createdAt: 0,
+ id: 'user-1',
+ parentId: null,
+ role: 'user',
+ updatedAt: 0,
+ } as unknown as Message,
+ ];
+
+ let parentId = 'user-1';
+ for (let step = 0; step < steps; step++) {
+ const assistantId = `ast-${step}`;
+ const toolMessageId = `tool-${step}`;
+ const toolCallId = `call-${step}`;
+
+ messages.push({
+ agentId: 'agent-1',
+ content: `step ${step}`,
+ createdAt: step * 2 + 1,
+ id: assistantId,
+ parentId,
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'run',
+ arguments: '{}',
+ id: toolCallId,
+ identifier: 'shell',
+ result_msg_id: toolMessageId,
+ type: 'default',
+ },
+ ],
+ updatedAt: step * 2 + 1,
+ } as unknown as Message);
+
+ messages.push({
+ content: `result ${step}`,
+ createdAt: step * 2 + 2,
+ id: toolMessageId,
+ parentId: assistantId,
+ role: 'tool',
+ tool_call_id: toolCallId,
+ updatedAt: step * 2 + 2,
+ } as Message);
+
+ parentId = toolMessageId;
+ }
+
+ return messages;
+};
+
+/**
+ * Every assistant carries two user replies, so each turn nests a branch inside
+ * the previous branch's subtree — i.e. the user regenerated at every turn.
+ *
+ * This is the one walk still bounded by stack depth: a branch node's output is
+ * itself nested (`branches: ContextNode[][]`), so `createBranchNode` re-enters
+ * the linear walk per branch. It holds to roughly 800 levels and fails around
+ * 1600; 500 here guards against that ceiling dropping.
+ */
+const nestedBranches = (levels: number): Message[] => {
+ const messages: Message[] = [
+ {
+ content: 'q',
+ createdAt: 0,
+ id: 'u0',
+ parentId: null,
+ role: 'user',
+ updatedAt: 0,
+ } as unknown as Message,
+ ];
+
+ let parentId = 'u0';
+ for (let level = 0; level < levels; level++) {
+ messages.push({
+ content: 'r',
+ createdAt: level * 3 + 1,
+ id: `a${level}`,
+ metadata: { activeBranchIndex: 0 },
+ parentId,
+ role: 'assistant',
+ updatedAt: level * 3 + 1,
+ } as unknown as Message);
+ messages.push({
+ content: 'follow-up',
+ createdAt: level * 3 + 2,
+ id: `u${level}x`,
+ parentId: `a${level}`,
+ role: 'user',
+ updatedAt: level * 3 + 2,
+ } as Message);
+ messages.push({
+ content: 'regenerated follow-up',
+ createdAt: level * 3 + 3,
+ id: `u${level}y`,
+ parentId: `a${level}`,
+ role: 'user',
+ updatedAt: level * 3 + 3,
+ } as Message);
+ parentId = `u${level}x`;
+ }
+
+ return messages;
+};
+
+describe('deep chain traversal', () => {
+ it('should parse deeply nested branches', () => {
+ expect(() => parse(nestedBranches(500))).not.toThrow();
+ });
+
+ it('should collect one very long assistant run without exhausting the stack', () => {
+ const messages = singleToolChain(3000);
+
+ expect(() => parse(messages)).not.toThrow();
+
+ const result = parse(messages);
+ // user row + one group bubble holding every step
+ expect(result.flatList).toHaveLength(2);
+ expect((result.flatList[1] as any).children).toHaveLength(3000);
+ });
+
+ it('should parse a deep linked chain without exhausting the stack', () => {
+ const messages = linkedChain(TURNS);
+ expect(messages).toHaveLength(TURNS * 2);
+
+ expect(() => parse(messages)).not.toThrow();
+ expect(parse(messages).flatList).toHaveLength(TURNS * 2);
+ });
+
+ it('should parse a deep tool-bearing chain without exhausting the stack', () => {
+ const messages = linkedChain(TURNS, { tools: true });
+
+ expect(() => parse(messages)).not.toThrow();
+ });
+
+ it('should keep chain order stable across the whole conversation', () => {
+ const result = parse(linkedChain(TURNS));
+ const ids = result.flatList.map((m) => m.id);
+
+ expect(ids[0]).toBe('u-0');
+ expect(ids[1]).toBe('a-0');
+ expect(ids.at(-2)).toBe(`u-${TURNS - 1}`);
+ expect(ids.at(-1)).toBe(`a-${TURNS - 1}`);
+ });
+
+ it('should build a contextTree for a deep chain', () => {
+ const result = parse(linkedChain(TURNS));
+
+ expect(result.contextTree).toHaveLength(TURNS * 2);
+ });
+});
diff --git a/packages/conversation-flow/src/__tests__/edgeCases.test.ts b/packages/conversation-flow/src/__tests__/edgeCases.test.ts
new file mode 100644
index 00000000000..f5da4f6bbc8
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/edgeCases.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+
+import { parse } from '../parse';
+import { inputs } from './fixtures';
+
+/**
+ * Characterization tests for flatten() paths the hand-written scenario fixtures
+ * never reached. Each case targets a specific uncovered branch in
+ * FlatListBuilder; assertions pin the observable shape so a traversal rewrite
+ * has to reproduce it.
+ */
+describe('flatList edge cases', () => {
+ it('should treat the first message as virtual root when every message has a parent', () => {
+ const result = parse(inputs.edgeCases.orphanThreadRoot);
+
+ expect(result.flatList.map((m) => m.id)).toEqual([
+ 'msg-thread-user-1',
+ 'msg-thread-assistant-1',
+ 'msg-thread-user-2',
+ 'msg-thread-assistant-2',
+ ]);
+ });
+
+ it('should fold a task-completion signal turn into the assistant group', () => {
+ const result = parse(inputs.edgeCases.taskCompletionSignal);
+
+ expect(result.flatList).toHaveLength(2);
+ expect(result.flatList[0].role).toBe('user');
+
+ const group = result.flatList[1] as any;
+ expect(group.role).toBe('assistantGroup');
+ expect(group.children.map((c: any) => c.id)).toEqual(['msg-assistant-1']);
+ // the post-task summary rides in its own field, rendered after the group body
+ expect(group.taskCompletions.map((c: any) => c.id)).toEqual(['msg-completion-1']);
+ });
+
+ it('should emit an assistant group sibling alongside aggregated tasks', () => {
+ const result = parse(inputs.edgeCases.tasksWithAssistantGroupSibling);
+
+ const roles = result.flatList.map((m) => m.role);
+ expect(roles).toEqual(['user', 'assistantGroup', 'tasks', 'assistantGroup']);
+ expect((result.flatList[2] as any).tasks).toHaveLength(2);
+ expect((result.flatList[3] as any).children.map((c: any) => c.id)).toEqual([
+ 'msg-assistant-followup',
+ ]);
+ });
+
+ it('should surface a supervisor summary parented to a task message', () => {
+ const result = parse(inputs.edgeCases.taskChildSupervisorSummary);
+
+ const summary = result.flatList.find((m) => m.id === 'msg-supervisor-summary');
+ expect(summary).toBeDefined();
+ expect(summary!.role).toBe('supervisor');
+ expect(summary!.content).toBe('');
+ expect((summary as any).children).toHaveLength(1);
+ expect((summary as any).children[0].content).toContain('Both audits are in');
+ });
+
+ it('should drop branch metadata when the active assistant branch is not created yet', () => {
+ const result = parse(inputs.edgeCases.optimisticAssistantBranch);
+
+ expect(result.flatList.map((m) => m.id)).toEqual(['msg-user-1', 'msg-assistant-1']);
+ expect((result.flatList[1] as any).branches).toBeUndefined();
+ });
+});
diff --git a/packages/conversation-flow/src/__tests__/fixtures/index.ts b/packages/conversation-flow/src/__tests__/fixtures/index.ts
index cc922f7ebda..4ed66760d22 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/index.ts
+++ b/packages/conversation-flow/src/__tests__/fixtures/index.ts
@@ -1,22 +1,7 @@
import type { Message, ParseResult } from '../../types';
-// Input fixtures
-import { agentCouncil as agentCouncilInputs } from './inputs/agentCouncil';
-import { agentGroup as agentGroupInputs } from './inputs/agentGroup';
-import assistantChainWithFollowupInput from './inputs/assistant-chain-with-followup.json';
-import { assistantGroup as assistantGroupInputs } from './inputs/assistantGroup';
-import { branch as branchInputs } from './inputs/branch';
-import { compare as compareInputs } from './inputs/compare';
-import linearConversationInput from './inputs/linear-conversation.json';
-import { tasks as tasksInputs } from './inputs/tasks';
-// Output fixtures
-import { agentCouncil as agentCouncilOutputs } from './outputs/agentCouncil';
-import { agentGroup as agentGroupOutputs } from './outputs/agentGroup';
-import assistantChainWithFollowupOutput from './outputs/assistant-chain-with-followup.json';
-import { assistantGroup as assistantGroupOutputs } from './outputs/assistantGroup';
-import { branch as branchOutputs } from './outputs/branch';
-import { compare as compareOutputs } from './outputs/compare';
-import linearConversationOutput from './outputs/linear-conversation.json';
-import { tasks as tasksOutputs } from './outputs/tasks';
+
+export { inputs } from './inputs';
+export { outputs } from './outputs';
/**
* Serialized parse result type
@@ -26,31 +11,3 @@ export interface SerializedParseResult {
flatList: ParseResult['flatList'];
messageMap: Record<string, Message>;
}
-
-/**
- * Test input fixtures - raw messages from database
- */
-export const inputs = {
- agentCouncil: agentCouncilInputs,
- agentGroup: agentGroupInputs,
- assistantChainWithFollowup: assistantChainWithFollowupInput as Message[],
- assistantGroup: assistantGroupInputs,
- branch: branchInputs,
- compare: compareInputs,
- linearConversation: linearConversationInput as Message[],
- tasks: tasksInputs,
-};
-
-/**
- * Test output fixtures - expected parse results
- */
-export const outputs = {
- agentCouncil: agentCouncilOutputs,
- agentGroup: agentGroupOutputs,
- assistantChainWithFollowup: assistantChainWithFollowupOutput as unknown as SerializedParseResult,
- assistantGroup: assistantGroupOutputs,
- branch: branchOutputs,
- compare: compareOutputs,
- linearConversation: linearConversationOutput as unknown as SerializedParseResult,
- tasks: tasksOutputs,
-};
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/compression/index.ts b/packages/conversation-flow/src/__tests__/fixtures/inputs/compression/index.ts
index c8fd4d90dd0..5e57886f3e5 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/inputs/compression/index.ts
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/compression/index.ts
@@ -1,11 +1,12 @@
+import type { Message } from '../../../../types';
import mixedGroups from './mixed-groups.json';
import multipleCompressions from './multiple-compressions.json';
import parallelGroup from './parallel-group.json';
import simpleCompression from './simple-compression.json';
export const compression = {
- mixedGroups,
- multipleCompressions,
- parallelGroup,
- simpleCompression,
+ mixedGroups: mixedGroups as unknown as Message[],
+ multipleCompressions: multipleCompressions as Message[],
+ parallelGroup: parallelGroup as unknown as Message[],
+ simpleCompression: simpleCompression as Message[],
};
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/index.ts b/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/index.ts
new file mode 100644
index 00000000000..faf5f6a39e9
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/index.ts
@@ -0,0 +1,14 @@
+import type { Message } from '../../../../types';
+import optimisticAssistantBranch from './optimistic-assistant-branch.json';
+import orphanThreadRoot from './orphan-thread-root.json';
+import taskChildSupervisorSummary from './task-child-supervisor-summary.json';
+import taskCompletionSignal from './task-completion-signal.json';
+import tasksWithAssistantGroupSibling from './tasks-with-assistant-group-sibling.json';
+
+export const edgeCases = {
+ optimisticAssistantBranch: optimisticAssistantBranch as Message[],
+ orphanThreadRoot: orphanThreadRoot as Message[],
+ taskChildSupervisorSummary: taskChildSupervisorSummary as Message[],
+ taskCompletionSignal: taskCompletionSignal as Message[],
+ tasksWithAssistantGroupSibling: tasksWithAssistantGroupSibling as Message[],
+};
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/optimistic-assistant-branch.json b/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/optimistic-assistant-branch.json
new file mode 100644
index 00000000000..a9b8b17975f
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/optimistic-assistant-branch.json
@@ -0,0 +1,39 @@
+[
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "What is the fastest way to seed the database?",
+ "parentId": null,
+ "createdAt": 1735526559000,
+ "updatedAt": 1735526559000
+ },
+ {
+ "id": "msg-assistant-1",
+ "role": "assistant",
+ "content": "Use the bulk loader rather than per-row inserts.",
+ "parentId": "msg-user-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1735526560000,
+ "updatedAt": 1735526560000,
+ "metadata": {
+ "activeBranchIndex": 2
+ }
+ },
+ {
+ "id": "msg-user-followup-a",
+ "role": "user",
+ "content": "How large a batch should I use?",
+ "parentId": "msg-assistant-1",
+ "createdAt": 1735526561000,
+ "updatedAt": 1735526561000
+ },
+ {
+ "id": "msg-user-followup-b",
+ "role": "user",
+ "content": "Does that work on a read replica?",
+ "parentId": "msg-assistant-1",
+ "createdAt": 1735526562000,
+ "updatedAt": 1735526562000
+ }
+]
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/orphan-thread-root.json b/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/orphan-thread-root.json
new file mode 100644
index 00000000000..3a352bc8d12
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/orphan-thread-root.json
@@ -0,0 +1,42 @@
+[
+ {
+ "id": "msg-thread-user-1",
+ "role": "user",
+ "content": "Continue the discussion in this thread.",
+ "parentId": "msg-outside-window",
+ "threadId": "thd_orphan",
+ "createdAt": 1735526559000,
+ "updatedAt": 1735526559000
+ },
+ {
+ "id": "msg-thread-assistant-1",
+ "role": "assistant",
+ "content": "Picking up from where the parent conversation left off.",
+ "parentId": "msg-thread-user-1",
+ "threadId": "thd_orphan",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1735526560000,
+ "updatedAt": 1735526560000
+ },
+ {
+ "id": "msg-thread-user-2",
+ "role": "user",
+ "content": "Good, keep going.",
+ "parentId": "msg-thread-assistant-1",
+ "threadId": "thd_orphan",
+ "createdAt": 1735526561000,
+ "updatedAt": 1735526561000
+ },
+ {
+ "id": "msg-thread-assistant-2",
+ "role": "assistant",
+ "content": "Here is the rest of the analysis.",
+ "parentId": "msg-thread-user-2",
+ "threadId": "thd_orphan",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1735526562000,
+ "updatedAt": 1735526562000
+ }
+]
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/task-child-supervisor-summary.json b/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/task-child-supervisor-summary.json
new file mode 100644
index 00000000000..3fb1fdab895
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/task-child-supervisor-summary.json
@@ -0,0 +1,95 @@
+[
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Dispatch the group and summarise when they are all done.",
+ "parentId": null,
+ "createdAt": 1735526559000,
+ "updatedAt": 1735526559000
+ },
+ {
+ "id": "msg-supervisor-1",
+ "role": "assistant",
+ "content": "Dispatching two agents.",
+ "parentId": "msg-user-1",
+ "agentId": "supervisor",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1735526560000,
+ "updatedAt": 1735526560000,
+ "metadata": {
+ "isSupervisor": true,
+ "orchestrationRole": "supervisor"
+ },
+ "tools": [
+ {
+ "id": "call_group_1",
+ "type": "builtin",
+ "apiName": "callSubAgents",
+ "arguments": "{\"tasks\": [{\"description\": \"Frontend audit\"}, {\"description\": \"Backend audit\"}]}",
+ "identifier": "lobe-group-management",
+ "result_msg_id": "msg-tool-1"
+ }
+ ]
+ },
+ {
+ "id": "msg-tool-1",
+ "role": "tool",
+ "content": "Triggered 2 async tasks",
+ "parentId": "msg-supervisor-1",
+ "tool_call_id": "call_group_1",
+ "createdAt": 1735526561000,
+ "updatedAt": 1735526561000
+ },
+ {
+ "id": "msg-task-frontend",
+ "role": "task",
+ "content": "# Frontend audit\n\nNo blocking issues.",
+ "parentId": "msg-tool-1",
+ "agentId": "agent-frontend",
+ "createdAt": 1735526562000,
+ "updatedAt": 1735526570000,
+ "taskDetail": {
+ "duration": 8000,
+ "status": "completed",
+ "threadId": "thd_frontend",
+ "title": "Frontend audit",
+ "totalCost": 0.01,
+ "totalMessages": 6,
+ "totalTokens": 24000
+ }
+ },
+ {
+ "id": "msg-task-backend",
+ "role": "task",
+ "content": "# Backend audit\n\nTwo slow queries found.",
+ "parentId": "msg-tool-1",
+ "agentId": "agent-backend",
+ "createdAt": 1735526563000,
+ "updatedAt": 1735526571000,
+ "taskDetail": {
+ "duration": 9000,
+ "status": "completed",
+ "threadId": "thd_backend",
+ "title": "Backend audit",
+ "totalCost": 0.012,
+ "totalMessages": 7,
+ "totalTokens": 26000
+ }
+ },
+ {
+ "id": "msg-supervisor-summary",
+ "role": "assistant",
+ "content": "Both audits are in — the backend needs query work, the frontend is clear.",
+ "parentId": "msg-task-backend",
+ "agentId": "supervisor",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1735526580000,
+ "updatedAt": 1735526580000,
+ "metadata": {
+ "isSupervisor": true,
+ "orchestrationRole": "supervisor"
+ }
+ }
+]
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/task-completion-signal.json b/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/task-completion-signal.json
new file mode 100644
index 00000000000..a1c7ac58b1f
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/task-completion-signal.json
@@ -0,0 +1,57 @@
+[
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Kick off the long-running migration and tell me when it lands.",
+ "parentId": null,
+ "createdAt": 1735526559000,
+ "updatedAt": 1735526559000
+ },
+ {
+ "id": "msg-assistant-1",
+ "role": "assistant",
+ "content": "Starting the migration now.",
+ "parentId": "msg-user-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1735526560000,
+ "updatedAt": 1735526560000,
+ "tools": [
+ {
+ "id": "call_migrate_1",
+ "type": "builtin",
+ "apiName": "runMigration",
+ "arguments": "{\"target\": \"postgres\"}",
+ "identifier": "lobe-monitor",
+ "result_msg_id": "msg-tool-1"
+ }
+ ]
+ },
+ {
+ "id": "msg-tool-1",
+ "role": "tool",
+ "content": "Migration started, running in background.",
+ "parentId": "msg-assistant-1",
+ "tool_call_id": "call_migrate_1",
+ "createdAt": 1735526561000,
+ "updatedAt": 1735526561000
+ },
+ {
+ "id": "msg-completion-1",
+ "role": "assistant",
+ "content": "The migration finished successfully — 14 tables moved.",
+ "parentId": "msg-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1735526562000,
+ "updatedAt": 1735526562000,
+ "metadata": {
+ "signal": {
+ "sequence": 1,
+ "sourceToolCallId": "call_migrate_1",
+ "sourceToolName": "runMigration",
+ "type": "task-completion"
+ }
+ }
+ }
+]
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/tasks-with-assistant-group-sibling.json b/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/tasks-with-assistant-group-sibling.json
new file mode 100644
index 00000000000..e012d739ab4
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/edgeCases/tasks-with-assistant-group-sibling.json
@@ -0,0 +1,102 @@
+[
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Run two research tasks, then look up the changelog.",
+ "parentId": null,
+ "createdAt": 1735526559000,
+ "updatedAt": 1735526559000
+ },
+ {
+ "id": "msg-assistant-1",
+ "role": "assistant",
+ "content": "Spawning two tasks.",
+ "parentId": "msg-user-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1735526560000,
+ "updatedAt": 1735526560000,
+ "tools": [
+ {
+ "id": "call_exec_tasks_1",
+ "type": "builtin",
+ "apiName": "callSubAgents",
+ "arguments": "{\"tasks\": [{\"description\": \"Research A\"}, {\"description\": \"Research B\"}]}",
+ "identifier": "lobe-agent",
+ "result_msg_id": "msg-tool-1"
+ }
+ ]
+ },
+ {
+ "id": "msg-tool-1",
+ "role": "tool",
+ "content": "Triggered 2 async tasks",
+ "parentId": "msg-assistant-1",
+ "tool_call_id": "call_exec_tasks_1",
+ "createdAt": 1735526561000,
+ "updatedAt": 1735526561000
+ },
+ {
+ "id": "msg-task-a",
+ "role": "task",
+ "content": "# Research A\n\nFindings for A.",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526562000,
+ "updatedAt": 1735526570000,
+ "taskDetail": {
+ "duration": 8000,
+ "status": "completed",
+ "threadId": "thd_a",
+ "title": "Research A",
+ "totalCost": 0.01,
+ "totalMessages": 5,
+ "totalTokens": 20000
+ }
+ },
+ {
+ "id": "msg-task-b",
+ "role": "task",
+ "content": "# Research B\n\nFindings for B.",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526563000,
+ "updatedAt": 1735526571000,
+ "taskDetail": {
+ "duration": 8000,
+ "status": "completed",
+ "threadId": "thd_b",
+ "title": "Research B",
+ "totalCost": 0.01,
+ "totalMessages": 5,
+ "totalTokens": 20000
+ }
+ },
+ {
+ "id": "msg-assistant-followup",
+ "role": "assistant",
+ "content": "Both tasks are done — now checking the changelog.",
+ "parentId": "msg-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1735526580000,
+ "updatedAt": 1735526580000,
+ "tools": [
+ {
+ "id": "call_changelog_1",
+ "type": "default",
+ "apiName": "readChangelog",
+ "arguments": "{\"repo\": \"lobehub\"}",
+ "identifier": "lobe-web-browsing",
+ "result_msg_id": "msg-tool-changelog"
+ }
+ ]
+ },
+ {
+ "id": "msg-tool-changelog",
+ "role": "tool",
+ "content": "v1.2.0 — shipped the new parser.",
+ "parentId": "msg-assistant-followup",
+ "tool_call_id": "call_changelog_1",
+ "createdAt": 1735526581000,
+ "updatedAt": 1735526581000
+ }
+]
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/index.ts b/packages/conversation-flow/src/__tests__/fixtures/inputs/index.ts
index 6a2e3268ba1..7fd76cc62a6 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/inputs/index.ts
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/index.ts
@@ -6,6 +6,7 @@ import { assistantGroup } from './assistantGroup';
import { branch } from './branch';
import { compare } from './compare';
import { compression } from './compression';
+import { edgeCases } from './edgeCases';
import linearConversation from './linear-conversation.json';
import { tasks } from './tasks';
@@ -17,6 +18,7 @@ export const inputs = {
branch,
compare,
compression,
+ edgeCases,
linearConversation: linearConversation as Message[],
tasks,
};
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/simple.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/simple.json
index 70190004cdb..a67ff55cc18 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/simple.json
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/simple.json
@@ -5,17 +5,18 @@
"type": "message"
},
{
- "id": "msg-supervisor-1",
- "type": "assistantGroup",
"children": [
{
"id": "msg-supervisor-1",
"type": "message",
"tools": ["msg-broadcast-tool-1"]
}
- ]
+ ],
+ "id": "msg-supervisor-1",
+ "type": "assistantGroup"
},
{
+ "id": "agentCouncil-msg-broadcast-tool-1-msg-agent-backend-1-msg-agent-devops-1-msg-agent-architect-1",
"members": [
{
"id": "msg-agent-backend-1",
@@ -30,7 +31,6 @@
"type": "message"
}
],
- "id": "agentCouncil-msg-broadcast-tool-1-msg-agent-backend-1-msg-agent-devops-1-msg-agent-architect-1",
"messageId": "msg-broadcast-tool-1",
"type": "agentCouncil"
}
@@ -54,8 +54,8 @@
"updatedAt": 1704067201000,
"children": [
{
- "id": "msg-supervisor-1",
"content": "",
+ "id": "msg-supervisor-1",
"tools": [
{
"id": "call_broadcast_1",
@@ -67,86 +67,80 @@
"identifier": "lobe-group-management",
"apiName": "broadcast",
"result": {
- "id": "msg-broadcast-tool-1",
- "content": "Broadcasting to 3 agents..."
+ "content": "Broadcasting to 3 agents...",
+ "id": "msg-broadcast-tool-1"
},
"result_msg_id": "msg-broadcast-tool-1"
}
]
- }
- ]
- },
- {
- "content": "",
- "createdAt": 1704067205000,
- "extra": {
- "parentMessageId": "msg-broadcast-tool-1"
- },
- "id": "agentCouncil-msg-broadcast-tool-1-msg-agent-backend-1-msg-agent-devops-1-msg-agent-architect-1",
- "members": [
- {
- "id": "msg-agent-backend-1",
- "role": "assistant",
- "agentId": "agent-backend",
- "content": "**From a Backend Developer's Perspective:**\n\n**Pros:**\n- Independent deployment of services\n- Technology flexibility per service\n- Better fault isolation\n- Easier to scale specific services\n\n**Cons:**\n- Increased complexity in service communication\n- Data consistency challenges\n- More complex debugging and monitoring\n- Network latency between services",
- "parentId": "msg-broadcast-tool-1",
- "model": "gpt-4",
- "provider": "openai",
- "createdAt": 1704067205000,
- "updatedAt": 1704067205000,
- "metadata": {
- "totalInputTokens": 50,
- "totalOutputTokens": 120,
- "totalTokens": 170,
- "tps": 45,
- "ttft": 350,
- "duration": 2667,
- "latency": 3017
- }
},
{
- "id": "msg-agent-devops-1",
- "role": "assistant",
- "agentId": "agent-devops",
- "content": "**From a DevOps Engineer's Perspective:**\n\n**Pros:**\n- CI/CD pipelines can be service-specific\n- Container orchestration fits naturally\n- Auto-scaling at service level\n- Blue-green deployments are easier\n\n**Cons:**\n- Complex infrastructure management\n- More services = more monitoring overhead\n- Configuration management complexity\n- Increased resource consumption (each service needs its own runtime)",
- "parentId": "msg-broadcast-tool-1",
- "model": "claude-3-5-sonnet-20241022",
- "provider": "anthropic",
- "createdAt": 1704067205500,
- "updatedAt": 1704067205500,
- "metadata": {
- "totalInputTokens": 50,
- "totalOutputTokens": 130,
- "totalTokens": 180,
- "tps": 52,
- "ttft": 280,
- "duration": 2500,
- "latency": 2780
- }
- },
- {
- "id": "msg-agent-architect-1",
- "role": "assistant",
- "agentId": "agent-architect",
- "content": "**From a Software Architect's Perspective:**\n\n**Pros:**\n- Clear service boundaries and ownership\n- Supports domain-driven design\n- Teams can work independently\n- Easier to understand individual services\n\n**Cons:**\n- Requires careful API versioning strategy\n- Cross-cutting concerns need special handling\n- Service discovery and load balancing complexity\n- Initial design requires significant upfront investment",
- "parentId": "msg-broadcast-tool-1",
- "model": "gpt-4",
- "provider": "openai",
- "createdAt": 1704067206000,
- "updatedAt": 1704067206000,
- "metadata": {
- "totalInputTokens": 50,
- "totalOutputTokens": 125,
- "totalTokens": 175,
- "tps": 48,
- "ttft": 320,
- "duration": 2604,
- "latency": 2924
- }
+ "content": "",
+ "council": [
+ {
+ "id": "msg-agent-backend-1",
+ "role": "assistant",
+ "agentId": "agent-backend",
+ "content": "**From a Backend Developer's Perspective:**\n\n**Pros:**\n- Independent deployment of services\n- Technology flexibility per service\n- Better fault isolation\n- Easier to scale specific services\n\n**Cons:**\n- Increased complexity in service communication\n- Data consistency challenges\n- More complex debugging and monitoring\n- Network latency between services",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "metadata": {
+ "totalInputTokens": 50,
+ "totalOutputTokens": 120,
+ "totalTokens": 170,
+ "tps": 45,
+ "ttft": 350,
+ "duration": 2667,
+ "latency": 3017
+ }
+ },
+ {
+ "id": "msg-agent-devops-1",
+ "role": "assistant",
+ "agentId": "agent-devops",
+ "content": "**From a DevOps Engineer's Perspective:**\n\n**Pros:**\n- CI/CD pipelines can be service-specific\n- Container orchestration fits naturally\n- Auto-scaling at service level\n- Blue-green deployments are easier\n\n**Cons:**\n- Complex infrastructure management\n- More services = more monitoring overhead\n- Configuration management complexity\n- Increased resource consumption (each service needs its own runtime)",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "claude-3-5-sonnet-20241022",
+ "provider": "anthropic",
+ "createdAt": 1704067205500,
+ "updatedAt": 1704067205500,
+ "metadata": {
+ "totalInputTokens": 50,
+ "totalOutputTokens": 130,
+ "totalTokens": 180,
+ "tps": 52,
+ "ttft": 280,
+ "duration": 2500,
+ "latency": 2780
+ }
+ },
+ {
+ "id": "msg-agent-architect-1",
+ "role": "assistant",
+ "agentId": "agent-architect",
+ "content": "**From a Software Architect's Perspective:**\n\n**Pros:**\n- Clear service boundaries and ownership\n- Supports domain-driven design\n- Teams can work independently\n- Easier to understand individual services\n\n**Cons:**\n- Requires careful API versioning strategy\n- Cross-cutting concerns need special handling\n- Service discovery and load balancing complexity\n- Initial design requires significant upfront investment",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067206000,
+ "updatedAt": 1704067206000,
+ "metadata": {
+ "totalInputTokens": 50,
+ "totalOutputTokens": 125,
+ "totalTokens": 175,
+ "tps": 48,
+ "ttft": 320,
+ "duration": 2604,
+ "latency": 2924
+ }
+ }
+ ],
+ "id": "council-msg-supervisor-1"
}
- ],
- "role": "agentCouncil",
- "updatedAt": 1704067206000
+ ]
}
],
"messageMap": {
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/with-supervisor-reply.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/with-supervisor-reply.json
index e901de5fa0e..10aa52b76ef 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/with-supervisor-reply.json
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/with-supervisor-reply.json
@@ -5,17 +5,18 @@
"type": "message"
},
{
- "id": "msg-supervisor-1",
- "type": "assistantGroup",
"children": [
{
"id": "msg-supervisor-1",
"type": "message",
"tools": ["msg-broadcast-tool-1"]
}
- ]
+ ],
+ "id": "msg-supervisor-1",
+ "type": "assistantGroup"
},
{
+ "id": "agentCouncil-msg-broadcast-tool-1-msg-agent-backend-1-msg-agent-devops-1-msg-agent-architect-1",
"members": [
{
"id": "msg-agent-backend-1",
@@ -30,7 +31,6 @@
"type": "message"
}
],
- "id": "agentCouncil-msg-broadcast-tool-1-msg-agent-backend-1-msg-agent-devops-1-msg-agent-architect-1",
"messageId": "msg-broadcast-tool-1",
"type": "agentCouncil"
},
@@ -56,17 +56,10 @@
"parentId": "msg-user-1",
"createdAt": 1704067201000,
"updatedAt": 1704067201000,
- "metadata": {
- "isSupervisor": true,
- "orchestrationRole": "supervisor"
- },
"children": [
{
- "id": "msg-supervisor-1",
"content": "",
- "metadata": {
- "isSupervisor": true
- },
+ "id": "msg-supervisor-1",
"tools": [
{
"id": "call_broadcast_1",
@@ -78,59 +71,60 @@
"identifier": "lobe-group-management",
"apiName": "broadcast",
"result": {
- "id": "msg-broadcast-tool-1",
- "content": "Broadcasting to 3 agents..."
+ "content": "Broadcasting to 3 agents...",
+ "id": "msg-broadcast-tool-1"
},
"result_msg_id": "msg-broadcast-tool-1"
}
- ]
- }
- ]
- },
- {
- "content": "",
- "createdAt": 1704067205000,
- "extra": {
- "parentMessageId": "msg-broadcast-tool-1"
- },
- "id": "agentCouncil-msg-broadcast-tool-1-msg-agent-backend-1-msg-agent-devops-1-msg-agent-architect-1",
- "members": [
- {
- "id": "msg-agent-backend-1",
- "role": "assistant",
- "agentId": "agent-backend",
- "content": "**From a Backend Developer's Perspective:**\n\n**Pros:**\n- Independent deployment\n- Technology flexibility\n\n**Cons:**\n- Service communication complexity\n- Data consistency challenges",
- "parentId": "msg-broadcast-tool-1",
- "model": "gpt-4",
- "provider": "openai",
- "createdAt": 1704067205000,
- "updatedAt": 1704067205000
- },
- {
- "id": "msg-agent-devops-1",
- "role": "assistant",
- "agentId": "agent-devops",
- "content": "**From a DevOps Engineer's Perspective:**\n\n**Pros:**\n- CI/CD pipelines can be service-specific\n- Auto-scaling at service level\n\n**Cons:**\n- Complex infrastructure management\n- More monitoring overhead",
- "parentId": "msg-broadcast-tool-1",
- "model": "claude-3-5-sonnet-20241022",
- "provider": "anthropic",
- "createdAt": 1704067205500,
- "updatedAt": 1704067205500
+ ],
+ "metadata": {
+ "isSupervisor": true
+ }
},
{
- "id": "msg-agent-architect-1",
- "role": "assistant",
- "agentId": "agent-architect",
- "content": "**From a Software Architect's Perspective:**\n\n**Pros:**\n- Clear service boundaries\n- Teams can work independently\n\n**Cons:**\n- API versioning complexity\n- Service discovery challenges",
- "parentId": "msg-broadcast-tool-1",
- "model": "gpt-4",
- "provider": "openai",
- "createdAt": 1704067206000,
- "updatedAt": 1704067206000
+ "content": "",
+ "council": [
+ {
+ "id": "msg-agent-backend-1",
+ "role": "assistant",
+ "agentId": "agent-backend",
+ "content": "**From a Backend Developer's Perspective:**\n\n**Pros:**\n- Independent deployment\n- Technology flexibility\n\n**Cons:**\n- Service communication complexity\n- Data consistency challenges",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000
+ },
+ {
+ "id": "msg-agent-devops-1",
+ "role": "assistant",
+ "agentId": "agent-devops",
+ "content": "**From a DevOps Engineer's Perspective:**\n\n**Pros:**\n- CI/CD pipelines can be service-specific\n- Auto-scaling at service level\n\n**Cons:**\n- Complex infrastructure management\n- More monitoring overhead",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "claude-3-5-sonnet-20241022",
+ "provider": "anthropic",
+ "createdAt": 1704067205500,
+ "updatedAt": 1704067205500
+ },
+ {
+ "id": "msg-agent-architect-1",
+ "role": "assistant",
+ "agentId": "agent-architect",
+ "content": "**From a Software Architect's Perspective:**\n\n**Pros:**\n- Clear service boundaries\n- Teams can work independently\n\n**Cons:**\n- API versioning complexity\n- Service discovery challenges",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067206000,
+ "updatedAt": 1704067206000
+ }
+ ],
+ "id": "council-msg-supervisor-1"
}
],
- "role": "agentCouncil",
- "updatedAt": 1704067206000
+ "metadata": {
+ "isSupervisor": true,
+ "orchestrationRole": "supervisor"
+ }
},
{
"id": "msg-supervisor-summary",
@@ -142,19 +136,19 @@
"provider": "openai",
"createdAt": 1704067210000,
"updatedAt": 1704067210000,
- "metadata": {
- "isSupervisor": true,
- "orchestrationRole": "supervisor"
- },
"children": [
{
- "id": "msg-supervisor-summary",
"content": "## Summary\n\nBased on the discussion from our team:\n\n**Key Pros:**\n- Independent deployment and scaling\n- Technology flexibility\n- Clear service boundaries\n\n**Key Cons:**\n- Increased complexity in communication and infrastructure\n- Data consistency and monitoring challenges\n\nI recommend starting with a modular monolith and gradually extracting services as needed.",
+ "id": "msg-supervisor-summary",
"metadata": {
"isSupervisor": true
}
}
- ]
+ ],
+ "metadata": {
+ "isSupervisor": true,
+ "orchestrationRole": "supervisor"
+ }
}
],
"messageMap": {
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/index.ts b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/index.ts
index 4d04ff1c69e..b53f7c6a23c 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/index.ts
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/index.ts
@@ -1,6 +1,10 @@
import type { SerializedParseResult } from '../..';
import speakDifferentAgent from './speak-different-agent.json';
+import supervisorAfterMultiTasks from './supervisor-after-multi-tasks.json';
+import supervisorContentOnly from './supervisor-content-only.json';
export const agentGroup = {
speakDifferentAgent: speakDifferentAgent as unknown as SerializedParseResult,
+ supervisorAfterMultiTasks: supervisorAfterMultiTasks as unknown as SerializedParseResult,
+ supervisorContentOnly: supervisorContentOnly as unknown as SerializedParseResult,
};
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/supervisor-after-multi-tasks.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/supervisor-after-multi-tasks.json
new file mode 100644
index 00000000000..8d02eb3ed0e
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/supervisor-after-multi-tasks.json
@@ -0,0 +1,257 @@
+{
+ "contextTree": [
+ {
+ "id": "msg-user-1",
+ "type": "message"
+ },
+ {
+ "children": [
+ {
+ "id": "msg-supervisor-1",
+ "type": "message",
+ "tools": ["msg-tool-1"]
+ }
+ ],
+ "id": "msg-supervisor-1",
+ "type": "assistantGroup"
+ },
+ {
+ "children": [
+ {
+ "id": "msg-task-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-2",
+ "type": "message"
+ }
+ ],
+ "id": "tasks-msg-tool-1-msg-task-1-msg-task-2",
+ "messageId": "msg-tool-1",
+ "type": "tasks"
+ },
+ {
+ "id": "msg-supervisor-summary",
+ "type": "message"
+ }
+ ],
+ "flatList": [
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "帮我调研下 clawdbot",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000
+ },
+ {
+ "id": "msg-supervisor-1",
+ "role": "supervisor",
+ "agentId": "supervisor",
+ "content": "",
+ "parentId": "msg-user-1",
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "children": [
+ {
+ "content": "我会安排团队成员进行调研。",
+ "id": "msg-supervisor-1",
+ "tools": [
+ {
+ "id": "call_tasks_1",
+ "type": "builtin",
+ "apiName": "executeAgentTasks",
+ "arguments": "{\"tasks\":[{\"agentId\":\"agent-1\",\"title\":\"任务1\"},{\"agentId\":\"agent-2\",\"title\":\"任务2\"}]}",
+ "identifier": "lobe-group-management",
+ "result": {
+ "content": "Triggered 2 tasks.",
+ "id": "msg-tool-1"
+ },
+ "result_msg_id": "msg-tool-1"
+ }
+ ],
+ "metadata": {
+ "isSupervisor": true
+ }
+ }
+ ],
+ "metadata": {
+ "isSupervisor": true,
+ "orchestrationRole": "supervisor"
+ }
+ },
+ {
+ "content": "",
+ "createdAt": 1704067203000,
+ "extra": {
+ "parentMessageId": "msg-tool-1"
+ },
+ "id": "groupTasks-msg-tool-1-msg-task-1-msg-task-2",
+ "role": "groupTasks",
+ "tasks": [
+ {
+ "id": "msg-task-1",
+ "role": "task",
+ "content": "调研结果1...",
+ "parentId": "msg-tool-1",
+ "agentId": "agent-1",
+ "createdAt": 1704067203000,
+ "updatedAt": 1704067203000,
+ "metadata": {
+ "taskTitle": "任务1"
+ },
+ "taskDetail": {
+ "status": "completed",
+ "threadId": "thd_xxx1",
+ "title": "任务1"
+ }
+ },
+ {
+ "id": "msg-task-2",
+ "role": "task",
+ "content": "调研结果2...",
+ "parentId": "msg-tool-1",
+ "agentId": "agent-2",
+ "createdAt": 1704067204000,
+ "updatedAt": 1704067204000,
+ "metadata": {
+ "taskTitle": "任务2"
+ },
+ "taskDetail": {
+ "status": "completed",
+ "threadId": "thd_xxx2",
+ "title": "任务2"
+ }
+ }
+ ],
+ "updatedAt": 1704067204000
+ },
+ {
+ "id": "msg-supervisor-summary",
+ "role": "supervisor",
+ "agentId": "supervisor",
+ "content": "",
+ "parentId": "msg-task-2",
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "model": "claude-sonnet-4",
+ "provider": "anthropic",
+ "children": [
+ {
+ "content": "调研完成!这是综合汇总报告...",
+ "id": "msg-supervisor-summary",
+ "performance": {
+ "tps": 78.99
+ },
+ "usage": {
+ "cost": 0.208
+ },
+ "metadata": {
+ "isSupervisor": true
+ }
+ }
+ ],
+ "performance": {
+ "tps": 78.99
+ },
+ "usage": {
+ "cost": 0.208
+ },
+ "metadata": {
+ "isSupervisor": true,
+ "orchestrationRole": "supervisor"
+ }
+ }
+ ],
+ "messageMap": {
+ "msg-user-1": {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "帮我调研下 clawdbot",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000
+ },
+ "msg-supervisor-1": {
+ "id": "msg-supervisor-1",
+ "role": "supervisor",
+ "agentId": "supervisor",
+ "content": "我会安排团队成员进行调研。",
+ "parentId": "msg-user-1",
+ "tools": [
+ {
+ "id": "call_tasks_1",
+ "type": "builtin",
+ "apiName": "executeAgentTasks",
+ "arguments": "{\"tasks\":[{\"agentId\":\"agent-1\",\"title\":\"任务1\"},{\"agentId\":\"agent-2\",\"title\":\"任务2\"}]}",
+ "identifier": "lobe-group-management"
+ }
+ ],
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "metadata": {
+ "isSupervisor": true
+ }
+ },
+ "msg-tool-1": {
+ "id": "msg-tool-1",
+ "role": "tool",
+ "content": "Triggered 2 tasks.",
+ "parentId": "msg-supervisor-1",
+ "tool_call_id": "call_tasks_1",
+ "createdAt": 1704067202000,
+ "updatedAt": 1704067202000
+ },
+ "msg-task-1": {
+ "id": "msg-task-1",
+ "role": "task",
+ "content": "调研结果1...",
+ "parentId": "msg-tool-1",
+ "agentId": "agent-1",
+ "createdAt": 1704067203000,
+ "updatedAt": 1704067203000,
+ "metadata": {
+ "taskTitle": "任务1"
+ },
+ "taskDetail": {
+ "status": "completed",
+ "threadId": "thd_xxx1",
+ "title": "任务1"
+ }
+ },
+ "msg-task-2": {
+ "id": "msg-task-2",
+ "role": "task",
+ "content": "调研结果2...",
+ "parentId": "msg-tool-1",
+ "agentId": "agent-2",
+ "createdAt": 1704067204000,
+ "updatedAt": 1704067204000,
+ "metadata": {
+ "taskTitle": "任务2"
+ },
+ "taskDetail": {
+ "status": "completed",
+ "threadId": "thd_xxx2",
+ "title": "任务2"
+ }
+ },
+ "msg-supervisor-summary": {
+ "id": "msg-supervisor-summary",
+ "role": "supervisor",
+ "agentId": "supervisor",
+ "content": "调研完成!这是综合汇总报告...",
+ "parentId": "msg-task-2",
+ "tools": null,
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "metadata": {
+ "isSupervisor": true,
+ "tps": 78.99,
+ "cost": 0.208
+ },
+ "model": "claude-sonnet-4",
+ "provider": "anthropic"
+ }
+ }
+}
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/supervisor-content-only.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/supervisor-content-only.json
new file mode 100644
index 00000000000..79bf8329a91
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/supervisor-content-only.json
@@ -0,0 +1,204 @@
+{
+ "contextTree": [
+ {
+ "id": "msg-user-1",
+ "type": "message"
+ },
+ {
+ "children": [
+ {
+ "id": "msg-supervisor-1",
+ "type": "message",
+ "tools": ["msg-tool-1"]
+ }
+ ],
+ "id": "msg-supervisor-1",
+ "type": "assistantGroup"
+ },
+ {
+ "id": "msg-tool-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-supervisor-summary",
+ "type": "message"
+ }
+ ],
+ "flatList": [
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "帮我调研下 clawdbot",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000
+ },
+ {
+ "id": "msg-supervisor-1",
+ "role": "supervisor",
+ "agentId": "supervisor",
+ "content": "",
+ "parentId": "msg-user-1",
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "children": [
+ {
+ "content": "我会安排团队成员进行调研。",
+ "id": "msg-supervisor-1",
+ "tools": [
+ {
+ "id": "call_tasks_1",
+ "type": "builtin",
+ "apiName": "executeAgentTasks",
+ "arguments": "{\"tasks\":[{\"agentId\":\"agent-1\",\"title\":\"调研任务\"}]}",
+ "identifier": "lobe-group-management",
+ "result": {
+ "content": "Triggered 1 task.",
+ "id": "msg-tool-1"
+ },
+ "result_msg_id": "msg-tool-1"
+ }
+ ],
+ "metadata": {
+ "isSupervisor": true
+ }
+ }
+ ],
+ "metadata": {
+ "isSupervisor": true,
+ "orchestrationRole": "supervisor"
+ }
+ },
+ {
+ "id": "msg-task-1",
+ "role": "task",
+ "content": "调研结果内容...",
+ "parentId": "msg-tool-1",
+ "agentId": "agent-1",
+ "createdAt": 1704067203000,
+ "updatedAt": 1704067203000,
+ "metadata": {
+ "taskTitle": "调研任务"
+ },
+ "taskDetail": {
+ "status": "completed",
+ "threadId": "thd_xxx",
+ "title": "调研任务"
+ }
+ },
+ {
+ "id": "msg-supervisor-summary",
+ "role": "supervisor",
+ "agentId": "supervisor",
+ "content": "",
+ "parentId": "msg-task-1",
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "model": "claude-sonnet-4",
+ "provider": "anthropic",
+ "children": [
+ {
+ "content": "调研完成!这是综合汇总报告...",
+ "id": "msg-supervisor-summary",
+ "performance": {
+ "tps": 78.99
+ },
+ "usage": {
+ "cost": 0.208
+ },
+ "metadata": {
+ "isSupervisor": true
+ }
+ }
+ ],
+ "performance": {
+ "tps": 78.99
+ },
+ "usage": {
+ "cost": 0.208
+ },
+ "metadata": {
+ "isSupervisor": true,
+ "orchestrationRole": "supervisor"
+ }
+ }
+ ],
+ "messageMap": {
+ "msg-user-1": {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "帮我调研下 clawdbot",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000
+ },
+ "msg-supervisor-1": {
+ "id": "msg-supervisor-1",
+ "role": "supervisor",
+ "agentId": "supervisor",
+ "content": "我会安排团队成员进行调研。",
+ "parentId": "msg-user-1",
+ "tools": [
+ {
+ "id": "call_tasks_1",
+ "type": "builtin",
+ "apiName": "executeAgentTasks",
+ "arguments": "{\"tasks\":[{\"agentId\":\"agent-1\",\"title\":\"调研任务\"}]}",
+ "identifier": "lobe-group-management"
+ }
+ ],
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "metadata": {
+ "isSupervisor": true
+ }
+ },
+ "msg-tool-1": {
+ "id": "msg-tool-1",
+ "role": "tool",
+ "content": "Triggered 1 task.",
+ "parentId": "msg-supervisor-1",
+ "tool_call_id": "call_tasks_1",
+ "createdAt": 1704067202000,
+ "updatedAt": 1704067202000
+ },
+ "msg-task-1": {
+ "id": "msg-task-1",
+ "role": "task",
+ "content": "调研结果内容...",
+ "parentId": "msg-tool-1",
+ "agentId": "agent-1",
+ "createdAt": 1704067203000,
+ "updatedAt": 1704067203000,
+ "metadata": {
+ "taskTitle": "调研任务"
+ },
+ "taskDetail": {
+ "status": "completed",
+ "threadId": "thd_xxx",
+ "title": "调研任务"
+ }
+ },
+ "msg-supervisor-summary": {
+ "id": "msg-supervisor-summary",
+ "role": "supervisor",
+ "agentId": "supervisor",
+ "content": "调研完成!这是综合汇总报告...",
+ "parentId": "msg-task-1",
+ "tools": null,
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "metadata": {
+ "isSupervisor": true,
+ "tps": 78.99,
+ "cost": 0.208
+ },
+ "model": "claude-sonnet-4",
+ "provider": "anthropic"
+ }
+ }
+}
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/index.ts b/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/index.ts
new file mode 100644
index 00000000000..24e860bd112
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/index.ts
@@ -0,0 +1,12 @@
+import type { SerializedParseResult } from '../..';
+import mixedGroups from './mixed-groups.json';
+import multipleCompressions from './multiple-compressions.json';
+import parallelGroup from './parallel-group.json';
+import simpleCompression from './simple-compression.json';
+
+export const compression = {
+ mixedGroups: mixedGroups as unknown as SerializedParseResult,
+ multipleCompressions: multipleCompressions as unknown as SerializedParseResult,
+ parallelGroup: parallelGroup as unknown as SerializedParseResult,
+ simpleCompression: simpleCompression as unknown as SerializedParseResult,
+};
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/mixed-groups.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/mixed-groups.json
new file mode 100644
index 00000000000..39ea5ea5c98
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/mixed-groups.json
@@ -0,0 +1,184 @@
+{
+ "contextTree": [
+ {
+ "id": "comp-group-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-compare-trigger",
+ "type": "message"
+ },
+ {
+ "id": "parallel-group-state",
+ "type": "message"
+ },
+ {
+ "id": "msg-decision",
+ "type": "message"
+ },
+ {
+ "id": "msg-implementation",
+ "type": "message"
+ }
+ ],
+ "flatList": [
+ {
+ "id": "comp-group-1",
+ "role": "compressedGroup",
+ "content": "Summary: Initial project discussion about building a chat application.",
+ "parentId": null,
+ "createdAt": 1704060000000,
+ "updatedAt": 1704060000000,
+ "meta": {},
+ "pinnedMessages": [
+ {
+ "id": "pinned-architecture",
+ "role": "assistant",
+ "content": "Key architecture decision: React + tRPC + PostgreSQL",
+ "createdAt": "2024-01-01T08:00:00.000Z",
+ "model": "gpt-4",
+ "provider": "openai"
+ }
+ ]
+ },
+ {
+ "id": "msg-compare-trigger",
+ "role": "user",
+ "content": "Which state management should I use: Redux, Zustand, or Jotai?",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ {
+ "id": "parallel-group-state",
+ "role": "compareGroup",
+ "content": null,
+ "parentId": null,
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {},
+ "children": [
+ {
+ "id": "resp-redux",
+ "role": "assistant",
+ "content": "Redux: Best for large-scale apps with complex state logic...",
+ "createdAt": "2024-01-01T10:00:05.000Z",
+ "model": "gpt-4",
+ "provider": "openai"
+ },
+ {
+ "id": "resp-zustand",
+ "role": "assistant",
+ "content": "Zustand: Lightweight and simple, great for most React apps...",
+ "createdAt": "2024-01-01T10:00:06.000Z",
+ "model": "claude-3-5-sonnet",
+ "provider": "anthropic"
+ }
+ ]
+ },
+ {
+ "id": "msg-decision",
+ "role": "user",
+ "content": "I'll go with Zustand then. Let's start implementation.",
+ "parentId": null,
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "meta": {}
+ },
+ {
+ "id": "msg-implementation",
+ "role": "assistant",
+ "content": "Great choice! Here's how to set up Zustand with TypeScript...",
+ "parentId": "msg-decision",
+ "createdAt": 1704067215000,
+ "updatedAt": 1704067215000,
+ "meta": {},
+ "metadata": {
+ "totalInputTokens": 300,
+ "totalOutputTokens": 450,
+ "totalTokens": 750
+ }
+ }
+ ],
+ "messageMap": {
+ "comp-group-1": {
+ "id": "comp-group-1",
+ "role": "compressedGroup",
+ "content": "Summary: Initial project discussion about building a chat application.",
+ "parentId": null,
+ "createdAt": 1704060000000,
+ "updatedAt": 1704060000000,
+ "meta": {},
+ "pinnedMessages": [
+ {
+ "id": "pinned-architecture",
+ "role": "assistant",
+ "content": "Key architecture decision: React + tRPC + PostgreSQL",
+ "createdAt": "2024-01-01T08:00:00.000Z",
+ "model": "gpt-4",
+ "provider": "openai"
+ }
+ ]
+ },
+ "msg-compare-trigger": {
+ "id": "msg-compare-trigger",
+ "role": "user",
+ "content": "Which state management should I use: Redux, Zustand, or Jotai?",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ "parallel-group-state": {
+ "id": "parallel-group-state",
+ "role": "compareGroup",
+ "content": null,
+ "parentId": null,
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {},
+ "children": [
+ {
+ "id": "resp-redux",
+ "role": "assistant",
+ "content": "Redux: Best for large-scale apps with complex state logic...",
+ "createdAt": "2024-01-01T10:00:05.000Z",
+ "model": "gpt-4",
+ "provider": "openai"
+ },
+ {
+ "id": "resp-zustand",
+ "role": "assistant",
+ "content": "Zustand: Lightweight and simple, great for most React apps...",
+ "createdAt": "2024-01-01T10:00:06.000Z",
+ "model": "claude-3-5-sonnet",
+ "provider": "anthropic"
+ }
+ ]
+ },
+ "msg-decision": {
+ "id": "msg-decision",
+ "role": "user",
+ "content": "I'll go with Zustand then. Let's start implementation.",
+ "parentId": null,
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "meta": {}
+ },
+ "msg-implementation": {
+ "id": "msg-implementation",
+ "role": "assistant",
+ "content": "Great choice! Here's how to set up Zustand with TypeScript...",
+ "parentId": "msg-decision",
+ "createdAt": 1704067215000,
+ "updatedAt": 1704067215000,
+ "meta": {},
+ "metadata": {
+ "totalInputTokens": 300,
+ "totalOutputTokens": 450,
+ "totalTokens": 750
+ }
+ }
+ }
+}
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/multiple-compressions.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/multiple-compressions.json
new file mode 100644
index 00000000000..5fe7a830e28
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/multiple-compressions.json
@@ -0,0 +1,162 @@
+{
+ "contextTree": [
+ {
+ "id": "comp-group-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-middle-001",
+ "type": "message"
+ },
+ {
+ "id": "msg-middle-002",
+ "type": "message"
+ },
+ {
+ "id": "comp-group-2",
+ "type": "message"
+ },
+ {
+ "id": "msg-recent-001",
+ "type": "message"
+ },
+ {
+ "id": "msg-recent-002",
+ "type": "message"
+ }
+ ],
+ "flatList": [
+ {
+ "id": "comp-group-1",
+ "role": "compressedGroup",
+ "content": "Summary: Early conversation about project setup and initial requirements.",
+ "parentId": null,
+ "createdAt": 1704060000000,
+ "updatedAt": 1704060000000,
+ "meta": {},
+ "pinnedMessages": [
+ {
+ "id": "pinned-1-1",
+ "role": "assistant",
+ "content": "Key decision: Use TypeScript with strict mode",
+ "createdAt": "2024-01-01T08:00:00.000Z",
+ "model": "gpt-4",
+ "provider": "openai"
+ }
+ ]
+ },
+ {
+ "id": "msg-middle-001",
+ "role": "user",
+ "content": "Let's discuss the database schema",
+ "parentId": null,
+ "createdAt": 1704063600000,
+ "updatedAt": 1704063600000,
+ "meta": {}
+ },
+ {
+ "id": "msg-middle-002",
+ "role": "assistant",
+ "content": "Here's my suggested schema design...",
+ "parentId": "msg-middle-001",
+ "createdAt": 1704063605000,
+ "updatedAt": 1704063605000,
+ "meta": {}
+ },
+ {
+ "id": "comp-group-2",
+ "role": "compressedGroup",
+ "content": "Summary: Database schema discussions concluded with PostgreSQL + Drizzle ORM decision.",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {},
+ "pinnedMessages": []
+ },
+ {
+ "id": "msg-recent-001",
+ "role": "user",
+ "content": "Now let's implement the API endpoints",
+ "parentId": null,
+ "createdAt": 1704070800000,
+ "updatedAt": 1704070800000,
+ "meta": {}
+ },
+ {
+ "id": "msg-recent-002",
+ "role": "assistant",
+ "content": "I'll create RESTful endpoints for CRUD operations...",
+ "parentId": "msg-recent-001",
+ "createdAt": 1704070805000,
+ "updatedAt": 1704070805000,
+ "meta": {}
+ }
+ ],
+ "messageMap": {
+ "comp-group-1": {
+ "id": "comp-group-1",
+ "role": "compressedGroup",
+ "content": "Summary: Early conversation about project setup and initial requirements.",
+ "parentId": null,
+ "createdAt": 1704060000000,
+ "updatedAt": 1704060000000,
+ "meta": {},
+ "pinnedMessages": [
+ {
+ "id": "pinned-1-1",
+ "role": "assistant",
+ "content": "Key decision: Use TypeScript with strict mode",
+ "createdAt": "2024-01-01T08:00:00.000Z",
+ "model": "gpt-4",
+ "provider": "openai"
+ }
+ ]
+ },
+ "msg-middle-001": {
+ "id": "msg-middle-001",
+ "role": "user",
+ "content": "Let's discuss the database schema",
+ "parentId": null,
+ "createdAt": 1704063600000,
+ "updatedAt": 1704063600000,
+ "meta": {}
+ },
+ "msg-middle-002": {
+ "id": "msg-middle-002",
+ "role": "assistant",
+ "content": "Here's my suggested schema design...",
+ "parentId": "msg-middle-001",
+ "createdAt": 1704063605000,
+ "updatedAt": 1704063605000,
+ "meta": {}
+ },
+ "comp-group-2": {
+ "id": "comp-group-2",
+ "role": "compressedGroup",
+ "content": "Summary: Database schema discussions concluded with PostgreSQL + Drizzle ORM decision.",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {},
+ "pinnedMessages": []
+ },
+ "msg-recent-001": {
+ "id": "msg-recent-001",
+ "role": "user",
+ "content": "Now let's implement the API endpoints",
+ "parentId": null,
+ "createdAt": 1704070800000,
+ "updatedAt": 1704070800000,
+ "meta": {}
+ },
+ "msg-recent-002": {
+ "id": "msg-recent-002",
+ "role": "assistant",
+ "content": "I'll create RESTful endpoints for CRUD operations...",
+ "parentId": "msg-recent-001",
+ "createdAt": 1704070805000,
+ "updatedAt": 1704070805000,
+ "meta": {}
+ }
+ }
+}
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/parallel-group.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/parallel-group.json
new file mode 100644
index 00000000000..19c2a5f0a37
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/parallel-group.json
@@ -0,0 +1,110 @@
+{
+ "contextTree": [
+ {
+ "id": "msg-user-001",
+ "type": "message"
+ },
+ {
+ "id": "parallel-group-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-user-002",
+ "type": "message"
+ }
+ ],
+ "flatList": [
+ {
+ "id": "msg-user-001",
+ "role": "user",
+ "content": "Compare REST vs GraphQL for my use case",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ {
+ "id": "parallel-group-1",
+ "role": "compareGroup",
+ "content": null,
+ "parentId": null,
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {},
+ "children": [
+ {
+ "id": "parallel-resp-gpt4",
+ "role": "assistant",
+ "content": "From GPT-4's perspective: REST is simpler and well-suited for CRUD operations...",
+ "createdAt": "2024-01-01T10:00:05.000Z",
+ "model": "gpt-4",
+ "provider": "openai"
+ },
+ {
+ "id": "parallel-resp-claude",
+ "role": "assistant",
+ "content": "From Claude's perspective: GraphQL offers more flexibility with its query language...",
+ "createdAt": "2024-01-01T10:00:06.000Z",
+ "model": "claude-3-5-sonnet",
+ "provider": "anthropic"
+ }
+ ]
+ },
+ {
+ "id": "msg-user-002",
+ "role": "user",
+ "content": "Thanks for the comparison!",
+ "parentId": null,
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "meta": {}
+ }
+ ],
+ "messageMap": {
+ "msg-user-001": {
+ "id": "msg-user-001",
+ "role": "user",
+ "content": "Compare REST vs GraphQL for my use case",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ "parallel-group-1": {
+ "id": "parallel-group-1",
+ "role": "compareGroup",
+ "content": null,
+ "parentId": null,
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {},
+ "children": [
+ {
+ "id": "parallel-resp-gpt4",
+ "role": "assistant",
+ "content": "From GPT-4's perspective: REST is simpler and well-suited for CRUD operations...",
+ "createdAt": "2024-01-01T10:00:05.000Z",
+ "model": "gpt-4",
+ "provider": "openai"
+ },
+ {
+ "id": "parallel-resp-claude",
+ "role": "assistant",
+ "content": "From Claude's perspective: GraphQL offers more flexibility with its query language...",
+ "createdAt": "2024-01-01T10:00:06.000Z",
+ "model": "claude-3-5-sonnet",
+ "provider": "anthropic"
+ }
+ ]
+ },
+ "msg-user-002": {
+ "id": "msg-user-002",
+ "role": "user",
+ "content": "Thanks for the comparison!",
+ "parentId": null,
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "meta": {}
+ }
+ }
+}
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/simple-compression.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/simple-compression.json
new file mode 100644
index 00000000000..01bc98b1ed8
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/compression/simple-compression.json
@@ -0,0 +1,122 @@
+{
+ "contextTree": [
+ {
+ "id": "comp-group-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-recent-001",
+ "type": "message"
+ },
+ {
+ "id": "msg-recent-002",
+ "type": "message"
+ }
+ ],
+ "flatList": [
+ {
+ "id": "comp-group-1",
+ "role": "compressedGroup",
+ "content": "Summary: User asked about prime numbers. Assistant provided implementation and test cases.",
+ "parentId": null,
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {},
+ "lastMessageId": "msg-compressed-last",
+ "pinnedMessages": [
+ {
+ "id": "pinned-msg-001",
+ "role": "assistant",
+ "content": "Here's a prime number checker function...",
+ "createdAt": "2024-01-01T10:01:00.000Z",
+ "model": "gpt-4",
+ "provider": "openai"
+ },
+ {
+ "id": "pinned-msg-002",
+ "role": "user",
+ "content": "Can you add documentation?",
+ "createdAt": "2024-01-01T10:02:00.000Z",
+ "model": null,
+ "provider": null
+ }
+ ]
+ },
+ {
+ "id": "msg-recent-001",
+ "role": "user",
+ "content": "Now let's optimize it further",
+ "parentId": null,
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "meta": {}
+ },
+ {
+ "id": "msg-recent-002",
+ "role": "assistant",
+ "content": "Sure! Here's an optimized version using the Sieve of Eratosthenes...",
+ "parentId": "msg-recent-001",
+ "createdAt": 1704067215000,
+ "updatedAt": 1704067215000,
+ "meta": {},
+ "metadata": {
+ "totalInputTokens": 200,
+ "totalOutputTokens": 150,
+ "totalTokens": 350
+ }
+ }
+ ],
+ "messageMap": {
+ "comp-group-1": {
+ "id": "comp-group-1",
+ "role": "compressedGroup",
+ "content": "Summary: User asked about prime numbers. Assistant provided implementation and test cases.",
+ "parentId": null,
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {},
+ "lastMessageId": "msg-compressed-last",
+ "pinnedMessages": [
+ {
+ "id": "pinned-msg-001",
+ "role": "assistant",
+ "content": "Here's a prime number checker function...",
+ "createdAt": "2024-01-01T10:01:00.000Z",
+ "model": "gpt-4",
+ "provider": "openai"
+ },
+ {
+ "id": "pinned-msg-002",
+ "role": "user",
+ "content": "Can you add documentation?",
+ "createdAt": "2024-01-01T10:02:00.000Z",
+ "model": null,
+ "provider": null
+ }
+ ]
+ },
+ "msg-recent-001": {
+ "id": "msg-recent-001",
+ "role": "user",
+ "content": "Now let's optimize it further",
+ "parentId": null,
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "meta": {}
+ },
+ "msg-recent-002": {
+ "id": "msg-recent-002",
+ "role": "assistant",
+ "content": "Sure! Here's an optimized version using the Sieve of Eratosthenes...",
+ "parentId": "msg-recent-001",
+ "createdAt": 1704067215000,
+ "updatedAt": 1704067215000,
+ "meta": {},
+ "metadata": {
+ "totalInputTokens": 200,
+ "totalOutputTokens": 150,
+ "totalTokens": 350
+ }
+ }
+ }
+}
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/index.ts b/packages/conversation-flow/src/__tests__/fixtures/outputs/index.ts
new file mode 100644
index 00000000000..768db9bdccd
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/index.ts
@@ -0,0 +1,22 @@
+import type { SerializedParseResult } from '..';
+import { agentCouncil } from './agentCouncil';
+import { agentGroup } from './agentGroup';
+import assistantChainWithFollowup from './assistant-chain-with-followup.json';
+import { assistantGroup } from './assistantGroup';
+import { branch } from './branch';
+import { compare } from './compare';
+import { compression } from './compression';
+import linearConversation from './linear-conversation.json';
+import { tasks } from './tasks';
+
+export const outputs = {
+ agentCouncil,
+ agentGroup,
+ assistantChainWithFollowup: assistantChainWithFollowup as unknown as SerializedParseResult,
+ assistantGroup,
+ branch,
+ compare,
+ compression,
+ linearConversation: linearConversation as unknown as SerializedParseResult,
+ tasks,
+};
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/index.ts b/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/index.ts
index 2285e951f65..11ba656d103 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/index.ts
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/index.ts
@@ -1,10 +1,14 @@
import type { SerializedParseResult } from '../../index';
+import multiTasksWithSummary from './multi-tasks-with-summary.json';
import simple from './simple.json';
import singleTaskWithToolChain from './single-task-with-tool-chain.json';
+import withAssistantGroup from './with-assistant-group.json';
import withSummary from './with-summary.json';
export const tasks = {
+ multiTasksWithSummary: multiTasksWithSummary as unknown as SerializedParseResult,
simple: simple as unknown as SerializedParseResult,
singleTaskWithToolChain: singleTaskWithToolChain as unknown as SerializedParseResult,
+ withAssistantGroup: withAssistantGroup as unknown as SerializedParseResult,
withSummary: withSummary as unknown as SerializedParseResult,
};
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/multi-tasks-with-summary.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/multi-tasks-with-summary.json
new file mode 100644
index 00000000000..e976b804877
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/multi-tasks-with-summary.json
@@ -0,0 +1,592 @@
+{
+ "contextTree": [
+ {
+ "id": "msg-user-1",
+ "type": "message"
+ },
+ {
+ "children": [
+ {
+ "id": "msg-assistant-1",
+ "type": "message",
+ "tools": ["msg-tool-1"]
+ }
+ ],
+ "id": "msg-assistant-1",
+ "type": "assistantGroup"
+ },
+ {
+ "children": [
+ {
+ "id": "msg-task-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-2",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-3",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-4",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-5",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-6",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-7",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-8",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-9",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-10",
+ "type": "message"
+ }
+ ],
+ "id": "tasks-msg-tool-1-msg-task-1-msg-task-2-msg-task-3-msg-task-4-msg-task-5-msg-task-6-msg-task-7-msg-task-8-msg-task-9-msg-task-10",
+ "messageId": "msg-tool-1",
+ "type": "tasks"
+ },
+ {
+ "id": "msg-assistant-summary",
+ "type": "message"
+ }
+ ],
+ "flatList": [
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Process these files in 10 parallel tasks and give me a summary.",
+ "parentId": null,
+ "createdAt": 1735526559382,
+ "updatedAt": 1735526559382
+ },
+ {
+ "id": "msg-assistant-1",
+ "role": "assistantGroup",
+ "content": "",
+ "parentId": "msg-user-1",
+ "createdAt": 1735526560163,
+ "updatedAt": 1735526585550,
+ "model": "gpt-4",
+ "provider": "openai",
+ "children": [
+ {
+ "content": "I'll process these files in 10 parallel tasks.",
+ "id": "msg-assistant-1",
+ "tools": [
+ {
+ "id": "call_exec_tasks_1",
+ "type": "builtin",
+ "apiName": "callSubAgents",
+ "arguments": "{\"tasks\": [{\"description\": \"Task 1\"}, {\"description\": \"Task 2\"}, {\"description\": \"Task 3\"}, {\"description\": \"Task 4\"}, {\"description\": \"Task 5\"}, {\"description\": \"Task 6\"}, {\"description\": \"Task 7\"}, {\"description\": \"Task 8\"}, {\"description\": \"Task 9\"}, {\"description\": \"Task 10\"}]}",
+ "identifier": "lobe-agent",
+ "result": {
+ "content": "Triggered 10 async tasks",
+ "id": "msg-tool-1",
+ "state": {
+ "type": "execSubAgents",
+ "tasks": [
+ {
+ "description": "Task 1"
+ },
+ {
+ "description": "Task 2"
+ },
+ {
+ "description": "Task 3"
+ },
+ {
+ "description": "Task 4"
+ },
+ {
+ "description": "Task 5"
+ },
+ {
+ "description": "Task 6"
+ },
+ {
+ "description": "Task 7"
+ },
+ {
+ "description": "Task 8"
+ },
+ {
+ "description": "Task 9"
+ },
+ {
+ "description": "Task 10"
+ }
+ ],
+ "parentMessageId": "msg-tool-1"
+ }
+ },
+ "result_msg_id": "msg-tool-1"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "content": "",
+ "createdAt": 1735526594643,
+ "extra": {
+ "parentMessageId": "msg-tool-1"
+ },
+ "id": "tasks-msg-tool-1-msg-task-1-msg-task-2-msg-task-3-msg-task-4-msg-task-5-msg-task-6-msg-task-7-msg-task-8-msg-task-9-msg-task-10",
+ "role": "tasks",
+ "tasks": [
+ {
+ "id": "msg-task-1",
+ "role": "task",
+ "content": "Task 1 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526594643,
+ "updatedAt": 1735526756262,
+ "taskDetail": {
+ "duration": 120000,
+ "status": "completed",
+ "threadId": "thd_task_1",
+ "title": "Task 1",
+ "totalCost": 0.015,
+ "totalMessages": 15,
+ "totalTokens": 100000
+ }
+ },
+ {
+ "id": "msg-task-2",
+ "role": "task",
+ "content": "Task 2 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526595000,
+ "updatedAt": 1735526757000,
+ "taskDetail": {
+ "duration": 121000,
+ "status": "completed",
+ "threadId": "thd_task_2",
+ "title": "Task 2",
+ "totalCost": 0.016,
+ "totalMessages": 16,
+ "totalTokens": 101000
+ }
+ },
+ {
+ "id": "msg-task-3",
+ "role": "task",
+ "content": "Task 3 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526596000,
+ "updatedAt": 1735526758000,
+ "taskDetail": {
+ "duration": 122000,
+ "status": "completed",
+ "threadId": "thd_task_3",
+ "title": "Task 3",
+ "totalCost": 0.017,
+ "totalMessages": 17,
+ "totalTokens": 102000
+ }
+ },
+ {
+ "id": "msg-task-4",
+ "role": "task",
+ "content": "Task 4 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526597000,
+ "updatedAt": 1735526759000,
+ "taskDetail": {
+ "duration": 123000,
+ "status": "completed",
+ "threadId": "thd_task_4",
+ "title": "Task 4",
+ "totalCost": 0.018,
+ "totalMessages": 18,
+ "totalTokens": 103000
+ }
+ },
+ {
+ "id": "msg-task-5",
+ "role": "task",
+ "content": "Task 5 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526598000,
+ "updatedAt": 1735526760000,
+ "taskDetail": {
+ "duration": 124000,
+ "status": "completed",
+ "threadId": "thd_task_5",
+ "title": "Task 5",
+ "totalCost": 0.019,
+ "totalMessages": 19,
+ "totalTokens": 104000
+ }
+ },
+ {
+ "id": "msg-task-6",
+ "role": "task",
+ "content": "Task 6 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526599000,
+ "updatedAt": 1735526761000,
+ "taskDetail": {
+ "duration": 125000,
+ "status": "completed",
+ "threadId": "thd_task_6",
+ "title": "Task 6",
+ "totalCost": 0.02,
+ "totalMessages": 20,
+ "totalTokens": 105000
+ }
+ },
+ {
+ "id": "msg-task-7",
+ "role": "task",
+ "content": "Task 7 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526600000,
+ "updatedAt": 1735526762000,
+ "taskDetail": {
+ "duration": 126000,
+ "status": "completed",
+ "threadId": "thd_task_7",
+ "title": "Task 7",
+ "totalCost": 0.021,
+ "totalMessages": 21,
+ "totalTokens": 106000
+ }
+ },
+ {
+ "id": "msg-task-8",
+ "role": "task",
+ "content": "Task 8 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526601000,
+ "updatedAt": 1735526763000,
+ "taskDetail": {
+ "duration": 127000,
+ "status": "completed",
+ "threadId": "thd_task_8",
+ "title": "Task 8",
+ "totalCost": 0.022,
+ "totalMessages": 22,
+ "totalTokens": 107000
+ }
+ },
+ {
+ "id": "msg-task-9",
+ "role": "task",
+ "content": "Task 9 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526602000,
+ "updatedAt": 1735526764000,
+ "taskDetail": {
+ "duration": 128000,
+ "status": "completed",
+ "threadId": "thd_task_9",
+ "title": "Task 9",
+ "totalCost": 0.023,
+ "totalMessages": 23,
+ "totalTokens": 108000
+ }
+ },
+ {
+ "id": "msg-task-10",
+ "role": "task",
+ "content": "Task 10 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526603000,
+ "updatedAt": 1735526765000,
+ "taskDetail": {
+ "duration": 129000,
+ "status": "completed",
+ "threadId": "thd_task_10",
+ "title": "Task 10",
+ "totalCost": 0.024,
+ "totalMessages": 24,
+ "totalTokens": 109000
+ }
+ }
+ ],
+ "updatedAt": 1735526765000
+ },
+ {
+ "id": "msg-assistant-summary",
+ "role": "assistant",
+ "content": "All 10 tasks completed successfully! Here's the comprehensive summary...",
+ "parentId": "msg-task-10",
+ "createdAt": 1735526810000,
+ "updatedAt": 1735526820000,
+ "model": "gpt-4",
+ "provider": "openai"
+ }
+ ],
+ "messageMap": {
+ "msg-user-1": {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Process these files in 10 parallel tasks and give me a summary.",
+ "parentId": null,
+ "createdAt": 1735526559382,
+ "updatedAt": 1735526559382
+ },
+ "msg-assistant-1": {
+ "id": "msg-assistant-1",
+ "role": "assistant",
+ "content": "I'll process these files in 10 parallel tasks.",
+ "parentId": "msg-user-1",
+ "createdAt": 1735526560163,
+ "updatedAt": 1735526585550,
+ "model": "gpt-4",
+ "provider": "openai",
+ "tools": [
+ {
+ "id": "call_exec_tasks_1",
+ "type": "builtin",
+ "apiName": "callSubAgents",
+ "arguments": "{\"tasks\": [{\"description\": \"Task 1\"}, {\"description\": \"Task 2\"}, {\"description\": \"Task 3\"}, {\"description\": \"Task 4\"}, {\"description\": \"Task 5\"}, {\"description\": \"Task 6\"}, {\"description\": \"Task 7\"}, {\"description\": \"Task 8\"}, {\"description\": \"Task 9\"}, {\"description\": \"Task 10\"}]}",
+ "identifier": "lobe-agent"
+ }
+ ]
+ },
+ "msg-tool-1": {
+ "id": "msg-tool-1",
+ "role": "tool",
+ "content": "Triggered 10 async tasks",
+ "parentId": "msg-assistant-1",
+ "tool_call_id": "call_exec_tasks_1",
+ "createdAt": 1735526588116,
+ "updatedAt": 1735526591337,
+ "pluginState": {
+ "type": "execSubAgents",
+ "tasks": [
+ {
+ "description": "Task 1"
+ },
+ {
+ "description": "Task 2"
+ },
+ {
+ "description": "Task 3"
+ },
+ {
+ "description": "Task 4"
+ },
+ {
+ "description": "Task 5"
+ },
+ {
+ "description": "Task 6"
+ },
+ {
+ "description": "Task 7"
+ },
+ {
+ "description": "Task 8"
+ },
+ {
+ "description": "Task 9"
+ },
+ {
+ "description": "Task 10"
+ }
+ ],
+ "parentMessageId": "msg-tool-1"
+ }
+ },
+ "msg-task-1": {
+ "id": "msg-task-1",
+ "role": "task",
+ "content": "Task 1 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526594643,
+ "updatedAt": 1735526756262,
+ "taskDetail": {
+ "duration": 120000,
+ "status": "completed",
+ "threadId": "thd_task_1",
+ "title": "Task 1",
+ "totalCost": 0.015,
+ "totalMessages": 15,
+ "totalTokens": 100000
+ }
+ },
+ "msg-task-2": {
+ "id": "msg-task-2",
+ "role": "task",
+ "content": "Task 2 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526595000,
+ "updatedAt": 1735526757000,
+ "taskDetail": {
+ "duration": 121000,
+ "status": "completed",
+ "threadId": "thd_task_2",
+ "title": "Task 2",
+ "totalCost": 0.016,
+ "totalMessages": 16,
+ "totalTokens": 101000
+ }
+ },
+ "msg-task-3": {
+ "id": "msg-task-3",
+ "role": "task",
+ "content": "Task 3 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526596000,
+ "updatedAt": 1735526758000,
+ "taskDetail": {
+ "duration": 122000,
+ "status": "completed",
+ "threadId": "thd_task_3",
+ "title": "Task 3",
+ "totalCost": 0.017,
+ "totalMessages": 17,
+ "totalTokens": 102000
+ }
+ },
+ "msg-task-4": {
+ "id": "msg-task-4",
+ "role": "task",
+ "content": "Task 4 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526597000,
+ "updatedAt": 1735526759000,
+ "taskDetail": {
+ "duration": 123000,
+ "status": "completed",
+ "threadId": "thd_task_4",
+ "title": "Task 4",
+ "totalCost": 0.018,
+ "totalMessages": 18,
+ "totalTokens": 103000
+ }
+ },
+ "msg-task-5": {
+ "id": "msg-task-5",
+ "role": "task",
+ "content": "Task 5 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526598000,
+ "updatedAt": 1735526760000,
+ "taskDetail": {
+ "duration": 124000,
+ "status": "completed",
+ "threadId": "thd_task_5",
+ "title": "Task 5",
+ "totalCost": 0.019,
+ "totalMessages": 19,
+ "totalTokens": 104000
+ }
+ },
+ "msg-task-6": {
+ "id": "msg-task-6",
+ "role": "task",
+ "content": "Task 6 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526599000,
+ "updatedAt": 1735526761000,
+ "taskDetail": {
+ "duration": 125000,
+ "status": "completed",
+ "threadId": "thd_task_6",
+ "title": "Task 6",
+ "totalCost": 0.02,
+ "totalMessages": 20,
+ "totalTokens": 105000
+ }
+ },
+ "msg-task-7": {
+ "id": "msg-task-7",
+ "role": "task",
+ "content": "Task 7 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526600000,
+ "updatedAt": 1735526762000,
+ "taskDetail": {
+ "duration": 126000,
+ "status": "completed",
+ "threadId": "thd_task_7",
+ "title": "Task 7",
+ "totalCost": 0.021,
+ "totalMessages": 21,
+ "totalTokens": 106000
+ }
+ },
+ "msg-task-8": {
+ "id": "msg-task-8",
+ "role": "task",
+ "content": "Task 8 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526601000,
+ "updatedAt": 1735526763000,
+ "taskDetail": {
+ "duration": 127000,
+ "status": "completed",
+ "threadId": "thd_task_8",
+ "title": "Task 8",
+ "totalCost": 0.022,
+ "totalMessages": 22,
+ "totalTokens": 107000
+ }
+ },
+ "msg-task-9": {
+ "id": "msg-task-9",
+ "role": "task",
+ "content": "Task 9 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526602000,
+ "updatedAt": 1735526764000,
+ "taskDetail": {
+ "duration": 128000,
+ "status": "completed",
+ "threadId": "thd_task_9",
+ "title": "Task 9",
+ "totalCost": 0.023,
+ "totalMessages": 23,
+ "totalTokens": 108000
+ }
+ },
+ "msg-task-10": {
+ "id": "msg-task-10",
+ "role": "task",
+ "content": "Task 10 completed with results...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526603000,
+ "updatedAt": 1735526765000,
+ "taskDetail": {
+ "duration": 129000,
+ "status": "completed",
+ "threadId": "thd_task_10",
+ "title": "Task 10",
+ "totalCost": 0.024,
+ "totalMessages": 24,
+ "totalTokens": 109000
+ }
+ },
+ "msg-assistant-summary": {
+ "id": "msg-assistant-summary",
+ "role": "assistant",
+ "content": "All 10 tasks completed successfully! Here's the comprehensive summary...",
+ "parentId": "msg-task-10",
+ "createdAt": 1735526810000,
+ "updatedAt": 1735526820000,
+ "model": "gpt-4",
+ "provider": "openai"
+ }
+ }
+}
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/with-assistant-group.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/with-assistant-group.json
new file mode 100644
index 00000000000..6e22ce176e1
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/with-assistant-group.json
@@ -0,0 +1,392 @@
+{
+ "contextTree": [
+ {
+ "id": "msg-user-1",
+ "type": "message"
+ },
+ {
+ "children": [
+ {
+ "id": "msg-assistant-1",
+ "type": "message",
+ "tools": ["msg-tool-1"]
+ }
+ ],
+ "id": "msg-assistant-1",
+ "type": "assistantGroup"
+ },
+ {
+ "children": [
+ {
+ "id": "msg-task-llm",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-agents",
+ "type": "message"
+ },
+ {
+ "id": "msg-task-rag",
+ "type": "message"
+ }
+ ],
+ "id": "tasks-msg-tool-1-msg-task-llm-msg-task-agents-msg-task-rag",
+ "messageId": "msg-tool-1",
+ "type": "tasks"
+ },
+ {
+ "children": [
+ {
+ "id": "msg-assistant-after-task",
+ "type": "message",
+ "tools": ["msg-tool-list-files"]
+ },
+ {
+ "id": "msg-assistant-final",
+ "type": "message"
+ }
+ ],
+ "id": "msg-assistant-after-task",
+ "type": "assistantGroup"
+ }
+ ],
+ "flatList": [
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Create three parallel tasks to research AI topics.",
+ "parentId": null,
+ "createdAt": 1735526559382,
+ "updatedAt": 1735526559382
+ },
+ {
+ "id": "msg-assistant-1",
+ "role": "assistantGroup",
+ "content": "",
+ "parentId": "msg-user-1",
+ "createdAt": 1735526560163,
+ "updatedAt": 1735526585550,
+ "model": "gpt-4",
+ "provider": "openai",
+ "children": [
+ {
+ "content": "Creating three parallel research tasks.",
+ "id": "msg-assistant-1",
+ "tools": [
+ {
+ "id": "call_exec_tasks_1",
+ "type": "builtin",
+ "apiName": "callSubAgents",
+ "arguments": "{\"tasks\": [{\"description\": \"Research LLM architectures\"}, {\"description\": \"Research AI agents\"}, {\"description\": \"Research RAG systems\"}]}",
+ "identifier": "lobe-agent",
+ "result": {
+ "content": "Triggered 3 async tasks",
+ "id": "msg-tool-1",
+ "state": {
+ "type": "execSubAgents",
+ "tasks": [
+ {
+ "description": "Research LLM architectures"
+ },
+ {
+ "description": "Research AI agents"
+ },
+ {
+ "description": "Research RAG systems"
+ }
+ ],
+ "parentMessageId": "msg-tool-1"
+ }
+ },
+ "result_msg_id": "msg-tool-1"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "content": "",
+ "createdAt": 1735526594643,
+ "extra": {
+ "parentMessageId": "msg-tool-1"
+ },
+ "id": "tasks-msg-tool-1-msg-task-llm-msg-task-agents-msg-task-rag",
+ "role": "tasks",
+ "tasks": [
+ {
+ "id": "msg-task-llm",
+ "role": "task",
+ "content": "# LLM Architectures\n\nTransformer-based models dominate...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526594643,
+ "updatedAt": 1735526756262,
+ "taskDetail": {
+ "duration": 120000,
+ "status": "completed",
+ "threadId": "thd_llm",
+ "title": "Research LLM architectures",
+ "totalCost": 0.015,
+ "totalMessages": 15,
+ "totalTokens": 100000
+ }
+ },
+ {
+ "id": "msg-task-agents",
+ "role": "task",
+ "content": "# AI Agents\n\nAutonomous agents using LLMs...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526595647,
+ "updatedAt": 1735526792430,
+ "taskDetail": {
+ "duration": 150000,
+ "status": "completed",
+ "threadId": "thd_agents",
+ "title": "Research AI agents",
+ "totalCost": 0.018,
+ "totalMessages": 20,
+ "totalTokens": 120000
+ }
+ },
+ {
+ "id": "msg-task-rag",
+ "role": "task",
+ "content": "# RAG Systems\n\nRetrieval Augmented Generation combines...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526596000,
+ "updatedAt": 1735526800000,
+ "taskDetail": {
+ "duration": 130000,
+ "status": "completed",
+ "threadId": "thd_rag",
+ "title": "Research RAG systems",
+ "totalCost": 0.016,
+ "totalMessages": 18,
+ "totalTokens": 110000
+ }
+ }
+ ],
+ "updatedAt": 1735526800000
+ },
+ {
+ "id": "msg-assistant-after-task",
+ "role": "assistantGroup",
+ "content": "",
+ "parentId": "msg-task-rag",
+ "createdAt": 1735526810000,
+ "updatedAt": 1735526815000,
+ "agentId": "agent-main",
+ "model": "gpt-4",
+ "provider": "openai",
+ "children": [
+ {
+ "content": "All tasks completed. Let me check the analysis files created.",
+ "id": "msg-assistant-after-task",
+ "tools": [
+ {
+ "id": "call_list_files",
+ "type": "builtin",
+ "apiName": "listFiles",
+ "arguments": "{\"path\": \"/analysis\"}",
+ "identifier": "lobe-local-system",
+ "result": {
+ "content": "./ANALYSIS_1.md\n./ANALYSIS_2.md\n./ANALYSIS_3.md",
+ "id": "msg-tool-list-files",
+ "state": {
+ "result": {
+ "output": "./ANALYSIS_1.md\n./ANALYSIS_2.md\n./ANALYSIS_3.md",
+ "success": true
+ }
+ }
+ },
+ "result_msg_id": "msg-tool-list-files"
+ }
+ ],
+ "usage": {
+ "cost": 0.001,
+ "totalInputTokens": 100,
+ "totalOutputTokens": 50,
+ "totalTokens": 150
+ }
+ },
+ {
+ "content": "I found 3 analysis files. Let me summarize the findings for you.",
+ "id": "msg-assistant-final",
+ "usage": {
+ "cost": 0.002,
+ "totalInputTokens": 200,
+ "totalOutputTokens": 80,
+ "totalTokens": 280
+ }
+ }
+ ],
+ "usage": {
+ "totalInputTokens": 300,
+ "totalOutputTokens": 130,
+ "totalTokens": 430,
+ "cost": 0.003
+ }
+ }
+ ],
+ "messageMap": {
+ "msg-user-1": {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Create three parallel tasks to research AI topics.",
+ "parentId": null,
+ "createdAt": 1735526559382,
+ "updatedAt": 1735526559382
+ },
+ "msg-assistant-1": {
+ "id": "msg-assistant-1",
+ "role": "assistant",
+ "content": "Creating three parallel research tasks.",
+ "parentId": "msg-user-1",
+ "createdAt": 1735526560163,
+ "updatedAt": 1735526585550,
+ "model": "gpt-4",
+ "provider": "openai",
+ "tools": [
+ {
+ "id": "call_exec_tasks_1",
+ "type": "builtin",
+ "apiName": "callSubAgents",
+ "arguments": "{\"tasks\": [{\"description\": \"Research LLM architectures\"}, {\"description\": \"Research AI agents\"}, {\"description\": \"Research RAG systems\"}]}",
+ "identifier": "lobe-agent"
+ }
+ ]
+ },
+ "msg-tool-1": {
+ "id": "msg-tool-1",
+ "role": "tool",
+ "content": "Triggered 3 async tasks",
+ "parentId": "msg-assistant-1",
+ "tool_call_id": "call_exec_tasks_1",
+ "createdAt": 1735526588116,
+ "updatedAt": 1735526591337,
+ "pluginState": {
+ "type": "execSubAgents",
+ "tasks": [
+ {
+ "description": "Research LLM architectures"
+ },
+ {
+ "description": "Research AI agents"
+ },
+ {
+ "description": "Research RAG systems"
+ }
+ ],
+ "parentMessageId": "msg-tool-1"
+ }
+ },
+ "msg-task-llm": {
+ "id": "msg-task-llm",
+ "role": "task",
+ "content": "# LLM Architectures\n\nTransformer-based models dominate...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526594643,
+ "updatedAt": 1735526756262,
+ "taskDetail": {
+ "duration": 120000,
+ "status": "completed",
+ "threadId": "thd_llm",
+ "title": "Research LLM architectures",
+ "totalCost": 0.015,
+ "totalMessages": 15,
+ "totalTokens": 100000
+ }
+ },
+ "msg-task-agents": {
+ "id": "msg-task-agents",
+ "role": "task",
+ "content": "# AI Agents\n\nAutonomous agents using LLMs...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526595647,
+ "updatedAt": 1735526792430,
+ "taskDetail": {
+ "duration": 150000,
+ "status": "completed",
+ "threadId": "thd_agents",
+ "title": "Research AI agents",
+ "totalCost": 0.018,
+ "totalMessages": 20,
+ "totalTokens": 120000
+ }
+ },
+ "msg-task-rag": {
+ "id": "msg-task-rag",
+ "role": "task",
+ "content": "# RAG Systems\n\nRetrieval Augmented Generation combines...",
+ "parentId": "msg-tool-1",
+ "createdAt": 1735526596000,
+ "updatedAt": 1735526800000,
+ "taskDetail": {
+ "duration": 130000,
+ "status": "completed",
+ "threadId": "thd_rag",
+ "title": "Research RAG systems",
+ "totalCost": 0.016,
+ "totalMessages": 18,
+ "totalTokens": 110000
+ }
+ },
+ "msg-assistant-after-task": {
+ "id": "msg-assistant-after-task",
+ "role": "assistant",
+ "content": "All tasks completed. Let me check the analysis files created.",
+ "parentId": "msg-task-rag",
+ "createdAt": 1735526810000,
+ "updatedAt": 1735526815000,
+ "agentId": "agent-main",
+ "model": "gpt-4",
+ "provider": "openai",
+ "tools": [
+ {
+ "id": "call_list_files",
+ "type": "builtin",
+ "apiName": "listFiles",
+ "arguments": "{\"path\": \"/analysis\"}",
+ "identifier": "lobe-local-system"
+ }
+ ],
+ "metadata": {
+ "totalInputTokens": 100,
+ "totalOutputTokens": 50,
+ "totalTokens": 150,
+ "cost": 0.001
+ }
+ },
+ "msg-tool-list-files": {
+ "id": "msg-tool-list-files",
+ "role": "tool",
+ "content": "./ANALYSIS_1.md\n./ANALYSIS_2.md\n./ANALYSIS_3.md",
+ "parentId": "msg-assistant-after-task",
+ "tool_call_id": "call_list_files",
+ "createdAt": 1735526816000,
+ "updatedAt": 1735526817000,
+ "pluginState": {
+ "result": {
+ "output": "./ANALYSIS_1.md\n./ANALYSIS_2.md\n./ANALYSIS_3.md",
+ "success": true
+ }
+ }
+ },
+ "msg-assistant-final": {
+ "id": "msg-assistant-final",
+ "role": "assistant",
+ "content": "I found 3 analysis files. Let me summarize the findings for you.",
+ "parentId": "msg-tool-list-files",
+ "createdAt": 1735526820000,
+ "updatedAt": 1735526825000,
+ "agentId": "agent-main",
+ "model": "gpt-4",
+ "provider": "openai",
+ "metadata": {
+ "totalInputTokens": 200,
+ "totalOutputTokens": 80,
+ "totalTokens": 280,
+ "cost": 0.002
+ }
+ }
+ }
+}
diff --git a/packages/conversation-flow/src/__tests__/parse.test.ts b/packages/conversation-flow/src/__tests__/parse.test.ts
index 757be89e369..c8e64c12164 100644
--- a/packages/conversation-flow/src/__tests__/parse.test.ts
+++ b/packages/conversation-flow/src/__tests__/parse.test.ts
@@ -435,6 +435,8 @@ describe('parse', () => {
'msg-agent-devops-1',
'msg-agent-architect-1',
]);
+
+ expect(serializeParseResult(result)).toEqual(outputs.agentCouncil.simple);
});
// Regression (server runtime tree): the server-side group orchestration parents
@@ -520,6 +522,8 @@ describe('parse', () => {
// No separate agentCouncil message; the council is a block with 3 members.
expect(result.flatList.some((m) => m.role === 'agentCouncil')).toBe(false);
expect(findCouncilBlock(result)?.council).toHaveLength(3);
+
+ expect(serializeParseResult(result)).toEqual(outputs.agentCouncil.withSupervisorReply);
});
// Regression: the supervisor's post-council reply must surface no matter which council
@@ -793,6 +797,8 @@ describe('parse', () => {
expect((supervisorSummary as any)?.children[0].content).toBe('调研完成!这是综合汇总报告...');
// The top-level content should be empty
expect(supervisorSummary?.content).toBe('');
+
+ expect(serializeParseResult(result)).toEqual(outputs.agentGroup.supervisorContentOnly);
});
it('should handle supervisor summary after multiple tasks (content folded into children)', () => {
@@ -815,6 +821,8 @@ describe('parse', () => {
expect(supervisorSummary.content).toBe(''); // content should be empty
expect((supervisorSummary as any).children).toHaveLength(1);
expect((supervisorSummary as any).children[0].content).toBe('调研完成!这是综合汇总报告...');
+
+ expect(serializeParseResult(result)).toEqual(outputs.agentGroup.supervisorAfterMultiTasks);
});
});
@@ -881,6 +889,8 @@ describe('parse', () => {
// 4. The summary message should be present and accessible
expect(result.flatList[3].id).toBe('msg-assistant-summary');
expect(result.flatList[3].content).toContain('All 10 tasks completed');
+
+ expect(serializeParseResult(result)).toEqual(outputs.tasks.multiTasksWithSummary);
});
it('should handle single sub-agent (callSubAgent) with tool chain after completion', () => {
@@ -909,10 +919,36 @@ describe('parse', () => {
expect(lastGroup.children[0].tools).toBeDefined();
expect(lastGroup.children[0].tools[0].result_msg_id).toBe('msg-tool-list-files');
expect(lastGroup.children[1].id).toBe('msg-assistant-final');
+
+ expect(serializeParseResult(result)).toEqual(outputs.tasks.withAssistantGroup);
});
});
describe('Compression', () => {
+ it('should parse a simple compressedGroup with follow-up turn', () => {
+ const result = parse(inputs.compression.simpleCompression);
+
+ expect(serializeParseResult(result)).toEqual(outputs.compression.simpleCompression);
+ });
+
+ it('should parse multiple compressedGroups in one conversation', () => {
+ const result = parse(inputs.compression.multipleCompressions);
+
+ expect(serializeParseResult(result)).toEqual(outputs.compression.multipleCompressions);
+ });
+
+ it('should parse a standalone parallel compareGroup', () => {
+ const result = parse(inputs.compression.parallelGroup);
+
+ expect(serializeParseResult(result)).toEqual(outputs.compression.parallelGroup);
+ });
+
+ it('should parse compressedGroup and compareGroup mixed in one conversation', () => {
+ const result = parse(inputs.compression.mixedGroups);
+
+ expect(serializeParseResult(result)).toEqual(outputs.compression.mixedGroups);
+ });
+
it('should keep follow-up chain visible after compressedGroup from recursive tool result', () => {
// Data provenance:
// - The compressedGroup + nested assistant/tool structure is abstracted from the
diff --git a/packages/conversation-flow/src/structuring.ts b/packages/conversation-flow/src/structuring.ts
index c970272d36e..7a7ed505fcf 100644
--- a/packages/conversation-flow/src/structuring.ts
+++ b/packages/conversation-flow/src/structuring.ts
@@ -11,20 +11,28 @@ import type { HelperMaps, IdNode } from './types';
export function buildIdTree(helperMaps: HelperMaps): IdNode[] {
const { childrenMap, messageMap } = helperMaps;
- // Build tree recursively starting from root messages (parentId = null)
- const buildTree = (messageId: string): IdNode => {
- const childIds = childrenMap.get(messageId) ?? [];
-
- // Filter children to only include those in main flow (not in threads)
- const mainFlowChildIds = childIds.filter((childId) => {
- const child = messageMap.get(childId);
- return child && !child.threadId;
- });
-
- return {
- children: mainFlowChildIds.map((childId) => buildTree(childId)),
- id: messageId,
- };
+ // Iterative build: a conversation's depth equals its length (each turn parents
+ // off the previous one), so recursing per node overflows the stack on long
+ // chains. Nodes are created on the way down, then filled from an explicit stack.
+ const buildTree = (rootId: string): IdNode => {
+ const root: IdNode = { children: [], id: rootId };
+ const pending: IdNode[] = [root];
+
+ while (pending.length > 0) {
+ const node = pending.pop()!;
+
+ // Filter children to only include those in main flow (not in threads)
+ for (const childId of childrenMap.get(node.id) ?? []) {
+ const child = messageMap.get(childId);
+ if (!child || child.threadId) continue;
+
+ const childNode: IdNode = { children: [], id: childId };
+ node.children.push(childNode);
+ pending.push(childNode);
+ }
+ }
+
+ return root;
};
// Get root message IDs (messages with parentId = null and no threadId)
diff --git a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts b/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
index fbd23f911b7..3dd8f4df652 100644
--- a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
+++ b/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
@@ -37,19 +37,35 @@ export class ContextTreeBuilder {
transformAll(idNodes: IdNode[]): ContextNode[] {
const contextTree: ContextNode[] = [];
- for (const idNode of idNodes) {
- this.transformToLinear(idNode, contextTree);
- }
+ this.runLinear(idNodes, contextTree);
return contextTree;
}
/**
- * Transform a single IdNode and append to contextTree array
+ * Depth-first drive of `transformToLinear` over an explicit stack.
+ *
+ * A conversation's tree depth equals its length (each turn parents off the
+ * previous one), so recursing per node overflows the stack on long chains.
+ * Continuations are returned in visit order and pushed reversed.
+ */
+ private runLinear(seed: IdNode[], contextTree: ContextNode[]): void {
+ const stack: IdNode[] = [];
+ for (let i = seed.length - 1; i >= 0; i--) stack.push(seed[i]);
+
+ while (stack.length > 0) {
+ const next = this.transformToLinear(stack.pop()!, contextTree);
+ for (let i = next.length - 1; i >= 0; i--) stack.push(next[i]);
+ }
+ }
+
+ /**
+ * Transform a single IdNode, append its node(s) to contextTree, and return the
+ * nodes the walk continues into (in visit order).
*/
- private transformToLinear(idNode: IdNode, contextTree: ContextNode[]): void {
+ private transformToLinear(idNode: IdNode, contextTree: ContextNode[]): IdNode[] {
const message = this.messageMap.get(idNode.id);
- if (!message) return;
+ if (!message) return [];
// Priority 1: Compare mode from user message metadata
if (this.isCompareMode(message) && idNode.children.length > 1) {
@@ -68,10 +84,10 @@ export class ContextTreeBuilder {
(child) => child.id === compareNode.activeColumnId,
);
if (activeColumnIdNode && activeColumnIdNode.children.length > 0) {
- this.transformToLinear(activeColumnIdNode.children[0], contextTree);
+ return [activeColumnIdNode.children[0]];
}
}
- return;
+ return [];
}
// Priority 2: Compare mode (from messageGroup metadata)
@@ -89,10 +105,10 @@ export class ContextTreeBuilder {
(child) => child.id === compareNode.activeColumnId,
);
if (activeColumnIdNode && activeColumnIdNode.children.length > 0) {
- this.transformToLinear(activeColumnIdNode.children[0], contextTree);
+ return [activeColumnIdNode.children[0]];
}
}
- return;
+ return [];
}
// Priority 3: AgentCouncil mode (from message metadata, typically on tool messages)
@@ -109,12 +125,9 @@ export class ContextTreeBuilder {
// the reply. Only the member carrying it has children, so iterating every member emits
// it exactly once and keeps contextTree in agreement with flatList (FlatListBuilder
// applies the same all-member continuation).
- for (const child of idNode.children) {
- if (child.children.length > 0) {
- this.transformToLinear(child.children[0], contextTree);
- }
- }
- return;
+ return idNode.children
+ .filter((child) => child.children.length > 0)
+ .map((child) => child.children[0]);
}
// Priority 3b: Tasks aggregation (multiple task children with same parent)
@@ -128,25 +141,20 @@ export class ContextTreeBuilder {
return childMsg?.role !== 'task';
});
- for (const nonTaskChild of nonTaskChildren) {
- this.transformToLinear(nonTaskChild, contextTree);
- }
-
// Also check for children of task messages (e.g., summary as child of last task)
const taskChildren = idNode.children.filter((child) => {
const childMsg = this.messageMap.get(child.id);
return childMsg?.role === 'task';
});
- for (const taskChild of taskChildren) {
- for (const taskGrandchild of taskChild.children) {
+ const taskGrandchildren = taskChildren.flatMap((taskChild) =>
+ taskChild.children.filter((taskGrandchild) => {
const taskGrandchildMsg = this.messageMap.get(taskGrandchild.id);
- if (taskGrandchildMsg && taskGrandchildMsg.role !== 'task') {
- this.transformToLinear(taskGrandchild, contextTree);
- }
- }
- }
- return;
+ return taskGrandchildMsg && taskGrandchildMsg.role !== 'task';
+ }),
+ );
+
+ return [...nonTaskChildren, ...taskGrandchildren];
}
// Priority 4: AssistantGroup (assistant + tools)
@@ -156,10 +164,7 @@ export class ContextTreeBuilder {
// Find the next message after tools
const nextMessage = this.messageCollector.findNextAfterTools(message, idNode);
- if (nextMessage) {
- this.transformToLinear(nextMessage, contextTree);
- }
- return;
+ return nextMessage ? [nextMessage] : [];
}
// Priority 6: Branch — multiple NON-TOOL children (dual-form reader invariant: tool children are inline data, not branch candidates).
@@ -178,7 +183,7 @@ export class ContextTreeBuilder {
contextTree.push(branchNode);
// Don't continue after branch - branch is an end point
- return;
+ return [];
}
// Priority 7: Regular message
@@ -186,9 +191,7 @@ export class ContextTreeBuilder {
contextTree.push(messageNode);
// Continue with single child
- if (idNode.children.length === 1) {
- this.transformToLinear(idNode.children[0], contextTree);
- }
+ return idNode.children.length === 1 ? [idNode.children[0]] : [];
}
/**
@@ -285,7 +288,7 @@ export class ContextTreeBuilder {
// Each branch is a tree starting from that child
const branches = idNode.children.map((child) => {
const branchTree: ContextNode[] = [];
- this.transformToLinear(child, branchTree);
+ this.runLinear([child], branchTree);
return branchTree;
});
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index edd6de482a9..a0a654c13ec 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -14,11 +14,33 @@ import type { MessageTransformer } from './MessageTransformer';
const isSupervisorMessage = (message: Message | undefined): boolean =>
message?.metadata?.orchestrationRole === 'supervisor' || !!message?.metadata?.isSupervisor;
+/**
+ * Which priority ladder a frame's children run through. The tasks-aggregation
+ * follow-ups use narrower ladders than the top level — see `tryTasksAggregation`.
+ */
+type LadderKind = 'full' | 'taskSibling' | 'taskGrandchild';
+
+/**
+ * A unit of pending traversal work.
+ *
+ * `children` walks `childIds` from `index`; `continuation` repeatedly drains the
+ * next unprocessed child hanging off a finished assistant group.
+ */
+type TraversalFrame =
+ | {
+ childIds: string[];
+ index: number;
+ kind: 'children';
+ ladder: LadderKind;
+ parentId: string | null;
+ }
+ | { kind: 'continuation'; parentIds: string[] };
+
/**
* FlatListBuilder - Builds flat message list following the active path
*
* Handles:
- * 1. Recursive traversal following active branches
+ * 1. Explicit-stack traversal following active branches
* 2. Creating virtual messages for Compare and AssistantGroup
* 3. Processing different message types with priority
*/
@@ -52,433 +74,239 @@ export class FlatListBuilder {
rootParentId = messages[0].parentId ?? null;
}
- // Build the active path by traversing from root
- this.buildFlatListRecursive(rootParentId, flatList, processedIds, messages);
+ this.runTraversal(rootParentId, flatList, processedIds, messages);
return flatList;
}
+ private childrenFrame(parentId: string | null, childIds?: string[]): TraversalFrame {
+ return {
+ childIds: childIds ?? this.childrenMap.get(parentId) ?? [],
+ index: 0,
+ kind: 'children',
+ ladder: 'full',
+ parentId,
+ };
+ }
+
+ private continuationFrame(assistantChain: Message[], allToolMessages: Message[]): TraversalFrame {
+ const lastAssistant = assistantChain.at(-1);
+ return {
+ kind: 'continuation',
+ parentIds: [
+ ...(lastAssistant ? [lastAssistant.id] : []),
+ ...allToolMessages.map((toolMessage) => toolMessage.id),
+ ],
+ };
+ }
+
/**
- * Recursively build flatList following the active path
+ * Explicit-stack walk of the active path.
+ *
+ * Every user turn parents off the previous assistant, so a conversation's tree
+ * depth equals its length — a recursive walk overflows the stack on long chains
+ * (RangeError past ~1.5k messages). Frames live on the heap instead.
+ *
+ * Frames pop LIFO; dispatch helpers return follow-ups in visit order and
+ * `pushAll` reverses them so the first entry is visited first.
*/
- private buildFlatListRecursive(
- parentId: string | null,
+ private runTraversal(
+ rootParentId: string | null,
flatList: Message[],
processedIds: Set<string>,
allMessages: Message[],
): void {
- const children = this.childrenMap.get(parentId) ?? [];
-
- // Broadcast councils now render in-bubble (a `council` block inside the
- // supervisor's assistant group), so there is no separate agentCouncil message
- // to emit when recursing into a council tool — its members were already
- // collected and marked processed by collectCouncilMembers.
- if (parentId) {
- const parentMessage = this.messageMap.get(parentId);
-
- // Pre-loop check: Tasks aggregation (multiple task messages with same parentId)
- // This handles the case when multiple async tasks are spawned from the same tool message
- if (parentMessage && children.length > 0) {
- const taskChildren = children.filter((childId) => {
- const child = this.messageMap.get(childId);
- return child?.role === 'task';
- });
-
- if (taskChildren.length > 1) {
- // Get non-task children (e.g., summary assistant message)
- const nonTaskChildren = children.filter((childId) => {
- const child = this.messageMap.get(childId);
- return child?.role !== 'task';
- });
-
- // Check if tasks have different agentIds (groupTasks) or same agentId (tasks)
- const taskAgentIds = new Set(
- taskChildren.map((childId) => this.messageMap.get(childId)?.agentId).filter(Boolean),
- );
- const isGroupTasks = taskAgentIds.size > 1;
-
- // Create appropriate virtual message based on agent diversity
- const tasksMessage = isGroupTasks
- ? this.createGroupTasksMessage(parentMessage, taskChildren, processedIds)
- : this.createTasksMessage(parentMessage, taskChildren, processedIds);
- flatList.push(tasksMessage);
-
- // Continue with non-task children (e.g., final summary from assistant)
- for (const nonTaskChildId of nonTaskChildren) {
- if (!processedIds.has(nonTaskChildId)) {
- const nonTaskChild = this.messageMap.get(nonTaskChildId);
- if (nonTaskChild) {
- // Check if it's an AssistantGroup (assistant with tools)
- if (
- nonTaskChild.role === 'assistant' &&
- nonTaskChild.tools &&
- nonTaskChild.tools.length > 0
- ) {
- this.processAssistantGroup(nonTaskChild, flatList, processedIds, allMessages);
- } else {
- flatList.push(nonTaskChild);
- processedIds.add(nonTaskChildId);
- this.buildFlatListRecursive(nonTaskChildId, flatList, processedIds, allMessages);
- }
- }
- }
- }
+ const stack: TraversalFrame[] = [this.childrenFrame(rootParentId)];
- // Also check for children of task messages (e.g., summary as child of last task)
- for (const taskChildId of taskChildren) {
- const taskChildrenIds = this.childrenMap.get(taskChildId) ?? [];
- for (const taskGrandchildId of taskChildrenIds) {
- if (!processedIds.has(taskGrandchildId)) {
- const taskGrandchild = this.messageMap.get(taskGrandchildId);
- if (taskGrandchild && taskGrandchild.role !== 'task') {
- // Check if it's an AssistantGroup (assistant with tools)
- if (
- taskGrandchild.role === 'assistant' &&
- taskGrandchild.tools &&
- taskGrandchild.tools.length > 0
- ) {
- this.processAssistantGroup(taskGrandchild, flatList, processedIds, allMessages);
- } else if (
- // Check if it's a supervisor message without tools (content-only)
- taskGrandchild.role === 'assistant' &&
- isSupervisorMessage(taskGrandchild) &&
- (!taskGrandchild.tools || taskGrandchild.tools.length === 0)
- ) {
- const supervisorMessage = this.createSupervisorContentMessage(taskGrandchild);
- flatList.push(supervisorMessage);
- processedIds.add(taskGrandchildId);
- this.buildFlatListRecursive(
- taskGrandchildId,
- flatList,
- processedIds,
- allMessages,
- );
- } else {
- flatList.push(taskGrandchild);
- processedIds.add(taskGrandchildId);
- this.buildFlatListRecursive(
- taskGrandchildId,
- flatList,
- processedIds,
- allMessages,
- );
- }
- }
- }
- }
- }
- return;
- }
- }
- }
-
- for (const childId of children) {
- if (processedIds.has(childId)) continue;
+ const pushAll = (frames: TraversalFrame[]): void => {
+ for (let i = frames.length - 1; i >= 0; i--) stack.push(frames[i]);
+ };
- const message = this.messageMap.get(childId);
- if (!message) continue;
+ while (stack.length > 0) {
+ const frame = stack.at(-1);
+ if (!frame) break;
- // Priority 1: Compare message group
- const messageGroup = message.groupId ? this.messageGroupMap.get(message.groupId) : undefined;
+ if (frame.kind === 'continuation') {
+ const next = this.findNextUnprocessedChild(frame.parentIds, processedIds);
+ if (!next) {
+ stack.pop();
+ continue;
+ }
- if (messageGroup && messageGroup.mode === 'compare' && !processedIds.has(messageGroup.id)) {
- const groupMembers = this.messageCollector.collectGroupMembers(
- message.groupId!,
- allMessages,
+ stack.push(
+ this.shouldDrainParentContinuations(next.parentId, processedIds)
+ ? this.childrenFrame(next.parentId)
+ : this.childrenFrame(next.parentId, [next.child.id]),
);
- const compareMessage = this.createCompareMessage(messageGroup, groupMembers);
- flatList.push(compareMessage);
- groupMembers.forEach((m) => processedIds.add(m.id));
- processedIds.add(messageGroup.id);
-
- // Continue with active column's children (if any)
- if ((compareMessage as any).activeColumnId) {
- this.buildFlatListRecursive(
- (compareMessage as any).activeColumnId,
- flatList,
- processedIds,
- allMessages,
- );
- }
continue;
}
- // Priority 2: AssistantGroup (assistant + tools), or the toolless
- // narration step that heads a tool-using chain — the latter must seed the
- // group instead of splitting into its own standalone bubble. Supervisors
- // are excluded from the toolless-head path so they still fall to 2b.
- if (
- message.role === 'assistant' &&
- ((message.tools && message.tools.length > 0) ||
- (!isSupervisorMessage(message) && this.messageCollector.isToolChainHead(message)))
- ) {
- // Collect the entire assistant group chain
- const assistantChain: Message[] = [];
- const allToolMessages: Message[] = [];
- this.messageCollector.collectAssistantChain(
- message,
- allMessages,
- assistantChain,
- allToolMessages,
+ // Tasks aggregation reads the parent's children as a set, before any single
+ // child is visited, and replaces the whole frame when it fires.
+ if (frame.index === 0 && frame.ladder === 'full') {
+ const aggregated = this.tryTasksAggregation(
+ frame.parentId,
+ frame.childIds,
+ flatList,
processedIds,
);
+ if (aggregated) {
+ stack.pop();
+ pushAll(aggregated);
+ continue;
+ }
+ }
- // Gather external-signal callback blocks () for any
- // tool in the chain that fired toolless reactive replies
- // (Monitor stdout pushes, etc.). Snapshot now so the UI doesn't
- // need to query messageMap; mark callback messages as processed
- // so they don't render as separate top-level bubbles.
- const signalBlocks = this.messageCollector.collectFlatSignalCallbacks(
- allToolMessages,
- allMessages,
- );
-
- // Post-task-summary turns () — 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);
+ if (frame.index >= frame.childIds.length) {
+ stack.pop();
+ continue;
+ }
- // Create assistantGroup virtual message
- const groupMessage = this.createAssistantGroupMessage(
- assistantChain[0],
- assistantChain,
- allToolMessages,
- signalBlocks,
- taskCompletionMessages,
- council?.members,
- );
- flatList.push(groupMessage);
+ const childId = frame.childIds[frame.index];
+ frame.index += 1;
- // Mark all as processed
- assistantChain.forEach((m) => processedIds.add(m.id));
- allToolMessages.forEach((m) => processedIds.add(m.id));
- for (const block of signalBlocks) {
- for (const cb of block.callbacks) processedIds.add(cb.id);
- }
- for (const completion of taskCompletionMessages) {
- processedIds.add(completion.id);
- }
+ if (processedIds.has(childId)) continue;
+ const message = this.messageMap.get(childId);
+ if (!message) continue;
- // Surface the supervisor's post-council reply (attached to one member).
- if (council) {
- for (const memberId of council.memberIds) {
- this.buildFlatListRecursive(memberId, flatList, processedIds, allMessages);
- }
- }
+ pushAll(this.dispatch(frame.ladder, message, flatList, processedIds, allMessages));
+ }
+ }
- this.continueAfterAssistantGroup(
- assistantChain,
- allToolMessages,
- flatList,
- processedIds,
- allMessages,
- );
- continue;
+ private dispatch(
+ ladder: LadderKind,
+ message: Message,
+ flatList: Message[],
+ processedIds: Set<string>,
+ allMessages: Message[],
+ ): TraversalFrame[] {
+ switch (ladder) {
+ case 'taskSibling': {
+ return this.dispatchTaskSibling(message, flatList, processedIds, allMessages);
}
+ case 'taskGrandchild': {
+ return this.dispatchTaskGrandchild(message, flatList, processedIds, allMessages);
+ }
+ default: {
+ return this.dispatchMessage(message, flatList, processedIds, allMessages);
+ }
+ }
+ }
- // Priority 2b: Supervisor message without tools (content-only)
- // Transform to supervisor role with content in children array
- if (
- message.role === 'assistant' &&
- isSupervisorMessage(message) &&
- (!message.tools || message.tools.length === 0)
- ) {
- const supervisorMessage = this.createSupervisorContentMessage(message);
- flatList.push(supervisorMessage);
- processedIds.add(message.id);
+ /**
+ * More than one `task` child under a parent collapses into a single virtual
+ * tasks row; the frame is then replaced by its follow-ups — non-task siblings
+ * first, then each task's own children.
+ *
+ * The follow-up ladders are deliberately narrower than the top-level one: a
+ * task sibling never opens a supervisor content bubble, a task grandchild does.
+ */
+ private tryTasksAggregation(
+ parentId: string | null,
+ children: string[],
+ flatList: Message[],
+ processedIds: Set<string>,
+ ): TraversalFrame[] | undefined {
+ if (!parentId || children.length === 0) return undefined;
- // Continue with children
- this.buildFlatListRecursive(message.id, flatList, processedIds, allMessages);
- continue;
- }
+ const parentMessage = this.messageMap.get(parentId);
+ if (!parentMessage) return undefined;
- // Priority 3a: Compare mode from user message metadata
- const childMessages = this.childrenMap.get(message.id) ?? [];
- // Non-tool children only are branch candidates (dual-form reader invariant: tool children are inline, not branches):
- // 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 message
- flatList.push(message);
- processedIds.add(message.id);
-
- // Create compare virtual message with proper handling of AssistantGroups
- const compareMessage = this.createCompareMessageFromChildIds(
- message,
- childMessages,
- allMessages,
- processedIds,
- );
- flatList.push(compareMessage);
-
- // Continue with active column's children (if any)
- if ((compareMessage as any).activeColumnId) {
- this.buildFlatListRecursive(
- (compareMessage as any).activeColumnId,
- flatList,
- processedIds,
- allMessages,
- );
- }
- continue;
- }
+ const taskChildren = children.filter(
+ (childId) => this.messageMap.get(childId)?.role === 'task',
+ );
+ if (taskChildren.length <= 1) return undefined;
- // Priority 3d: User message with branches (multiple assistant children)
- // Branch indicator should be on the active assistant child message
- if (message.role === 'user' && nonToolChildMessages.length > 1) {
- const activeBranchId = this.branchResolver.getActiveBranchIdFromMetadata(
- message,
- nonToolChildMessages,
- this.childrenMap,
- );
+ const nonTaskChildren = children.filter(
+ (childId) => this.messageMap.get(childId)?.role !== 'task',
+ );
- // Optimistic update: activeBranchId is undefined when branch is being created
- // In this case, just add user message without branch info and continue
- if (!activeBranchId) {
- flatList.push(message);
- processedIds.add(message.id);
- continue;
- }
+ const taskAgentIds = new Set(
+ taskChildren.map((childId) => this.messageMap.get(childId)?.agentId).filter(Boolean),
+ );
+ const isGroupTasks = taskAgentIds.size > 1;
- // Add user message without branch (branch goes on the child)
- flatList.push(message);
- processedIds.add(message.id);
-
- const activeBranchIndex = nonToolChildMessages.indexOf(activeBranchId);
-
- // Continue with active branch - check if it's an assistantGroup
- const activeBranchMsg = this.messageMap.get(activeBranchId);
- if (activeBranchMsg) {
- // Check if active branch is assistant with tools (should be assistantGroup)
- if (
- activeBranchMsg.role === 'assistant' &&
- activeBranchMsg.tools &&
- activeBranchMsg.tools.length > 0
- ) {
- // Collect the entire assistant group chain
- const assistantChain: Message[] = [];
- const allToolMessages: Message[] = [];
- this.messageCollector.collectAssistantChain(
- activeBranchMsg,
- allMessages,
- assistantChain,
- allToolMessages,
- processedIds,
- );
-
- // Create assistantGroup virtual message with branch metadata
- const groupMessage = this.createAssistantGroupMessage(
- assistantChain[0],
- assistantChain,
- allToolMessages,
- );
- // Add branch info to the assistantGroup message
- const groupMessageWithBranches = this.createMessageWithBranches(
- groupMessage,
- nonToolChildMessages.length,
- activeBranchIndex,
- );
- flatList.push(groupMessageWithBranches);
-
- // Mark all as processed
- assistantChain.forEach((m) => processedIds.add(m.id));
- allToolMessages.forEach((m) => processedIds.add(m.id));
-
- this.continueAfterAssistantGroup(
- assistantChain,
- allToolMessages,
- flatList,
- processedIds,
- allMessages,
- );
- } else {
- // Regular assistant message (not assistantGroup) - add branch info
- const activeBranchWithBranches = this.createMessageWithBranches(
- activeBranchMsg,
- nonToolChildMessages.length,
- activeBranchIndex,
- );
- flatList.push(activeBranchWithBranches);
- processedIds.add(activeBranchId);
-
- // Continue with active branch's children
- this.buildFlatListRecursive(activeBranchId, flatList, processedIds, allMessages);
- }
- }
- continue;
- }
+ flatList.push(
+ isGroupTasks
+ ? this.createGroupTasksMessage(parentMessage, taskChildren, processedIds)
+ : this.createTasksMessage(parentMessage, taskChildren, processedIds),
+ );
- // Priority 3e: Assistant message with branches (multiple user children)
- // Branch indicator should be on the active user child message
- if (message.role === 'assistant' && nonToolChildMessages.length > 1) {
- const activeBranchId = this.branchResolver.getActiveBranchIdFromMetadata(
- message,
- nonToolChildMessages,
- this.childrenMap,
- );
+ const followUps: TraversalFrame[] = [
+ {
+ childIds: nonTaskChildren,
+ index: 0,
+ kind: 'children',
+ ladder: 'taskSibling',
+ parentId,
+ },
+ ];
- // Optimistic update: activeBranchId is undefined when branch is being created
- // In this case, just add assistant message without branch info and continue
- if (!activeBranchId) {
- flatList.push(message);
- processedIds.add(message.id);
- continue;
- }
+ for (const taskChildId of taskChildren) {
+ followUps.push({
+ childIds: this.childrenMap.get(taskChildId) ?? [],
+ index: 0,
+ kind: 'children',
+ ladder: 'taskGrandchild',
+ parentId: taskChildId,
+ });
+ }
- // Add the assistant message without branch (branch goes on the child)
- flatList.push(message);
- processedIds.add(message.id);
+ return followUps;
+ }
- const activeBranchIndex = nonToolChildMessages.indexOf(activeBranchId);
+ private dispatchTaskSibling(
+ message: Message,
+ flatList: Message[],
+ processedIds: Set<string>,
+ allMessages: Message[],
+ ): TraversalFrame[] {
+ if (message.role === 'assistant' && message.tools && message.tools.length > 0) {
+ return this.emitAssistantGroup(message, flatList, processedIds, allMessages);
+ }
- // Continue with active branch and add branch info to the user child
- const activeBranchMsg = this.messageMap.get(activeBranchId);
- if (activeBranchMsg) {
- // Add branch info to the active user child message
- const activeBranchWithBranches = this.createMessageWithBranches(
- activeBranchMsg,
- nonToolChildMessages.length,
- activeBranchIndex,
- );
- flatList.push(activeBranchWithBranches);
- processedIds.add(activeBranchId);
+ flatList.push(message);
+ processedIds.add(message.id);
+ return [this.childrenFrame(message.id)];
+ }
- // Continue with active branch's children
- this.buildFlatListRecursive(activeBranchId, flatList, processedIds, allMessages);
- }
- continue;
- }
+ private dispatchTaskGrandchild(
+ message: Message,
+ flatList: Message[],
+ processedIds: Set<string>,
+ allMessages: Message[],
+ ): TraversalFrame[] {
+ if (message.role === 'task') return [];
- // Priority 4: Regular message
- flatList.push(message);
- processedIds.add(message.id);
+ if (message.role === 'assistant' && message.tools && message.tools.length > 0) {
+ return this.emitAssistantGroup(message, flatList, processedIds, allMessages);
+ }
- // Continue with children
- this.buildFlatListRecursive(message.id, flatList, processedIds, allMessages);
+ if (
+ message.role === 'assistant' &&
+ isSupervisorMessage(message) &&
+ (!message.tools || message.tools.length === 0)
+ ) {
+ flatList.push(this.createSupervisorContentMessage(message));
+ processedIds.add(message.id);
+ return [this.childrenFrame(message.id)];
}
+
+ flatList.push(message);
+ processedIds.add(message.id);
+ return [this.childrenFrame(message.id)];
}
/**
- * Process an assistant message with tools into an AssistantGroup
- * Extracted to avoid code duplication in task children handling
+ * AssistantGroup without the top-level extras (signal callbacks, task
+ * completions) — the shape the tasks follow-up path has always emitted.
*/
- private processAssistantGroup(
+ private emitAssistantGroup(
message: Message,
flatList: Message[],
processedIds: Set<string>,
allMessages: Message[],
- ): void {
- // Collect the entire assistant group chain
+ ): TraversalFrame[] {
const assistantChain: Message[] = [];
const allToolMessages: Message[] = [];
this.messageCollector.collectAssistantChain(
@@ -489,10 +317,8 @@ export class FlatListBuilder {
processedIds,
);
- // A broadcast turn embeds its members as an in-bubble council block.
const council = this.collectCouncilMembers(allToolMessages, allMessages, processedIds);
- // Create assistantGroup virtual message
const groupMessage = this.createAssistantGroupMessage(
assistantChain[0],
assistantChain,
@@ -503,55 +329,246 @@ export class FlatListBuilder {
);
flatList.push(groupMessage);
- // Mark all as processed
assistantChain.forEach((m) => processedIds.add(m.id));
allToolMessages.forEach((m) => processedIds.add(m.id));
+ const frames: TraversalFrame[] = [];
if (council) {
- for (const memberId of council.memberIds) {
- this.buildFlatListRecursive(memberId, flatList, processedIds, allMessages);
- }
+ for (const memberId of council.memberIds) frames.push(this.childrenFrame(memberId));
}
-
- this.continueAfterAssistantGroup(
- assistantChain,
- allToolMessages,
- flatList,
- processedIds,
- allMessages,
- );
+ frames.push(this.continuationFrame(assistantChain, allToolMessages));
+ return frames;
}
- private continueAfterAssistantGroup(
- assistantChain: Message[],
- allToolMessages: Message[],
+ /**
+ * Top-level priority ladder: the first shape that matches claims the message,
+ * emits its row(s), marks the raw messages it swallowed, and returns where the
+ * walk resumes.
+ */
+ private dispatchMessage(
+ message: Message,
flatList: Message[],
processedIds: Set<string>,
allMessages: Message[],
- ): void {
- const lastAssistant = assistantChain.at(-1);
- const parentIds = [
- ...(lastAssistant ? [lastAssistant.id] : []),
- ...allToolMessages.map((toolMessage) => toolMessage.id),
- ];
+ ): TraversalFrame[] {
+ // Priority 1: Compare message group
+ const messageGroup = message.groupId ? this.messageGroupMap.get(message.groupId) : undefined;
+
+ if (messageGroup && messageGroup.mode === 'compare' && !processedIds.has(messageGroup.id)) {
+ const groupMembers = this.messageCollector.collectGroupMembers(message.groupId!, allMessages);
+ const compareMessage = this.createCompareMessage(messageGroup, groupMembers);
+ flatList.push(compareMessage);
+ groupMembers.forEach((m) => processedIds.add(m.id));
+ processedIds.add(messageGroup.id);
+
+ // Continue with active column's children (if any)
+ const activeColumnId = (compareMessage as any).activeColumnId;
+ return activeColumnId ? [this.childrenFrame(activeColumnId)] : [];
+ }
- while (true) {
- const nextContinuation = this.findNextUnprocessedChild(parentIds, processedIds);
- if (!nextContinuation) return;
+ // Priority 2: AssistantGroup (assistant + tools), or the toolless
+ // narration step that heads a tool-using chain — the latter must seed the
+ // group instead of splitting into its own standalone bubble. Supervisors
+ // are excluded from the toolless-head path so they still fall to 2b.
+ if (
+ message.role === 'assistant' &&
+ ((message.tools && message.tools.length > 0) ||
+ (!isSupervisorMessage(message) && this.messageCollector.isToolChainHead(message)))
+ ) {
+ const assistantChain: Message[] = [];
+ const allToolMessages: Message[] = [];
+ this.messageCollector.collectAssistantChain(
+ message,
+ allMessages,
+ assistantChain,
+ allToolMessages,
+ processedIds,
+ );
- if (this.shouldDrainParentContinuations(nextContinuation.parentId, processedIds)) {
- this.buildFlatListRecursive(nextContinuation.parentId, flatList, processedIds, allMessages);
- continue;
+ // Gather external-signal callback blocks for any tool in the chain that
+ // fired toolless reactive replies (Monitor stdout pushes, etc.). Snapshot
+ // now so the UI doesn't need to query messageMap.
+ const signalBlocks = this.messageCollector.collectFlatSignalCallbacks(
+ allToolMessages,
+ allMessages,
+ );
+
+ // Post-task-summary turns — toolless siblings of the callbacks under the
+ // same tool_result, rendered AFTER the SignalCallbacks accordion.
+ const taskCompletionMessages = this.messageCollector.collectFlatTaskCompletions(
+ allToolMessages,
+ allMessages,
+ );
+
+ // A broadcast turn renders its members as one in-bubble council block.
+ const council = this.collectCouncilMembers(allToolMessages, allMessages, processedIds);
+
+ const groupMessage = this.createAssistantGroupMessage(
+ assistantChain[0],
+ assistantChain,
+ allToolMessages,
+ signalBlocks,
+ taskCompletionMessages,
+ council?.members,
+ );
+ flatList.push(groupMessage);
+
+ assistantChain.forEach((m) => processedIds.add(m.id));
+ allToolMessages.forEach((m) => processedIds.add(m.id));
+ for (const block of signalBlocks) {
+ for (const cb of block.callbacks) processedIds.add(cb.id);
+ }
+ for (const completion of taskCompletionMessages) {
+ processedIds.add(completion.id);
}
- this.buildFlatListRecursiveForChild(
- nextContinuation.parentId,
- nextContinuation.child.id,
- flatList,
- processedIds,
+ const frames: TraversalFrame[] = [];
+ // Surface the supervisor's post-council reply (attached to one member).
+ if (council) {
+ for (const memberId of council.memberIds) frames.push(this.childrenFrame(memberId));
+ }
+ frames.push(this.continuationFrame(assistantChain, allToolMessages));
+ return frames;
+ }
+
+ // Priority 2b: Supervisor message without tools (content-only)
+ // Transform to supervisor role with content in children array
+ if (
+ message.role === 'assistant' &&
+ isSupervisorMessage(message) &&
+ (!message.tools || message.tools.length === 0)
+ ) {
+ flatList.push(this.createSupervisorContentMessage(message));
+ processedIds.add(message.id);
+ return [this.childrenFrame(message.id)];
+ }
+
+ // Priority 3a: Compare mode from user message metadata
+ const childMessages = this.childrenMap.get(message.id) ?? [];
+ // Non-tool children only are branch candidates (dual-form reader invariant: tool children are inline, not branches):
+ // 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) {
+ flatList.push(message);
+ processedIds.add(message.id);
+
+ const compareMessage = this.createCompareMessageFromChildIds(
+ message,
+ childMessages,
allMessages,
+ processedIds,
+ );
+ flatList.push(compareMessage);
+
+ const activeColumnId = (compareMessage as any).activeColumnId;
+ return activeColumnId ? [this.childrenFrame(activeColumnId)] : [];
+ }
+
+ // Priority 3d: User message with branches (multiple assistant children)
+ // Branch indicator should be on the active assistant child message
+ if (message.role === 'user' && nonToolChildMessages.length > 1) {
+ const activeBranchId = this.branchResolver.getActiveBranchIdFromMetadata(
+ message,
+ nonToolChildMessages,
+ this.childrenMap,
+ );
+
+ flatList.push(message);
+ processedIds.add(message.id);
+
+ // Optimistic update: activeBranchId is undefined when branch is being created
+ if (!activeBranchId) return [];
+
+ const activeBranchIndex = nonToolChildMessages.indexOf(activeBranchId);
+ const activeBranchMsg = this.messageMap.get(activeBranchId);
+ if (!activeBranchMsg) return [];
+
+ // Check if active branch is assistant with tools (should be assistantGroup)
+ if (
+ activeBranchMsg.role === 'assistant' &&
+ activeBranchMsg.tools &&
+ activeBranchMsg.tools.length > 0
+ ) {
+ const assistantChain: Message[] = [];
+ const allToolMessages: Message[] = [];
+ this.messageCollector.collectAssistantChain(
+ activeBranchMsg,
+ allMessages,
+ assistantChain,
+ allToolMessages,
+ processedIds,
+ );
+
+ const groupMessage = this.createAssistantGroupMessage(
+ assistantChain[0],
+ assistantChain,
+ allToolMessages,
+ );
+ flatList.push(
+ this.createMessageWithBranches(
+ groupMessage,
+ nonToolChildMessages.length,
+ activeBranchIndex,
+ ),
+ );
+
+ assistantChain.forEach((m) => processedIds.add(m.id));
+ allToolMessages.forEach((m) => processedIds.add(m.id));
+
+ return [this.continuationFrame(assistantChain, allToolMessages)];
+ }
+
+ // Regular assistant message (not assistantGroup) - add branch info
+ flatList.push(
+ this.createMessageWithBranches(
+ activeBranchMsg,
+ nonToolChildMessages.length,
+ activeBranchIndex,
+ ),
);
+ processedIds.add(activeBranchId);
+ return [this.childrenFrame(activeBranchId)];
}
+
+ // Priority 3e: Assistant message with branches (multiple user children)
+ // Branch indicator should be on the active user child message
+ if (message.role === 'assistant' && nonToolChildMessages.length > 1) {
+ const activeBranchId = this.branchResolver.getActiveBranchIdFromMetadata(
+ message,
+ nonToolChildMessages,
+ this.childrenMap,
+ );
+
+ // Add the assistant message without branch (branch goes on the child)
+ flatList.push(message);
+ processedIds.add(message.id);
+
+ // Optimistic update: activeBranchId is undefined when branch is being created
+ if (!activeBranchId) return [];
+
+ const activeBranchIndex = nonToolChildMessages.indexOf(activeBranchId);
+ const activeBranchMsg = this.messageMap.get(activeBranchId);
+ if (!activeBranchMsg) return [];
+
+ // Add branch info to the active user child message
+ flatList.push(
+ this.createMessageWithBranches(
+ activeBranchMsg,
+ nonToolChildMessages.length,
+ activeBranchIndex,
+ ),
+ );
+ processedIds.add(activeBranchId);
+ return [this.childrenFrame(activeBranchId)];
+ }
+
+ // Priority 4: Regular message
+ flatList.push(message);
+ processedIds.add(message.id);
+ return [this.childrenFrame(message.id)];
}
/**
@@ -612,23 +629,6 @@ export class FlatListBuilder {
return { memberIds, members: (councilVirtual as { members?: Message[] }).members ?? [] };
}
- private buildFlatListRecursiveForChild(
- parentId: string,
- childId: string,
- flatList: Message[],
- processedIds: Set<string>,
- allMessages: Message[],
- ): void {
- const childIds = this.childrenMap.get(parentId) ?? [];
- this.childrenMap.set(parentId, [childId]);
-
- try {
- this.buildFlatListRecursive(parentId, flatList, processedIds, allMessages);
- } finally {
- this.childrenMap.set(parentId, childIds);
- }
- }
-
private findNextUnprocessedChild(
parentIds: string[],
processedIds: Set<string>,
diff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.ts
index 733e4f9f0ee..12265fa5d87 100644
--- a/packages/conversation-flow/src/transformation/MessageCollector.ts
+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts
@@ -162,75 +162,67 @@ export class MessageCollector {
allToolMessages: Message[],
processedIds: Set<string>,
): void {
- if (processedIds.has(currentAssistant.id)) return;
-
- // Mark visited up front so duplicated tool_call_ids (the same tool result
- // reachable from multiple assistants) can't recurse forever.
- processedIds.add(currentAssistant.id);
-
- // Add current assistant to chain
- assistantChain.push(currentAssistant);
-
- // Get the agentId of the first assistant in the chain (the group owner)
- const groupAgentId = assistantChain[0].agentId;
-
- // Collect its tool messages
- const toolMessages = this.collectToolMessages(currentAssistant, allMessages);
- allToolMessages.push(...toolMessages);
-
- // Find the next step's assistant. Role-aware dual-form walk:
- // 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;
+ let current: Message | undefined = currentAssistant;
- if (continuation.tools && continuation.tools.length > 0) {
- // Continue the chain (recursion marks it processed at the top)
- this.collectAssistantChain(
- continuation,
- allMessages,
- assistantChain,
- allToolMessages,
- processedIds,
- );
- return;
- }
+ // A run is a chain, so its length is the step count — walking it with
+ // recursion would cost stack depth per step.
+ while (current) {
+ if (processedIds.has(current.id)) return;
+
+ // Mark visited up front so duplicated tool_call_ids (the same tool result
+ // reachable from multiple assistants) can't loop forever.
+ processedIds.add(current.id);
+
+ // Add current assistant to chain
+ assistantChain.push(current);
+
+ // Get the agentId of the first assistant in the chain (the group owner)
+ const groupAgentId = assistantChain[0].agentId;
- // Toolless continuations are still part of the same hetero-agent run. The
- // model can emit several prose-only progress updates before the next tool
- // call, so keep walking until the chain either ends in a toolless final
- // answer or reaches the next tool-using assistant.
- let toollessContinuation: Message | undefined = continuation;
- while (
- toollessContinuation &&
- (!toollessContinuation.tools || toollessContinuation.tools.length === 0)
- ) {
- assistantChain.push(toollessContinuation);
- processedIds.add(toollessContinuation.id);
-
- toollessContinuation = this.findFlatChainContinuation(
- toollessContinuation,
- [], // a toolless step owns no tool results
+ // Collect its tool messages
+ const toolMessages = this.collectToolMessages(current, allMessages);
+ allToolMessages.push(...toolMessages);
+
+ // Find the next step's assistant. Role-aware dual-form walk:
+ // 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(
+ current,
+ toolMessages,
allMessages,
processedIds,
groupAgentId,
);
- }
+ if (!continuation) return;
- if (toollessContinuation) {
- this.collectAssistantChain(
- toollessContinuation,
- allMessages,
- assistantChain,
- allToolMessages,
- processedIds,
- );
+ if (continuation.tools && continuation.tools.length > 0) {
+ // Continue the chain (the loop head marks it processed)
+ current = continuation;
+ continue;
+ }
+
+ // Toolless continuations are still part of the same hetero-agent run. The
+ // model can emit several prose-only progress updates before the next tool
+ // call, so keep walking until the chain either ends in a toolless final
+ // answer or reaches the next tool-using assistant.
+ let toollessContinuation: Message | undefined = continuation;
+ while (
+ toollessContinuation &&
+ (!toollessContinuation.tools || toollessContinuation.tools.length === 0)
+ ) {
+ assistantChain.push(toollessContinuation);
+ processedIds.add(toollessContinuation.id);
+
+ toollessContinuation = this.findFlatChainContinuation(
+ toollessContinuation,
+ [], // a toolless step owns no tool results
+ allMessages,
+ processedIds,
+ groupAgentId,
+ );
+ }
+
+ current = toollessContinuation;
}
}
@@ -408,29 +400,35 @@ export class MessageCollector {
// Get the agentId of the first assistant in the group (the group owner)
const agentId = groupAgentId ?? message.agentId;
- // Get tool message IDs if this assistant has tools
- const toolIds = idNode.children
- .filter((child) => {
- const childMsg = this.messageMap.get(child.id);
- return childMsg?.role === 'tool';
- })
- .map((child) => child.id);
-
- // Add current assistant message node
- const messageNode: MessageNode = {
- id: message.id,
- type: 'message',
- };
- if (toolIds.length > 0) {
- messageNode.tools = toolIds;
- }
- children.push(messageNode);
+ let currentMessage: Message | undefined = message;
+ let currentNode: IdNode | undefined = idNode;
+
+ // Walked as a loop, not recursion: a run's depth is its step count.
+ while (currentMessage && currentNode) {
+ // Get tool message IDs if this assistant has tools
+ const toolIds = currentNode.children
+ .filter((child) => {
+ const childMsg = this.messageMap.get(child.id);
+ return childMsg?.role === 'tool';
+ })
+ .map((child) => child.id);
+
+ // Add current assistant message node
+ const messageNode: MessageNode = {
+ id: currentMessage.id,
+ type: 'message',
+ };
+ if (toolIds.length > 0) {
+ messageNode.tools = toolIds;
+ }
+ children.push(messageNode);
- // 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 next step's assistant (dual-form aware, see findChainContinuationNode)
+ const nextNode = this.findChainContinuationNode(currentNode, agentId);
+ if (!nextNode) return;
+
+ currentMessage = this.messageMap.get(nextNode.id);
+ currentNode = nextNode;
}
}
@@ -501,60 +499,80 @@ export class MessageCollector {
const blocks: SignalCallbacksNode[] = [];
const visited = new Set<string>();
- const walk = (node: IdNode): void => {
- if (visited.has(node.id)) return;
- visited.add(node.id);
+ const emitBlockFor = (toolNode: IdNode): void => {
+ // 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 toolNode.children) {
+ const toolChildMsg = this.messageMap.get(toolChild.id);
+ if (!toolChildMsg) continue;
+ if (!isCallbackSignal(getMessageSignal(toolChildMsg))) continue;
+ callbacks.push(toolChildMsg);
+ }
- for (const child of node.children) {
+ if (callbacks.length === 0) return;
+
+ // 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-${toolNode.id}`,
+ sourceToolCallId: first.sourceToolCallId,
+ sourceToolMessageId: toolNode.id,
+ sourceToolName: first.sourceToolName,
+ type: 'signalCallbacks',
+ });
+ };
+
+ // Explicit task stack rather than recursion — a run's depth is its step
+ // count. Emitting a tool's block and descending into its follower are
+ // separate tasks so the original pre-order interleaving is preserved when a
+ // step owns more than one tool.
+ type SignalTask = { kind: 'emit'; toolNode: IdNode } | { kind: 'walk'; node: IdNode };
+ const stack: SignalTask[] = [{ kind: 'walk', node: idNode }];
+
+ while (stack.length > 0) {
+ const task = stack.pop()!;
+
+ if (task.kind === 'emit') {
+ emitBlockFor(task.toolNode);
+ continue;
+ }
+
+ if (visited.has(task.node.id)) continue;
+ visited.add(task.node.id);
+
+ const scheduled: SignalTask[] = [];
+ for (const child of task.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',
- });
- }
+ scheduled.push({ kind: 'emit', toolNode: child });
- // Continue walking the main chain — recurse into the next
- // main-chain follower under this tool (skipping signal
- // callbacks, just like `collectAssistantGroupMessages` does).
+ // Continue walking the main chain — descend 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);
+ scheduled.push({ kind: 'walk', node: nextChild });
break;
}
}
- };
- walk(idNode);
+ for (let i = scheduled.length - 1; i >= 0; i--) stack.push(scheduled[i]);
+ }
+
return blocks;
}
@@ -580,37 +598,54 @@ export class MessageCollector {
const nodes: MessageNode[] = [];
const visited = new Set<string>();
- const walk = (node: IdNode): void => {
- if (visited.has(node.id)) return;
- visited.add(node.id);
+ const emitCompletionsFor = (toolNode: IdNode): void => {
+ for (const toolChild of toolNode.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' });
+ }
+ };
+
+ // Explicit task stack rather than recursion — see collectSignalCallbacks for
+ // why emit and descend are separate tasks.
+ type CompletionTask = { kind: 'emit'; toolNode: IdNode } | { kind: 'walk'; node: IdNode };
+ const stack: CompletionTask[] = [{ kind: 'walk', node: idNode }];
- for (const child of node.children) {
+ while (stack.length > 0) {
+ const task = stack.pop()!;
+
+ if (task.kind === 'emit') {
+ emitCompletionsFor(task.toolNode);
+ continue;
+ }
+
+ if (visited.has(task.node.id)) continue;
+ visited.add(task.node.id);
+
+ const scheduled: CompletionTask[] = [];
+ for (const child of task.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' });
- }
+ scheduled.push({ kind: 'emit', toolNode: child });
- // Continue walking the main chain into the next non-signal
- // follower under this tool (same skip rule as
- // `collectAssistantGroupMessages`).
+ // 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);
+ scheduled.push({ kind: 'walk', node: nextChild });
break;
}
}
- };
- walk(idNode);
+ for (let i = scheduled.length - 1; i >= 0; i--) stack.push(scheduled[i]);
+ }
+
return nodes;
}