π€― 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(hetero-agent): wire AskUserBridge response events to renderer (#14732)
Arvin Xu5174c13ef1ff
diff --git a/packages/heterogeneous-agents/src/askUser/AskUserBridge.test.ts b/packages/heterogeneous-agents/src/askUser/AskUserBridge.test.tsindex ee29220beee..89527428159 100644--- a/packages/heterogeneous-agents/src/askUser/AskUserBridge.test.ts+++ b/packages/heterogeneous-agents/src/askUser/AskUserBridge.test.ts@@ -182,6 +182,104 @@ describe('AskUserBridge', () => {});});+ describe('response event mirror', () => {+ it('emits agent_intervention_response on user resolve() with the result echoed', async () => {+ const bridge = new AskUserBridge('op-1');+ const drain = drainEvents(bridge);+ const pending = bridge.pending({ arguments: {}, toolCallId: 'tc-1' });++ const req = await drain.firstEvent;+ expect(req.type).toBe('agent_intervention_request');++ bridge.resolve('tc-1', { result: { picked: 'red' } });+ await pending;++ const resp = (await drain.events.next()).value as any;+ expect(resp.type).toBe('agent_intervention_response');+ expect(resp.operationId).toBe('op-1');+ expect(resp.data).toEqual({+ cancelReason: undefined,+ cancelled: undefined,+ result: { picked: 'red' },+ toolCallId: 'tc-1',+ });+ drain.stop();+ });++ it('emits agent_intervention_response on cancel() with user_cancelled', async () => {+ const bridge = new AskUserBridge('op-1');+ const drain = drainEvents(bridge);+ const pending = bridge.pending({ arguments: {}, toolCallId: 'tc-1' });+ await drain.firstEvent;++ bridge.cancel('tc-1');+ await pending;++ const resp = (await drain.events.next()).value as any;+ expect(resp.type).toBe('agent_intervention_response');+ expect(resp.data).toEqual({+ cancelReason: 'user_cancelled',+ cancelled: true,+ result: undefined,+ toolCallId: 'tc-1',+ });+ drain.stop();+ });++ it('emits agent_intervention_response on timeout with cancelReason: timeout', async () => {+ const bridge = new AskUserBridge('op-1');+ const drain = drainEvents(bridge);+ const pending = bridge.pending({ arguments: {}, toolCallId: 'tc-1' }, { timeoutMs: 100 });+ await drain.firstEvent;++ vi.advanceTimersByTime(101);+ await pending;++ const resp = (await drain.events.next()).value as any;+ expect(resp.type).toBe('agent_intervention_response');+ expect(resp.data).toEqual({+ cancelReason: 'timeout',+ cancelled: true,+ result: undefined,+ toolCallId: 'tc-1',+ });+ drain.stop();+ });++ it('emits agent_intervention_response for every pending entry on cancelAll()', async () => {+ const bridge = new AskUserBridge('op-1');+ const drain = drainEvents(bridge);+ bridge.pending({ arguments: {}, toolCallId: 'tc-1' });+ bridge.pending({ arguments: {}, toolCallId: 'tc-2' });++ // Drain the two request events first.+ await drain.firstEvent;+ await drain.events.next();++ bridge.cancelAll('session_ended');++ // Two response events, one per pending toolCallId. Order matches the+ // pending Map insertion order (tc-1 then tc-2).+ const resp1 = (await drain.events.next()).value as any;+ const resp2 = (await drain.events.next()).value as any;+ expect([resp1, resp2].map((e) => e.type)).toEqual([+ 'agent_intervention_response',+ 'agent_intervention_response',+ ]);+ const ids = [resp1.data.toolCallId, resp2.data.toolCallId].sort();+ expect(ids).toEqual(['tc-1', 'tc-2']);+ for (const r of [resp1, resp2]) {+ expect(r.data.cancelled).toBe(true);+ expect(r.data.cancelReason).toBe('session_ended');+ }++ // Iterator ends right after the drain β `cancelAll` flips `closed` only+ // AFTER emitting, so the response events land before the stream closes.+ const end = await drain.events.next();+ expect(end.done).toBe(true);+ });+ });+describe('event stream', () => {it('emits one request event per pending() call', async () => {const bridge = new AskUserBridge('op-1');diff --git a/packages/heterogeneous-agents/src/askUser/AskUserBridge.ts b/packages/heterogeneous-agents/src/askUser/AskUserBridge.tsindex 5d2dc795fbf..0957ae52b09 100644--- a/packages/heterogeneous-agents/src/askUser/AskUserBridge.ts+++ b/packages/heterogeneous-agents/src/askUser/AskUserBridge.ts@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';import type {AgentInterventionRequestData,+ AgentInterventionResponseData,AgentStreamEvent,} from '@lobechat/agent-gateway-client';@@ -86,9 +87,16 @@ interface BridgeOptions {* producer to forward.* 4. Producer eventually calls `resolve(toolCallId, payload)` (from the* consumer's `agent_intervention_response`) β Promise resolves.- * 5. Or: deadline / `cancelAll()` rejects the pending Promise with a+ * 5. Or: deadline / `cancelAll()` resolves the pending Promise with a* `{ cancelled: true, cancelReason }` answer (no exception thrown).*+ * Every terminal path (resolve / cancel / timeout / cancelAll) ALSO emits+ * an `agent_intervention_response` AgentStreamEvent on `events()`, so the+ * wire stream alone is enough for a consumer to reconstruct each+ * intervention's terminal state β critical for the renderer, whose+ * intervention UI would otherwise stay "pending" after a producer-side+ * timeout silently unblocks CC.+ ** Errors only surface from `pending()` if the bridge itself is misused* (e.g. emitting after `cancelAll`). Cancellation/timeout is normal flow,* not an exception.@@ -139,6 +147,12 @@ export class AskUserBridge {const timeoutTimer = setTimeout(() => {this.pending_.delete(toolCallId);clearInterval(progressTimer);+ // Mirror the terminal state onto the outbound stream so the consumer+ // can flip the UI's intervention to `rejected` before the owning op+ // finishes and gets garbage-collected. Without this, the renderer+ // would still show the form as pending after the bridge has already+ // given up.+ this.emitResponse(toolCallId, { cancelReason: 'timeout', cancelled: true });resolve({ cancelled: true, cancelReason: 'timeout' });}, timeoutMs);@@ -196,6 +210,15 @@ export class AskUserBridge {if (!entry) return;this.pending_.delete(toolCallId);entry.cleanup();+ // Echo the resolution on the outbound stream. For user-driven submits+ // the consumer has already optimistically updated, but emitting keeps+ // the wire contract symmetric (request β response) and lets late+ // subscribers reconstruct the terminal state purely from events.+ this.emitResponse(toolCallId, {+ cancelReason: payload.cancelled ? (payload.cancelReason ?? 'user_cancelled') : undefined,+ cancelled: payload.cancelled,+ result: payload.cancelled ? undefined : payload.result,+ });entry.resolve(payload.cancelled? { cancelReason: payload.cancelReason ?? 'user_cancelled', cancelled: true }@@ -219,12 +242,17 @@ export class AskUserBridge {*/cancelAll(reason: InterventionAnswer['cancelReason'] = 'session_ended'): void {if (this.closed) return;- this.closed = true;- for (const entry of this.pending_.values()) {+ // Emit + resolve every pending entry BEFORE flipping `closed`, so the+ // outbound response events land via the normal path (queue or live+ // waiter) and aren't swallowed by the iterator-end drain that runs+ // immediately after.+ for (const [toolCallId, entry] of this.pending_) {entry.cleanup();+ this.emitResponse(toolCallId, { cancelReason: reason, cancelled: true });entry.resolve({ cancelReason: reason, cancelled: true });}this.pending_.clear();+ this.closed = true;// Drain any waiters with a "done" so consumers can break their loop.while (this.outboundWaiters.length > 0) {const waiter = this.outboundWaiters.shift()!;@@ -269,4 +297,27 @@ export class AskUserBridge {this.outboundQueue.push(event);}}++ private emitResponse(+ toolCallId: string,+ payload: {+ cancelReason?: InterventionAnswer['cancelReason'];+ cancelled?: boolean;+ result?: unknown;+ },+ ): void {+ const data: AgentInterventionResponseData = {+ cancelled: payload.cancelled,+ cancelReason: payload.cancelReason,+ result: payload.result,+ toolCallId,+ };+ this.emit({+ data,+ operationId: this.operationId,+ stepIndex: this.getStepIndex(),+ timestamp: Date.now(),+ type: 'agent_intervention_response',+ });+ }}diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.tsindex a9ef1468cc1..548647fa282 100644--- a/src/store/chat/slices/aiChat/actions/conversationControl.ts+++ b/src/store/chat/slices/aiChat/actions/conversationControl.ts@@ -686,7 +686,21 @@ export class ConversationControlActionImpl {topicId: this.#get().activeTopicId,threadId: this.#get().activeThreadId,};- const optimisticContext: OptimisticUpdateContext = { operationId };+ // If the operation has already been garbage-collected (e.g. the bridge+ // timed out earlier and `runtime_end` rolled the op into `completed`+ // 30s+ ago), don't pass the stale opId into the optimistic chain β the+ // `internal_getConversationContext` fallback uses global state, which+ // 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 operationAlive = !!this.#get().operations[operationId];+ if (!operationAlive) {+ console.warn(+ '[submitHeteroIntervention] operation already gone, using global-state fallback for optimistic write:',+ operationId,+ );+ }+ const optimisticContext: OptimisticUpdateContext = operationAlive ? { operationId } : {};if (actionType === 'submit') {await this.#get().optimisticUpdateMessagePlugin(diff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.tsindex 1fbd4ed004c..8576a414222 100644--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts@@ -1,5 +1,6 @@import type {AgentInterventionRequestData,+ AgentInterventionResponseData,AgentStreamEvent,} from '@lobechat/agent-gateway-client';import { isDesktop } from '@lobechat/const';@@ -1360,6 +1361,40 @@ export const executeHeterogeneousAgent = async (return;}+ // βββ agent_intervention_response: bridge-side terminal state βββ+ // Mirrors the bridge's terminal state onto the UI. Only acts on the+ // cases the user did NOT drive β `user_cancelled` and successful+ // submits are already optimistic-updated by `submitHeteroIntervention`+ // and arrive here as a wire echo. Timeout / session_ended are the+ // ones that would otherwise strand the form on `status: 'pending'`+ // until the owning operation gets garbage-collected (at which point+ // 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 },+ );+ } catch (err) {+ console.error('[HeterogeneousAgent] persist intervention rejection failed:', err);+ }+ });+ return;+ }+// βββ tool_result: update tool message content in DB (ACP-only) βββif (event.type === 'tool_result') {const { content, isError, pluginState, toolCallId } = event.data as {diff --git a/src/store/chat/slices/operation/__tests__/actions.test.ts b/src/store/chat/slices/operation/__tests__/actions.test.tsindex 2f959e2b9eb..1de6c59fff7 100644--- a/src/store/chat/slices/operation/__tests__/actions.test.ts+++ b/src/store/chat/slices/operation/__tests__/actions.test.ts@@ -1141,12 +1141,33 @@ describe('Operation Actions', () => {expect(context.groupId).toBe('global-group');});- it('should throw error when operationId is invalid', () => {+ it('should fall back to global state when operationId is invalid', () => {const { result } = renderHook(() => useChatStore());- expect(() => {- result.current.internal_getConversationContext({ operationId: 'invalid-op-id' });- }).toThrow('Operation not found');+ act(() => {+ useChatStore.setState({+ activeAgentId: 'fallback-agent',+ activeTopicId: 'fallback-topic',+ activeThreadId: 'fallback-thread',+ activeGroupId: 'fallback-group',+ });+ });++ // Long-lived intervention surfaces can outlive the operation they+ // were started under (op GC'd 30s after runtime_end). The previous+ // throw would tear down the whole optimistic write chain on Submit;+ // instead, degrade gracefully to the global state so the IPC submit+ // can still ship.+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const context = result.current.internal_getConversationContext({+ operationId: 'invalid-op-id',+ });+ expect(context.agentId).toBe('fallback-agent');+ expect(context.topicId).toBe('fallback-topic');+ expect(context.threadId).toBe('fallback-thread');+ expect(context.groupId).toBe('fallback-group');+ expect(warnSpy).toHaveBeenCalled();+ warnSpy.mockRestore();});});diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.tsindex 5a2749091fb..994276d4a10 100644--- a/src/store/chat/slices/operation/actions.ts+++ b/src/store/chat/slices/operation/actions.ts@@ -50,23 +50,33 @@ export class OperationActionsImpl {if (context?.operationId) {const operation = this.#get().operations[context.operationId];if (!operation) {+ // The op was already cleaned up (e.g. completed CC turn whose+ // runtime_end fired and was GC'd 30s later), but a late caller+ // β typically a long-lived intervention surface β still carries+ // the opId. Throwing here would tear down the optimistic write+ // and any follow-up IPC the caller was about to perform, so we+ // degrade to the global-state fallback and log loudly.log(- '[internal_getConversationContext] ERROR: Operation not found: %s',+ '[internal_getConversationContext] WARNING: Operation not found, falling back to global state: %s',context.operationId,);- throw new Error(`Operation not found: ${context.operationId}`);+ console.warn(+ '[internal_getConversationContext] operation not found, using global state:',+ context.operationId,+ );+ } else {+ const { agentId, topicId, threadId, scope, isNew, groupId } = operation.context;+ log(+ '[internal_getConversationContext] get from operation %s: agentId=%s, topicId=%s, threadId=%s, scope=%s, groupId=%s',+ context.operationId,+ agentId,+ topicId,+ threadId,+ scope,+ groupId,+ );+ return { agentId: agentId!, topicId, threadId, scope, isNew, groupId };}- const { agentId, topicId, threadId, scope, isNew, groupId } = operation.context;- log(- '[internal_getConversationContext] get from operation %s: agentId=%s, topicId=%s, threadId=%s, scope=%s, groupId=%s',- context.operationId,- agentId,- topicId,- threadId,- scope,- groupId,- );- return { agentId: agentId!, topicId, threadId, scope, isNew, groupId };}// Fallback to global state@@ -606,12 +616,15 @@ export class OperationActionsImpl {}}- // Remove from messageOperationMap- const messageEntry = Object.entries(state.messageOperationMap).find(- ([, opId]) => opId === operationId,- );- if (messageEntry) {- delete state.messageOperationMap[messageEntry[0]];+ // Remove EVERY messageOperationMap entry pointing to this opId.+ // Assistant + tool messages from the same turn often map to the+ // same operation; the previous `find` + single-delete left+ // dangling references behind, which `submitHeteroIntervention`+ // later read back as a stale opId and threw on lookup.+ for (const [messageId, opId] of Object.entries(state.messageOperationMap)) {+ if (opId === operationId) {+ delete state.messageOperationMap[messageId];+ }}});}),