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: 工具结束后同步关闭 UserQuestion (#21874)

Mochaea1af445a34d
diff --git a/.agents/skills/ux/references/feedback.md b/.agents/skills/ux/references/feedback.md
index 94e95854792..27a9a90a37c 100644
--- a/.agents/skills/ux/references/feedback.md
+++ b/.agents/skills/ux/references/feedback.md
@@ -143,6 +143,13 @@ state hands control back and restores certainty. Retry re-runs the _same_ fetch
`mutate` / query refetch), shows loading again while it re-runs, and stays available if it
fails again; keep any already-loaded context rather than blowing the surface away.
+When an upstream lifecycle event can settle an interaction, consume that event and
+close the obsolete form automatically. Reconcile missed events internally on reconnect
+or a bounded acknowledgement wait; do not require a “check runtime status” action.
+A submit/cancel racing completion should report that the operation ended and preserve
+its terminal state, rather than restore the obsolete form or invent a successful answer.
+Verify both completion before the click and completion while delivery is in flight.
+
**But not every failure should offer Retry — gate it on whether a retry could plausibly
succeed.** A `401` (auth expired / invalid) or `403` (no permission) wall will just fail
again the same way, so a **Reload** button there is a false promise: it invites the user to
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.interventionAck.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.interventionAck.test.ts
index 1051380bc7c..240ff13f8af 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.interventionAck.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.interventionAck.test.ts
@@ -23,6 +23,83 @@ describe('HeterogeneousPersistenceHandler — event branch coverage', () => {
afterEach(() => __resetOperationStatesForTesting());
describe('agent_intervention producer ACK', () => {
+ it.each(['answer', 'tool_result'])(
+ 'keeps subagent question ownership through a cold request and %s',
+ async (outcome) => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+ const args = JSON.stringify({
+ questions: [
+ { header: 'Scope', question: 'Proceed?', options: [{ label: 'Yes' }, { label: 'No' }] },
+ ],
+ });
+ const child = { parentToolCallId: 'task-parent', subagentMessageId: 'child-turn' };
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tools_calling',
+ subagent: child,
+ toolsCalling: [
+ {
+ apiName: 'askUserQuestion',
+ arguments: args,
+ id: 'child-question',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ],
+ }),
+ ]);
+ const toolRow = [...h.messages.values()].find((m) => m.tool_call_id === 'child-question')!;
+ expect(toolRow.threadId).toBeTruthy();
+ h.messageModel.listMessagePluginsByTopic.mockImplementation(
+ async () =>
+ [...h.messages.values()]
+ .filter((m) => m.role === 'tool')
+ .map((m) => ({
+ ...m.plugin,
+ id: m.id,
+ state: m.pluginState,
+ toolCallId: m.tool_call_id,
+ })) as never[],
+ );
+ __resetOperationStatesForTesting();
+ await ingest(h, [
+ buildEvent('agent_intervention_request', 1, {
+ apiName: 'askUserQuestion',
+ arguments: args,
+ deadline: 1_900_000_000_000,
+ identifier: 'claude-code',
+ interactionKind: 'question',
+ provider: 'claude-code',
+ toolCallId: 'child-question',
+ }),
+ ]);
+ expect(
+ [...h.messages.values()].filter((m) => m.tool_call_id === 'child-question'),
+ ).toHaveLength(1);
+ expect(notifyAgentInterventionRequired).toHaveBeenCalledWith(
+ expect.objectContaining({
+ context: expect.objectContaining({
+ assistantMessageId: toolRow.parentId,
+ scope: 'thread',
+ threadId: toolRow.threadId,
+ }),
+ }),
+ );
+ await ingest(h, [
+ buildEvent(outcome === 'answer' ? 'agent_intervention_response' : 'tool_result', 2, {
+ ...(outcome === 'answer'
+ ? { producerAck: true, result: { 'Proceed?': 'Yes' } }
+ : { content: 'done', subagent: child }),
+ toolCallId: 'child-question',
+ }),
+ ]);
+ expect(h.messages.get(toolRow.id)?.plugin?.intervention.status).toBe(
+ outcome === 'answer' ? 'approved' : 'aborted',
+ );
+ expect(h.messages.get(toolRow.id)?.threadId).toBe(toolRow.threadId);
+ },
+ );
+
const materializeAskUserTool = async (
h: ReturnType<typeof createHarness>,
toolCallId: string,
@@ -60,6 +137,63 @@ describe('HeterogeneousPersistenceHandler — event branch coverage', () => {
toolCallId,
});
+ it.each(['tool_result', 'agent_runtime_end', 'error', 'finish'])(
+ 'persists automatic closure on %s even after a cold replica reload',
+ async (type) => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+ const request = missingProviderRequest('ended-question');
+ request.data.provider = 'claude-code';
+ await ingest(h, [request]);
+ const question = [...h.messages.values()].find((m) => m.tool_call_id === 'ended-question')!;
+ h.messages.set('other-operation-question', {
+ ...question,
+ id: 'other-operation-question',
+ tool_call_id: 'other-question',
+ plugin: {
+ ...question.plugin,
+ intervention: { status: 'pending', operationId: 'other-op' },
+ },
+ });
+ h.messageModel.listMessagePluginsByTopic.mockImplementation(
+ async () =>
+ [...h.messages.values()]
+ .filter((m) => m.role === 'tool')
+ .map((m) => ({
+ ...m.plugin,
+ id: m.id,
+ state: m.pluginState,
+ toolCallId: m.tool_call_id,
+ })) as never[],
+ );
+ __resetOperationStatesForTesting();
+
+ if (type === 'finish') {
+ await h.handler.finish({
+ operationId: h.operationId,
+ topicId: h.topicId,
+ result: 'success',
+ });
+ } else {
+ await ingest(h, [buildEvent(type, 2, { content: 'done', toolCallId: 'ended-question' })]);
+ }
+
+ const row = [...h.messages.values()].find((m) => m.tool_call_id === 'ended-question');
+ expect(row?.plugin?.intervention).toMatchObject({ status: 'aborted', resolving: false });
+ expect(row?.pluginState?.heterogeneousIntervention.transition).toBe('session_ended');
+ expect(h.messages.get('other-operation-question')?.plugin?.intervention.status).toBe(
+ 'pending',
+ );
+ expect(acknowledgeAgentInterventionProducerResolution).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'session_ended', toolCallId: 'ended-question' }),
+ );
+ __resetOperationStatesForTesting();
+ await ingest(h, [{ ...request, timestamp: request.timestamp + 1 }]);
+ const restored = [...h.messages.values()].find((m) => m.tool_call_id === 'ended-question');
+ expect(restored?.plugin?.intervention.status).toBe('aborted');
+ expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
+ },
+ );
+
it('rejects an invalid first Cloud review before any intervention side effect', async () => {
const h = createHarness({ topicAgentId: 'agent-test' });
const toolCallId = 'invalid-cloud-question';
@@ -104,77 +238,80 @@ describe('HeterogeneousPersistenceHandler — event branch coverage', () => {
});
});
- it('canonicalizes an omitted Claude multiSelect before durable review notification', async () => {
- const h = createHarness({ topicAgentId: 'agent-test' });
+ it.each(['claude-code', 'opencode'] as const)(
+ 'canonicalizes an omitted %s multiSelect before durable review notification',
+ async (provider) => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
- await ingest(h, [
- buildEvent('agent_intervention_request', 0, {
- apiName: 'askUserQuestion',
- arguments: JSON.stringify({
- questions: [
- {
- header: 'Producer ACK E2E',
- options: [
- { description: 'Proceed with validation.', label: 'Continue' },
- { description: 'Halt validation.', label: 'Stop' },
- ],
- question: 'Continue read only validation?',
- },
- ],
- }),
- deadline: 1_900_000_000_000,
- identifier: 'claude-code',
- interactionKind: 'question',
- provider: 'claude-code',
- toolCallId: 'claude-question-1',
- }),
- ]);
-
- expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
- expect(notifyAgentInterventionRequired.mock.calls[0][0]).toMatchObject({
- items: [
- {
- detail: {
+ await ingest(h, [
+ buildEvent('agent_intervention_request', 0, {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({
questions: [
{
header: 'Producer ACK E2E',
- id: 'question_1',
- multiple: false,
options: [
- {
- description: 'Proceed with validation.',
- id: 'Continue',
- label: 'Continue',
- },
- {
- description: 'Halt validation.',
- id: 'Stop',
- label: 'Stop',
- },
+ { description: 'Proceed with validation.', label: 'Continue' },
+ { description: 'Halt validation.', label: 'Stop' },
],
question: 'Continue read only validation?',
},
],
- title: 'Producer ACK E2E',
- type: 'question',
- },
- interactionKind: 'question',
- provider: 'claude-code',
- summary: 'Continue read only validation?',
- },
- ],
- summary: 'Continue read only validation?',
- });
- expect(h.messageModel.updatePluginState).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({
- heterogeneousIntervention: expect.objectContaining({
+ }),
+ deadline: 1_900_000_000_000,
+ identifier: 'claude-code',
interactionKind: 'question',
- provider: 'claude-code',
+ provider,
+ toolCallId: 'claude-question-1',
}),
- }),
- );
- });
+ ]);
+
+ expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
+ expect(notifyAgentInterventionRequired.mock.calls[0][0]).toMatchObject({
+ items: [
+ {
+ detail: {
+ questions: [
+ {
+ header: 'Producer ACK E2E',
+ id: 'question_1',
+ multiple: false,
+ options: [
+ {
+ description: 'Proceed with validation.',
+ id: 'Continue',
+ label: 'Continue',
+ },
+ {
+ description: 'Halt validation.',
+ id: 'Stop',
+ label: 'Stop',
+ },
+ ],
+ question: 'Continue read only validation?',
+ },
+ ],
+ title: 'Producer ACK E2E',
+ type: 'question',
+ },
+ interactionKind: 'question',
+ provider,
+ summary: 'Continue read only validation?',
+ },
+ ],
+ summary: 'Continue read only validation?',
+ });
+ expect(h.messageModel.updatePluginState).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ heterogeneousIntervention: expect.objectContaining({
+ interactionKind: 'question',
+ provider,
+ }),
+ }),
+ );
+ },
+ );
it('lets the user type their own answer to a heterogeneous question', async () => {
const h = createHarness({ topicAgentId: 'agent-test' });
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
index 626f2febb6e..1d4fc1a4460 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
@@ -243,7 +243,7 @@ export class HeterogeneousPersistenceHandler {
// after the publish) races the refetch and the error card doesn't render
// live. Bootstrap from topic.metadata.runningOperation like ingest does;
// a stale/mismatched operation stays a no-op.
- if (!state && params.result === 'error' && params.error && params.topicId) {
+ if (!state && params.topicId) {
try {
state = await loadOrCreateState(
this.deps,
@@ -265,6 +265,20 @@ export class HeterogeneousPersistenceHandler {
if (!state) return;
try {
+ // A producer may finish without ingesting its final stream event. Close
+ // its pending questions before the caller publishes runtime_end. Refresh
+ // only the intervention projection: finish must not flush stale text.
+ await refreshToolMessageIndex(this.deps, state);
+ const terminal = reduceMainAgent(
+ state.main,
+ { type: 'agent_runtime_end' },
+ this.mainReduceCtx(state),
+ );
+ for (const intent of terminal.intents) {
+ if (intent.kind === 'setToolIntervention') {
+ await applyMainIntent(this.deps, state, intent, state.lastStepIndex);
+ }
+ }
if (params.error) await this.persistFinishError(state, params.error);
} finally {
operationStates.delete(params.operationId);
@@ -297,6 +311,7 @@ export class HeterogeneousPersistenceHandler {
return {
agentId: state.agentId,
newId: (kind) => (kind === 'thread' ? generateThreadId() : `msg_${createNanoId(18)()}`),
+ toolMessageIds: state.toolMsgIdByCallId,
topicId: state.topicId,
};
}
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts
index 69dbd514c7e..24ae3f07927 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts
@@ -27,6 +27,7 @@ interface StoredHeterogeneousIntervention {
deadline?: number;
interactionKind?: AgentInterventionInteractionKind;
notificationTransition?: MainAgentInterventionTransition;
+ operationId: string;
provider?: AgentInterventionProvider;
resolutionRequestId?: string;
summary?: string;
@@ -144,6 +145,7 @@ export const INTERVENTION_PROVIDERS = new Set<AgentInterventionProvider>([
'cursor',
'devin',
'droid',
+ 'opencode',
'qoder',
]);
@@ -180,6 +182,7 @@ export async function applyToolIntervention(
const durableState: StoredHeterogeneousIntervention = {
deadline: intent.request?.deadline,
interactionKind: intent.request?.interactionKind,
+ operationId: state.operationId,
provider: intent.request?.provider,
resolutionRequestId: intent.resolutionRequestId,
summary,
@@ -203,7 +206,8 @@ export async function applyToolIntervention(
`Unsafe heterogeneous intervention review payload toolCallId=${intent.toolCallId}`,
);
}
- const assistantMessageId = state.main.currentAssistantId;
+ const toolMessage = await deps.messageModel.findById(toolMsgId);
+ const assistantMessageId = toolMessage?.parentId ?? state.main.currentAssistantId;
if (!assistantMessageId) {
throw new Error(
`Missing assistant owner for heterogeneous intervention toolCallId=${intent.toolCallId}`,
@@ -246,6 +250,7 @@ export async function applyToolIntervention(
agentId: state.agentId ?? undefined,
assistantMessageId,
operationId: state.operationId,
+ ...(toolMessage?.threadId && { scope: 'thread' as const, threadId: toolMessage.threadId }),
topicId: state.topicId,
workspaceId: deps.workspaceId,
},
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
index f481cc67916..bb92c136cbc 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
@@ -279,7 +279,12 @@ export async function refreshToolMessageIndex(
? (metadata.provider as AgentInterventionProvider)
: undefined;
- if (transition) {
+ if (
+ transition &&
+ (plugin.intervention?.operationId ??
+ metadata.operationId ??
+ plugin.metadata?.operationId) === state.operationId
+ ) {
const request =
typeof plugin.apiName === 'string' &&
typeof plugin.arguments === 'string' &&
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 99a69a9712d..23cc853fe46 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2806,6 +2806,7 @@
"tool.intervention.stopTooltip": "Stop here — nothing pending runs and the agent does not continue",
"tool.intervention.submit": "Submit",
"tool.intervention.toolAbort": "You canceled this Skill call",
+ "tool.intervention.toolEnded": "This tool call has ended",
"tool.intervention.toolRejected": "This Skill call was rejected",
"tool.intervention.toolSkipped": "You skipped this step",
"tool.intervention.viewParameters": "View parameters ({{count}})",
diff --git a/locales/en-US/tool.json b/locales/en-US/tool.json
index f960649d833..c9770841817 100644
--- a/locales/en-US/tool.json
+++ b/locales/en-US/tool.json
@@ -41,7 +41,6 @@
"agentMarketplace.render.alreadyInLibraryTag": "Already in library",
"agentMarketplace.render.alreadyInLibrary_one": "{{count}} already in library",
"agentMarketplace.render.alreadyInLibrary_other": "{{count}} already in library",
- "askUserQuestion.checkStatus": "Check submission status",
"askUserQuestion.checking": "Checking submission status…",
"askUserQuestion.customOption.placeholder": "Or write your own…",
"askUserQuestion.escape.back": "Back to options",
@@ -55,7 +54,6 @@
"askUserQuestion.submitting": "Submitting your response…",
"askUserQuestion.supplement.enter": "Additional notes",
"askUserQuestion.supplement.placeholder": "Add context to your selected answers…",
- "askUserQuestion.uncertain": "We couldn’t confirm whether your response was received. Check its status before trying again.",
"claudeCode.askUserQuestion.customOption.placeholder": "Or write your own…",
"claudeCode.askUserQuestion.escape.back": "Back to options",
"claudeCode.askUserQuestion.escape.enter": "Replace all",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 772185576ca..4fe35e8111d 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2806,6 +2806,7 @@
"tool.intervention.stopTooltip": "就停在这一步——待审批的工具都不会执行,Agent 也不会继续",
"tool.intervention.submit": "提交",
"tool.intervention.toolAbort": "你已取消本次技能调用",
+ "tool.intervention.toolEnded": "本次工具调用已结束",
"tool.intervention.toolRejected": "本次技能调用已被拒绝",
"tool.intervention.toolSkipped": "你已跳过此步骤",
"tool.intervention.viewParameters": "查看参数 ({{count}})",
diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.json
index b2305a3eb96..3652dff61d7 100644
--- a/locales/zh-CN/tool.json
+++ b/locales/zh-CN/tool.json
@@ -41,7 +41,6 @@
"agentMarketplace.render.alreadyInLibraryTag": "已在库中",
"agentMarketplace.render.alreadyInLibrary_one": "{{count}} 个已在库中",
"agentMarketplace.render.alreadyInLibrary_other": "{{count}} 个已在库中",
- "askUserQuestion.checkStatus": "检查提交状态",
"askUserQuestion.checking": "正在确认提交状态…",
"askUserQuestion.customOption.placeholder": "或自己输入…",
"askUserQuestion.escape.back": "返回选项",
@@ -55,7 +54,6 @@
"askUserQuestion.submitting": "正在提交你的回答…",
"askUserQuestion.supplement.enter": "补充说明",
"askUserQuestion.supplement.placeholder": "为已选答案补充更多背景…",
- "askUserQuestion.uncertain": "暂时无法确认回答是否已收到,请先检查提交状态。",
"claudeCode.askUserQuestion.customOption.placeholder": "或自己输入…",
"claudeCode.askUserQuestion.escape.back": "返回选项",
"claudeCode.askUserQuestion.escape.enter": "全部替换",
diff --git a/packages/agent-gateway-client/src/intervention.test.ts b/packages/agent-gateway-client/src/intervention.test.ts
index 93b425e5bc7..dd191e008e0 100644
--- a/packages/agent-gateway-client/src/intervention.test.ts
+++ b/packages/agent-gateway-client/src/intervention.test.ts
@@ -28,6 +28,14 @@ const request = (overrides: Partial<AgentInterventionRequestData> = {}) => ({
});
describe('sanitizeAgentInterventionRequestForReview', () => {
+ it('accepts an OpenCode question while retaining its producer identity', () => {
+ expect(
+ sanitizeAgentInterventionRequestForReview(
+ request({ identifier: 'opencode', interactionKind: 'question', provider: 'opencode' }),
+ ),
+ ).toMatchObject({ identifier: 'opencode', interactionKind: 'question', provider: 'opencode' });
+ });
+
it('keeps only canonical review fields and exact provider option ids', () => {
const sanitized = sanitizeAgentInterventionRequestForReview(request());
diff --git a/packages/agent-gateway-client/src/intervention.ts b/packages/agent-gateway-client/src/intervention.ts
index 82be478f01e..bca9cd0c8ab 100644
--- a/packages/agent-gateway-client/src/intervention.ts
+++ b/packages/agent-gateway-client/src/intervention.ts
@@ -16,6 +16,7 @@ const PROVIDERS = new Set<AgentInterventionProvider>([
'cursor',
'devin',
'droid',
+ 'opencode',
'qoder',
]);
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index 638228f4c44..89250d14aa7 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -261,7 +261,8 @@ export interface OperationHeartbeatData extends StepCompleteData {
export type AgentInterventionInteractionKind = 'permission' | 'plan' | 'question';
/** Producer that owns the blocked interaction. */
-export type AgentInterventionProvider = 'claude-code' | 'cursor' | 'devin' | 'droid' | 'qoder';
+export type AgentInterventionProvider =
+ 'claude-code' | 'cursor' | 'devin' | 'droid' | 'opencode' | 'qoder';
/** Whitelisted option surface that may be persisted for cold-start review. */
export interface AgentInterventionRenderOption {
diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx
index f4542804ea3..a4e97251ea4 100644
--- a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx
@@ -6,10 +6,13 @@ import {
AskUserQuestionView,
DEFAULT_COUNTDOWN_MS,
DRAFT_PLUGIN_STATE_KEY,
+ SUBMIT_ACK_TIMEOUT_MS,
useAskUserForm,
} from '@lobechat/shared-tool-ui/ask-user';
import type { BuiltinInterventionProps } from '@lobechat/types';
-import { memo, useCallback } from 'react';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { CircleAlert } from 'lucide-react';
+import { memo, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useConversationStore } from '@/features/Conversation/store';
@@ -51,6 +54,12 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
)?.heterogeneousIntervention?.deadline;
return typeof stored === 'number' ? stored : undefined;
});
+ const context = useConversationStore((s) => s.context);
+ const checkQuestionSubmission = useChatStore((s) => s.checkQuestionSubmission);
+ const submissionPhase = useChatStore((s) => s.questionSubmissions[messageId]);
+ const resolving = useConversationStore(
+ (s) => dataSelectors.getDbMessageById(messageId)(s)?.pluginIntervention?.resolving === true,
+ );
const setInterventionDraft = useChatStore((s) => s.setInterventionDraft);
const writeDraft = useCallback(
(draft: AskUserDraft) => setInterventionDraft(messageId, draft),
@@ -67,6 +76,19 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
writeDraft,
});
+ // Stream events normally settle the card. Revalidate a missed ACK after
+ // remount or reconnect without asking the user to inspect runtime state.
+ useEffect(() => {
+ if (!resolving) return;
+ const reconcile = () => void checkQuestionSubmission(messageId, context);
+ const timer = window.setTimeout(reconcile, SUBMIT_ACK_TIMEOUT_MS);
+ window.addEventListener('online', reconcile);
+ return () => {
+ window.clearTimeout(timer);
+ window.removeEventListener('online', reconcile);
+ };
+ }, [checkQuestionSubmission, context, messageId, resolving]);
+
const labels = {
customPlaceholder: t('claudeCode.askUserQuestion.customOption.placeholder'),
escapeBack: t('claudeCode.askUserQuestion.escape.back'),
@@ -84,12 +106,21 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
};
return (
- <AskUserQuestionView
- {...form}
- showCountdown
- actionsPortalTarget={actionsPortalTarget}
- labels={labels}
- />
+ <Flexbox gap={8}>
+ {(form.submissionFailed ||
+ submissionPhase === 'failed' ||
+ submissionPhase === 'uncertain') && (
+ <Text fontSize={12} role="alert" type="danger">
+ <Icon icon={CircleAlert} size={14} /> {t('askUserQuestion.submitFailed')}
+ </Text>
+ )}
+ <AskUserQuestionView
+ {...form}
+ showCountdown
+ actionsPortalTarget={actionsPortalTarget}
+ labels={labels}
+ />
+ </Flexbox>
);
});
diff --git a/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx b/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx
index b115ea8c168..beb31de1999 100644
--- a/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx
+++ b/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx
@@ -8,9 +8,9 @@ import {
useAskUserForm,
} from '@lobechat/shared-tool-ui/ask-user';
import type { BuiltinInterventionProps } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Alert, Button, Spin, Text } from '@lobehub/ui';
-import { memo, useCallback } from 'react';
+import { Flexbox, Icon, Spin, Text } from '@lobehub/ui';
+import { CircleAlert } from 'lucide-react';
+import { memo, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useConversationStore } from '@/features/Conversation/store';
@@ -57,6 +57,13 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
writeDraft,
});
+ useEffect(() => {
+ if (submissionPhase !== 'uncertain') return;
+ const reconcile = () => void checkQuestionSubmission(messageId, context);
+ window.addEventListener('online', reconcile);
+ return () => window.removeEventListener('online', reconcile);
+ }, [checkQuestionSubmission, context, messageId, submissionPhase]);
+
// Read-only surfaces (resolved / historical messages) show a compact summary
// of what was asked instead of the interactive form.
if (interactionMode !== 'custom') {
@@ -92,17 +99,6 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
);
}
- if (submissionPhase === 'uncertain') {
- return (
- <Flexbox gap={8} padding={8}>
- <Text role="status">{t('askUserQuestion.uncertain')}</Text>
- <Button onClick={() => checkQuestionSubmission(messageId, context)}>
- {t('askUserQuestion.checkStatus')}
- </Button>
- </Flexbox>
- );
- }
-
const labels = {
customPlaceholder: t('askUserQuestion.customOption.placeholder'),
escapeBack: t('askUserQuestion.escape.back'),
@@ -121,8 +117,10 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
return (
<Flexbox gap={8}>
- {submissionPhase === 'failed' && (
- <Alert title={t('askUserQuestion.submitFailed')} type="error" />
+ {(submissionPhase === 'failed' || submissionPhase === 'uncertain') && (
+ <Text fontSize={12} role="alert" type="danger">
+ <Icon icon={CircleAlert} size={14} /> {t('askUserQuestion.submitFailed')}
+ </Text>
)}
<AskUserQuestionView
{...form}
diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.ts
index 83c2f0ec690..08a71e1514a 100644
--- a/packages/builtin-tools/src/register.ts
+++ b/packages/builtin-tools/src/register.ts
@@ -309,7 +309,10 @@ export const registerBuiltinToolSurfaces = (): void => {
[LobeActivatorManifest.identifier]: LobeActivatorRenders as Record<string, BuiltinRender>,
[WebBrowsingManifest.identifier]: WebBrowsingRenders as Record<string, BuiltinRender>,
[WebOnboardingManifest.identifier]: WebOnboardingRenders as Record<string, BuiltinRender>,
- [OPENCODE_IDENTIFIER]: heterogeneousCliRenders,
+ [OPENCODE_IDENTIFIER]: {
+ ...heterogeneousCliRenders,
+ [ClaudeCodeApiName.AskUserQuestion]: ClaudeCodeRenders[ClaudeCodeApiName.AskUserQuestion],
+ },
[PI_IDENTIFIER]: heterogeneousCliRenders,
[KIMI_CODE_IDENTIFIER]: KimiCodeRenders as Record<string, BuiltinRender>,
codex: {
@@ -386,7 +389,10 @@ export const registerBuiltinToolSurfaces = (): void => {
[UserInteractionIdentifier]: UserInteractionInspectors as Record<string, BuiltinInspector>,
[WebBrowsingManifest.identifier]: WebBrowsingInspectors as Record<string, BuiltinInspector>,
[WebOnboardingManifest.identifier]: WebOnboardingInspectors as Record<string, BuiltinInspector>,
- [OPENCODE_IDENTIFIER]: heterogeneousCliInspectors,
+ [OPENCODE_IDENTIFIER]: {
+ ...heterogeneousCliInspectors,
+ [ClaudeCodeApiName.AskUserQuestion]: ClaudeCodeInspectors[ClaudeCodeApiName.AskUserQuestion],
+ },
[PI_IDENTIFIER]: heterogeneousCliInspectors,
[KIMI_CODE_IDENTIFIER]: KimiCodeInspectors,
'codex': CodexInspectors,
@@ -445,6 +451,10 @@ export const registerBuiltinToolSurfaces = (): void => {
ClaudeCodeInterventions[ClaudeCodeApiName.AskUserQuestion],
},
[QODER_IDENTIFIER]: ClaudeCodeInterventions as Record<string, BuiltinIntervention>,
+ [OPENCODE_IDENTIFIER]: {
+ [ClaudeCodeApiName.AskUserQuestion]:
+ ClaudeCodeInterventions[ClaudeCodeApiName.AskUserQuestion],
+ },
[CredsIdentifier]: CredsInterventions as Record<string, BuiltinIntervention>,
[CloudSandboxManifest.identifier]: CloudSandboxInterventions as Record<
string,
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
index 5267e412ba6..22128f38e5b 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
@@ -619,6 +619,65 @@ describe('reduceMainAgent — heterogeneous intervention ACK boundary', () => {
expect(state.interventionsByCallId.get('permission-1')?.transition).toBe('pending');
});
+ it('keeps an existing subagent question out of the main tool batch and applies its ACK', () => {
+ const ctx = makeCtx({ toolMessageIds: new Map([['permission-1', 'child-tool']]) });
+ const ack = {
+ data: { producerAck: true, result: { answer: 'allow' }, toolCallId: 'permission-1' },
+ type: 'agent_intervention_response',
+ };
+ const { state, steps } = run([request, ack], 'A0', ctx);
+
+ expect(ofKind(steps[0], 'persistToolBatch')).toEqual([]);
+ expect(state.toolState.toolMsgIdByCallId.size).toBe(0);
+ expect(ofKind(steps[1], 'setToolIntervention')).toEqual([
+ expect.objectContaining({ intervention: { status: 'approved' }, toolCallId: 'permission-1' }),
+ ]);
+ });
+
+ it('closes a scoped child result and keeps a late unscoped request on the original tool', () => {
+ const ctx = makeCtx({ toolMessageIds: new Map([['permission-1', 'child-tool']]) });
+ const result = {
+ data: {
+ content: 'done',
+ subagent: { parentToolCallId: 'task-1', subagentMessageId: 'child-turn' },
+ toolCallId: 'permission-1',
+ },
+ type: 'tool_result',
+ };
+ const { state, steps } = run([request, result, request], 'A0', ctx);
+
+ expect(ofKind(steps[1], 'setToolIntervention')).toEqual([
+ expect.objectContaining({ toolCallId: 'permission-1', transition: 'session_ended' }),
+ ]);
+ expect(ofKind(steps[1], 'resolveToolResult')).toHaveLength(0);
+ expect(ofKind(steps[2], 'persistToolBatch')).toEqual([]);
+ expect(state.interventionsByCallId.get('permission-1')?.intervention.status).toBe('aborted');
+ });
+
+ it('closes a child question when its parent finishes and keeps late requests out of main', () => {
+ const ctx = makeCtx({ toolMessageIds: new Map([['permission-1', 'child-tool']]) });
+ const childTools = {
+ data: {
+ chunkType: 'tools_calling',
+ subagent: { parentToolCallId: 'task-1', subagentMessageId: 'child-turn' },
+ toolsCalling: [{ ...tool('permission-1'), apiName: 'askUserQuestion' }],
+ },
+ type: 'stream_chunk',
+ };
+ const { state, steps } = run(
+ [childTools, request, toolResultEvent('task-1', 'child finished'), request],
+ 'A0',
+ ctx,
+ );
+
+ expect(state.subagents.runs.size).toBe(0);
+ expect(ofKind(steps[2], 'setToolIntervention')).toEqual([
+ expect.objectContaining({ toolCallId: 'permission-1', transition: 'session_ended' }),
+ ]);
+ expect(ofKind(steps[3], 'persistToolBatch')).toEqual([]);
+ expect(ofKind(steps[3], 'setToolIntervention')[0].transition).toBe('session_ended');
+ });
+
it('keeps the XADD publish leg non-terminal and resolves only on producer ACK', () => {
const requestId = '018fbd8e-7baf-7c6d-8000-000000000001';
const publishLeg = {
@@ -670,4 +729,52 @@ describe('reduceMainAgent — heterogeneous intervention ACK boundary', () => {
});
expect(state.interventionsByCallId.get('permission-1')?.transition).toBe('resolved');
});
+
+ it('closes only the question whose upstream tool has returned, without a user response', () => {
+ const other = { ...request, data: { ...request.data, toolCallId: 'question-2' } };
+ const { state, steps } = run([request, other, toolResultEvent('permission-1', 'done')]);
+
+ expect(ofKind(steps[2], 'setToolIntervention')).toEqual([
+ expect.objectContaining({
+ intervention: { rejectedReason: 'session_ended', resolving: false, status: 'aborted' },
+ toolCallId: 'permission-1',
+ transition: 'session_ended',
+ }),
+ ]);
+ expect(state.interventionsByCallId.get('question-2')?.transition).toBe('pending');
+ });
+
+ it.each(['agent_runtime_end', 'error'])('closes unanswered questions on %s', (type) => {
+ const { state, steps } = run([request, { data: {}, type }]);
+ expect(ofKind(steps[1], 'setToolIntervention')).toEqual([
+ expect.objectContaining({ toolCallId: 'permission-1', transition: 'session_ended' }),
+ ]);
+ expect(state.interventionsByCallId.get('permission-1')?.intervention.status).toBe('aborted');
+ });
+
+ it('preserves an acknowledged answer after the tool and runtime finish', () => {
+ const ack = {
+ data: { producerAck: true, result: { 'Run command?': 'allow' }, toolCallId: 'permission-1' },
+ type: 'agent_intervention_response',
+ };
+ const { state, steps } = run([
+ request,
+ ack,
+ toolResultEvent('permission-1', 'done'),
+ { type: 'agent_runtime_end' },
+ ]);
+ expect(ofKind(steps[2], 'setToolIntervention')).toEqual([]);
+ expect(ofKind(steps[3], 'setToolIntervention')).toEqual([]);
+ expect(state.interventionsByCallId.get('permission-1')?.intervention.status).toBe('approved');
+ });
+
+ it.each(['tool_result', 'agent_runtime_end'])(
+ 'does not reopen a late request after %s',
+ (type) => {
+ const end = { data: { toolCallId: 'permission-1', content: 'done' }, type };
+ const { state, steps } = run([end, request]);
+ expect(state.interventionsByCallId.get('permission-1')?.intervention.status).toBe('aborted');
+ expect(ofKind(steps[1], 'setToolIntervention')[0]?.transition).toBe('session_ended');
+ },
+ );
});
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
index 29eca8b5a6a..09240eed1fb 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
@@ -342,13 +342,24 @@ const reduceInterventionRequest = (
const intervention: MainAgentInterventionState = existing
? { ...existing, request }
: { intervention: { status: 'pending' }, request, transition: 'pending' };
+ if (state.ended && intervention.intervention.status === 'pending') {
+ intervention.intervention = {
+ rejectedReason: 'session_ended',
+ resolving: false,
+ status: 'aborted',
+ };
+ intervention.transition = 'session_ended';
+ }
preparedState.interventionsByCallId.set(request.toolCallId, intervention);
// The bridge and the adapter run on independent async pumps, so the request
// can arrive before tools_calling. The request already carries the complete
// canonical tool payload; materialize it here instead of dropping pending
// state or relying on process affinity for a later replay.
- if (!state.toolState.toolMsgIdByCallId.has(request.toolCallId)) {
+ if (
+ !state.toolState.toolMsgIdByCallId.has(request.toolCallId) &&
+ !ctx.toolMessageIds?.has(request.toolCallId)
+ ) {
return reduceToolsChunk(
preparedState,
[
@@ -370,7 +381,11 @@ const reduceInterventionRequest = (
};
};
-const reduceInterventionResponse = (state: MainAgentRunState, data: any): ReduceResult => {
+const reduceInterventionResponse = (
+ state: MainAgentRunState,
+ data: any,
+ ctx: MainAgentReduceCtx,
+): ReduceResult => {
if (typeof data?.toolCallId !== 'string' || data.toolCallId.length === 0) {
return { intents: [], state };
}
@@ -401,7 +416,10 @@ const reduceInterventionResponse = (state: MainAgentRunState, data: any): Reduce
const next = copyState(state);
next.interventionsByCallId.set(data.toolCallId, intervention);
- if (!state.toolState.toolMsgIdByCallId.has(data.toolCallId)) {
+ if (
+ !state.toolState.toolMsgIdByCallId.has(data.toolCallId) &&
+ !ctx.toolMessageIds?.has(data.toolCallId)
+ ) {
return { intents: [], state: next };
}
@@ -411,6 +429,31 @@ const reduceInterventionResponse = (state: MainAgentRunState, data: any): Reduce
};
};
+/** A terminal tool/run is authoritative even when its bridge ACK never arrives. */
+const endInterventions = (
+ state: MainAgentRunState,
+ toolCallIds: Iterable<string>,
+): ReduceResult => {
+ const next = copyState(state);
+ const intents: AnyIntent[] = [];
+ for (const toolCallId of toolCallIds) {
+ const existing = next.interventionsByCallId.get(toolCallId);
+ if (existing && existing.intervention.status !== 'pending') continue;
+ const ended: MainAgentInterventionState = {
+ ...existing,
+ intervention: { rejectedReason: 'session_ended', resolving: false, status: 'aborted' },
+ transition: 'session_ended',
+ };
+ // Remember results that race ahead of the bridge request, without creating
+ // an intervention write/notification for ordinary tools.
+ next.interventionsByCallId.set(toolCallId, ended);
+ if (existing?.request) {
+ intents.push({ ...ended, kind: 'setToolIntervention', toolCallId });
+ }
+ }
+ return { intents, state: next };
+};
+
const reduceStreamChunk = (
state: MainAgentRunState,
data: any,
@@ -472,8 +515,12 @@ const reduceToolResult = (
pluginState: data.pluginState,
toolCallId,
};
- const delegated = delegateSubagent(state, event, ctx);
- return { intents: [main, ...delegated.intents], state: delegated.state };
+ const ended = endInterventions(state, [
+ toolCallId,
+ ...(state.subagents.runs.get(toolCallId)?.lifetimeToolCallIds ?? []),
+ ]);
+ const delegated = delegateSubagent(ended.state, event, ctx);
+ return { intents: [main, ...ended.intents, ...delegated.intents], state: delegated.state };
};
const reduceTurnMetadata = (state: MainAgentRunState, data: any): ReduceResult => {
@@ -553,12 +600,13 @@ const reduceTerminal = (
// Reset accumulators so a follow-up terminal/flush is an idempotent no-op,
// then drain any subagent runs that never saw their parent tool_result.
- const drained = copyState(state);
+ const ended = endInterventions(state, state.interventionsByCallId.keys());
+ const drained = ended.state;
drained.accContent = '';
drained.accReasoning = '';
drained.ended = true;
const delegated = delegateSubagent(drained, event, ctx);
- return { intents: [...intents, ...delegated.intents], state: delegated.state };
+ return { intents: [...intents, ...ended.intents, ...delegated.intents], state: delegated.state };
};
/**
@@ -572,7 +620,16 @@ export const reduce = (
ctx: MainAgentReduceCtx,
): ReduceResult => {
// Subagent-tagged chunks / turn_metadata belong wholly to the coordinator.
- if (getEventScope(event).kind === 'subagent') return delegateSubagent(state, event, ctx);
+ if (getEventScope(event).kind === 'subagent') {
+ const ended =
+ event.type === 'tool_result' &&
+ typeof event.data?.toolCallId === 'string' &&
+ event.data.toolCallId
+ ? endInterventions(state, [event.data?.toolCallId])
+ : { intents: [], state };
+ const delegated = delegateSubagent(ended.state, event, ctx);
+ return { intents: [...ended.intents, ...delegated.intents], state: delegated.state };
+ }
const data = event.data ?? {};
switch (event.type) {
@@ -599,7 +656,7 @@ export const reduce = (
return reduceInterventionRequest(state, data, ctx);
}
case 'agent_intervention_response': {
- return reduceInterventionResponse(state, data);
+ return reduceInterventionResponse(state, data, ctx);
}
case 'step_complete': {
if (data?.phase === 'turn_metadata') return reduceTurnMetadata(state, data);
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
index 0a8304a283f..8c5157655b8 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
@@ -169,6 +169,8 @@ export interface MainAgentReduceCtx {
agentId?: string | null;
/** Allocate a prefixed id (`thd_…` / `msg_…`). Deterministic counter in tests. */
newId: (kind: 'message' | 'thread') => string;
+ /** Persisted tools across all turns and subagent threads, owned by the interpreter. */
+ toolMessageIds?: ReadonlyMap<string, string>;
topicId: string | null;
}
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 1f584f80de6..0ea9d375625 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -3235,6 +3235,7 @@ export default {
'tool.intervention.scrollToIntervention': 'View',
'tool.intervention.viewParameters': 'View parameters ({{count}})',
'tool.intervention.toolAbort': 'You canceled this Skill call',
+ 'tool.intervention.toolEnded': 'This tool call has ended',
'tool.intervention.toolRejected': 'This Skill call was rejected',
'tool.intervention.questionSkipped': 'You skipped this question',
'tool.intervention.questionTimedOut': 'This question timed out before it was answered',
diff --git a/packages/locales/src/default/tool.ts b/packages/locales/src/default/tool.ts
index 78ab87fb6cc..d61e0e503a4 100644
--- a/packages/locales/src/default/tool.ts
+++ b/packages/locales/src/default/tool.ts
@@ -1,9 +1,6 @@
export default {
'askUserQuestion.submitting': 'Submitting your response…',
'askUserQuestion.checking': 'Checking submission status…',
- 'askUserQuestion.uncertain':
- 'We couldn’t confirm whether your response was received. Check its status before trying again.',
- 'askUserQuestion.checkStatus': 'Check submission status',
'askUserQuestion.submitFailed':
'Your response hasn’t been confirmed. Your answers are saved; please try again.',
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts
index ab6081dcc0a..50f8a6ebb9b 100644
--- a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts
+++ b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts
@@ -566,3 +566,30 @@ describe('useAskUserForm requireAllAnswered', () => {
});
});
});
+
+describe('question submission recovery', () => {
+ it('keeps the answer and exposes failure so an explicit retry can succeed', async () => {
+ const { hook, onInteractionAction } = setup(singleQuestionArgs);
+ onInteractionAction.mockRejectedValueOnce(new Error('offline'));
+ act(() => hook.result.current.handleToggle(singleQuestionArgs.questions[0], 'Narrow'));
+ await act(async () => hook.result.current.handleSubmit());
+ expect(hook.result.current.submissionFailed).toBe(true);
+ expect(hook.result.current.submitting).toBe(false);
+ expect(hook.result.current.picks['How broad?']).toBe('Narrow');
+ await act(async () => hook.result.current.handleSubmit());
+ expect(hook.result.current.submissionFailed).toBe(false);
+ expect(onInteractionAction).toHaveBeenCalledTimes(2);
+ hook.unmount();
+ });
+
+ it('does not send both submit and skip before React renders the busy state', async () => {
+ const { hook, onInteractionAction } = setup(singleQuestionArgs);
+ act(() => hook.result.current.handleToggle(singleQuestionArgs.questions[0], 'Narrow'));
+ await act(async () => {
+ hook.result.current.handleSubmit();
+ hook.result.current.handleSkip();
+ });
+ expect(onInteractionAction).toHaveBeenCalledTimes(1);
+ hook.unmount();
+ });
+});
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts
index c158cabc439..d211b79e2c3 100644
--- a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts
+++ b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts
@@ -85,6 +85,7 @@ export interface AskUserFormApi {
setEscapeMode: (next: boolean) => void;
setQuestionMode: (key: string) => void;
setSupplementMode: (next: boolean) => void;
+ submissionFailed: boolean;
submitting: boolean;
supplementActive: boolean;
supplementText: string;
@@ -123,6 +124,8 @@ export const useAskUserForm = ({
() => initial.supplementActive && !initial.escapeActive,
);
const [submitting, setSubmitting] = useState(false);
+ const [submissionFailed, setSubmissionFailed] = useState(false);
+ const inFlight = useRef(false);
const [autoSubmitted, setAutoSubmitted] = useState(false);
const [activeTab, setActiveTab] = useState<string>(() => {
// Resume on the first unanswered question rather than always at Q1.
@@ -173,7 +176,10 @@ export const useAskUserForm = ({
useEffect(() => () => clearTimeout(ackTimer.current), []);
const awaitProducerAck = useCallback(() => {
clearTimeout(ackTimer.current);
- ackTimer.current = setTimeout(() => setSubmitting(false), SUBMIT_SETTLE_FALLBACK_MS);
+ ackTimer.current = setTimeout(() => {
+ inFlight.current = false;
+ setSubmitting(false);
+ }, SUBMIT_SETTLE_FALLBACK_MS);
}, []);
/**
@@ -183,13 +189,17 @@ export const useAskUserForm = ({
*/
const submitWith = useCallback(
async (payload: Record<string, string | string[]>) => {
- if (!onInteractionAction || submitting || disabled) return;
+ if (!onInteractionAction || inFlight.current || disabled) return;
+ inFlight.current = true;
+ setSubmissionFailed(false);
setSubmitting(true);
try {
await onInteractionAction({ payload, type: 'submit' });
awaitProducerAck();
} catch (err) {
console.error('[AskUserQuestion] submit failed:', err);
+ inFlight.current = false;
+ setSubmissionFailed(true);
setSubmitting(false);
}
},
@@ -420,13 +430,17 @@ export const useAskUserForm = ({
]);
const handleSkip = useCallback(async () => {
- if (!onInteractionAction || submitting || disabled) return;
+ if (!onInteractionAction || inFlight.current || disabled) return;
+ inFlight.current = true;
+ setSubmissionFailed(false);
setSubmitting(true);
try {
await onInteractionAction({ type: 'skip' });
awaitProducerAck();
} catch (err) {
console.error('[AskUserQuestion] skip failed:', err);
+ inFlight.current = false;
+ setSubmissionFailed(true);
setSubmitting(false);
}
}, [awaitProducerAck, disabled, onInteractionAction, submitting]);
@@ -523,6 +537,7 @@ export const useAskUserForm = ({
setQuestionMode,
setSupplementMode,
submitting: submitting || disabled,
+ submissionFailed,
supplementActive: inSupplement,
supplementText,
};
diff --git a/packages/types/src/agent/heterogeneousIntervention.ts b/packages/types/src/agent/heterogeneousIntervention.ts
index 6ab3273b728..75b090c7946 100644
--- a/packages/types/src/agent/heterogeneousIntervention.ts
+++ b/packages/types/src/agent/heterogeneousIntervention.ts
@@ -8,6 +8,7 @@ export const HETEROGENEOUS_AGENT_INTERVENTION_PROVIDERS = [
'cursor',
'devin',
'droid',
+ 'opencode',
'qoder',
] as const;
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/AbortResponse.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/AbortResponse.tsx
index 09bf46a1e0e..caa6178a8f6 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/AbortResponse.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/AbortResponse.tsx
@@ -2,10 +2,15 @@ import { Alert } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-const AbortResponse = memo(() => {
+const AbortResponse = memo<{ sessionEnded?: boolean }>(({ sessionEnded }) => {
const { t } = useTranslation('chat');
- return <Alert title={t('tool.intervention.toolAbort')} type={'secondary'} />;
+ return (
+ <Alert
+ title={t(sessionEnded ? 'tool.intervention.toolEnded' : 'tool.intervention.toolAbort')}
+ type={'secondary'}
+ />
+ );
});
export default AbortResponse;
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts
index 644970f74a6..447c478813d 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts
@@ -108,7 +108,7 @@ describe('customInteractionHandlers', () => {
});
});
- it.each(['devin', 'droid', 'qoder'])(
+ it.each(['devin', 'droid', 'opencode', 'qoder'])(
'routes %s tools through the heterogeneous custom flow',
(type) => {
expect(isCustomInteractionIdentifier(type, 'askUserQuestion')).toBe(true);
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts
index 4083b7dda62..947fa1c84a8 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts
@@ -19,6 +19,7 @@ import { topicService } from '@/services/topic';
const CURSOR_IDENTIFIER = 'cursor';
const DEVIN_IDENTIFIER = 'devin';
const DROID_IDENTIFIER = 'droid';
+const OPENCODE_IDENTIFIER = 'opencode';
const QODER_IDENTIFIER = 'qoder';
interface SubmitToolInteractionOptions {
@@ -172,6 +173,7 @@ const HETERO_CUSTOM_INTERACTION_IDENTIFIERS = new Set<string>([
CURSOR_IDENTIFIER,
DEVIN_IDENTIFIER,
DROID_IDENTIFIER,
+ OPENCODE_IDENTIFIER,
QODER_IDENTIFIER,
]);
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx
index 8ea2d130c94..891291029e0 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx
@@ -80,7 +80,7 @@ const Render = memo<RenderProps>(
}
if (intervention?.status === 'aborted') {
- return <AbortResponse />;
+ return <AbortResponse sessionEnded={intervention.rejectedReason === 'session_ended'} />;
}
// Handle arguments streaming state
diff --git a/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.test.ts b/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.test.ts
index 316a5d92198..1a58cfd097c 100644
--- a/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.test.ts
+++ b/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.test.ts
@@ -1,7 +1,10 @@
import { type UIChatMessage } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
+import { dispatchInterventionState } from '@/store/chat/slices/agentRun/actions/entries/interventionProjection';
+import { messagesReducer } from '@/store/chat/slices/message/reducer';
import { type Operation } from '@/store/chat/slices/operation/types';
+import type { ChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { collectGlobalApprovals } from './useGlobalPendingApprovals';
@@ -177,4 +180,51 @@ describe('collectGlobalApprovals', () => {
expect(groups[0].interventions[0].identifier).toBe('claude-code');
expect(groups[0].interventions[0].toolMessageId).toBe('msg_cc_tool');
});
+ it.each(['aborted', 'approved', 'rejected'] as const)(
+ 'removes a %s question from every tab while keeping another operation pending',
+ (status) => {
+ const source = { agentId: 'agent-source', topicId: 'topic-source' };
+ const unrelated = { agentId: 'agent-other', topicId: 'topic-other' };
+ const sourceKey = messageMapKey(source);
+ const otherKey = messageMapKey(unrelated);
+ const tool = pendingToolMessage('question-source', 'same-call-id');
+ const other = pendingToolMessage('question-other', 'same-call-id');
+ const state = {
+ dbMessagesMap: { [sourceKey]: [tool], [otherKey]: [other] },
+ operations: { source: op(source), other: op(unrelated) },
+ } as unknown as ChatStore;
+ state.internal_dispatchMessage = (action, options) => {
+ const bucket = messageMapKey(options!.context!);
+ state.dbMessagesMap[bucket] = messagesReducer(state.dbMessagesMap[bucket], action);
+ };
+ const tabViews = ['tab-a', 'tab-b', 'tab-hidden'].map(
+ (topicId) => () =>
+ collectGlobalApprovals(
+ state.dbMessagesMap,
+ state.operations,
+ messageMapKey({ agentId: 'viewer', topicId }),
+ ),
+ );
+ for (const read of tabViews)
+ expect(
+ read()
+ .flatMap((g) => g.interventions)
+ .map((i) => i.toolMessageId),
+ ).toContain(tool.id);
+ // The interpreter applies this production projection before awaiting persistence.
+ dispatchInterventionState(
+ () => state,
+ tool.id,
+ { status, resolving: false },
+ { context: source },
+ );
+ for (const read of tabViews) {
+ expect(
+ read()
+ .flatMap((g) => g.interventions)
+ .map((i) => i.toolMessageId),
+ ).toEqual([other.id]);
+ }
+ },
+ );
});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
index 017d62c2bf7..7b88e27d5f1 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -11,7 +11,6 @@ import { useUserStore } from '@/store/user';
import { useChatStore } from '../../../../store';
import { messageMapKey } from '../../../../utils/messageMapKey';
-import { dbMessageSelectors } from '../../../message/selectors';
import * as agentDispatcher from '../dispatch/agentDispatcher';
import { createMockMessage, createMockResolvedAgentConfig, TEST_IDS } from './fixtures';
import { resetTestEnvironment } from './helpers';
@@ -3304,6 +3303,7 @@ describe('ConversationControl actions', () => {
const resolvingIntervention = {
...toolMessage.pluginIntervention,
resolving: true,
+ skipped: actionType === 'skip',
status: 'pending',
};
expect(dispatchSpy).toHaveBeenCalledWith(
@@ -3431,9 +3431,9 @@ describe('ConversationControl actions', () => {
.mockResolvedValue(undefined as any);
await act(async () => {
- await result.current.submitHeteroIntervention('tool-msg-source-unavailable', 'submit', {
- Question: 'Answer',
- });
+ await expect(
+ result.current.submitHeteroIntervention(toolMessage.id, 'submit', { Question: 'Answer' }),
+ ).rejects.toThrow('Question runtime is unavailable');
});
expect(sourceMutation).toHaveBeenCalledOnce();
@@ -3503,11 +3503,10 @@ describe('ConversationControl actions', () => {
expect(sourceMutation).toHaveBeenCalledWith(
expect.objectContaining({ operationId: 'server-operation-local-fallback' }),
);
- expect(pluginSpy).toHaveBeenCalledWith(
- 'tool-msg-local-fallback',
- { intervention: { status: 'approved' } },
- { operationId: clientOperationId },
- );
+ expect(
+ result.current.dbMessagesMap[chatKey].find((m) => m.id === 'tool-msg-local-fallback')
+ ?.pluginIntervention,
+ ).toMatchObject({ status: 'pending', resolving: true });
expect(localSubmit).toHaveBeenCalledWith({
operationId: clientOperationId,
result: { Question: 'Answer' },
@@ -3704,7 +3703,7 @@ describe('ConversationControl actions', () => {
});
});
- it('submits via IPC, persists optimistic intervention, and flips topic status to running (submit)', async () => {
+ it('submits via IPC, awaits the producer result, and flips topic status to running', async () => {
const { result } = renderHook(() => useChatStore());
const agentId = 'hetero-agent';
@@ -3764,12 +3763,11 @@ describe('ConversationControl actions', () => {
await result.current.submitHeteroIntervention('tool-msg-1', 'submit', payload);
});
- // Optimistic approval runs against the resolved op (operationId carried).
- expect(result.current.optimisticUpdateMessagePlugin).toHaveBeenCalledWith(
- 'tool-msg-1',
- { intervention: { status: 'approved' } },
- { operationId: assistantOpId },
- );
+ // Publishing waits for the producer ACK instead of claiming approval.
+ expect(
+ result.current.dbMessagesMap[chatKey].find((m) => m.id === 'tool-msg-1')
+ ?.pluginIntervention,
+ ).toMatchObject({ status: 'pending', resolving: true });
// IPC submit forwards the resolved operationId + toolCallId + result.
expect(submitInterventionSpy).toHaveBeenCalledWith({
@@ -3846,11 +3844,10 @@ describe('ConversationControl actions', () => {
});
expect(result.current.messageOperationMap[assistantMessage.id]).toBe(reasoningOpId);
- expect(result.current.optimisticUpdateMessagePlugin).toHaveBeenCalledWith(
- 'tool-msg-1',
- { intervention: { status: 'approved' } },
- { operationId: executionOpId },
- );
+ expect(
+ result.current.dbMessagesMap[chatKey].find((m) => m.id === 'tool-msg-1')
+ ?.pluginIntervention,
+ ).toMatchObject({ status: 'pending', resolving: true });
expect(submitInterventionSpy).toHaveBeenCalledWith({
operationId: executionOpId,
result: payload,
@@ -3859,7 +3856,7 @@ describe('ConversationControl actions', () => {
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 () => {
+ it("keeps the card 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 `{}`
// (global-state fallback) rather than carrying the stale operationId. With
@@ -3920,19 +3917,16 @@ describe('ConversationControl actions', () => {
).resolves.toBeUndefined();
});
- // Remote publish is only transport acceptance: keep the form pending,
- // mark it resolving, and use the empty global-state fallback context.
- // The hint is dispatched locally onto both projections the UI reads and
- // deliberately never persisted — a refresh must recover an actionable
- // card rather than a permanently disabled one.
- const resolvingIntervention = { resolving: true, status: 'pending' };
+ // Remote delivery waits for the ACK in the card's context, even after op GC.
+ // Both projections receive this local-only hint; Cancel clears skip intent.
+ const resolvingIntervention = { resolving: true, skipped: false, status: 'pending' };
expect(dispatchSpy).toHaveBeenCalledWith(
{
id: 'tool-msg-1',
type: 'updateMessage',
value: { pluginIntervention: resolvingIntervention },
},
- {},
+ { context: { agentId, topicId, threadId: undefined } },
);
expect(dispatchSpy).toHaveBeenCalledWith(
{
@@ -3941,7 +3935,7 @@ describe('ConversationControl actions', () => {
type: 'updateMessageTools',
value: { intervention: resolvingIntervention },
},
- {},
+ { context: { agentId, topicId, threadId: undefined } },
);
expect(pluginSpy).not.toHaveBeenCalledWith(
'tool-msg-1',
@@ -3988,255 +3982,11 @@ describe('ConversationControl actions', () => {
publishError,
);
});
- expect(pluginSpy).toHaveBeenLastCalledWith(
- 'tool-msg-1',
- // A failed publish rolls back to pending AND drops the in-flight hint,
- // so the card the user has to retry is actionable again.
- { intervention: { resolving: false, status: 'pending' } },
- {},
- );
- });
-
- it('settles a remote card that the producer never acknowledges', async () => {
- // Regression: the ask-user bridge stops waiting at its own deadline and
- // its long-poll stops listening with it, so an answer published after
- // that point can never be echoed back. The card was left on
- // `pending + resolving` forever — every button disabled, the submit
- // button spinning, with no way out but a refresh. The server accepted the
- // answer, so the card settles as answered and leaves the surface; it is
- // never re-offered, which would invite a duplicate answer.
- vi.useFakeTimers();
- 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',
- },
- pluginIntervention: { status: 'pending' },
- role: 'tool',
- tool_call_id: 'cc_call_1',
- } as any);
-
- act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeThreadId: undefined,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [assistantMessage, toolMessage] },
- messagesMap: { [chatKey]: [assistantMessage, toolMessage] },
- // A GC'd op routes to the remote transport, the path that waits for
- // a producer ACK.
- messageOperationMap: { [assistantMessage.id]: 'gc-op-id' },
- operations: {},
- });
- });
-
- const pluginSpy = vi
- .spyOn(result.current, 'optimisticUpdateMessagePlugin')
- .mockResolvedValue(undefined);
- vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);
- vi.spyOn(result.current, 'updateTopicStatus').mockResolvedValue(undefined as any);
- vi.spyOn(messageService, 'updateMessagePluginState').mockResolvedValue({
- messages: [],
- success: true,
- });
-
- await act(async () => {
- await result.current.submitHeteroIntervention('tool-msg-1', 'submit', { q: 'a' });
- });
-
- const resolvingMessage = dbMessageSelectors.getDbMessageById('tool-msg-1')(
- useChatStore.getState(),
- );
- expect(resolvingMessage?.pluginIntervention?.resolving).toBe(true);
- pluginSpy.mockClear();
-
- // No ACK ever arrives.
- await act(async () => {
- vi.advanceTimersByTime(30 * 1000);
- });
-
- expect(pluginSpy).toHaveBeenCalledWith(
- 'tool-msg-1',
- { intervention: { resolving: false, status: 'approved' } },
- expect.anything(),
- );
-
- // The card must leave the surface on the local write alone. The durable
- // write is best-effort; waiting on its echo is what left the card on
- // screen in the first place.
- const settled = dbMessageSelectors.getDbMessageById('tool-msg-1')(useChatStore.getState());
- expect(settled?.pluginIntervention?.status).toBe('approved');
- expect(settled?.pluginIntervention?.resolving).toBe(false);
-
- vi.useRealTimers();
- });
-
- it.each([
- {
- actionType: 'skip' as const,
- expected: {
- rejectedReason: 'User skipped',
- resolving: false,
- skipped: true,
- status: 'rejected',
- },
- },
- {
- actionType: 'cancel' as const,
- expected: {
- rejectedReason: 'User cancelled',
- resolving: false,
- skipped: false,
- status: 'rejected',
- },
- },
- ])(
- 'settles an unacknowledged $actionType as the decision the user made, not as an answer',
- async ({ actionType, expected }) => {
- // Regression: the settle timer runs for every remote action but always
- // stamped `approved`, so an accepted skip/cancel that never got a
- // producer ACK was rendered and persisted as an approved answer.
- vi.useFakeTimers();
- const { result } = renderHook(() => useChatStore());
-
- const agentId = 'hetero-agent';
- const topicId = 'hetero-topic';
- const chatKey = messageMapKey({ agentId, topicId });
- const assistantMessage = createMockMessage({
- id: `assistant-${actionType}`,
- role: 'assistant',
- });
- const toolMessage = createMockMessage({
- id: `tool-${actionType}`,
- parentId: assistantMessage.id,
- plugin: {
- apiName: 'askUserQuestion',
- arguments: '{}',
- identifier: 'lobe-claude-code',
- type: 'default',
- },
- pluginIntervention: { status: 'pending' },
- role: 'tool',
- tool_call_id: `call-${actionType}`,
- } as any);
-
- act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeThreadId: undefined,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [assistantMessage, toolMessage] },
- messagesMap: { [chatKey]: [assistantMessage, toolMessage] },
- messageOperationMap: { [assistantMessage.id]: `gc-op-${actionType}` },
- operations: {},
- });
- });
-
- const pluginSpy = vi
- .spyOn(result.current, 'optimisticUpdateMessagePlugin')
- .mockResolvedValue(undefined);
- vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);
- vi.spyOn(result.current, 'updateTopicStatus').mockResolvedValue(undefined as any);
-
- await act(async () => {
- await result.current.submitHeteroIntervention(toolMessage.id, actionType);
- });
- pluginSpy.mockClear();
-
- await act(async () => {
- vi.advanceTimersByTime(30 * 1000);
- });
-
- expect(pluginSpy).toHaveBeenCalledWith(
- toolMessage.id,
- { intervention: expected },
- expect.anything(),
- );
- const settled = dbMessageSelectors.getDbMessageById(toolMessage.id)(
- useChatStore.getState(),
- );
- expect(settled?.pluginIntervention).toMatchObject(expected);
-
- vi.useRealTimers();
- },
- );
-
- it('leaves an acknowledged card alone when the settle timer fires', async () => {
- vi.useFakeTimers();
- const { result } = renderHook(() => useChatStore());
-
- const agentId = 'hetero-agent';
- const topicId = 'hetero-topic';
- const chatKey = messageMapKey({ agentId, topicId });
- const assistantMessage = createMockMessage({ id: 'assistant-msg-2', role: 'assistant' });
- const toolMessage = createMockMessage({
- id: 'tool-msg-2',
- parentId: assistantMessage.id,
- plugin: {
- apiName: 'askUserQuestion',
- arguments: '{}',
- identifier: 'lobe-claude-code',
- type: 'default',
- },
- pluginIntervention: { status: 'pending' },
- role: 'tool',
- tool_call_id: 'cc_call_2',
- } as any);
-
- act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeThreadId: undefined,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [assistantMessage, toolMessage] },
- messagesMap: { [chatKey]: [assistantMessage, toolMessage] },
- messageOperationMap: { [assistantMessage.id]: 'gc-op-id-2' },
- operations: {},
- });
- });
-
- vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);
- vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);
- vi.spyOn(result.current, 'updateTopicStatus').mockResolvedValue(undefined as any);
- vi.spyOn(messageService, 'updateMessagePluginState').mockResolvedValue({
- messages: [],
- success: true,
- });
-
- await act(async () => {
- await result.current.submitHeteroIntervention('tool-msg-2', 'submit', { q: 'a' });
- });
-
- // The producer ACKs and the card goes terminal before the timer fires.
- act(() => {
- result.current.internal_dispatchMessage(
- {
- id: 'tool-msg-2',
- type: 'updateMessage',
- value: { pluginIntervention: { resolving: false, status: 'approved' } },
- },
- {},
- );
- });
-
- await act(async () => {
- vi.advanceTimersByTime(30 * 1000);
- });
-
- const settled = dbMessageSelectors.getDbMessageById('tool-msg-2')(useChatStore.getState());
- expect(settled?.pluginIntervention?.status).toBe('approved');
-
- vi.useRealTimers();
+ expect(
+ result.current.dbMessagesMap[chatKey].find((m) => m.id === 'tool-msg-1')
+ ?.pluginIntervention,
+ ).toMatchObject({ resolving: false, status: 'pending' });
+ expect(pluginSpy).not.toHaveBeenCalled();
});
it('flips topic status on the passed context, NOT the active topic, when submitting from a background conversation', async () => {
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 6cc10be3381..2830379770c 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -1,14 +1,4 @@
-/**
- * Tests for heterogeneousAgentExecutor DB persistence layer.
- *
- * Verifies the critical path: CC stream events → messageService DB writes.
- * Covers:
- * - Tool 3-phase persistence (pre-register → create → backfill)
- * - Tool result content updates
- * - Multi-step assistant message creation with correct parentId chain
- * - Content/reasoning/model/usage final writes
- * - Sync snapshot + reset to prevent cross-step content contamination
- */
+/** CLI stream → tool persistence, turn chaining and final snapshot regression tests. */
import type * as LobeChatConst from '@lobechat/const';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
@@ -1098,91 +1088,97 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
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?',
- },
- ],
+ it.each([false, true])(
+ 'keeps question ownership and closes its upstream tool (subagent=%s)',
+ async (subagent) => {
+ const optimisticUpdateMessagePlugin = vi.fn(async () => {});
+ const store = createMockStore({
+ optimisticUpdateMessagePlugin,
+ updateTopicStatus: vi.fn(),
+ });
+ let resolveSendPrompt!: () => void;
+ mockSendPrompt.mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveSendPrompt = resolve;
}),
- 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', {
+ );
+ const executorPromise = executeHeterogeneousAgent(() => store, defaultParams);
+ await flush();
+ ipc.emitRawLine('ipc-sess-1', ccInit());
+ const args = {
questions: [
{
header: 'Scope',
- options: [
- { description: 'Keep it narrow', label: 'Small' },
- { description: 'Do all of it', label: 'All' },
- ],
+ options: [{ label: 'Small' }, { 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;
- });
+ };
+ const child = { parentToolCallId: 'task-parent', subagentMessageId: 'child-turn' };
+ if (subagent) {
+ ipc.emitStreamEvent('ipc-sess-1', {
+ data: {
+ chunkType: 'tools_calling',
+ subagent: child,
+ toolsCalling: [
+ {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify(args),
+ id: 'toolu_ask',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ],
+ },
+ type: 'stream_chunk',
+ });
+ await flush();
+ }
+ ipc.emitStreamEvent('ipc-sess-1', {
+ data: {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify(args),
+ deadline: Date.now() + 300_000,
+ identifier: 'claude-code',
+ toolCallId: 'toolu_ask',
+ },
+ type: 'agent_intervention_request',
+ });
+ await flush();
+ const tools = mockCreateMessage.mock.calls.filter(
+ ([m]: any) => m.role === 'tool' && m.tool_call_id === 'toolu_ask',
+ );
+ expect(tools).toHaveLength(1);
+ const toolRow = tools[0][0];
+ const expectedContext = subagent
+ ? {
+ context: { ...defaultContext, scope: 'thread', threadId: toolRow.threadId },
+ operationId: 'op-1',
+ }
+ : { operationId: 'op-1' };
+ expect(subagent ? toolRow.threadId : !toolRow.threadId).toBeTruthy();
+ expect(optimisticUpdateMessagePlugin).toHaveBeenCalledWith(
+ toolRow.id,
+ { intervention: { status: 'pending' } },
+ expectedContext,
+ );
+ ipc.emitStreamEvent('ipc-sess-1', {
+ data: { content: 'done', ...(subagent && { subagent: child }), toolCallId: 'toolu_ask' },
+ type: 'tool_result',
+ });
+ await flush();
+ expect(optimisticUpdateMessagePlugin).toHaveBeenLastCalledWith(
+ toolRow.id,
+ { intervention: expect.objectContaining({ status: 'aborted' }) },
+ expectedContext,
+ );
+ 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/__tests__/questionSubmission.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/questionSubmission.test.ts
index c91123a732e..06dfa082b3d 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/questionSubmission.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/questionSubmission.test.ts
@@ -85,6 +85,34 @@ describe('question submission feedback', () => {
},
);
+ it('reconciles a stale resolving flag from the authoritative pending row', async () => {
+ const { action, state } = createAction();
+ state.dbMessagesMap[key] = [
+ {
+ ...question,
+ pluginIntervention: { ...question.pluginIntervention!, resolving: true },
+ },
+ ];
+ vi.mocked(messageService.getMessages).mockResolvedValue([question]);
+ await action.checkQuestionSubmission(question.id, context);
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.resolving).not.toBe(true);
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.status).toBe('pending');
+ });
+
+ it('unlocks a stale resolving form when automatic reconciliation is unavailable', async () => {
+ const { action, state } = createAction();
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ state.dbMessagesMap[key] = [
+ { ...question, pluginIntervention: { ...question.pluginIntervention!, resolving: true } },
+ ];
+ vi.mocked(messageService.getMessages).mockRejectedValueOnce(new Error('Temporary 503'));
+ await action.checkQuestionSubmission(question.id, context);
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.resolving).toBe(false);
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.status).toBe('pending');
+ expect(state.questionSubmissions.question).toBe('uncertain');
+ log.mockRestore();
+ });
+
it('restores the saved answers after a failed submit and authoritative pending read', async () => {
const { action, state } = createAction();
const error = new Error('submit failed');
@@ -121,7 +149,7 @@ describe('question submission feedback', () => {
expect(state.dbMessagesMap[key][0].pluginIntervention?.status).toBe('approved');
});
- it('keeps an unconfirmed response collapsed until checking succeeds', async () => {
+ it('automatically checks an uncertain response before retrying delivery', async () => {
const { action, state } = createAction();
const log = vi.spyOn(console, 'error').mockImplementation(() => {});
vi.mocked(messageService.getMessages).mockRejectedValueOnce(new Error('offline'));
@@ -132,11 +160,15 @@ describe('question submission feedback', () => {
).rejects.toThrow('offline');
expect(state.questionSubmissions.question).toBe('uncertain');
const submit = vi.fn();
- await action.runQuestionSubmission(question.id, context, submit);
+ vi.mocked(messageService.getMessages).mockRejectedValueOnce(new Error('offline'));
+ await expect(action.runQuestionSubmission(question.id, context, submit)).rejects.toThrow(
+ 'could not be confirmed',
+ );
expect(submit).not.toHaveBeenCalled();
vi.mocked(messageService.getMessages).mockResolvedValueOnce([question]);
- await action.checkQuestionSubmission(question.id, context);
- expect(state.questionSubmissions.question).toBe('failed');
+ await action.runQuestionSubmission(question.id, context, submit);
+ expect(submit).toHaveBeenCalledOnce();
+ expect(state.questionSubmissions.question).toBeUndefined();
log.mockRestore();
});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.questionLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.questionLifecycle.test.ts
new file mode 100644
index 00000000000..080a4c80066
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.questionLifecycle.test.ts
@@ -0,0 +1,271 @@
+import { toast } from '@lobehub/ui';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { resolveRejectedCopyKey } from '@/features/Conversation/Messages/AssistantGroup/Tool/Detail/resolveRejectedCopyKey';
+import { lambdaClient } from '@/libs/trpc/client';
+import { aiAgentService } from '@/services/aiAgent';
+import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
+import { messageService } from '@/services/message';
+import { messagesReducer } from '@/store/chat/slices/message/reducer';
+import type { ChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import { createMockMessage } from '../__tests__/fixtures';
+import { preserveSkippedIntervention } from '../transports/hetero/interventionAck';
+import { ConversationControlActionImpl } from './conversationControl';
+
+vi.mock('@/services/aiAgent', () => ({
+ aiAgentService: { resolveAgentInterventionBySource: vi.fn() },
+}));
+vi.mock('@/services/message', () => ({
+ messageService: { getMessages: vi.fn(), updateMessagePluginState: vi.fn() },
+}));
+vi.mock('@/services/electron/heterogeneousAgent', () => ({
+ heterogeneousAgentService: { submitIntervention: vi.fn() },
+}));
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: { aiAgent: { submitHeteroIntervention: { mutate: vi.fn() } } },
+}));
+
+const context = {
+ agentId: 'agent',
+ topicId: 'topic',
+ scope: 'thread' as const,
+ threadId: 'thread',
+};
+const key = messageMapKey(context);
+const makeState = (ended: boolean) => {
+ const message = createMockMessage({
+ id: 'question',
+ role: 'tool',
+ tool_call_id: 'call',
+ parentId: 'assistant',
+ pluginIntervention: {
+ batchId: 'batch',
+ operationId: 'operation',
+ status: ended ? 'aborted' : 'pending',
+ ...(ended && { rejectedReason: 'session_ended' }),
+ },
+ pluginState: { heterogeneousIntervention: { interactionKind: 'question' } },
+ });
+ const state = {
+ dbMessagesMap: { [key]: [message] },
+ questionSubmissions: {},
+ messageOperationMap: {},
+ refreshMessages: vi.fn(),
+ } as unknown as ChatStore;
+ state.internal_dispatchMessage = (action) => {
+ state.dbMessagesMap[key] = messagesReducer(state.dbMessagesMap[key], action);
+ };
+ const control = new ConversationControlActionImpl(vi.fn(), () => state);
+ return { state, control };
+};
+
+beforeEach(() => vi.resetAllMocks());
+
+describe('question actions racing tool completion', () => {
+ it.each(['desktop', 'remote', 'source'] as const)(
+ 'preserves skip intent until the %s ACK and clears it for a later cancel',
+ async (transport) => {
+ const { control, state } = makeState(false);
+ if (transport === 'source') {
+ state.internal_confirmQuestionSubmission = vi.fn();
+ vi.mocked(aiAgentService.resolveAgentInterventionBySource)
+ .mockResolvedValueOnce({ handled: true, state: 'claimed' })
+ .mockResolvedValueOnce({ handled: true, state: 'claimed' });
+ } else {
+ state.dbMessagesMap[key][0].pluginIntervention = { status: 'pending' };
+ state.messageOperationMap = { assistant: 'operation' };
+ state.operations = {
+ operation: {
+ type: transport === 'desktop' ? 'execHeterogeneousAgent' : 'execServerAgentRuntime',
+ context,
+ },
+ } as ChatStore['operations'];
+ state.internal_getConversationContext = () => context;
+ vi.mocked(heterogeneousAgentService.submitIntervention).mockResolvedValue(undefined);
+ vi.mocked(lambdaClient.aiAgent.submitHeteroIntervention.mutate).mockResolvedValue(
+ undefined,
+ );
+ }
+
+ await control.submitHeteroIntervention('question', 'skip', undefined, context);
+ const pending = state.dbMessagesMap[key][0].pluginIntervention;
+ expect(pending).toMatchObject({ status: 'pending', resolving: true, skipped: true });
+ const ack = { status: 'rejected' as const, rejectedReason: 'user_cancelled' };
+ const skipped = preserveSkippedIntervention(ack, pending);
+ expect(
+ resolveRejectedCopyKey({
+ ...skipped,
+ apiName: 'askUserQuestion',
+ reason: ack.rejectedReason,
+ }),
+ ).toBe('tool.intervention.questionSkipped');
+
+ // A retry using Cancel must not inherit an earlier unconfirmed skip.
+ await control.submitHeteroIntervention('question', 'cancel', undefined, context);
+ const cancelled = preserveSkippedIntervention(
+ ack,
+ state.dbMessagesMap[key][0].pluginIntervention,
+ );
+ expect(cancelled.skipped).not.toBe(true);
+ expect(
+ resolveRejectedCopyKey({
+ ...cancelled,
+ apiName: 'askUserQuestion',
+ reason: ack.rejectedReason,
+ }),
+ ).toBe('tool.intervention.rejectedWithReason');
+ },
+ );
+
+ it('restores the skip marker when desktop delivery fails without an ACK', async () => {
+ const { control, state } = makeState(false);
+ state.dbMessagesMap[key][0].pluginIntervention = { status: 'pending' };
+ state.messageOperationMap = { assistant: 'operation' };
+ state.operations = {
+ operation: { type: 'execHeterogeneousAgent', context },
+ } as ChatStore['operations'];
+ state.internal_getConversationContext = () => context;
+ state.checkQuestionSubmission = vi.fn().mockResolvedValue(false);
+ vi.mocked(heterogeneousAgentService.submitIntervention).mockRejectedValueOnce(
+ new Error('IPC delivery failed'),
+ );
+ await expect(
+ control.submitHeteroIntervention('question', 'skip', undefined, context),
+ ).rejects.toThrow('IPC delivery failed');
+ expect(state.dbMessagesMap[key][0].pluginIntervention).toMatchObject({
+ status: 'pending',
+ resolving: false,
+ });
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.skipped).not.toBe(true);
+ });
+
+ it.each(['submit', 'skip', 'cancel'] as const)(
+ 'notifies on a late %s without delivering or reopening an ended question',
+ async (type) => {
+ const { control, state } = makeState(true);
+ const notice = vi.spyOn(toast, 'info').mockImplementation(() => '' as never);
+ await control.submitHeteroIntervention('question', type, { Color: 'Blue' }, context);
+ expect(notice).toHaveBeenCalledOnce();
+ expect(aiAgentService.resolveAgentInterventionBySource).not.toHaveBeenCalled();
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.status).toBe('aborted');
+ notice.mockRestore();
+ },
+ );
+
+ it('refreshes a server-ended question and reports the late action without replacing it', async () => {
+ const { control, state } = makeState(false);
+ const notice = vi.spyOn(toast, 'info').mockImplementation(() => '' as never);
+ vi.mocked(aiAgentService.resolveAgentInterventionBySource).mockResolvedValueOnce({
+ handled: true,
+ state: 'already_resolved',
+ });
+ vi.mocked(state.refreshMessages).mockImplementationOnce(async () => {
+ state.dbMessagesMap[key] = [
+ {
+ ...state.dbMessagesMap[key][0],
+ pluginIntervention: {
+ status: 'aborted',
+ resolving: false,
+ rejectedReason: 'session_ended',
+ },
+ },
+ ];
+ });
+ await control.submitHeteroIntervention('question', 'submit', { Color: 'Blue' }, context);
+ expect(state.refreshMessages).toHaveBeenCalledWith(context);
+ expect(notice).toHaveBeenCalledOnce();
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.status).toBe('aborted');
+ notice.mockRestore();
+ });
+
+ it('does not publish or reopen a desktop question that ends while saving the answer', async () => {
+ const { control, state } = makeState(false);
+ state.dbMessagesMap[key] = [
+ { ...state.dbMessagesMap[key][0], pluginIntervention: { status: 'pending' } },
+ ];
+ state.messageOperationMap = { assistant: 'desktop-operation' };
+ state.operations = {
+ 'desktop-operation': { type: 'execHeterogeneousAgent', context },
+ } as ChatStore['operations'];
+ state.internal_getConversationContext = () => context;
+ state.optimisticUpdateMessagePlugin = vi.fn();
+ const notice = vi.spyOn(toast, 'info').mockImplementation(() => '' as never);
+ vi.mocked(messageService.updateMessagePluginState).mockImplementationOnce(async () => {
+ state.internal_dispatchMessage({
+ id: 'question',
+ type: 'updateMessage',
+ value: {
+ pluginIntervention: {
+ status: 'aborted',
+ resolving: false,
+ rejectedReason: 'session_ended',
+ },
+ },
+ });
+ return { messages: [], success: true };
+ });
+ await control.submitHeteroIntervention('question', 'submit', { Color: 'Blue' }, context);
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.status).toBe('aborted');
+ expect(state.optimisticUpdateMessagePlugin).not.toHaveBeenCalled();
+ expect(notice).toHaveBeenCalledOnce();
+ notice.mockRestore();
+ });
+
+ it.each(['approved', 'rejected'] as const)(
+ 'does not roll back producer %s when the transport later fails',
+ async (status) => {
+ const { control, state } = makeState(false);
+ state.dbMessagesMap[key] = [
+ {
+ ...state.dbMessagesMap[key][0],
+ pluginIntervention: { status: 'pending' },
+ },
+ ];
+ state.messageOperationMap = { assistant: 'gc-operation' };
+ state.operations = {};
+ state.optimisticUpdateMessagePlugin = vi.fn();
+ vi.mocked(lambdaClient.aiAgent.submitHeteroIntervention.mutate).mockImplementationOnce(
+ async () => {
+ state.dbMessagesMap[key] = [
+ {
+ ...state.dbMessagesMap[key][0],
+ pluginIntervention: { status, resolving: false },
+ },
+ ];
+ throw new Error('Response lost after producer ACK');
+ },
+ );
+ await expect(
+ control.submitHeteroIntervention('question', 'skip', undefined, context),
+ ).resolves.toBeUndefined();
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.status).toBe(status);
+ expect(state.optimisticUpdateMessagePlugin).not.toHaveBeenCalled();
+ },
+ );
+
+ it('keeps a terminal event when delivery fails after the tool has ended', async () => {
+ const { control, state } = makeState(false);
+ const notice = vi.spyOn(toast, 'info').mockImplementation(() => '' as never);
+ vi.mocked(aiAgentService.resolveAgentInterventionBySource).mockImplementationOnce(async () => {
+ state.dbMessagesMap[key] = [
+ {
+ ...state.dbMessagesMap[key][0],
+ pluginIntervention: {
+ status: 'aborted',
+ resolving: false,
+ rejectedReason: 'session_ended',
+ },
+ },
+ ];
+ throw new Error('Producer has already ended');
+ });
+ await expect(
+ control.submitHeteroIntervention('question', 'submit', { Color: 'Blue' }, context),
+ ).resolves.toBeUndefined();
+ expect(notice).toHaveBeenCalledOnce();
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.status).toBe('aborted');
+ notice.mockRestore();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
index dd52575fe5a..84ecded66e1 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
@@ -6,9 +6,9 @@ import {
type ConversationContext,
type MessageMetadata,
resolveAgentAgencyConfig,
- type ToolIntervention,
type UIChatMessage,
} from '@lobechat/types';
+import { toast } from '@lobehub/ui';
import { t } from 'i18next';
import { type ChatInputEditor } from '@/features/ChatInput';
@@ -113,13 +113,6 @@ const toHeterogeneousSourceAction = (
}
};
-/**
- * How long a published-but-unacknowledged hetero intervention stays in the
- * `resolving` phase before it is settled. Mirrors `SUBMIT_ACK_TIMEOUT_MS` in
- * `@lobechat/shared-tool-ui/ask-user`.
- */
-const HETERO_INTERVENTION_ACK_TIMEOUT_MS = 30 * 1000;
-
export const conversationControl = (set: Setter, get: () => ChatStore, _api?: unknown) =>
new ConversationControlActionImpl(set, get, _api);
@@ -481,56 +474,13 @@ export class ConversationControlActionImpl {
return true;
};
- /**
- * A remote submit parks the card on `pending + resolving` until the blocked
- * producer echoes its ACK. That ACK can never arrive when the producer is
- * already gone — its own ask-user deadline elapsed, its process died, or its
- * long-poll stopped listening the moment the bridge settled — and nothing
- * else moves the card off that phase, so every surface reading it stays
- * permanently non-actionable.
- *
- * Settle it after a bounded wait rather than handing the buttons back. The
- * server accepted the user's decision for delivery, so from their side the
- * question IS resolved; re-offering it would ask them to decide a second time
- * and risk a duplicate landing on a producer that already has one. The
- * terminal state is the one the user chose — an answer settles `approved`, a
- * skip or cancel settles `rejected` — matching what the local desktop path
- * stamps immediately. A later real producer result simply overwrites this.
- */
- #scheduleHeteroInterventionSettle = (
- toolMessageId: string,
- actionType: 'submit' | 'skip' | 'cancel',
- context: OptimisticUpdateContext,
- ): void => {
- const settled: Partial<ToolIntervention> =
- actionType === 'submit'
- ? { resolving: false, status: 'approved' }
- : {
- rejectedReason: actionType === 'skip' ? 'User skipped' : 'User cancelled',
- resolving: false,
- skipped: actionType === 'skip',
- status: 'rejected',
- };
-
- setTimeout(() => {
- const intervention = dbMessageSelectors.getDbMessageById(toolMessageId)(
- this.#get(),
- )?.pluginIntervention;
- // Anything terminal already won the race — never reopen a settled card.
- if (intervention?.resolving !== true || intervention.status !== 'pending') return;
-
- // Write the terminal state onto the projections the surfaces read BEFORE
- // persisting: `optimisticUpdateMessagePlugin` only reaches the tool row's
- // top-level `pluginIntervention` (what the card list is built from) once
- // the server echoes, so a failed or slow write would leave the card on
- // screen — the exact state this settle exists to end.
- this.#interventions.dispatch(toolMessageId, settled, context);
- void this.#get().optimisticUpdateMessagePlugin(
- toolMessageId,
- { intervention: settled },
- context,
- );
- }, HETERO_INTERVENTION_ACK_TIMEOUT_MS);
+ #discardSettledHeteroQuestion = (id: string): boolean => {
+ const intervention = dbMessageSelectors.getDbMessageById(id)(this.#get())?.pluginIntervention;
+ if (!intervention || intervention.status === 'pending') return false;
+ if (intervention.status === 'aborted') {
+ toast.info(t('tool.intervention.toolEnded', { ns: 'chat' }));
+ }
+ return true;
};
#writeTopicStatus = (context: ConversationContext, status: ChatTopicStatus, force?: boolean) => {
@@ -1759,8 +1709,7 @@ export class ConversationControlActionImpl {
* keeps going on its own; no synthetic user message, no new op.
*
* The framework's intervention surface still drives the UI: we just
- * stamp the local terminal state immediately. Remote submits remain
- * `pending + resolving` until the blocked producer echoes its ACK, so the
+ * keep submissions `pending + resolving` until the producer echoes its ACK, so the
* form stays visible and disabled across remounts without claiming success.
*
* `actionType`:
@@ -1776,12 +1725,12 @@ export class ConversationControlActionImpl {
context?: ConversationContext,
): Promise<void> => {
const toolMessage = dbMessageSelectors.getDbMessageById(toolMessageId)(this.#get());
- if (!toolMessage) return;
+ if (!toolMessage) throw new Error('Question message is unavailable');
+ if (this.#discardSettledHeteroQuestion(toolMessageId)) return;
const toolCallId = toolMessage.tool_call_id;
if (!toolCallId) {
- console.warn('[submitHeteroIntervention] tool message has no tool_call_id', toolMessageId);
- return;
+ throw new Error('Question has no tool call identity');
}
const effectiveContext: ConversationContext = context ?? {
@@ -1790,7 +1739,6 @@ export class ConversationControlActionImpl {
threadId: this.#get().activeThreadId,
};
const originalIntervention = toolMessage.pluginIntervention;
- const originalContent = toolMessage.content;
const interventionState = (
toolMessage.pluginState as
{ heterogeneousIntervention?: { interactionKind?: unknown } } | undefined
@@ -1807,24 +1755,34 @@ export class ConversationControlActionImpl {
// durable first-winner claim. The message/runtime ids are locators only;
// the source endpoint remains responsible for ACL and token authority.
if (originalIntervention?.batchId && originalIntervention.operationId && sourceAction) {
- const sourceResolution = await this.tryResolveAgentInterventionBySource({
- action: sourceAction,
- context: effectiveContext,
- toolMessageIds: [toolMessageId],
- });
+ let sourceResolution: ResolveAgentInterventionBySourceResult;
+ try {
+ sourceResolution = await this.tryResolveAgentInterventionBySource({
+ action: sourceAction,
+ context: effectiveContext,
+ toolMessageIds: [toolMessageId],
+ });
+ } catch (error) {
+ if (this.#discardSettledHeteroQuestion(toolMessageId)) return;
+ if (await this.#get().checkQuestionSubmission(toolMessageId, effectiveContext)) {
+ this.#discardSettledHeteroQuestion(toolMessageId);
+ return;
+ }
+ throw error;
+ }
+ if (this.#discardSettledHeteroQuestion(toolMessageId)) return;
if (this.#discardAlreadyResolvedSource(sourceResolution)) return;
if (sourceResolution.handled) {
const sourceOptimisticContext: OptimisticUpdateContext = { context: effectiveContext };
this.#interventions.dispatch(
toolMessageId,
- { resolving: true, status: 'pending' },
+ { resolving: true, skipped: actionType === 'skip', status: 'pending' },
sourceOptimisticContext,
);
if (actionType === 'submit') {
await this.setInterventionAnswers(toolMessageId, payload ?? {}, sourceOptimisticContext);
}
- this.#scheduleHeteroInterventionSettle(toolMessageId, actionType, sourceOptimisticContext);
return;
}
}
@@ -1841,8 +1799,11 @@ export class ConversationControlActionImpl {
messageOperationMap?.[toolMessageId];
if (!candidateOperationId) {
- console.warn('[submitHeteroIntervention] no operationId for', toolMessageId);
- return;
+ if (await this.#get().checkQuestionSubmission(toolMessageId, effectiveContext)) {
+ this.#discardSettledHeteroQuestion(toolMessageId);
+ return;
+ }
+ throw new Error('Question runtime is unavailable');
}
// Resolve the runtime execution op before choosing IPC vs remote transport.
@@ -1851,76 +1812,30 @@ export class ConversationControlActionImpl {
const { operation, operationId } =
this.#resolveHeteroInterventionExecutionOperation(candidateOperationId);
- // 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.
+ // A cold/GC'd run still uses the card's captured context, never the active tab.
const operationAlive = !!operation;
if (!operationAlive) {
console.warn(
- '[submitHeteroIntervention] operation already gone, using global-state fallback for optimistic write:',
+ '[submitHeteroIntervention] operation already gone, using card context:',
operationId,
);
}
- const optimisticContext: OptimisticUpdateContext = operationAlive ? { operationId } : {};
+ const optimisticContext: OptimisticUpdateContext = operationAlive
+ ? { operationId }
+ : { context: effectiveContext };
const isLocalDesktopHetero = operation?.type === 'execHeterogeneousAgent';
- if (!isLocalDesktopHetero) {
- // Publishing the user intent is not completion. Keep the interaction
- // pending but mark its in-flight phase so a remount/retry cannot present
- // an optimistic terminal state before the producer has consumed it.
- this.#interventions.dispatch(
- toolMessageId,
- { resolving: true, status: 'pending' },
- optimisticContext,
- );
- if (actionType === 'submit') {
- await this.setInterventionAnswers(toolMessageId, payload ?? {}, optimisticContext);
- }
- } else if (actionType === 'submit') {
- await this.#get().optimisticUpdateMessagePlugin(
- toolMessageId,
- { intervention: { status: 'approved' } },
- optimisticContext,
- );
- // Persist the structured `{ [questionText]: selectedLabel(s) }` answers
- // to `pluginState.askUserAnswers` so the Render component can show
- // Q&A pairs instead of parsing the bridge's prose `User answers:`
- // dump out of `content`. Best-effort — never block the IPC submit.
+ // Both transports wait for the producer's result event. Local IPC delivery
+ // does not prove that an already-ended bridge consumed the answer.
+ this.#interventions.dispatch(
+ toolMessageId,
+ { resolving: true, skipped: actionType === 'skip', status: 'pending' },
+ optimisticContext,
+ );
+ if (actionType === 'submit') {
await this.setInterventionAnswers(toolMessageId, payload ?? {}, optimisticContext);
- // Bridge formats its own "User answers:" string for CC, so the eventual
- // tool_result re-rewrites this content. The optimistic write is just
- // for the brief gap between Submit and CC echoing the result back.
- const summary = `User submitted: ${JSON.stringify(payload ?? {})}`;
- await this.#get().optimisticUpdateMessageContent(
- toolMessageId,
- summary,
- undefined,
- optimisticContext,
- );
- } else {
- const reason = actionType === 'skip' ? 'User skipped' : 'User cancelled';
- await this.#get().optimisticUpdateMessagePlugin(
- toolMessageId,
- {
- intervention: {
- rejectedReason: reason,
- skipped: actionType === 'skip',
- status: 'rejected',
- },
- },
- optimisticContext,
- );
- await this.#get().optimisticUpdateMessageContent(
- toolMessageId,
- `${reason} this interaction.`,
- undefined,
- optimisticContext,
- );
}
+ if (this.#discardSettledHeteroQuestion(toolMessageId)) return;
// Forward the answer to the producer over the transport THIS op actually
// ran on — read from the op itself, not re-derived from the current agent
@@ -1974,35 +1889,20 @@ export class ConversationControlActionImpl {
toolCallId,
},
);
- this.#scheduleHeteroInterventionSettle(toolMessageId, actionType, optimisticContext);
}
} catch (err) {
+ if (this.#discardSettledHeteroQuestion(toolMessageId)) return;
console.error('[submitHeteroIntervention] submitIntervention failed:', err);
- // Drop the in-flight hint first: the rollback below only reaches
- // `pluginIntervention` once the server echoes, and a failed publish must
- // never leave the card disabled waiting on an ACK that was never asked for.
- if (!isLocalDesktopHetero) {
- this.#interventions.dispatch(
- toolMessageId,
- { resolving: false, status: 'pending' },
- optimisticContext,
- );
- }
- await this.#get().optimisticUpdateMessagePlugin(
+ // Only the client-owned in-flight hint needs undoing. Writing pending
+ // back to the server could overwrite a producer result racing this error.
+ this.#interventions.dispatch(
toolMessageId,
- // `resolving` is never part of what a rollback restores: it describes
- // an in-flight publish, and this one just failed. Carrying a hint left
- // by an earlier attempt would re-disable the card the user must retry.
- { intervention: { ...(originalIntervention ?? { status: 'pending' }), resolving: false } },
+ { resolving: false, skipped: originalIntervention?.skipped ?? false, status: 'pending' },
optimisticContext,
);
- if (isLocalDesktopHetero) {
- await this.#get().optimisticUpdateMessageContent(
- toolMessageId,
- originalContent,
- undefined,
- optimisticContext,
- );
+ if (await this.#get().checkQuestionSubmission(toolMessageId, effectiveContext)) {
+ this.#discardSettledHeteroQuestion(toolMessageId);
+ return;
}
throw err;
}
diff --git a/src/store/chat/slices/agentRun/actions/entries/interventionProjection.ts b/src/store/chat/slices/agentRun/actions/entries/interventionProjection.ts
index 95d86e62498..66bf686cdb4 100644
--- a/src/store/chat/slices/agentRun/actions/entries/interventionProjection.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/interventionProjection.ts
@@ -16,7 +16,7 @@ import { type ChatStore } from '@/store/chat/store';
* terminal settle it is the fast half: the durable write follows separately,
* and the card must not wait on it to leave the screen.
*/
-const dispatchInterventionState = (
+export const dispatchInterventionState = (
get: () => ChatStore,
toolMessageId: string,
patch: Partial<ToolIntervention>,
diff --git a/src/store/chat/slices/agentRun/actions/entries/questionSubmission.ts b/src/store/chat/slices/agentRun/actions/entries/questionSubmission.ts
index ed9f90f5459..18eafe95252 100644
--- a/src/store/chat/slices/agentRun/actions/entries/questionSubmission.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/questionSubmission.ts
@@ -1,4 +1,6 @@
import type { ConversationContext, UIChatMessage } from '@lobechat/types';
+import { toast } from '@lobehub/ui';
+import { t } from 'i18next';
import type { AgentInterventionSourceAction } from '@/services/aiAgent';
import { messageService } from '@/services/message';
@@ -71,6 +73,17 @@ export class QuestionSubmissionActionImpl {
this.#setPhase(id);
return true;
}
+ // Reconcile stale client-only resolving flags as well as terminal results.
+ this.#applyResolution(
+ {
+ ...message,
+ pluginIntervention: {
+ ...message.pluginIntervention,
+ resolving: message.pluginIntervention.resolving === true,
+ },
+ },
+ context,
+ );
this.#setPhase(id, 'failed');
return false;
}
@@ -79,19 +92,50 @@ export class QuestionSubmissionActionImpl {
return true;
} catch (error) {
console.error('[QuestionSubmission] Failed to check resolution:', error);
+ const current = dbMessageSelectors.getDbMessageById(id)(this.#get());
+ if (current?.pluginIntervention && current.pluginIntervention.status !== 'pending') {
+ this.#setPhase(id);
+ return true;
+ }
+ if (current?.pluginIntervention?.resolving) {
+ this.#applyResolution(
+ { ...current, pluginIntervention: { ...current.pluginIntervention, resolving: false } },
+ context,
+ );
+ }
this.#setPhase(id, 'uncertain');
return false;
}
};
+ #notifyEnded = (id: string): boolean => {
+ if (
+ dbMessageSelectors.getDbMessageById(id)(this.#get())?.pluginIntervention?.status !== 'aborted'
+ ) {
+ return false;
+ }
+ toast.info(t('tool.intervention.toolEnded', { ns: 'chat' }));
+ this.#setPhase(id);
+ return true;
+ };
+
/** The form can collapse immediately without writing to the server-owned pending row. */
runQuestionSubmission = async (
id: string,
context: ConversationContext,
submit: () => Promise<void>,
): Promise<void> => {
+ if (this.#notifyEnded(id)) return;
const phase = this.#get().questionSubmissions[id];
- if (phase && phase !== 'failed') return;
+ if (phase === 'uncertain') {
+ if (await this.checkQuestionSubmission(id, context)) {
+ this.#notifyEnded(id);
+ return;
+ }
+ if (this.#get().questionSubmissions[id] !== 'failed') {
+ throw new Error('Question submission could not be confirmed');
+ }
+ } else if (phase && phase !== 'failed') return;
this.#setPhase(id, 'submitting');
try {
await submit();
@@ -100,11 +144,16 @@ export class QuestionSubmissionActionImpl {
if (message?.pluginIntervention && message.pluginIntervention.status !== 'pending') {
// The answer was accepted; a continuation failure must not reopen it.
this.#setPhase(id);
+ if (this.#notifyEnded(id)) return;
throw error;
}
- if (await this.checkQuestionSubmission(id, context)) return;
+ if (await this.checkQuestionSubmission(id, context)) {
+ this.#notifyEnded(id);
+ return;
+ }
throw error;
}
+ if (this.#notifyEnded(id)) return;
const resultPhase = this.#get().questionSubmissions[id];
if (resultPhase === 'failed' || resultPhase === 'uncertain') {
throw new Error('Question submission could not be confirmed');
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 ee70d1d61c6..dfcc1e9ec8b 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -1,8 +1,4 @@
-import type {
- AgentInterventionRequestData,
- AgentInterventionResponseData,
- AgentStreamEvent,
-} from '@lobechat/agent-gateway-client';
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { stripGoalCommand } from '@lobechat/builtin-tool-goal';
import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
@@ -88,12 +84,14 @@ import { getElectronStoreState } from '@/store/electron';
import { getUserStoreState, useUserStore } from '@/store/user';
import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectors';
+import { dispatchInterventionState } from '../../entries/interventionProjection';
import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';
import type { RunScope } from '../../lifecycle/types';
import { createGatewayEventHandler } from '../gateway/gatewayEventHandler';
import { isCompletedRuntimeEnd } from '../gateway/runtimeEndReason';
import { withHeteroContext } from '../viewedTaskPrompt';
import { getNativeHeteroSessionBindingKey, isRecoverableResumeError } from './heteroResume';
+import { preserveSkippedIntervention } from './interventionAck';
import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';
import { createPendingCreateLedger } from './pendingCreateLedger';
import { resolveQuotaAccountSpawnPlan } from './resolveQuotaAccountEnv';
@@ -695,24 +693,16 @@ export const executeHeterogeneousAgent = async (
return out;
};
- /**
- * Global `tool_use.id → tool message DB id` lookup, shared across the
- * main agent and every subagent run. `tool_result` events identify
- * the target row by `toolCallId` alone (no scope context needed), so
- * one flat map keeps the lookup trivial. Interpreter-owned (NOT reducer
- * state — it maps to DB row ids the reducer pre-allocates): populated when
- * `applyMainIntent` / `applySubagentIntent` create tool messages, read by
- * `persistToolResult` and the intervention handlers.
- */
+ // Run-global persisted tools retain their message and thread ownership after
+ // a subagent finalizes, so unscoped bridge requests cannot create main copies.
const toolMsgIdByCallId: Map<string, string> = new Map();
+ const toolThreadIdByCallId = new Map<string, string>();
const lastAppliedToolStateSeqByCallId = new Map<string, number>();
const mainToolCallIds = new Set<string>();
/** Terminal results reject later state until a new tool_start reopens the call id. */
const completedToolStateCallIds = new Set<string>();
/** Final tool_result supersedes every pending non-terminal state retry. */
const terminalToolMessageIds = 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
@@ -820,9 +810,9 @@ export const executeHeterogeneousAgent = async (
*/
let sawStreamedEvent = false;
- const getCurrentFrontendMessages = () =>
- (get().dbMessagesMap?.[messageMapKey(context)] ??
- get().messagesMap?.[messageMapKey(context)] ??
+ const getCurrentFrontendMessages = (messageContext = context) =>
+ (get().dbMessagesMap?.[messageMapKey(messageContext)] ??
+ get().messagesMap?.[messageMapKey(messageContext)] ??
[]) as UIChatMessage[];
const attachInitialAssistantSeed = (event: AgentStreamEvent): void => {
@@ -1048,80 +1038,6 @@ export const executeHeterogeneousAgent = async (
heterogeneousToolStateSeq: snapshotSeq,
};
};
- 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 ||
@@ -1234,6 +1150,7 @@ export const executeHeterogeneousAgent = async (
);
for (const message of toolRows) {
toolMsgIdByCallId.set(message.tool_call_id!, message.id);
+ toolThreadIdByCallId.set(message.tool_call_id!, thread.id);
}
const subagentMessageId = (currentAssistant.metadata as Record<string, unknown> | null)
?.subagentMessageId;
@@ -1464,8 +1381,8 @@ export const executeHeterogeneousAgent = async (
for (const { message, toolCallId } of persistedToolMessages) {
toolMsgIdByCallId.set(toolCallId, message.id);
+ toolThreadIdByCallId.set(toolCallId, intent.threadId);
t?.stream.create(message);
- await replayPendingInterventionsForToolCall(toolCallId);
}
// Surface the live assistant tools[] + content into the thread bucket.
@@ -1573,17 +1490,43 @@ export const executeHeterogeneousAgent = async (
// ─── Main-agent run coordinator (shared reducer) interpreter ─────────────
- /**
- * Apply ONE main-scoped coordinator intent against the renderer's write-behind
- * DB queue plus the local raw-message bucket. Best-effort (errors logged,
- * never thrown) — mirroring the prior inline persist helpers, so the run state
- * always advances regardless of a transient DB failure (the next event /
- * terminal flush re-persists). Token-level text/reasoning still streams via the
- * gateway handler; tool rows and result links are local SoT here so tool_end
- * reconciliation does not need a DB fetch.
- */
+ // The persisted row owns the thread for bridge transitions as well as tool results.
const applyMainIntent = async (intent: MainAgentIntent) => {
switch (intent.kind) {
+ case 'setToolIntervention': {
+ const toolMsgId = toolMsgIdByCallId.get(intent.toolCallId);
+ if (!toolMsgId) throw new Error(`Missing intervention tool: ${intent.toolCallId}`);
+ await messageWriteBatcher.flush('before-intervention');
+ const threadId = toolThreadIdByCallId.get(intent.toolCallId);
+ const interventionContext = threadId
+ ? { ...context, scope: 'thread' as MessageMapScope, threadId }
+ : context;
+ const previous = getCurrentFrontendMessages(interventionContext).find(
+ (msg) => msg.id === toolMsgId,
+ );
+ const intervention = preserveSkippedIntervention(
+ intent.intervention,
+ previous?.pluginIntervention,
+ );
+ const writeContext = threadId
+ ? { context: interventionContext, operationId }
+ : { operationId };
+ // Every tab's global approval island reads this shared projection.
+ dispatchInterventionState(get, toolMsgId, intervention, writeContext);
+ await get().optimisticUpdateMessagePlugin(toolMsgId, { intervention }, writeContext);
+ if (intent.transition === 'pending') {
+ writeTopicStatus('waitingForHuman');
+ void notifyDesktopHumanApprovalRequired(get, context);
+ } else if (
+ ![...mainState.interventionsByCallId].some(
+ ([id, item]) => id !== intent.toolCallId && item.intervention.status === 'pending',
+ )
+ ) {
+ writeTopicStatus('running');
+ }
+ return;
+ }
+
case 'createAssistant': {
const createMetadata: Record<string, any> = { ...heteroProvenance(intent.mainMessageId) };
if (intent.signal) createMetadata.signal = intent.signal;
@@ -1739,9 +1682,6 @@ export const executeHeterogeneousAgent = async (
},
{ operationId },
);
- for (const x of intent.tools) {
- if (x.isNew) await replayPendingInterventionsForToolCall(x.payload.id);
- }
return;
}
@@ -1889,6 +1829,7 @@ export const executeHeterogeneousAgent = async (
const ctx: MainAgentReduceCtx = {
agentId: context.agentId,
newId: (kind) => (kind === 'thread' ? generateThreadId() : `msg_${createNanoId(18)()}`),
+ toolMessageIds: toolMsgIdByCallId,
topicId: context.topicId ?? null,
};
const { intents, state: next } = reduceMainAgent(mainState, event, ctx);
@@ -2109,50 +2050,13 @@ export const executeHeterogeneousAgent = async (
get().updateOperationMetadata?.(operationId, { streamRetry: undefined });
}
- // ─── agent_intervention_request: CC AskUserQuestion needs user input ───
- // Stamp the canonical `pluginIntervention.status='pending'` on the
- // matching tool message via `optimisticUpdateMessagePlugin` — that
- // single primitive (1) writes to DB, (2) updates the in-memory
- // `dbMessagesMap` reducer, AND (3) mirrors the same intervention onto
- // the parent assistant's `tools[].intervention` so both surfaces
- // (inline tool body + bottom InterventionBar) light up immediately.
- // The Intervention component registered under
- // `BuiltinToolInterventions['claude-code'][askUserQuestion]` is
- // 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`; 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 () => {
- if (await applyInterventionRequest(data)) return;
-
- pendingInterventionRequests.set(data.toolCallId, data);
- if (!toolMsgIdByCallId.has(data.toolCallId)) {
- console.warn(
- '[HeterogeneousAgent] deferred intervention_request for unknown toolCallId:',
- data.toolCallId,
- );
- }
- });
- 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;
- persistQueue = persistQueue.then(async () => {
- if (await applyInterventionResponse(data)) return;
- pendingInterventionResponses.set(data.toolCallId, data);
- });
+ // Requests, ACKs and tool/runtime completion share one state machine so
+ // a missing bridge response cannot leave a completed question pending.
+ if (
+ event.type === 'agent_intervention_request' ||
+ event.type === 'agent_intervention_response'
+ ) {
+ persistQueue = persistQueue.then(() => reduceAndApplyMain(event));
return;
}
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/interventionAck.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/interventionAck.test.ts
new file mode 100644
index 00000000000..d68d1ae3256
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/interventionAck.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+
+import { preserveSkippedIntervention } from './interventionAck';
+
+describe('preserveSkippedIntervention', () => {
+ it('keeps an explicit local skip after the producer acknowledges user cancellation', () => {
+ const incoming = { rejectedReason: 'user_cancelled', status: 'rejected' as const };
+ expect(preserveSkippedIntervention(incoming, { skipped: true, status: 'rejected' })).toEqual({
+ ...incoming,
+ skipped: true,
+ });
+ expect(incoming).not.toHaveProperty('skipped');
+ });
+
+ it('keeps a cancelled action distinct from a skipped action', () => {
+ const incoming = { rejectedReason: 'user_cancelled', status: 'rejected' as const };
+ expect(preserveSkippedIntervention(incoming, { skipped: false, status: 'rejected' })).toBe(
+ incoming,
+ );
+ expect(preserveSkippedIntervention(incoming)).toBe(incoming);
+ });
+
+ it.each([
+ { status: 'approved' as const },
+ { rejectedReason: 'timeout', status: 'rejected' as const },
+ { rejectedReason: 'session_ended', status: 'aborted' as const },
+ ])('does not carry a skip into a different terminal outcome: $status', (incoming) => {
+ expect(preserveSkippedIntervention(incoming, { skipped: true, status: 'rejected' })).toBe(
+ incoming,
+ );
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/interventionAck.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/interventionAck.ts
new file mode 100644
index 00000000000..c02bbed90c3
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/interventionAck.ts
@@ -0,0 +1,11 @@
+import type { ToolIntervention } from '@lobechat/types';
+
+export const preserveSkippedIntervention = (
+ incoming: ToolIntervention,
+ previous?: ToolIntervention,
+): ToolIntervention =>
+ incoming.status === 'rejected' &&
+ incoming.rejectedReason === 'user_cancelled' &&
+ previous?.skipped === true
+ ? { ...incoming, skipped: true }
+ : incoming;
diff --git a/src/store/tool/builtinToolRegistry.test.ts b/src/store/tool/builtinToolRegistry.test.ts
index 15d7255720f..e8a766c36dc 100644
--- a/src/store/tool/builtinToolRegistry.test.ts
+++ b/src/store/tool/builtinToolRegistry.test.ts
@@ -425,6 +425,11 @@ describe('builtin tool registry', () => {
ClaudeCodeInterventions[UserInteractionApiName.askUserQuestion],
);
expect(getBuiltinIntervention('qoder', UserInteractionApiName.askUserQuestion)).toBeDefined();
+ expect(getBuiltinInspector('opencode', UserInteractionApiName.askUserQuestion)).toBeDefined();
+ expect(getBuiltinRender('opencode', UserInteractionApiName.askUserQuestion)).toBeDefined();
+ expect(getBuiltinIntervention('opencode', UserInteractionApiName.askUserQuestion)).toBe(
+ ClaudeCodeInterventions[UserInteractionApiName.askUserQuestion],
+ );
});
it('registers command and local-file surfaces for Devin ACP tool names', () => {