π€― 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
π fix: serialize CC ask-user interventions (#16943)
Arvin Xuc61f201fe976
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex 9dec04d3905..b5ba32e583f 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -256,7 +256,7 @@ interface CliTraceSession {interface InterventionSlot {bridge: AskUserBridge;/** Resolves once bridge.events() iterator ends (after `cancelAll`). */- pumpDone: Promise<void>;+ pumpDone?: Promise<void>;/** Path to the per-op temp `mcp.json` we wrote for `--mcp-config`. */tmpConfigPath: string;}@@ -777,17 +777,13 @@ export default class HeterogeneousAgentCtr extends ControllerModule {/*** Register a per-op AskUserQuestion bridge, write its temp `mcp.json`,- * and start pumping the bridge's outbound events into the regular- * `heteroAgentEvent` broadcast. Caller must invoke the returned cleanup- * after the spawn finishes (success, error, or cancel) to remove the- * temp file and tear down the bridge.- *- * Pump errors are logged but never thrown β they don't fail the spawn.+ * and stash it for the spawn path. The actual bridge event pump is started+ * from `handleSpawnedAgentProcess`, where it can share the stdout broadcast+ * queue instead of racing the adapter pipeline as a second producer.*/private async setupInterventionForOp(operationId: string,- sessionId: string,- ): Promise<{ cleanup: () => Promise<void>; tmpConfigPath: string }> {+ ): Promise<{ bridge: AskUserBridge; cleanup: () => Promise<void>; tmpConfigPath: string }> {const server = await this.ensureAskUserMcpServerStarted();const bridge = server.registerOperation(operationId);const tmpConfigPath = path.join(os.tmpdir(), `lobe-cc-mcp-${operationId}.json`);@@ -807,31 +803,21 @@ export default class HeterogeneousAgentCtr extends ControllerModule {};await writeFile(tmpConfigPath, JSON.stringify(config), 'utf8');- // Pump bridge.events() into the `heteroAgentEvent` broadcast. The- // iterator only ends after `cancelAll()`, so `pumpDone` resolves at- // cleanup time and gates teardown.- const pumpDone = (async () => {- for await (const event of bridge.events()) {- this.broadcast('heteroAgentEvent', { event, sessionId });- }- })().catch((err) => {- logger.warn('AskUserQuestion bridge pump error:', err);- });-- this.opIdToIntervention.set(operationId, { bridge, pumpDone, tmpConfigPath });+ const slot: InterventionSlot = { bridge, tmpConfigPath };+ this.opIdToIntervention.set(operationId, slot);const cleanup = async () => {// Unregistering on the server cancels all bridge pendings AND closes// the events iterator (cancelAll fires from within unregisterOperation).this.askUserMcpServer?.unregisterOperation(operationId);- await pumpDone;+ await slot.pumpDone;this.opIdToIntervention.delete(operationId);await unlink(tmpConfigPath).catch(() => {/* file may already be gone if app crashed mid-prompt */});};- return { cleanup, tmpConfigPath };+ return { bridge, cleanup, tmpConfigPath };}// βββ File cache βββ@@ -976,7 +962,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {// into `--mcp-config`. Codex / future agents skip this entirely.const intervention =session.agentType === 'claude-code'- ? await this.setupInterventionForOp(params.operationId, session.sessionId).catch((err) => {+ ? await this.setupInterventionForOp(params.operationId).catch((err) => {logger.warn('Failed to set up AskUserQuestion bridge β proceeding without it:', err);return undefined;})@@ -1311,6 +1297,15 @@ export default class HeterogeneousAgentCtr extends ControllerModule {});let stdoutBroadcastQueue: Promise<void> = Promise.resolve();+ const broadcastStreamEvents = (events: AgentStreamEvent[]) => {+ for (const event of events) {+ this.broadcast('heteroAgentEvent', {+ event,+ sessionId: session.sessionId,+ });+ }+ };+const broadcastPipelineBatch = (produce: () => ReturnType<AgentStreamPipeline['push']>) => {stdoutBroadcastQueue = stdoutBroadcastQueue.then(async () => {@@ -1329,18 +1324,36 @@ export default class HeterogeneousAgentCtr extends ControllerModule {traceSession,})),);- for (const event of events) {- this.broadcast('heteroAgentEvent', {- event,- sessionId: session.sessionId,- });- }+ broadcastStreamEvents(events);}).catch((error) => {logger.error('Failed to broadcast agent stream batch:', error);});};+ const broadcastBridgeEvent = (event: AgentStreamEvent) => {+ stdoutBroadcastQueue = stdoutBroadcastQueue+ .then(() => {+ broadcastStreamEvents([event]);+ })+ .catch((error) => {+ logger.error('Failed to broadcast AskUserQuestion bridge event:', error);+ });+ };++ if (intervention) {+ const pumpDone = (async () => {+ for await (const event of intervention.bridge.events()) {+ broadcastBridgeEvent(event);+ }+ await stdoutBroadcastQueue;+ })().catch((err) => {+ logger.warn('AskUserQuestion bridge pump error:', err);+ });+ const slot = this.opIdToIntervention.get(params.operationId);+ if (slot) slot.pumpDone = pumpDone;+ }+// Stream stdout events through the producer pipeline.const stdout = proc.stdout as Readable;stdout.on('data', (chunk: Buffer) => {diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex 331c304823a..aa56c6f30db 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -1305,6 +1305,111 @@ describe('HeterogeneousAgentCtr', () => {expect(runtimeEndIdx).toBeLessThan(completeIdx);expect(sendDurationMs).toBeGreaterThanOrEqual(900);});++ it('serializes AskUserQuestion bridge events behind already-queued stdout tool events', async () => {+ const initLine = `${JSON.stringify({+ model: 'claude-sonnet-4-6',+ session_id: 'cc-session-1',+ subtype: 'init',+ type: 'system',+ })}\n`;+ const askToolUseLine = `${JSON.stringify({+ message: {+ content: [+ {+ id: 'toolu_ask',+ input: {+ questions: [+ {+ header: 'Scope',+ options: [+ { description: 'Keep it narrow', label: 'Small' },+ { description: 'Do all of it', label: 'All' },+ ],+ question: 'How much should I do?',+ },+ ],+ },+ name: 'mcp__lobe_cc__ask_user_question',+ type: 'tool_use',+ },+ ],+ id: 'msg_ask',+ model: 'claude-sonnet-4-6',+ role: 'assistant',+ },+ type: 'assistant',+ })}\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;++ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);++ proc.__start = () => {+ setImmediate(() => {+ stdout.write(initLine);+ stdout.write(askToolUseLine);++ const bridge = (ctr as any).opIdToIntervention.get('op-test')?.bridge;+ void bridge?.pending({+ arguments: {+ questions: [+ {+ header: 'Scope',+ options: [+ { description: 'Keep it narrow', label: 'Small' },+ { description: 'Do all of it', label: 'All' },+ ],+ question: 'How much should I do?',+ },+ ],+ },+ toolCallId: 'toolu_ask',+ });++ stderr.end();+ stdout.end();+ proc.emit('exit', 0);+ });+ };+ nextFakeProc = proc;++ const { sessionId } = await ctr.startSession({ agentType: 'claude-code', command: 'claude' });+ await ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId });++ const toolEventIdx = broadcasts.findIndex(+ (b) =>+ b.channel === 'heteroAgentEvent' &&+ (b.data as any)?.event?.type === 'stream_chunk' &&+ (b.data as any)?.event?.data?.toolsCalling?.some((tool: any) => tool.id === 'toolu_ask'),+ );+ const interventionIdx = broadcasts.findIndex(+ (b) =>+ b.channel === 'heteroAgentEvent' &&+ (b.data as any)?.event?.type === 'agent_intervention_request' &&+ (b.data as any)?.event?.data?.toolCallId === 'toolu_ask',+ );++ expect(toolEventIdx).toBeGreaterThan(-1);+ expect(interventionIdx).toBeGreaterThan(-1);+ expect(toolEventIdx).toBeLessThan(interventionIdx);+ });});describe('app-quit cleanup of AskUserQuestion temp configs ()', () => {diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.tsindex 6b627bf584e..26e0cda49e5 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts@@ -2312,6 +2312,81 @@ describe('ConversationControl actions', () => {);});+ it('resolves the local hetero execution op from a reasoning child before submitting via IPC', async () => {+ const { result } = renderHook(() => useChatStore());++ const agentId = 'hetero-agent';+ const topicId = 'hetero-topic';+ const chatKey = messageMapKey({ agentId, topicId });++ const assistantMessage = createMockMessage({+ id: 'assistant-msg-1',+ role: 'assistant',+ });+ const toolMessage = createMockMessage({+ id: 'tool-msg-1',+ parentId: assistantMessage.id,+ plugin: {+ apiName: 'askUserQuestion',+ arguments: '{}',+ identifier: 'lobe-claude-code',+ type: 'default',+ },+ role: 'tool',+ tool_call_id: 'cc_call_1',+ } as any);++ let executionOpId!: string;+ let reasoningOpId!: string;+ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ activeThreadId: undefined,+ dbMessagesMap: { [chatKey]: [assistantMessage, toolMessage] },+ messagesMap: { [chatKey]: [assistantMessage, toolMessage] },+ });++ executionOpId = result.current.startOperation({+ context: { agentId, messageId: 'user-msg-1', threadId: null, topicId },+ type: 'execHeterogeneousAgent',+ }).operationId;++ reasoningOpId = result.current.startOperation({+ context: { messageId: assistantMessage.id },+ parentOperationId: executionOpId,+ type: 'reasoning',+ }).operationId;++ result.current.completeOperation(reasoningOpId);+ });++ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);+ vi.spyOn(result.current, 'updateTopicStatus').mockResolvedValue(undefined as any);+ const submitInterventionSpy = vi+ .spyOn(heterogeneousAgentService, 'submitIntervention')+ .mockResolvedValue(undefined as any);++ const payload = { 'Which color?': 'Blue' };+ await act(async () => {+ await result.current.submitHeteroIntervention('tool-msg-1', 'submit', payload);+ });++ expect(result.current.messageOperationMap[assistantMessage.id]).toBe(reasoningOpId);+ expect(result.current.optimisticUpdateMessagePlugin).toHaveBeenCalledWith(+ 'tool-msg-1',+ { intervention: { status: 'approved' } },+ { operationId: executionOpId },+ );+ expect(submitInterventionSpy).toHaveBeenCalledWith({+ operationId: executionOpId,+ result: payload,+ toolCallId: 'cc_call_1',+ });+ expect(lambdaClient.aiAgent.submitHeteroIntervention.mutate).not.toHaveBeenCalled();+ });+it("falls back to global-state optimistic context and routes a GC'd op to the remote tRPC transport", async () => {// When the resolved op has already been garbage-collected (not present in// `operations`), the optimistic context is the empty object `{}`diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 878c2abf0d3..a4bee456a69 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -183,6 +183,19 @@ function setupIpcCapture() {});}},+ /** Emit an already-adapted AgentStreamEvent, matching main-process bridge events. */+ emitStreamEvent: (sessionId: string, event: any) => {+ const handler = listeners.get('heteroAgentEvent');+ handler?.(null, {+ event: {+ operationId: defaultParams.operationId,+ stepIndex: 0,+ timestamp: Date.now(),+ ...event,+ },+ sessionId,+ });+ },/** Simulate session completion */emitComplete: (sessionId: string) => {const handler = listeners.get('heteroAgentSessionComplete');@@ -680,6 +693,92 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(types.filter((type: string) => type === 'updateToolMessage')).toHaveLength(1);expect(types.indexOf('updateToolMessage')).toBeGreaterThan(types.indexOf('createMessage'));});++ it('replays an early AskUserQuestion intervention after the batched tool row exists', async () => {+ const optimisticUpdateMessagePlugin = vi.fn(async () => {});+ const updateTopicStatus = vi.fn(async () => {});+ const store = createMockStore({+ optimisticUpdateMessagePlugin,+ updateTopicStatus,+ });+ const get = vi.fn(() => store);++ 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.emitStreamEvent('ipc-sess-1', {+ data: {+ apiName: 'askUserQuestion',+ arguments: JSON.stringify({+ questions: [+ {+ header: 'Scope',+ options: [+ { description: 'Keep it narrow', label: 'Small' },+ { description: 'Do all of it', label: 'All' },+ ],+ question: 'How much should I do?',+ },+ ],+ }),+ deadline: Date.now() + 300_000,+ identifier: 'claude-code',+ toolCallId: 'toolu_ask',+ },+ type: 'agent_intervention_request',+ });+ await flush();++ expect(optimisticUpdateMessagePlugin).not.toHaveBeenCalled();++ ipc.emitRawLine(+ 'ipc-sess-1',+ ccToolUse('msg_ask', 'toolu_ask', 'mcp__lobe_cc__ask_user_question', {+ questions: [+ {+ header: 'Scope',+ options: [+ { description: 'Keep it narrow', label: 'Small' },+ { description: 'Do all of it', label: 'All' },+ ],+ question: 'How much should I do?',+ },+ ],+ }),+ );+ await flush();++ const toolCreateIndex = mockCreateMessage.mock.calls.findIndex(+ ([params]: any) => params.role === 'tool' && params.tool_call_id === 'toolu_ask',+ );+ expect(toolCreateIndex).toBeGreaterThanOrEqual(0);+ expect(optimisticUpdateMessagePlugin).toHaveBeenCalledWith(+ mockCreateMessage.mock.calls[toolCreateIndex][0].id,+ { intervention: { status: 'pending' } },+ { operationId: 'op-1' },+ );+ expect(mockCreateMessage.mock.invocationCallOrder[toolCreateIndex]).toBeLessThan(+ optimisticUpdateMessagePlugin.mock.invocationCallOrder[0],+ );+ expect(updateTopicStatus).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'waitingForHuman', topicId: 'topic-1' }),+ );++ ipc.emitRawLine('ipc-sess-1', ccToolResult('toolu_ask', 'User answers:\n- Scope: Small'));+ ipc.emitRawLine('ipc-sess-1', ccResult());+ ipc.emitComplete('ipc-sess-1');+ await flush();+ resolveSendPrompt();+ await executorPromise;+ });});// ββββββββββββββββββββββββββββββββββββββββββββββββββββdiff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.tsindex 5a8c3da5d54..f6571cdb5b5 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts@@ -19,6 +19,7 @@ import {import { type OptimisticUpdateContext } from '@/store/chat/slices/message/actions/optimisticUpdate';import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';import { operationSelectors } from '@/store/chat/slices/operation/selectors';+import type { Operation } from '@/store/chat/slices/operation/types';import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';import { type ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -101,6 +102,36 @@ export class ConversationControlActionImpl {);};+ #resolveHeteroInterventionExecutionOperation = (+ initialOperationId: string,+ ): { operation?: Operation; operationId: string } => {+ const operations: ChatStore['operations'] = this.#get().operations;+ const visited = new Set<string>();+ let currentOperationId: string | undefined = initialOperationId;+ let lastResolved: { operation?: Operation; operationId: string } | undefined;++ while (currentOperationId && !visited.has(currentOperationId)) {+ visited.add(currentOperationId);+ const operation: Operation | undefined = operations[currentOperationId];+ lastResolved = { operation, operationId: currentOperationId };++ if (!operation) break;++ // `sendMessage` is the tree root, but it does not own the AskUser bridge.+ // Stop at the runtime execution node that produced this intervention.+ if (+ operation.type === 'execHeterogeneousAgent' ||+ operation.type === 'execServerAgentRuntime'+ ) {+ return { operation, operationId: currentOperationId };+ }++ currentOperationId = operation.parentOperationId;+ }++ return lastResolved ?? { operationId: initialOperationId };+ };+/*** Local tool-interaction resumes are continuations of the original request.* Preserve the request trigger so downstream chat requests keep the same@@ -915,19 +946,26 @@ export class ConversationControlActionImpl {return;}- // Walk up to the assistant that owns this tool β its operation is the- // running CC stream we need to address. Falls through to the tool- // message id itself if a producer ever associated it directly.+ // Walk up to the assistant that owns this tool. `messageOperationMap` is a+ // most-granular pointer, so it may reference a transient child op+ // (`reasoning`, `toolCalling`, ...), not the runtime execution that owns+ // the AskUser bridge.const { messageOperationMap } = this.#get();- const operationId =+ const candidateOperationId =(toolMessage.parentId && messageOperationMap?.[toolMessage.parentId]) ??messageOperationMap?.[toolMessageId];- if (!operationId) {+ if (!candidateOperationId) {console.warn('[submitHeteroIntervention] no operationId for', toolMessageId);return;}+ // Resolve the runtime execution op before choosing IPC vs remote transport.+ // For local CC this is `execHeterogeneousAgent`; for gateway/device runs+ // this is `execServerAgentRuntime`.+ const { operation, operationId } =+ this.#resolveHeteroInterventionExecutionOperation(candidateOperationId);+const effectiveContext: ConversationContext = context ?? {agentId: this.#get().activeAgentId,topicId: this.#get().activeTopicId,@@ -940,7 +978,6 @@ export class ConversationControlActionImpl {// matches the active conversation the user just clicked in. The IPC// submit below stays unchanged: `bridge.resolve()` no-ops on unknown// toolCallIds, so it's safe to fire even when the bridge is gone.- const operation = this.#get().operations[operationId];const operationAlive = !!operation;if (!operationAlive) {console.warn(diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex e2302503dda..8928117c900 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -748,6 +748,8 @@ export const executeHeterogeneousAgent = async (*/const toolMsgIdByCallId: Map<string, string> = new Map();const mainToolCallIds = new Set<string>();+ const pendingInterventionRequests = new Map<string, AgentInterventionRequestData>();+ const pendingInterventionResponses = new Map<string, AgentInterventionResponseData>();/*** Shared main-agent run coordinator state β the pure reducer in* `@lobechat/heterogeneous-agents`. Owns the main turn/step state machine@@ -1013,6 +1015,80 @@ export const executeHeterogeneousAgent = async ((err) => console.error('[HeterogeneousAgent] Failed to update tool message content:', err),);};+ const applyInterventionRequest = async (data: AgentInterventionRequestData): Promise<boolean> => {+ const toolMsgId = toolMsgIdByCallId.get(data.toolCallId);+ if (!toolMsgId) return false;++ // The id is pre-allocated before the batched createMessage has necessarily+ // flushed. Persist the row before writing plugin/intervention state.+ await messageWriteBatcher.flush('before-intervention-request');++ try {+ await get().optimisticUpdateMessagePlugin(+ toolMsgId,+ { intervention: { status: 'pending' } },+ { operationId },+ );+ // Sidebar topic row swaps the running spinner for a hand icon+ // so it's obvious from the topic list that this conversation is+ // blocked on the user, not still streaming.+ writeTopicStatus('waitingForHuman');+ // Parity with the homogeneous approval paths (client / gateway /+ // aiAgent): a CC AskUserQuestion now also bumps the dock badge and+ // bounces the macOS dock. The helper is desktop-guarded and only+ // requests attention while the window is hidden/unfocused, so it's+ // a no-op when the user is already looking at the approval.+ void notifyDesktopHumanApprovalRequired(get, context);+ } catch (err) {+ console.error('[HeterogeneousAgent] persist intervention pending failed:', err);+ }++ return true;+ };+ const applyInterventionResponse = async (+ data: AgentInterventionResponseData,+ ): Promise<boolean> => {+ const { cancelled, cancelReason, toolCallId } = data;+ if (!cancelled) return true;+ if (cancelReason === 'user_cancelled') return true;++ const toolMsgId = toolMsgIdByCallId.get(toolCallId);+ if (!toolMsgId) return false;++ await messageWriteBatcher.flush('before-intervention-response');++ try {+ await get().optimisticUpdateMessagePlugin(+ toolMsgId,+ {+ intervention: {+ rejectedReason: cancelReason ?? 'session_ended',+ status: 'rejected',+ },+ },+ { operationId },+ );+ // Bridge resolved without the user β drop the hand state so the+ // sidebar reflects that we're back to whatever the stream does+ // next (`active`/`failed` lands shortly after via runtime_end).+ writeTopicStatus('running');+ } catch (err) {+ console.error('[HeterogeneousAgent] persist intervention rejection failed:', err);+ }++ return true;+ };+ const replayPendingInterventionsForToolCall = async (toolCallId: string): Promise<void> => {+ const request = pendingInterventionRequests.get(toolCallId);+ if (request && (await applyInterventionRequest(request))) {+ pendingInterventionRequests.delete(toolCallId);+ }++ const response = pendingInterventionResponses.get(toolCallId);+ if (response && (await applyInterventionResponse(response))) {+ pendingInterventionResponses.delete(toolCallId);+ }+ };const retryWithoutResume = (error: unknown): boolean => {if (resumeFallbackTriggered ||@@ -1265,6 +1341,7 @@ export const executeHeterogeneousAgent = async (}toolMsgIdByCallId.set(x.payload.id, x.toolMessageId);t?.stream.create(toolMsg as UIChatMessage);+ await replayPendingInterventionsForToolCall(x.payload.id);}// Phase 3: backfill result_msg_id on assistant.tools[].@@ -1488,6 +1565,9 @@ export const executeHeterogeneousAgent = async (},{ operationId },);+ for (const x of intent.tools) {+ if (x.isNew) await replayPendingInterventionsForToolCall(x.payload.id);+ }return;}@@ -1636,37 +1716,19 @@ export const executeHeterogeneousAgent = async (// rendered automatically by the framework while pending; the// eventual `tool_result` content (formatted answer text) gets// overwritten via the existing `tool_result` branch below.- // Deferred behind `persistQueue` so it lands AFTER `persistToolBatch`- // populates `toolMsgIdByCallId`.+ // Deferred behind `persistQueue`; if the bridge event beats the stdout+ // tool_use event, cache it and replay once the tool id is registered.if (event.type === 'agent_intervention_request') {const data = event.data as AgentInterventionRequestData;persistQueue = persistQueue.then(async () => {- const toolMsgId = toolMsgIdByCallId.get(data.toolCallId);- if (!toolMsgId) {+ if (await applyInterventionRequest(data)) return;++ pendingInterventionRequests.set(data.toolCallId, data);+ if (!toolMsgIdByCallId.has(data.toolCallId)) {console.warn(- '[HeterogeneousAgent] intervention_request for unknown toolCallId:',+ '[HeterogeneousAgent] deferred intervention_request for unknown toolCallId:',data.toolCallId,);- return;- }- try {- await get().optimisticUpdateMessagePlugin(- toolMsgId,- { intervention: { status: 'pending' } },- { operationId },- );- // Sidebar topic row swaps the running spinner for a hand icon- // so it's obvious from the topic list that this conversation is- // blocked on the user, not still streaming.- writeTopicStatus('waitingForHuman');- // Parity with the homogeneous approval paths (client / gateway /- // aiAgent): a CC AskUserQuestion now also bumps the dock badge and- // bounces the macOS dock. The helper is desktop-guarded and only- // requests attention while the window is hidden/unfocused, so it's- // a no-op when the user is already looking at the approval.- void notifyDesktopHumanApprovalRequired(get, context);- } catch (err) {- console.error('[HeterogeneousAgent] persist intervention pending failed:', err);}});return;@@ -1682,30 +1744,9 @@ export const executeHeterogeneousAgent = async (// a Submit click would throw `Operation not found`).if (event.type === 'agent_intervention_response') {const data = event.data as AgentInterventionResponseData;- const { cancelled, cancelReason, toolCallId } = data;- if (!cancelled) return;- if (cancelReason === 'user_cancelled') return;persistQueue = persistQueue.then(async () => {- const toolMsgId = toolMsgIdByCallId.get(toolCallId);- if (!toolMsgId) return;- try {- await get().optimisticUpdateMessagePlugin(- toolMsgId,- {- intervention: {- rejectedReason: cancelReason ?? 'session_ended',- status: 'rejected',- },- },- { operationId },- );- // Bridge resolved without the user β drop the hand state so the- // sidebar reflects that we're back to whatever the stream does- // next (`active`/`failed` lands shortly after via runtime_end).- writeTopicStatus('running');- } catch (err) {- console.error('[HeterogeneousAgent] persist intervention rejection failed:', err);- }+ if (await applyInterventionResponse(data)) return;+ pendingInterventionResponses.set(data.toolCallId, data);});return;}