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.

✨ feat(lobe-agent): add askUserQuestion capability & soft-disable agent onboarding (#16760)

Arvin Xuf9f504f56e6b
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index ffd48360b7e..83dafdf13be 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -194,6 +194,26 @@ const ExecAgentSchema = z
toolCallId: z.string(),
})
.optional(),
+ /**
+ * Resume a previous op paused on a `humanIntervention: 'always'` tool (e.g.
+ * lobe-agent `askUserQuestion`). When set, the new op writes the
+ * human-provided answer as the target tool message's result and resumes from
+ * `phase: 'tool_result'` β€” the tool is NOT re-executed, so the runtime never
+ * overwrites the answer with a fresh "pending" placeholder. Mutually
+ * exclusive with `resumeApproval`.
+ */
+ resumeToolResult: z
+ .object({
+ /** The human-provided tool result (the answer text). */
+ content: z.string(),
+ /** ID of the pending `role='tool'` message this result targets. */
+ parentMessageId: z.string(),
+ /** Optional plugin state to persist on the tool message. */
+ pluginState: z.record(z.unknown()).optional(),
+ /** tool_call_id of the pending tool call being answered. */
+ toolCallId: z.string(),
+ })
+ .optional(),
/**
* Tool identifiers the user @-mentioned in this message. Enabled for this
* run in addition to the agent's pinned plugins, so a mentioned tool that
@@ -700,6 +720,7 @@ export const aiAgentRouter = router({
mentionedAgents,
parentMessageId,
resumeApproval,
+ resumeToolResult,
selectedToolIds,
trigger,
userInterventionConfig,
@@ -722,6 +743,7 @@ export const aiAgentRouter = router({
// human-approval resume β€” either way, skip user message creation.
resume: !!parentMessageId,
resumeApproval,
+ resumeToolResult,
selectedToolIds,
slug,
trigger: trigger ?? RequestTrigger.Chat,
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts
new file mode 100644
index 00000000000..33d52f49e50
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts
@@ -0,0 +1,299 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import type * as ModelBankModule from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '../index';
+
+const {
+ mockCreateOperation,
+ mockFindById,
+ mockFindMessagePlugin,
+ mockMessageCreate,
+ mockMessageQuery,
+ mockUpdateMessagePlugin,
+ mockUpdatePluginState,
+ mockUpdateToolMessage,
+} = vi.hoisted(() => ({
+ mockCreateOperation: vi.fn(),
+ mockFindById: vi.fn(),
+ mockFindMessagePlugin: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ mockMessageQuery: vi.fn(),
+ mockUpdateMessagePlugin: vi.fn(),
+ mockUpdatePluginState: vi.fn(),
+ mockUpdateToolMessage: vi.fn(),
+}));
+
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(() => ({
+ create: mockMessageCreate,
+ findById: mockFindById,
+ findMessagePlugin: mockFindMessagePlugin,
+ query: mockMessageQuery,
+ update: vi.fn().mockResolvedValue({}),
+ updateMessagePlugin: mockUpdateMessagePlugin,
+ updatePluginState: mockUpdatePluginState,
+ updateToolMessage: mockUpdateToolMessage,
+ })),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(() => ({ queryAgents: vi.fn().mockResolvedValue([]) })),
+}));
+
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(() => ({
+ getAgentConfig: vi.fn().mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-1',
+ knowledgeBases: [],
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant',
+ }),
+ })),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(() => ({ query: vi.fn().mockResolvedValue([]) })),
+}));
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(() => ({
+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ updateMetadata: vi.fn(),
+ })),
+}));
+
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn().mockImplementation(() => ({
+ create: vi.fn(),
+ findById: vi.fn(),
+ update: vi.fn(),
+ })),
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: vi.fn().mockImplementation(() => ({
+ getUserSettings: vi.fn().mockResolvedValue(undefined),
+ })),
+}));
+
+vi.mock('@/database/models/userMemory/persona', () => ({
+ UserPersonaModel: vi.fn().mockImplementation(() => ({
+ getLatestPersonaDocument: vi.fn().mockResolvedValue(undefined),
+ })),
+}));
+
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(() => ({
+ createOperation: mockCreateOperation,
+ })),
+}));
+
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn().mockImplementation(() => ({
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/server/services/composio', () => ({
+ ComposioService: vi.fn().mockImplementation(() => ({
+ getComposioManifests: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({ uploadFromUrl: vi.fn() })),
+}));
+
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
+ }),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: { isConfigured: false, queryDeviceList: vi.fn().mockResolvedValue([]) },
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: vi.fn(),
+}));
+
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ abilities: { functionCall: true, vision: true },
+ id: 'gpt-4',
+ providerId: 'openai',
+ },
+ ],
+ };
+});
+
+describe('AiAgentService.execAgent - resumeToolResult', () => {
+ let service: AiAgentService;
+
+ // `messages` row β€” `findById` returns this.
+ const pendingToolMessage = {
+ id: 'tool-msg-1',
+ role: 'tool',
+ sessionId: 'session-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ };
+ // `message_plugins` row β€” fetched via findMessagePlugin.
+ const pendingToolPlugin = {
+ apiName: 'askUserQuestion',
+ arguments: '{"question":"favorite color?"}',
+ identifier: 'lobe-agent',
+ toolCallId: 'call_ask',
+ type: 'builtin',
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockCreateOperation.mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ });
+ mockFindById.mockResolvedValue(pendingToolMessage);
+ mockFindMessagePlugin.mockResolvedValue(pendingToolPlugin);
+ mockMessageQuery.mockResolvedValue([{ content: 'hi', id: 'history-1', role: 'user' }]);
+ mockMessageCreate.mockResolvedValue({ id: 'assistant-msg-new' });
+ mockUpdateMessagePlugin.mockResolvedValue(undefined);
+ mockUpdatePluginState.mockResolvedValue(undefined);
+ mockUpdateToolMessage.mockResolvedValue(undefined);
+ service = new AiAgentService({} as unknown as LobeChatDatabase, 'user-1');
+ });
+
+ const baseParams = {
+ agentId: 'agent-1',
+ appContext: { sessionId: 'session-1', threadId: 'thread-1', topicId: 'topic-1' },
+ parentMessageId: 'tool-msg-1',
+ prompt: '',
+ };
+
+ it('writes the human answer as tool content, marks approved, and resumes from tool_result (no re-execution)', async () => {
+ await service.execAgent({
+ ...baseParams,
+ resumeToolResult: {
+ content: 'My favorite color is blue',
+ parentMessageId: 'tool-msg-1',
+ toolCallId: 'call_ask',
+ },
+ });
+
+ // The human answer becomes the tool message's result content.
+ expect(mockUpdateToolMessage).toHaveBeenCalledWith('tool-msg-1', {
+ content: 'My favorite color is blue',
+ });
+ // Intervention is marked approved so the pending state clears.
+ expect(mockUpdateMessagePlugin).toHaveBeenCalledWith('tool-msg-1', {
+ intervention: { status: 'approved' },
+ });
+
+ // Resumes from `tool_result` β€” NOT `human_approved_tool` (which would
+ // re-dispatch the tool and overwrite the answer).
+ expect(mockCreateOperation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ initialContext: expect.objectContaining({
+ payload: expect.objectContaining({ parentMessageId: 'tool-msg-1' }),
+ phase: 'tool_result',
+ }),
+ }),
+ );
+ const call = mockCreateOperation.mock.calls[0][0];
+ expect(call.initialContext.phase).not.toBe('human_approved_tool');
+ });
+
+ it('persists pluginState when provided', async () => {
+ await service.execAgent({
+ ...baseParams,
+ resumeToolResult: {
+ content: 'blue',
+ parentMessageId: 'tool-msg-1',
+ pluginState: { askUserAnswers: { 'favorite color?': 'blue' } },
+ toolCallId: 'call_ask',
+ },
+ });
+
+ expect(mockUpdatePluginState).toHaveBeenCalledWith('tool-msg-1', {
+ askUserAnswers: { 'favorite color?': 'blue' },
+ });
+ });
+
+ it('does not persist pluginState when omitted', async () => {
+ await service.execAgent({
+ ...baseParams,
+ resumeToolResult: {
+ content: 'blue',
+ parentMessageId: 'tool-msg-1',
+ toolCallId: 'call_ask',
+ },
+ });
+
+ expect(mockUpdatePluginState).not.toHaveBeenCalled();
+ });
+
+ describe('validation guards', () => {
+ it('throws when the parent message is not role=tool', async () => {
+ mockFindById.mockResolvedValue({ ...pendingToolMessage, role: 'user' });
+
+ await expect(
+ service.execAgent({
+ ...baseParams,
+ resumeToolResult: {
+ content: 'blue',
+ parentMessageId: 'tool-msg-1',
+ toolCallId: 'call_ask',
+ },
+ }),
+ ).rejects.toThrow(/role='tool'/);
+ });
+
+ it('throws when the stored tool_call_id does not match the resume request', async () => {
+ mockFindMessagePlugin.mockResolvedValue({ ...pendingToolPlugin, toolCallId: 'call_other' });
+
+ await expect(
+ service.execAgent({
+ ...baseParams,
+ resumeToolResult: {
+ content: 'blue',
+ parentMessageId: 'tool-msg-1',
+ toolCallId: 'call_ask',
+ },
+ }),
+ ).rejects.toThrow(/toolCallId mismatch/);
+ });
+
+ it('throws when no plugin row exists for the target message', async () => {
+ mockFindMessagePlugin.mockResolvedValue(undefined);
+
+ await expect(
+ service.execAgent({
+ ...baseParams,
+ resumeToolResult: {
+ content: 'blue',
+ parentMessageId: 'tool-msg-1',
+ toolCallId: 'call_ask',
+ },
+ }),
+ ).rejects.toThrow(/no plugin row/);
+ });
+ });
+});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 48a69f4a992..a76e6969586 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -338,6 +338,20 @@ interface InternalExecAgentParams extends ExecAgentParams {
rejectionReason?: string;
toolCallId: string;
};
+ /**
+ * When present, this execAgent call resumes a previous op that paused on a
+ * `humanIntervention: 'always'` tool (e.g. lobe-agent `askUserQuestion`). The
+ * service writes the human-provided `content` as the target tool message's
+ * result and resumes from `phase: 'tool_result'` β€” the tool is NOT
+ * re-executed. `parentMessageId` must point at the pending `role='tool'`
+ * message. Mutually exclusive with `resumeApproval`.
+ */
+ resumeToolResult?: {
+ content: string;
+ parentMessageId: string;
+ pluginState?: Record<string, unknown>;
+ toolCallId: string;
+ };
/**
* Tool identifiers the user @-mentioned in this message. Merged into the
* agent's plugin set for this run (alongside `additionalPluginIds`) so a
@@ -953,6 +967,7 @@ export class AiAgentService {
parentOperationId,
resume,
resumeApproval,
+ resumeToolResult,
selectedToolIds,
mentionedAgents,
suppressUserMessage,
@@ -1154,7 +1169,7 @@ export class AiAgentService {
// tRPC router get `resume: true` via the router, but the service-level
// API allows resumeApproval alone β€” fold both into a single effective
// flag so downstream resume branches don't need to know about approval.
- const effectiveResume = resume || !!resumeApproval;
+ const effectiveResume = resume || !!resumeApproval || !!resumeToolResult;
// Both resume and suppressUserMessage run the turn off existing history
// instead of appending a new user message β€” share the message-construction
@@ -1265,6 +1280,63 @@ export class AiAgentService {
);
}
+ // 2.7. Human-answer resume: a `humanIntervention: 'always'` tool (e.g.
+ // lobe-agent `askUserQuestion`) paused this run. Write the human-provided
+ // answer as the target tool message's result and mark the intervention
+ // approved so the history fetched below reflects the answer before the
+ // first step runs. Unlike `resumeApproval` (`approved`), we resume from
+ // `phase: 'tool_result'` (see 16c) rather than re-executing the tool β€” the
+ // answer IS the result. Same validation shape as resumeApproval:
+ // parent must be a pending role='tool' message tied to the tool call.
+ // `resumeApproval` and `resumeToolResult` are mutually exclusive.
+ if (resumeToolResult) {
+ if (!resumeParentMessage) {
+ throw new Error('resumeToolResult requires parentMessageId to point at a tool message');
+ }
+ if (resumeParentMessage.role !== 'tool') {
+ throw new Error(
+ `resumeToolResult.parentMessageId must point at a role='tool' message, got role='${resumeParentMessage.role}'`,
+ );
+ }
+
+ const resumeToolResultPlugin = await this.messageModel.findMessagePlugin(
+ resumeToolResult.parentMessageId,
+ );
+ if (!resumeToolResultPlugin) {
+ throw new Error(
+ `resumeToolResult: no plugin row for tool message ${resumeToolResult.parentMessageId}`,
+ );
+ }
+ if (
+ resumeToolResultPlugin.toolCallId &&
+ resumeToolResultPlugin.toolCallId !== resumeToolResult.toolCallId
+ ) {
+ throw new Error(
+ `resumeToolResult.toolCallId mismatch for message ${resumeToolResult.parentMessageId}: ` +
+ `stored=${resumeToolResultPlugin.toolCallId}, requested=${resumeToolResult.toolCallId}`,
+ );
+ }
+
+ await this.messageModel.updateToolMessage(resumeToolResult.parentMessageId, {
+ content: resumeToolResult.content,
+ });
+ await this.messageModel.updateMessagePlugin(resumeToolResult.parentMessageId, {
+ intervention: { status: 'approved' },
+ });
+ if (resumeToolResult.pluginState) {
+ await this.messageModel.updatePluginState(
+ resumeToolResult.parentMessageId,
+ resumeToolResult.pluginState,
+ );
+ }
+
+ log(
+ 'execAgent: resumeToolResult applied to tool message %s (toolCallId=%s)',
+ resumeToolResult.parentMessageId,
+ resumeToolResult.toolCallId,
+ );
+ }
+
// 3. Handle topic creation: if no topicId provided, create a new topic; otherwise reuse existing
let topicId = appContext?.topicId;
const isNewTopic = !topicId;
@@ -3135,6 +3207,27 @@ export class AiAgentService {
}
}
+ // 16c. Human-answer resume β€” resume from the persisted tool result WITHOUT
+ // re-executing the tool. The DB write above (2.7) already set the tool
+ // message content to the human answer, so `allMessages` reflects it. Using
+ // `phase: 'tool_result'` (not `human_approved_tool`) makes the runner
+ // continue the loop from the answered tool call rather than dispatching a
+ // fresh `call_tool` β€” which would overwrite the answer with a new "pending"
+ // result. Mirrors the client's tool-result-only resume path.
+ if (resumeToolResult) {
+ initialContext = {
+ initialContext: initialContext.initialContext,
+ payload: { parentMessageId: resumeToolResult.parentMessageId } as any,
+ phase: 'tool_result' as const,
+ session: {
+ messageCount: allMessages.length,
+ sessionId: operationId,
+ status: 'idle' as const,
+ stepCount: 0,
+ },
+ };
+ }
+
// 17. Log final operation parameters summary
log(
'execAgent: creating operation %s with params: model=%s, provider=%s, tools=%d, messages=%d, manifests=%d',
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
index c6375f42eaa..9e06398542c 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
@@ -15,6 +15,7 @@ import {
selectVisualFileItems,
validateVisualMediaUrls,
} from '@lobechat/builtin-tool-lobe-agent';
+import { UserInteractionExecutionRuntime } from '@lobechat/builtin-tool-user-interaction/executionRuntime';
import type { LobeChatDatabase } from '@lobechat/database';
import type { ChatStreamPayload } from '@lobechat/model-runtime';
import { consumeStreamUntilDone } from '@lobechat/model-runtime';
@@ -89,6 +90,10 @@ class LobeAgentExecutionRuntime {
private topicId?: string;
private planRuntime: PlanExecutionRuntime;
private workspaceId?: string;
+ // Reused from the standalone user-interaction tool. askUserQuestion is
+ // human-intervention 'always', so the user's UI answer normally becomes the
+ // tool result; this runtime is only the fallback executor.
+ private interactionRuntime = new UserInteractionExecutionRuntime();
constructor(context: LobeAgentRuntimeContext) {
this.agentId = context.agentId;
@@ -110,6 +115,11 @@ class LobeAgentExecutionRuntime {
);
}
+ // ==================== Ask User Question ====================
+
+ askUserQuestion = (params: unknown): Promise<BuiltinServerRuntimeOutput> =>
+ this.interactionRuntime.askUserQuestion(params);
+
// ==================== Plan / Todo (delegated to PlanExecutionRuntime) ====================
createPlan = (params: any) =>
diff --git a/locales/en-US/tool.json b/locales/en-US/tool.json
index 0d0e491b491..9361319f3d9 100644
--- a/locales/en-US/tool.json
+++ b/locales/en-US/tool.json
@@ -40,6 +40,13 @@
"agentMarketplace.render.alreadyInLibraryTag": "Already in library",
"agentMarketplace.render.alreadyInLibrary_one": "{{count}} already in library",
"agentMarketplace.render.alreadyInLibrary_other": "{{count}} already in library",
+ "askUserQuestion.customOption.placeholder": "Or write your own…",
+ "askUserQuestion.escape.back": "Back to options",
+ "askUserQuestion.escape.enter": "Or type directly",
+ "askUserQuestion.escape.placeholder": "Type your answer here…",
+ "askUserQuestion.multiSelectTag": "(multi-select)",
+ "askUserQuestion.skip": "Skip",
+ "askUserQuestion.submit": "Submit",
"claudeCode.askUserQuestion.customOption.placeholder": "Or write your own…",
"claudeCode.askUserQuestion.escape.back": "Back to options",
"claudeCode.askUserQuestion.escape.enter": "Or type directly",
diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.json
index a1396a08dde..aa818de2546 100644
--- a/locales/zh-CN/tool.json
+++ b/locales/zh-CN/tool.json
@@ -40,6 +40,13 @@
"agentMarketplace.render.alreadyInLibraryTag": "ε·²εœ¨εΊ“δΈ­",
"agentMarketplace.render.alreadyInLibrary_one": "{{count}} δΈͺε·²εœ¨εΊ“δΈ­",
"agentMarketplace.render.alreadyInLibrary_other": "{{count}} δΈͺε·²εœ¨εΊ“δΈ­",
+ "askUserQuestion.customOption.placeholder": "ζˆ–θ‡ͺε·±θΎ“ε…₯…",
+ "askUserQuestion.escape.back": "θΏ”ε›žι€‰ι‘Ή",
+ "askUserQuestion.escape.enter": "ζˆ–η›΄ζŽ₯θΎ“ε…₯",
+ "askUserQuestion.escape.placeholder": "εœ¨ζ­€θΎ“ε…₯δ½ ηš„ε›žε€β€¦",
+ "askUserQuestion.multiSelectTag": "οΌˆε€šι€‰οΌ‰",
+ "askUserQuestion.skip": "θ·³θΏ‡",
+ "askUserQuestion.submit": "提亀",
"claudeCode.askUserQuestion.customOption.placeholder": "ζˆ–θ‡ͺε·±θΎ“ε…₯…",
"claudeCode.askUserQuestion.escape.back": "θΏ”ε›žι€‰ι‘Ή",
"claudeCode.askUserQuestion.escape.enter": "ζˆ–η›΄ζŽ₯θΎ“ε…₯",
diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/draft.ts b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/draft.ts
deleted file mode 100644
index 07010282cf1..00000000000
--- a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/draft.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import type { AskUserQuestionItem } from '../../../types';
-
-/**
- * The one sentinel key, and it lives in the *submit payload* β€” never in the
- * draft. When the payload sent to CC is exactly `{ __freeform__: <text> }`,
- * the bridge formatter (`AskUserMcpServer.formatAnswerForCC`) forwards the
- * text verbatim β€” no `User answers:` framing β€” matching the escape hatch
- * `lobe-user-interaction` uses. The in-progress draft keeps this same text in
- * a named `escapeText` field instead, so no sentinel leaks into form state.
- */
-export const FREEFORM_PAYLOAD_KEY = '__freeform__';
-
-/**
- * Server-side bridge timeout β€” mirrors `DEFAULT_ASK_USER_TIMEOUT_MS` in
- * `@lobechat/heterogeneous-agents` `askUser/constants.ts` (the authoritative
- * clock). Kept as a local literal because this package has no dep on that one;
- * **keep the two in sync**. Not strictly synchronized at runtime β€” server is
- * authoritative β€” but keeps the on-screen countdown close to reality without
- * plumbing a deadline through every layer.
- */
-export const COUNTDOWN_MS = 10 * 60 * 1000;
-
-/** Key under tool message `pluginState` where the in-progress draft lives. */
-export const DRAFT_PLUGIN_STATE_KEY = 'askUserDraft';
-
-/**
- * In-progress form state, persisted on the tool message's
- * `pluginState.askUserDraft` so HMR reloads, store re-mounts, and tab switches
- * all keep partial answers around β€” only a fresh `tool_use` starts blank.
- *
- * Three independent answer slices, kept apart so picks and custom text can
- * coexist on one question (multi-select) and a half-typed escape reply never
- * bleeds into the form payload:
- * - `picks` β†’ multi-choice selections, keyed by question text
- * - `custom` β†’ per-question "write your own" text, keyed by question text
- * - `escape*` β†’ the global "Or type directly" box (whole-form bypass)
- *
- * Storing this as a typed object (rather than a flat string-keyed map) is what
- * lets us avoid sentinel key prefixes for the picks/custom split.
- */
-export type AskUserDraft = {
- custom: Record<string, string>;
- escapeActive: boolean;
- escapeText: string;
- picks: Record<string, string | string[]>;
-};
-
-/** Coerce a persisted (possibly partial / legacy) blob into a full draft. */
-export const readDraft = (raw: unknown): AskUserDraft => {
- const d = (raw ?? {}) as Partial<AskUserDraft>;
- return {
- custom: d.custom ?? {},
- escapeActive: !!d.escapeActive,
- escapeText: typeof d.escapeText === 'string' ? d.escapeText : '',
- picks: d.picks ?? {},
- };
-};
-
-/** A question counts as answered when it has a pick or non-empty custom text. */
-export const isQuestionAnswered = (
- q: AskUserQuestionItem,
- picks: Record<string, string | string[]>,
- custom: Record<string, string>,
-): boolean => {
- if (custom[q.question]?.trim()) return true;
- const a = picks[q.question];
- return q.multiSelect ? Array.isArray(a) && a.length > 0 : !!a;
-};
-
-/**
- * Merge picks + custom text into the structured payload CC receives: each
- * question maps to its picks, its custom text, or both (multi-select appends
- * custom as an extra entry). Shared by the Submit button and the timeout
- * fallback so the two never diverge.
- */
-export const buildSubmitPayload = (
- questions: AskUserQuestionItem[],
- picks: Record<string, string | string[]>,
- custom: Record<string, string>,
-): Record<string, string | string[]> => {
- const payload: Record<string, string | string[]> = {};
- for (const q of questions) {
- const text = custom[q.question]?.trim();
- if (q.multiSelect) {
- const chosen = Array.isArray(picks[q.question]) ? (picks[q.question] as string[]) : [];
- const merged = text ? [...chosen, text] : chosen;
- if (merged.length > 0) payload[q.question] = merged;
- } else if (text) {
- payload[q.question] = text;
- } else if (picks[q.question]) {
- payload[q.question] = picks[q.question];
- }
- }
- return payload;
-};
-
-export const formatRemaining = (msLeft: number): string => {
- const totalSec = Math.max(0, Math.floor(msLeft / 1000));
- const min = Math.floor(totalSec / 60);
- const sec = totalSec % 60;
- return `${min}:${sec.toString().padStart(2, '0')}`;
-};
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 e586b6546e7..bfb090d12a5 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
@@ -1,163 +1,78 @@
'use client';
+import {
+ type AskUserDraft,
+ type AskUserQuestionArgs,
+ AskUserQuestionView,
+ DEFAULT_COUNTDOWN_MS,
+ DRAFT_PLUGIN_STATE_KEY,
+ useAskUserForm,
+} from '@lobechat/shared-tool-ui/ask-user';
import type { BuiltinInterventionProps } from '@lobechat/types';
-import { Flexbox, Icon, Text, TextArea } from '@lobehub/ui';
-import { Button, Tabs } from '@lobehub/ui/base-ui';
-import { Check, PenLine, Send, X } from 'lucide-react';
-import { memo } from 'react';
-import { createPortal } from 'react-dom';
+import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import type { AskUserQuestionArgs } from '../../../types';
-import { formatRemaining, isQuestionAnswered } from './draft';
-import QuestionPanel from './QuestionPanel';
-import { useAskUserForm } from './useAskUserForm';
+import { useConversationStore } from '@/features/Conversation/store';
+import { dataSelectors } from '@/features/Conversation/store/slices/data/selectors';
+import { useChatStore } from '@/store/chat';
/**
* CC AskUserQuestion intervention component.
*
- * Pure form β€” `onInteractionAction` ({type:'submit'|'skip'}) is the only
- * outbound side effect. The framework's `handleInteractionAction` (or the
- * hetero branch the chat conversation wires up) marks
- * `pluginIntervention.status` and forwards the answer to CC over IPC.
+ * A thin host wrapper around the shared `useAskUserForm` + `AskUserQuestionView`
+ * (in `@lobechat/shared-tool-ui/ask-user`). This wrapper owns the two
+ * app-coupled bits the shared module intentionally does not:
+ * - draft persistence β€” read from / written to the tool message's
+ * `pluginState.askUserDraft` via the conversation + chat stores, so HMR,
+ * remounts, and tab switches resume where the user left off, and
+ * - i18n β€” the `labels` built from CC's `claudeCode.askUserQuestion.*` keys.
*
- * Answering a question
- * - Pick one of the numbered options, or
- * - Write your own in the trailing (numbered) input. Single-select treats the
- * two as mutually exclusive (typing clears the pick and vice-versa);
- * multi-select appends the custom text as an extra entry alongside the checked
- * options.
- *
- * Layout
- * - One question β†’ renders the question + options directly, no tab strip, and
- * no whole-form escape (the per-question custom box already is the full
- * custom answer).
- * - Multiple questions β†’ top tab bar (Q1, Q2, …) with a trailing "Or type
- * directly" tab as a visible peer: selecting it swaps all questions for one
- * freeform box that answers the whole form at once. Picking an answer
- * auto-advances to the next unanswered question.
- *
- * State, handlers, and draft persistence all live in `useAskUserForm`; this
- * component is just the view.
+ * Everything else (pick/custom/escape/auto-advance/submit, the countdown, the
+ * timeout fallback, and the `__freeform__` bridge) lives in the shared hook.
*/
const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestionArgs>>((props) => {
const { t } = useTranslation('tool');
- const { actionsPortalTarget } = props;
- const {
- activeQuestion,
- activeTab,
- custom,
- escapeActive,
- escapeText,
- expired,
- handleCustomChange,
- handleEscapeTextChange,
- handleSkip,
- handleSubmit,
- handleToggle,
- isMulti,
- isSubmitDisabled,
- picks,
- questions,
- remainingMs,
- setActiveTab,
- setEscapeMode,
- submitting,
- } = useAskUserForm(props);
+ const { actionsPortalTarget, args, messageId, onInteractionAction } = props;
- const footer = (
- <Flexbox horizontal align="center" gap={8} justify="space-between" width={'100%'}>
- <Text fontSize={12} type="secondary">
- {expired
- ? t('claudeCode.askUserQuestion.timeExpired')
- : t('claudeCode.askUserQuestion.timeRemaining', {
- time: formatRemaining(remainingMs),
- })}
- </Text>
- <Flexbox horizontal gap={8}>
- <Button disabled={submitting} icon={<Icon icon={X} />} onClick={handleSkip}>
- {t('claudeCode.askUserQuestion.skip')}
- </Button>
- <Button
- disabled={isSubmitDisabled}
- icon={<Icon icon={Send} />}
- loading={submitting}
- type="primary"
- onClick={handleSubmit}
- >
- {t('claudeCode.askUserQuestion.submit')}
- </Button>
- </Flexbox>
- </Flexbox>
+ // Persisted draft β€” read from the tool message's pluginState so the form
+ // stays where the user left it across unmount / HMR / refresh.
+ const persistedDraft = useConversationStore((s) => {
+ const msg = dataSelectors.getDbMessageById(messageId)(s);
+ return (msg?.pluginState as { [DRAFT_PLUGIN_STATE_KEY]?: unknown })?.[DRAFT_PLUGIN_STATE_KEY];
+ });
+ const setInterventionDraft = useChatStore((s) => s.setInterventionDraft);
+ const writeDraft = useCallback(
+ (draft: AskUserDraft) => setInterventionDraft(messageId, draft),
+ [messageId, setInterventionDraft],
);
- return (
- <Flexbox gap={12}>
- {isMulti && (
- <Tabs
- activeKey={escapeActive ? 'escape' : activeTab}
- variant="square"
- items={[
- ...questions.map((q, idx) => {
- const done = isQuestionAnswered(q, picks, custom);
- return {
- key: String(idx),
- label: (
- <Flexbox horizontal align="center" gap={6}>
- <Text>Q{idx + 1}</Text>
- {done && <Icon icon={Check} size={12} />}
- </Flexbox>
- ),
- };
- }),
- // The whole-form freeform sits as a visible peer to the questions β€”
- // it replaces *all* of them, so it reads as a sibling choice, not a
- // hidden mode toggle.
- {
- key: 'escape',
- label: (
- <Flexbox horizontal align="center" gap={6}>
- <Icon icon={PenLine} size={12} />
- <Text>{t('claudeCode.askUserQuestion.escape.enter')}</Text>
- </Flexbox>
- ),
- },
- ]}
- onChange={(key: string) => {
- if (key === 'escape') {
- setEscapeMode(true);
- } else {
- setEscapeMode(false);
- setActiveTab(key);
- }
- }}
- />
- )}
+ const form = useAskUserForm({
+ args,
+ countdownMs: DEFAULT_COUNTDOWN_MS,
+ onInteractionAction,
+ persistedDraft,
+ writeDraft,
+ });
- {escapeActive ? (
- <TextArea
- autoSize={{ maxRows: 8, minRows: 3 }}
- disabled={expired || submitting}
- placeholder={t('claudeCode.askUserQuestion.escape.placeholder')}
- value={escapeText}
- variant="filled"
- onChange={(e) => handleEscapeTextChange(e.target.value)}
- />
- ) : (
- activeQuestion && (
- <QuestionPanel
- answer={picks[activeQuestion.question]}
- customValue={custom[activeQuestion.question] ?? ''}
- disabled={expired || submitting}
- question={activeQuestion}
- onCustomChange={handleCustomChange}
- onToggle={handleToggle}
- />
- )
- )}
+ const labels = {
+ customPlaceholder: t('claudeCode.askUserQuestion.customOption.placeholder'),
+ escapeBack: t('claudeCode.askUserQuestion.escape.back'),
+ escapeEnter: t('claudeCode.askUserQuestion.escape.enter'),
+ escapePlaceholder: t('claudeCode.askUserQuestion.escape.placeholder'),
+ multiSelectTag: t('claudeCode.askUserQuestion.multiSelectTag'),
+ skip: t('claudeCode.askUserQuestion.skip'),
+ submit: t('claudeCode.askUserQuestion.submit'),
+ timeExpired: t('claudeCode.askUserQuestion.timeExpired'),
+ timeRemaining: (time: string) => t('claudeCode.askUserQuestion.timeRemaining', { time }),
+ };
- {actionsPortalTarget ? createPortal(footer, actionsPortalTarget) : footer}
- </Flexbox>
+ return (
+ <AskUserQuestionView
+ {...form}
+ showCountdown
+ actionsPortalTarget={actionsPortalTarget}
+ labels={labels}
+ />
);
});
diff --git a/packages/builtin-tool-claude-code/src/types.ts b/packages/builtin-tool-claude-code/src/types.ts
index b8b01345f2d..f7787b8b0f1 100644
--- a/packages/builtin-tool-claude-code/src/types.ts
+++ b/packages/builtin-tool-claude-code/src/types.ts
@@ -260,32 +260,15 @@ export interface SendMessageResult {
}
/**
- * One option on an AskUserQuestion question β€” `label` is what the user picks,
- * `description` is the supporting text shown alongside.
+ * AskUserQuestion data model now lives in `@lobechat/shared-tool-ui/ask-user`
+ * and is consumed identically by the builtin `user-interaction` / `lobe-agent`
+ * surfaces. Re-exported here so CC's existing import sites keep resolving.
*/
-export interface AskUserQuestionOption {
- description: string;
- label: string;
-}
-
-/**
- * One question in an `AskUserQuestion` invocation β€” header is short (≀12
- * chars per CC's contract), `options` is 2-4 entries, `multiSelect` is opt-in.
- */
-export interface AskUserQuestionItem {
- header: string;
- multiSelect?: boolean;
- options: AskUserQuestionOption[];
- question: string;
-}
-
-/**
- * `AskUserQuestion` tool arguments β€” mirrors CC's own schema verbatim so the
- * model's existing prompts work unchanged. 1-4 questions per call.
- */
-export interface AskUserQuestionArgs {
- questions: AskUserQuestionItem[];
-}
+export type {
+ AskUserQuestionArgs,
+ AskUserQuestionItem,
+ AskUserQuestionOption,
+} from '@lobechat/shared-tool-ui/ask-user';
/**
* Arguments for CC's built-in `WebSearch` tool. CC issues a web search via
diff --git a/packages/builtin-tool-lobe-agent/package.json b/packages/builtin-tool-lobe-agent/package.json
index 3ffec6829bf..91999f0c7da 100644
--- a/packages/builtin-tool-lobe-agent/package.json
+++ b/packages/builtin-tool-lobe-agent/package.json
@@ -14,6 +14,7 @@
"test:update": "vitest -u"
},
"dependencies": {
+ "@lobechat/builtin-tool-user-interaction": "workspace:*",
"@lobechat/const": "workspace:*",
"@lobechat/prompts": "workspace:*",
"@lobechat/utils": "workspace:*"
diff --git a/packages/builtin-tool-lobe-agent/src/client/Intervention/index.ts b/packages/builtin-tool-lobe-agent/src/client/Intervention/index.ts
index 4e23f93a60b..966f5912233 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Intervention/index.ts
+++ b/packages/builtin-tool-lobe-agent/src/client/Intervention/index.ts
@@ -1,3 +1,4 @@
+import { AskUserQuestionIntervention } from '@lobechat/builtin-tool-user-interaction/client';
import type { BuiltinIntervention } from '@lobechat/types';
import { LobeAgentApiName } from '../../types';
@@ -10,8 +11,13 @@ import CreatePlanIntervention from './CreatePlan';
*
* Intervention components allow users to review and modify tool parameters
* before the tool is executed.
+ *
+ * `askUserQuestion` reuses the standalone user-interaction card: it renders as
+ * an inline custom form (not the default approve/reject) β€” see
+ * `isCustomInteractionIdentifier` in customInteractionHandlers.
*/
export const LobeAgentInterventions: Record<string, BuiltinIntervention> = {
+ [LobeAgentApiName.askUserQuestion]: AskUserQuestionIntervention as BuiltinIntervention,
[LobeAgentApiName.clearTodos]: ClearTodosIntervention as BuiltinIntervention,
[LobeAgentApiName.createPlan]: CreatePlanIntervention as BuiltinIntervention,
[LobeAgentApiName.createTodos]: AddTodoIntervention as BuiltinIntervention,
diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts
index 311414f0745..85bdde50d19 100644
--- a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts
+++ b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts
@@ -1,3 +1,4 @@
+import { UserInteractionExecutionRuntime } from '@lobechat/builtin-tool-user-interaction/executionRuntime';
import type { BuiltinToolContext, BuiltinToolResult, ChatStreamPayload } from '@lobechat/types';
import { BaseExecutor, RequestTrigger } from '@lobechat/types';
@@ -7,6 +8,7 @@ import { useNotebookStore } from '@/store/notebook';
import { LobeAgentManifest } from '../../manifest';
import type {
AnalyzeVisualMediaParams,
+ AskUserQuestionArgs,
CallSubAgentParams,
ClearTodosParams,
CreatePlanParams,
@@ -152,6 +154,16 @@ class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {
private planRuntime = new PlanExecutionRuntime(clientPlanService);
+ // Reused from the standalone user-interaction tool β€” askUserQuestion is
+ // human-intervention 'always', so in normal flows the user's UI submit
+ // becomes the tool result and this runtime is only the fallback executor.
+ private interactionRuntime = new UserInteractionExecutionRuntime();
+
+ // ==================== Ask User Question ====================
+
+ askUserQuestion = (params: AskUserQuestionArgs): Promise<BuiltinToolResult> =>
+ this.interactionRuntime.askUserQuestion(params);
+
// ==================== Plan / Todo ====================
createPlan = (params: CreatePlanParams, ctx: BuiltinToolContext): Promise<BuiltinToolResult> =>
diff --git a/packages/builtin-tool-lobe-agent/src/manifest.ts b/packages/builtin-tool-lobe-agent/src/manifest.ts
index b9b44b51a0c..9e9116a9cfd 100644
--- a/packages/builtin-tool-lobe-agent/src/manifest.ts
+++ b/packages/builtin-tool-lobe-agent/src/manifest.ts
@@ -183,6 +183,47 @@ export const LobeAgentManifest: BuiltinToolManifest = {
},
},
+ // ==================== Ask User Question ====================
+ {
+ description: 'Ask the user one or more clarifying questions with multiple-choice options.',
+ humanIntervention: 'always',
+ name: LobeAgentApiName.askUserQuestion,
+ renderDisplayControl: 'collapsed',
+ parameters: {
+ properties: {
+ questions: {
+ items: {
+ properties: {
+ header: { type: 'string' },
+ multiSelect: { type: 'boolean' },
+ options: {
+ items: {
+ properties: {
+ description: { type: 'string' },
+ label: { type: 'string' },
+ },
+ required: ['label', 'description'],
+ type: 'object',
+ },
+ maxItems: 4,
+ minItems: 2,
+ type: 'array',
+ },
+ question: { type: 'string' },
+ },
+ required: ['header', 'question', 'options'],
+ type: 'object',
+ },
+ maxItems: 4,
+ minItems: 1,
+ type: 'array',
+ },
+ },
+ required: ['questions'],
+ type: 'object',
+ },
+ },
+
// ==================== Sub-Agent ====================
{
description:
diff --git a/packages/builtin-tool-lobe-agent/src/systemRole.ts b/packages/builtin-tool-lobe-agent/src/systemRole.ts
index fd7da60604c..b2cec4ca790 100644
--- a/packages/builtin-tool-lobe-agent/src/systemRole.ts
+++ b/packages/builtin-tool-lobe-agent/src/systemRole.ts
@@ -213,11 +213,24 @@ Use it only for refs/URLs you cannot inspect directly, or when the active model
</visual_analysis>
`;
-// Sections independent of sub-agent dispatch (visual fallback + plan/todo). Kept
-// as a base so contexts where callSubAgent is unavailable can drop the sub-agent
+const askUserQuestionSection = `
+<ask_user_question>
+\`askUserQuestion\` opens a UI-mediated question so the user can clarify their intent before you act.
+
+- Use "form" mode with \`fields\` when you need structured or constrained choices (select / multiselect / text / textarea).
+- Use "freeform" mode for a single open-ended response.
+- Reach for it only when the request is genuinely ambiguous and the clarification would materially change your answer β€” do NOT interrogate the user for details you can reasonably infer or that don't affect the outcome.
+- Ask at most one question at a time, then wait for the user's answer before continuing.
+- Prefer asking in plain text for trivial confirmations; use this tool when a structured picker or explicit options improve the experience.
+</ask_user_question>
+`;
+
+// Sections independent of sub-agent dispatch (visual fallback + ask-user + plan/todo).
+// Kept as a base so contexts where callSubAgent is unavailable can drop the sub-agent
// guidance without leaving dangling references to a tool the model can't call.
const baseSystemPrompt = `Use Lobe Agent capabilities only when the active model needs built-in assistance. Prefer the active model's native capabilities whenever they are sufficient. Follow each tool's description and schema, and use tool results to answer the user directly.
${visualAnalysisSection}
+${askUserQuestionSection}
${planTodoSection}`;
/** Full prompt, including sub-agent dispatch (callSubAgent) guidance. */
diff --git a/packages/builtin-tool-lobe-agent/src/types.ts b/packages/builtin-tool-lobe-agent/src/types.ts
index 49046c611cb..ea54f26ba94 100644
--- a/packages/builtin-tool-lobe-agent/src/types.ts
+++ b/packages/builtin-tool-lobe-agent/src/types.ts
@@ -2,6 +2,7 @@ export const LobeAgentIdentifier = 'lobe-agent';
export const LobeAgentApiName = {
analyzeVisualMedia: 'analyzeVisualMedia',
+ askUserQuestion: 'askUserQuestion',
callSubAgent: 'callSubAgent',
clearTodos: 'clearTodos',
createPlan: 'createPlan',
@@ -12,6 +13,18 @@ export const LobeAgentApiName = {
export type LobeAgentApiNameType = (typeof LobeAgentApiName)[keyof typeof LobeAgentApiName];
+// ==================== Ask User Question ====================
+//
+// The ask-user-to-clarify capability is reused from the standalone
+// `builtin-tool-user-interaction` package (which still ships independently for
+// now). Re-exported here so lobe-agent consumers get the argument types from a
+// single import surface while both tools coexist.
+export type {
+ AskUserQuestionArgs,
+ AskUserQuestionItem,
+ AskUserQuestionOption,
+} from '@lobechat/builtin-tool-user-interaction';
+
export interface AnalyzeVisualMediaParams {
question: string;
refs?: string[];
diff --git a/packages/builtin-tool-user-interaction/package.json b/packages/builtin-tool-user-interaction/package.json
index 96b51c0b5ca..21ac43bd678 100644
--- a/packages/builtin-tool-user-interaction/package.json
+++ b/packages/builtin-tool-user-interaction/package.json
@@ -9,6 +9,9 @@
"./executionRuntime": "./src/ExecutionRuntime/index.ts"
},
"main": "./src/index.ts",
+ "dependencies": {
+ "@lobechat/shared-tool-ui": "workspace:*"
+ },
"devDependencies": {
"@lobechat/types": "workspace:*"
},
diff --git a/packages/builtin-tool-user-interaction/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-user-interaction/src/ExecutionRuntime/index.test.ts
index 3dd7ff0c0e6..9fa863b480a 100644
--- a/packages/builtin-tool-user-interaction/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-user-interaction/src/ExecutionRuntime/index.test.ts
@@ -2,92 +2,98 @@ import { describe, expect, it } from 'vitest';
import { UserInteractionExecutionRuntime } from './index';
+const sampleArgs = {
+ questions: [
+ {
+ header: 'Scope',
+ options: [
+ { description: 'Only the current file', label: 'This file' },
+ { description: 'The entire project', label: 'Whole project' },
+ ],
+ question: 'Which scope should I apply the change to?',
+ },
+ ],
+};
+
describe('UserInteractionExecutionRuntime', () => {
- it('creates a pending interaction request', async () => {
+ it('creates a pending interaction request storing the questions', async () => {
const runtime = new UserInteractionExecutionRuntime();
- const result = await runtime.askUserQuestion({
- question: { id: 'q1', mode: 'freeform', prompt: 'What is your name?' },
- });
+ const result = await runtime.askUserQuestion(sampleArgs);
expect(result.success).toBe(true);
- expect(result.state).toMatchObject({
- requestId: 'q1',
- status: 'pending',
- question: { id: 'q1', mode: 'freeform', prompt: 'What is your name?' },
+ expect(result.state.status).toBe('pending');
+ expect(typeof result.state.requestId).toBe('string');
+ expect(result.state.question).toEqual(sampleArgs);
+ });
+
+ it('rejects invalid args (fewer than 2 options)', async () => {
+ const runtime = new UserInteractionExecutionRuntime();
+ const result = await runtime.askUserQuestion({
+ questions: [
+ {
+ header: 'Scope',
+ options: [{ description: 'Only the current file', label: 'This file' }],
+ question: 'Which scope?',
+ },
+ ],
});
+
+ expect(result.success).toBe(false);
});
it('marks interaction as submitted with response', async () => {
const runtime = new UserInteractionExecutionRuntime();
- await runtime.askUserQuestion({
- question: {
- fields: [{ key: 'name', kind: 'text' as const, label: 'Name', required: true }],
- id: 'q2',
- mode: 'form' as const,
- prompt: 'Fill this form',
- },
- });
+ const created = await runtime.askUserQuestion(sampleArgs);
+ const { requestId } = created.state;
const result = await runtime.submitUserResponse({
- requestId: 'q2',
- response: { name: 'Alice' },
+ requestId,
+ response: { [sampleArgs.questions[0].question]: 'This file' },
});
expect(result.success).toBe(true);
expect(result.state).toMatchObject({
- requestId: 'q2',
+ requestId,
+ response: { [sampleArgs.questions[0].question]: 'This file' },
status: 'submitted',
- response: { name: 'Alice' },
});
});
it('marks interaction as skipped with reason', async () => {
const runtime = new UserInteractionExecutionRuntime();
- await runtime.askUserQuestion({
- question: { id: 'q3', mode: 'freeform', prompt: 'Optional question' },
- });
+ const created = await runtime.askUserQuestion(sampleArgs);
+ const { requestId } = created.state;
- const result = await runtime.skipUserResponse({
- requestId: 'q3',
- reason: 'Not relevant',
- });
+ const result = await runtime.skipUserResponse({ reason: 'Not relevant', requestId });
expect(result.success).toBe(true);
expect(result.state).toMatchObject({
- requestId: 'q3',
- status: 'skipped',
+ requestId,
skipReason: 'Not relevant',
+ status: 'skipped',
});
});
it('marks interaction as cancelled', async () => {
const runtime = new UserInteractionExecutionRuntime();
- await runtime.askUserQuestion({
- question: { id: 'q4', mode: 'freeform', prompt: 'Will be cancelled' },
- });
+ const created = await runtime.askUserQuestion(sampleArgs);
+ const { requestId } = created.state;
- const result = await runtime.cancelUserResponse({ requestId: 'q4' });
+ const result = await runtime.cancelUserResponse({ requestId });
expect(result.success).toBe(true);
- expect(result.state).toMatchObject({
- requestId: 'q4',
- status: 'cancelled',
- });
+ expect(result.state).toMatchObject({ requestId, status: 'cancelled' });
});
it('gets current interaction state', async () => {
const runtime = new UserInteractionExecutionRuntime();
- await runtime.askUserQuestion({
- question: { id: 'q5', mode: 'freeform', prompt: 'Check state' },
- });
+ const created = await runtime.askUserQuestion(sampleArgs);
+ const { requestId } = created.state;
- const result = await runtime.getInteractionState({ requestId: 'q5' });
+ const result = await runtime.getInteractionState({ requestId });
expect(result.success).toBe(true);
- expect(result.state).toMatchObject({
- requestId: 'q5',
- status: 'pending',
- });
+ expect(result.state).toMatchObject({ requestId, status: 'pending' });
});
it('returns error for non-existent interaction', async () => {
@@ -99,15 +105,11 @@ describe('UserInteractionExecutionRuntime', () => {
it('prevents submitting a non-pending interaction', async () => {
const runtime = new UserInteractionExecutionRuntime();
- await runtime.askUserQuestion({
- question: { id: 'q6', mode: 'freeform', prompt: 'Already done' },
- });
- await runtime.cancelUserResponse({ requestId: 'q6' });
+ const created = await runtime.askUserQuestion(sampleArgs);
+ const { requestId } = created.state;
+ await runtime.cancelUserResponse({ requestId });
- const result = await runtime.submitUserResponse({
- requestId: 'q6',
- response: { late: true },
- });
+ const result = await runtime.submitUserResponse({ requestId, response: { late: true } });
expect(result.success).toBe(false);
});
diff --git a/packages/builtin-tool-user-interaction/src/ExecutionRuntime/index.ts b/packages/builtin-tool-user-interaction/src/ExecutionRuntime/index.ts
index 19ffa1ca3b0..b79ce8afe95 100644
--- a/packages/builtin-tool-user-interaction/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-user-interaction/src/ExecutionRuntime/index.ts
@@ -9,40 +9,26 @@ import type {
SubmitUserResponseArgs,
} from '../types';
-const interactionFieldOptionSchema = z.object({
+const optionSchema = z.object({
+ description: z.string(),
label: z.string(),
- value: z.string(),
});
-const interactionFieldSchema = z.object({
- key: z.string(),
- kind: z.enum(['multiselect', 'select', 'text', 'textarea']),
- label: z.string(),
- options: z.array(interactionFieldOptionSchema).optional(),
- placeholder: z.string().optional(),
- required: z.boolean().optional(),
- value: z.union([z.string(), z.array(z.string())]).optional(),
+const questionSchema = z.object({
+ header: z.string(),
+ multiSelect: z.boolean().optional(),
+ options: z.array(optionSchema).min(2).max(4),
+ question: z.string(),
});
-const questionSchema = z
- .object({
- description: z.string().optional(),
- fields: z.array(interactionFieldSchema).optional(),
- id: z.string(),
- metadata: z.record(z.unknown()).optional(),
- mode: z.enum(['form', 'freeform']),
- prompt: z.string(),
- })
- .strict()
- .refine((q) => q.mode !== 'form' || (q.fields && q.fields.length > 0), {
- message:
- 'Mode "form" requires a non-empty "fields" array. Use "freeform" mode for open-ended input, or provide "fields" for structured form input.',
- });
-
const askUserQuestionArgsSchema = z.object({
- question: questionSchema,
+ questions: z.array(questionSchema).min(1).max(4),
});
+/** Opaque, process-local id for a pending interaction request. */
+const generateRequestId = (): string =>
+ `ask_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
+
export class UserInteractionExecutionRuntime {
private interactions: Map<string, InteractionState> = new Map();
@@ -56,11 +42,10 @@ export class UserInteractionExecutionRuntime {
};
}
- const { question } = parsed.data;
- const requestId = question.id;
+ const requestId = generateRequestId();
const state: InteractionState = {
- question,
+ question: parsed.data,
requestId,
status: 'pending',
};
@@ -68,7 +53,7 @@ export class UserInteractionExecutionRuntime {
this.interactions.set(requestId, state);
return {
- content: `Question "${question.prompt}" is now pending user response.`,
+ content: 'Question(s) presented to the user; awaiting response.',
state,
success: true,
};
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 5dc4f840d7c..e09dada8c8a 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
@@ -1,236 +1,97 @@
'use client';
+import {
+ type AskUserDraft,
+ type AskUserQuestionArgs,
+ AskUserQuestionView,
+ DRAFT_PLUGIN_STATE_KEY,
+ useAskUserForm,
+} from '@lobechat/shared-tool-ui/ask-user';
import type { BuiltinInterventionProps } from '@lobechat/types';
-import { SendButton } from '@lobehub/editor/react';
-import { Flexbox, Icon, Input, Text, TextArea } from '@lobehub/ui';
-import { Select } from '@lobehub/ui/base-ui';
-import { ArrowLeft, PenLine } from 'lucide-react';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { Flexbox, Text } from '@lobehub/ui';
+import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import type { AskUserQuestionArgs, InteractionField } from '../../../types';
-import { styles } from './style';
-
-const FieldInput = memo<{
- field: InteractionField;
- onChange: (key: string, value: string | string[]) => void;
- onPressEnter?: () => void;
- value?: string | string[];
-}>(({ field, value, onChange, onPressEnter }) => {
- switch (field.kind) {
- case 'textarea': {
- return (
- <TextArea
- autoSize={{ maxRows: 6, minRows: 2 }}
- placeholder={field.placeholder}
- value={value as string}
- variant={'filled'}
- onChange={(e) => onChange(field.key, e.target.value)}
- />
- );
- }
- case 'select': {
- return (
- <Select
- options={field.options?.map((o) => ({ label: o.label, value: o.value }))}
- placeholder={field.placeholder}
- style={{ width: '100%' }}
- value={value as string}
- variant={'filled'}
- onChange={(v) => onChange(field.key, v as string)}
- />
- );
- }
- case 'multiselect': {
- return (
- <Select
- mode="multiple"
- options={field.options?.map((o) => ({ label: o.label, value: o.value }))}
- placeholder={field.placeholder}
- style={{ width: '100%' }}
- value={value as string[]}
- variant={'filled'}
- onChange={(v) => onChange(field.key, v as string[])}
- />
- );
- }
- default: {
- return (
- <Input
- placeholder={field.placeholder}
- value={value as string}
- variant={'filled'}
- onChange={(e) => onChange(field.key, e.target.value)}
- onPressEnter={onPressEnter}
- />
- );
- }
- }
-});
-
-const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestionArgs>>(
- ({ args, interactionMode, onInteractionAction }) => {
- const { t } = useTranslation('ui');
- const { question } = args;
- const isCustom = interactionMode === 'custom';
-
- const initialValues: Record<string, string | string[]> = {};
- if (question.fields) {
- for (const field of question.fields) {
- if (field.value !== undefined) initialValues[field.key] = field.value;
- }
- }
-
- const [formData, setFormData] = useState<Record<string, string | string[]>>(initialValues);
- const [submitting, setSubmitting] = useState(false);
- const [escapeActive, setEscapeActive] = useState(false);
- const [escapeText, setEscapeText] = useState('');
- const escapeContainerRef = useRef<HTMLDivElement>(null);
- const formContainerRef = useRef<HTMLDivElement>(null);
-
- const handleFieldChange = useCallback((key: string, value: string | string[]) => {
- setFormData((prev) => ({ ...prev, [key]: value }));
- }, []);
-
- const handleSubmit = useCallback(async () => {
- if (!onInteractionAction) return;
- setSubmitting(true);
- try {
- if (escapeActive) {
- await onInteractionAction({ payload: { __freeform__: escapeText }, type: 'submit' });
- } else {
- await onInteractionAction({ payload: formData, type: 'submit' });
- }
- } catch (error) {
- console.error(error);
- } finally {
- setSubmitting(false);
- }
- }, [escapeActive, escapeText, formData, onInteractionAction]);
-
- const handleSkip = useCallback(async () => {
- if (!onInteractionAction) return;
- await onInteractionAction({ type: 'skip' });
- }, [onInteractionAction]);
-
- const handleEscapeToggle = useCallback(() => {
- setEscapeActive((prev) => !prev);
- }, []);
-
- useEffect(() => {
- const timer = setTimeout(() => {
- if (escapeActive) {
- const textarea =
- escapeContainerRef.current?.querySelector<HTMLTextAreaElement>('textarea');
- textarea?.focus();
- } else {
- const firstInput =
- formContainerRef.current?.querySelector<HTMLElement>('input, textarea');
- firstInput?.focus();
- }
- }, 0);
- return () => clearTimeout(timer);
- }, [escapeActive]);
-
- const isFreeform = !question.fields || question.fields.length === 0;
- const shouldShowEscapeAction = !isFreeform;
-
- const isSubmitDisabled = escapeActive
- ? !escapeText.trim()
- : isFreeform
- ? !formData['__freeform__']
- : (question.fields?.some((f) => f.required && !formData[f.key]) ?? false);
-
- if (!isCustom) {
- return (
- <Flexbox gap={8}>
- <Text>{question.prompt}</Text>
- {question.fields && question.fields.length > 0 && (
- <ul style={{ margin: 0, paddingLeft: 20 }}>
- {question.fields.map((field) => (
- <li key={field.key}>
- {field.label}
- {field.required && ' *'}
- </li>
- ))}
- </ul>
- )}
- </Flexbox>
- );
- }
-
+import { useConversationStore } from '@/features/Conversation/store';
+import { dataSelectors } from '@/features/Conversation/store/slices/data/selectors';
+import { useChatStore } from '@/store/chat';
+
+/**
+ * Builtin `askUserQuestion` intervention β€” the same multi-question form the
+ * Claude Code surface uses, wired to the shared `useAskUserForm` +
+ * `AskUserQuestionView` (`@lobechat/shared-tool-ui/ask-user`).
+ *
+ * Unlike Claude Code there is no bridge timeout here, so `countdownMs` is
+ * omitted (no countdown, no timeout fallback). This wrapper owns the two
+ * app-coupled bits: draft persistence (via the conversation + chat stores) and
+ * i18n (generic `askUserQuestion.*` keys).
+ *
+ * When the card is shown read-only (`interactionMode !== 'custom'`, e.g. a
+ * resolved / historical message), it renders a compact summary of the questions
+ * instead of the interactive form.
+ */
+const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestionArgs>>((props) => {
+ const { t } = useTranslation('tool');
+ const { actionsPortalTarget, args, interactionMode, messageId, onInteractionAction } = props;
+
+ const persistedDraft = useConversationStore((s) => {
+ const msg = dataSelectors.getDbMessageById(messageId)(s);
+ return (msg?.pluginState as { [DRAFT_PLUGIN_STATE_KEY]?: unknown })?.[DRAFT_PLUGIN_STATE_KEY];
+ });
+ const setInterventionDraft = useChatStore((s) => s.setInterventionDraft);
+ const writeDraft = useCallback(
+ (draft: AskUserDraft) => setInterventionDraft(messageId, draft),
+ [messageId, setInterventionDraft],
+ );
+
+ const form = useAskUserForm({
+ args,
+ onInteractionAction,
+ persistedDraft,
+ writeDraft,
+ });
+
+ // Read-only surfaces (resolved / historical messages) show a compact summary
+ // of what was asked instead of the interactive form.
+ if (interactionMode !== 'custom') {
+ const questions = args?.questions ?? [];
return (
- <Flexbox gap={12}>
- <Text style={{ fontWeight: 500 }}>{question.prompt}</Text>
- {question.description && (
- <Text style={{ fontSize: 13 }} type="secondary">
- {question.description}
- </Text>
- )}
- {isFreeform ? (
- <TextArea
- autoSize={{ maxRows: 6, minRows: 3 }}
- placeholder={question.description || ''}
- value={formData['__freeform__'] as string}
- variant={'filled'}
- onChange={(e) => handleFieldChange('__freeform__', e.target.value)}
- />
- ) : (
- <>
- {!escapeActive ? (
- <Flexbox gap={16} ref={formContainerRef}>
- {question.fields!.map((field) => (
- <Flexbox gap={6} key={field.key}>
- <Text style={{ fontSize: 13 }}>
- {field.label}
- {field.required && <span style={{ color: 'red' }}> *</span>}
- </Text>
- <FieldInput
- field={field}
- value={formData[field.key]}
- onChange={handleFieldChange}
- onPressEnter={() => {
- if (!isSubmitDisabled) handleSubmit();
- }}
- />
- </Flexbox>
- ))}
- </Flexbox>
- ) : (
- <TextArea
- autoSize={{ maxRows: 6, minRows: 3 }}
- value={escapeText}
- variant={'filled'}
- onChange={(e) => setEscapeText(e.target.value)}
- />
- )}
- </>
- )}
- <Flexbox horizontal gap={8} justify={'space-between'}>
- <Flexbox horizontal gap={8} justify="flex-start">
- {escapeActive && shouldShowEscapeAction ? (
- <Text className={styles.escapeLink} type="secondary" onClick={handleEscapeToggle}>
- <Icon icon={ArrowLeft} /> {t('form.otherBack')}
+ <Flexbox gap={8}>
+ {questions.map((q, idx) => (
+ <Flexbox gap={2} key={`${q.question}-${idx}`}>
+ {q.header && (
+ <Text fontSize={12} type="secondary">
+ {q.header}
</Text>
- ) : (
- <>
- <Text className={styles.escapeLink} type="secondary" onClick={handleSkip}>
- {t('form.skip')}
- </Text>
- {shouldShowEscapeAction && (
- <Text className={styles.escapeLink} type="secondary" onClick={handleEscapeToggle}>
- {t('form.other')} <Icon icon={PenLine} />
- </Text>
- )}
- </>
)}
+ <Text>{q.question}</Text>
</Flexbox>
- <SendButton disabled={isSubmitDisabled} loading={submitting} onClick={handleSubmit} />
- </Flexbox>
+ ))}
</Flexbox>
);
- },
-);
+ }
+
+ const labels = {
+ customPlaceholder: t('askUserQuestion.customOption.placeholder'),
+ escapeBack: t('askUserQuestion.escape.back'),
+ escapeEnter: t('askUserQuestion.escape.enter'),
+ escapePlaceholder: t('askUserQuestion.escape.placeholder'),
+ multiSelectTag: t('askUserQuestion.multiSelectTag'),
+ skip: t('askUserQuestion.skip'),
+ submit: t('askUserQuestion.submit'),
+ timeExpired: '',
+ timeRemaining: () => '',
+ };
+
+ return (
+ <AskUserQuestionView
+ {...form}
+ actionsPortalTarget={actionsPortalTarget}
+ labels={labels}
+ showCountdown={false}
+ />
+ );
+});
AskUserQuestionIntervention.displayName = 'AskUserQuestionIntervention';
diff --git a/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/style.ts b/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/style.ts
deleted file mode 100644
index cfc9c5ee4f8..00000000000
--- a/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/style.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { createStaticStyles } from 'antd-style';
-
-export const styles = createStaticStyles(({ css, cssVar }) => ({
- escapeLink: css`
- cursor: pointer;
-
- display: inline-flex;
- gap: 4px;
- align-items: center;
-
- padding-block: 4px;
- padding-inline: 0;
-
- font-size: 13px;
-
- transition: color ${cssVar.motionDurationMid};
-
- &:hover {
- color: ${cssVar.colorPrimary} !important;
- }
- `,
-}));
diff --git a/packages/builtin-tool-user-interaction/src/client/index.ts b/packages/builtin-tool-user-interaction/src/client/index.ts
index 79dc312cafe..282cfc3ea20 100644
--- a/packages/builtin-tool-user-interaction/src/client/index.ts
+++ b/packages/builtin-tool-user-interaction/src/client/index.ts
@@ -1,3 +1,4 @@
export { UserInteractionManifest } from '../manifest';
export * from '../types';
export { UserInteractionInterventions } from './Intervention';
+export { default as AskUserQuestionIntervention } from './Intervention/AskUserQuestion';
diff --git a/packages/builtin-tool-user-interaction/src/index.ts b/packages/builtin-tool-user-interaction/src/index.ts
index 807b12a89f5..0d29756e518 100644
--- a/packages/builtin-tool-user-interaction/src/index.ts
+++ b/packages/builtin-tool-user-interaction/src/index.ts
@@ -2,12 +2,12 @@ export * from './ExecutionRuntime';
export { UserInteractionManifest } from './manifest';
export { systemPrompt } from './systemRole';
export {
+ type AskUserDraft,
type AskUserQuestionArgs,
+ type AskUserQuestionItem,
+ type AskUserQuestionOption,
type CancelUserResponseArgs,
type GetInteractionStateArgs,
- type InteractionField,
- type InteractionFieldOption,
- type InteractionMode,
type InteractionState,
type InteractionStatus,
type SkipUserResponseArgs,
diff --git a/packages/builtin-tool-user-interaction/src/manifest.ts b/packages/builtin-tool-user-interaction/src/manifest.ts
index 1d64841026c..b5bd1533afc 100644
--- a/packages/builtin-tool-user-interaction/src/manifest.ts
+++ b/packages/builtin-tool-user-interaction/src/manifest.ts
@@ -6,63 +6,41 @@ import { UserInteractionApiName, UserInteractionIdentifier } from './types';
export const UserInteractionManifest: BuiltinToolManifest = {
api: [
{
- description:
- 'Create a UI-mediated interaction request with either structured form fields or freeform input. Returns the request in pending state.',
+ description: 'Ask the user one or more clarifying questions with multiple-choice options.',
humanIntervention: 'always',
name: UserInteractionApiName.askUserQuestion,
renderDisplayControl: 'collapsed',
parameters: {
properties: {
- question: {
- properties: {
- description: { type: 'string' },
- fields: {
- items: {
- properties: {
- key: { type: 'string' },
- kind: {
- enum: ['multiselect', 'select', 'text', 'textarea'],
- type: 'string',
- },
- label: { type: 'string' },
- options: {
- items: {
- properties: {
- label: { type: 'string' },
- value: { type: 'string' },
- },
- required: ['label', 'value'],
- type: 'object',
- },
- type: 'array',
- },
- placeholder: { type: 'string' },
- required: { type: 'boolean' },
- value: {
- oneOf: [{ type: 'string' }, { items: { type: 'string' }, type: 'array' }],
+ questions: {
+ items: {
+ properties: {
+ header: { type: 'string' },
+ multiSelect: { type: 'boolean' },
+ options: {
+ items: {
+ properties: {
+ description: { type: 'string' },
+ label: { type: 'string' },
},
+ required: ['label', 'description'],
+ type: 'object',
},
- required: ['key', 'kind', 'label'],
- type: 'object',
+ maxItems: 4,
+ minItems: 2,
+ type: 'array',
},
- type: 'array',
+ question: { type: 'string' },
},
- id: { type: 'string' },
- metadata: {
- additionalProperties: true,
- type: 'object',
- },
- mode: {
- enum: ['form', 'freeform'],
- type: 'string',
- },
- prompt: { type: 'string' },
+ required: ['header', 'question', 'options'],
+ type: 'object',
},
- required: ['id', 'mode', 'prompt'],
- type: 'object',
+ maxItems: 4,
+ minItems: 1,
+ type: 'array',
},
},
- required: ['question'],
+ required: ['questions'],
type: 'object',
},
},
diff --git a/packages/builtin-tool-user-interaction/src/systemRole.ts b/packages/builtin-tool-user-interaction/src/systemRole.ts
index 143840d6623..39033a2b801 100644
--- a/packages/builtin-tool-user-interaction/src/systemRole.ts
+++ b/packages/builtin-tool-user-interaction/src/systemRole.ts
@@ -1,19 +1,23 @@
-export const systemPrompt = `You have access to a User Interaction tool for collecting user input through UI-mediated interactions.
+export const systemPrompt = `You have access to a User Interaction tool for asking the user clarifying questions through a UI-mediated multiple-choice form.
<primary_usage>
Regular model usage:
-1. Use askUserQuestion to request input from the user.
-2. Use "form" mode when you need structured fields, constrained options, or explicit choices.
-3. Use "freeform" mode for a single open-ended response.
-4. Keep at most one unresolved interaction request at a time.
-5. After calling askUserQuestion, wait for the user's next action before asking another question.
+1. Use askUserQuestion to ask the user one or more clarifying questions.
+2. Provide 1-4 questions. Each question has:
+ - "header": a short label for the question.
+ - "question": the full question text.
+ - "options": 2-4 choices, each with a "label" and a "description".
+ - "multiSelect" (optional): set true when the user may pick more than one option.
+3. Keep at most one unresolved askUserQuestion request at a time.
+4. After calling askUserQuestion, wait for the user's next action before asking again.
+5. Ask only on genuine ambiguity β€” when a short clarification would materially change your answer. Do not ask when you can reasonably proceed.
</primary_usage>
<framework_lifecycle>
Framework-managed lifecycle:
-1. askUserQuestion creates a pending interaction request that the UI presents to the user.
+1. askUserQuestion creates a pending request that the UI presents to the user.
2. submitUserResponse, skipUserResponse, and cancelUserResponse represent lifecycle outcomes of that request.
-3. In normal product flows, those lifecycle APIs are usually handled by the client or framework after the user acts in the UI.
+3. In normal product flows, those lifecycle APIs are handled by the client or framework after the user acts in the UI.
4. Do not proactively call submitUserResponse, skipUserResponse, or cancelUserResponse during ordinary conversation unless a higher-level instruction explicitly asks you to test, recover, or inspect the interaction flow.
</framework_lifecycle>
@@ -25,9 +29,8 @@ Recovery and inspection:
</recovery_usage>
<best_practices>
-- Provide a clear and concise prompt.
-- Include only the fields that are necessary.
-- Prefer this tool when structured collection, explicit choices, or UI-mediated input would improve the experience.
+- Keep questions and options concise; make each option meaningfully distinct.
+- Ask the minimum number of questions needed to disambiguate.
- Whether to ask in plain text or through this tool is determined by the host agent's instructions.
</best_practices>
`;
diff --git a/packages/builtin-tool-user-interaction/src/types.ts b/packages/builtin-tool-user-interaction/src/types.ts
index 49e8d6594e4..1f706f46307 100644
--- a/packages/builtin-tool-user-interaction/src/types.ts
+++ b/packages/builtin-tool-user-interaction/src/types.ts
@@ -1,3 +1,5 @@
+import type { AskUserQuestionArgs } from '@lobechat/shared-tool-ui/ask-user';
+
export const UserInteractionIdentifier = 'lobe-user-interaction';
export const UserInteractionApiName = {
@@ -8,35 +10,19 @@ export const UserInteractionApiName = {
submitUserResponse: 'submitUserResponse',
} as const;
-export type InteractionMode = 'form' | 'freeform';
-
export type InteractionStatus = 'cancelled' | 'pending' | 'skipped' | 'submitted';
-export interface InteractionFieldOption {
- label: string;
- value: string;
-}
-
-export interface InteractionField {
- key: string;
- kind: 'multiselect' | 'select' | 'text' | 'textarea';
- label: string;
- options?: InteractionFieldOption[];
- placeholder?: string;
- required?: boolean;
- value?: string | string[];
-}
-
-export interface AskUserQuestionArgs {
- question: {
- description?: string;
- fields?: InteractionField[];
- id: string;
- metadata?: Record<string, unknown>;
- mode: InteractionMode;
- prompt: string;
- };
-}
+/**
+ * The AskUserQuestion data model is shared with Claude Code and lobe-agent β€” it
+ * lives in `@lobechat/shared-tool-ui/ask-user`. Re-exported here so consumers
+ * get the argument types from this package's single import surface.
+ */
+export type {
+ AskUserDraft,
+ AskUserQuestionArgs,
+ AskUserQuestionItem,
+ AskUserQuestionOption,
+} from '@lobechat/shared-tool-ui/ask-user';
export interface SubmitUserResponseArgs {
requestId: string;
@@ -57,7 +43,8 @@ export interface GetInteractionStateArgs {
}
export interface InteractionState {
- question?: AskUserQuestionArgs['question'];
+ /** The whole `{ questions }` payload presented to the user. */
+ question?: AskUserQuestionArgs;
requestId: string;
response?: Record<string, unknown>;
skipReason?: string;
diff --git a/packages/business/const/src/index.ts b/packages/business/const/src/index.ts
index e486ba2aa95..741a8fd5f06 100644
--- a/packages/business/const/src/index.ts
+++ b/packages/business/const/src/index.ts
@@ -4,11 +4,17 @@ export * from './branding';
export * from './llm';
export * from './url';
-const isDev = process.env.NODE_ENV === 'development';
-
export const ENABLE_BUSINESS_FEATURES = false;
-export const AGENT_ONBOARDING_ENABLED = isDev;
+/**
+ * Master switch for the conversational agent-onboarding flow.
+ *
+ * Soft-disabled: kept in the codebase but permanently off, so onboarding always
+ * falls back to the classic form flow (`deriveOnboardingBranchPath`) and the
+ * agent-mode switch stays hidden (`ModeSwitch`). Flip back to `isDev` (or a real
+ * flag) to revive it.
+ */
+export const AGENT_ONBOARDING_ENABLED = false;
export const OFFICIAL_PROVIDER_DISABLE_ERROR = 'The official provider cannot be disabled.';
diff --git a/packages/heterogeneous-agents/src/askUser/constants.ts b/packages/heterogeneous-agents/src/askUser/constants.ts
index 4d08afbd27d..a54f430b274 100644
--- a/packages/heterogeneous-agents/src/askUser/constants.ts
+++ b/packages/heterogeneous-agents/src/askUser/constants.ts
@@ -23,8 +23,8 @@ export const ASK_USER_API_NAME = 'askUserQuestion';
/**
* How long the server holds a pending ask-user question before it times out
* into a `cancelled` answer. This is the **authoritative** clock β€” the client
- * countdown (`builtin-tool-claude-code` `draft.ts` `COUNTDOWN_MS`) mirrors this
- * value and must be kept in sync (that package has no dep on this one, so it
- * can't import the const directly).
+ * countdown (`@lobechat/shared-tool-ui/ask-user` `draft.ts`
+ * `DEFAULT_COUNTDOWN_MS`) mirrors this value and must be kept in sync (that
+ * package has no dep on this one, so it can't import the const directly).
*/
export const DEFAULT_ASK_USER_TIMEOUT_MS = 10 * 60 * 1000;
diff --git a/packages/locales/src/default/tool.ts b/packages/locales/src/default/tool.ts
index ab54372cc5a..ca1fe136e57 100644
--- a/packages/locales/src/default/tool.ts
+++ b/packages/locales/src/default/tool.ts
@@ -42,6 +42,13 @@ export default {
'agentMarketplace.render.alreadyInLibrary_other': '{{count}} already in library',
'agentMarketplace.picker.failedToLoad': 'Failed to load templates. Please try again later.',
'agentMarketplace.picker.summary': '{{filtered}} / {{total}} templates available.',
+ 'askUserQuestion.customOption.placeholder': 'Or write your own…',
+ 'askUserQuestion.escape.back': 'Back to options',
+ 'askUserQuestion.escape.enter': 'Or type directly',
+ 'askUserQuestion.escape.placeholder': 'Type your answer here…',
+ 'askUserQuestion.multiSelectTag': '(multi-select)',
+ 'askUserQuestion.skip': 'Skip',
+ 'askUserQuestion.submit': 'Submit',
'claudeCode.askUserQuestion.customOption.placeholder': 'Or write your own…',
'claudeCode.askUserQuestion.escape.back': 'Back to options',
'claudeCode.askUserQuestion.escape.enter': 'Or type directly',
diff --git a/packages/shared-tool-ui/package.json b/packages/shared-tool-ui/package.json
index aec1cb01798..e174d449f31 100644
--- a/packages/shared-tool-ui/package.json
+++ b/packages/shared-tool-ui/package.json
@@ -4,6 +4,7 @@
"private": true,
"exports": {
".": "./src/index.ts",
+ "./ask-user": "./src/AskUserQuestion/index.ts",
"./components": "./src/components/index.ts",
"./inspectors": "./src/Inspector/index.ts",
"./inspectors/github-labels": "./src/Inspector/GitHub/labels.ts",
@@ -25,6 +26,7 @@
"lucide-react": "*",
"path-browserify-esm": "*",
"react": "*",
+ "react-dom": "*",
"react-i18next": "*"
}
}
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx b/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx
new file mode 100644
index 00000000000..4207cd89645
--- /dev/null
+++ b/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx
@@ -0,0 +1,180 @@
+'use client';
+
+import { Flexbox, Icon, Text, TextArea } from '@lobehub/ui';
+import { Button, Tabs } from '@lobehub/ui/base-ui';
+import { Check, PenLine, Send, X } from 'lucide-react';
+import { memo } from 'react';
+import { createPortal } from 'react-dom';
+
+import { formatRemaining, isQuestionAnswered } from './draft';
+import QuestionPanel from './QuestionPanel';
+import type { AskUserFormApi } from './useAskUserForm';
+
+/**
+ * All display strings the view needs. Kept i18n-free so `shared-tool-ui` stays
+ * app-decoupled β€” each host builds this from its own namespace (Claude Code
+ * uses its `claudeCode.askUserQuestion.*` keys, the builtin surface uses the
+ * generic `askUserQuestion.*` keys).
+ */
+export interface AskUserQuestionLabels {
+ customPlaceholder: string;
+ /** "Back to options" β€” reserved for hosts that render a back affordance. */
+ escapeBack: string;
+ escapeEnter: string;
+ escapePlaceholder: string;
+ multiSelectTag: string;
+ skip: string;
+ submit: string;
+ timeExpired: string;
+ timeRemaining: (time: string) => string;
+}
+
+export interface AskUserQuestionViewProps extends AskUserFormApi {
+ /** Portal the Skip/Submit footer here so it stays pinned below the scroll. */
+ actionsPortalTarget?: HTMLElement | null;
+ labels: AskUserQuestionLabels;
+ /** Render the countdown text in the footer (only when a countdown is active). */
+ showCountdown: boolean;
+}
+
+/**
+ * The presentational shell for AskUserQuestion:
+ * - a top tab strip (Q1, Q2, … + a trailing "Or type directly" escape tab) when
+ * there is more than one question,
+ * - the active `QuestionPanel` (or the whole-form escape TextArea), and
+ * - a Skip/Submit footer with an optional countdown.
+ *
+ * All state and handlers arrive via props (from `useAskUserForm`); this
+ * component is pure view and holds no state of its own.
+ */
+export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {
+ const {
+ actionsPortalTarget,
+ activeQuestion,
+ activeTab,
+ custom,
+ escapeActive,
+ escapeText,
+ expired,
+ handleCustomChange,
+ handleEscapeTextChange,
+ handleSkip,
+ handleSubmit,
+ handleToggle,
+ isMulti,
+ isSubmitDisabled,
+ labels,
+ picks,
+ questions,
+ remainingMs,
+ setActiveTab,
+ setEscapeMode,
+ showCountdown,
+ submitting,
+ } = props;
+
+ const footer = (
+ <Flexbox
+ horizontal
+ align="center"
+ gap={8}
+ justify={showCountdown ? 'space-between' : 'flex-end'}
+ width={'100%'}
+ >
+ {showCountdown && (
+ <Text fontSize={12} type="secondary">
+ {expired ? labels.timeExpired : labels.timeRemaining(formatRemaining(remainingMs))}
+ </Text>
+ )}
+ <Flexbox horizontal gap={8}>
+ <Button disabled={submitting} icon={<Icon icon={X} />} onClick={handleSkip}>
+ {labels.skip}
+ </Button>
+ <Button
+ disabled={isSubmitDisabled}
+ icon={<Icon icon={Send} />}
+ loading={submitting}
+ type="primary"
+ onClick={handleSubmit}
+ >
+ {labels.submit}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+
+ return (
+ <Flexbox gap={12}>
+ {isMulti && (
+ <Tabs
+ activeKey={escapeActive ? 'escape' : activeTab}
+ variant="square"
+ items={[
+ ...questions.map((q, idx) => {
+ const done = isQuestionAnswered(q, picks, custom);
+ return {
+ key: String(idx),
+ label: (
+ <Flexbox horizontal align="center" gap={6}>
+ <Text>Q{idx + 1}</Text>
+ {done && <Icon icon={Check} size={12} />}
+ </Flexbox>
+ ),
+ };
+ }),
+ // The whole-form freeform sits as a visible peer to the questions β€”
+ // it replaces *all* of them, so it reads as a sibling choice, not a
+ // hidden mode toggle.
+ {
+ key: 'escape',
+ label: (
+ <Flexbox horizontal align="center" gap={6}>
+ <Icon icon={PenLine} size={12} />
+ <Text>{labels.escapeEnter}</Text>
+ </Flexbox>
+ ),
+ },
+ ]}
+ onChange={(key: string) => {
+ if (key === 'escape') {
+ setEscapeMode(true);
+ } else {
+ setEscapeMode(false);
+ setActiveTab(key);
+ }
+ }}
+ />
+ )}
+
+ {escapeActive ? (
+ <TextArea
+ autoSize={{ maxRows: 8, minRows: 3 }}
+ disabled={expired || submitting}
+ placeholder={labels.escapePlaceholder}
+ value={escapeText}
+ variant="filled"
+ onChange={(e) => handleEscapeTextChange(e.target.value)}
+ />
+ ) : (
+ activeQuestion && (
+ <QuestionPanel
+ answer={picks[activeQuestion.question]}
+ customPlaceholder={labels.customPlaceholder}
+ customValue={custom[activeQuestion.question] ?? ''}
+ disabled={expired || submitting}
+ multiSelectTag={labels.multiSelectTag}
+ question={activeQuestion}
+ onCustomChange={handleCustomChange}
+ onToggle={handleToggle}
+ />
+ )
+ )}
+
+ {actionsPortalTarget ? createPortal(footer, actionsPortalTarget) : footer}
+ </Flexbox>
+ );
+});
+
+AskUserQuestionView.displayName = 'AskUserQuestionView';
+
+export default AskUserQuestionView;
diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/QuestionPanel.tsx b/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx
similarity index 80%
rename from packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/QuestionPanel.tsx
rename to packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx
index 8d851f19593..8d83c50a522 100644
--- a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/QuestionPanel.tsx
+++ b/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx
@@ -3,10 +3,9 @@
import { Flexbox, Text, TextArea } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import type { AskUserQuestionItem } from '../../../types';
-import OptionCard from './OptionCard';
+import { OptionCard } from '../components';
+import type { AskUserQuestionItem } from './types';
const styles = createStaticStyles(({ css, cssVar }) => ({
// Per-question "write your own" input β€” sits as the last row in the option
@@ -42,9 +41,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
interface QuestionPanelProps {
/** The picked option label(s) for this question, if any. */
answer: string | string[] | undefined;
+ /** Placeholder for the trailing "write your own" free-text row. */
+ customPlaceholder: string;
/** The free-text "write your own" value for this question. */
customValue: string;
disabled: boolean;
+ /** Tag shown next to the header when the question is multi-select. */
+ multiSelectTag: string;
onCustomChange: (q: AskUserQuestionItem, value: string) => void;
onToggle: (q: AskUserQuestionItem, label: string) => void;
question: AskUserQuestionItem;
@@ -53,10 +56,21 @@ interface QuestionPanelProps {
/**
* A single question: its header/title, the numbered options, and a trailing
* free-text box so the user can answer in their own words instead of picking.
+ *
+ * Presentational and i18n-free β€” the two visible strings come in as props so
+ * the panel stays app-decoupled and reusable across surfaces.
*/
-const QuestionPanel = memo<QuestionPanelProps>(
- ({ question, answer, customValue, disabled, onToggle, onCustomChange }) => {
- const { t } = useTranslation('tool');
+export const QuestionPanel = memo<QuestionPanelProps>(
+ ({
+ question,
+ answer,
+ customValue,
+ customPlaceholder,
+ disabled,
+ multiSelectTag,
+ onToggle,
+ onCustomChange,
+ }) => {
const isOptionSelected = (label: string): boolean =>
question.multiSelect ? Array.isArray(answer) && answer.includes(label) : answer === label;
@@ -66,7 +80,7 @@ const QuestionPanel = memo<QuestionPanelProps>(
{question.header && <Text type="secondary">{question.header}</Text>}
{question.multiSelect && (
<Text fontSize={12} type="secondary">
- {t('claudeCode.askUserQuestion.multiSelectTag')}
+ {multiSelectTag}
</Text>
)}
</Flexbox>
@@ -91,7 +105,7 @@ const QuestionPanel = memo<QuestionPanelProps>(
<TextArea
autoSize={{ maxRows: 4, minRows: 1 }}
disabled={disabled}
- placeholder={t('claudeCode.askUserQuestion.customOption.placeholder')}
+ placeholder={customPlaceholder}
style={{ flex: 1 }}
value={customValue}
variant="filled"
@@ -104,6 +118,6 @@ const QuestionPanel = memo<QuestionPanelProps>(
},
);
-QuestionPanel.displayName = 'CCAskUserQuestionPanel';
+QuestionPanel.displayName = 'AskUserQuestionPanel';
export default QuestionPanel;
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/draft.ts b/packages/shared-tool-ui/src/AskUserQuestion/draft.ts
new file mode 100644
index 00000000000..f896946b570
--- /dev/null
+++ b/packages/shared-tool-ui/src/AskUserQuestion/draft.ts
@@ -0,0 +1,76 @@
+import type { AskUserDraft, AskUserQuestionItem } from './types';
+
+/**
+ * The one sentinel key, and it lives in the *submit payload* β€” never in the
+ * draft. When the payload sent back is exactly `{ __freeform__: <text> }`, the
+ * bridge formatter forwards the text verbatim β€” no `User answers:` framing.
+ * The in-progress draft keeps this same text in a named `escapeText` field
+ * instead, so no sentinel leaks into form state.
+ */
+export const FREEFORM_PAYLOAD_KEY = '__freeform__';
+
+/**
+ * Default on-screen countdown, mirroring the server-side bridge timeout
+ * (`DEFAULT_ASK_USER_TIMEOUT_MS`). Hosts that have no bridge timeout (the
+ * builtin surfaces) pass `undefined` to disable the countdown entirely.
+ */
+export const DEFAULT_COUNTDOWN_MS = 10 * 60 * 1000;
+
+/** Key under tool message `pluginState` where the in-progress draft lives. */
+export const DRAFT_PLUGIN_STATE_KEY = 'askUserDraft';
+
+/** Coerce a persisted (possibly partial / legacy) blob into a full draft. */
+export const readDraft = (raw: unknown): AskUserDraft => {
+ const d = (raw ?? {}) as Partial<AskUserDraft>;
+ return {
+ custom: d.custom ?? {},
+ escapeActive: !!d.escapeActive,
+ escapeText: typeof d.escapeText === 'string' ? d.escapeText : '',
+ picks: d.picks ?? {},
+ };
+};
+
+/** A question counts as answered when it has a pick or non-empty custom text. */
+export const isQuestionAnswered = (
+ q: AskUserQuestionItem,
+ picks: Record<string, string | string[]>,
+ custom: Record<string, string>,
+): boolean => {
+ if (custom[q.question]?.trim()) return true;
+ const a = picks[q.question];
+ return q.multiSelect ? Array.isArray(a) && a.length > 0 : !!a;
+};
+
+/**
+ * Merge picks + custom text into the structured payload: each question maps to
+ * its picks, its custom text, or both (multi-select appends custom as an extra
+ * entry). Shared by the Submit button and the timeout fallback so the two never
+ * diverge.
+ */
+export const buildSubmitPayload = (
+ questions: AskUserQuestionItem[],
+ picks: Record<string, string | string[]>,
+ custom: Record<string, string>,
+): Record<string, string | string[]> => {
+ const payload: Record<string, string | string[]> = {};
+ for (const q of questions) {
+ const text = custom[q.question]?.trim();
+ if (q.multiSelect) {
+ const chosen = Array.isArray(picks[q.question]) ? (picks[q.question] as string[]) : [];
+ const merged = text ? [...chosen, text] : chosen;
+ if (merged.length > 0) payload[q.question] = merged;
+ } else if (text) {
+ payload[q.question] = text;
+ } else if (picks[q.question]) {
+ payload[q.question] = picks[q.question];
+ }
+ }
+ return payload;
+};
+
+export const formatRemaining = (msLeft: number): string => {
+ const totalSec = Math.max(0, Math.floor(msLeft / 1000));
+ const min = Math.floor(totalSec / 60);
+ const sec = totalSec % 60;
+ return `${min}:${sec.toString().padStart(2, '0')}`;
+};
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/index.ts b/packages/shared-tool-ui/src/AskUserQuestion/index.ts
new file mode 100644
index 00000000000..7062dcd2473
--- /dev/null
+++ b/packages/shared-tool-ui/src/AskUserQuestion/index.ts
@@ -0,0 +1,22 @@
+export {
+ type AskUserQuestionLabels,
+ AskUserQuestionView,
+ type AskUserQuestionViewProps,
+} from './AskUserQuestionView';
+export {
+ buildSubmitPayload,
+ DEFAULT_COUNTDOWN_MS,
+ DRAFT_PLUGIN_STATE_KEY,
+ formatRemaining,
+ FREEFORM_PAYLOAD_KEY,
+ isQuestionAnswered,
+ readDraft,
+} from './draft';
+export { default as QuestionPanel } from './QuestionPanel';
+export type {
+ AskUserDraft,
+ AskUserQuestionArgs,
+ AskUserQuestionItem,
+ AskUserQuestionOption,
+} from './types';
+export { type AskUserFormApi, useAskUserForm, type UseAskUserFormParams } from './useAskUserForm';
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/types.ts b/packages/shared-tool-ui/src/AskUserQuestion/types.ts
new file mode 100644
index 00000000000..3414bed19ef
--- /dev/null
+++ b/packages/shared-tool-ui/src/AskUserQuestion/types.ts
@@ -0,0 +1,51 @@
+/**
+ * One option on an AskUserQuestion question β€” `label` is what the user picks,
+ * `description` is the supporting text shown alongside.
+ */
+export interface AskUserQuestionOption {
+ description?: string;
+ label: string;
+}
+
+/**
+ * One question in an `AskUserQuestion` invocation β€” `header` is short, `options`
+ * is 2-4 entries, `multiSelect` is opt-in.
+ */
+export interface AskUserQuestionItem {
+ header: string;
+ multiSelect?: boolean;
+ options: AskUserQuestionOption[];
+ question: string;
+}
+
+/**
+ * `AskUserQuestion` tool arguments β€” 1-4 questions per call. Shared across the
+ * Claude Code intervention and the builtin `user-interaction` / `lobe-agent`
+ * clarification surfaces so the model's prompts and the UI stay identical.
+ */
+export interface AskUserQuestionArgs {
+ questions: AskUserQuestionItem[];
+}
+
+/**
+ * In-progress form state, persisted on the tool message's
+ * `pluginState.askUserDraft` so HMR reloads, store re-mounts, and tab switches
+ * all keep partial answers around β€” only a fresh `tool_use` starts blank.
+ *
+ * Three independent answer slices, kept apart so picks and custom text can
+ * coexist on one question (multi-select) and a half-typed escape reply never
+ * bleeds into the form payload:
+ * - `picks` β†’ multi-choice selections, keyed by question text
+ * - `custom` β†’ per-question "write your own" text, keyed by question text
+ * - `escape*` β†’ the global "Or type directly" box (whole-form bypass)
+ *
+ * Declared as a `type` (not `interface`) so it satisfies the
+ * `Record<string, unknown>` param of the store's `setInterventionDraft` β€” an
+ * interface has no implicit index signature and would fail that assignment.
+ */
+export type AskUserDraft = {
+ custom: Record<string, string>;
+ escapeActive: boolean;
+ escapeText: string;
+ picks: Record<string, string | string[]>;
+};
diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/useAskUserForm.ts b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts
similarity index 76%
rename from packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/useAskUserForm.ts
rename to packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts
index 7ef39395ab1..d3384c2e0ad 100644
--- a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/useAskUserForm.ts
+++ b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts
@@ -1,44 +1,64 @@
import type { BuiltinInterventionProps } from '@lobechat/types';
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useConversationStore } from '@/features/Conversation/store';
-import { dataSelectors } from '@/features/Conversation/store/slices/data/selectors';
-import { useChatStore } from '@/store/chat';
+import { buildSubmitPayload, FREEFORM_PAYLOAD_KEY, isQuestionAnswered, readDraft } from './draft';
+import type { AskUserDraft, AskUserQuestionArgs, AskUserQuestionItem } from './types';
-import type { AskUserQuestionArgs, AskUserQuestionItem } from '../../../types';
-import type { AskUserDraft } from './draft';
-import {
- buildSubmitPayload,
- COUNTDOWN_MS,
- DRAFT_PLUGIN_STATE_KEY,
- FREEFORM_PAYLOAD_KEY,
- isQuestionAnswered,
- readDraft,
-} from './draft';
+export interface UseAskUserFormParams {
+ args: AskUserQuestionArgs | undefined;
+ /**
+ * When set, drives an on-screen countdown + a timeout fallback that submits
+ * option 1 of every unanswered question when the clock hits zero. When
+ * `undefined` the countdown + fallback are disabled entirely (`expired` stays
+ * `false`, no timer runs) β€” used by surfaces with no bridge timeout.
+ */
+ countdownMs?: number;
+ onInteractionAction?: BuiltinInterventionProps<AskUserQuestionArgs>['onInteractionAction'];
+ /** Raw persisted draft blob read from the host's store (coerced internally). */
+ persistedDraft: unknown;
+ /** Persist the full draft; host wires this to its own store. */
+ writeDraft: (draft: AskUserDraft) => void;
+}
+
+export interface AskUserFormApi {
+ activeQuestion?: AskUserQuestionItem;
+ activeTab: string;
+ custom: Record<string, string>;
+ escapeActive: boolean;
+ escapeText: string;
+ expired: boolean;
+ handleCustomChange: (q: AskUserQuestionItem, value: string) => void;
+ handleEscapeTextChange: (value: string) => void;
+ handleSkip: () => void;
+ handleSubmit: () => void;
+ handleToggle: (q: AskUserQuestionItem, label: string) => void;
+ isMulti: boolean;
+ isSubmitDisabled: boolean;
+ picks: Record<string, string | string[]>;
+ questions: AskUserQuestionItem[];
+ remainingMs: number;
+ setActiveTab: (key: string) => void;
+ setEscapeMode: (next: boolean) => void;
+ submitting: boolean;
+}
/**
- * All state + handlers for the CC AskUserQuestion form. Kept out of the view
- * so `index.tsx` stays a thin render of the returned values.
+ * All state + handlers for the AskUserQuestion form. Kept out of the view so
+ * the per-package `index.tsx` stays a thin render of the returned values.
*
- * Draft persistence: every mutation mirrors the full form state into the tool
- * message's `pluginState.askUserDraft` (see `setInterventionDraft`) so HMR,
- * remounts, and tab switches resume where the user left off.
+ * Draft persistence is host-owned: the caller passes the raw `persistedDraft`
+ * (read from wherever it stores plugin state) and a `writeDraft` callback, so
+ * this hook never touches any app store directly and stays app-decoupled.
*/
export const useAskUserForm = ({
args,
- messageId,
+ countdownMs,
onInteractionAction,
-}: BuiltinInterventionProps<AskUserQuestionArgs>) => {
+ persistedDraft,
+ writeDraft,
+}: UseAskUserFormParams): AskUserFormApi => {
const questions = args?.questions ?? [];
- // Persisted draft β€” read from the tool message's pluginState so the form
- // stays where the user left it across unmount / HMR / refresh.
- const persistedDraft = useConversationStore((s) => {
- const msg = dataSelectors.getDbMessageById(messageId)(s);
- return (msg?.pluginState as { [DRAFT_PLUGIN_STATE_KEY]?: unknown })?.[DRAFT_PLUGIN_STATE_KEY];
- });
- const setInterventionDraft = useChatStore((s) => s.setInterventionDraft);
-
// Plain const (not a hook) so it can read `persistedDraft` without tripping
// exhaustive-deps; consumed only by the once-run useState initializers below.
const initial = readDraft(persistedDraft);
@@ -54,20 +74,19 @@ export const useAskUserForm = ({
return String(idx >= 0 ? idx : 0);
});
+ // Countdown is opt-in: only surfaces with a bridge timeout pass `countdownMs`.
+ const countdownEnabled = countdownMs != null;
+
// Mounted-time deadline; server has its own clock and will return isError if
// it expires first. Drift of a few seconds is fine.
- const deadline = useMemo(() => Date.now() + COUNTDOWN_MS, []);
+ const deadline = useMemo(() => Date.now() + (countdownMs ?? 0), [countdownMs]);
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
+ if (!countdownEnabled) return;
const id = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(id);
- }, []);
- const expired = now >= deadline;
-
- const writeDraft = useCallback(
- (next: AskUserDraft) => setInterventionDraft(messageId, next),
- [messageId, setInterventionDraft],
- );
+ }, [countdownEnabled]);
+ const expired = countdownEnabled ? now >= deadline : false;
const handleToggle = useCallback(
(q: AskUserQuestionItem, label: string) => {
@@ -174,7 +193,7 @@ export const useAskUserForm = ({
const handleSubmit = useCallback(() => {
if (escapeActive && escapeAvailable) {
// Escape mode is mutually exclusive with picks β€” send the text alone
- // under `__freeform__`. Bridge formatter forwards it to CC verbatim.
+ // under `__freeform__`. Bridge formatter forwards it verbatim.
void submitWith({ [FREEFORM_PAYLOAD_KEY]: escapeText.trim() });
} else {
void submitWith(buildSubmitPayload(questions, picks, custom));
diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/OptionCard.tsx b/packages/shared-tool-ui/src/components/OptionCard.tsx
similarity index 86%
rename from packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/OptionCard.tsx
rename to packages/shared-tool-ui/src/components/OptionCard.tsx
index 94a5b962345..185095a04ae 100644
--- a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/OptionCard.tsx
+++ b/packages/shared-tool-ui/src/components/OptionCard.tsx
@@ -65,7 +65,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-interface OptionCardProps {
+export interface OptionCardProps {
description?: string;
disabled?: boolean;
index: number;
@@ -75,11 +75,16 @@ interface OptionCardProps {
}
/**
- * One numbered option in a question. Outlined when picked, neutral otherwise;
+ * One numbered option in a question. Filled when picked, neutral otherwise;
* a right-side checkmark seals the selection so the state reads cleanly even
* with the number chip kept neutral.
+ *
+ * Presentational and self-contained β€” shared across the ask-user surfaces
+ * (Claude Code `AskUserQuestion`, the builtin `user-interaction` /
+ * `lobe-agent` clarification form) so the tiled options read identically
+ * everywhere.
*/
-const OptionCard = memo<OptionCardProps>(
+export const OptionCard = memo<OptionCardProps>(
({ index, label, description, selected, disabled, onToggle }) => (
<Flexbox
horizontal
@@ -102,6 +107,6 @@ const OptionCard = memo<OptionCardProps>(
),
);
-OptionCard.displayName = 'CCAskUserQuestionOption';
+OptionCard.displayName = 'OptionCard';
export default OptionCard;
diff --git a/packages/shared-tool-ui/src/components/index.ts b/packages/shared-tool-ui/src/components/index.ts
index 5e66897c535..fc2e1ec8c0b 100644
--- a/packages/shared-tool-ui/src/components/index.ts
+++ b/packages/shared-tool-ui/src/components/index.ts
@@ -1,2 +1,3 @@
export { AnimatedNumber } from './AnimatedNumber';
export { FilePathDisplay } from './FilePathDisplay';
+export { OptionCard, type OptionCardProps } from './OptionCard';
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 8832c60d68b..6d9fb9ecfdb 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts
@@ -1,4 +1,5 @@
import { ClaudeCodeIdentifier } from '@lobechat/builtin-tool-claude-code';
+import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';
import { UserInteractionIdentifier } from '@lobechat/builtin-tool-user-interaction';
import {
WebOnboardingApiName,
@@ -142,8 +143,18 @@ const HETERO_CUSTOM_INTERACTION_IDENTIFIERS = new Set<string>([ClaudeCodeIdentif
export const isHeteroInteractionIdentifier = (identifier: string) =>
HETERO_CUSTOM_INTERACTION_IDENTIFIERS.has(identifier);
+/**
+ * lobe-agent reuses the user-interaction `askUserQuestion` card. Unlike the
+ * standalone tool (whose whole identifier is a custom interaction), lobe-agent
+ * has other APIs (createPlan / clearTodos …) that must keep the default
+ * approve/reject UI β€” so only its `askUserQuestion` API is a custom interaction.
+ */
+const isLobeAgentAskUserQuestion = (identifier: string, apiName?: string) =>
+ identifier === LobeAgentIdentifier && apiName === LobeAgentApiName.askUserQuestion;
+
export const isCustomInteractionIdentifier = (identifier: string, apiName?: string) =>
identifier === UserInteractionIdentifier ||
+ isLobeAgentAskUserQuestion(identifier, apiName) ||
isHeteroInteractionIdentifier(identifier) ||
Boolean(findCustomInteractionSubmitHandler(identifier, apiName));
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index c94ca733ac3..2340894c65a 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -29,6 +29,28 @@ export interface ResumeApprovalParam {
toolCallId: string;
}
+/**
+ * Resume instruction for an operation that paused on a `humanIntervention:
+ * 'always'` tool (e.g. lobe-agent `askUserQuestion`) during a GATEWAY/server
+ * run. When present, the new op writes the human-provided answer as the pending
+ * tool message's result and resumes from `phase: 'tool_result'` β€” the tool is
+ * NOT re-executed, so the server runtime never overwrites the answer with a
+ * fresh "pending" placeholder.
+ *
+ * Kept as a top-level field (not folded into `appContext`) so the server schema
+ * can validate it independently.
+ */
+export interface ResumeToolResultParam {
+ /** The human-provided tool result (the answer text). */
+ content: string;
+ /** ID of the pending `role='tool'` message this result targets. */
+ parentMessageId: string;
+ /** Optional plugin state to persist on the tool message. */
+ pluginState?: Record<string, unknown>;
+ /** tool_call_id of the pending tool call being answered. */
+ toolCallId: string;
+}
+
export interface ExecAgentTaskParams {
agentId?: string;
appContext?: ExecAgentAppContext;
@@ -48,6 +70,8 @@ export interface ExecAgentTaskParams {
prompt: string;
/** Resume a previous op paused on `human_approve_required` instead of starting from a fresh user prompt. */
resumeApproval?: ResumeApprovalParam;
+ /** Resume a previous op paused on a human-intervention tool by carrying the human answer as the tool result. */
+ resumeToolResult?: ResumeToolResultParam;
/** Tool identifiers the user @-mentioned in this message; the server enables them for this run. */
selectedToolIds?: string[];
slug?: string;
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 bceacab2d68..fa01b78c8cc 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -1395,6 +1395,217 @@ describe('ConversationControl actions', () => {
}),
);
});
+
+ describe('server-mode branch', () => {
+ it('starts a new Gateway op with resumeToolResult carrying the answer and does NOT run local runtime', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ const agentId = 'server-agent';
+ const topicId = 'server-topic';
+ const chatKey = messageMapKey({ agentId, topicId });
+
+ const userMessage = createMockMessage({
+ id: 'user-msg',
+ metadata: { trigger: RequestTrigger.Chat },
+ role: 'user',
+ });
+ const assistantMessage = createMockMessage({
+ id: 'assistant-msg',
+ parentId: userMessage.id,
+ role: 'assistant',
+ });
+ const toolMessage = createMockMessage({
+ groupId: 'group-1',
+ id: 'tool-msg-1',
+ parentId: assistantMessage.id,
+ plugin: {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ identifier: 'lobe-agent',
+ type: 'default',
+ },
+ role: 'tool',
+ // `tool_call_id` is what the server uses to locate the pending tool
+ // call; the new Gateway op carries it forward via `resumeToolResult`.
+ tool_call_id: 'call_ask',
+ } as any);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: topicId,
+ activeThreadId: undefined,
+ dbMessagesMap: { [chatKey]: [userMessage, assistantMessage, toolMessage] },
+ messagesMap: { [chatKey]: [userMessage, assistantMessage, toolMessage] },
+ });
+
+ // Presence of an `execServerAgentRuntime` op is one half of the
+ // Gateway-resume signal; the other is `isGatewayModeEnabled`.
+ result.current.startOperation({
+ context: { agentId, topicId, threadId: null },
+ metadata: { serverOperationId: 'server-op-xyz' },
+ type: 'execServerAgentRuntime',
+ });
+ });
+
+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);
+ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);
+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);
+ const executeGatewayAgentSpy = vi
+ .spyOn(result.current, 'executeGatewayAgent')
+ .mockResolvedValue({} as any);
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
+ .mockResolvedValue(undefined);
+
+ await act(async () => {
+ await result.current.submitToolInteraction('tool-msg-1', { answer: 'blue' }, undefined, {
+ toolResultContent: 'My favorite color is blue',
+ });
+ });
+
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: '',
+ parentMessageId: 'tool-msg-1',
+ resumeToolResult: {
+ content: 'My favorite color is blue',
+ parentMessageId: 'tool-msg-1',
+ toolCallId: 'call_ask',
+ },
+ }),
+ );
+ expect(executeClientAgentSpy).not.toHaveBeenCalled();
+
+ // Fallback guard: the paused `execServerAgentRuntime` op is completed.
+ const pausedServerOps = Object.values(result.current.operations).filter(
+ (op: any) => op.type === 'execServerAgentRuntime',
+ );
+ expect(pausedServerOps).toHaveLength(1);
+ expect(pausedServerOps[0]!.status).toBe('completed');
+
+ executeGatewayAgentSpy.mockRestore();
+ });
+
+ it('forwards pluginState into resumeToolResult when provided', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ const agentId = 'server-agent';
+ const topicId = 'server-topic';
+ const chatKey = messageMapKey({ agentId, topicId });
+
+ const toolMessage = createMockMessage({
+ id: 'tool-msg-1',
+ plugin: {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ identifier: 'lobe-agent',
+ type: 'default',
+ },
+ role: 'tool',
+ tool_call_id: 'call_ask',
+ } as any);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: topicId,
+ activeThreadId: undefined,
+ dbMessagesMap: { [chatKey]: [toolMessage] },
+ messagesMap: { [chatKey]: [toolMessage] },
+ });
+ });
+
+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);
+ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);
+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);
+ vi.spyOn(result.current, 'optimisticUpdatePluginState').mockResolvedValue(undefined);
+ const executeGatewayAgentSpy = vi
+ .spyOn(result.current, 'executeGatewayAgent')
+ .mockResolvedValue({} as any);
+
+ await act(async () => {
+ await result.current.submitToolInteraction('tool-msg-1', { answer: 'blue' }, undefined, {
+ pluginState: { askUserAnswers: { q: 'blue' } },
+ toolResultContent: 'blue',
+ });
+ });
+
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ resumeToolResult: expect.objectContaining({
+ pluginState: { askUserAnswers: { q: 'blue' } },
+ }),
+ }),
+ );
+
+ executeGatewayAgentSpy.mockRestore();
+ });
+
+ it('takes the client path (executeClientAgent) when gateway mode is disabled', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ const agentId = 'client-agent';
+ const topicId = 'client-topic';
+ const chatKey = messageMapKey({ agentId, topicId });
+
+ const toolMessage = createMockMessage({
+ groupId: 'group-1',
+ id: 'tool-msg-1',
+ plugin: {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ identifier: 'lobe-agent',
+ type: 'default',
+ },
+ role: 'tool',
+ tool_call_id: 'call_ask',
+ } as any);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: topicId,
+ activeThreadId: undefined,
+ dbMessagesMap: { [chatKey]: [toolMessage] },
+ messagesMap: { [chatKey]: [toolMessage] },
+ });
+ });
+
+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(false);
+ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);
+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);
+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({
+ agentConfig: createMockResolvedAgentConfig(),
+ context: { phase: 'init' } as any,
+ state: {} as any,
+ });
+ const executeGatewayAgentSpy = vi
+ .spyOn(result.current, 'executeGatewayAgent')
+ .mockResolvedValue({} as any);
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
+ .mockResolvedValue(undefined);
+
+ await act(async () => {
+ await result.current.submitToolInteraction('tool-msg-1', { answer: 'blue' }, undefined, {
+ createUserMessage: false,
+ toolResultContent: 'blue',
+ });
+ });
+
+ expect(executeGatewayAgentSpy).not.toHaveBeenCalled();
+ expect(executeClientAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ initialContext: expect.objectContaining({ phase: 'tool_result' }),
+ parentMessageId: 'tool-msg-1',
+ parentMessageType: 'tool',
+ }),
+ );
+
+ executeGatewayAgentSpy.mockRestore();
+ });
+ });
});
describe('skipToolInteraction', () => {
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
index a90792a0c43..981ba67b1fd 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
@@ -450,7 +450,7 @@ export class ConversationControlActionImpl {
this.#emitRunResumed(effectiveContext, {
operationId,
parentMessageId: toolMessageId,
- runtimeType: 'client',
+ runtimeType: this.#shouldUseGatewayResume(effectiveContext) ? 'gateway' : 'client',
});
// 1. Mark intervention as approved and set tool result to user's response
@@ -476,6 +476,52 @@ export class ConversationControlActionImpl {
);
}
+ // 1.5. Server-mode: start a **new** Gateway op carrying the human answer as
+ // the tool result via `resumeToolResult`. The server writes the answer as
+ // the pending tool message's content, marks intervention approved, and
+ // resumes from `phase: 'tool_result'` (NO re-execution). The synthetic user
+ // message (2b) is not needed β€” the server continues from the answered tool
+ // call. Mirrors approveToolCalling's gateway branch.
+ if (this.#shouldUseGatewayResume(effectiveContext)) {
+ const toolCallId = toolMessage.tool_call_id;
+ if (!toolCallId) {
+ console.warn(
+ '[submitToolInteraction][server] tool message missing tool_call_id; skipping resume',
+ );
+ completeOperation(operationId);
+ return;
+ }
+ const requestMetadata = this.#getRequestMetadataFromMessageChain(toolMessageId);
+ // Snapshot paused op IDs before the resume call; retire them only after
+ // executeGatewayAgent succeeds so a transient failure leaves the running
+ // marker intact and `#shouldUseGatewayResume` still flags Gateway mode.
+ const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);
+ try {
+ await this.#get().executeGatewayAgent({
+ context: effectiveContext,
+ message: '',
+ metadata: requestMetadata,
+ parentMessageId: toolMessageId,
+ resumeToolResult: {
+ content: toolContent,
+ parentMessageId: toolMessageId,
+ toolCallId,
+ ...(options?.pluginState ? { pluginState: options.pluginState } : {}),
+ },
+ });
+ this.#completeOpsById(pausedOpIds);
+ completeOperation(operationId);
+ } catch (error) {
+ const err = error as Error;
+ console.error('[submitToolInteraction][server] Gateway resume failed:', err);
+ this.#get().failOperation(operationId, {
+ type: 'submitToolInteraction',
+ message: err.message || 'Unknown error',
+ });
+ }
+ return;
+ }
+
const chatKey = messageMapKey({ agentId, topicId, threadId, scope });
// 2a. Tool-result-only path: skip the synthetic user message and resume from the
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 735cafd2d87..139f4a90e8c 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -13,7 +13,11 @@ import type {
} from '@lobechat/types';
import { isDesktop } from '@/const/version';
-import { aiAgentService, type ResumeApprovalParam } from '@/services/aiAgent';
+import {
+ aiAgentService,
+ type ResumeApprovalParam,
+ type ResumeToolResultParam,
+} from '@/services/aiAgent';
import { gatewayConnectionService } from '@/services/electron/gatewayConnection';
import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
@@ -392,6 +396,13 @@ export class GatewayActionImpl {
* a fresh user prompt.
*/
resumeApproval?: ResumeApprovalParam;
+ /**
+ * Resume a paused op waiting on a human-intervention tool (e.g. lobe-agent
+ * `askUserQuestion`). Forwarded to `aiAgentService.execAgentTask` so the new
+ * server-side op writes the human answer as the tool result and resumes from
+ * `phase: 'tool_result'` WITHOUT re-executing the tool.
+ */
+ resumeToolResult?: ResumeToolResultParam;
/**
* Tool identifiers the user @-mentioned in this message. Forwarded to the
* server as `selectedToolIds` so the server runtime enables them for this
@@ -427,6 +438,7 @@ export class GatewayActionImpl {
parentMessageId,
parentOperationId,
resumeApproval,
+ resumeToolResult,
selectedToolIds,
mentionedAgents,
tempMessageIds,
@@ -502,6 +514,7 @@ export class GatewayActionImpl {
parentMessageId,
prompt: message,
resumeApproval,
+ resumeToolResult,
selectedToolIds,
trigger: metadata?.trigger,
userInterventionConfig,