Skip to content

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

πŸ› fix(hetero): batch subagent message persistence (#17085)

Arvin Xu7e6af5470961
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index b64203dbb27..116c196013c 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -51,10 +51,12 @@ vi.mock('@/services/message', () => ({
// threadService β€” subagent Thread creation (CC `Task` tool_use)
const mockCreateThread = vi.fn();
+const mockGetThreads = vi.fn();
const mockUpdateThread = vi.fn();
vi.mock('@/services/thread', () => ({
threadService: {
createThread: (...args: unknown[]) => mockCreateThread(...args),
+ getThreads: (...args: unknown[]) => mockGetThreads(...args),
updateThread: (...args: unknown[]) => mockUpdateThread(...args),
},
}));
@@ -497,6 +499,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
agentSessionId: ipc.getAdapterSessionId(sessionId),
}));
mockGetMessages.mockResolvedValue([]);
+ mockGetThreads.mockResolvedValue([]);
// Honor a caller-provided `id` like the real messageService does β€” the
// main + subagent coordinators PRE-ALLOCATE message ids so their intents can
// carry concrete parentId chains. A mock that minted its own id would break
@@ -3367,6 +3370,59 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
// ────────────────────────────────────────────────────
describe('CC subagent thread-container', () => {
+ it('does not recreate a finalized subagent Thread after a client executor restart', async () => {
+ mockGetThreads.mockResolvedValue([
+ {
+ id: 'thread-existing',
+ metadata: { sourceToolCallId: 'toolu_task' },
+ status: ThreadStatus.Active,
+ type: 'isolation',
+ },
+ ]);
+
+ await runWithEvents([
+ ccInit(),
+ ccSubagentText('msg_sub', 'toolu_task', 'replayed late event'),
+ ccResult(),
+ ]);
+
+ expect(mockCreateThread).not.toHaveBeenCalled();
+ });
+
+ it('reattaches a continuing subagent to its existing Processing Thread', async () => {
+ mockGetThreads.mockResolvedValue([
+ {
+ id: 'thread-existing',
+ metadata: { sourceToolCallId: 'toolu_task' },
+ status: ThreadStatus.Processing,
+ type: 'isolation',
+ },
+ ]);
+ mockGetMessages.mockResolvedValue([
+ {
+ id: 'assistant-existing',
+ metadata: { subagentMessageId: 'msg_sub' },
+ role: 'assistant',
+ threadId: 'thread-existing',
+ topicId: 'topic-1',
+ },
+ ]);
+
+ await runWithEvents([
+ ccInit(),
+ ccSubagentText('msg_sub', 'toolu_task', 'continued event'),
+ ccSubagentSpawnResult('toolu_task', 'done'),
+ ccResult(),
+ ]);
+
+ expect(mockCreateThread).not.toHaveBeenCalled();
+ expect(mockUpdateMessage.mock.calls).toContainEqual([
+ 'assistant-existing',
+ expect.objectContaining({ content: 'continued event' }),
+ undefined,
+ ]);
+ });
+
it('does NOT create a Thread on Task tool_use alone (lazy creation)', async () => {
// Task tool_use without any subagent events should NOT trigger
// Thread creation β€” we only know the spawn is real once the
@@ -3464,6 +3520,43 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(subAssistantMsg![0]).toMatchObject({ threadId });
});
+ it('preserves subagent tool ids when a later batch operation fails', async () => {
+ const defaultBatchMutate = mockBatchMutate.getMockImplementation()!;
+ mockBatchMutate.mockImplementation(async (operations: any[]) => {
+ const result = await defaultBatchMutate(operations);
+ const hasSubagentToolCreate = operations.some(
+ (operation) =>
+ operation.type === 'createMessage' && operation.message?.tool_call_id === 'toolu_child',
+ );
+ if (!hasSubagentToolCreate) return result;
+
+ const finalIndex = operations.length - 1;
+ return {
+ results: result.results.map((item: any) =>
+ item.index === finalIndex ? { ...item, success: false } : item,
+ ),
+ success: false,
+ };
+ });
+
+ await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'inspect',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentToolUse('msg_sub_1', 'toolu_task', 'toolu_child', 'Bash', { command: 'ls' }),
+ ccToolResult('toolu_child', 'ls output'),
+ ccResult(),
+ ]);
+
+ expect(mockUpdateToolMessage.mock.calls).toContainEqual([
+ expect.any(String),
+ expect.objectContaining({ content: 'ls output' }),
+ undefined,
+ ]);
+ });
+
it('opens a NEW in-thread assistant when subagentMessageId changes (turn boundary)', async () => {
await runWithEvents([
ccInit(),
@@ -3629,7 +3722,14 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
([id, val]: any) => id !== 'ast-initial' && val.content === 'Here is the summary.',
);
expect(threadAssistantContentWrites.length).toBeGreaterThan(0);
- expect(threadAssistantContentWrites[0][2]).toMatchObject({ topicId: 'topic-1' });
+ expect(mockBatchMutate.mock.calls).toContainEqual([
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: 'updateMessage',
+ value: expect.objectContaining({ content: 'Here is the summary.' }),
+ }),
+ ]),
+ ]);
// Sanity β€” the in-thread assistants exist under the right thread.
const threadAssistants = mockCreateMessage.mock.calls.filter(
([p]: any) => p.role === 'assistant' && p.threadId === threadId,
@@ -3912,6 +4012,14 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
payload.content === spawnResult,
);
expect(terminalCreate).toBeDefined();
+ expect(mockBatchMutate.mock.calls).toContainEqual([
+ expect.arrayContaining([
+ expect.objectContaining({
+ message: expect.objectContaining({ content: spawnResult, role: 'assistant', threadId }),
+ type: 'createMessage',
+ }),
+ ]),
+ ]);
// Terminal message chains off the in-thread assistant (the subagent
// spine), with the child tool inline, so the transcript flows
@@ -3921,6 +4029,15 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
([payload]: any) => payload.role === 'tool' && payload.tool_call_id === 'toolu_child',
);
expect(toolCreate).toBeDefined();
+ expect(mockBatchMutate.mock.calls).toContainEqual([
+ expect.arrayContaining([
+ expect.objectContaining({ type: 'updateMessage' }),
+ expect.objectContaining({
+ message: expect.objectContaining({ tool_call_id: 'toolu_child' }),
+ type: 'createMessage',
+ }),
+ ]),
+ ]);
const firstAssistantCreate = mockCreateMessage.mock.calls.find(
([payload]: any) => payload.role === 'assistant' && payload.threadId === threadId,
);
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index 17cb8c4db99..b8170bf3553 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -15,7 +15,9 @@ import {
type MainAgentReduceCtx,
type MainAgentRunState,
reduceMainAgent,
+ rehydrateSubagentRunsState,
type SubagentIntent,
+ type SubagentRunSnapshot,
} from '@lobechat/heterogeneous-agents';
import { formatContextSelections, formatPageSelections } from '@lobechat/prompts';
import type {
@@ -392,46 +394,6 @@ interface SubagentStoreDispatcher {
update: (id: string, value: Partial<UIChatMessage>) => void;
}
-/**
- * Update a tool message's content in DB when tool_result arrives.
- *
- * `pluginState` (when provided by the adapter) is written in the same request
- * as `content` so downstream consumers observe a single atomic update β€”
- * critical for `selectTodosFromMessages` which reads both role=tool and
- * `pluginState.todos` in one pass.
- */
-const persistToolResult = async (
- toolCallId: string,
- content: string,
- isError: boolean,
- toolMsgIdByCallId: Map<string, string>,
- context: ConversationContext,
- pluginState?: Record<string, any>,
-) => {
- const toolMsgId = toolMsgIdByCallId.get(toolCallId);
- if (!toolMsgId) {
- console.warn('[HeterogeneousAgent] tool_result for unknown toolCallId:', toolCallId);
- return;
- }
-
- try {
- await messageService.updateToolMessage(
- toolMsgId,
- {
- content,
- pluginError: isError ? { message: content } : undefined,
- pluginState,
- },
- {
- agentId: context.agentId,
- topicId: context.topicId,
- },
- );
- } catch (err) {
- console.error('[HeterogeneousAgent] Failed to update tool message content:', err);
- }
-};
-
const HETERO_MESSAGE_WRITE_BATCH_IDLE_MS = 5_000;
const HETERO_MESSAGE_WRITE_BATCH_MAX_OPS = 50;
const HETERO_TERMINAL_PERSIST_DRAIN_TIMEOUT_MS = 10_000;
@@ -637,6 +599,42 @@ const createMessageWriteBatcher = (deps: {
};
};
+interface MessageBatchMutationResult {
+ results?: Array<{ index: number; success: boolean }>;
+ success?: boolean;
+}
+
+class MessageBatchMutationError extends Error {
+ constructor(public readonly result: MessageBatchMutationResult) {
+ const failedCount = result.results?.filter((item) => !item.success).length;
+ super(`messageService.batchMutate failed for ${failedCount || 'unknown'} operation(s)`);
+ }
+}
+
+const mutateMessageBatch = async (operations: MessageBatchOperation[]): Promise<void> => {
+ const batchMutate = (
+ messageService as { batchMutate?: (operations: MessageBatchOperation[]) => Promise<any> }
+ ).batchMutate;
+
+ if (!batchMutate) {
+ for (const operation of operations) {
+ if (operation.type === 'createMessage') await messageService.createMessage(operation.message);
+ else if (operation.type === 'updateToolMessage')
+ await messageService.updateToolMessage(operation.id, operation.value);
+ else await messageService.updateMessage(operation.id, operation.value);
+ }
+ return;
+ }
+
+ const result = (await batchMutate(operations)) as MessageBatchMutationResult;
+ const failed = (result?.results ?? []).filter(
+ (item: { success?: boolean }) => item.success === false,
+ );
+ if (result?.success === false || failed.length > 0) {
+ throw new MessageBatchMutationError(result);
+ }
+};
+
/**
* Execute a prompt via an external agent CLI.
*
@@ -1223,6 +1221,69 @@ export const executeHeterogeneousAgent = async (
};
};
+ const getSubagentThread = (threadId: string) => {
+ const existing = subagentThreads.get(threadId);
+ if (existing) return existing;
+
+ const created = beginSubagentRun(threadId);
+ subagentThreads.set(threadId, created);
+ return created;
+ };
+
+ const rehydrateClientSubagentRuns = async (): Promise<void> => {
+ if (!context.topicId) return;
+
+ try {
+ const threads = await threadService.getThreads(context.topicId);
+ const snapshots: SubagentRunSnapshot[] = [];
+ const finalizedParents: string[] = [];
+
+ for (const thread of threads) {
+ if (thread.type !== ThreadType.Isolation) continue;
+ const parentToolCallId = thread.metadata?.sourceToolCallId;
+ if (!parentToolCallId) continue;
+
+ if (thread.status !== ThreadStatus.Processing) {
+ finalizedParents.push(parentToolCallId);
+ continue;
+ }
+
+ const messages = await messageService.getMessages({
+ threadId: thread.id,
+ topicId: context.topicId,
+ });
+ const currentAssistant = messages.findLast((message) => message.role === 'assistant');
+ if (!currentAssistant) continue;
+
+ const toolRows = messages.filter(
+ (message) => message.role === 'tool' && message.tool_call_id,
+ );
+ for (const message of toolRows) {
+ toolMsgIdByCallId.set(message.tool_call_id!, message.id);
+ }
+ const subagentMessageId = (currentAssistant.metadata as Record<string, unknown> | null)
+ ?.subagentMessageId;
+
+ snapshots.push({
+ currentAssistantId: currentAssistant.id,
+ currentSubagentMessageId:
+ typeof subagentMessageId === 'string' ? subagentMessageId : undefined,
+ lastChainParentId: currentAssistant.id,
+ lifetimeToolCallIds: toolRows.map((message) => message.tool_call_id!),
+ parentToolCallId,
+ threadId: thread.id,
+ });
+ }
+
+ mainState = {
+ ...mainState,
+ subagents: rehydrateSubagentRunsState(snapshots, finalizedParents),
+ };
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to rehydrate client subagent runs:', err);
+ }
+ };
+
/**
* Mark a per-spawn sub-operation completed. Wrapper around
* `completeOperation` so the coordinator interpreter (`finalizeThread`)
@@ -1253,6 +1314,7 @@ export const executeHeterogeneousAgent = async (
await threadService.createThread({
id: intent.threadId,
metadata: {
+ operationId,
sourceToolCallId: intent.sourceToolCallId,
startedAt: new Date().toISOString(),
subagentType: intent.subagentType,
@@ -1277,7 +1339,7 @@ export const executeHeterogeneousAgent = async (
}
case 'createMessage': {
- const t = subagentThreads.get(intent.threadId);
+ const t = getSubagentThread(intent.threadId);
const subMetadata = heteroProvenance(intent.subagentMessageId);
const msg = {
agentId: intent.agentId ?? undefined,
@@ -1290,7 +1352,7 @@ export const executeHeterogeneousAgent = async (
topicId: context.topicId,
};
try {
- await messageService.createMessage(msg);
+ await mutateMessageBatch([{ message: msg, type: 'createMessage' }]);
} catch (err) {
// Rethrow so `reduceAndApplyMain` skips the state commit β€” the
// run keeps its pre-create shape and the next event re-emits the
@@ -1305,7 +1367,7 @@ export const executeHeterogeneousAgent = async (
// Live token-level UI only β€” no DB write (durable content lands via
// persistContent / persistToolBatch). Mirrors the old text-chunk path.
case 'streamContent': {
- const t = subagentThreads.get(intent.threadId);
+ const t = getSubagentThread(intent.threadId);
const value: Partial<UIChatMessage> = {};
if (intent.content !== undefined) value.content = intent.content;
if (intent.reasoning !== undefined)
@@ -1315,16 +1377,15 @@ export const executeHeterogeneousAgent = async (
}
case 'persistContent': {
- const t = subagentThreads.get(intent.threadId);
+ const t = getSubagentThread(intent.threadId);
const update: Record<string, any> = {};
if (intent.content) update.content = intent.content;
if (intent.reasoning) update.reasoning = { content: intent.reasoning };
if (Object.keys(update).length === 0) return;
try {
- await messageService.updateMessage(intent.messageId, update, {
- agentId: context.agentId,
- topicId: context.topicId,
- });
+ await mutateMessageBatch([
+ { id: intent.messageId, type: 'updateMessage', value: update },
+ ]);
// Success drains any prior pending flush for this thread.
pendingSubagentFlush.delete(intent.threadId);
t?.stream.update(intent.messageId, update as Partial<UIChatMessage>);
@@ -1343,7 +1404,7 @@ export const executeHeterogeneousAgent = async (
}
case 'persistToolBatch': {
- const t = subagentThreads.get(intent.threadId);
+ const t = getSubagentThread(intent.threadId);
const buildUpdate = (withResult: boolean): Record<string, any> => {
const update: Record<string, any> = {
tools: intent.tools.map((x) =>
@@ -1355,18 +1416,19 @@ export const executeHeterogeneousAgent = async (
return update;
};
- // Phase 1: pre-register assistant.tools[] (no result_msg_id yet).
- try {
- await messageService.updateMessage(intent.assistantMessageId, buildUpdate(false), {
- agentId: context.agentId,
- topicId: context.topicId,
- });
- } catch (err) {
- console.error('[HeterogeneousAgent] Failed to pre-register subagent tools:', err);
- }
+ const operations: MessageBatchOperation[] = [
+ {
+ id: intent.assistantMessageId,
+ type: 'updateMessage',
+ value: buildUpdate(false),
+ },
+ ];
+ const newToolMessages: Array<{
+ message: UIChatMessage;
+ operationIndex: number;
+ toolCallId: string;
+ }> = [];
- // Phase 2: create rows for new tools with their pre-allocated ids,
- // register the global lookup, and seed the thread bucket bubble.
for (const x of intent.tools) {
if (!x.isNew) continue;
const subToolMetadata = heteroProvenance(intent.subagentMessageId);
@@ -1387,25 +1449,38 @@ export const executeHeterogeneousAgent = async (
tool_call_id: x.payload.id,
topicId: context.topicId,
};
- try {
- await messageService.createMessage(toolMsg);
- } catch (err) {
- console.error('[HeterogeneousAgent] Failed to create subagent tool message:', err);
- continue;
- }
- toolMsgIdByCallId.set(x.payload.id, x.toolMessageId);
- t?.stream.create(toolMsg as UIChatMessage);
- await replayPendingInterventionsForToolCall(x.payload.id);
+ operations.push({ message: toolMsg, type: 'createMessage' });
+ newToolMessages.push({
+ message: toolMsg as UIChatMessage,
+ operationIndex: operations.length - 1,
+ toolCallId: x.payload.id,
+ });
}
+ operations.push({
+ id: intent.assistantMessageId,
+ type: 'updateMessage',
+ value: buildUpdate(true),
+ });
- // Phase 3: backfill result_msg_id on assistant.tools[].
+ let persistedToolMessages = newToolMessages;
try {
- await messageService.updateMessage(intent.assistantMessageId, buildUpdate(true), {
- agentId: context.agentId,
- topicId: context.topicId,
- });
+ await mutateMessageBatch(operations);
} catch (err) {
- console.error('[HeterogeneousAgent] Failed to finalize subagent tools:', err);
+ console.error('[HeterogeneousAgent] Failed to persist subagent tool batch:', err);
+ if (!(err instanceof MessageBatchMutationError)) return;
+
+ const succeededIndexes = new Set(
+ err.result.results?.filter((item) => item.success).map((item) => item.index) ?? [],
+ );
+ persistedToolMessages = newToolMessages.filter(({ operationIndex }) =>
+ succeededIndexes.has(operationIndex),
+ );
+ }
+
+ for (const { message, toolCallId } of persistedToolMessages) {
+ toolMsgIdByCallId.set(toolCallId, message.id);
+ t?.stream.create(message);
+ await replayPendingInterventionsForToolCall(toolCallId);
}
// Surface the live assistant tools[] + content into the thread bucket.
@@ -1414,28 +1489,26 @@ export const executeHeterogeneousAgent = async (
}
case 'resolveToolResult': {
- const t = subagentThreads.get(intent.threadId);
- // DB write (via the global tool-message map) + live thread bucket update.
- await persistToolResult(
- intent.toolCallId,
- intent.content,
- intent.isError,
- toolMsgIdByCallId,
- context,
- intent.pluginState,
- );
+ const t = getSubagentThread(intent.threadId);
const toolMsgId = toolMsgIdByCallId.get(intent.toolCallId);
if (toolMsgId) {
- const update: Partial<UIChatMessage> = { content: intent.content };
- if (intent.pluginState) (update as any).pluginState = intent.pluginState;
- if (intent.isError) (update as any).pluginError = { message: intent.content };
- t?.stream.update(toolMsgId, update);
+ const update: ToolMessageUpdateOperation['value'] = {
+ content: intent.content,
+ pluginError: intent.isError ? { message: intent.content } : undefined,
+ pluginState: intent.pluginState,
+ };
+ try {
+ await mutateMessageBatch([{ id: toolMsgId, type: 'updateToolMessage', value: update }]);
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to persist subagent tool result:', err);
+ }
+ t?.stream.update(toolMsgId, update as Partial<UIChatMessage>);
}
return;
}
case 'recordUsage': {
- const t = subagentThreads.get(intent.threadId);
+ const t = getSubagentThread(intent.threadId);
const update = {
// Wholesale metadata overwrite β€” re-stamp the session + message
// provenance the createMessage write put there, or usage would wipe it.
@@ -1464,7 +1537,7 @@ export const executeHeterogeneousAgent = async (
} catch (err) {
console.error('[HeterogeneousAgent] Failed to mark subagent thread complete:', err);
}
- const t = subagentThreads.get(intent.threadId);
+ const t = getSubagentThread(intent.threadId);
if (t) completeSubagentOp(t.subOperationId);
return;
}
@@ -1755,6 +1828,8 @@ export const executeHeterogeneousAgent = async (
mainState = next;
};
+ await rehydrateClientSubagentRuns();
+
try {
// Start session (pass resumeSessionId for multi-turn --resume)
const result = await heterogeneousAgentService.startSession({