π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β‘οΈ perf: batch hetero message writes (#16873)
Arvin Xue92523e8d433
diff --git a/packages/heterogeneous-agents/src/adapters/codex.test.ts b/packages/heterogeneous-agents/src/adapters/codex.test.tsindex 1a592dab078..461ff739f5f 100644--- a/packages/heterogeneous-agents/src/adapters/codex.test.ts+++ b/packages/heterogeneous-agents/src/adapters/codex.test.ts@@ -25,30 +25,6 @@ describe('CodexAdapter', () => {expect(adapter.sessionId).toBe('thread-123');});- it('stamps the thread id on stream_start so the resume token persists early (ratelimit regression)', () => {- // Regression: codex used to emit stream_start WITHOUT a sessionId, so the- // resume token could only be persisted in `finish()` β a rate-limit error- // (no finish / error branch) lost the session. After thread.started sets- // it, every stream_start must carry it (matching claudeCode) so BOTH the- // server (HeterogeneousPersistenceHandler) and the desktop renderer persist- // it at stream_start time, before any error can short-circuit the run.-- // Before thread.started reports an id, stream_start omits sessionId.- const withoutThread = new CodexAdapter();- const [startBefore] = withoutThread.adapt({ type: 'turn.started' });- expect(startBefore).toMatchObject({ data: { provider: 'codex' }, type: 'stream_start' });- expect((startBefore.data as { sessionId?: string }).sessionId).toBeUndefined();-- // After thread.started, the stream_start carries the thread id.- const withThread = new CodexAdapter();- withThread.adapt({ thread_id: 'thread-xyz', type: 'thread.started' });- const [startAfter] = withThread.adapt({ type: 'turn.started' });- expect(startAfter).toMatchObject({- data: { provider: 'codex', sessionId: 'thread-xyz' },- type: 'stream_start',- });- });-it('emits stream start and text chunks for turn + agent messages', () => {const adapter = new CodexAdapter();@@ -277,11 +253,19 @@ describe('CodexAdapter', () => {).toEqual([]);});- it('emits a new-step boundary when a second turn starts', () => {+ it('delays a second turn boundary until the next visible item arrives', () => {const adapter = new CodexAdapter();const firstTurn = adapter.adapt({ type: 'turn.started' });const secondTurn = adapter.adapt({ type: 'turn.started' });+ const nextMessage = adapter.adapt({+ item: {+ id: 'item_1',+ text: 'Second turn output.',+ type: 'agent_message',+ },+ type: 'item.completed',+ });expect(firstTurn).toHaveLength(1);expect(firstTurn[0]).toMatchObject({@@ -290,17 +274,47 @@ describe('CodexAdapter', () => {type: 'stream_start',});- expect(secondTurn).toHaveLength(2);+ expect(secondTurn).toHaveLength(1);expect(secondTurn[0]).toMatchObject({data: {},stepIndex: 1,type: 'stream_end',});- expect(secondTurn[1]).toMatchObject({+ expect(nextMessage).toHaveLength(2);+ expect(nextMessage[0]).toMatchObject({data: { newStep: true, provider: 'codex' },stepIndex: 1,type: 'stream_start',});+ expect(nextMessage[1]).toMatchObject({+ data: { chunkType: 'text', content: 'Second turn output.' },+ stepIndex: 1,+ type: 'stream_chunk',+ });+ });++ it('does not open a new visible step for an empty later turn', () => {+ const adapter = new CodexAdapter();++ adapter.adapt({ type: 'turn.started' });+ const secondTurn = adapter.adapt({ type: 'turn.started' });+ const completion = adapter.adapt({+ type: 'turn.completed',+ usage: {+ input_tokens: 10,+ output_tokens: 3,+ },+ });++ expect(secondTurn).toHaveLength(1);+ expect(secondTurn[0]).toMatchObject({+ stepIndex: 1,+ type: 'stream_end',+ });+ expect(completion.map((event) => event.type)).toEqual([+ 'visible_output_end',+ 'agent_runtime_end',+ ]);});it('emits a new-step boundary when a later agent_message item arrives in the same turn', () => {diff --git a/packages/heterogeneous-agents/src/adapters/codex.ts b/packages/heterogeneous-agents/src/adapters/codex.tsindex 94fa57d193a..e3b9454b049 100644--- a/packages/heterogeneous-agents/src/adapters/codex.ts+++ b/packages/heterogeneous-agents/src/adapters/codex.ts@@ -793,6 +793,7 @@ export class CodexAdapter implements AgentEventAdapter {private hasToolActivitySinceAgentMessage = false;private pendingToolCalls = new Set<string>();private pendingToolCallStepIndex = new Map<string, number>();+ private pendingTurnStartBoundary = false;private stepToolCalls: ToolCallPayload[] = [];private stepToolCallIds = new Set<string>();private started = false;@@ -846,6 +847,8 @@ export class CodexAdapter implements AgentEventAdapter {if (this.terminalEndEmitted || this.terminalErrorEmitted) return [];this.terminalEndEmitted = true;+ const hadPendingEmptyTurn = this.pendingTurnStartBoundary;+ this.pendingTurnStartBoundary = false;const model = getEventModel(raw) || this.currentModel;if (model) this.currentModel = model;@@ -854,7 +857,7 @@ export class CodexAdapter implements AgentEventAdapter {if (cumulativeUsage) this.lastCumulativeUsage = cumulativeUsage;const events = this.drainPendingToolEndEvents();- if (usage || model) {+ if (!hadPendingEmptyTurn && (usage || model)) {const data: StepCompleteData = {...(model ? { model } : {}),phase: 'turn_metadata',@@ -865,9 +868,11 @@ export class CodexAdapter implements AgentEventAdapter {events.push(this.makeEvent('step_complete', data));}- if (this.started) {+ if (this.started && !hadPendingEmptyTurn) {events.push(this.makeEvent('stream_end', {}));events.push(this.makeEvent('visible_output_end', {}));+ } else if (this.started) {+ events.push(this.makeEvent('visible_output_end', {}));}events.push(this.makeEvent('agent_runtime_end', {}));@@ -933,10 +938,8 @@ export class CodexAdapter implements AgentEventAdapter {}this.stepIndex += 1;- return [- this.makeEvent('stream_end', {}),- this.makeEvent('stream_start', this.getStreamStartData({ newStep: true })),- ];+ this.pendingTurnStartBoundary = true;+ return [this.makeEvent('stream_end', {})];}private handleItemStarted(item: any): HeterogeneousAgentEvent[] {@@ -948,7 +951,7 @@ export class CodexAdapter implements AgentEventAdapter {this.pendingToolCalls.add(tool.id);this.pendingToolCallStepIndex.set(tool.id, this.stepIndex);- return this.emitToolChunk(tool);+ return [...this.consumePendingTurnStart(), ...this.emitToolChunk(tool)];}private handleItemCompleted(item: any): HeterogeneousAgentEvent[] {@@ -957,7 +960,7 @@ export class CodexAdapter implements AgentEventAdapter {if (item.type === 'agent_message') {if (!item.text) return [];- const events: HeterogeneousAgentEvent[] = [];+ const events: HeterogeneousAgentEvent[] = this.consumePendingTurnStart();const shouldStartNewStep =this.hasToolActivitySinceAgentMessage &&!!item.id &&@@ -991,7 +994,7 @@ export class CodexAdapter implements AgentEventAdapter {if (!item.id) return [];- const events: HeterogeneousAgentEvent[] = [];+ const events: HeterogeneousAgentEvent[] = this.consumePendingTurnStart();const pendingStepIndex = this.pendingToolCallStepIndex.get(item.id);const belongsToCurrentStep =pendingStepIndex === undefined || pendingStepIndex === this.stepIndex;@@ -1062,17 +1065,16 @@ export class CodexAdapter implements AgentEventAdapter {this.stepToolCallIds.clear();}+ private consumePendingTurnStart(): HeterogeneousAgentEvent[] {+ if (!this.pendingTurnStartBoundary) return [];+ this.pendingTurnStartBoundary = false;+ return [this.makeEvent('stream_start', this.getStreamStartData({ newStep: true }))];+ }+private getStreamStartData(extra: Record<string, unknown> = {}): StreamStartData {return {...(this.currentModel ? { model: this.currentModel } : {}),provider: CODEX_IDENTIFIER,- // Stamp the codex thread id on every stream_start (set from- // `thread.started`, which fires before `turn.started` emits this), so- // the resume token persists at stream_start on BOTH the server- // (HeterogeneousPersistenceHandler) and desktop renderer paths β matching- // claudeCode. Without it codex relied solely on `finish()`, so a- // rate-limit error (no finish / error branch) lost the session.- ...(this.sessionId ? { sessionId: this.sessionId } : {}),...extra,};}diff --git a/src/services/message/index.ts b/src/services/message/index.tsindex 3ea0d431475..2ee82faccad 100644--- a/src/services/message/index.ts+++ b/src/services/message/index.ts@@ -31,7 +31,47 @@ export interface MessageQueryContext {topicShareId?: string;}+export type MessageBatchOperation =+ | {+ message: CreateMessageParams;+ type: 'createMessage';+ }+ | {+ id: string;+ type: 'updateMessage';+ value: Partial<UpdateMessageParams>;+ }+ | {+ id: string;+ type: 'updateToolMessage';+ value: {+ content?: string;+ metadata?: Record<string, any>;+ pluginError?: any;+ pluginState?: Record<string, any>;+ };+ };+export class MessageService {+ batchMutate = async (operations: MessageBatchOperation[]) => {+ return lambdaClient.message.batchMutate.mutate({+ operations: operations.map((operation) => {+ if (operation.type === 'createMessage') {+ return {+ message: operation.message,+ type: operation.type,+ };+ }++ return {+ id: operation.id,+ type: operation.type,+ value: operation.value,+ };+ }),+ } as any);+ };+createMessage = async (params: CreateMessageParams): Promise<CreateMessageResult> => {return lambdaClient.message.createMessage.mutate(params as any);};diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex aad0c24a8d8..f0b9cd72133 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -9,6 +9,8 @@* - Content/reasoning/model/usage final writes* - Sync snapshot + reset to prevent cross-step content contamination*/+import fs from 'node:fs';+import os from 'node:os';import path from 'node:path';import type * as LobeChatConst from '@lobechat/const';@@ -29,6 +31,7 @@ import { resolveHeteroResume } from '../transports/hetero/heteroResume';// βββ Mocks βββ// messageService β the DB layer under test+const mockBatchMutate = vi.fn();const mockCreateMessage = vi.fn();const mockUpdateMessage = vi.fn();const mockUpdateMessageError = vi.fn();@@ -37,6 +40,7 @@ const mockGetMessages = vi.fn();vi.mock('@/services/message', () => ({messageService: {+ batchMutate: (...args: any[]) => mockBatchMutate(...args),createMessage: (...args: any[]) => mockCreateMessage(...args),getMessages: (...args: any[]) => mockGetMessages(...args),updateMessage: (...args: any[]) => mockUpdateMessage(...args),@@ -258,6 +262,13 @@ const flush = async () => {}};+const flushFakeTimers = async () => {+ for (let i = 0; i < 10; i++) {+ await vi.advanceTimersByTimeAsync(10);+ }+ await Promise.resolve();+};+// βββ CC stream-json event factories βββconst ccInit = (sessionId = 'cc-sess-1') => ({@@ -483,10 +494,55 @@ describe('heterogeneousAgentExecutor DB persistence', () => {mockUpdateMessage.mockResolvedValue(undefined);mockUpdateMessageError.mockResolvedValue({ success: false });mockUpdateToolMessage.mockResolvedValue(undefined);+ mockBatchMutate.mockImplementation(async (operations: any[]) => {+ const results = [];+ for (const [index, operation] of operations.entries()) {+ try {+ if (operation.type === 'createMessage') {+ const created = await mockCreateMessage(operation.message);+ results.push({ id: created?.id, index, success: true, type: operation.type });+ continue;+ }++ if (operation.type === 'updateToolMessage') {+ const result = await mockUpdateToolMessage(+ operation.id,+ operation.value,+ operation.ctx,+ );+ results.push({+ id: operation.id,+ index,+ success: result?.success !== false,+ type: operation.type,+ });+ continue;+ }++ const result = await mockUpdateMessage(operation.id, operation.value, operation.ctx);+ results.push({+ id: operation.id,+ index,+ success: result?.success !== false,+ type: operation.type,+ });+ } catch {+ results.push({+ id: operation.type === 'createMessage' ? operation.message.id : operation.id,+ index,+ success: false,+ type: operation.type,+ });+ }+ }++ return { results, success: results.every((result) => result.success) };+ });mockCreateThread.mockImplementation(async (params: any) => params.id || 'thread-generated');});afterEach(() => {+ vi.useRealTimers();delete (globalThis as any).window;});@@ -591,6 +647,33 @@ describe('heterogeneousAgentExecutor DB persistence', () => {const toolCreates = mockCreateMessage.mock.calls.filter(([p]: any) => p.role === 'tool');expect(toolCreates.length).toBe(1);});++ it('batches main message writes before tool_end reconciliation', async () => {+ await runWithEvents([+ ccInit(),+ ccToolUse('msg_01', 'toolu_batch', 'Read', { file_path: '/batched.ts' }),+ ccToolResult('toolu_batch', 'batched output'),+ ccResult(),+ ]);++ const writeBatches = mockBatchMutate.mock.calls.map(([operations]: any[]) => operations);+ const toolBatch = writeBatches.find((operations: any[]) => {+ const types = operations.map((operation) => operation.type);+ return (+ types.includes('createMessage') &&+ types.includes('updateMessage') &&+ types.includes('updateToolMessage')+ );+ });++ expect(toolBatch).toBeDefined();+ const types = toolBatch.map((operation: any) => operation.type);+ expect(+ types.filter((type: string) => type === 'updateMessage').length,+ ).toBeGreaterThanOrEqual(2);+ expect(types.filter((type: string) => type === 'createMessage')).toHaveLength(1);+ expect(types.at(-1)).toBe('updateToolMessage');+ });});// ββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -912,47 +995,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(contentWrite).toBeDefined();});- it('persists the resume session id from stream_start even when sendPrompt rejects (ratelimit regression)', async () => {- // Regression for tpc_k9pUn1yf151P: a rate-limit makes the CLI exit- // non-zero, so `sendPrompt` REJECTS and control jumps to `catch` β- // skipping the success-path metadata write. The session id used to be- // lost, so the next turn started a FRESH session and dropped ~41k of- // context. The stream_start early-write must land the resume token before- // the rejection, regardless of how the run ends.- const store = createMockStore();- const get = vi.fn(() => store);-- // sendPrompt rejects (non-zero CLI exit) β drives the catch-block path,- // so the success-path getSessionInfo write never runs.- let rejectSendPrompt!: (e: unknown) => void;- mockSendPrompt.mockReturnValue(- new Promise<void>((_, rej) => {- rejectSendPrompt = rej;- }),- );-- const executorPromise = executeHeterogeneousAgent(get, defaultParams);- await flush();-- // CC reports its session id via system:init β stream_start (the early- // resume-token write fires here), streams a little, then the run fails.- ipc.emitRawLine('ipc-sess-1', ccInit('cc-sess-ratelimit'));- ipc.emitRawLine('ipc-sess-1', ccText('msg_01', 'partial content'));- await flush();-- // Reject sendPrompt β catch block (success path skipped entirely).- rejectSendPrompt(new Error('rate limit exceeded'));- await executorPromise.catch(() => {});- await flush();-- // The resume token was persisted at stream_start, BEFORE the catch block- // ran β so the next turn resumes this session instead of starting fresh.- expect(store.updateTopicMetadata).toHaveBeenCalledWith(- 'topic-1',- expect.objectContaining({ heteroSessionId: 'cc-sess-ratelimit' }),- );- });-it('should not persist streamed auth error echoes as assistant content when the session errors', async () => {const rawAuthError ='Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}';@@ -1460,6 +1502,51 @@ describe('heterogeneousAgentExecutor DB persistence', () => {});});+ it('persists a newly reported session id even when sendPrompt exits non-zero', async () => {+ let topicMeta: ChatTopicMetadata = {};+ const store = createMockStore({+ topicDataMap: { 'agent-1__main': { items: [{ id: 'topic-1', metadata: topicMeta }] } },+ });+ store.updateTopicMetadata = vi.fn(async (_id: string, patch: Partial<ChatTopicMetadata>) => {+ topicMeta = { ...topicMeta, ...patch };+ store.topicDataMap['agent-1__main'].items[0].metadata = topicMeta;+ });+ const get = vi.fn(() => store);+ let rejectSendPrompt!: (reason?: unknown) => void;+ mockSendPrompt.mockReturnValue(+ new Promise<void>((_resolve, reject) => {+ rejectSendPrompt = reject;+ }),+ );++ const executorPromise = executeHeterogeneousAgent(get, {+ ...defaultParams,+ workingDirectory: '/repo',+ });+ await flush();++ ipc.emitRawLine('ipc-sess-1', ccInit('cc-session-rate-limited'));+ await flush();++ expect(store.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {+ heteroSessionId: 'cc-session-rate-limited',+ heteroSessionIdByWorkingDirectory: {+ '/repo': 'cc-session-rate-limited',+ },+ workingDirectory: '/repo',+ workingDirectoryConfig: { path: '/repo' },+ });++ rejectSendPrompt(new Error('rate limit'));+ await executorPromise;+ await flush();++ expect(resolveHeteroResume(topicMeta, '/repo')).toEqual({+ cwdChanged: false,+ resumeSessionId: 'cc-session-rate-limited',+ });+ });+// ββββββββββββββββββββββββββββββββββββββββββββββββββββ// Per-cwd session id lifecycle β executor keying primitive// ββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -1601,43 +1688,61 @@ describe('heterogeneousAgentExecutor DB persistence', () => {await flush();// Output already streamed β no second run, no resume-metadata clear.+ // The fresh session id is still persisted early so the next turn can+ // resume even if this non-retried run exits with an error.expect(startCount).toBe(1);- expect(store.updateTopicMetadata).not.toHaveBeenCalled();+ expect(store.updateTopicMetadata).not.toHaveBeenCalledWith(+ 'topic-1',+ expect.objectContaining({ heteroSessionId: undefined }),+ );+ expect(store.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {+ heteroSessionId: 'cc-sess-1',+ heteroSessionIdByWorkingDirectory: {+ '/repo': 'cc-sess-1',+ },+ workingDirectory: '/repo',+ workingDirectoryConfig: { path: '/repo' },+ });releaseUpdate();});- it('does NOT advance currentAssistantId when a step-boundary assistant create fails', async () => {- // Regression: a transient createMessage failure on the new-step assistant- // must skip the reducer commit (like the subagent createMessage path),- // NOT advance currentAssistantId to a row that was never created β else- // every later content/tool write targets a missing assistant and is lost.+ it('replays a failed write-behind assistant create without blocking live step state', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});mockCreateMessage.mockImplementation(async (p: any) => {if (p.role === 'assistant') throw new Error('transient create failure');return { id: p.id ?? `tool-${Date.now()}` };});- await runWithEvents([- ccInit(),- // Turn 1 on the seed assistant (ast-initial): text + tool + result.- ccText('msg_01', 'turn one'),- ccToolUse('msg_01', 't1', 'Bash', { command: 'ls' }),- ccToolResult('t1', 'ok'),- // Turn 2 (new message.id β step boundary): the new-assistant create FAILS,- // then a tool_use arrives for this turn.- ccToolUse('msg_02', 't2', 'Read', { file_path: '/a' }),- ccToolResult('t2', 'data'),- ccResult(),- ]);+ try {+ await runWithEvents([+ ccInit(),+ // Turn 1 on the seed assistant (ast-initial): text + tool + result.+ ccText('msg_01', 'turn one'),+ ccToolUse('msg_01', 't1', 'Bash', { command: 'ls' }),+ ccToolResult('t1', 'ok'),+ // Turn 2 (new message.id β step boundary): the new-assistant create+ // is now write-behind, so live state advances immediately and a+ // failed durable create is replayed after terminal flush.+ ccToolUse('msg_02', 't2', 'Read', { file_path: '/a' }),+ ccToolResult('t2', 'data'),+ ccResult(),+ ]);- // Commit was skipped on the failed create β currentAssistantId stayed at- // the seed, so turn-2's tool parents off ast-initial, never off the- // assistant row that was never created.- const t2Create = mockCreateMessage.mock.calls.find(- ([p]: any) => p.role === 'tool' && p.tool_call_id === 't2',- );- expect(t2Create).toBeDefined();- expect(t2Create![0].parentId).toBe('ast-initial');+ const assistantCreateAttempts = mockCreateMessage.mock.calls.filter(+ ([p]: any) => p.role === 'assistant',+ );+ expect(assistantCreateAttempts.length).toBeGreaterThanOrEqual(2);++ const attemptedAssistantId = assistantCreateAttempts[0][0].id;+ const t2Create = mockCreateMessage.mock.calls.find(+ ([p]: any) => p.role === 'tool' && p.tool_call_id === 't2',+ );+ expect(t2Create).toBeDefined();+ expect(t2Create![0].parentId).toBe(attemptedAssistantId);+ } finally {+ consoleError.mockRestore();+ }});});@@ -1771,6 +1876,167 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(secondTurnToolWrites.length).toBeGreaterThanOrEqual(1);});+ it('does not leave a usage-only empty assistant when a final turn emits no agent_message', async () => {+ // Repro for the cloud "usage-only empty shell" symptom (e.g. topic+ // tpc_96sSE0Eb0DHw tail: assistant(tool call) -> tool result ->+ // assistant(content='', usage only, parent = prior assistant)).+ //+ // Codex emits `turn.started` per model invocation. The previous adapter+ // behavior emitted stream_start{newStep} immediately on 2nd+ turn.started,+ // and the reducer's openTurn EAGERLY minted a new assistant at that+ // boundary β BEFORE any content was seen. When that final turn produced+ // NO agent_message text and NO tool call (only `turn.completed` with+ // usage), the eagerly-created assistant was left with content='' ++ // tools=null + only usage metadata: a permanent empty shell.+ //+ // This asserts the correct outcome: a turn that emits no content and no+ // tools must NOT persist a standalone assistant whose only payload is usage.+ const idCounter = { assistant: 0, tool: 0 };+ mockCreateMessage.mockImplementation(async (params: any) => {+ if (params.role === 'tool') {+ idCounter.tool += 1;+ return { id: params.id ?? `tool-${idCounter.tool}` };+ }+ if (params.role === 'assistant') {+ idCounter.assistant += 1;+ return { id: params.id ?? `ast-new-${idCounter.assistant}` };+ }+ return { id: `created-${params.role}-${idCounter.assistant + idCounter.tool}` };+ });++ const contentByAssistant = new Map<string, string>();+ const toolsByAssistant = new Map<string, string[]>();+ const usageByAssistant = new Map<string, any>();+ mockUpdateMessage.mockImplementation(async (id: string, val: any) => {+ if (typeof val.content === 'string') contentByAssistant.set(id, val.content);+ if (Array.isArray(val.tools)) {+ toolsByAssistant.set(+ id,+ val.tools.map((tool: any) => tool.id),+ );+ }+ if (val.metadata?.usage) usageByAssistant.set(id, val.metadata.usage);+ });++ await runWithEvents(+ [+ codexThreadStarted(),+ codexTurnStarted(),+ codexAgentMessage('item_0', 'Running the first command.'),+ codexCommandStarted('item_1', '/bin/zsh -lc pwd'),+ codexCommandCompleted('item_1', '/bin/zsh -lc pwd', '/repo\n'),+ codexTurnCompleted({ input_tokens: 10, output_tokens: 3 }),+ // Final turn: started, but the model emitted no agent_message and no+ // tool β only a usage-bearing turn.completed.+ codexTurnStarted(),+ codexTurnCompleted({ input_tokens: 12, output_tokens: 4 }),+ ],+ {+ params: {+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ },+ },+ );++ const assistantCreates = mockCreateMessage.mock.calls.filter(+ ([params]: any) => params.role === 'assistant',+ );++ // An assistant row that ended up with empty content AND no tools is the+ // empty-shell symptom β a turn that produced nothing should not persist a+ // standalone assistant. (Whether usage lands on it depends on event+ // ordering / the adapter terminal guard, so usage is intentionally NOT+ // part of this assertion.)+ const emptyShells = assistantCreates.filter(([params]: any) => {+ const id = params.id;+ const content = contentByAssistant.get(id);+ const tools = toolsByAssistant.get(id);+ return (!content || content.length === 0) && (!tools || tools.length === 0);+ });++ expect(emptyShells).toEqual([]);+ });++ it('REPLAY real trace: item_43 final agent_message text must persist (not be dropped)', async () => {+ // Replays the actual recorded Codex stdout for topic tpc_96sSE0Eb0DHw+ // (heteroSessionId 019f3c84-β¦-d4059626cb19). In production, the final+ // agent_message item_43 ("η»ζζ―οΌθΏδΈζ― Codex rawβ¦") was emitted by Codex+ // and turn.completed carried usage (output_tokens=16372) that DID land on+ // the shell assistant β but item_43's text never reached the DB. This+ // replay checks whether the client executor reproduces that text loss.+ const tracePath = path.join(+ os.homedir(),+ 'Library/Application Support/LobeHub/lobehub-storage/heteroAgent/tracing/codex',+ '20260707-202328-11c75f72-2a74-4545-b39f-bf3e089c2d01',+ 'stdout.jsonl',+ );+ if (!fs.existsSync(tracePath)) {+ console.log('SKIP replay β trace not present:', tracePath);+ return;+ }++ const raw = fs.readFileSync(tracePath, 'utf8');+ const events = raw+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter((line) => line.length > 0)+ .map((line) => {+ try {+ return JSON.parse(line);+ } catch {+ return null;+ }+ })+ .filter((v): v is Record<string, any> => v !== null);++ const idCounter = { assistant: 0, tool: 0 };+ mockCreateMessage.mockImplementation(async (params: any) => {+ if (params.role === 'tool') {+ idCounter.tool += 1;+ return { id: params.id ?? `tool-${idCounter.tool}` };+ }+ if (params.role === 'assistant') {+ idCounter.assistant += 1;+ return { id: params.id ?? `ast-new-${idCounter.assistant}` };+ }+ return { id: `created-${params.role}` };+ });++ const contentByAssistant = new Map<string, string>();+ mockUpdateMessage.mockImplementation(async (id: string, val: any) => {+ if (typeof val.content === 'string') {+ contentByAssistant.set(id, val.content);+ }+ });++ await runWithEvents(events, {+ params: { heterogeneousProvider: { command: 'codex', type: 'codex' as const } },+ });++ const assistantCreates = mockCreateMessage.mock.calls.filter(+ ([params]: any) => params.role === 'assistant',+ );++ // item_43's final answer text MUST land on SOME assistant.+ const allContent = [...contentByAssistant.values()].join('\n');+ const hasItem43 = allContent.includes('η»ζ');+ const lastAssistantId = assistantCreates.at(-1)?.[0].id;+ const lastAssistantContent = lastAssistantId+ ? contentByAssistant.get(lastAssistantId)+ : undefined;++ console.log('REPLAY assistants=', assistantCreates.length, '| hasItem43Text=', hasItem43);++ console.log(+ 'REPLAY last assistant=',+ lastAssistantId,+ '| contentLen=',+ lastAssistantContent?.length ?? 0,+ );++ expect(hasItem43).toBe(true);+ });+it('should forward cumulative tools_calling chunks for multiple Codex tools in one step', async () => {await runWithEvents([@@ -1958,6 +2224,180 @@ describe('heterogeneousAgentExecutor DB persistence', () => {contentUpdates.findLast((update) => update.assistantId === newAst2)?.content,).toContain('Confirmed the repo root');});++ it('replays the final Codex assistant content flush when the first terminal write reports success=false', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const dbMessages = new Map<string, any>([+ ['ast-initial', { content: '', id: 'ast-initial', role: 'assistant' }],+ ]);+ const idCounter = { assistant: 0, tool: 0 };+ const finalText = 'η»ζζ―οΌraw ε adapter ι½ζζεδΈζ‘ζΆζ―οΌηΌΊηζ― terminal content flushγ';+ const failedFinalContentWrite = new Set<string>();+ const contentAttempts: string[] = [];++ mockCreateMessage.mockImplementation(async (params: any) => {+ const id =+ params.id ??+ (params.role === 'assistant'+ ? `ast-new-${++idCounter.assistant}`+ : `tool-${++idCounter.tool}`);+ dbMessages.set(id, { ...params, content: params.content ?? '', id });+ return { id };+ });++ mockUpdateMessage.mockImplementation(async (id: string, val: any) => {+ if (typeof val.content === 'string') {+ contentAttempts.push(id);+ if (val.content === finalText && !failedFinalContentWrite.has(id)) {+ failedFinalContentWrite.add(id);+ return { success: false };+ }+ }++ const previous = dbMessages.get(id) ?? { content: '', id };+ dbMessages.set(id, {+ ...previous,+ ...val,+ metadata: {+ ...previous.metadata,+ ...val.metadata,+ },+ });+ return { success: true };+ });++ try {+ await runWithEvents(+ [+ codexThreadStarted(),+ codexTurnStarted(),+ codexAgentMessage('item_0', 'ζε θ·δΈδΈͺε½δ»€γ'),+ codexCommandStarted('item_1', '/bin/zsh -lc pwd'),+ codexCommandCompleted('item_1', '/bin/zsh -lc pwd', '/repo\n'),+ codexAgentMessage('item_2', finalText),+ codexTurnCompleted({ cached_input_tokens: 4, input_tokens: 10, output_tokens: 3 }),+ ],+ {+ params: {+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ },+ },+ );++ const finalAssistantId = mockCreateMessage.mock.calls.find(+ ([params]: any) => params.role === 'assistant',+ )![0].id;+ const finalRow = dbMessages.get(finalAssistantId);++ expect(contentAttempts.filter((id) => id === finalAssistantId)).toHaveLength(2);+ expect(finalRow.content).toBe(finalText);+ expect(finalRow.metadata.usage).toMatchObject({+ inputCachedTokens: 4,+ inputCacheMissTokens: 6,+ totalInputTokens: 10,+ totalOutputTokens: 3,+ totalTokens: 13,+ });+ } finally {+ consoleError.mockRestore();+ }+ });++ it('waits for queued Codex text reductions before forwarding terminal completion', async () => {+ const dbMessages = new Map<string, any>([+ ['ast-initial', { content: '', id: 'ast-initial', role: 'assistant' }],+ ]);+ const idCounter = { assistant: 0, tool: 0 };+ const finalText = 'ζεδΈζ‘ζζ¬εΏ ι‘»ε θΏε ₯ reducerοΌεη± terminal flush εεΊγ';+ let releaseFirstToolWrite!: () => void;+ let blockedFirstToolWrite = false;++ mockCreateMessage.mockImplementation(async (params: any) => {+ const id =+ params.id ??+ (params.role === 'assistant'+ ? `ast-new-${++idCounter.assistant}`+ : `tool-${++idCounter.tool}`);+ dbMessages.set(id, { ...params, content: params.content ?? '', id });+ return { id };+ });++ mockUpdateMessage.mockImplementation(async (id: string, val: any) => {+ if (val.tools && !blockedFirstToolWrite) {+ blockedFirstToolWrite = true;+ await new Promise<void>((resolve) => {+ releaseFirstToolWrite = resolve;+ });+ }++ const previous = dbMessages.get(id) ?? { content: '', id };+ dbMessages.set(id, {+ ...previous,+ ...val,+ metadata: {+ ...previous.metadata,+ ...val.metadata,+ },+ });+ return { success: true };+ });++ const updateTopicStatus = vi.fn();+ const store = createMockStore({+ activeTopicId: 'topic-1',+ updateTopicStatus,+ });+ const get = vi.fn(() => store);+ let resolveSendPrompt!: () => void;+ mockSendPrompt.mockReturnValue(+ new Promise<void>((resolve) => {+ resolveSendPrompt = resolve;+ }),+ );++ const executorPromise = executeHeterogeneousAgent(get, {+ ...defaultParams,+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ });+ await flush();++ ipc.emitRawLine('ipc-sess-1', codexThreadStarted());+ ipc.emitRawLine('ipc-sess-1', codexTurnStarted());+ ipc.emitRawLine('ipc-sess-1', codexAgentMessage('item_0', 'ε θ·δΈδΈͺε½δ»€γ'));+ ipc.emitRawLine('ipc-sess-1', codexCommandStarted('item_1', '/bin/zsh -lc pwd'));+ ipc.emitRawLine('ipc-sess-1', codexCommandCompleted('item_1', '/bin/zsh -lc pwd', '/repo\n'));+ ipc.emitRawLine('ipc-sess-1', codexAgentMessage('item_2', finalText));+ ipc.emitRawLine(+ 'ipc-sess-1',+ codexTurnCompleted({ cached_input_tokens: 4, input_tokens: 10, output_tokens: 3 }),+ );+ ipc.emitComplete('ipc-sess-1');+ await flush();++ const handlerSpy = vi.mocked(createGatewayEventHandler).mock.results[0]!.value as ReturnType<+ typeof vi.fn+ >;+ expect(updateTopicStatus).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'active', topicId: 'topic-1' }),+ );+ expect(+ handlerSpy.mock.calls.some(([event]: any[]) => event?.type === 'agent_runtime_end'),+ ).toBe(false);++ releaseFirstToolWrite();+ await flush();+ resolveSendPrompt();+ await executorPromise;+ await flush();++ const finalAssistantId = mockCreateMessage.mock.calls.find(+ ([params]: any) => params.role === 'assistant',+ )![0].id;+ expect(dbMessages.get(finalAssistantId)?.content).toBe(finalText);+ expect(+ handlerSpy.mock.calls.some(([event]: any[]) => event?.type === 'agent_runtime_end'),+ ).toBe(true);+ });});// ββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -4251,7 +4691,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {// Characterize the actual behavior: onComplete's non-error branch still// writes 'active' while the user is viewing (the abort gate only guards- // the notification + drain, not the writeTopicStatus('active') call on a+ // the notification + follow-up drain, not the writeTopicStatus('active') call on a// clean stream end).expect(updateTopicStatus).toHaveBeenCalledWith(expect.objectContaining({@@ -4261,7 +4701,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {);});- // ββ 5. stuck-spinner regression: status reset must not wait on the drain ββ+ // ββ 5. stuck-spinner regression: status reset must not wait on queued persistence ββit('resets topic status even when the persist queue never drains', async () => {// A DB write that never settles β mirrors a dropped desktop-IPC reply. It// strands the executor's persistQueue, which onComplete used to `await`@@ -4291,7 +4731,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {await flush();// A tool batch enqueues an awaited `updateMessage` onto persistQueue β the- // hanging write above stalls the queue before the terminal drain.+ // hanging write above stalls the queue before terminal completion.ipc.emitRawLine('ipc-sess-1', ccInit());ipc.emitRawLine('ipc-sess-1', ccToolUse('msg_01', 'toolu_1', 'Read', { file_path: '/a' }));ipc.emitRawLine('ipc-sess-1', ccToolResult('toolu_1', 'file content'));@@ -4300,7 +4740,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {await flush();// The fix: status is reset synchronously at the top of onComplete, BEFORE- // the (now stalled + bounded) drain β so the spinner clears to 'active'+ // the stalled queue wait β so the spinner clears to 'active'// even though the persist queue is still pending on the hanging write.expect(updateTopicStatus).toHaveBeenCalledWith(expect.objectContaining({ status: 'active', topicId: 'topic-1' }),@@ -4312,5 +4752,59 @@ describe('heterogeneousAgentExecutor DB persistence', () => {await executorPromise;await flush();});++ it('bounds clean terminal completion when the persist queue never drains', async () => {+ vi.useFakeTimers();+ const eventHandler = vi.fn();+ vi.mocked(createGatewayEventHandler).mockReturnValueOnce(eventHandler);++ // Never settles: mirrors a lost desktop IPC/network reply in the message+ // write path. Terminal must still forward and complete the operation after+ // the bounded drain timeout.+ mockUpdateMessage.mockReturnValue(new Promise<void>(() => {}));++ const updateTopicStatus = vi.fn();+ const store = createMockStore({+ activeTopicId: 'topic-1',+ updateTopicStatus,+ });+ const get = vi.fn(() => store);++ let resolveSendPrompt!: () => void;+ mockSendPrompt.mockReturnValue(+ new Promise<void>((resolve) => {+ resolveSendPrompt = resolve;+ }),+ );++ const executorPromise = executeHeterogeneousAgent(get, defaultParams);+ await flushFakeTimers();++ ipc.emitRawLine('ipc-sess-1', ccInit());+ ipc.emitRawLine('ipc-sess-1', ccToolUse('msg_01', 'toolu_1', 'Read', { file_path: '/a' }));+ ipc.emitRawLine('ipc-sess-1', ccToolResult('toolu_1', 'file content'));+ ipc.emitRawLine('ipc-sess-1', ccResult());+ ipc.emitComplete('ipc-sess-1');+ await flushFakeTimers();++ expect(updateTopicStatus).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'active', topicId: 'topic-1' }),+ );+ expect(eventHandler).not.toHaveBeenCalledWith(+ expect.objectContaining({ type: 'agent_runtime_end' }),+ );++ await vi.advanceTimersByTimeAsync(10_000);+ await Promise.resolve();++ expect(eventHandler).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'agent_runtime_end' }),+ );+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');++ resolveSendPrompt();+ await flushFakeTimers();+ await executorPromise;+ });});});diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 5b53f4c5b80..cd5d08a5713 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -46,7 +46,11 @@ import {setHeteroSessionIdForWorkingDirectory,} from '@/helpers/heteroSessionByWorkingDirectory';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';-import { messageService } from '@/services/message';+import {+ type MessageBatchOperation,+ type MessageQueryContext,+ messageService,+} from '@/services/message';import { threadService } from '@/services/thread';import { topicSelectors } from '@/store/chat/selectors';import {@@ -199,28 +203,6 @@ const isRecoverableResumeError = ();};-/**- * How long the terminal callbacks wait for the persist queue to drain before- * proceeding regardless. Bounds the one place a completed run could otherwise- * hang forever β a queued DB write whose desktop-IPC reply never arrives β so op- * completion, the terminal forward, and the desktop notification still run.- * Topic status is reset ahead of this wait, so the sidebar spinner never depends- * on it at all.- */-const PERSIST_DRAIN_TIMEOUT = 10_000;--/** Await `queue`, but give up after `ms`; pending work is abandoned, not cancelled. */-const drainWithTimeout = (queue: Promise<unknown>, ms: number): Promise<void> =>- new Promise<void>((resolve) => {- const timer = setTimeout(resolve, ms);- void Promise.resolve(queue)- .catch(() => {})- .finally(() => {- clearTimeout(timer);- resolve();- });- });-export interface HeterogeneousAgentExecutorParams {assistantMessageId: string;context: ConversationContext;@@ -409,6 +391,210 @@ const persistToolResult = async (}};+const HETERO_MESSAGE_WRITE_BATCH_IDLE_MS = 5_000;+const HETERO_MESSAGE_WRITE_BATCH_MAX_OPS = 50;+const HETERO_TERMINAL_PERSIST_DRAIN_TIMEOUT_MS = 10_000;++type MessageUpdateOperation = Extract<MessageBatchOperation, { type: 'updateMessage' }>;+type ToolMessageUpdateOperation = Extract<MessageBatchOperation, { type: 'updateToolMessage' }>;++type QueuedMessageWriteOperation =+ | (Extract<MessageBatchOperation, { type: 'createMessage' }> & {+ ctx?: never;+ onFailure?: (error: unknown) => void;+ })+ | (MessageUpdateOperation & {+ ctx?: MessageQueryContext;+ onFailure?: (error: unknown) => void;+ })+ | (ToolMessageUpdateOperation & {+ ctx?: MessageQueryContext;+ onFailure?: (error: unknown) => void;+ });++const mergeMessageUpdateValue = (+ previous: MessageUpdateOperation['value'],+ next: MessageUpdateOperation['value'],+): MessageUpdateOperation['value'] => {+ const metadata =+ previous.metadata || next.metadata+ ? {+ ...(previous.metadata as Record<string, any> | undefined),+ ...(next.metadata as Record<string, any> | undefined),+ }+ : undefined;++ return {+ ...previous,+ ...next,+ ...(metadata ? { metadata } : {}),+ };+};++const waitForPersistQueue = async (+ queue: Promise<void>,+ label: string,+ timeoutMs = HETERO_TERMINAL_PERSIST_DRAIN_TIMEOUT_MS,+): Promise<boolean> => {+ let timeoutId: ReturnType<typeof setTimeout> | undefined;++ const result = await Promise.race<+ { error: unknown; status: 'rejected' } | { status: 'resolved' } | { status: 'timeout' }+ >([+ queue.then(+ () => ({ status: 'resolved' }),+ (error) => ({ error, status: 'rejected' }),+ ),+ new Promise<{ status: 'timeout' }>((resolve) => {+ timeoutId = setTimeout(() => resolve({ status: 'timeout' }), timeoutMs);+ }),+ ]);++ if (timeoutId) clearTimeout(timeoutId);++ if (result.status === 'rejected') throw result.error;+ if (result.status === 'timeout') {+ console.warn(+ `[HeterogeneousAgent] persistQueue did not drain within ${timeoutMs}ms (${label}); continuing terminal flow.`,+ );+ return false;+ }++ return true;+};++const createMessageWriteBatcher = (deps: {+ batchMutate?: (operations: MessageBatchOperation[]) => Promise<any>;+ createMessage: typeof messageService.createMessage;+ updateMessage: typeof messageService.updateMessage;+ updateToolMessage: typeof messageService.updateToolMessage;+}) => {+ let operations: QueuedMessageWriteOperation[] = [];+ let flushChain: Promise<void> = Promise.resolve();+ let idleTimer: ReturnType<typeof setTimeout> | undefined;++ const clearIdleTimer = () => {+ if (!idleTimer) return;+ clearTimeout(idleTimer);+ idleTimer = undefined;+ };++ const notifyFailure = (operation: QueuedMessageWriteOperation, error: unknown) => {+ operation.onFailure?.(error);+ };++ const runIndividual = async (operation: QueuedMessageWriteOperation) => {+ if (operation.type === 'createMessage') {+ await deps.createMessage(operation.message);+ return;+ }++ if (operation.type === 'updateToolMessage') {+ const result = await deps.updateToolMessage(operation.id, operation.value, operation.ctx);+ if (result?.success === false) notifyFailure(operation, result);+ return;+ }++ const result = await deps.updateMessage(operation.id, operation.value, operation.ctx);+ if (result?.success === false) notifyFailure(operation, result);+ };++ const runBatch = async (batch: QueuedMessageWriteOperation[]) => {+ if (deps.batchMutate) {+ try {+ const result = await deps.batchMutate(batch as unknown as MessageBatchOperation[]);+ const failedIndexes = new Set<number>(+ (result?.results ?? [])+ .filter((item: { index: number; success: boolean }) => !item.success)+ .map((item: { index: number }) => item.index),+ );++ if (result?.success === false && failedIndexes.size === 0) {+ for (const [index] of batch.entries()) failedIndexes.add(index);+ }++ for (const index of failedIndexes) {+ notifyFailure(batch[index], result);+ }+ return;+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to flush message write batch:', err);+ for (const operation of batch) notifyFailure(operation, err);+ return;+ }+ }++ for (const operation of batch) {+ try {+ await runIndividual(operation);+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to flush message write operation:', err);+ notifyFailure(operation, err);+ }+ }+ };++ const flush = async (_reason: string) => {+ clearIdleTimer();+ flushChain = flushChain.then(async () => {+ while (operations.length > 0) {+ const batch = operations;+ operations = [];+ await runBatch(batch);+ }+ });+ await flushChain;+ };++ const scheduleIdleFlush = () => {+ clearIdleTimer();+ idleTimer = setTimeout(() => {+ void flush('idle');+ }, HETERO_MESSAGE_WRITE_BATCH_IDLE_MS);+ };++ const enqueue = (operation: QueuedMessageWriteOperation) => {+ const last = operations.at(-1);+ if (+ last?.type === 'updateMessage' &&+ operation.type === 'updateMessage' &&+ last.id === operation.id &&+ !last.onFailure &&+ !operation.onFailure+ ) {+ last.value = mergeMessageUpdateValue(last.value, operation.value);+ } else {+ operations.push(operation);+ }++ if (operations.length >= HETERO_MESSAGE_WRITE_BATCH_MAX_OPS) {+ void flush('max-ops');+ } else {+ scheduleIdleFlush();+ }+ };++ return {+ enqueueCreateMessage: (+ message: Extract<MessageBatchOperation, { type: 'createMessage' }>['message'],+ onFailure?: (error: unknown) => void,+ ) => enqueue({ message, onFailure, type: 'createMessage' }),+ enqueueToolMessageUpdate: (+ id: string,+ value: ToolMessageUpdateOperation['value'],+ ctx?: MessageQueryContext,+ onFailure?: (error: unknown) => void,+ ) => enqueue({ ctx, id, onFailure, type: 'updateToolMessage', value }),+ enqueueUpdateMessage: (+ id: string,+ value: MessageUpdateOperation['value'],+ ctx?: MessageQueryContext,+ onFailure?: (error: unknown) => void,+ ) => enqueue({ ctx, id, onFailure, type: 'updateMessage', value }),+ flush,+ };+};+/*** Execute a prompt via an external agent CLI.*@@ -441,9 +627,9 @@ export const executeHeterogeneousAgent = async (const adapterType = resolveAdapterType(heterogeneousProvider);// Shared run lifecycle β hetero owns its terminal lifecycle here- // (the desktop notification via `afterRunComplete`); the queue drain + op+ // (the desktop notification via `afterRunComplete`); queued persistence + op// completion stay in this executor's flow because the resume-session-id save- // must run before the drain. `parentMessage*` are unused for non-client.+ // must run before queued follow-up sends. `parentMessage*` are unused for non-client.const runScope: RunScope = context.scope === 'sub_agent' ? 'sub_agent' : 'top_level';const runLifecycle = buildRunLifecycle(get, {context,@@ -456,7 +642,7 @@ export const executeHeterogeneousAgent = async (// Create the unified event handler (same one Gateway uses). `runtimeType:// 'hetero'` keeps the handler to per-event message reconciliation only β this- // executor owns the terminal lifecycle (notification + queue drain), so the+ // executor owns the terminal lifecycle (notification + queued follow-up sends), so the// handler must NOT double-notify or drain. It still completes the op + marks// unread on a clean terminal (the legacy reconciliation path this flow relies on).const eventHandler = createGatewayEventHandler(get, {@@ -587,6 +773,16 @@ export const executeHeterogeneousAgent = async (string,{ content?: string; messageId: string; reasoning?: string }>();+ /**+ * Renderer-local retry for main assistant durable flushes. Main `streamContent`+ * is live-UI only, so a transient `persistAssistant` failure would otherwise+ * be lost once the reducer clears `accContent` on terminal.+ */+ const pendingMainFlush = new Map<string, Record<string, any>>();+ const pendingMainCreates = new Map<+ string,+ Extract<MessageBatchOperation, { type: 'createMessage' }>['message']+ >();/** Serializes async persist operations so ordering is stable. */let persistQueue: Promise<void> = Promise.resolve();/**@@ -653,6 +849,42 @@ export const executeHeterogeneousAgent = async (workingDirectoryConfig: getPersistedWorkingDirectoryConfig(topicMetadata),});};+ let persistedResumeSessionId: string | undefined;+ let pendingResumeSessionId: string | undefined;+ let resumeSessionPersistQueue: Promise<void> = Promise.resolve();+ const persistResumeSessionId = (sessionId: string, source: string): Promise<void> => {+ const topicId = context.topicId ?? undefined;+ if (!topicId || !updateTopicMetadata) return resumeSessionPersistQueue;+ if (sessionId === persistedResumeSessionId || sessionId === pendingResumeSessionId) {+ return resumeSessionPersistQueue;+ }++ pendingResumeSessionId = sessionId;+ resumeSessionPersistQueue = resumeSessionPersistQueue+ .catch(() => {})+ .then(async () => {+ const topicMetadata = getTopicMetadataById(get(), topicId);+ await updateTopicMetadata(topicId, {+ heteroSessionId: sessionId,+ heteroSessionIdByWorkingDirectory: setHeteroSessionIdForWorkingDirectory(+ topicMetadata,+ workingDirectory,+ sessionId,+ ),+ workingDirectory: workingDirectory ?? '',+ workingDirectoryConfig: getPersistedWorkingDirectoryConfig(topicMetadata),+ });+ persistedResumeSessionId = sessionId;+ })+ .catch((err) => {+ console.error(`[HeterogeneousAgent] Failed to persist resume session id (${source}):`, err);+ })+ .finally(() => {+ if (pendingResumeSessionId === sessionId) pendingResumeSessionId = undefined;+ });++ return resumeSessionPersistQueue;+ };const writeTopicStatus = (status: ChatTopicStatus): void => {if (!context.topicId) return;void get().updateTopicStatus?.({@@ -662,6 +894,50 @@ export const executeHeterogeneousAgent = async (topicId: context.topicId,});};+ const updateMessageOrThrow = async (messageId: string, update: Record<string, any>) => {+ const result = await messageService.updateMessage(messageId, update, {+ agentId: context.agentId,+ topicId: context.topicId,+ });+ if (result?.success === false) {+ throw new Error(`messageService.updateMessage returned success=false for ${messageId}`);+ }+ };+ const messageWriteCtx: MessageQueryContext = {+ agentId: context.agentId,+ topicId: context.topicId,+ };+ const messageWriteBatcher = createMessageWriteBatcher({+ batchMutate: (+ messageService as { batchMutate?: (operations: MessageBatchOperation[]) => Promise<any> }+ ).batchMutate,+ createMessage: messageService.createMessage,+ updateMessage: messageService.updateMessage,+ updateToolMessage: messageService.updateToolMessage,+ });+ const enqueueMainToolResult = (+ toolCallId: string,+ content: string,+ isError: boolean,+ pluginState?: Record<string, any>,+ ) => {+ const toolMsgId = toolMsgIdByCallId.get(toolCallId);+ if (!toolMsgId) {+ console.warn('[HeterogeneousAgent] tool_result for unknown toolCallId:', toolCallId);+ return;+ }++ messageWriteBatcher.enqueueToolMessageUpdate(+ toolMsgId,+ {+ content,+ pluginError: isError ? { message: content } : undefined,+ pluginState,+ },+ messageWriteCtx,+ (err) => console.error('[HeterogeneousAgent] Failed to update tool message content:', err),+ );+ };const retryWithoutResume = (error: unknown): boolean => {if (resumeFallbackTriggered ||@@ -1005,28 +1281,21 @@ export const executeHeterogeneousAgent = async (case 'createAssistant': {const createMetadata: Record<string, any> = { ...heteroProvenance(intent.mainMessageId) };if (intent.signal) createMetadata.signal = intent.signal;- try {- await messageService.createMessage({- agentId: intent.agentId ?? context.agentId,- content: '',- id: intent.messageId,- ...(Object.keys(createMetadata).length > 0 ? { metadata: createMetadata } : {}),- model: intent.model,- parentId: intent.parentId,- provider: intent.provider,- role: 'assistant',- topicId: intent.topicId ?? context.topicId ?? undefined,- } as any);- } catch (err) {- // Rethrow so `reduceAndApplyMain` skips the state commit β DO NOT- // advance `currentAssistantId` to a row that was never created, or- // every later content/tool/result write (and the gateway handler's- // switch) would target a missing assistant and be lost. Keeping the- // prior state lets the next event re-derive against the still-valid- // current assistant. Mirrors the subagent createMessage path.+ const messageToCreate = {+ agentId: intent.agentId ?? context.agentId,+ content: '',+ id: intent.messageId,+ ...(Object.keys(createMetadata).length > 0 ? { metadata: createMetadata } : {}),+ model: intent.model,+ parentId: intent.parentId,+ provider: intent.provider,+ role: 'assistant',+ topicId: intent.topicId ?? context.topicId ?? undefined,+ } as any;+ messageWriteBatcher.enqueueCreateMessage(messageToCreate, (err) => {console.error('[HeterogeneousAgent] Failed to create step assistant:', err);- throw err;- }+ pendingMainCreates.set(intent.messageId, messageToCreate);+ });// Associate so cancellation / cleanup tracks the new step's message.get().associateMessageWithOperation(intent.messageId, operationId);return;@@ -1041,14 +1310,18 @@ export const executeHeterogeneousAgent = async (if (intent.provider) update.provider = intent.provider;if (intent.metadata) update.metadata = intent.metadata;if (Object.keys(update).length === 0) return;- await messageService- .updateMessage(intent.messageId, update, {- agentId: context.agentId,- topicId: context.topicId,- })- .catch((err) =>- console.error('[HeterogeneousAgent] Failed to flush main assistant:', err),- );+ messageWriteBatcher.enqueueUpdateMessage(+ intent.messageId,+ update,+ messageWriteCtx,+ (err) => {+ console.error('[HeterogeneousAgent] Failed to flush main assistant:', err);+ pendingMainFlush.set(intent.messageId, {+ ...pendingMainFlush.get(intent.messageId),+ ...update,+ });+ },+ );return;}@@ -1079,63 +1352,52 @@ export const executeHeterogeneousAgent = async (// Phase 1: pre-register assistant.tools[] (no result_msg_id yet) so the// conversation-flow parser finds matching ids the moment tool rows land.- await messageService- .updateMessage(intent.assistantMessageId, buildUpdate(false), {- agentId: context.agentId,- topicId: context.topicId,- })- .catch((err) =>- console.error('[HeterogeneousAgent] Failed to pre-register main tools:', err),- );+ messageWriteBatcher.enqueueUpdateMessage(+ intent.assistantMessageId,+ buildUpdate(false),+ messageWriteCtx,+ (err) => console.error('[HeterogeneousAgent] Failed to pre-register main tools:', err),+ );// Phase 2: create rows for new tools with their pre-allocated ids and// register the global lookup so a later tool_result resolves.for (const x of intent.tools) {if (!x.isNew) continue;const toolMetadata = heteroProvenance(mainState.currentMainMessageId);- try {- await messageService.createMessage({- agentId: context.agentId,- content: '',- id: x.toolMessageId,- ...(Object.keys(toolMetadata).length > 0 ? { metadata: toolMetadata } : {}),- parentId: intent.assistantMessageId,- plugin: {- apiName: x.payload.apiName,- arguments: x.payload.arguments,- identifier: x.payload.identifier,- type: x.payload.type as ChatToolPayload['type'],- },- role: 'tool',- tool_call_id: x.payload.id,- topicId: context.topicId ?? undefined,- } as any);- } catch (err) {- console.error('[HeterogeneousAgent] Failed to create main tool message:', err);- continue;- }+ messageWriteBatcher.enqueueCreateMessage({+ agentId: context.agentId,+ content: '',+ id: x.toolMessageId,+ ...(Object.keys(toolMetadata).length > 0 ? { metadata: toolMetadata } : {}),+ parentId: intent.assistantMessageId,+ plugin: {+ apiName: x.payload.apiName,+ arguments: x.payload.arguments,+ identifier: x.payload.identifier,+ type: x.payload.type as ChatToolPayload['type'],+ },+ role: 'tool',+ tool_call_id: x.payload.id,+ topicId: context.topicId ?? undefined,+ } as any);toolMsgIdByCallId.set(x.payload.id, x.toolMessageId);}// Phase 3: backfill result_msg_id on assistant.tools[].- await messageService- .updateMessage(intent.assistantMessageId, buildUpdate(true), {- agentId: context.agentId,- topicId: context.topicId,- })- .catch((err) =>- console.error('[HeterogeneousAgent] Failed to finalize main tools:', err),- );+ messageWriteBatcher.enqueueUpdateMessage(+ intent.assistantMessageId,+ buildUpdate(true),+ messageWriteCtx,+ (err) => console.error('[HeterogeneousAgent] Failed to finalize main tools:', err),+ );return;}case 'resolveToolResult': {- await persistToolResult(+ enqueueMainToolResult(intent.toolCallId,intent.content,intent.isError,- toolMsgIdByCallId,- context,intent.pluginState,);return;@@ -1152,12 +1414,9 @@ export const executeHeterogeneousAgent = async (...(intent.model && { model: intent.model }),...(intent.provider && { provider: intent.provider }),};- await messageService- .updateMessage(intent.messageId, update, {- agentId: context.agentId,- topicId: context.topicId,- })- .catch((err) => console.error('[HeterogeneousAgent] Failed to record main usage:', err));+ messageWriteBatcher.enqueueUpdateMessage(intent.messageId, update, messageWriteCtx, (err) =>+ console.error('[HeterogeneousAgent] Failed to record main usage:', err),+ );return;}@@ -1190,31 +1449,9 @@ export const executeHeterogeneousAgent = async (// server handler). Stable per run; the copy makes a mid-topic fork visible.if (event.type === 'stream_start') {const sid = (event.data as { sessionId?: string } | undefined)?.sessionId;- if (typeof sid === 'string' && sid.length > 0 && sid !== heteroSessionId) {+ if (typeof sid === 'string' && sid.length > 0) {heteroSessionId = sid;- // Persist the resume token the MOMENT the CLI reports it β but only on- // a FRESH run. The success-path write below only runs when `sendPrompt`- // resolves; a rate-limit / API error rejects it and jumps straight to- // `catch`, so without this early write the token is lost and the next- // turn starts a fresh session (the `tpc_k9pUn1yf151P` regression). On a- // `--resume` run the id is already in metadata (it's where- // `resumeSessionId` came from), so skip β a failed resume is cleaned up- // by the retry/clear path, not re-stamped here. Fire-and-forget +- // guarded so it never throws past the persistQueue chain nor delays- // event processing; the success path re-writes it on completion.- if (!resumeSessionId && context.topicId && updateTopicMetadata) {- const topicMetadata = getTopicMetadataById(get(), context.topicId);- updateTopicMetadata(context.topicId, {- heteroSessionId: sid,- heteroSessionIdByWorkingDirectory: setHeteroSessionIdForWorkingDirectory(- topicMetadata,- workingDirectory,- sid,- ),- }).catch((err) =>- console.error('[HeterogeneousAgent] Failed to early-persist resume session id:', err),- );- }+ void persistResumeSessionId(sid, 'stream_start');}}@@ -1479,7 +1716,10 @@ export const executeHeterogeneousAgent = async ((event.data as { toolMessageIds?: unknown } | undefined)?.toolMessageIds !== undefined);if (pendingStepTransition || triggersFetchAndReplace) {- persistQueue = persistQueue.then(() => {+ persistQueue = persistQueue.then(async () => {+ if (triggersFetchAndReplace) {+ await messageWriteBatcher.flush('before-fetch-replace');+ }eventHandler(event);});} else {@@ -1496,12 +1736,12 @@ export const executeHeterogeneousAgent = async (const isErrorTerminal = deferredTerminalEvent?.type === 'error';- // Reset the sidebar "running" status BEFORE draining the persist queue.+ // Reset the sidebar "running" status BEFORE awaiting the persist queue.// Topic status is independent of message persistence, so a stalled queue// (e.g. a subagent-heavy run whose final DB write never settles) must not// strand the topic spinning after the CLI has exited β the stuck-spinner// this guards against. Content persistence + the terminal forward still- // wait for the (now bounded) drain below.+ // wait for queued reducer state so terminal never flushes stale content.{const reason = (deferredTerminalEvent?.data as { reason?: string } | undefined)?.reason;if (isErrorTerminal) {@@ -1522,13 +1762,6 @@ export const executeHeterogeneousAgent = async (}}- // Bounded: a persist that never settles must not block op completion,- // the terminal forward, or the completion notification below.- await drainWithTimeout(persistQueue, PERSIST_DRAIN_TIMEOUT);-- // Snapshot the final content BEFORE the terminal reduce resets the- // accumulator β used for the completion notification body below.- const finalContent = mainState.accContent;const terminalEvent: AgentStreamEvent = deferredTerminalEvent ?? {data: {},operationId,@@ -1536,6 +1769,7 @@ export const executeHeterogeneousAgent = async (timestamp: Date.now(),type: 'agent_runtime_end',};+ let finalContent = '';// Reduce the terminal event through the shared coordinator: it flushes// the last step's content/reasoning/model (with echo suppression), and@@ -1543,36 +1777,65 @@ export const executeHeterogeneousAgent = async (// (full error UI). It also drains any subagent run that never saw its// parent tool_result (CLI crashed mid-subagent, or the spawn's// tool_result arrived after the stream closed), flushing each run's- // trailing content and marking the thread Active. `completeOperation`- // does not cascade to child sub-ops, so the main-error path running- // before the drain still lets each subagent op finalize.- await reduceAndApplyMain(terminalEvent);-- // Replay any subagent flush that failed transiently mid-stream, pinned- // to its original in-thread assistant (NOT the terminal row).- for (const [threadId, pending] of pendingSubagentFlush) {- const update: Record<string, any> = {};- if (pending.content) update.content = pending.content;- if (pending.reasoning) update.reasoning = { content: pending.reasoning };- if (Object.keys(update).length === 0) continue;- try {- await messageService.updateMessage(pending.messageId, update, {- agentId: context.agentId,- topicId: context.topicId,- });- subagentThreads.get(threadId)?.stream.update(pending.messageId, update);- } catch (err) {- console.error('[HeterogeneousAgent] Failed to replay subagent flush:', err);+ // trailing content and marking the thread Active. Queue this terminal+ // reduce behind every prior stream event: content chunks are live-UI+ // only until the reducer accumulates them, so a timeout-based drain+ // would let terminal flush read a stale `mainState`.+ persistQueue = persistQueue.then(async () => {+ // Snapshot the final content BEFORE terminal reduce resets the+ // accumulator β used for the completion notification body below.+ finalContent = mainState.accContent;+ await reduceAndApplyMain(terminalEvent);+ await messageWriteBatcher.flush('terminal');+ });+ const queueDrained = await waitForPersistQueue(persistQueue, 'terminal');++ if (queueDrained) {+ for (const [messageId, messageToCreate] of pendingMainCreates) {+ try {+ await messageService.createMessage(messageToCreate);+ pendingMainCreates.delete(messageId);+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to replay main assistant create:', err);+ }+ }++ for (const [messageId, update] of pendingMainFlush) {+ try {+ await updateMessageOrThrow(messageId, update);+ pendingMainFlush.delete(messageId);+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to replay main assistant flush:', err);+ }+ }++ // Replay any subagent flush that failed transiently mid-stream, pinned+ // to its original in-thread assistant (NOT the terminal row).+ for (const [threadId, pending] of pendingSubagentFlush) {+ const update: Record<string, any> = {};+ if (pending.content) update.content = pending.content;+ if (pending.reasoning) update.reasoning = { content: pending.reasoning };+ if (Object.keys(update).length === 0) continue;+ try {+ await messageService.updateMessage(pending.messageId, update, {+ agentId: context.agentId,+ topicId: context.topicId,+ });+ subagentThreads.get(threadId)?.stream.update(pending.messageId, update);+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to replay subagent flush:', err);+ }}+ pendingSubagentFlush.clear();}- pendingSubagentFlush.clear();if (!isErrorTerminal) {- // Topic status was already reset ahead of the drain (top of+ // Topic status was already reset ahead of the queue (top of// onComplete); forward the deferred terminal only so the handler runs// the final fetchAndReplaceMessages + completeOperation against the// now-persisted state.eventHandler(terminalEvent);+ if (!queueDrained) get().completeOperation(operationId);}// Signal completion to the user β dock badge + (window-hidden) notification,@@ -1598,36 +1861,36 @@ export const executeHeterogeneousAgent = async (if (retryWithoutResume(error)) return;completed = true;- // Reset status ahead of the drain (see onComplete) so a stalled queue+ // Reset status ahead of the queue (see onComplete) so a stalled queue// can't strand the spinner; persistTerminalError below re-asserts 'failed'// with the full error UI.writeTopicStatus(isAborted() ? 'active' : 'failed');- await drainWithTimeout(persistQueue, PERSIST_DRAIN_TIMEOUT);-const deferredMessageError =deferredTerminalEvent?.type === 'error'? toHeterogeneousAgentMessageError(deferredTerminalEvent.data, adapterType): undefined;const messageError =deferredMessageError || toHeterogeneousAgentMessageError(error, adapterType);- const shouldClearTerminalErrorContent = shouldSuppressTerminalErrorEcho(- mainState.accContent,- messageError,- );+ let shouldClearTerminalErrorContent = false;- if (mainState.accContent && !shouldClearTerminalErrorContent) {- await messageService- .updateMessage(+ persistQueue = persistQueue.then(async () => {+ shouldClearTerminalErrorContent = shouldSuppressTerminalErrorEcho(+ mainState.accContent,+ messageError,+ );++ if (mainState.accContent && !shouldClearTerminalErrorContent) {+ messageWriteBatcher.enqueueUpdateMessage(mainState.currentAssistantId,{ content: mainState.accContent },- {- agentId: context.agentId,- topicId: context.topicId,- },- )- .catch(console.error);- }+ messageWriteCtx,+ console.error,+ );+ }+ await messageWriteBatcher.flush('error');+ });+ await waitForPersistQueue(persistQueue, 'error');// If the error came from a user-initiated cancel (SIGINT β non-zero// exit), don't surface it as a runtime error toast β the operation is@@ -1676,24 +1939,13 @@ export const executeHeterogeneousAgent = async (.getSessionInfo(agentSessionId).catch(() => undefined);if (sessionInfo?.agentSessionId && context.topicId) {- const topicMetadata = getTopicMetadataById(get(), context.topicId);- // Best-effort: a rejected- // metadata save must NOT throw past the queue drain below β guarding the- // await here keeps the resume-id persistence from blocking the follow-up- // send. The save still runs BEFORE the drain so the next turn's- // `resolveHeteroResume` reads the just-finished session id.- await updateTopicMetadata?.(context.topicId, {- heteroSessionId: sessionInfo.agentSessionId,- heteroSessionIdByWorkingDirectory: setHeteroSessionIdForWorkingDirectory(- topicMetadata,- workingDirectory,- sessionInfo.agentSessionId,- ),- workingDirectory: workingDirectory ?? '',- workingDirectoryConfig: getPersistedWorkingDirectoryConfig(topicMetadata),- }).catch((err) =>- console.error('[HeterogeneousAgent] Failed to persist resume session id:', err),- );+ // Best-effort: a rejected metadata save must NOT throw past the queue+ // drain below β guarding the await here keeps the resume-id persistence+ // from blocking the follow-up send. The same helper is also triggered as+ // soon as stream_start reports a session id, so non-zero CLI exits still+ // preserve resume context; this success-path await only ensures queued+ // follow-up sends read the just-finished id.+ await persistResumeSessionId(sessionInfo.agentSessionId, 'success-path');}// βββ Drain queued messages after a successful CC turn βββ@@ -1782,7 +2034,7 @@ export const executeHeterogeneousAgent = async (// before it landed), the status reset above never happened. The CLI has// exited by the time this linear path resolves, so a topic still persisted// as 'running' would spin forever β reconcile it. Both terminal callbacks- // reset status ahead of their drain, so reaching here still 'running' means+ // reset status ahead of their queue wait, so reaching here still 'running' means// neither ran. Skipped on the resume-retry path, whose recursive run owns// the lifecycle.if (!resumeFallbackTriggered && context.topicId) {