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: wait for late hetero terminal events (#16907)

Arvin Xu8791450bc3ab
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index 0f9144d17d7..622fe8c404e 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -109,6 +109,10 @@ const CODEX_STDERR_STATUS_LINE = 'Reading prompt from stdin...';
const CODEX_WARN_LOG_PATTERN = /^\d{4}-\d{2}-\d{2}T\S+\s+WARN\s+/;
const CODEX_LOG_PATTERN = /^\d{4}-\d{2}-\d{2}T\S+\s+(?:DEBUG|ERROR|INFO|TRACE|WARN)\s+/;
const CLI_ERROR_LINE_PATTERN = /^(?:error:|Error:|Usage:)/;
+const HETERO_SESSION_COMPLETE_GRACE_MS = 1_000;
+
+const waitForHeteroSessionCompleteGrace = () =>
+ new Promise<void>((resolve) => setTimeout(resolve, HETERO_SESSION_COMPLETE_GRACE_MS));
// ─── IPC types ───
@@ -1277,6 +1281,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
signal,
});
await this.flushCliTrace(traceSession);
+ await waitForHeteroSessionCompleteGrace();
logger.info('Agent process exited:', { code, sessionId: session.sessionId, signal });
session.process = undefined;
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 32d05748902..e646cfd20f7 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -1116,6 +1116,81 @@ describe('HeterogeneousAgentCtr', () => {
const toolEnds = events.filter((b) => (b.data as any)?.event?.type === 'tool_end');
expect(toolEnds.length).toBeGreaterThan(0);
});
+
+ it('delivers late final Codex stdout chunks BEFORE heteroAgentSessionComplete', async () => {
+ const threadStarted = `${JSON.stringify({ thread_id: 't1', type: 'thread.started' })}\n`;
+ const turnStarted = `${JSON.stringify({ type: 'turn.started' })}\n`;
+ const finalMessage = `${JSON.stringify({
+ item: {
+ id: 'item_103',
+ text: 'Final report after late stdout.',
+ type: 'agent_message',
+ },
+ type: 'item.completed',
+ })}\n`;
+ const turnCompleted = `${JSON.stringify({
+ type: 'turn.completed',
+ usage: { input_tokens: 10, output_tokens: 5 },
+ })}\n`;
+
+ const proc = new EventEmitter() as any;
+ const stdout = new PassThrough();
+ const stderr = new PassThrough();
+ proc.stdout = stdout;
+ proc.stderr = stderr;
+ proc.stdin = {
+ end: vi.fn(),
+ write: vi.fn((_chunk: any, cb?: () => void) => {
+ cb?.();
+ return true;
+ }),
+ };
+ proc.kill = vi.fn();
+ proc.killed = false;
+ proc.__start = () => {
+ setImmediate(() => {
+ stdout.write(threadStarted);
+ stdout.write(turnStarted);
+ stderr.end();
+ proc.emit('exit', 0);
+ setImmediate(() => {
+ stdout.write(finalMessage);
+ stdout.write(turnCompleted);
+ stdout.end();
+ });
+ });
+ };
+ nextFakeProc = proc;
+
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({ agentType: 'codex', command: 'codex' });
+ const sendStartedAt = Date.now();
+ await ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId });
+ const sendDurationMs = Date.now() - sendStartedAt;
+
+ const completeIdx = broadcasts.findIndex((b) => b.channel === 'heteroAgentSessionComplete');
+ const finalChunkIdx = broadcasts.findIndex(
+ (b) =>
+ b.channel === 'heteroAgentEvent' &&
+ (b.data as any)?.event?.type === 'stream_chunk' &&
+ (b.data as any)?.event?.data?.content === 'Final report after late stdout.',
+ );
+ const runtimeEndIdx = broadcasts.findIndex(
+ (b) =>
+ b.channel === 'heteroAgentEvent' &&
+ (b.data as any)?.event?.type === 'agent_runtime_end',
+ );
+
+ expect(completeIdx).toBeGreaterThan(-1);
+ expect(finalChunkIdx).toBeGreaterThan(-1);
+ expect(runtimeEndIdx).toBeGreaterThan(-1);
+ expect(finalChunkIdx).toBeLessThan(completeIdx);
+ expect(runtimeEndIdx).toBeLessThan(completeIdx);
+ expect(sendDurationMs).toBeGreaterThanOrEqual(900);
+ });
});
describe('app-quit cleanup of AskUserQuestion temp configs ()', () => {
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 f0b9cd72133..00a63bf2dd6 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -121,7 +121,9 @@ function setupIpcCapture() {
on: vi.fn((channel: string, handler: (...args: any[]) => void) => {
listeners.set(channel, handler);
}),
- removeListener: vi.fn(),
+ removeListener: vi.fn((channel: string, handler: (...args: any[]) => void) => {
+ if (listeners.get(channel) === handler) listeners.delete(channel);
+ }),
},
},
};
@@ -1785,6 +1787,68 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
});
+ it('waits for late Codex terminal events when Electron complete arrives before stdout tail', async () => {
+ const store = createMockStore();
+ const get = vi.fn(() => store);
+
+ let resolveSendPrompt: () => void;
+ mockSendPrompt.mockReturnValue(
+ new Promise<void>((r) => {
+ resolveSendPrompt = r;
+ }),
+ );
+
+ let executorSettled = false;
+ const executorPromise = executeHeterogeneousAgent(get, {
+ ...defaultParams,
+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },
+ }).finally(() => {
+ executorSettled = true;
+ });
+ await flush();
+
+ ipc.emitRawLine('ipc-sess-1', codexThreadStarted());
+ ipc.emitRawLine('ipc-sess-1', codexTurnStarted());
+ ipc.emitRawLine('ipc-sess-1', codexAgentMessage('item_0', 'Checking prior state.'));
+ 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'));
+
+ // Reproduce the Electron race: completion notification reaches the
+ // renderer before the final agent_message + turn.completed stdout tail.
+ ipc.emitComplete('ipc-sess-1');
+ await flush();
+
+ // Main resolves sendPrompt immediately after broadcasting complete. The
+ // executor must keep the IPC subscription alive while onComplete is
+ // waiting for the late terminal stdout tail.
+ resolveSendPrompt!();
+ await flush();
+ expect(executorSettled).toBe(false);
+ expect(ipc.getListeners().has('heteroAgentEvent')).toBe(true);
+
+ ipc.emitRawLine(
+ 'ipc-sess-1',
+ codexAgentMessage('item_2', 'Final report after late stdout.'),
+ );
+ ipc.emitRawLine('ipc-sess-1', codexTurnCompleted({ input_tokens: 10, output_tokens: 5 }));
+ await flush();
+
+ await executorPromise;
+ await flush();
+
+ const finalWrite = mockUpdateMessage.mock.calls.find(
+ ([, value]: any) => value.content === 'Final report after late stdout.',
+ );
+ expect(finalWrite).toBeDefined();
+
+ const finalAssistantId = finalWrite![0];
+ expect(
+ mockCreateMessage.mock.calls.some(
+ ([params]: any) => params.role === 'assistant' && params.id === finalAssistantId,
+ ),
+ ).toBe(true);
+ });
+
it('should switch to a new assistant before persisting the next turn tool', async () => {
const idCounter = { assistant: 0, tool: 0 };
mockCreateMessage.mockImplementation(async (params: any) => {
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 cd5d08a5713..bd7fd86cfe0 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -394,6 +394,7 @@ 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;
+const HETERO_TERMINAL_EVENT_GRACE_TIMEOUT_MS = 3_000;
type MessageUpdateOperation = Extract<MessageBatchOperation, { type: 'updateMessage' }>;
type ToolMessageUpdateOperation = Extract<MessageBatchOperation, { type: 'updateToolMessage' }>;
@@ -792,6 +793,41 @@ export const executeHeterogeneousAgent = async (
* writes with stale DB state. onComplete forwards after persistence.
*/
let deferredTerminalEvent: AgentStreamEvent | null = null;
+ let terminalEventWaiters: Array<() => void> = [];
+ const notifyTerminalEvent = () => {
+ const waiters = terminalEventWaiters;
+ terminalEventWaiters = [];
+ for (const resolve of waiters) resolve();
+ };
+ const waitForTerminalEvent = (ms: number): Promise<void> => {
+ if (deferredTerminalEvent) return Promise.resolve();
+
+ return new Promise<void>((resolve) => {
+ let settled = false;
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ terminalEventWaiters = terminalEventWaiters.filter((waiter) => waiter !== finish);
+ resolve();
+ };
+ const timer = setTimeout(finish, ms);
+ terminalEventWaiters.push(finish);
+ });
+ };
+ let completionCallbackPromise: Promise<void> | null = null;
+ const runCompletionCallback = (callback: () => Promise<void>): Promise<void> => {
+ if (completionCallbackPromise) return completionCallbackPromise;
+
+ completionCallbackPromise = callback().catch((err) => {
+ console.error('[HeterogeneousAgent] completion callback failed:', err);
+ });
+ return completionCallbackPromise;
+ };
+ const waitForCompletionCallback = async () => {
+ const promise = completionCallbackPromise;
+ if (promise) await promise;
+ };
/**
* True while a step transition is in flight (stream_start queued but not yet
* forwarded to handler). Events that would normally be forwarded sync must
@@ -1652,6 +1688,7 @@ export const executeHeterogeneousAgent = async (
// which would read stale DB state (before we persist final content + usage).
if (event.type === 'agent_runtime_end' || event.type === 'error') {
deferredTerminalEvent = event;
+ notifyTerminalEvent();
return;
}
@@ -1730,177 +1767,188 @@ export const executeHeterogeneousAgent = async (
unsubscribe = subscribeBroadcasts(agentSessionId, {
onStreamEvent: handleStreamEvent,
- onComplete: async () => {
- if (completed) return;
- completed = true;
-
- const isErrorTerminal = deferredTerminalEvent?.type === 'error';
-
- // 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 queued reducer state so terminal never flushes stale content.
- {
- const reason = (deferredTerminalEvent?.data as { reason?: string } | undefined)?.reason;
- if (isErrorTerminal) {
- writeTopicStatus('failed');
- } else if (!isAborted() && isCompletedRuntimeEnd(reason)) {
- // Clean completion: the viewer sees 'active'; a background topic gets
- // the unread badge (markTopicUnread self-guards on activeTopicId).
- if (get().activeTopicId === context.topicId) writeTopicStatus('active');
- else
- get().markTopicUnread?.({
- agentId: context.agentId,
- groupId: context.groupId,
- topicId: context.topicId,
- });
- } else {
- // Cancel / deferred-tool park β€” back to a neutral 'active'.
- writeTopicStatus('active');
+ onComplete: () => {
+ void runCompletionCallback(async () => {
+ if (completed) return;
+ completed = true;
+
+ if (!isAborted() && !deferredTerminalEvent) {
+ await waitForTerminalEvent(HETERO_TERMINAL_EVENT_GRACE_TIMEOUT_MS);
}
- }
- const terminalEvent: AgentStreamEvent = deferredTerminalEvent ?? {
- data: {},
- operationId,
- stepIndex: 0,
- 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
- // β€” for an error terminal β€” emits `setError` β†’ `persistTerminalError`
- // (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. 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);
+ const isErrorTerminal = deferredTerminalEvent?.type === 'error';
+
+ // 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 queued reducer state so terminal never flushes stale content.
+ {
+ const reason = (deferredTerminalEvent?.data as { reason?: string } | undefined)
+ ?.reason;
+ if (isErrorTerminal) {
+ writeTopicStatus('failed');
+ } else if (!isAborted() && isCompletedRuntimeEnd(reason)) {
+ // Clean completion: the viewer sees 'active'; a background topic gets
+ // the unread badge (markTopicUnread self-guards on activeTopicId).
+ if (get().activeTopicId === context.topicId) writeTopicStatus('active');
+ else
+ get().markTopicUnread?.({
+ agentId: context.agentId,
+ groupId: context.groupId,
+ topicId: context.topicId,
+ });
+ } else {
+ // Cancel / deferred-tool park β€” back to a neutral 'active'.
+ writeTopicStatus('active');
}
}
- 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);
+ const terminalEvent: AgentStreamEvent = deferredTerminalEvent ?? {
+ data: {},
+ operationId,
+ stepIndex: 0,
+ 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
+ // β€” for an error terminal β€” emits `setError` β†’ `persistTerminalError`
+ // (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. 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);
+ }
}
- }
- // 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);
+ 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 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);
- }
+ if (!isErrorTerminal) {
+ // Topic status was already reset ahead of the queue (top of
+ // onComplete); forward the deferred terminal only so the handler runs
+ // the final fetchAndReplaceMessages + completeOperation against the
+ // now-persisted state.
+ eventHandler(terminalEvent);
+ if (!queueDrained) get().completeOperation(operationId);
+ }
- // Signal completion to the user β€” dock badge + (window-hidden) notification,
- // delegated to the shared `afterRunComplete` hook. It does the same
- // showNotification + setBadgeCount fan-out for non-client runtimes. We pass
- // the in-memory accumulated content (the store snapshot isn't durable yet);
- // the shared helper strips markdown + caps length + resolves the title.
- // Skip for aborted runs and for error terminations.
- if (!isAborted() && !isErrorTerminal) {
- await runLifecycle.afterRunComplete({
- context,
- notification: { content: finalContent },
- operationId,
- runId: operationId,
- runScope,
- runtimeType: 'hetero',
- });
- }
+ // Signal completion to the user β€” dock badge + (window-hidden) notification,
+ // delegated to the shared `afterRunComplete` hook. It does the same
+ // showNotification + setBadgeCount fan-out for non-client runtimes. We pass
+ // the in-memory accumulated content (the store snapshot isn't durable yet);
+ // the shared helper strips markdown + caps length + resolves the title.
+ // Skip for aborted runs and for error terminations.
+ if (!isAborted() && !isErrorTerminal) {
+ await runLifecycle.afterRunComplete({
+ context,
+ notification: { content: finalContent },
+ operationId,
+ runId: operationId,
+ runScope,
+ runtimeType: 'hetero',
+ });
+ }
+ });
},
- onError: async (error) => {
- if (completed) return;
- if (retryWithoutResume(error)) return;
- completed = true;
+ onError: (error) => {
+ void runCompletionCallback(async () => {
+ if (completed) return;
+ if (retryWithoutResume(error)) return;
+ completed = true;
- // 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');
+ // 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');
- const deferredMessageError =
- deferredTerminalEvent?.type === 'error'
- ? toHeterogeneousAgentMessageError(deferredTerminalEvent.data, adapterType)
- : undefined;
- const messageError =
- deferredMessageError || toHeterogeneousAgentMessageError(error, adapterType);
- let shouldClearTerminalErrorContent = false;
+ const deferredMessageError =
+ deferredTerminalEvent?.type === 'error'
+ ? toHeterogeneousAgentMessageError(deferredTerminalEvent.data, adapterType)
+ : undefined;
+ const messageError =
+ deferredMessageError || toHeterogeneousAgentMessageError(error, adapterType);
+ let shouldClearTerminalErrorContent = false;
+
+ persistQueue = persistQueue.then(async () => {
+ shouldClearTerminalErrorContent = shouldSuppressTerminalErrorEcho(
+ mainState.accContent,
+ messageError,
+ );
- persistQueue = persistQueue.then(async () => {
- shouldClearTerminalErrorContent = shouldSuppressTerminalErrorEcho(
- mainState.accContent,
- messageError,
- );
+ if (mainState.accContent && !shouldClearTerminalErrorContent) {
+ messageWriteBatcher.enqueueUpdateMessage(
+ mainState.currentAssistantId,
+ { content: mainState.accContent },
+ messageWriteCtx,
+ console.error,
+ );
+ }
+ await messageWriteBatcher.flush('error');
+ });
+ await waitForPersistQueue(persistQueue, 'error');
- if (mainState.accContent && !shouldClearTerminalErrorContent) {
- messageWriteBatcher.enqueueUpdateMessage(
- mainState.currentAssistantId,
- { content: mainState.accContent },
- messageWriteCtx,
- console.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
+ // already marked cancelled and the partial content is persisted above.
+ if (isAborted()) {
+ writeTopicStatus('active');
+ return;
}
- 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
- // already marked cancelled and the partial content is persisted above.
- if (isAborted()) {
- writeTopicStatus('active');
- return;
- }
- await persistTerminalError(messageError, { clearContent: shouldClearTerminalErrorContent });
+ await persistTerminalError(messageError, {
+ clearContent: shouldClearTerminalErrorContent,
+ });
+ });
},
});
@@ -1923,6 +1971,7 @@ export const executeHeterogeneousAgent = async (
} else {
await heterogeneousAgentService.sendPrompt(agentSessionId, message, operationId, imageList);
}
+ await waitForCompletionCallback();
// Persist heterogeneous-agent session id + the cwd it was created under,
// for multi-turn resume. CC stores sessions per-cwd
@@ -2025,6 +2074,7 @@ export const executeHeterogeneousAgent = async (
});
}
} finally {
+ await waitForCompletionCallback();
unsubscribe?.();
// Don't stopSession here β€” keep it alive for multi-turn resume.
// Session cleanup happens on topic deletion or Electron quit.