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(codex): stream live todo progress (#17329)

AmAzing-8d9ccca0e25c
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index 94f6594d20e..c9849771e9c 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -398,6 +398,107 @@ describe('hetero exec command', () => {
expect(exitSpy).toHaveBeenCalledWith(130);
});
+ it('flushes terminal tool events before finishing a server-ingest run as cancelled', async () => {
+ let sigintHandler: (() => void) | undefined;
+ vi.spyOn(process, 'on').mockImplementation(((event: string, listener: () => void) => {
+ if (event === 'SIGINT') sigintHandler = listener;
+ return process;
+ }) as typeof process.on);
+
+ let resolveFirstEvent: ((result: IteratorResult<Record<string, unknown>>) => void) | undefined;
+ let eventIndex = 0;
+ const events: AsyncIterable<Record<string, unknown>> = {
+ [Symbol.asyncIterator]() {
+ return {
+ next: async () => {
+ if (eventIndex === 0) {
+ eventIndex += 1;
+ return new Promise<IteratorResult<Record<string, unknown>>>((resolve) => {
+ resolveFirstEvent = resolve;
+ });
+ }
+ if (eventIndex === 1) {
+ eventIndex += 1;
+ return {
+ done: false,
+ value: {
+ data: { isSuccess: false, toolCallId: 'todo-1' },
+ operationId: 'op-cancel',
+ stepIndex: 0,
+ timestamp: 2,
+ type: 'tool_end',
+ },
+ };
+ }
+ return { done: true, value: undefined };
+ },
+ };
+ },
+ };
+ const stderr = new PassThrough();
+ stderr.end();
+ const kill = vi.fn();
+ mockSpawnAgent.mockResolvedValue({
+ events,
+ exit: Promise.resolve({ code: null, signal: 'SIGINT' }),
+ kill,
+ pid: 12_345,
+ stderr,
+ });
+
+ const callOrder: string[] = [];
+ mockHeteroIngestMutate.mockImplementation(async ({ events: batch }) => {
+ callOrder.push(...batch.map((event: { type: string }) => event.type));
+ return { ack: true };
+ });
+ mockHeteroFinishMutate.mockImplementation(async ({ result }) => {
+ callOrder.push(`finish:${result}`);
+ return { ack: true };
+ });
+
+ const command = runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'codex',
+ '--prompt',
+ 'hi',
+ '--topic',
+ 'topic-1',
+ '--operation-id',
+ 'op-cancel',
+ '--render',
+ 'none',
+ ]);
+ for (let i = 0; i < 20 && !sigintHandler; i += 1) await Promise.resolve();
+
+ sigintHandler?.();
+ expect(kill).toHaveBeenCalledWith('SIGINT');
+ expect(mockHeteroFinishMutate).not.toHaveBeenCalled();
+
+ resolveFirstEvent?.({
+ done: false,
+ value: {
+ data: {
+ content: 'Todo list update interrupted.',
+ isError: true,
+ pluginState: { todos: { items: [] } },
+ toolCallId: 'todo-1',
+ },
+ operationId: 'op-cancel',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'tool_result',
+ },
+ });
+ await command;
+
+ expect(callOrder).toEqual(['tool_result', 'tool_end', 'finish:cancelled']);
+ expect(mockHeteroFinishMutate).toHaveBeenCalledWith(
+ expect.objectContaining({ error: undefined, result: 'cancelled' }),
+ );
+ });
+
it('combines --prompt + --image into mixed content blocks', async () => {
mockSpawnAgent.mockReturnValue(createFakeHandle());
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index 88dbb40aebb..c0123184a38 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -534,6 +534,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
*
* Returns:
* code / signal β€” child exit info
+ * cancelled β€” true when this CLI received SIGINT/SIGTERM for the run
* sessionId β€” CC session id from `system.init` (undefined on resume failure)
* ingestError β€” true when a batch could not be flushed after retries
* resumeNotFound β€” true when a resume-not-found error was intercepted
@@ -555,6 +556,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
interceptResumeErrors: boolean,
runLabel: string,
): Promise<{
+ cancelled: boolean;
code: number | null;
ingestError: boolean;
resumeNotFound: boolean;
@@ -618,32 +620,17 @@ const exec = async (options: ExecOptions): Promise<void> => {
// Ctrl-C β†’ SIGINT to the child's process group.
// Repeated Ctrl-C escalates to SIGKILL.
let interrupted = false;
- const onSigint = async () => {
+ const onSigint = () => {
if (interrupted) {
handle.kill('SIGKILL');
return;
}
interrupted = true;
handle.kill('SIGINT');
- if (serverIngester && sink) {
- try {
- await serverIngester.drain();
- await sink.finish({ result: 'cancelled' });
- } catch {
- // best-effort; process is exiting anyway
- }
- }
};
- const onSigterm = async () => {
+ const onSigterm = () => {
+ interrupted = true;
handle.kill('SIGTERM');
- if (serverIngester && sink) {
- try {
- await serverIngester.drain();
- await sink.finish({ result: 'cancelled' });
- } catch {
- // best-effort
- }
- }
};
process.on('SIGINT', onSigint);
process.on('SIGTERM', onSigterm);
@@ -734,6 +721,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
}
return {
+ cancelled: interrupted,
code,
ingestError,
resumeNotFound,
@@ -792,7 +780,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
// fresh session. The server's `heteroSessionId` is updated with the new id,
// breaking the stale-session loop.
let result = first;
- if (first.resumeNotFound) {
+ if (!first.cancelled && first.resumeNotFound) {
log.info('Resume failed (session not found or context overflow) β€” retrying without --resume');
result = await runOneAgent(
{
@@ -830,7 +818,10 @@ const exec = async (options: ExecOptions): Promise<void> => {
// still exits 0, so the exit code alone would report `success`. Treat any
// pushed terminal error as a failed run so the topic/task is marked failed.
const exitedClean =
- !result.ingestError && !result.sawTerminalError && (code === 0 || signal === 'SIGTERM');
+ !result.cancelled &&
+ !result.ingestError &&
+ !result.sawTerminalError &&
+ (code === 0 || signal === 'SIGTERM');
// When the run failed, pass an error detail so the server surfaces a useful
// message instead of the generic "Agent execution failed" fallback. Prefer
@@ -845,22 +836,23 @@ const exec = async (options: ExecOptions): Promise<void> => {
// re-deriving from the flattened message via the process-only classifier,
// which would drop `agentType`/`code` and demote the client UI to the
// generic error card.
- const finishError = exitedClean
- ? undefined
- : result.terminalErrorData
- ? {
- body: { ...result.terminalErrorData },
- message: String(result.terminalErrorData.message ?? errorDetail ?? ''),
- type: 'AgentRuntimeError',
- }
- : errorDetail
- ? buildFinishError(errorDetail.slice(-1024), 'AgentRuntimeError')
- : undefined;
+ const finishError =
+ result.cancelled || exitedClean
+ ? undefined
+ : result.terminalErrorData
+ ? {
+ body: { ...result.terminalErrorData },
+ message: String(result.terminalErrorData.message ?? errorDetail ?? ''),
+ type: 'AgentRuntimeError',
+ }
+ : errorDetail
+ ? buildFinishError(errorDetail.slice(-1024), 'AgentRuntimeError')
+ : undefined;
try {
await sink.finish({
error: finishError,
- result: exitedClean ? 'success' : 'error',
+ result: result.cancelled ? 'cancelled' : exitedClean ? 'success' : 'error',
sessionId,
});
} catch (err) {
diff --git a/apps/cli/src/utils/CoalescingBatchIngester.test.ts b/apps/cli/src/utils/CoalescingBatchIngester.test.ts
index 1ea0f1ad157..2496d289ad1 100644
--- a/apps/cli/src/utils/CoalescingBatchIngester.test.ts
+++ b/apps/cli/src/utils/CoalescingBatchIngester.test.ts
@@ -75,6 +75,51 @@ describe('CoalescingBatchIngester', () => {
});
});
+ it('forwards every tool-state snapshot unchanged and after preceding text', async () => {
+ const { batches, sink } = createSink();
+ const ingester = new CoalescingBatchIngester(sink);
+
+ ingester.push(textEvent('before state'));
+ ingester.push(
+ makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState: { version: 1 },
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ toolCallId: 'todo-1',
+ }),
+ );
+ ingester.push(
+ makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState: { version: 2 },
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ toolCallId: 'todo-1',
+ }),
+ );
+ await ingester.drain();
+
+ const batch = batches.flat();
+ expect(batch.map((event) => (event.data as any).chunkType)).toEqual([
+ 'text',
+ 'tool_state',
+ 'tool_state',
+ ]);
+ expect(batch[1].data).toMatchObject({
+ pluginState: { version: 1 },
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ toolCallId: 'todo-1',
+ });
+ expect(batch[2].data).toMatchObject({
+ pluginState: { version: 2 },
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ toolCallId: 'todo-1',
+ });
+ });
+
it('flushes a pending snapshot on the debounce timer without needing a following event', async () => {
const { batches, ingest, sink } = createSink();
const ingester = new CoalescingBatchIngester(sink);
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index b9b37aacaae..02f00dfc4c6 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -56,6 +56,11 @@ const messageAnalyticsSchema = z.object({
topicId: z.string().optional(),
});
+const heterogeneousToolStateSnapshotSchema = z.object({
+ operationId: z.string().min(1),
+ snapshotSeq: z.number().int().positive(),
+});
+
const messageBatchOperationSchema = z.discriminatedUnion('type', [
z.object({
message: CreateNewMessageParamsSchema,
@@ -71,6 +76,7 @@ const messageBatchOperationSchema = z.discriminatedUnion('type', [
type: z.literal('updateToolMessage'),
value: z.object({
content: z.string().optional(),
+ heterogeneousToolState: heterogeneousToolStateSnapshotSchema.optional(),
metadata: z.record(z.string(), z.any()).optional(),
pluginError: z.any().optional(),
pluginState: z.record(z.string(), z.any()).optional(),
@@ -706,6 +712,7 @@ export const messageRouter = router({
id: z.string(),
value: z.object({
content: z.string().optional(),
+ heterogeneousToolState: heterogeneousToolStateSnapshotSchema.optional(),
metadata: z.object({}).passthrough().optional(),
pluginError: z.any().optional(),
pluginState: z.object({}).passthrough().optional(),
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index 0c1c7f1d5f1..92acf7644d2 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -117,6 +117,8 @@ interface OperationState {
* Recovered on a cold replica from the current assistant's stamped metadata.
*/
heteroSessionId: string | undefined;
+ /** Last DB-confirmed tool-state seq, scoped to this operation. */
+ lastAppliedToolStateSeqByCallId: Map<string, number>;
lastStepIndex: number;
main: MainAgentRunState;
operationId: string;
@@ -458,6 +460,7 @@ export class HeterogeneousPersistenceHandler {
// which differs from the actual id when a fork/new session occurred.
heteroSessionId: undefined,
lastStepIndex: 0,
+ lastAppliedToolStateSeqByCallId: new Map(),
main: createMainAgentRunState(currentAssistantMessageId),
operationId,
processedKeys: new Set(),
@@ -542,6 +545,19 @@ export class HeterogeneousPersistenceHandler {
const toolPlugins = await this.deps.messageModel.listMessagePluginsByTopic(state.topicId);
for (const plugin of toolPlugins) {
if (plugin.toolCallId) state.toolMsgIdByCallId.set(plugin.toolCallId, plugin.id);
+ if (
+ plugin.toolCallId &&
+ plugin.metadata?.heterogeneousToolStateOperationId === state.operationId &&
+ typeof plugin.metadata.heterogeneousToolStateSeq === 'number'
+ ) {
+ state.lastAppliedToolStateSeqByCallId.set(
+ plugin.toolCallId,
+ Math.max(
+ state.lastAppliedToolStateSeqByCallId.get(plugin.toolCallId) ?? 0,
+ plugin.metadata.heterogeneousToolStateSeq,
+ ),
+ );
+ }
}
}
@@ -968,6 +984,11 @@ export class HeterogeneousPersistenceHandler {
return;
}
+ case 'updateToolState': {
+ await this.applyToolState(state, intent);
+ return;
+ }
+
case 'recordUsage': {
const update: Record<string, any> = {};
if (intent.usage !== undefined) {
@@ -1015,11 +1036,49 @@ export class HeterogeneousPersistenceHandler {
return;
}
- await this.deps.messageModel.updateToolMessage(toolMsgId, {
+ const result = await this.deps.messageModel.updateToolMessage(toolMsgId, {
content: intent.content,
pluginError: intent.isError ? { message: intent.content } : undefined,
pluginState: intent.pluginState,
});
+ if (!result.success) {
+ throw new Error(`Failed to persist tool_result for message ${toolMsgId}`);
+ }
+ }
+
+ private async applyToolState(
+ state: OperationState,
+ intent: {
+ pluginState: Record<string, unknown>;
+ snapshotSeq: number;
+ toolCallId: string;
+ },
+ ): Promise<void> {
+ const lastApplied = state.lastAppliedToolStateSeqByCallId.get(intent.toolCallId) ?? 0;
+ if (intent.snapshotSeq <= lastApplied) return;
+
+ const toolMsgId = state.toolMsgIdByCallId.get(intent.toolCallId);
+ if (!toolMsgId) {
+ throw new Error(
+ `tool_state for unknown toolCallId=${intent.toolCallId} op=${state.operationId}`,
+ );
+ }
+
+ const result = await this.deps.messageModel.updateToolMessage(toolMsgId, {
+ heterogeneousToolState: {
+ operationId: state.operationId,
+ snapshotSeq: intent.snapshotSeq,
+ },
+ pluginState: intent.pluginState,
+ });
+ if (!result.success) {
+ throw new Error(`Failed to persist tool_state for message ${toolMsgId}`);
+ }
+
+ state.lastAppliedToolStateSeqByCallId.set(
+ intent.toolCallId,
+ result.snapshotSeq ?? intent.snapshotSeq,
+ );
}
private buildToolBatchUpdate(
@@ -1148,6 +1207,11 @@ export class HeterogeneousPersistenceHandler {
return;
}
+ case 'updateToolState': {
+ await this.applyToolState(state, intent);
+ return;
+ }
+
case 'persistContent': {
const update: Record<string, any> = {};
if (intent.content) update.content = intent.content;
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
index 15502967268..79ab6eeb4c2 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
@@ -107,18 +107,43 @@ const createHarness = (
updateToolMessage: vi.fn(
async (
id: string,
- patch: { content?: string; metadata?: any; pluginError?: any; pluginState?: any },
+ patch: {
+ content?: string;
+ heterogeneousToolState?: { operationId: string; snapshotSeq: number };
+ metadata?: any;
+ pluginError?: any;
+ pluginState?: any;
+ },
) => {
const existing = messages.get(id);
if (!existing) return { success: false };
+ const snapshot = patch.heterogeneousToolState;
+ const currentSeq =
+ snapshot && existing.metadata?.heterogeneousToolStateOperationId === snapshot.operationId
+ ? (existing.metadata.heterogeneousToolStateSeq ?? 0)
+ : 0;
+ if (snapshot && snapshot.snapshotSeq <= currentSeq) {
+ return { applied: false, snapshotSeq: currentSeq, success: true };
+ }
messages.set(id, {
...existing,
content: patch.content ?? existing.content,
- metadata: patch.metadata ?? existing.metadata,
+ metadata: snapshot
+ ? {
+ ...existing.metadata,
+ ...patch.metadata,
+ heterogeneousToolStateOperationId: snapshot.operationId,
+ heterogeneousToolStateSeq: snapshot.snapshotSeq,
+ }
+ : (patch.metadata ?? existing.metadata),
pluginError: patch.pluginError,
pluginState: patch.pluginState ?? existing.pluginState,
});
- return { success: true };
+ return {
+ applied: true,
+ snapshotSeq: snapshot?.snapshotSeq,
+ success: true,
+ };
},
),
findById: vi.fn(async (id: string) => messages.get(id) ?? null),
@@ -406,6 +431,94 @@ describe('HeterogeneousPersistenceHandler β€” event branch coverage', () => {
expect(flushed).toBeDefined();
});
+ it('persists tool_state DB-first and drops stale in-operation snapshots', async () => {
+ const h = createHarness();
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tools_calling',
+ toolsCalling: [
+ {
+ apiName: 'todo_list',
+ arguments: '{}',
+ id: 'todo-1',
+ identifier: 'codex',
+ type: 'default',
+ },
+ ],
+ }),
+ buildEvent('stream_chunk', 1, {
+ chunkType: 'tool_state',
+ pluginState: { todos: { items: [{ status: 'processing', text: 'Implement' }] } },
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ toolCallId: 'todo-1',
+ }),
+ buildEvent('stream_chunk', 2, {
+ chunkType: 'tool_state',
+ pluginState: { stale: true },
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ toolCallId: 'todo-1',
+ }),
+ ]);
+
+ const stateWrites = h.messageModel.updateToolMessage.mock.calls.filter(
+ ([, patch]) => patch.heterogeneousToolState,
+ );
+ expect(stateWrites).toHaveLength(1);
+ expect(stateWrites[0][1]).toMatchObject({
+ heterogeneousToolState: { operationId: h.operationId, snapshotSeq: 2 },
+ pluginState: {
+ todos: { items: [{ status: 'processing', text: 'Implement' }] },
+ },
+ });
+ const toolMessage = [...h.messages.values()].find(
+ (message) => message.tool_call_id === 'todo-1',
+ );
+ expect(toolMessage?.metadata).toMatchObject({
+ heterogeneousToolStateOperationId: h.operationId,
+ heterogeneousToolStateSeq: 2,
+ });
+ expect(toolMessage?.pluginState).not.toEqual({ stale: true });
+ });
+
+ it('restores the tool-state watermark from DB after a cold operation-state reset', async () => {
+ const h = createHarness();
+ h.messages.set('tool-existing', {
+ agentId: null,
+ content: '',
+ id: 'tool-existing',
+ metadata: {
+ heterogeneousToolStateOperationId: h.operationId,
+ heterogeneousToolStateSeq: 4,
+ },
+ pluginState: { current: true },
+ role: 'tool',
+ tool_call_id: 'todo-existing',
+ topicId: h.topicId,
+ });
+ h.messageModel.listMessagePluginsByTopic.mockResolvedValue([
+ {
+ id: 'tool-existing',
+ metadata: h.messages.get('tool-existing')?.metadata,
+ toolCallId: 'todo-existing',
+ },
+ ] as any);
+
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tool_state',
+ pluginState: { stale: true },
+ snapshotMode: 'replace',
+ snapshotSeq: 3,
+ toolCallId: 'todo-existing',
+ }),
+ ]);
+
+ expect(h.messageModel.updateToolMessage).not.toHaveBeenCalled();
+ expect(h.messages.get('tool-existing')?.pluginState).toEqual({ current: true });
+ });
+
it('tools_calling with empty array is a no-op', async () => {
const h = createHarness();
await ingest(h, [
diff --git a/apps/server/src/services/message/index.ts b/apps/server/src/services/message/index.ts
index 738356a2750..aedd87f16de 100644
--- a/apps/server/src/services/message/index.ts
+++ b/apps/server/src/services/message/index.ts
@@ -2,6 +2,7 @@ import { type LobeChatDatabase } from '@lobechat/database';
import { CompressionRepository } from '@lobechat/database';
import {
type CreateMessageParams,
+ type HeterogeneousToolStateSnapshot,
type QueryMessageParams,
type UIChatMessage,
type UpdateMessageParams,
@@ -76,6 +77,7 @@ export type MessageBatchOperation =
type: 'updateToolMessage';
value: {
content?: string;
+ heterogeneousToolState?: HeterogeneousToolStateSnapshot;
metadata?: Record<string, any>;
pluginError?: any;
pluginState?: Record<string, any>;
@@ -360,6 +362,7 @@ export class MessageService {
id: string,
value: {
content?: string;
+ heterogeneousToolState?: HeterogeneousToolStateSnapshot;
metadata?: Record<string, any>;
pluginError?: any;
pluginState?: Record<string, any>;
diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.ts
index db67f473be6..c994d5009c7 100644
--- a/packages/agent-gateway-client/src/index.ts
+++ b/packages/agent-gateway-client/src/index.ts
@@ -16,4 +16,5 @@ export type {
ToolExecuteData,
ToolResultMessage,
ToolStartData,
+ ToolStateChunkData,
} from './types';
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index 9fdb9d5a25d..1409264744b 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -62,6 +62,7 @@ export interface AgentStreamEvent {
export type StreamChunkType =
| 'text'
| 'reasoning'
+ | 'tool_state'
| 'tools_calling'
| 'image'
| 'grounding'
@@ -76,6 +77,7 @@ export interface StreamChunkData {
grounding?: any;
imageList?: any[];
images?: any[];
+ pluginState?: Record<string, unknown>;
reasoning?: string;
reasoningParts?: Array<{ text: string; type: 'text' } | { image: string; type: 'image' }>;
/**
@@ -85,14 +87,26 @@ export interface StreamChunkData {
*/
snapshotMode?: 'replace';
/**
- * Operation-monotonic sequence for `replace` snapshots. Consumers drop a
- * snapshot whose seq is ≀ the last applied one β€” that is a redelivery
- * (producer batch retry) or an out-of-order duplicate.
+ * Sequence for `replace` snapshots. Text/reasoning producers keep it
+ * operation-monotonic; `tool_state` keeps it monotonic per toolCallId.
+ * Consumers drop a snapshot whose seq is ≀ the matching last-applied one.
*/
snapshotSeq?: number;
+ toolCallId?: string;
toolsCalling?: any[];
}
+/** Replace-only, non-terminal state snapshot for a running tool message. */
+export interface ToolStateChunkData {
+ chunkType: 'tool_state';
+ pluginState: Record<string, unknown>;
+ snapshotMode: 'replace';
+ snapshotSeq: number;
+ /** Subagent context is intentionally structural to avoid a package cycle. */
+ subagent?: { parentToolCallId: string; [key: string]: unknown };
+ toolCallId: string;
+}
+
// ─── Typed Event Data ───
/**
diff --git a/packages/database/src/models/__tests__/messages/message.update.test.ts b/packages/database/src/models/__tests__/messages/message.update.test.ts
index 73bdd66e1ae..d23395049c7 100644
--- a/packages/database/src/models/__tests__/messages/message.update.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.update.test.ts
@@ -655,6 +655,117 @@ describe('MessageModel Update Tests', () => {
});
});
+ it('atomically replaces heterogeneous tool state and rejects stale snapshots', async () => {
+ await serverDB.insert(messages).values({
+ content: '',
+ id: 'tool-state-msg',
+ metadata: { preserved: true },
+ role: 'tool',
+ userId,
+ });
+ await serverDB.insert(messagePlugins).values({
+ id: 'tool-state-msg',
+ identifier: 'codex',
+ state: { obsolete: true },
+ toolCallId: 'todo-1',
+ userId,
+ });
+
+ const applied = await messageModel.updateToolMessage('tool-state-msg', {
+ heterogeneousToolState: { operationId: 'op-1', snapshotSeq: 2 },
+ pluginState: { todos: { items: [{ status: 'processing', text: 'Implement' }] } },
+ });
+
+ expect(applied).toEqual({ applied: true, snapshotSeq: 2, success: true });
+ expect(
+ (await serverDB.select().from(messages).where(eq(messages.id, 'tool-state-msg')))[0]
+ .metadata,
+ ).toEqual({
+ heterogeneousToolStateOperationId: 'op-1',
+ heterogeneousToolStateSeq: 2,
+ preserved: true,
+ });
+ expect(
+ (
+ await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, 'tool-state-msg'))
+ )[0].state,
+ ).toEqual({ todos: { items: [{ status: 'processing', text: 'Implement' }] } });
+
+ const stale = await messageModel.updateToolMessage('tool-state-msg', {
+ heterogeneousToolState: { operationId: 'op-1', snapshotSeq: 1 },
+ pluginState: { stale: true },
+ });
+
+ expect(stale).toEqual({ applied: false, snapshotSeq: 2, success: true });
+ expect(
+ (
+ await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, 'tool-state-msg'))
+ )[0].state,
+ ).toEqual({ todos: { items: [{ status: 'processing', text: 'Implement' }] } });
+
+ const nextOperation = await messageModel.updateToolMessage('tool-state-msg', {
+ heterogeneousToolState: { operationId: 'op-2', snapshotSeq: 1 },
+ pluginState: { restarted: true },
+ });
+
+ expect(nextOperation).toEqual({ applied: true, snapshotSeq: 1, success: true });
+ expect(
+ (await serverDB.select().from(messages).where(eq(messages.id, 'tool-state-msg')))[0]
+ .metadata,
+ ).toMatchObject({
+ heterogeneousToolStateOperationId: 'op-2',
+ heterogeneousToolStateSeq: 1,
+ });
+ });
+
+ it('keeps the highest tool-state seq across concurrent writers', async () => {
+ await serverDB.insert(messages).values({
+ content: '',
+ id: 'tool-state-concurrent',
+ role: 'tool',
+ userId,
+ });
+ await serverDB.insert(messagePlugins).values({
+ id: 'tool-state-concurrent',
+ identifier: 'codex',
+ toolCallId: 'todo-concurrent',
+ userId,
+ });
+
+ await Promise.all([
+ messageModel.updateToolMessage('tool-state-concurrent', {
+ heterogeneousToolState: { operationId: 'op-concurrent', snapshotSeq: 2 },
+ pluginState: { version: 2 },
+ }),
+ messageModel.updateToolMessage('tool-state-concurrent', {
+ heterogeneousToolState: { operationId: 'op-concurrent', snapshotSeq: 3 },
+ pluginState: { version: 3 },
+ }),
+ ]);
+
+ const message = (
+ await serverDB.select().from(messages).where(eq(messages.id, 'tool-state-concurrent'))
+ )[0];
+ const plugin = (
+ await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, 'tool-state-concurrent'))
+ )[0];
+
+ expect(message.metadata).toMatchObject({
+ heterogeneousToolStateOperationId: 'op-concurrent',
+ heterogeneousToolStateSeq: 3,
+ });
+ expect(plugin.state).toEqual({ version: 3 });
+ });
+
it('should update pluginError only', async () => {
await serverDB.insert(messages).values({
id: 'tool-msg-4',
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 05624402cd4..6eca76f99e9 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -10,7 +10,9 @@ import type {
ChatVideoItem,
CreateMessageParams,
DBMessageItem,
+ HeterogeneousToolStateSnapshot,
IThreadType,
+ MessageMetadata,
MessagePluginItem,
ModelRankItem,
ModelUsage,
@@ -2607,7 +2609,9 @@ export class MessageModel {
* This is used by onboarding analytics to reconstruct successful assistant
* creation results before the topic is moved into inbox.
*/
- listMessagePluginsByTopic = async (topicId: string): Promise<MessagePluginItem[]> => {
+ listMessagePluginsByTopic = async (
+ topicId: string,
+ ): Promise<Array<MessagePluginItem & { metadata?: MessageMetadata }>> => {
const rows = await this.db
.select({
apiName: messagePlugins.apiName,
@@ -2617,6 +2621,7 @@ export class MessageModel {
id: messagePlugins.id,
identifier: messagePlugins.identifier,
intervention: messagePlugins.intervention,
+ metadata: messages.metadata,
state: messagePlugins.state,
toolCallId: messagePlugins.toolCallId,
type: messagePlugins.type,
@@ -2635,6 +2640,7 @@ export class MessageModel {
id: row.id,
identifier: row.identifier ?? undefined,
intervention: row.intervention ?? undefined,
+ metadata: row.metadata ?? undefined,
state: row.state ?? undefined,
toolCallId: row.toolCallId ?? undefined,
type: row.type ?? 'default',
@@ -2650,33 +2656,79 @@ export class MessageModel {
id: string,
params: {
content?: string;
+ heterogeneousToolState?: HeterogeneousToolStateSnapshot;
metadata?: Record<string, any>;
pluginError?: any;
pluginState?: Record<string, any>;
},
- ): Promise<{ success: boolean }> => {
- const { content, metadata, pluginState, pluginError } = params;
+ ): Promise<{ applied: boolean; snapshotSeq?: number; success: boolean }> => {
+ const { content, heterogeneousToolState, metadata, pluginState, pluginError } = params;
// `undefined` while no branch has looked for the row yet; see `update` above
// for why a write that matches nothing must not report success.
let matchedRow: boolean | undefined;
+ let applied = true;
+ let snapshotSeq: number | undefined;
try {
await this.db.transaction(async (trx) => {
+ let existingMetadata: Record<string, any> | undefined;
+
+ if (metadata !== undefined || heterogeneousToolState !== undefined) {
+ const baseQuery = trx
+ .select({ metadata: messages.metadata })
+ .from(messages)
+ .where(and(eq(messages.id, id), this.ownership()))
+ .limit(1);
+ const [existingMessage] = heterogeneousToolState
+ ? await baseQuery.for('update')
+ : await baseQuery;
+
+ matchedRow = !!existingMessage;
+ if (!existingMessage) return;
+
+ existingMetadata = (existingMessage.metadata ?? {}) as Record<string, any>;
+
+ if (heterogeneousToolState) {
+ const currentOperationId = existingMetadata.heterogeneousToolStateOperationId;
+ const rawCurrentSeq = existingMetadata.heterogeneousToolStateSeq;
+ const currentSeq =
+ currentOperationId === heterogeneousToolState.operationId &&
+ typeof rawCurrentSeq === 'number' &&
+ Number.isFinite(rawCurrentSeq)
+ ? rawCurrentSeq
+ : 0;
+
+ if (heterogeneousToolState.snapshotSeq <= currentSeq) {
+ applied = false;
+ snapshotSeq = currentSeq;
+ return;
+ }
+
+ snapshotSeq = heterogeneousToolState.snapshotSeq;
+ }
+ }
+
// Update messages table (content, metadata)
- if (content !== undefined || metadata !== undefined) {
+ if (
+ content !== undefined ||
+ metadata !== undefined ||
+ heterogeneousToolState !== undefined
+ ) {
const messageUpdateData: Record<string, any> = {};
if (content !== undefined) {
messageUpdateData.content = content;
}
- if (metadata !== undefined) {
- // Need to merge with existing metadata
- const existingMessage = await trx.query.messages.findFirst({
- where: and(eq(messages.id, id), this.ownership()),
- });
- messageUpdateData.metadata = merge(existingMessage?.metadata || {}, metadata);
+ if (metadata !== undefined || heterogeneousToolState !== undefined) {
+ const mergedMetadata = merge(existingMetadata || {}, metadata || {});
+ messageUpdateData.metadata = heterogeneousToolState
+ ? merge(mergedMetadata, {
+ heterogeneousToolStateOperationId: heterogeneousToolState.operationId,
+ heterogeneousToolStateSeq: heterogeneousToolState.snapshotSeq,
+ })
+ : mergedMetadata;
}
if (Object.keys(messageUpdateData).length > 0) {
@@ -2704,7 +2756,9 @@ export class MessageModel {
const pluginUpdateData: Record<string, any> = {};
if (pluginState !== undefined) {
- pluginUpdateData.state = merge(pluginItem.state || {}, pluginState);
+ pluginUpdateData.state = heterogeneousToolState
+ ? pluginState
+ : merge(pluginItem.state || {}, pluginState);
}
if (pluginError !== undefined) {
@@ -2717,19 +2771,21 @@ export class MessageModel {
.set(pluginUpdateData)
.where(and(eq(messagePlugins.id, id), this.pluginsOwnership()));
}
+ } else if (heterogeneousToolState) {
+ throw new Error(`No tool plugin matched id ${id}`);
}
}
});
if (matchedRow === false) {
console.error(`Update tool message error: no tool message matched id ${id}`);
- return { success: false };
+ return { applied: false, success: false };
}
- return { success: true };
+ return { applied, snapshotSeq, success: true };
} catch (error) {
console.error('Update tool message error:', error);
- return { success: false };
+ return { applied: false, success: false };
}
};
diff --git a/packages/heterogeneous-agents/src/adapters/codex.test.ts b/packages/heterogeneous-agents/src/adapters/codex.test.ts
index 020821b2356..69a43a4a33d 100644
--- a/packages/heterogeneous-agents/src/adapters/codex.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/codex.test.ts
@@ -705,7 +705,7 @@ describe('CodexAdapter', () => {
expect(result.data.pluginState.stdout).toBe(result.data.content);
});
- it('maps todo_list items into shared todo plugin state', () => {
+ it('maps todo_list items into shared todo plugin state after successful turn completion', () => {
const adapter = new CodexAdapter();
const todoItem = {
@@ -722,10 +722,22 @@ describe('CodexAdapter', () => {
item: todoItem,
type: 'item.started',
});
- const completed = adapter.adapt({
+ const updated = adapter.adapt({
+ item: {
+ ...todoItem,
+ items: [
+ { completed: true, text: 'Create the three-item todo list' },
+ { completed: true, text: 'Keep the second item incomplete' },
+ { completed: false, text: 'Keep the third item incomplete' },
+ ],
+ },
+ type: 'item.updated',
+ });
+ const deferredCompletion = adapter.adapt({
item: todoItem,
type: 'item.completed',
});
+ const completed = adapter.adapt({ type: 'turn.completed' });
expect(started[0]).toMatchObject({
data: {
@@ -740,6 +752,36 @@ describe('CodexAdapter', () => {
},
type: 'stream_chunk',
});
+ expect(started[2]).toMatchObject({
+ data: {
+ chunkType: 'tool_state',
+ pluginState: {
+ todos: {
+ items: [
+ { status: 'completed', text: 'Create the three-item todo list' },
+ { status: 'processing', text: 'Keep the second item incomplete' },
+ { status: 'todo', text: 'Keep the third item incomplete' },
+ ],
+ },
+ },
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ toolCallId: 'item_0',
+ },
+ type: 'stream_chunk',
+ });
+ expect(updated).toEqual([
+ expect.objectContaining({
+ data: expect.objectContaining({
+ chunkType: 'tool_state',
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ toolCallId: 'item_0',
+ }),
+ type: 'stream_chunk',
+ }),
+ ]);
+ expect(deferredCompletion).toEqual([]);
expect(completed[0]).toMatchObject({
data: {
content: 'Todo list updated (1/3 completed).',
@@ -760,6 +802,137 @@ describe('CodexAdapter', () => {
data: { isSuccess: true, toolCallId: 'item_0' },
type: 'tool_end',
});
+ expect(completed.some((event) => event.data?.chunkType === 'tool_state')).toBe(false);
+ expect(adapter.flush()).toEqual([]);
+ });
+
+ it('emits an explicit empty Todo snapshot when a non-empty list is cleared', () => {
+ const adapter = new CodexAdapter();
+ const startedItem = {
+ id: 'todo-cleared',
+ items: [{ completed: false, text: 'Temporary task' }],
+ status: 'in_progress',
+ type: 'todo_list',
+ };
+
+ adapter.adapt({ item: startedItem, type: 'item.started' });
+ const updated = adapter.adapt({
+ item: { ...startedItem, items: [] },
+ type: 'item.updated',
+ });
+ const completed = adapter.adapt({
+ item: { ...startedItem, items: [], status: 'completed' },
+ type: 'item.completed',
+ });
+
+ expect(updated).toEqual([
+ expect.objectContaining({
+ data: expect.objectContaining({
+ chunkType: 'tool_state',
+ pluginState: { todos: expect.objectContaining({ items: [] }) },
+ snapshotSeq: 2,
+ toolCallId: 'todo-cleared',
+ }),
+ type: 'stream_chunk',
+ }),
+ ]);
+ expect(completed[0]).toMatchObject({
+ data: {
+ isError: false,
+ pluginState: { todos: { items: [] } },
+ toolCallId: 'todo-cleared',
+ },
+ type: 'tool_result',
+ });
+ });
+
+ it('clears a pending Todo snapshot when the runtime is interrupted', () => {
+ const adapter = new CodexAdapter();
+
+ const todoItem = {
+ id: 'todo-interrupted',
+ items: [
+ { completed: false, text: 'First task' },
+ { completed: false, text: 'Still running' },
+ ],
+ type: 'todo_list',
+ };
+
+ adapter.adapt({
+ item: todoItem,
+ type: 'item.started',
+ });
+ adapter.adapt({
+ item: {
+ ...todoItem,
+ items: [
+ { completed: true, text: 'First task' },
+ { completed: false, text: 'Still running' },
+ ],
+ },
+ type: 'item.updated',
+ });
+ const deferredCompletion = adapter.adapt({
+ item: {
+ ...todoItem,
+ items: [
+ { completed: true, text: 'First task' },
+ { completed: false, text: 'Still running' },
+ ],
+ },
+ type: 'item.completed',
+ });
+
+ expect(deferredCompletion).toEqual([]);
+ expect(adapter.flush()).toEqual([
+ expect.objectContaining({
+ data: {
+ content: 'Todo list update interrupted.',
+ isError: true,
+ pluginState: { todos: expect.objectContaining({ items: [] }) },
+ toolCallId: 'todo-interrupted',
+ },
+ type: 'tool_result',
+ }),
+ expect.objectContaining({
+ data: { isSuccess: false, toolCallId: 'todo-interrupted' },
+ type: 'tool_end',
+ }),
+ ]);
+ expect(adapter.flush()).toEqual([]);
+ });
+
+ it('ignores todo item.updated events that have no active started tool', () => {
+ const adapter = new CodexAdapter();
+
+ expect(
+ adapter.adapt({
+ item: {
+ id: 'missing-start',
+ items: [{ completed: false, text: 'Not registered' }],
+ type: 'todo_list',
+ },
+ type: 'item.updated',
+ }),
+ ).toEqual([]);
+ });
+
+ it('keeps tool-state sequence monotonic if a tool call id is reused in one operation', () => {
+ const adapter = new CodexAdapter();
+ const item = {
+ id: 'reused-todo',
+ items: [{ completed: false, text: 'Implement' }],
+ type: 'todo_list',
+ };
+
+ const first = adapter.adapt({ item, type: 'item.started' });
+ adapter.adapt({ item: { ...item, status: 'completed' }, type: 'item.completed' });
+ const second = adapter.adapt({ item, type: 'item.started' });
+
+ expect(first.find((event) => event.data?.chunkType === 'tool_state')?.data.snapshotSeq).toBe(1);
+ expect(second.find((event) => event.data?.chunkType === 'tool_state')?.data.snapshotSeq).toBe(
+ 2,
+ );
});
it('maps file_change items into readable tool results', () => {
@@ -938,11 +1111,11 @@ describe('CodexAdapter', () => {
data: {
content: 'Todo list update failed.',
isError: true,
+ pluginState: { todos: { items: [] } },
toolCallId: 'todo_failed',
},
type: 'tool_result',
});
- expect(failedTodo[0].data).not.toHaveProperty('pluginState');
expect(failedTodo[1]).toMatchObject({
data: { isSuccess: false, toolCallId: 'todo_failed' },
type: 'tool_end',
diff --git a/packages/heterogeneous-agents/src/adapters/codex.ts b/packages/heterogeneous-agents/src/adapters/codex.ts
index e3b9454b049..508258e6849 100644
--- a/packages/heterogeneous-agents/src/adapters/codex.ts
+++ b/packages/heterogeneous-agents/src/adapters/codex.ts
@@ -7,6 +7,7 @@ import type {
StreamStartData,
ToolCallPayload,
ToolResultData,
+ ToolStateChunkData,
UsageData,
} from '../types';
import { toCodexUsageData, toTurnUsageFromCumulative } from '../utils/codexUsage';
@@ -47,6 +48,11 @@ interface CodexTodoListEntry {
text?: string;
}
+interface TodoListPluginItem {
+ status: 'completed' | 'processing' | 'todo';
+ text: string;
+}
+
interface CodexTodoListItem extends CodexBaseItem {
items?: CodexTodoListEntry[];
}
@@ -136,6 +142,13 @@ const normalizeTodoListItems = (item: CodexTodoListItem) =>
}))
.filter((todo) => todo.text.length > 0);
+const createTodoListPluginState = (items: TodoListPluginItem[]) => ({
+ todos: {
+ items,
+ updatedAt: new Date().toISOString(),
+ },
+});
+
/**
* Codex's `todo_list` only exposes a boolean completed flag. To light up the
* shared todo progress UI, treat the first incomplete item as the active one
@@ -143,24 +156,18 @@ const normalizeTodoListItems = (item: CodexTodoListItem) =>
*/
const synthesizeTodoListPluginState = (item: CodexTodoListItem) => {
const todos = normalizeTodoListItems(item);
- if (todos.length === 0) return;
let assignedProcessing = false;
- const items = todos.map((todo) => {
- if (todo.completed) return { status: 'completed', text: todo.text } as const;
+ const items = todos.map<TodoListPluginItem>((todo) => {
+ if (todo.completed) return { status: 'completed', text: todo.text };
if (!assignedProcessing) {
assignedProcessing = true;
- return { status: 'processing', text: todo.text } as const;
+ return { status: 'processing', text: todo.text };
}
- return { status: 'todo', text: todo.text } as const;
+ return { status: 'todo', text: todo.text };
});
- return {
- todos: {
- items,
- updatedAt: new Date().toISOString(),
- },
- };
+ return createTodoListPluginState(items);
};
const synthesizeFileChangePluginState = (item: CodexFileChangeItem) => {
@@ -513,18 +520,19 @@ const getToolResultData = (item: CodexToolItem): ToolResultData => {
};
}
- const pluginState =
- isSuccess && isTodoListItem(item)
+ const pluginState = isTodoListItem(item)
+ ? isSuccess
? synthesizeTodoListPluginState(item)
- : isSuccess && isFileChangeItem(item)
- ? synthesizeFileChangePluginState(item)
- : isMcpToolCallItem(item)
- ? synthesizeMcpToolPluginState(item)
- : isCollabToolCallItem(item)
- ? synthesizeCollabToolPluginState(item)
- : isWebSearchItem(item)
- ? synthesizeWebSearchPluginState(item)
- : undefined;
+ : createTodoListPluginState([])
+ : isSuccess && isFileChangeItem(item)
+ ? synthesizeFileChangePluginState(item)
+ : isMcpToolCallItem(item)
+ ? synthesizeMcpToolPluginState(item)
+ : isCollabToolCallItem(item)
+ ? synthesizeCollabToolPluginState(item)
+ : isWebSearchItem(item)
+ ? synthesizeWebSearchPluginState(item)
+ : undefined;
return {
content: output,
@@ -791,11 +799,15 @@ export class CodexAdapter implements AgentEventAdapter {
private hasTextInCurrentStep = false;
private hasToolActivitySinceAgentMessage = false;
+ private deferredTodoCompletions = new Map<string, CodexTodoListItem>();
+ private pendingTodoToolCalls = new Set<string>();
private pendingToolCalls = new Set<string>();
private pendingToolCallStepIndex = new Map<string, number>();
private pendingTurnStartBoundary = false;
private stepToolCalls: ToolCallPayload[] = [];
private stepToolCallIds = new Set<string>();
+ /** Monotonic within this adapter operation, independently per tool call. */
+ private toolStateSnapshotSeqByCallId = new Map<string, number>();
private started = false;
private stepIndex = 0;
private terminalEndEmitted = false;
@@ -830,6 +842,9 @@ export class CodexAdapter implements AgentEventAdapter {
case 'item.started': {
return this.handleItemStarted(raw.item);
}
+ case 'item.updated': {
+ return this.handleItemUpdated(raw.item);
+ }
case 'item.completed': {
return this.handleItemCompleted(raw.item);
}
@@ -855,7 +870,7 @@ export class CodexAdapter implements AgentEventAdapter {
const cumulativeUsage = toCodexUsageData(raw.usage);
const usage = toTurnUsageFromCumulative(cumulativeUsage, this.lastCumulativeUsage);
if (cumulativeUsage) this.lastCumulativeUsage = cumulativeUsage;
- const events = this.drainPendingToolEndEvents();
+ const events = this.drainPendingToolEndEvents('success');
if (!hadPendingEmptyTurn && (usage || model)) {
const data: StepCompleteData = {
@@ -900,9 +915,10 @@ export class CodexAdapter implements AgentEventAdapter {
stderr,
};
- const events: HeterogeneousAgentEvent[] = this.started
- ? [this.makeEvent('stream_end', {}), this.makeEvent('visible_output_end', {})]
- : [];
+ const events = this.drainPendingToolEndEvents();
+ if (this.started) {
+ events.push(this.makeEvent('stream_end', {}), this.makeEvent('visible_output_end', {}));
+ }
events.push(this.makeEvent('error', data));
return events;
@@ -951,7 +967,19 @@ export class CodexAdapter implements AgentEventAdapter {
this.pendingToolCalls.add(tool.id);
this.pendingToolCallStepIndex.set(tool.id, this.stepIndex);
- return [...this.consumePendingTurnStart(), ...this.emitToolChunk(tool)];
+ const events = [...this.consumePendingTurnStart(), ...this.emitToolChunk(tool)];
+ if (isTodoListItem(item)) {
+ this.pendingTodoToolCalls.add(tool.id);
+ events.push(this.createToolStateEvent(item));
+ }
+
+ return events;
+ }
+
+ private handleItemUpdated(item: any): HeterogeneousAgentEvent[] {
+ if (!item?.id || !isTodoListItem(item) || !this.pendingToolCalls.has(item.id)) return [];
+
+ return [this.createToolStateEvent(item)];
}
private handleItemCompleted(item: any): HeterogeneousAgentEvent[] {
@@ -994,6 +1022,18 @@ export class CodexAdapter implements AgentEventAdapter {
if (!item.id) return [];
+ // Codex emits the same status-less todo completion before both a successful
+ // turn completion and an interrupted process exit. Keep it pending until
+ // the turn outcome tells us whether to preserve or clear the Todo state.
+ if (
+ isTodoListItem(item) &&
+ item.status === undefined &&
+ this.pendingTodoToolCalls.has(item.id)
+ ) {
+ this.deferredTodoCompletions.set(item.id, item);
+ return this.consumePendingTurnStart();
+ }
+
const events: HeterogeneousAgentEvent[] = this.consumePendingTurnStart();
const pendingStepIndex = this.pendingToolCallStepIndex.get(item.id);
const belongsToCurrentStep =
@@ -1007,14 +1047,25 @@ export class CodexAdapter implements AgentEventAdapter {
this.pendingToolCalls.delete(item.id);
this.pendingToolCallStepIndex.delete(item.id);
+ this.pendingTodoToolCalls.delete(item.id);
+ this.deferredTodoCompletions.delete(item.id);
if (belongsToCurrentStep) this.hasToolActivitySinceAgentMessage = true;
- const resultData = getToolResultData(item as CodexToolItem);
- const isSuccess = isSuccessfulToolCompletion(item as CodexToolItem);
- events.push(this.makeEvent('tool_result', resultData));
+ events.push(...this.createToolCompletionEvents(item as CodexToolItem, toolPayload));
+
+ return events;
+ }
+
+ private createToolCompletionEvents(
+ item: CodexToolItem,
+ toolPayload = toToolPayload(item),
+ ): HeterogeneousAgentEvent[] {
+ const resultData = getToolResultData(item);
+ const isSuccess = isSuccessfulToolCompletion(item);
// Align tool_end with the server/gateway shape β€” carry the `{ toolCalling }`
// payload + a `BuiltinToolResult`-shaped `result` so renderer `onAfterCall`
// hooks resolve the executor and observe the result, identically to server runs.
- events.push(
+ return [
+ this.makeEvent('tool_result', resultData),
this.makeEvent('tool_end', {
isSuccess,
payload: { toolCalling: toolPayload },
@@ -1025,24 +1076,61 @@ export class CodexAdapter implements AgentEventAdapter {
},
toolCallId: item.id,
}),
- );
-
- return events;
+ ];
}
- private drainPendingToolEndEvents(): HeterogeneousAgentEvent[] {
- const events = [...this.pendingToolCalls].map((toolCallId) =>
- this.makeEvent('tool_end', {
+ private drainPendingToolEndEvents(
+ terminalReason: 'interrupted' | 'success' = 'interrupted',
+ ): HeterogeneousAgentEvent[] {
+ const events = [...this.pendingToolCalls].flatMap((toolCallId) => {
+ const deferredTodoCompletion = this.deferredTodoCompletions.get(toolCallId);
+ if (terminalReason === 'success' && deferredTodoCompletion) {
+ return this.createToolCompletionEvents(deferredTodoCompletion);
+ }
+
+ const toolEnd = this.makeEvent('tool_end', {
isSuccess: false,
toolCallId,
- }),
- );
-
+ });
+ if (!this.pendingTodoToolCalls.has(toolCallId)) return [toolEnd];
+
+ // A pending Todo has no provider item.completed payload to supersede its
+ // live processing snapshot. Emit an explicit terminal clear before end
+ // so cancellation, process interruption, and truncated streams cannot
+ // leave TodoProgress stuck forever.
+ return [
+ this.makeEvent('tool_result', {
+ content: 'Todo list update interrupted.',
+ isError: true,
+ pluginState: createTodoListPluginState([]),
+ toolCallId,
+ } satisfies ToolResultData),
+ toolEnd,
+ ];
+ });
+
+ this.pendingTodoToolCalls.clear();
this.pendingToolCalls.clear();
this.pendingToolCallStepIndex.clear();
+ this.deferredTodoCompletions.clear();
return events;
}
+ private createToolStateEvent(item: CodexTodoListItem): HeterogeneousAgentEvent {
+ const pluginState = synthesizeTodoListPluginState(item);
+
+ const snapshotSeq = (this.toolStateSnapshotSeqByCallId.get(item.id) ?? 0) + 1;
+ this.toolStateSnapshotSeqByCallId.set(item.id, snapshotSeq);
+
+ return this.makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState,
+ snapshotMode: 'replace',
+ snapshotSeq,
+ toolCallId: item.id,
+ } satisfies ToolStateChunkData);
+ }
+
private emitToolChunk(tool: ToolCallPayload): HeterogeneousAgentEvent[] {
if (!this.stepToolCallIds.has(tool.id)) {
this.stepToolCallIds.add(tool.id);
diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.ts
index e679975a47a..e0f0c791be4 100644
--- a/packages/heterogeneous-agents/src/index.ts
+++ b/packages/heterogeneous-agents/src/index.ts
@@ -21,6 +21,7 @@ export type {
MainRecordUsageIntent,
MainResolveToolResultIntent,
MainStreamContentIntent,
+ MainUpdateToolStateIntent,
PersistAssistantIntent,
SetErrorIntent,
} from './mainAgentCoordinator';
@@ -41,6 +42,7 @@ export type {
SubagentReduceCtx,
SubagentRunSnapshot,
SubagentRunsState,
+ UpdateToolStateIntent,
} from './subagentCoordinator';
export {
createSubagentRunsState,
@@ -63,4 +65,5 @@ export type {
ToolCallPayload,
ToolEndData,
ToolResultData,
+ ToolStateChunkData,
} from './types';
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/index.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/index.ts
index 072e8dcaee5..96e773af900 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/index.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/index.ts
@@ -9,6 +9,7 @@ export type {
MainRecordUsageIntent,
MainResolveToolResultIntent,
MainStreamContentIntent,
+ MainUpdateToolStateIntent,
PersistAssistantIntent,
SetErrorIntent,
} from './types';
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
index 1f15c663c9a..8aa4513fdf6 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
@@ -55,6 +55,21 @@ const toolsEvent = (tools: any[]) => ({
type: 'stream_chunk',
});
+const toolStateEvent = (
+ toolCallId: string,
+ snapshotSeq: number,
+ pluginState: Record<string, unknown>,
+) => ({
+ data: {
+ chunkType: 'tool_state',
+ pluginState,
+ snapshotMode: 'replace',
+ snapshotSeq,
+ toolCallId,
+ },
+ type: 'stream_chunk',
+});
+
const toolResultEvent = (toolCallId: string, content: string, extra: Record<string, any> = {}) => ({
data: { content, toolCallId, ...extra },
type: 'tool_result',
@@ -108,6 +123,40 @@ describe('main agent reducer', () => {
expect(state.accContent).toBe('Hello world');
});
+ it('emits a replace-only tool-state intent without mutating reducer state', () => {
+ const pluginState = { todos: { items: [{ status: 'processing', text: 'Implement' }] } };
+ const initial = createMainAgentRunState('A0');
+ const result = reduceMainAgent(initial, toolStateEvent('todo-1', 2, pluginState), makeCtx());
+
+ expect(result.intents).toEqual([
+ {
+ kind: 'updateToolState',
+ pluginState,
+ snapshotSeq: 2,
+ toolCallId: 'todo-1',
+ },
+ ]);
+ expect(result.state).toBe(initial);
+ });
+
+ it('ignores malformed tool-state chunks', () => {
+ const { steps } = run([
+ toolStateEvent('todo-1', 0, { todos: {} }),
+ {
+ data: {
+ chunkType: 'tool_state',
+ pluginState: [],
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ toolCallId: 'todo-1',
+ },
+ type: 'stream_chunk',
+ },
+ ]);
+
+ expect(steps).toEqual([[], []]);
+ });
+
it('replace-mode text snapshots replace, and stale sequences are dropped', () => {
const { steps, state } = run([
textEvent('v2', { snapshotMode: 'replace', snapshotSeq: 2 }),
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
index 94c763a6258..37010597900 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
@@ -319,6 +319,29 @@ const reduceStreamChunk = (
if (data?.chunkType === 'reasoning' && typeof data.reasoning === 'string') {
return reduceReasoningChunk(state, data);
}
+ if (
+ data?.chunkType === 'tool_state' &&
+ data.snapshotMode === 'replace' &&
+ typeof data.toolCallId === 'string' &&
+ data.toolCallId.length > 0 &&
+ Number.isInteger(data.snapshotSeq) &&
+ data.snapshotSeq > 0 &&
+ typeof data.pluginState === 'object' &&
+ data.pluginState !== null &&
+ !Array.isArray(data.pluginState)
+ ) {
+ return {
+ intents: [
+ {
+ kind: 'updateToolState',
+ pluginState: data.pluginState,
+ snapshotSeq: data.snapshotSeq,
+ toolCallId: data.toolCallId,
+ },
+ ],
+ state,
+ };
+ }
if (data?.chunkType === 'tools_calling') {
const tools = (data.toolsCalling as ToolCallPayload[] | undefined) ?? [];
if (tools.length === 0) return { intents: [], state };
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
index 9928939564a..57c4216fd65 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
@@ -171,6 +171,7 @@ export type MainAgentIntent =
| PersistAssistantIntent
| MainStreamContentIntent
| MainPersistToolBatchIntent
+ | MainUpdateToolStateIntent
| MainResolveToolResultIntent
| MainRecordUsageIntent
| SetErrorIntent;
@@ -234,6 +235,14 @@ export interface MainPersistToolBatchIntent {
tools: PersistToolBatchEntry[];
}
+/** Replace the live/durable plugin state for a still-running main-agent tool. */
+export interface MainUpdateToolStateIntent {
+ kind: 'updateToolState';
+ pluginState: Record<string, unknown>;
+ snapshotSeq: number;
+ toolCallId: string;
+}
+
/**
* Resolve a main-agent tool_result. The interpreter looks up the tool-message
* id from its `toolCallId β†’ messageId` map (the run-global one, DB-backed on
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/index.ts b/packages/heterogeneous-agents/src/subagentCoordinator/index.ts
index 90a064dca2a..1f1d9489133 100644
--- a/packages/heterogeneous-agents/src/subagentCoordinator/index.ts
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/index.ts
@@ -16,5 +16,6 @@ export type {
SubagentRunSnapshot,
SubagentRunsState,
SubagentTurnToolState,
+ UpdateToolStateIntent,
} from './types';
export { createSubagentRunsState, rehydrateSubagentRunsState } from './types';
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts
index 6f48cd0c33d..e973964a8d2 100644
--- a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts
@@ -47,6 +47,23 @@ const toolsEvent = (parentToolCallId: string, subagentMessageId: string, tools:
type: 'stream_chunk',
});
+const toolStateEvent = (
+ parentToolCallId: string,
+ subagentMessageId: string,
+ toolCallId: string,
+ snapshotSeq: number,
+) => ({
+ data: {
+ chunkType: 'tool_state',
+ pluginState: { progress: snapshotSeq },
+ snapshotMode: 'replace',
+ snapshotSeq,
+ subagent: sub(parentToolCallId, subagentMessageId),
+ toolCallId,
+ },
+ type: 'stream_chunk',
+});
+
const tool = (id: string) => ({
apiName: 'Bash',
arguments: '{}',
@@ -221,6 +238,23 @@ describe('subagent reducer', () => {
]);
});
+ it('routes tool-state snapshots to the owning subagent thread', () => {
+ const { steps } = run([
+ toolsEvent('task-1', 'm1', [tool('tc-1')]),
+ toolStateEvent('task-1', 'm1', 'tc-1', 3),
+ ]);
+
+ expect(steps[1]).toEqual([
+ {
+ kind: 'updateToolState',
+ pluginState: { progress: 3 },
+ snapshotSeq: 3,
+ threadId: 'thd_1',
+ toolCallId: 'tc-1',
+ },
+ ]);
+ });
+
it('finalizes on the parent tool_result: flush + terminal assistant + finalizeThread + deletes run', () => {
const { steps, state } = run([
textEvent('task-1', 'm1', 'trailing summary'),
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts
index c1b2b65ad51..bf0383d30e8 100644
--- a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts
@@ -387,6 +387,33 @@ export const reduce = (
if (data.chunkType === 'reasoning' && typeof data.reasoning === 'string' && data.reasoning) {
return reduceTextChunk(state, subCtx, 'reasoning', data.reasoning, ctx);
}
+ if (
+ data.chunkType === 'tool_state' &&
+ data.snapshotMode === 'replace' &&
+ typeof data.toolCallId === 'string' &&
+ data.toolCallId.length > 0 &&
+ Number.isInteger(data.snapshotSeq) &&
+ data.snapshotSeq > 0 &&
+ typeof data.pluginState === 'object' &&
+ data.pluginState !== null &&
+ !Array.isArray(data.pluginState)
+ ) {
+ const owner = findRunByInnerToolCallId(state, data.toolCallId);
+ if (!owner) return { intents: [], state };
+
+ return {
+ intents: [
+ {
+ kind: 'updateToolState',
+ pluginState: data.pluginState,
+ snapshotSeq: data.snapshotSeq,
+ threadId: owner.run.threadId,
+ toolCallId: data.toolCallId,
+ },
+ ],
+ state,
+ };
+ }
if (data.chunkType === 'tools_calling') {
const tools = (data.toolsCalling as ToolCallPayload[] | undefined) ?? [];
if (tools.length === 0) return { intents: [], state };
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/types.ts b/packages/heterogeneous-agents/src/subagentCoordinator/types.ts
index 51984998d16..1225e9aa564 100644
--- a/packages/heterogeneous-agents/src/subagentCoordinator/types.ts
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/types.ts
@@ -196,6 +196,7 @@ export type SubagentIntent =
| StreamContentIntent
| PersistContentIntent
| PersistToolBatchIntent
+ | UpdateToolStateIntent
| ResolveToolResultIntent
| RecordUsageIntent
| FinalizeThreadIntent;
@@ -289,6 +290,15 @@ export interface PersistToolBatchIntent {
tools: PersistToolBatchEntry[];
}
+/** Replace the live/durable plugin state for a still-running inner tool. */
+export interface UpdateToolStateIntent {
+ kind: 'updateToolState';
+ pluginState: Record<string, unknown>;
+ snapshotSeq: number;
+ threadId: string;
+ toolCallId: string;
+}
+
/**
* Resolve an inner subagent tool_result. The interpreter looks up the
* tool-message id from its own `toolCallId β†’ messageId` map (populated by
diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.ts
index 345c766c426..c57b1351136 100644
--- a/packages/heterogeneous-agents/src/types.ts
+++ b/packages/heterogeneous-agents/src/types.ts
@@ -43,7 +43,7 @@ export type HeterogeneousEventType =
| 'agent_runtime_end'
| 'error';
-export type StreamChunkType = 'text' | 'reasoning' | 'tools_calling';
+export type StreamChunkType = 'text' | 'reasoning' | 'tool_state' | 'tools_calling';
export interface HeterogeneousAgentEvent {
data: any;
@@ -188,16 +188,36 @@ export interface SubagentEventContext {
export interface StreamChunkData {
chunkType: StreamChunkType;
content?: string;
+ pluginState?: Record<string, unknown>;
reasoning?: string;
+ snapshotMode?: 'replace';
+ snapshotSeq?: number;
/**
* Subagent context for the entire chunk β€” peer to `toolsCalling`,
* `content`, and `reasoning`. Stream-state info (parent spawn id,
* subagent turn id) belongs on the event, not inside the payloads.
*/
subagent?: SubagentEventContext;
+ toolCallId?: string;
toolsCalling?: ToolCallPayload[];
}
+/**
+ * Non-terminal, replace-only snapshot for a running tool message.
+ *
+ * `snapshotSeq` is monotonic within `(operationId, toolCallId)`; operationId
+ * lives on the enclosing wire event. The final `tool_result` remains the
+ * authoritative terminal snapshot and does not consume this sequence.
+ */
+export interface ToolStateChunkData {
+ chunkType: 'tool_state';
+ pluginState: Record<string, unknown>;
+ snapshotMode: 'replace';
+ snapshotSeq: number;
+ subagent?: SubagentEventContext;
+ toolCallId: string;
+}
+
/** Data shape for tool_end events */
export interface ToolEndData {
isSuccess: boolean;
diff --git a/packages/types/src/message/common/metadata.test.ts b/packages/types/src/message/common/metadata.test.ts
index fdb06b9e5d0..bc32d18da71 100644
--- a/packages/types/src/message/common/metadata.test.ts
+++ b/packages/types/src/message/common/metadata.test.ts
@@ -22,4 +22,16 @@ describe('MessageMetadataSchema', () => {
expect(parsed).toEqual({ heteroMessageId: 'cc-1', heteroSessionId: 'sess-A' });
});
+
+ it('preserves the durable heterogeneous tool-state watermark', () => {
+ const parsed = MessageMetadataSchema.parse({
+ heterogeneousToolStateOperationId: 'op-1',
+ heterogeneousToolStateSeq: 4,
+ });
+
+ expect(parsed).toEqual({
+ heterogeneousToolStateOperationId: 'op-1',
+ heterogeneousToolStateSeq: 4,
+ });
+ });
});
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index d5ff08e9469..f4628e000e1 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -193,6 +193,10 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSche
// CreateMessageParamsSchema (the renderer executor's `messageService` path).
heteroMessageId: z.string().optional(),
heteroSessionId: z.string().optional(),
+ // Durable watermark for replace-only heterogeneous tool-state snapshots.
+ // The pair is scoped by operation so a later run may restart seq at 1.
+ heterogeneousToolStateOperationId: z.string().optional(),
+ heterogeneousToolStateSeq: z.number().int().positive().optional(),
inspectExpanded: z.boolean().optional(),
isMultimodal: z.boolean().optional(),
isSupervisor: z.boolean().optional(),
@@ -281,6 +285,10 @@ export interface MessageMetadata {
/** @deprecated use `metadata.performance` instead */
duration?: number;
finishType?: string;
+ /** Operation owning the durable heterogeneous tool-state watermark. */
+ heterogeneousToolStateOperationId?: string;
+ /** Last persisted replace-snapshot sequence for this tool message. */
+ heterogeneousToolStateSeq?: number;
/**
* The native id of this message inside the hetero agent (Claude Code /
* Codex) that produced it β€” forensic provenance tying a row back to its
diff --git a/packages/types/src/message/common/tools.ts b/packages/types/src/message/common/tools.ts
index 0fb61e2c85b..c0a76ce07c0 100644
--- a/packages/types/src/message/common/tools.ts
+++ b/packages/types/src/message/common/tools.ts
@@ -62,6 +62,15 @@ export interface ChatToolResult {
state?: any;
}
+/**
+ * Internal conditional-write descriptor for a heterogeneous tool-state
+ * snapshot. It is not part of the renderer-facing pluginState payload.
+ */
+export interface HeterogeneousToolStateSnapshot {
+ operationId: string;
+ snapshotSeq: number;
+}
+
/**
* Chat tool payload with merged execution result
*/
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 5ea57194a37..4c8f53bfca0 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -5,6 +5,7 @@ import {
type ChatTTS,
type CreateMessageParams,
type CreateMessageResult,
+ type HeterogeneousToolStateSnapshot,
type MessageMetadata,
type MessagePluginItem,
type ModelRankItem,
@@ -60,6 +61,7 @@ export type MessageBatchOperation =
type: 'updateToolMessage';
value: {
content?: string;
+ heterogeneousToolState?: HeterogeneousToolStateSnapshot;
metadata?: Record<string, any>;
pluginError?: any;
pluginState?: Record<string, any>;
@@ -289,6 +291,7 @@ export class MessageService {
id: string,
value: {
content?: string;
+ heterogeneousToolState?: HeterogeneousToolStateSnapshot;
metadata?: Record<string, any>;
pluginError?: any;
pluginState?: Record<string, any>;
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 b488a9e33cd..8e5648273e0 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -219,6 +219,7 @@ function createMockStore(overrides: Record<string, any> = {}) {
const store = {
associateMessageWithOperation: vi.fn(),
completeOperation: vi.fn(),
+ dbMessagesMap: {},
drainQueuedMessages: vi.fn(() => []),
internal_dispatchMessage: vi.fn(),
internal_toggleToolCallingStreaming: vi.fn(),
@@ -462,6 +463,23 @@ const codexCommandCompleted = (id: string, command: string, aggregatedOutput: st
type: 'item.completed',
});
+const codexTodo = (
+ lifecycle: 'item.completed' | 'item.started' | 'item.updated',
+ completed: number,
+) => ({
+ item: {
+ id: 'todo-1',
+ items: [
+ { completed: completed >= 1, text: 'Inspect' },
+ { completed: completed >= 2, text: 'Implement' },
+ { completed: completed >= 3, text: 'Verify' },
+ ],
+ status: lifecycle === 'item.completed' ? 'completed' : 'in_progress',
+ type: 'todo_list',
+ },
+ type: lifecycle,
+});
+
const codexTurnCompleted = (usage?: {
cached_input_tokens?: number;
input_tokens?: number;
@@ -565,7 +583,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
/**
- * Runs the executor in background, then feeds CC events and completes.
+ * Runs the executor in background, then feeds raw events or inline emitters and completes.
* Returns a promise that resolves when the executor finishes.
*/
async function runWithEvents(
@@ -591,9 +609,10 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
// Wait for startSession + subscribeBroadcasts to complete
await flush();
- // Feed CC events
+ // Feed raw adapter inputs or invoke an inline emitter for already-adapted events.
for (const event of ccEvents) {
- ipc.emitRawLine('ipc-sess-1', event);
+ if (typeof event === 'function') event();
+ else ipc.emitRawLine('ipc-sess-1', event);
}
// Signal completion
@@ -2083,6 +2102,190 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
describe('Codex multi-turn persistence', () => {
+ it('optimistically replaces TodoProgress state while Codex is still running', async () => {
+ const { store } = await runWithEvents(
+ [
+ codexTurnStarted(),
+ codexTodo('item.started', 0),
+ codexTodo('item.updated', 1),
+ codexTodo('item.completed', 3),
+ codexTurnCompleted(),
+ ],
+ {
+ params: {
+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },
+ },
+ },
+ );
+
+ const stateWrites = mockUpdateToolMessage.mock.calls
+ .map(([, value]) => value)
+ .filter((value) => value.heterogeneousToolState);
+ expect(stateWrites).toEqual([
+ expect.objectContaining({
+ heterogeneousToolState: { operationId: 'op-1', snapshotSeq: 1 },
+ }),
+ expect.objectContaining({
+ heterogeneousToolState: { operationId: 'op-1', snapshotSeq: 2 },
+ }),
+ ]);
+
+ const optimisticStates = store.internal_dispatchMessage.mock.calls
+ .map(([payload]: any[]) => payload)
+ .filter((payload: any) => payload.type === 'replaceMessagePluginState');
+ expect(optimisticStates).toHaveLength(2);
+ expect(optimisticStates.at(-1)).toMatchObject({
+ metadata: {
+ heterogeneousToolStateOperationId: 'op-1',
+ heterogeneousToolStateSeq: 2,
+ },
+ value: {
+ todos: {
+ items: [
+ { status: 'completed', text: 'Inspect' },
+ { status: 'processing', text: 'Implement' },
+ { status: 'todo', text: 'Verify' },
+ ],
+ },
+ },
+ });
+
+ const finalWrite = mockUpdateToolMessage.mock.calls
+ .map(([, value]) => value)
+ .find((value) => value.content === 'Todo list updated (3/3 completed).');
+ expect(finalWrite).toMatchObject({
+ pluginState: {
+ todos: {
+ items: [
+ { status: 'completed', text: 'Inspect' },
+ { status: 'completed', text: 'Implement' },
+ { status: 'completed', text: 'Verify' },
+ ],
+ },
+ },
+ });
+ expect(finalWrite).not.toHaveProperty('heterogeneousToolState');
+ });
+
+ it('does not replay failed intermediate tool state after the final result succeeds', async () => {
+ mockUpdateToolMessage.mockImplementation(async (_id, value) => ({
+ success: !value.heterogeneousToolState,
+ }));
+
+ await runWithEvents(
+ [
+ codexTurnStarted(),
+ codexTodo('item.started', 0),
+ codexTodo('item.updated', 1),
+ codexTodo('item.completed', 3),
+ codexTurnCompleted(),
+ ],
+ {
+ params: {
+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },
+ },
+ },
+ );
+
+ const writes = mockUpdateToolMessage.mock.calls.map(([, value]) => value);
+ expect(writes.filter((value) => value.heterogeneousToolState)).toHaveLength(2);
+ expect(
+ writes.filter((value) => value.content === 'Todo list updated (3/3 completed).'),
+ ).toHaveLength(1);
+ expect(writes).toHaveLength(3);
+ });
+
+ it('drops main tool-state snapshots that arrive after the terminal result', async () => {
+ const latePluginState = {
+ todos: { items: [{ status: 'processing', text: 'Stale progress' }] },
+ };
+ const { store } = await runWithEvents(
+ [
+ codexTurnStarted(),
+ codexTodo('item.started', 0),
+ codexTodo('item.completed', 3),
+ () =>
+ ipc.emitStreamEvent('ipc-sess-1', {
+ data: {
+ chunkType: 'tool_state',
+ pluginState: latePluginState,
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ toolCallId: 'todo-1',
+ },
+ type: 'stream_chunk',
+ }),
+ codexTurnCompleted(),
+ ],
+ {
+ params: {
+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },
+ },
+ },
+ );
+
+ const writes = mockUpdateToolMessage.mock.calls.map(([, value]) => value);
+ expect(
+ writes.some(
+ (value) =>
+ value.heterogeneousToolState?.snapshotSeq === 2 &&
+ value.pluginState === latePluginState,
+ ),
+ ).toBe(false);
+ expect(writes.some((value) => value.content === 'Todo list updated (3/3 completed).')).toBe(
+ true,
+ );
+ expect(
+ store.internal_dispatchMessage.mock.calls.some(
+ ([payload]: any[]) =>
+ payload.type === 'replaceMessagePluginState' && payload.value === latePluginState,
+ ),
+ ).toBe(false);
+ });
+
+ it('accepts main tool state again after a new tool lifecycle starts', async () => {
+ const nextPluginState = {
+ todos: { items: [{ status: 'processing', text: 'New lifecycle' }] },
+ };
+ await runWithEvents(
+ [
+ codexTurnStarted(),
+ codexTodo('item.started', 0),
+ codexTodo('item.completed', 3),
+ () =>
+ ipc.emitStreamEvent('ipc-sess-1', {
+ data: { toolCallId: 'todo-1' },
+ type: 'tool_start',
+ }),
+ () =>
+ ipc.emitStreamEvent('ipc-sess-1', {
+ data: {
+ chunkType: 'tool_state',
+ pluginState: nextPluginState,
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ toolCallId: 'todo-1',
+ },
+ type: 'stream_chunk',
+ }),
+ codexTurnCompleted(),
+ ],
+ {
+ params: {
+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },
+ },
+ },
+ );
+
+ expect(
+ mockUpdateToolMessage.mock.calls.some(
+ ([, value]) =>
+ value.heterogeneousToolState?.snapshotSeq === 2 &&
+ value.pluginState === nextPluginState,
+ ),
+ ).toBe(true);
+ });
+
it('should persist Codex host model metadata onto the current assistant message', async () => {
await runWithEvents(
[
@@ -3382,6 +3585,50 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
// ────────────────────────────────────────────────────
describe('CC subagent thread-container', () => {
+ it('drops subagent tool-state snapshots that arrive after the terminal result', async () => {
+ const latePluginState = { status: 'processing' };
+ const { store } = await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'Inspect files',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentToolUse('msg_sub', 'toolu_task', 'toolu_child', 'Read'),
+ ccSubagentToolResult('toolu_child', 'toolu_task', 'file content'),
+ () =>
+ ipc.emitStreamEvent('ipc-sess-1', {
+ data: {
+ chunkType: 'tool_state',
+ pluginState: latePluginState,
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ subagent: { parentToolCallId: 'toolu_task' },
+ toolCallId: 'toolu_child',
+ },
+ type: 'stream_chunk',
+ }),
+ ccSubagentSpawnResult('toolu_task', 'done'),
+ ccResult(),
+ ]);
+
+ expect(
+ mockUpdateToolMessage.mock.calls.some(
+ ([, value]) =>
+ value.heterogeneousToolState?.snapshotSeq === 1 &&
+ value.pluginState === latePluginState,
+ ),
+ ).toBe(false);
+ expect(
+ mockUpdateToolMessage.mock.calls.some(([, value]) => value.content === 'file content'),
+ ).toBe(true);
+ expect(
+ store.internal_dispatchMessage.mock.calls.some(
+ ([payload]: any[]) =>
+ payload.type === 'replaceMessagePluginState' && payload.value === latePluginState,
+ ),
+ ).toBe(false);
+ });
+
it('does not recreate a finalized subagent Thread after a client executor restart', async () => {
mockGetThreads.mockResolvedValue([
{
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 317b45cb798..4d4a3654f44 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
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { messageService } from '@/services/message';
import * as agentSignalBridge from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';
import type { ChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { createGatewayEventHandler } from './gatewayEventHandler';
@@ -263,6 +264,389 @@ describe('createGatewayEventHandler', () => {
expect(store.replaceMessages).not.toHaveBeenCalled();
});
+ it('bootstraps a missing tool once and reapplies the latest snapshot after a stale refetch', async () => {
+ const key = messageMapKey(context);
+ let resolveFetch: ((messages: UIChatMessage[]) => void) | undefined;
+ const getMessages = vi.spyOn(messageService, 'getMessages').mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveFetch = resolve as (messages: UIChatMessage[]) => void;
+ }),
+ );
+ const store = createStore();
+ (store.replaceMessages as ReturnType<typeof vi.fn>).mockImplementation(
+ (messages: UIChatMessage[]) => {
+ store.dbMessagesMap[key] = messages;
+ },
+ );
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'seed-msg',
+ context,
+ operationId: 'op-1',
+ });
+
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState: { version: 3 },
+ snapshotMode: 'replace',
+ snapshotSeq: 3,
+ toolCallId: 'todo-1',
+ }),
+ );
+ await flush();
+ expect(getMessages).toHaveBeenCalledTimes(1);
+
+ // Arrives while the bootstrap read is still pending. It must update the
+ // synchronous latest cache rather than wait behind that read.
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState: { version: 4 },
+ snapshotMode: 'replace',
+ snapshotSeq: 4,
+ toolCallId: 'todo-1',
+ }),
+ );
+ resolveFetch?.([
+ {
+ content: '',
+ id: 'tool-msg-1',
+ metadata: {
+ heterogeneousToolStateOperationId: 'op-1',
+ heterogeneousToolStateSeq: 3,
+ },
+ parentId: 'seed-msg',
+ pluginState: { version: 3 },
+ role: 'tool',
+ tool_call_id: 'todo-1',
+ } as UIChatMessage,
+ ]);
+ await flush();
+
+ expect(getMessages).toHaveBeenCalledTimes(1);
+ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(
+ {
+ id: 'tool-msg-1',
+ metadata: {
+ heterogeneousToolStateOperationId: 'op-1',
+ heterogeneousToolStateSeq: 4,
+ },
+ type: 'replaceMessagePluginState',
+ value: { version: 4 },
+ },
+ { operationId: 'op-1' },
+ );
+ });
+
+ it('bootstraps the current tool instead of applying a reused call id to an older run', async () => {
+ const key = messageMapKey(context);
+ const getMessages = vi.spyOn(messageService, 'getMessages').mockResolvedValue([
+ {
+ content: '',
+ id: 'tool-current',
+ parentId: 'seed-msg',
+ pluginState: { version: 1 },
+ role: 'tool',
+ tool_call_id: 'todo-1',
+ } as UIChatMessage,
+ ]);
+ const store = createStore({
+ [key]: [
+ {
+ content: 'Previous run result',
+ id: 'tool-previous',
+ parentId: 'assistant-previous',
+ pluginState: { version: 'previous' },
+ role: 'tool',
+ tool_call_id: 'todo-1',
+ } as UIChatMessage,
+ ],
+ });
+ (store.replaceMessages as ReturnType<typeof vi.fn>).mockImplementation(
+ (messages: UIChatMessage[]) => {
+ store.dbMessagesMap[key] = messages;
+ },
+ );
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'seed-msg',
+ context,
+ operationId: 'op-1',
+ });
+
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState: { version: 2 },
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ toolCallId: 'todo-1',
+ }),
+ );
+ await flush();
+
+ expect(getMessages).toHaveBeenCalledTimes(1);
+ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(
+ {
+ id: 'tool-current',
+ metadata: {
+ heterogeneousToolStateOperationId: 'op-1',
+ heterogeneousToolStateSeq: 2,
+ },
+ type: 'replaceMessagePluginState',
+ value: { version: 2 },
+ },
+ { operationId: 'op-1' },
+ );
+ });
+
+ it('drops a tool-state event at or below the message durable watermark', async () => {
+ const key = messageMapKey(context);
+ const getMessages = vi.spyOn(messageService, 'getMessages');
+ const store = createStore({
+ [key]: [
+ {
+ content: '',
+ id: 'tool-msg-1',
+ metadata: {
+ heterogeneousToolStateOperationId: 'op-1',
+ heterogeneousToolStateSeq: 5,
+ },
+ parentId: 'seed-msg',
+ pluginState: { version: 5 },
+ role: 'tool',
+ tool_call_id: 'todo-1',
+ } as UIChatMessage,
+ ],
+ });
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'seed-msg',
+ context,
+ operationId: 'op-1',
+ });
+
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState: { version: 4 },
+ snapshotMode: 'replace',
+ snapshotSeq: 4,
+ toolCallId: 'todo-1',
+ }),
+ );
+ await flush();
+
+ expect(store.internal_dispatchMessage).not.toHaveBeenCalled();
+ expect(getMessages).not.toHaveBeenCalled();
+ });
+
+ it('orders the terminal refresh after a pending bootstrap so the final tool state wins', async () => {
+ const key = messageMapKey(context);
+ const fetchResolvers: Array<(messages: UIChatMessage[]) => void> = [];
+ const getMessages = vi.spyOn(messageService, 'getMessages').mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ fetchResolvers.push(resolve as (messages: UIChatMessage[]) => void);
+ }),
+ );
+ const store = createStore();
+ (store.replaceMessages as ReturnType<typeof vi.fn>).mockImplementation(
+ (messages: UIChatMessage[]) => {
+ store.dbMessagesMap[key] = messages;
+ },
+ );
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'seed-msg',
+ context,
+ operationId: 'op-1',
+ });
+
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState: { version: 3 },
+ snapshotMode: 'replace',
+ snapshotSeq: 3,
+ toolCallId: 'todo-1',
+ }),
+ );
+ await flush();
+ expect(getMessages).toHaveBeenCalledTimes(1);
+
+ handler(
+ makeEvent('tool_end', {
+ isSuccess: true,
+ toolCallId: 'todo-1',
+ }),
+ );
+
+ await flush();
+ // The terminal refresh is queued behind the bootstrap instead of racing it.
+ expect(getMessages).toHaveBeenCalledTimes(1);
+
+ fetchResolvers[0]?.([
+ {
+ content: '',
+ id: 'tool-msg-1',
+ pluginState: { version: 3 },
+ role: 'tool',
+ tool_call_id: 'todo-1',
+ } as UIChatMessage,
+ ]);
+ await flush();
+ expect(getMessages).toHaveBeenCalledTimes(2);
+
+ fetchResolvers[1]?.([
+ {
+ content: 'Todo list updated.',
+ id: 'tool-msg-1',
+ pluginState: { version: 'final' },
+ role: 'tool',
+ tool_call_id: 'todo-1',
+ } as UIChatMessage,
+ ]);
+ await flush();
+
+ expect(store.dbMessagesMap[key]).toEqual([
+ expect.objectContaining({
+ content: 'Todo list updated.',
+ pluginState: { version: 'final' },
+ }),
+ ]);
+ });
+
+ it('accepts a new tool-state lifecycle when a call id is reused in one operation', async () => {
+ const key = messageMapKey(context);
+ const store = createStore({
+ [key]: [
+ {
+ content: '',
+ id: 'tool-msg-1',
+ parentId: 'seed-msg',
+ role: 'tool',
+ tool_call_id: 'todo-1',
+ } as UIChatMessage,
+ ],
+ });
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'seed-msg',
+ context,
+ operationId: 'op-1',
+ runtimeType: 'hetero',
+ });
+
+ handler(makeEvent('tool_start', { toolCallId: 'todo-1' }));
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState: { version: 1 },
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ toolCallId: 'todo-1',
+ }),
+ );
+ await flush();
+
+ handler(
+ makeEvent('tool_end', {
+ isSuccess: true,
+ skipMessageFetch: true,
+ toolCallId: 'todo-1',
+ }),
+ );
+ await flush();
+
+ handler(makeEvent('tool_start', { toolCallId: 'todo-1' }));
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState: { version: 2 },
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ toolCallId: 'todo-1',
+ }),
+ );
+ await flush();
+
+ const stateUpdates = (store.internal_dispatchMessage as ReturnType<typeof vi.fn>).mock.calls
+ .map(([payload]) => payload)
+ .filter((payload) => payload.type === 'replaceMessagePluginState');
+ expect(stateUpdates).toMatchObject([{ value: { version: 1 } }, { value: { version: 2 } }]);
+ });
+
+ it('retries bootstrap when a newer snapshot arrives before the first fetch fails', async () => {
+ const key = messageMapKey(context);
+ let rejectBootstrap: ((reason: Error) => void) | undefined;
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const getMessages = vi
+ .spyOn(messageService, 'getMessages')
+ .mockImplementationOnce(
+ () =>
+ new Promise((_, reject) => {
+ rejectBootstrap = reject;
+ }),
+ )
+ .mockResolvedValueOnce([
+ {
+ content: '',
+ id: 'tool-msg-1',
+ parentId: 'seed-msg',
+ pluginState: { version: 1 },
+ role: 'tool',
+ tool_call_id: 'todo-1',
+ } as UIChatMessage,
+ ]);
+ const store = createStore();
+ (store.replaceMessages as ReturnType<typeof vi.fn>).mockImplementation(
+ (messages: UIChatMessage[]) => {
+ store.dbMessagesMap[key] = messages;
+ },
+ );
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'seed-msg',
+ context,
+ operationId: 'op-1',
+ });
+
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState: { version: 1 },
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ toolCallId: 'todo-1',
+ }),
+ );
+ await flush();
+ expect(getMessages).toHaveBeenCalledTimes(1);
+
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState: { version: 2 },
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ toolCallId: 'todo-1',
+ }),
+ );
+ rejectBootstrap?.(new Error('bootstrap failed'));
+ await flush();
+
+ expect(getMessages).toHaveBeenCalledTimes(2);
+ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(
+ {
+ id: 'tool-msg-1',
+ metadata: {
+ heterogeneousToolStateOperationId: 'op-1',
+ heterogeneousToolStateSeq: 2,
+ },
+ type: 'replaceMessagePluginState',
+ value: { version: 2 },
+ },
+ { operationId: 'op-1' },
+ );
+ });
+
it('ignores a sub-agent progress event with no tool message anchor', async () => {
const store = createStore();
const handler = createGatewayEventHandler(() => store, {
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 c3b696dd7b1..bbabc4cd849 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -7,6 +7,7 @@ import type {
ToolEndData,
ToolExecuteData,
ToolStartData,
+ ToolStateChunkData,
} from '@lobechat/agent-gateway-client';
import type {
BuiltinToolResult,
@@ -27,6 +28,7 @@ import type {
import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';
import type { ChatStore } from '@/store/chat/store';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
// `agent_runtime_end` reasons that are NOT a clean completion: a mid-stream
// cancel and a deferred-tool park. These must NOT mark the topic unread, and
@@ -90,6 +92,16 @@ const getToolId = (tool: unknown): string | undefined =>
const getToolResultMessageId = (tool: unknown): string | undefined =>
isRecord(tool) ? pickNonEmptyString(tool.result_msg_id) : undefined;
+const isToolStateChunkData = (data: unknown): data is ToolStateChunkData =>
+ isRecord(data) &&
+ data.chunkType === 'tool_state' &&
+ data.snapshotMode === 'replace' &&
+ typeof data.toolCallId === 'string' &&
+ data.toolCallId.length > 0 &&
+ Number.isInteger(data.snapshotSeq) &&
+ (data.snapshotSeq as number) > 0 &&
+ isRecord(data.pluginState);
+
const preserveToolResultMessageIds = (
toolsCalling: unknown[],
existingTools: unknown,
@@ -421,6 +433,10 @@ export const createGatewayEventHandler = (
// NOT reset on stream boundaries β€” a seq ≀ these is a redelivered duplicate.
let lastTextSnapshotSeq = 0;
let lastReasoningSnapshotSeq = 0;
+ const latestToolStateByCallId = new Map<string, ToolStateChunkData & { operationId: string }>();
+ const toolStateBootstrapPromiseByCallId = new Map<string, Promise<void>>();
+ const lastAppliedToolStateSeqByCallId = new Map<string, number>();
+ const completedToolStateCallIds = new Set<string>();
// Tracks whether any server-confirmed state has actually arrived
// (server-assigned assistant id, streamed text/reasoning/tools, or a SoT
@@ -458,8 +474,118 @@ export const createGatewayEventHandler = (
// Sequential processing queue β€” ensures stream_chunk waits for stream_start's fetch
let processingChain: Promise<void> = Promise.resolve();
- const enqueue = (fn: () => Promise<void> | void): void => {
+ const enqueue = (fn: () => Promise<void> | void): Promise<void> => {
processingChain = processingChain.then(fn, fn);
+ return processingChain;
+ };
+
+ const getToolMessageByCallId = (toolCallId: string): UIChatMessage | undefined => {
+ const messages = get().dbMessagesMap[messageMapKey(context)] ?? [];
+ // Tool-call ids are operation-scoped, not topic-global. Codex can reuse an
+ // id in a later run while that run's newly persisted tool row has not yet
+ // reached the store. Parent scoping prevents us from mistaking the prior
+ // run's row for the current one and skipping the bootstrap refetch.
+ return messages.findLast(
+ (message) =>
+ message.tool_call_id === toolCallId && message.parentId === currentAssistantMessageId,
+ );
+ };
+
+ const applyLatestToolState = (toolCallId: string, reapplyAfterRefetch = false): boolean => {
+ const latest = latestToolStateByCallId.get(toolCallId);
+ if (terminalState || completedToolStateCallIds.has(toolCallId)) return true;
+ const toolMessage = getToolMessageByCallId(toolCallId);
+ if (!latest || !toolMessage) return false;
+
+ const storedSeq =
+ toolMessage.metadata?.heterogeneousToolStateOperationId === latest.operationId &&
+ typeof toolMessage.metadata.heterogeneousToolStateSeq === 'number'
+ ? toolMessage.metadata.heterogeneousToolStateSeq
+ : 0;
+ const inMemorySeq = lastAppliedToolStateSeqByCallId.get(toolCallId) ?? 0;
+
+ // A bootstrap refetch can replace an optimistic seq=4 with DB seq=3. In
+ // that path the message's own watermark, not the in-memory map, decides
+ // whether the cached latest snapshot must be re-applied.
+ if (latest.snapshotSeq <= storedSeq) {
+ lastAppliedToolStateSeqByCallId.set(toolCallId, Math.max(inMemorySeq, storedSeq));
+ return true;
+ }
+ if (!reapplyAfterRefetch && latest.snapshotSeq <= inMemorySeq) return true;
+
+ lastAppliedToolStateSeqByCallId.set(toolCallId, latest.snapshotSeq);
+ get().internal_dispatchMessage(
+ {
+ id: toolMessage.id,
+ metadata: {
+ heterogeneousToolStateOperationId: latest.operationId,
+ heterogeneousToolStateSeq: latest.snapshotSeq,
+ },
+ type: 'replaceMessagePluginState',
+ value: latest.pluginState,
+ },
+ dispatchContext,
+ );
+ return true;
+ };
+
+ const scheduleToolState = (
+ data: ToolStateChunkData,
+ eventOperationId: string | undefined,
+ bootstrapRetry = false,
+ ): void => {
+ if (completedToolStateCallIds.has(data.toolCallId)) return;
+
+ const stateOperationId = eventOperationId || gatewayOperationId;
+ const previous = latestToolStateByCallId.get(data.toolCallId);
+ if (!bootstrapRetry) {
+ if (previous?.operationId === stateOperationId && data.snapshotSeq <= previous.snapshotSeq) {
+ return;
+ }
+
+ // Cache synchronously. A later seq can now overtake an in-flight bootstrap
+ // read; the bootstrap completion always reapplies this map's newest value.
+ latestToolStateByCallId.set(data.toolCallId, { ...data, operationId: stateOperationId });
+ }
+
+ if (getToolMessageByCallId(data.toolCallId)) {
+ enqueue(() => {
+ applyLatestToolState(data.toolCallId);
+ });
+ return;
+ }
+
+ if (toolStateBootstrapPromiseByCallId.has(data.toolCallId)) return;
+
+ let reconciled = false;
+ const bootstrapSnapshotSeq = data.snapshotSeq;
+ // Bootstrap reconciliation is part of the same queue as tool_end. If this
+ // read finishes late, the terminal refresh must still run after it so an
+ // intermediate DB snapshot can never become the last store replacement.
+ const bootstrapPromise = enqueue(async () => {
+ // A preceding queued tools_calling handler may have brought the row in.
+ if (!getToolMessageByCallId(data.toolCallId)) {
+ await fetchAndReplaceMessages(get, context, { skipWorks: true }).catch(console.error);
+ }
+ reconciled = applyLatestToolState(data.toolCallId, true);
+ });
+ const trackedBootstrapPromise = bootstrapPromise.finally(() => {
+ toolStateBootstrapPromiseByCallId.delete(data.toolCallId);
+
+ const latest = latestToolStateByCallId.get(data.toolCallId);
+ // A newer snapshot may have arrived while a failed/empty bootstrap was
+ // in flight. Retry for that newer state, but never spin on the same seq.
+ if (
+ !reconciled &&
+ !terminalState &&
+ !completedToolStateCallIds.has(data.toolCallId) &&
+ latest &&
+ latest.snapshotSeq > bootstrapSnapshotSeq
+ ) {
+ scheduleToolState(latest, latest.operationId, true);
+ }
+ });
+ toolStateBootstrapPromiseByCallId.set(data.toolCallId, trackedBootstrapPromise);
};
return (event: AgentStreamEvent) => {
@@ -472,6 +598,11 @@ export const createGatewayEventHandler = (
// them before forwarding; the gateway path doesn't. (DB is unaffected.)
if ((event.data as { subagent?: unknown } | undefined)?.subagent) return;
+ if (event.type === 'stream_chunk' && isToolStateChunkData(event.data)) {
+ scheduleToolState(event.data, event.operationId);
+ return;
+ }
+
if (event.type === 'agent_runtime_end' || event.type === 'error') {
terminalState = event.type === 'error' ? 'error' : 'completed';
}
@@ -766,6 +897,13 @@ export const createGatewayEventHandler = (
// Server creates tool messages in DB.
// Loading is already active from stream_start (not cleared by stream_end).
const data = event.data as ToolStartData | undefined;
+ const startedToolCallId =
+ getToolId(data?.toolCalling) ||
+ (isRecord(data) ? pickNonEmptyString(data.toolCallId) : undefined);
+ // A producer may reuse a call id within one operation. A new lifecycle
+ // re-opens state delivery while the seq watermark remains monotonic, so
+ // delayed snapshots from the previous lifecycle are still rejected.
+ if (startedToolCallId) completedToolStateCallIds.delete(startedToolCallId);
enqueue(async () => {
await dispatchOnBeforeCall(data, context.topicId ?? undefined).catch(console.error);
});
@@ -845,6 +983,13 @@ export const createGatewayEventHandler = (
case 'tool_end': {
const data = event.data as ToolEndData | undefined;
+ const completedToolCallId =
+ getToolId(unwrapToolPayload(data?.payload)) ||
+ (isRecord(data) ? pickNonEmptyString(data.toolCallId) : undefined);
+ if (completedToolCallId) {
+ completedToolStateCallIds.add(completedToolCallId);
+ latestToolStateByCallId.delete(completedToolCallId);
+ }
enqueue(async () => {
const maybeRefresh = shouldSkipMessageFetch(event, runtimeType)
? Promise.resolve()
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 da170e615d6..1ca3e329679 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -57,6 +57,7 @@ import {
} from '@/services/message';
import { threadService } from '@/services/thread';
import { topicSelectors } from '@/store/chat/selectors';
+import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';
import {
mergeQueuedMessages,
reconstructUploadFilesFromQueue,
@@ -437,6 +438,12 @@ const subscribeBroadcasts = (
interface SubagentStoreDispatcher {
/** Push a new message into the thread bucket (user / assistant / tool). */
create: (msg: UIChatMessage) => void;
+ /** Atomically replace pluginState and advance its optimistic watermark. */
+ replacePluginState: (
+ id: string,
+ pluginState: Record<string, unknown>,
+ metadata: NonNullable<UIChatMessage['metadata']>,
+ ) => void;
/** Update a message already in the thread bucket by id. */
update: (id: string, value: Partial<UIChatMessage>) => void;
}
@@ -663,7 +670,12 @@ export const executeHeterogeneousAgent = async (
* `persistToolResult` and the intervention handlers.
*/
const toolMsgIdByCallId: Map<string, string> = new Map();
+ const lastAppliedToolStateSeqByCallId = new Map<string, number>();
const mainToolCallIds = new Set<string>();
+ /** Terminal results reject later state until a new tool_start reopens the call id. */
+ const completedToolStateCallIds = new Set<string>();
+ /** Final tool_result supersedes every pending non-terminal state retry. */
+ const terminalToolMessageIds = new Set<string>();
const pendingInterventionRequests = new Map<string, AgentInterventionRequestData>();
const pendingInterventionResponses = new Map<string, AgentInterventionResponseData>();
/**
@@ -703,7 +715,7 @@ export const executeHeterogeneousAgent = async (
* be lost once the reducer clears `accContent` on terminal.
*/
const pendingMainFlush = new Map<string, Record<string, any>>();
- /** Retry ledger for tool result content / plugin state. */
+ /** Retry ledger for the latest non-superseded tool write. */
const pendingToolFlush = new Map<string, ToolMessageUpdateOperation['value']>();
/** Later intents carry a superset of the payload, so a shallow merge wins. */
@@ -924,12 +936,16 @@ export const executeHeterogeneousAgent = async (
) => {
if (!mainToolCallIds.has(toolCallId)) return;
+ completedToolStateCallIds.add(toolCallId);
const toolMsgId = toolMsgIdByCallId.get(toolCallId);
if (!toolMsgId) {
console.warn('[HeterogeneousAgent] tool_result for unknown toolCallId:', toolCallId);
return;
}
+ terminalToolMessageIds.add(toolMsgId);
+ pendingToolFlush.delete(toolMsgId);
+
const toolUpdate = {
content,
pluginError: isError ? { message: content } : undefined,
@@ -937,9 +953,29 @@ export const executeHeterogeneousAgent = async (
};
messageWriteBatcher.enqueueToolMessageUpdate(toolMsgId, toolUpdate, messageWriteCtx, (err) => {
console.error('[HeterogeneousAgent] Failed to update tool message content:', err);
- pendingToolFlush.set(toolMsgId, { ...pendingToolFlush.get(toolMsgId), ...toolUpdate });
+ pendingToolFlush.set(toolMsgId, toolUpdate);
});
};
+ const claimToolStateSnapshot = (
+ toolCallId: string,
+ toolMsgId: string,
+ snapshotSeq: number,
+ ): NonNullable<UIChatMessage['metadata']> | undefined => {
+ const stored = dbMessageSelectors.getDbMessageById(toolMsgId)(get());
+ const durableSeq =
+ stored?.metadata?.heterogeneousToolStateOperationId === operationId &&
+ typeof stored.metadata.heterogeneousToolStateSeq === 'number'
+ ? stored.metadata.heterogeneousToolStateSeq
+ : 0;
+ const lastApplied = Math.max(durableSeq, lastAppliedToolStateSeqByCallId.get(toolCallId) ?? 0);
+ if (snapshotSeq <= lastApplied) return;
+
+ lastAppliedToolStateSeqByCallId.set(toolCallId, snapshotSeq);
+ return {
+ heterogeneousToolStateOperationId: operationId,
+ heterogeneousToolStateSeq: snapshotSeq,
+ };
+ };
const applyInterventionRequest = async (data: AgentInterventionRequestData): Promise<boolean> => {
const toolMsgId = toolMsgIdByCallId.get(data.toolCallId);
if (!toolMsgId) return false;
@@ -1083,6 +1119,12 @@ export const executeHeterogeneousAgent = async (
dispatchCtx,
);
},
+ replacePluginState(id, pluginState, metadata) {
+ get().internal_dispatchMessage(
+ { id, metadata, type: 'replaceMessagePluginState', value: pluginState },
+ dispatchCtx,
+ );
+ },
update(id, value) {
get().internal_dispatchMessage(
{ id, type: 'updateMessage', value: value as any },
@@ -1374,8 +1416,11 @@ export const executeHeterogeneousAgent = async (
case 'resolveToolResult': {
const t = getSubagentThread(intent.threadId);
+ completedToolStateCallIds.add(intent.toolCallId);
const toolMsgId = toolMsgIdByCallId.get(intent.toolCallId);
if (toolMsgId) {
+ terminalToolMessageIds.add(toolMsgId);
+ pendingToolFlush.delete(toolMsgId);
const update: ToolMessageUpdateOperation['value'] = {
content: intent.content,
pluginError: intent.isError ? { message: intent.content } : undefined,
@@ -1385,12 +1430,48 @@ export const executeHeterogeneousAgent = async (
await mutateMessageBatch([{ id: toolMsgId, type: 'updateToolMessage', value: update }]);
} catch (err) {
console.error('[HeterogeneousAgent] Failed to persist subagent tool result:', err);
+ pendingToolFlush.set(toolMsgId, update);
}
t?.stream.update(toolMsgId, update as Partial<UIChatMessage>);
}
return;
}
+ case 'updateToolState': {
+ if (completedToolStateCallIds.has(intent.toolCallId)) return;
+
+ const t = getSubagentThread(intent.threadId);
+ const toolMsgId = toolMsgIdByCallId.get(intent.toolCallId);
+ if (!toolMsgId) {
+ console.warn(
+ '[HeterogeneousAgent] tool_state for unknown subagent toolCallId:',
+ intent.toolCallId,
+ );
+ return;
+ }
+
+ const metadata = claimToolStateSnapshot(intent.toolCallId, toolMsgId, intent.snapshotSeq);
+ if (!metadata) return;
+
+ const update: ToolMessageUpdateOperation['value'] = {
+ heterogeneousToolState: {
+ operationId,
+ snapshotSeq: intent.snapshotSeq,
+ },
+ pluginState: intent.pluginState,
+ };
+ try {
+ await mutateMessageBatch([{ id: toolMsgId, type: 'updateToolMessage', value: update }]);
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to persist subagent tool state:', err);
+ if (!terminalToolMessageIds.has(toolMsgId)) {
+ pendingToolFlush.set(toolMsgId, { ...pendingToolFlush.get(toolMsgId), ...update });
+ }
+ }
+ t.stream.replacePluginState(toolMsgId, intent.pluginState, metadata);
+ return;
+ }
+
case 'recordUsage': {
const t = getSubagentThread(intent.threadId);
const update = {
@@ -1628,6 +1709,46 @@ export const executeHeterogeneousAgent = async (
return;
}
+ case 'updateToolState': {
+ if (
+ !mainToolCallIds.has(intent.toolCallId) ||
+ completedToolStateCallIds.has(intent.toolCallId)
+ ) {
+ return;
+ }
+
+ const toolMsgId = toolMsgIdByCallId.get(intent.toolCallId);
+ if (!toolMsgId) {
+ console.warn(
+ '[HeterogeneousAgent] tool_state for unknown main toolCallId:',
+ intent.toolCallId,
+ );
+ return;
+ }
+
+ const metadata = claimToolStateSnapshot(intent.toolCallId, toolMsgId, intent.snapshotSeq);
+ if (!metadata) return;
+
+ const update: ToolMessageUpdateOperation['value'] = {
+ heterogeneousToolState: {
+ operationId,
+ snapshotSeq: intent.snapshotSeq,
+ },
+ pluginState: intent.pluginState,
+ };
+ messageWriteBatcher.enqueueToolMessageUpdate(toolMsgId, update, messageWriteCtx, (err) => {
+ console.error('[HeterogeneousAgent] Failed to persist main tool state:', err);
+ if (!terminalToolMessageIds.has(toolMsgId)) {
+ pendingToolFlush.set(toolMsgId, { ...pendingToolFlush.get(toolMsgId), ...update });
+ }
+ });
+ get().internal_dispatchMessage(
+ { id: toolMsgId, metadata, type: 'replaceMessagePluginState', value: intent.pluginState },
+ { operationId },
+ );
+ return;
+ }
+
case 'recordUsage': {
const update = {
// Keep usage on the promoted top-level field so the live message UI
@@ -1828,6 +1949,17 @@ export const executeHeterogeneousAgent = async (
return;
}
+ if (event.type === 'tool_start') {
+ const toolCallId = (event.data as { toolCallId?: unknown } | undefined)?.toolCallId;
+ if (typeof toolCallId === 'string') {
+ // Keep lifecycle changes on the same FIFO as results and state so a
+ // rapid result β†’ start β†’ state sequence cannot be observed out of order.
+ persistQueue = persistQueue.then(() => {
+ completedToolStateCallIds.delete(toolCallId);
+ });
+ }
+ }
+
// ─── tool_result: reducer writes the tool content + finalizes spawns ───
// For a main tool (incl. a subagent's parent Task tool, which is
// main-scoped) the reducer emits `resolveToolResult` β†’ DB content write
@@ -1882,6 +2014,16 @@ export const executeHeterogeneousAgent = async (
return;
}
+ // tool_state is interpreted locally after the preceding tools_calling
+ // intent has registered its tool row. Do not also forward it to the
+ // gateway handler: that path would bootstrap-refetch while the local
+ // write-behind create may still be queued.
+ if (event.type === 'stream_chunk' && event.data?.chunkType === 'tool_state') {
+ sawStreamedEvent = true;
+ persistQueue = persistQueue.then(() => reduceAndApplyMain(event));
+ return;
+ }
+
// ─── stream_chunk / stream_start(init): drive the reducer for DB ───
// text/reasoning accumulation, main tool-batch persistence, subagent
// delegation (thread create / turn boundary / tool persist / live thread
diff --git a/src/store/chat/slices/message/reducer.test.ts b/src/store/chat/slices/message/reducer.test.ts
index c511f7ad45b..36223ed5cca 100644
--- a/src/store/chat/slices/message/reducer.test.ts
+++ b/src/store/chat/slices/message/reducer.test.ts
@@ -246,6 +246,39 @@ describe('messagesReducer', () => {
});
});
+ describe('replaceMessagePluginState', () => {
+ it('replaces plugin state and advances its metadata watermark atomically', () => {
+ const state: UIChatMessage[] = [
+ {
+ content: '',
+ id: 'tool-1',
+ metadata: { heteroMessageId: 'native-tool-1' },
+ pluginState: { obsolete: true, todos: { items: [{ text: 'old' }] } },
+ role: 'tool',
+ } as UIChatMessage,
+ ];
+
+ const newState = messagesReducer(state, {
+ id: 'tool-1',
+ metadata: {
+ heterogeneousToolStateOperationId: 'op-1',
+ heterogeneousToolStateSeq: 2,
+ },
+ type: 'replaceMessagePluginState',
+ value: { todos: { items: [{ status: 'processing', text: 'new' }] } },
+ });
+
+ expect(newState[0].pluginState).toEqual({
+ todos: { items: [{ status: 'processing', text: 'new' }] },
+ });
+ expect(newState[0].metadata).toEqual({
+ heteroMessageId: 'native-tool-1',
+ heterogeneousToolStateOperationId: 'op-1',
+ heterogeneousToolStateSeq: 2,
+ });
+ });
+ });
+
describe('updateMessagePlugin', () => {
it('should update the plugin of a tool message', () => {
const toolMessage: UIChatMessage = {
diff --git a/src/store/chat/slices/message/reducer.ts b/src/store/chat/slices/message/reducer.ts
index a3b43686a84..b49f0ec356b 100644
--- a/src/store/chat/slices/message/reducer.ts
+++ b/src/store/chat/slices/message/reducer.ts
@@ -45,6 +45,13 @@ interface UpdatePluginState {
value: any;
}
+interface ReplaceMessagePluginState {
+ id: string;
+ metadata?: Partial<NonNullable<UIChatMessage['metadata']>>;
+ type: 'replaceMessagePluginState';
+ value: UIChatMessage['pluginState'];
+}
+
interface UpdateMessagePlugin {
id: string;
type: 'updateMessagePlugin';
@@ -87,6 +94,7 @@ export type MessageDispatch =
| UpdateMessage
| UpdateMessages
| UpdatePluginState
+ | ReplaceMessagePluginState
| UpdateMessageExtra
| UpdateMessageMetadata
| DeleteMessage
@@ -119,6 +127,18 @@ export const messagesReducer = (
});
}
+ case 'replaceMessagePluginState': {
+ return produce(state, (draftState) => {
+ const { id, metadata, value } = payload;
+ const message = draftState.find((item) => item.id === id);
+ if (!message || message.role !== 'tool') return;
+
+ message.pluginState = value;
+ if (metadata) message.metadata = merge(message.metadata, metadata);
+ message.updatedAt = Date.now();
+ });
+ }
+
case 'updateMessageExtra': {
return produce(state, (draftState) => {
const { id, key, value } = payload;