Skip to content

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

πŸ› fix(hetero): persist final answer before unlocking follow-ups (#19922)

YuTengjingf93359d9074f
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
index 1659dfe3d74..35985735b40 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
@@ -435,6 +435,34 @@ describe('main agent reducer', () => {
expect(state.accContent).toBe(''); // reset β†’ idempotent re-finalize
});
+ it('persists the open turn on visible_output_end while the run stays open', () => {
+ const { steps, state } = run([
+ initEvent('claude-opus-4-8', 'claude-code'),
+ reasoningEvent('thinking'),
+ textEvent('final answer'),
+ { data: {}, type: 'visible_output_end' },
+ ]);
+ expect(steps[3]).toEqual([
+ {
+ content: 'final answer',
+ kind: 'persistAssistant',
+ messageId: 'A0',
+ model: 'claude-opus-4-8',
+ provider: 'claude-code',
+ reasoning: 'thinking',
+ },
+ ]);
+ // Not a terminal: the accumulators stay so the later terminal flush
+ // rewrites the same content instead of blanking it.
+ expect(state.ended).toBeFalsy();
+ expect(state.accContent).toBe('final answer');
+ });
+
+ it('emits nothing on visible_output_end when the turn has no text', () => {
+ const { steps } = run([{ data: {}, type: 'visible_output_end' }]);
+ expect(steps[0]).toEqual([]);
+ });
+
it('suppresses echoed content and stamps the error on AuthRequired terminal error', () => {
const stderr = 'invalid api key';
const { steps } = run([
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
index 76e896de7fc..c28a68ad5ee 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
@@ -498,6 +498,32 @@ const reduceTurnMetadata = (state: MainAgentRunState, data: any): ReduceResult =
};
};
+/**
+ * `visible_output_end` β€” the CLI finished its visible reply, but the run may
+ * stay open (CC SDK mode keeps the transport alive for background tasks, so
+ * the terminal flush can land minutes later). The UI already lets the user
+ * send a follow-up at this point, and that send replaces the store with the
+ * server's rows β€” so the final step's text must be durable NOW, or the prior
+ * answer renders empty until a refresh (LOBE-14345).
+ *
+ * Accumulators are kept, not reset: the later terminal flush rewrites the same
+ * content idempotently, and a background-task turn opens a new step through
+ * `openTurn` as usual.
+ */
+const reduceVisibleOutputEnd = (state: MainAgentRunState): ReduceResult => {
+ if (!state.accContent && !state.accReasoning) return { intents: [], state };
+
+ const flush: Record<string, any> = {};
+ if (state.accContent) flush.content = state.accContent;
+ if (state.accReasoning) flush.reasoning = state.accReasoning;
+ if (state.turnModel) flush.model = state.turnModel;
+ if (state.turnProvider) flush.provider = state.turnProvider;
+ return {
+ intents: [{ kind: 'persistAssistant', messageId: state.currentAssistantId, ...flush }],
+ state,
+ };
+};
+
const reduceTerminal = (
state: MainAgentRunState,
event: { data?: any; type?: string },
@@ -579,6 +605,9 @@ export const reduce = (
if (data?.phase === 'turn_metadata') return reduceTurnMetadata(state, data);
return { intents: [], state };
}
+ case 'visible_output_end': {
+ return reduceVisibleOutputEnd(state);
+ }
case 'agent_runtime_end':
case 'error': {
return reduceTerminal(state, event, ctx);
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 74ad42206e6..54ab270b6ab 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -1330,6 +1330,185 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
// ────────────────────────────────────────────────────
describe('final content writes (onComplete)', () => {
+ /**
+ * CC SDK mode keeps the transport open after `result`, so the terminal
+ * flush can land minutes later β€” but `visible_output_end` already lets the
+ * user send a follow-up, whose server response replaces the store. The
+ * final text must hit the DB before the UI is unlocked (LOBE-14345).
+ */
+ it('persists the final text before unlocking follow-ups on visible_output_end', async () => {
+ const store = createMockStore();
+ const get = vi.fn(() => store);
+
+ let resolveSendPrompt: () => void;
+ mockSendPrompt.mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveSendPrompt = resolve;
+ }),
+ );
+
+ const executorPromise = executeHeterogeneousAgent(get, defaultParams);
+ await flush();
+
+ ipc.emitStreamEvent('ipc-sess-1', {
+ data: { chunkType: 'text', content: 'final answer' },
+ type: 'stream_chunk',
+ });
+ ipc.emitStreamEvent('ipc-sess-1', { data: {}, type: 'visible_output_end' });
+ // Well inside the batcher's idle window: only an explicit flush lands the write.
+ await flush();
+
+ const contentWriteIndex = mockUpdateMessage.mock.calls.findIndex(
+ ([id, value]: any) => id === 'ast-initial' && value.content === 'final answer',
+ );
+ expect(contentWriteIndex).toBeGreaterThanOrEqual(0);
+
+ // The gateway handler (mocked here) is what flips `visibleLoadingDone`,
+ // so the forward must come after the durable write.
+ const handlerSpy = vi.mocked(createGatewayEventHandler).mock.results.at(-1)!
+ .value as ReturnType<typeof vi.fn>;
+ const unlockIndex = handlerSpy.mock.calls.findIndex(
+ ([event]: any) => event.type === 'visible_output_end',
+ );
+ expect(unlockIndex).toBeGreaterThanOrEqual(0);
+ expect(mockUpdateMessage.mock.invocationCallOrder[contentWriteIndex]).toBeLessThan(
+ handlerSpy.mock.invocationCallOrder[unlockIndex],
+ );
+
+ ipc.emitComplete('ipc-sess-1');
+ await flush();
+ resolveSendPrompt!();
+ await flush();
+ await executorPromise;
+ await flush();
+ });
+
+ /**
+ * `flush` resolves even when the write failed, and the terminal replay may
+ * be minutes away in CC SDK mode β€” retry once before unlocking follow-ups.
+ */
+ it('retries a failed final-text write before unlocking follow-ups on visible_output_end', async () => {
+ const store = createMockStore();
+ const get = vi.fn(() => store);
+
+ let failedOnce = false;
+ mockUpdateMessage.mockImplementation(async (_id: string, value: any) => {
+ if (value?.content === 'final answer' && !failedOnce) {
+ failedOnce = true;
+ throw new Error('transient write failure');
+ }
+ });
+
+ let resolveSendPrompt: () => void;
+ mockSendPrompt.mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveSendPrompt = resolve;
+ }),
+ );
+
+ const executorPromise = executeHeterogeneousAgent(get, defaultParams);
+ await flush();
+
+ ipc.emitStreamEvent('ipc-sess-1', {
+ data: { chunkType: 'text', content: 'final answer' },
+ type: 'stream_chunk',
+ });
+ ipc.emitStreamEvent('ipc-sess-1', { data: {}, type: 'visible_output_end' });
+ await flush();
+
+ const contentWrites = mockUpdateMessage.mock.calls
+ .map(([id, value]: any, index: number) => ({ id, index, value }))
+ .filter(({ id, value }) => id === 'ast-initial' && value.content === 'final answer');
+ expect(contentWrites).toHaveLength(2);
+
+ const handlerSpy = vi.mocked(createGatewayEventHandler).mock.results.at(-1)!
+ .value as ReturnType<typeof vi.fn>;
+ const unlockIndex = handlerSpy.mock.calls.findIndex(
+ ([event]: any) => event.type === 'visible_output_end',
+ );
+ expect(unlockIndex).toBeGreaterThanOrEqual(0);
+ expect(mockUpdateMessage.mock.invocationCallOrder[contentWrites[1].index]).toBeLessThan(
+ handlerSpy.mock.invocationCallOrder[unlockIndex],
+ );
+
+ ipc.emitComplete('ipc-sess-1');
+ await flush();
+ resolveSendPrompt!();
+ await flush();
+ await executorPromise;
+ await flush();
+ });
+
+ /**
+ * The final step's assistant row can fail to create in the same batch as
+ * its content patch. Patching before re-creating matches zero rows yet
+ * reports success, so creates must be replayed first.
+ */
+ it('replays a failed step create before its final-text patch on visible_output_end', async () => {
+ const store = createMockStore();
+ const get = vi.fn(() => store);
+
+ // Minimal table: an update against a missing row is a silent no-op, like the DB.
+ const rows = new Map<string, Record<string, any>>([['ast-initial', {}]]);
+ mockCreateMessage.mockImplementation(async (params: any) => {
+ rows.set(params.id, { ...params });
+ return { id: params.id };
+ });
+ mockUpdateMessage.mockImplementation(async (id: string, value: any) => {
+ if (rows.has(id)) rows.set(id, { ...rows.get(id), ...value });
+ });
+ const defaultBatchMutate = mockBatchMutate.getMockImplementation()!;
+ let failedOnce = false;
+ mockBatchMutate.mockImplementation(async (operations: any[]) => {
+ const createsStepAssistant = operations.some(
+ (operation) =>
+ operation.type === 'createMessage' &&
+ operation.message?.role === 'assistant' &&
+ operation.message?.id !== 'ast-initial',
+ );
+ if (createsStepAssistant && !failedOnce) {
+ failedOnce = true;
+ throw new Error('transient batch failure');
+ }
+ return defaultBatchMutate(operations);
+ });
+
+ let resolveSendPrompt: () => void;
+ mockSendPrompt.mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveSendPrompt = resolve;
+ }),
+ );
+
+ const executorPromise = executeHeterogeneousAgent(get, defaultParams);
+ await flush();
+
+ ipc.emitRawLine('ipc-sess-1', ccInit());
+ ipc.emitRawLine('ipc-sess-1', ccToolUse('msg_1', 'toolu_1', 'Bash', { command: 'ls' }));
+ ipc.emitRawLine('ipc-sess-1', ccToolResult('toolu_1', 'ok'));
+ ipc.emitRawLine('ipc-sess-1', ccText('msg_2', 'final answer'));
+ ipc.emitStreamEvent('ipc-sess-1', { data: {}, type: 'visible_output_end' });
+ await flush();
+
+ expect(failedOnce).toBe(true);
+ const handlerSpy = vi.mocked(createGatewayEventHandler).mock.results.at(-1)!
+ .value as ReturnType<typeof vi.fn>;
+ expect(
+ handlerSpy.mock.calls.some(([event]: any) => event.type === 'visible_output_end'),
+ ).toBe(true);
+ const stepAssistant = [...rows.entries()].find(
+ ([id, row]) => id !== 'ast-initial' && row.role === 'assistant',
+ );
+ expect(stepAssistant?.[1].content).toBe('final answer');
+
+ ipc.emitComplete('ipc-sess-1');
+ await flush();
+ resolveSendPrompt!();
+ await flush();
+ await executorPromise;
+ await flush();
+ });
+
it('should write accumulated content + model + provider to the final assistant message', async () => {
await runWithEvents([
ccInit(),
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 655a7b8a8e2..241edd0091b 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -977,6 +977,26 @@ export const executeHeterogeneousAgent = async (
flush: messageWriteBatcher.flush,
});
+ /**
+ * Retry each failed row create, then each stashed main-assistant patch, once.
+ * Order is load-bearing: rows first, in the order they were enqueued (that is
+ * their FK dependency order), then the content patches β€” an update against a
+ * row that does not exist yet matches zero rows yet still reports success.
+ * Best-effort by design: a write that fails again stays stashed for the next
+ * replay, and never holds the run or the input lock.
+ */
+ const replayPendingMainWrites = async () => {
+ await pendingCreateLedger.drain();
+ 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 enqueueMainToolResult = (
toolCallId: string,
content: string,
@@ -2224,6 +2244,34 @@ export const executeHeterogeneousAgent = async (
return;
}
+ // ─── visible_output_end: make the final text durable BEFORE unlocking ───
+ // The handler marks the op `visibleLoadingDone` on this event, which lets
+ // the user send a follow-up while the run is still open (CC SDK mode
+ // keeps the transport alive, so the terminal flush may be minutes away).
+ // That send replaces the store with the server's rows; forwarding only
+ // after the reducer's persist has been flushed guarantees those rows
+ // already carry the final answer (LOBE-14345).
+ //
+ // Skipped when the terminal event already arrived in the same batch: its
+ // flush runs right behind this one, and only it can decide whether the
+ // text is an echoed error that must NOT be persisted (AuthRequired).
+ //
+ // `flush` resolves even when a write failed (failures are only stashed),
+ // so retry once right here instead of leaving it for the terminal replay
+ // minutes away. Unlock either way, matching the terminal path: a
+ // persistent DB failure must not keep the input locked.
+ if (event.type === 'visible_output_end') {
+ persistQueue = persistQueue.then(async () => {
+ if (!deferredTerminalEvent) {
+ await reduceAndApplyMain(event);
+ await messageWriteBatcher.flush('visible-output-end');
+ await replayPendingMainWrites();
+ }
+ eventHandler(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
@@ -2379,19 +2427,9 @@ export const executeHeterogeneousAgent = async (
const queueDrained = await waitForPersistQueue(persistQueue, 'terminal');
if (queueDrained) {
- // Order is load-bearing: rows first, in the order they were enqueued
- // (that is their FK dependency order), then the content patches β€”
- // an update against a row that does not exist yet matches zero rows.
- await pendingCreateLedger.drain();
-
- 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);
- }
- }
+ // Rows and main patches first; the tool patches below also need
+ // their rows to exist.
+ await replayPendingMainWrites();
for (const [messageId, update] of pendingToolFlush) {
try {