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: add optimistic feedback for V2 user question submissions (#19681)

Arvin Xu92367e93a60a
diff --git a/locales/en-US/tool.json b/locales/en-US/tool.json
index e148478b7c1..c4505fae74d 100644
--- a/locales/en-US/tool.json
+++ b/locales/en-US/tool.json
@@ -41,6 +41,8 @@
"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",
"askUserQuestion.escape.enter": "Replace all",
@@ -49,8 +51,11 @@
"askUserQuestion.recommendedTag": "Recommended",
"askUserQuestion.skip": "Skip",
"askUserQuestion.submit": "Submit",
+ "askUserQuestion.submitFailed": "Your response hasn’t been confirmed. Your answers are saved; please try again.",
+ "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/tool.json b/locales/zh-CN/tool.json
index 3284a942fb6..473f9048bbc 100644
--- a/locales/zh-CN/tool.json
+++ b/locales/zh-CN/tool.json
@@ -41,6 +41,8 @@
"agentMarketplace.render.alreadyInLibraryTag": "已在库中",
"agentMarketplace.render.alreadyInLibrary_one": "{{count}} 个已在库中",
"agentMarketplace.render.alreadyInLibrary_other": "{{count}} 个已在库中",
+ "askUserQuestion.checkStatus": "检查提交状态",
+ "askUserQuestion.checking": "正在确认提交状态…",
"askUserQuestion.customOption.placeholder": "或自己输入…",
"askUserQuestion.escape.back": "返回选项",
"askUserQuestion.escape.enter": "全部替换",
@@ -49,8 +51,11 @@
"askUserQuestion.recommendedTag": "推荐",
"askUserQuestion.skip": "跳过",
"askUserQuestion.submit": "提交",
+ "askUserQuestion.submitFailed": "回答尚未确认提交,已保留你的答案,请重试。",
+ "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/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx b/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx
index 2b72d0aac09..96a37d665f3 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
@@ -9,10 +9,11 @@ import {
} from '@lobechat/shared-tool-ui/ask-user';
import type { BuiltinInterventionProps } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
-import { Text } from '@lobehub/ui/base-ui';
+import { Alert, Button, Text } from '@lobehub/ui/base-ui';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { useConversationStore } from '@/features/Conversation/store';
import { dataSelectors } from '@/features/Conversation/store/slices/data/selectors';
import { useChatStore } from '@/store/chat';
@@ -41,6 +42,9 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
return (msg?.pluginState as { [DRAFT_PLUGIN_STATE_KEY]?: unknown })?.[DRAFT_PLUGIN_STATE_KEY];
});
const setInterventionDraft = useChatStore((s) => s.setInterventionDraft);
+ const submissionPhase = useChatStore((s) => s.questionSubmissions[messageId]);
+ const checkQuestionSubmission = useChatStore((s) => s.checkQuestionSubmission);
+ const context = useConversationStore((s) => s.context);
const writeDraft = useCallback(
(draft: AskUserDraft) => setInterventionDraft(messageId, draft),
[messageId, setInterventionDraft],
@@ -74,6 +78,32 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
);
}
+ if (submissionPhase === 'submitting' || submissionPhase === 'checking') {
+ return (
+ <Flexbox horizontal align="center" gap={8} padding={8} role="status">
+ <NeuralNetworkLoading size={16} />
+ <Text type="secondary">
+ {t(
+ submissionPhase === 'submitting'
+ ? 'askUserQuestion.submitting'
+ : 'askUserQuestion.checking',
+ )}
+ </Text>
+ </Flexbox>
+ );
+ }
+
+ 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'),
@@ -90,12 +120,17 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
};
return (
- <AskUserQuestionView
- {...form}
- actionsPortalTarget={actionsPortalTarget}
- labels={labels}
- showCountdown={false}
- />
+ <Flexbox gap={8}>
+ {submissionPhase === 'failed' && (
+ <Alert title={t('askUserQuestion.submitFailed')} type="error" />
+ )}
+ <AskUserQuestionView
+ {...form}
+ actionsPortalTarget={actionsPortalTarget}
+ labels={labels}
+ showCountdown={false}
+ />
+ </Flexbox>
);
});
diff --git a/packages/locales/src/default/tool.ts b/packages/locales/src/default/tool.ts
index a539e47952b..edd9e02d95a 100644
--- a/packages/locales/src/default/tool.ts
+++ b/packages/locales/src/default/tool.ts
@@ -1,4 +1,12 @@
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.',
+
'agentGroupManagement.executeTask.agent': 'Execute Agent',
'agentGroupManagement.executeTask.cancelled': 'Cancelled',
'agentGroupManagement.executeTask.completed': 'Task Completed',
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx
index 0de3a2fda2b..9f864f4b08f 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx
@@ -72,6 +72,11 @@ vi.mock('@/store/tool', () => ({
useToolStore: (selector: (state: unknown) => unknown) => selector({}),
}));
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: unknown) => unknown) =>
+ selector({ runQuestionSubmission: vi.fn() }),
+}));
+
vi.mock('@/store/user', () => ({
useUserStore: (selector: (state: unknown) => unknown) => selector({}),
}));
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx
index 80958ae20ed..89b331fda8b 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx
@@ -5,6 +5,7 @@ import { memo, Suspense, useCallback, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useSingleton } from '@/hooks/useSingleton';
+import { useChatStore } from '@/store/chat';
import { useUserStore } from '@/store/user';
import { toolInterventionSelectors } from '@/store/user/selectors';
@@ -132,7 +133,7 @@ const Intervention = memo<InterventionProps>(
// land on whichever topic the user is currently viewing.
const submitHeteroIntervention = useConversationStore((s) => s.submitHeteroIntervention);
- const handleInteractionAction = useCallback(
+ const executeInteractionAction = useCallback(
async (
action:
| { type: 'submit'; payload: Record<string, unknown> }
@@ -231,6 +232,31 @@ const Intervention = memo<InterventionProps>(
],
);
+ const context = useConversationStore((s) => s.context);
+ const runQuestionSubmission = useChatStore((s) => s.runQuestionSubmission);
+ const handleInteractionAction = useCallback(
+ (action: Parameters<typeof executeInteractionAction>[0]) => {
+ if (
+ usesDurableServerClaim &&
+ apiName === 'askUserQuestion' &&
+ ['lobe-agent', 'lobe-user-interaction'].includes(identifier) &&
+ (action.type === 'submit' || action.type === 'skip')
+ ) {
+ return runQuestionSubmission(id, context, () => executeInteractionAction(action));
+ }
+ return executeInteractionAction(action);
+ },
+ [
+ apiName,
+ context,
+ executeInteractionAction,
+ id,
+ identifier,
+ runQuestionSubmission,
+ usesDurableServerClaim,
+ ],
+ );
+
const BuiltinToolInterventionRender = getBuiltinIntervention(identifier, apiName);
if (BuiltinToolInterventionRender) {
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 192578acc3b..fbe9b7acc2f 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -68,6 +68,7 @@ beforeEach(() => {
});
useChatStore.setState({
updateTopicStatus: vi.fn().mockResolvedValue(undefined),
+ questionSubmissions: {},
});
useUserStore.setState({ user: undefined, workspaceUserPreference: {} });
});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/questionSubmission.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/questionSubmission.test.ts
new file mode 100644
index 00000000000..c91123a732e
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/questionSubmission.test.ts
@@ -0,0 +1,159 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+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 type { StoreSetter } from '@/store/types';
+
+import { QuestionSubmissionActionImpl } from '../entries/questionSubmission';
+import { createMockMessage } from './fixtures';
+
+vi.mock('@/services/message', () => ({ messageService: { getMessages: vi.fn() } }));
+
+const context = { agentId: 'agent-question', topicId: 'topic-question' };
+const key = messageMapKey(context);
+const question = createMockMessage({
+ content: '',
+ id: 'question',
+ plugin: {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ identifier: 'lobe-agent',
+ type: 'default',
+ },
+ pluginIntervention: { batchId: 'batch', operationId: 'operation', status: 'pending' },
+ pluginState: { askUserDraft: { picks: { Color: ['Blue'] }, supplementText: 'Keep my note' } },
+ role: 'tool',
+ tool_call_id: 'call-question',
+});
+
+const createAction = () => {
+ const state = {
+ dbMessagesMap: { [key]: [question] },
+ questionSubmissions: {},
+ refreshMessages: vi.fn().mockResolvedValue(undefined),
+ } as unknown as ChatStore;
+ state.internal_dispatchMessage = (payload) => {
+ state.dbMessagesMap[key] = messagesReducer(state.dbMessagesMap[key], payload);
+ };
+ const set: StoreSetter<ChatStore> = (update) => {
+ Object.assign(state, typeof update === 'function' ? update(state) : update);
+ };
+ const action = new QuestionSubmissionActionImpl(set, () => state);
+ return { action, state };
+};
+
+beforeEach(() => {
+ vi.mocked(messageService.getMessages).mockReset();
+});
+
+describe('question submission feedback', () => {
+ it('collapses immediately without changing the pending row and blocks duplicate clicks', async () => {
+ const { action, state } = createAction();
+ const request = Promise.withResolvers<void>();
+ const submit = vi.fn(() => request.promise);
+ const pending = action.runQuestionSubmission(question.id, context, submit);
+ expect(state.questionSubmissions.question).toBe('submitting');
+ expect(state.dbMessagesMap[key][0]).toEqual(question);
+ await action.runQuestionSubmission(question.id, context, submit);
+ expect(submit).toHaveBeenCalledOnce();
+ request.resolve();
+ await pending;
+ expect(state.questionSubmissions.question).toBeUndefined();
+ });
+
+ it.each(['submit_answers', 'skip_interaction'] as const)(
+ 'settles %s locally on confirmation without waiting for message revalidation',
+ async (type) => {
+ const { action, state } = createAction();
+ state.refreshMessages = vi.fn(() => new Promise<void>(() => {}));
+ action.internal_confirmQuestionSubmission(
+ question.id,
+ type === 'submit_answers' ? { type, result: { Color: ['Blue'] } } : { type },
+ context,
+ );
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.status).toBe(
+ type === 'submit_answers' ? 'approved' : 'rejected',
+ );
+ expect(state.dbMessagesMap[key][0].pluginState).toMatchObject(question.pluginState!);
+ if (type === 'submit_answers') {
+ expect(state.dbMessagesMap[key][0].pluginState).toHaveProperty('askUserAnswers', {
+ Color: ['Blue'],
+ });
+ }
+ },
+ );
+
+ it('restores the saved answers after a failed submit and authoritative pending read', async () => {
+ const { action, state } = createAction();
+ const error = new Error('submit failed');
+ vi.mocked(messageService.getMessages).mockResolvedValue([question]);
+ await expect(
+ action.runQuestionSubmission(question.id, context, async () => {
+ throw error;
+ }),
+ ).rejects.toThrow(error);
+ expect(state.questionSubmissions.question).toBe('failed');
+ expect(state.dbMessagesMap[key][0].pluginState).toEqual(question.pluginState);
+ const retry = vi.fn().mockResolvedValue(undefined);
+ await action.runQuestionSubmission(question.id, context, retry);
+ expect(retry).toHaveBeenCalledOnce();
+ });
+
+ it('adopts a server-confirmed answer after a lost response without reopening the form', async () => {
+ const { action, state } = createAction();
+ vi.mocked(messageService.getMessages).mockResolvedValue([
+ {
+ ...question,
+ content: 'Already answered',
+ pluginIntervention: { status: 'approved' },
+ pluginState: { askUserAnswers: { Color: ['Red'] } },
+ },
+ ]);
+ await action.runQuestionSubmission(question.id, context, async () => {
+ throw new TypeError('Failed to fetch');
+ });
+ expect(state.questionSubmissions.question).toBeUndefined();
+ expect(state.dbMessagesMap[key][0].pluginState).toMatchObject({
+ askUserAnswers: { Color: ['Red'] },
+ });
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.status).toBe('approved');
+ });
+
+ it('keeps an unconfirmed response collapsed until checking succeeds', async () => {
+ const { action, state } = createAction();
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(messageService.getMessages).mockRejectedValueOnce(new Error('offline'));
+ await expect(
+ action.runQuestionSubmission(question.id, context, async () => {
+ throw new Error('offline');
+ }),
+ ).rejects.toThrow('offline');
+ expect(state.questionSubmissions.question).toBe('uncertain');
+ const submit = vi.fn();
+ await action.runQuestionSubmission(question.id, context, submit);
+ expect(submit).not.toHaveBeenCalled();
+ vi.mocked(messageService.getMessages).mockResolvedValueOnce([question]);
+ await action.checkQuestionSubmission(question.id, context);
+ expect(state.questionSubmissions.question).toBe('failed');
+ log.mockRestore();
+ });
+
+ it('does not reopen an accepted answer when connecting its continuation fails', async () => {
+ const { action, state } = createAction();
+ await expect(
+ action.runQuestionSubmission(question.id, context, async () => {
+ action.internal_confirmQuestionSubmission(
+ question.id,
+ { type: 'submit_answers', result: { Color: ['Blue'] } },
+ context,
+ );
+ throw new Error('connection failed');
+ }),
+ ).rejects.toThrow('connection failed');
+ expect(state.questionSubmissions.question).toBeUndefined();
+ expect(state.dbMessagesMap[key][0].pluginIntervention?.status).toBe('approved');
+ expect(messageService.getMessages).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
index 0876f92f5a9..e73831193ab 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
@@ -178,8 +178,24 @@ export class ConversationControlActionImpl {
});
if (result.handled) {
this.#interventionResolutionRequestIds.delete(resolutionKey);
+ if (result.state === 'claimed' && params.context) {
+ for (const id of params.toolMessageIds) {
+ this.#get().internal_confirmQuestionSubmission(id, params.action, params.context);
+ }
+ }
if (result.state === 'already_resolved' && params.context) {
- await this.#get().refreshMessages(params.context);
+ const submittingQuestions = params.toolMessageIds.filter(
+ (id) => this.#get().questionSubmissions[id],
+ );
+ if (submittingQuestions.length > 0) {
+ await Promise.all(
+ submittingQuestions.map((id) =>
+ this.#get().checkQuestionSubmission(id, params.context!),
+ ),
+ );
+ } else {
+ await this.#get().refreshMessages(params.context);
+ }
}
}
return result;
diff --git a/src/store/chat/slices/agentRun/actions/entries/questionSubmission.ts b/src/store/chat/slices/agentRun/actions/entries/questionSubmission.ts
new file mode 100644
index 00000000000..4e166a70296
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/questionSubmission.ts
@@ -0,0 +1,156 @@
+import type { ConversationContext, UIChatMessage } from '@lobechat/types';
+
+import type { AgentInterventionSourceAction } from '@/services/aiAgent';
+import { messageService } from '@/services/message';
+import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';
+import type { ChatStore } from '@/store/chat/store';
+import type { StoreSetter } from '@/store/types';
+
+import type { QuestionSubmissionPhase } from '../../initialState';
+
+export class QuestionSubmissionActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: StoreSetter<ChatStore>;
+
+ constructor(set: StoreSetter<ChatStore>, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ #setPhase = (id: string, phase?: QuestionSubmissionPhase) => {
+ this.#set((state) => {
+ const questionSubmissions = { ...state.questionSubmissions };
+ if (phase) questionSubmissions[id] = phase;
+ else delete questionSubmissions[id];
+ return { questionSubmissions };
+ });
+ };
+
+ #applyResolution = (message: UIChatMessage, context: ConversationContext) => {
+ const { content, pluginIntervention, pluginState } = message;
+ const dispatchContext = { context };
+ this.#get().internal_dispatchMessage(
+ {
+ id: message.id,
+ type: 'updateMessage',
+ value: { content, pluginIntervention, pluginState },
+ },
+ dispatchContext,
+ );
+ if (message.parentId && message.tool_call_id) {
+ this.#get().internal_dispatchMessage(
+ {
+ id: message.parentId,
+ tool_call_id: message.tool_call_id,
+ type: 'updateMessageTools',
+ value: { intervention: pluginIntervention },
+ },
+ dispatchContext,
+ );
+ }
+ };
+
+ /** Reconcile only this tool row: a late read must not overwrite streamed assistant content. */
+ checkQuestionSubmission = async (id: string, context: ConversationContext): Promise<boolean> => {
+ if (this.#get().questionSubmissions[id] === 'checking') return false;
+ this.#setPhase(id, 'checking');
+ try {
+ const messages = await messageService.getMessages({ ...context, skipWorks: true });
+ const message = messages.find((item) => item.id === id);
+ if (!message?.pluginIntervention) throw new Error('Question resolution is unavailable');
+ if (message.pluginIntervention.status === 'pending') {
+ // An event may have confirmed the answer while this read was in flight.
+ const current = dbMessageSelectors.getDbMessageById(id)(this.#get());
+ if (current?.pluginIntervention && current.pluginIntervention.status !== 'pending') {
+ this.#setPhase(id);
+ return true;
+ }
+ this.#setPhase(id, 'failed');
+ return false;
+ }
+ this.#applyResolution(message, context);
+ this.#setPhase(id);
+ return true;
+ } catch (error) {
+ console.error('[QuestionSubmission] Failed to check resolution:', error);
+ this.#setPhase(id, 'uncertain');
+ return false;
+ }
+ };
+
+ /** The form can collapse immediately without writing to the server-owned pending row. */
+ runQuestionSubmission = async (
+ id: string,
+ context: ConversationContext,
+ submit: () => Promise<void>,
+ ): Promise<void> => {
+ const phase = this.#get().questionSubmissions[id];
+ if (phase && phase !== 'failed') return;
+ this.#setPhase(id, 'submitting');
+ try {
+ await submit();
+ } catch (error) {
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
+ if (message?.pluginIntervention && message.pluginIntervention.status !== 'pending') {
+ // The answer was accepted; a continuation failure must not reopen it.
+ this.#setPhase(id);
+ throw error;
+ }
+ if (await this.checkQuestionSubmission(id, context)) return;
+ throw error;
+ }
+ const resultPhase = this.#get().questionSubmissions[id];
+ if (resultPhase === 'failed' || resultPhase === 'uncertain') {
+ throw new Error('Question submission could not be confirmed');
+ }
+ this.#setPhase(id);
+ };
+
+ /** Apply only a confirmed built-in question claim; heterogeneous producer ACKs stay separate. */
+ internal_confirmQuestionSubmission = (
+ id: string,
+ action: AgentInterventionSourceAction,
+ context: ConversationContext,
+ ): void => {
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
+ if (
+ message?.plugin?.apiName !== 'askUserQuestion' ||
+ !['lobe-agent', 'lobe-user-interaction'].includes(message.plugin.identifier) ||
+ (action.type !== 'submit_answers' && action.type !== 'skip_interaction')
+ )
+ return;
+
+ const skipped = action.type === 'skip_interaction';
+ this.#applyResolution(
+ {
+ ...message,
+ content: skipped
+ ? 'User skipped this question.'
+ : `User submitted: ${JSON.stringify(action.result)}`,
+ pluginIntervention: {
+ ...message.pluginIntervention,
+ resolving: false,
+ ...(skipped ? { skipped: true } : {}),
+ status: skipped ? 'rejected' : 'approved',
+ },
+ pluginState: skipped
+ ? message.pluginState
+ : { ...message.pluginState, askUserAnswers: action.result },
+ },
+ context,
+ );
+ // Authoritative events / ordinary message revalidation reconcile the result.
+ // Do not put a second network round trip on the continuation's critical path.
+ void this.#get()
+ .refreshMessages(context)
+ .catch((error) => {
+ console.error('[QuestionSubmission] Background revalidation failed:', error);
+ });
+ };
+}
+
+export type QuestionSubmissionAction = Pick<
+ QuestionSubmissionActionImpl,
+ keyof QuestionSubmissionActionImpl
+>;
diff --git a/src/store/chat/slices/agentRun/actions/index.ts b/src/store/chat/slices/agentRun/actions/index.ts
index 4945476cafd..75ab074fbf7 100644
--- a/src/store/chat/slices/agentRun/actions/index.ts
+++ b/src/store/chat/slices/agentRun/actions/index.ts
@@ -7,6 +7,10 @@ import { type ConversationControlAction } from './entries/conversationControl';
import { ConversationControlActionImpl } from './entries/conversationControl';
import { type ConversationLifecycleAction } from './entries/conversationLifecycle';
import { ConversationLifecycleActionImpl } from './entries/conversationLifecycle';
+import {
+ type QuestionSubmissionAction,
+ QuestionSubmissionActionImpl,
+} from './entries/questionSubmission';
import { type ChatMemoryAction } from './state/memory';
import { ChatMemoryActionImpl } from './state/memory';
import { type StreamingStatesAction } from './state/streamingStates';
@@ -22,6 +26,7 @@ export type ChatAgentRunAction = ChatMemoryAction &
ClientToolExecutionAction &
ConversationLifecycleAction &
ConversationControlAction &
+ QuestionSubmissionAction &
GatewayAction &
StreamingExecutorAction &
StreamingStatesAction;
@@ -41,6 +46,7 @@ export const chatAgentRun: StateCreator<
new ClientToolExecutionActionImpl(...params),
new ConversationLifecycleActionImpl(...params),
new ConversationControlActionImpl(...params),
+ new QuestionSubmissionActionImpl(...params),
new GatewayActionImpl(...params),
new StreamingExecutorActionImpl(...params),
new StreamingStatesActionImpl(...params),
diff --git a/src/store/chat/slices/agentRun/initialState.ts b/src/store/chat/slices/agentRun/initialState.ts
index 92bf1e7700d..27fb8e54de8 100644
--- a/src/store/chat/slices/agentRun/initialState.ts
+++ b/src/store/chat/slices/agentRun/initialState.ts
@@ -21,6 +21,8 @@ export interface GatewayFeedEntry {
status: string;
}
+export type QuestionSubmissionPhase = 'submitting' | 'checking' | 'failed' | 'uncertain';
+
export interface ChatAIChatState {
/**
* Active Agent Gateway WebSocket connections, keyed by operationId
@@ -45,6 +47,8 @@ export interface ChatAIChatState {
* UI can render a distinct "running on device" state.
*/
pendingClientToolExecutions: Record<string, boolean>;
+ /** Local UI feedback only; never persisted as the server intervention status. */
+ questionSubmissions: Record<string, QuestionSubmissionPhase>;
searchWorkflowLoadingIds: string[];
threadInputEditor: ChatInputEditor | null;
/**
@@ -61,6 +65,7 @@ export const initialAiChatState: ChatAIChatState = {
mainConversationScrollToIndex: null,
mainInputEditor: null,
pendingClientToolExecutions: {},
+ questionSubmissions: {},
searchWorkflowLoadingIds: [],
threadInputEditor: null,
toolCallingStreamIds: {},