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: use frontend SoT for hetero tool reconciliation (#16946)

Arvin Xu8db3defaab12
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 00a63bf2dd6..878c2abf0d3 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -552,8 +552,11 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
* Runs the executor in background, then feeds CC events and completes.
* Returns a promise that resolves when the executor finishes.
*/
- async function runWithEvents(ccEvents: any[], opts?: { params?: Partial<typeof defaultParams> }) {
- const store = createMockStore();
+ async function runWithEvents(
+ ccEvents: any[],
+ opts?: { params?: Partial<typeof defaultParams>; store?: any },
+ ) {
+ const store = opts?.store ?? createMockStore();
const get = vi.fn(() => store);
// sendPrompt will resolve after we emit all events
@@ -674,7 +677,8 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
types.filter((type: string) => type === 'updateMessage').length,
).toBeGreaterThanOrEqual(2);
expect(types.filter((type: string) => type === 'createMessage')).toHaveLength(1);
- expect(types.at(-1)).toBe('updateToolMessage');
+ expect(types.filter((type: string) => type === 'updateToolMessage')).toHaveLength(1);
+ expect(types.indexOf('updateToolMessage')).toBeGreaterThan(types.indexOf('createMessage'));
});
});
@@ -1826,10 +1830,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(executorSettled).toBe(false);
expect(ipc.getListeners().has('heteroAgentEvent')).toBe(true);
- ipc.emitRawLine(
- 'ipc-sess-1',
- codexAgentMessage('item_2', 'Final report after late stdout.'),
- );
+ ipc.emitRawLine('ipc-sess-1', codexAgentMessage('item_2', 'Final report after late stdout.'));
ipc.emitRawLine('ipc-sess-1', codexTurnCompleted({ input_tokens: 10, output_tokens: 5 }));
await flush();
@@ -4301,44 +4302,75 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
// ────────────────────────────────────────────────────
- // Parallel main tool batch: tool_end must not race ahead of persistQueue
+ // Parallel main tool batch: frontend raw state is SoT before tool_end
// ────────────────────────────────────────────────────
describe('parallel-tools rollback regression', () => {
+ it('forwards initial stream_start with the existing assistant id so the handler skips DB refresh', async () => {
+ await runWithEvents([ccInit(), ccResult()]);
+
+ const handlerSpy = vi.mocked(createGatewayEventHandler).mock.results.at(-1)
+ ?.value as ReturnType<typeof vi.fn>;
+ const initialStreamStart = handlerSpy.mock.calls
+ .map(([event]: any[]) => event)
+ .find((event: any) => event?.type === 'stream_start' && !event.data?.newStep);
+
+ expect(initialStreamStart?.data?.assistantMessage).toMatchObject({
+ agentId: 'agent-1',
+ id: 'ast-initial',
+ role: 'assistant',
+ topicId: 'topic-1',
+ });
+ });
+
+ it('forwards terminal runtime_end with frontend uiMessages so the handler skips DB refresh', async () => {
+ const frontendMessages = [
+ {
+ agentId: 'agent-1',
+ content: 'test prompt',
+ id: 'user-1',
+ role: 'user',
+ topicId: 'topic-1',
+ },
+ {
+ agentId: 'agent-1',
+ content: 'done',
+ id: 'ast-initial',
+ role: 'assistant',
+ topicId: 'topic-1',
+ },
+ ];
+ const store = createMockStore({
+ dbMessagesMap: { 'main_agent-1_topic-1': frontendMessages },
+ messagesMap: { 'main_agent-1_topic-1': frontendMessages },
+ });
+
+ await runWithEvents([ccInit(), ccText('msg_01', 'done'), ccResult()], { store });
+
+ const handlerSpy = vi.mocked(createGatewayEventHandler).mock.results.at(-1)
+ ?.value as ReturnType<typeof vi.fn>;
+ const terminalRuntimeEnd = handlerSpy.mock.calls
+ .map(([event]: any[]) => event)
+ .find((event: any) => event?.type === 'agent_runtime_end');
+
+ expect(terminalRuntimeEnd?.data?.uiMessages).toEqual(frontendMessages);
+ });
+
/**
* User-reported bug: when CC fires a large parallel tool batch (e.g. 7
* Bash commands at once), the AssistantGroup tool count occasionally
* "rolls back" β€” e.g. UI shows "7 ζ¬‘ζŠ€θƒ½θ°ƒη”¨" then drops to 6.
*
- * Root cause: the executor's `persistQueue` (DB writes) and the gateway
- * handler's `processingChain` (in-memory dispatch + fetchAndReplaceMessages
- * on tool_end) are two independent serial queues with no happens-before
- * between them. `tool_end` events are forwarded to the handler
- * SYNCHRONOUSLY at the bottom of `handleStreamEvent` (the
- * `pendingStepTransition` gate only fires on stream_start(newStep), not
- * inside a single message.id with parallel tool_use). So when a fast
- * tool_result lands before persistQueue has flushed the LAST
- * persistToolBatch's Phase 1/3 write, the handler runs
- * fetchAndReplaceMessages β†’ reads `assistant.tools` with a partial array
- * β†’ replaceMessages clobbers in-memory state from N β†’ N-k.
- *
- * Observable invariant: by the time the handler is invoked with the FIRST
- * `tool_end` event (which is what triggers fetchAndReplaceMessages), the
- * most recent `mockUpdateMessage` call that wrote a `tools` array must
- * already carry the full cumulative tool list. Otherwise, in real life,
- * the DB read at that moment would return a shorter array and the UI
- * would visibly drop tools.
- *
- * The test slows down `mockUpdateMessage` whenever `val.tools` is present,
- * simulating the lag between Phase 1/3 writes and the rest of the stream.
- * `vi.fn().mock.invocationCallOrder` gives a total ordering across all
- * mocks so we can compare "when was the Nth tools-write CALLED" against
- * "when was the first tool_end forwarded to the handler".
+ * New invariant: the executor treats the renderer's raw message bucket as
+ * the streaming SoT. Before forwarding the first `tool_end`, it must have
+ * locally created all tool rows and updated the parent assistant's `tools[]`
+ * with pre-allocated `result_msg_id`s. The forwarded event is marked so the
+ * gateway handler skips its historical DB refetch; write-behind batchMutate
+ * can drain independently without clobbering the frontend snapshot.
*/
- it('handler must not receive tool_end before persistQueue flushes full tools[]', async () => {
- // Slow tools-bearing updateMessage writes β€” mirrors a real PG/lambda
- // round trip taking long enough that a fast Bash tool_result can land
- // before all 7 persistToolBatch operations finish their Phase 1/3.
+ it('handler receives tool_end only after local raw SoT has full tools[]', async () => {
+ // Slow DB writes to prove local SoT, not backend timing, is the ordering
+ // source. tool_end should no longer depend on these writes completing.
const TOOLS_WRITE_DELAY_MS = 12;
mockUpdateMessage.mockImplementation(async (_id: string, val: any) => {
if (val?.tools) {
@@ -4346,13 +4378,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
}
});
- // Give each tool message a deterministic id so we can spot-check.
- let toolIdx = 0;
- mockCreateMessage.mockImplementation(async (params: any) => {
- if (params.role === 'tool') return { id: `tool-msg-${++toolIdx}` };
- return { id: `ast-${params.role}-${Date.now()}` };
- });
-
const PARALLEL = 7;
const toolIds = Array.from({ length: PARALLEL }, (_, i) => `toolu_par_${i + 1}`);
@@ -4369,59 +4394,111 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
}
events.push(ccResult());
- await runWithEvents(events);
+ const { store } = await runWithEvents(events);
const handlerSpy = vi.mocked(createGatewayEventHandler).mock.results[0]?.value as ReturnType<
typeof vi.fn
>;
expect(handlerSpy).toBeDefined();
- // Find the FIRST tool_end forwarded to the handler β€” this is the call
- // that would trigger `fetchAndReplaceMessages` in real life and read
- // assistant.tools[] from DB.
+ // Find the FIRST tool_end forwarded to the handler. Historically this
+ // would trigger `fetchAndReplaceMessages`; it now carries a skip marker
+ // after local raw SoT has settled.
const handlerCalls = handlerSpy.mock.calls.map((args, i) => ({
event: args[0] as any,
order: handlerSpy.mock.invocationCallOrder[i],
}));
const firstToolEnd = handlerCalls.find(({ event }) => event?.type === 'tool_end');
expect(firstToolEnd).toBeDefined();
-
- // All `mockUpdateMessage(_, { tools })` calls β€” these are persistToolBatch
- // Phase 1 (pre-register) and Phase 3 (backfill) writes. Their invocation
- // order is the moment Phase 1/3 ENTERED `await messageService.updateMessage`.
- // Because persistToolBatch awaits each phase before moving on, the order
- // here is a faithful proxy for the DB-write timeline.
- const toolsWrites = mockUpdateMessage.mock.calls
- .map((args, i) => ({
- tools: (args[1] as any)?.tools,
- order: mockUpdateMessage.mock.invocationCallOrder[i],
+ expect(firstToolEnd!.event.data?.skipMessageFetch).toBe(true);
+
+ // Local raw-bucket assistant tools[] updates. This is the frontend SoT the
+ // UI reads while write-behind persistence is still draining.
+ const localToolsWrites = store.internal_dispatchMessage.mock.calls
+ .map((args: any[], i: number) => ({
+ payload: args[0] as any,
+ order: store.internal_dispatchMessage.mock.invocationCallOrder[i],
}))
- .filter(({ tools }) => Array.isArray(tools));
+ .filter(
+ ({ payload }: { payload: any }) =>
+ payload.type === 'updateMessage' && Array.isArray(payload.value?.tools),
+ );
// The latest tools[] write that started BEFORE the handler's first tool_end.
- // If the executor properly defers tool_end through persistQueue, this
- // should be the FINAL Phase 3 write carrying all 7 tools.
- const latestBeforeToolEnd = toolsWrites.findLast(({ order }) => order < firstToolEnd!.order);
-
- // The bug: without the deferral fix, persistQueue is still mid-flight
- // (or hasn't started) when tool_end is forwarded, so the latest tools[]
- // write seen at that point has fewer than PARALLEL entries β€” exactly
- // the "7 β†’ 6" rollback the user sees in the UI.
- const writtenCount = latestBeforeToolEnd?.tools?.length ?? 0;
- const writtenIds = (latestBeforeToolEnd?.tools ?? []).map((t: any) => t.id);
+ // With frontend SoT this must be the final local update carrying all 7
+ // tools, regardless of whether DB updateMessage has completed.
+ const latestBeforeToolEnd = localToolsWrites.findLast(
+ ({ order }: { order: number }) => order < firstToolEnd!.order,
+ );
+
+ const writtenTools = latestBeforeToolEnd?.payload.value.tools ?? [];
+ const writtenCount = writtenTools.length;
+ const writtenIds = writtenTools.map((t: any) => t.id);
const handlerEventTrail = handlerCalls.map(({ event }) => event?.type).join(',');
expect(
writtenCount,
`tool_end forwarded to handler at order ${firstToolEnd!.order} ` +
- `but the latest persistToolBatch tools[] write at that point had ` +
- `${writtenCount}/${PARALLEL} tools β€” fetchAndReplaceMessages would ` +
- `read partial assistant.tools[] and roll back the UI. ` +
+ `but the latest local tools[] write at that point had ` +
+ `${writtenCount}/${PARALLEL} tools. ` +
`Handler event trail: [${handlerEventTrail}]`,
).toBe(PARALLEL);
// All 7 tool ids must be present in that write β€” guards against any
// weird ordering where the last write happens to have 7 entries but
// the wrong ones (e.g. dedupe bug repopulating from a stale set).
for (const id of toolIds) expect(writtenIds).toContain(id);
+ for (const tool of writtenTools) expect(tool.result_msg_id).toMatch(/^msg_/);
+ });
+
+ it('creates main tool rows and resolves tool results in the local raw bucket', async () => {
+ const toolIds = ['toolu_sot_1', 'toolu_sot_2', 'toolu_sot_3'];
+ const events: any[] = [ccInit()];
+ for (const id of toolIds) {
+ events.push(ccToolUse('msg_sot', id, 'Bash', { command: `echo ${id}` }));
+ }
+ for (const id of toolIds) {
+ events.push(ccToolResult(id, `result of ${id}`));
+ }
+ events.push(ccResult());
+
+ const { store } = await runWithEvents(events);
+ const dispatches = store.internal_dispatchMessage.mock.calls.map(
+ ([payload]: any[]) => payload,
+ );
+ const localToolCreates = dispatches.filter(
+ (payload: any) => payload.type === 'createMessage' && payload.value?.role === 'tool',
+ );
+
+ expect(localToolCreates).toHaveLength(toolIds.length);
+
+ const messageIdByToolCallId = new Map<string, string>();
+ for (const payload of localToolCreates) {
+ messageIdByToolCallId.set(payload.value.tool_call_id, payload.value.id);
+ expect(payload.value).toMatchObject({
+ parentId: 'ast-initial',
+ role: 'tool',
+ topicId: 'topic-1',
+ });
+ }
+
+ const finalAssistantTools = dispatches.findLast(
+ (payload: any) =>
+ payload.type === 'updateMessage' &&
+ payload.id === 'ast-initial' &&
+ Array.isArray(payload.value?.tools),
+ ).value.tools;
+
+ for (const id of toolIds) {
+ const tool = finalAssistantTools.find((item: any) => item.id === id);
+ expect(tool?.result_msg_id).toBe(messageIdByToolCallId.get(id));
+ expect(
+ dispatches.some(
+ (payload: any) =>
+ payload.type === 'updateMessage' &&
+ payload.id === messageIdByToolCallId.get(id) &&
+ payload.value?.content === `result of ${id}`,
+ ),
+ ).toBe(true);
+ }
});
});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
index a5d9b66df1e..4501d16f291 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
@@ -109,6 +109,109 @@ describe('createGatewayEventHandler', () => {
expect(store.internal_dispatchMessage).not.toHaveBeenCalled();
});
+ it('skips tool_end DB refetch for hetero events that already reconciled frontend state', async () => {
+ const getMessages = vi
+ .spyOn(messageService, 'getMessages')
+ .mockResolvedValue([] as unknown as UIChatMessage[]);
+ const store = createStore();
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'seed-msg',
+ context,
+ operationId: 'op-1',
+ runtimeType: 'hetero',
+ });
+
+ handler(makeEvent('tool_end', { isSuccess: true, skipMessageFetch: true }));
+ await flush();
+
+ expect(getMessages).not.toHaveBeenCalled();
+ expect(store.replaceMessages).not.toHaveBeenCalled();
+ });
+
+ it('keeps gateway tool_end on the DB-refetch path even if the skip flag is present', async () => {
+ const getMessages = vi
+ .spyOn(messageService, 'getMessages')
+ .mockResolvedValue([] as unknown as UIChatMessage[]);
+ const store = createStore();
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'seed-msg',
+ context,
+ operationId: 'op-1',
+ });
+
+ handler(makeEvent('tool_end', { isSuccess: true, skipMessageFetch: true }));
+ await flush();
+
+ expect(getMessages).toHaveBeenCalledWith(context);
+ expect(store.replaceMessages).toHaveBeenCalledWith([], { context });
+ });
+
+ it('skips hetero execution_complete DB refetch when frontend state is the snapshot', async () => {
+ const getMessages = vi
+ .spyOn(messageService, 'getMessages')
+ .mockResolvedValue([] as unknown as UIChatMessage[]);
+ const store = createStore();
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'seed-msg',
+ context,
+ operationId: 'op-1',
+ runtimeType: 'hetero',
+ });
+
+ handler(makeEvent('step_complete', { phase: 'execution_complete', skipMessageFetch: true }));
+ await flush();
+
+ expect(getMessages).not.toHaveBeenCalled();
+ expect(store.replaceMessages).not.toHaveBeenCalled();
+ });
+
+ it('preserves existing result_msg_id when a tools_calling chunk omits result links', async () => {
+ const store = createStore({
+ key: [
+ {
+ content: '',
+ id: 'seed-msg',
+ role: 'assistant',
+ tools: [
+ { apiName: 'Read', id: 'tc-1', result_msg_id: 'tool-msg-1' },
+ { apiName: 'Write', id: 'tc-2', result_msg_id: 'tool-msg-2' },
+ ],
+ } as unknown as UIChatMessage,
+ ],
+ });
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'seed-msg',
+ context,
+ operationId: 'op-1',
+ runtimeType: 'hetero',
+ });
+
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'tools_calling',
+ toolsCalling: [
+ { apiName: 'Read', id: 'tc-1' },
+ { apiName: 'Write', id: 'tc-2', result_msg_id: 'server-tool-msg-2' },
+ ],
+ }),
+ );
+ await flush();
+
+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
+ {
+ id: 'seed-msg',
+ type: 'updateMessage',
+ value: {
+ tools: [
+ { apiName: 'Read', id: 'tc-1', result_msg_id: 'tool-msg-1' },
+ { apiName: 'Write', id: 'tc-2', result_msg_id: 'server-tool-msg-2' },
+ ],
+ },
+ },
+ { operationId: 'op-1' },
+ );
+ });
+
it('does not insert a shell when the assistant row is already in the store', async () => {
const store = createStore({
key: [{ content: 'existing', id: 'step2-msg', role: 'assistant' } as UIChatMessage],
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
index 89e74bfa05b..84cc922c663 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -61,6 +61,47 @@ const fetchAndReplaceMessages = async (get: () => ChatStore, context: Conversati
return messages;
};
+const shouldSkipMessageFetch = (
+ event: AgentStreamEvent,
+ runtimeType: 'gateway' | 'hetero',
+): boolean => runtimeType === 'hetero' && event.data?.skipMessageFetch === true;
+
+const getToolId = (tool: unknown): string | undefined =>
+ isRecord(tool) ? pickNonEmptyString(tool.id) : undefined;
+
+const getToolResultMessageId = (tool: unknown): string | undefined =>
+ isRecord(tool) ? pickNonEmptyString(tool.result_msg_id) : undefined;
+
+const preserveToolResultMessageIds = (
+ toolsCalling: unknown[],
+ existingTools: unknown,
+): unknown[] => {
+ if (!Array.isArray(existingTools)) return toolsCalling;
+
+ const resultMsgIdByToolId = new Map<string, string>();
+ for (const tool of existingTools) {
+ const toolId = getToolId(tool);
+ const resultMsgId = getToolResultMessageId(tool);
+ if (toolId && resultMsgId) resultMsgIdByToolId.set(toolId, resultMsgId);
+ }
+
+ if (resultMsgIdByToolId.size === 0) return toolsCalling;
+
+ let changed = false;
+ const merged = toolsCalling.map((tool) => {
+ const toolId = getToolId(tool);
+ if (!toolId || getToolResultMessageId(tool)) return tool;
+
+ const resultMsgId = resultMsgIdByToolId.get(toolId);
+ if (!resultMsgId || !isRecord(tool)) return tool;
+
+ changed = true;
+ return { ...tool, result_msg_id: resultMsgId };
+ });
+
+ return changed ? merged : toolsCalling;
+};
+
interface ChatToolPayloadLike {
apiName?: unknown;
arguments?: unknown;
@@ -567,11 +608,16 @@ export const createGatewayEventHandler = (
if (data.chunkType === 'tools_calling' && data.toolsCalling) {
endReasoningIfNeeded();
hasStreamedContent = true;
+ const toolsCalling = preserveToolResultMessageIds(
+ data.toolsCalling as unknown[],
+ dbMessageSelectors.getDbMessageById(currentAssistantMessageId)(get())?.tools,
+ ) as NonNullable<StreamChunkData['toolsCalling']>;
+
get().internal_dispatchMessage(
{
id: currentAssistantMessageId,
type: 'updateMessage',
- value: { tools: data.toolsCalling },
+ value: { tools: toolsCalling },
},
dispatchContext,
);
@@ -579,7 +625,7 @@ export const createGatewayEventHandler = (
// Drive tool calling animation
get().internal_toggleToolCallingStreaming(
currentAssistantMessageId,
- data.toolsCalling.map(() => true),
+ toolsCalling.map(() => true),
);
// If the server attached a `toolMessageIds` map, it has persisted
@@ -723,8 +769,11 @@ export const createGatewayEventHandler = (
case 'tool_end': {
const data = event.data as ToolEndData | undefined;
enqueue(async () => {
+ const maybeRefresh = shouldSkipMessageFetch(event, runtimeType)
+ ? Promise.resolve()
+ : fetchAndReplaceMessages(get, context).catch(console.error);
await Promise.all([
- fetchAndReplaceMessages(get, context).catch(console.error),
+ maybeRefresh,
dispatchOnAfterCall(data, context.topicId ?? undefined).catch(console.error),
]);
});
@@ -747,7 +796,9 @@ export const createGatewayEventHandler = (
sourceId: `${operationId}:gateway:step_complete:${event.stepIndex}`,
sourceType: 'client.gateway.step_complete',
});
- await fetchAndReplaceMessages(get, context).catch(console.error);
+ if (!shouldSkipMessageFetch(event, runtimeType)) {
+ await fetchAndReplaceMessages(get, context).catch(console.error);
+ }
});
}
break;
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 bd7fd86cfe0..e2302503dda 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -68,6 +68,10 @@ import { createGatewayEventHandler, isCompletedRuntimeEnd } from '../gateway/gat
/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */
const generateThreadId = () => `thd_${createNanoId(16)()}`;
+const markSkipMessageFetch = (event: AgentStreamEvent): void => {
+ event.data = { ...event.data, skipMessageFetch: true };
+};
+
const CLI_AUTH_REQUIRED_PATTERNS = [
/failed to authenticate/i,
/invalid authentication credentials/i,
@@ -743,6 +747,7 @@ export const executeHeterogeneousAgent = async (
* `persistToolResult` and the intervention handlers.
*/
const toolMsgIdByCallId: Map<string, string> = new Map();
+ const mainToolCallIds = new Set<string>();
/**
* Shared main-agent run coordinator state β€” the pure reducer in
* `@lobechat/heterogeneous-agents`. Owns the main turn/step state machine
@@ -847,6 +852,38 @@ export const executeHeterogeneousAgent = async (
*/
let sawStreamedEvent = false;
+ const getCurrentFrontendMessages = () =>
+ (get().dbMessagesMap?.[messageMapKey(context)] ??
+ get().messagesMap?.[messageMapKey(context)] ??
+ []) as UIChatMessage[];
+
+ const attachInitialAssistantSeed = (event: AgentStreamEvent): void => {
+ if (event.type !== 'stream_start') return;
+ if ((event.data as { newStep?: boolean } | undefined)?.newStep) return;
+ const data = (event.data ?? {}) as Record<string, any>;
+ if (data.assistantMessage?.id) return;
+
+ data.assistantMessage = {
+ agentId: context.agentId,
+ id: mainState.currentAssistantId,
+ model: data.model,
+ provider: data.provider,
+ role: 'assistant',
+ topicId: context.topicId ?? undefined,
+ };
+ event.data = data;
+ };
+
+ const attachTerminalFrontendSnapshot = (event: AgentStreamEvent): void => {
+ if (event.type !== 'agent_runtime_end') return;
+ const data = (event.data ?? {}) as Record<string, any>;
+ if (Array.isArray(data.uiMessages)) return;
+
+ const uiMessages = getCurrentFrontendMessages();
+ if (uiMessages.length === 0) return;
+ event.data = { ...data, uiMessages };
+ };
+
// Subscribe to the operation's abort signal so we can drop late events and
// stop writing to DB the moment the user clicks Stop. If the op is gone
// (cleaned up already) or missing in a test stub, treat as not-aborted.
@@ -957,6 +994,8 @@ export const executeHeterogeneousAgent = async (
isError: boolean,
pluginState?: Record<string, any>,
) => {
+ if (!mainToolCallIds.has(toolCallId)) return;
+
const toolMsgId = toolMsgIdByCallId.get(toolCallId);
if (!toolMsgId) {
console.warn('[HeterogeneousAgent] tool_result for unknown toolCallId:', toolCallId);
@@ -1304,13 +1343,13 @@ export const executeHeterogeneousAgent = async (
// ─── Main-agent run coordinator (shared reducer) interpreter ─────────────
/**
- * Apply ONE main-scoped coordinator intent against the renderer's DB
- * surfaces. Best-effort (errors logged, never thrown) β€” mirroring the prior
- * inline persist helpers, so the run state always advances regardless of a
- * transient DB failure (the next event / terminal flush re-persists). Live
- * UI is NOT driven here: the executor still forwards raw stream events to the
- * gateway `eventHandler` for token-level streaming, so `streamContent` is a
- * no-op (the server no-ops it too).
+ * Apply ONE main-scoped coordinator intent against the renderer's write-behind
+ * DB queue plus the local raw-message bucket. Best-effort (errors logged,
+ * never thrown) β€” mirroring the prior inline persist helpers, so the run state
+ * always advances regardless of a transient DB failure (the next event /
+ * terminal flush re-persists). Token-level text/reasoning still streams via the
+ * gateway handler; tool rows and result links are local SoT here so tool_end
+ * reconciliation does not need a DB fetch.
*/
const applyMainIntent = async (intent: MainAgentIntent) => {
switch (intent.kind) {
@@ -1332,6 +1371,10 @@ export const executeHeterogeneousAgent = async (
console.error('[HeterogeneousAgent] Failed to create step assistant:', err);
pendingMainCreates.set(intent.messageId, messageToCreate);
});
+ get().internal_dispatchMessage(
+ { id: intent.messageId, type: 'createMessage', value: messageToCreate },
+ { operationId },
+ );
// Associate so cancellation / cleanup tracks the new step's message.
get().associateMessageWithOperation(intent.messageId, operationId);
return;
@@ -1386,21 +1429,9 @@ export const executeHeterogeneousAgent = async (
return update;
};
- // Phase 1: pre-register assistant.tools[] (no result_msg_id yet) so the
- // conversation-flow parser finds matching ids the moment tool rows land.
- messageWriteBatcher.enqueueUpdateMessage(
- intent.assistantMessageId,
- buildUpdate(false),
- messageWriteCtx,
- (err) => console.error('[HeterogeneousAgent] Failed to pre-register main tools:', err),
- );
-
- // Phase 2: create rows for new tools with their pre-allocated ids and
- // register the global lookup so a later tool_result resolves.
- for (const x of intent.tools) {
- if (!x.isNew) continue;
+ const buildToolMessage = (x: (typeof intent.tools)[number]) => {
const toolMetadata = heteroProvenance(mainState.currentMainMessageId);
- messageWriteBatcher.enqueueCreateMessage({
+ return {
agentId: context.agentId,
content: '',
id: x.toolMessageId,
@@ -1415,17 +1446,48 @@ export const executeHeterogeneousAgent = async (
role: 'tool',
tool_call_id: x.payload.id,
topicId: context.topicId ?? undefined,
- } as any);
+ } as any;
+ };
+
+ // Phase 1: pre-register assistant.tools[] (no result_msg_id yet) so the
+ // conversation-flow parser finds matching ids the moment tool rows land.
+ messageWriteBatcher.enqueueUpdateMessage(
+ intent.assistantMessageId,
+ buildUpdate(false),
+ messageWriteCtx,
+ (err) => console.error('[HeterogeneousAgent] Failed to pre-register main tools:', err),
+ );
+
+ // Phase 2: create rows for new tools with their pre-allocated ids and
+ // register the global lookup so a later tool_result resolves.
+ for (const x of intent.tools) {
+ if (!x.isNew) continue;
+ const toolMsg = buildToolMessage(x);
+ messageWriteBatcher.enqueueCreateMessage(toolMsg);
toolMsgIdByCallId.set(x.payload.id, x.toolMessageId);
+ mainToolCallIds.add(x.payload.id);
+ get().internal_dispatchMessage(
+ { id: x.toolMessageId, type: 'createMessage', value: toolMsg },
+ { operationId },
+ );
}
// Phase 3: backfill result_msg_id on assistant.tools[].
+ const finalAssistantUpdate = buildUpdate(true);
messageWriteBatcher.enqueueUpdateMessage(
intent.assistantMessageId,
- buildUpdate(true),
+ finalAssistantUpdate,
messageWriteCtx,
(err) => console.error('[HeterogeneousAgent] Failed to finalize main tools:', err),
);
+ get().internal_dispatchMessage(
+ {
+ id: intent.assistantMessageId,
+ type: 'updateMessage',
+ value: finalAssistantUpdate as Partial<UIChatMessage>,
+ },
+ { operationId },
+ );
return;
}
@@ -1436,6 +1498,16 @@ export const executeHeterogeneousAgent = async (
intent.isError,
intent.pluginState,
);
+ const toolMsgId = toolMsgIdByCallId.get(intent.toolCallId);
+ if (toolMsgId && mainToolCallIds.has(intent.toolCallId)) {
+ 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 };
+ get().internal_dispatchMessage(
+ { id: toolMsgId, type: 'updateMessage', value: update },
+ { operationId },
+ );
+ }
return;
}
@@ -1735,26 +1807,31 @@ export const executeHeterogeneousAgent = async (
// Forward to the unified Gateway handler.
//
- // Events that drive `fetchAndReplaceMessages` on the handler side
- // (`tool_end`, `step_complete:execution_complete`, `stream_chunk` with a
- // server-attached `toolMessageIds`) must wait for `persistQueue` to drain
- // β€” otherwise the handler reads `assistant.tools[]` while a parallel
- // `persistToolBatch` is still mid-flight and `replaceMessages` clobbers
- // the in-memory cumulative tools[] with a shorter snapshot. That's the
- // "7 β†’ 6 tool-calls" rollback users see on parallel CC tool batches.
+ // Events that used to drive `fetchAndReplaceMessages` on the handler side
+ // (`tool_end`, `step_complete:execution_complete`) now wait only for the
+ // reducer to settle local raw-message SoT, then tell the handler to skip
+ // the DB fetch. This keeps parallel tool batches from being overwritten by
+ // a stale DB snapshot while write-behind batchMutate drains independently.
+ // `stream_chunk` with server-attached `toolMessageIds` still fetches: that
+ // path means the server created rows the client does not have locally.
//
// Other forwards (text / reasoning / tools_calling dispatches) stay
// synchronous so live streaming UX isn't gated on DB round-trips.
- const triggersFetchAndReplace =
+ attachInitialAssistantSeed(event);
+ const hasFrontendSotReconciliation =
event.type === 'tool_end' ||
(event.type === 'step_complete' &&
- (event.data as { phase?: string } | undefined)?.phase === 'execution_complete') ||
+ (event.data as { phase?: string } | undefined)?.phase === 'execution_complete');
+ const triggersFetchAndReplace =
+ hasFrontendSotReconciliation ||
(event.type === 'stream_chunk' &&
(event.data as { toolMessageIds?: unknown } | undefined)?.toolMessageIds !== undefined);
if (pendingStepTransition || triggersFetchAndReplace) {
persistQueue = persistQueue.then(async () => {
- if (triggersFetchAndReplace) {
+ if (hasFrontendSotReconciliation) {
+ markSkipMessageFetch(event);
+ } else if (triggersFetchAndReplace) {
await messageWriteBatcher.flush('before-fetch-replace');
}
eventHandler(event);
@@ -1785,8 +1862,7 @@ export const executeHeterogeneousAgent = async (
// this guards against. Content persistence + the terminal forward still
// wait for queued reducer state so terminal never flushes stale content.
{
- const reason = (deferredTerminalEvent?.data as { reason?: string } | undefined)
- ?.reason;
+ const reason = (deferredTerminalEvent?.data as { reason?: string } | undefined)?.reason;
if (isErrorTerminal) {
writeTopicStatus('failed');
} else if (!isAborted() && isCompletedRuntimeEnd(reason)) {
@@ -1874,9 +1950,10 @@ export const executeHeterogeneousAgent = async (
if (!isErrorTerminal) {
// Topic status was already reset ahead of the queue (top of
- // onComplete); forward the deferred terminal only so the handler runs
- // the final fetchAndReplaceMessages + completeOperation against the
- // now-persisted state.
+ // onComplete); forward the deferred terminal with the current
+ // frontend SoT so the handler can complete the operation without a
+ // DB refresh that may race write-behind batchMutate.
+ attachTerminalFrontendSnapshot(terminalEvent);
eventHandler(terminalEvent);
if (!queueDrained) get().completeOperation(operationId);
}