🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: guard AskUserQuestion payloads (#16830)
Arvin Xubf32a1999a1b
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex f92fad99eae..b642a8fc674 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1059,6 +1059,9 @@"tool.intervention.rejectReasonPlaceholder": "Tell the agent what you'd like instead","tool.intervention.rejectedWithReason": "This Skill call was rejected: {{reason}}","tool.intervention.rememberSimilar": "Don't ask again for similar actions",+ "tool.intervention.renderFallback.description": "This display was downgraded to raw JSON because the current model was not capable enough to generate a stable interactive payload. Switch to a stronger model and try again.",+ "tool.intervention.renderFallback.rawJson": "Raw JSON",+ "tool.intervention.renderFallback.title": "Interaction display downgraded","tool.intervention.scrollToIntervention": "View","tool.intervention.submit": "Submit","tool.intervention.toolAbort": "You canceled this Skill call",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex c49ad0dd2a4..d3b1fd88428 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1059,6 +1059,9 @@"tool.intervention.rejectReasonPlaceholder": "告诉 Agent 你希望它怎么做","tool.intervention.rejectedWithReason": "本次技能调用已被拒绝:{{reason}}","tool.intervention.rememberSimilar": "类似操作不再询问",+ "tool.intervention.renderFallback.description": "由于当前模型能力不足,未能生成稳定的交互式参数,因此此请求已降级为原始 JSON。建议更换更强的模型后重试。",+ "tool.intervention.renderFallback.rawJson": "原始 JSON",+ "tool.intervention.renderFallback.title": "交互展示已降级","tool.intervention.scrollToIntervention": "查看","tool.intervention.submit": "提交","tool.intervention.toolAbort": "你已取消本次技能调用",diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/AskUserQuestion.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/AskUserQuestion.tsxindex 74074737db0..02e4febe5c0 100644--- a/packages/builtin-tool-claude-code/src/client/Inspector/AskUserQuestion.tsx+++ b/packages/builtin-tool-claude-code/src/client/Inspector/AskUserQuestion.tsx@@ -1,12 +1,14 @@'use client';+import { normalizeAskUserQuestions } from '@lobechat/shared-tool-ui/ask-user';import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';import type { BuiltinInspectorProps } from '@lobechat/types';import { createStaticStyles, cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { type AskUserQuestionArgs, ClaudeCodeApiName } from '../../types';+import type { AskUserQuestionArgs } from '../../types';+import { ClaudeCodeApiName } from '../../types';const styles = createStaticStyles(({ css, cssVar }) => ({chip: css`@@ -31,7 +33,8 @@ export const AskUserQuestionInspector = memo<BuiltinInspectorProps<AskUserQuesti({ args, partialArgs, isArgumentsStreaming, isLoading }) => {const { t } = useTranslation('plugin');const label = t(ClaudeCodeApiName.AskUserQuestion as any);- const questions = args?.questions ?? partialArgs?.questions ?? [];+ const argsQuestions = normalizeAskUserQuestions(args);+ const questions = argsQuestions.length ? argsQuestions : normalizeAskUserQuestions(partialArgs);const summary =questions.length === 0? undefineddiff --git a/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsxindex c3f56c7174c..10c936a0529 100644--- a/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsx+++ b/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsx@@ -1,5 +1,6 @@'use client';+import { normalizeAskUserQuestions } from '@lobechat/shared-tool-ui/ask-user';import type { BuiltinRenderProps } from '@lobechat/types';import { Flexbox, Icon, Text } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';@@ -134,7 +135,7 @@ const AskUserQuestion = memo<BuiltinRenderProps<AskUserQuestionArgs, AskUserQuestionState, unknown>>(({ args, pluginError, pluginState }) => {const { t } = useTranslation('plugin');- const questions = args?.questions ?? [];+ const questions = normalizeAskUserQuestions(args);const answers = pluginState?.askUserAnswers;const freeform = answers?.['__freeform__'];const freeformText = typeof freeform === 'string' ? freeform.trim() : '';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.tsxindex e09dada8c8a..d156c95aeaf 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,10 +1,10 @@'use client';+import type { AskUserDraft, AskUserQuestionArgs } from '@lobechat/shared-tool-ui/ask-user';import {- type AskUserDraft,- type AskUserQuestionArgs,AskUserQuestionView,DRAFT_PLUGIN_STATE_KEY,+ normalizeAskUserQuestions,useAskUserForm,} from '@lobechat/shared-tool-ui/ask-user';import type { BuiltinInterventionProps } from '@lobechat/types';@@ -54,7 +54,7 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio// 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 ?? [];+ const questions = normalizeAskUserQuestions(args);return (<Flexbox gap={8}>{questions.map((q, idx) => (diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 22e4f04c8df..73aa84067e3 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1147,6 +1147,10 @@ export default {'tool.intervention.optionApprove': 'Approve','tool.intervention.optionApproveRemember': "Approve, and don't ask again for similar actions",'tool.intervention.rememberSimilar': "Don't ask again for similar actions",+ 'tool.intervention.renderFallback.description':+ 'This display was downgraded to raw JSON because the current model was not capable enough to generate a stable interactive payload. Switch to a stronger model and try again.',+ 'tool.intervention.renderFallback.rawJson': 'Raw JSON',+ 'tool.intervention.renderFallback.title': 'Interaction display downgraded','tool.intervention.submit': 'Submit','tool.intervention.mode.allowList': 'Allow List','tool.intervention.mode.allowListDesc': 'Only automatically execute approved tools',diff --git a/packages/shared-tool-ui/src/AskUserQuestion/index.ts b/packages/shared-tool-ui/src/AskUserQuestion/index.tsindex 7062dcd2473..345b8e5e508 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/index.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/index.ts@@ -12,6 +12,7 @@ export {isQuestionAnswered,readDraft,} from './draft';+export { normalizeAskUserQuestions } from './normalize';export { default as QuestionPanel } from './QuestionPanel';export type {AskUserDraft,diff --git a/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.ts b/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.tsnew file mode 100644index 00000000000..25db83055bf--- /dev/null+++ b/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from 'vitest';++import { normalizeAskUserQuestions } from './normalize';++describe('normalizeAskUserQuestions', () => {+ it('keeps valid question arrays', () => {+ const questions = normalizeAskUserQuestions({+ questions: [+ {+ header: 'Scope',+ multiSelect: true,+ options: [+ { description: 'Fix the crash only', label: 'Narrow' },+ { description: 'Also harden related renderers', label: 'Full' },+ ],+ question: 'How broad should the fix be?',+ },+ ],+ });++ expect(questions).toEqual([+ {+ header: 'Scope',+ multiSelect: true,+ options: [+ { description: 'Fix the crash only', label: 'Narrow' },+ { description: 'Also harden related renderers', label: 'Full' },+ ],+ question: 'How broad should the fix be?',+ },+ ]);+ });++ it('accepts a single question object for stale payloads', () => {+ const questions = normalizeAskUserQuestions({+ questions: {+ header: 'Mode',+ options: [{ label: 'Auto' }, { description: 'Manual path', label: 'Manual' }],+ question: 'Which mode?',+ },+ });++ expect(questions).toEqual([+ {+ header: 'Mode',+ options: [{ label: 'Auto' }, { description: 'Manual path', label: 'Manual' }],+ question: 'Which mode?',+ },+ ]);+ });++ it('drops malformed question payloads instead of returning non-arrays', () => {+ expect(normalizeAskUserQuestions({ questions: 'not-json' })).toEqual([]);+ expect(normalizeAskUserQuestions({ questions: null })).toEqual([]);+ expect(normalizeAskUserQuestions({ questions: [{ options: [], question: 42 }] })).toEqual([]);+ });++ it('parses stringified args or questions from double-encoded payloads', () => {+ const expected = [+ {+ header: 'Mode',+ options: [{ label: 'Auto' }],+ question: 'Which mode?',+ },+ ];++ expect(+ normalizeAskUserQuestions(+ JSON.stringify({+ questions: expected,+ }),+ ),+ ).toEqual(expected);+ expect(normalizeAskUserQuestions({ questions: JSON.stringify(expected) })).toEqual(expected);+ });++ it('normalizes malformed options so renderers can map safely', () => {+ const questions = normalizeAskUserQuestions({+ questions: [+ {+ header: 123,+ multiSelect: 'yes',+ options: [{ label: 'Keep' }, { description: 'missing label' }, null],+ question: 'Pick one',+ },+ ],+ });++ expect(questions).toEqual([+ {+ header: '',+ options: [{ label: 'Keep' }],+ question: 'Pick one',+ },+ ]);+ });+});diff --git a/packages/shared-tool-ui/src/AskUserQuestion/normalize.ts b/packages/shared-tool-ui/src/AskUserQuestion/normalize.tsnew file mode 100644index 00000000000..4836f3fd6ab--- /dev/null+++ b/packages/shared-tool-ui/src/AskUserQuestion/normalize.ts@@ -0,0 +1,73 @@+import { pickString, toRecord } from '@lobechat/utils/object';++import type { AskUserQuestionArgs, AskUserQuestionItem, AskUserQuestionOption } from './types';++const parseJsonString = (value: unknown): unknown => {+ if (typeof value !== 'string') return value;++ try {+ return JSON.parse(value) as unknown;+ } catch {+ return value;+ }+};++const normalizeOption = (value: unknown): AskUserQuestionOption | undefined => {+ const option = toRecord(value);+ const label = pickString(option?.label);++ if (!label) return;++ const description = pickString(option?.description);++ return description ? { description, label } : { label };+};++const isQuestionOption = (+ option: AskUserQuestionOption | undefined,+): option is AskUserQuestionOption => !!option;++const normalizeQuestion = (value: unknown): AskUserQuestionItem | undefined => {+ const item = toRecord(value);+ const question = pickString(item?.question);++ if (!question) return;++ const rawOptions = item?.options;+ const options = Array.isArray(rawOptions)+ ? rawOptions.map(normalizeOption).filter(isQuestionOption)+ : [];+ const header = pickString(item?.header) ?? '';+ const multiSelect = typeof item?.multiSelect === 'boolean' ? item.multiSelect : undefined;++ return {+ header,+ ...(multiSelect === undefined ? {} : { multiSelect }),+ options,+ question,+ };+};++const isQuestionItem = (+ question: AskUserQuestionItem | undefined,+): question is AskUserQuestionItem => !!question;++/**+ * Tool arguments come from model/runtime payloads, so tolerate stale or weakly+ * shaped messages instead of letting one bad card crash the conversation page.+ */+export const normalizeAskUserQuestions = (+ args: Partial<AskUserQuestionArgs> | unknown,+): AskUserQuestionItem[] => {+ const parsedArgs = parseJsonString(args);+ const rawArgs = toRecord(parsedArgs);+ const rawQuestions = parseJsonString(rawArgs?.questions ?? parsedArgs);++ if (Array.isArray(rawQuestions)) {+ return rawQuestions.map(normalizeQuestion).filter(isQuestionItem);+ }++ const question = normalizeQuestion(rawQuestions);++ return question ? [question] : [];+};diff --git a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.tsindex d3384c2e0ad..0e87cfae3a4 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts@@ -2,6 +2,7 @@ import type { BuiltinInterventionProps } from '@lobechat/types';import { useCallback, useEffect, useMemo, useState } from 'react';import { buildSubmitPayload, FREEFORM_PAYLOAD_KEY, isQuestionAnswered, readDraft } from './draft';+import { normalizeAskUserQuestions } from './normalize';import type { AskUserDraft, AskUserQuestionArgs, AskUserQuestionItem } from './types';export interface UseAskUserFormParams {@@ -57,7 +58,7 @@ export const useAskUserForm = ({persistedDraft,writeDraft,}: UseAskUserFormParams): AskUserFormApi => {- const questions = args?.questions ?? [];+ const questions = useMemo(() => normalizeAskUserQuestions(args), [args]);// Plain const (not a hook) so it can read `persistedDraft` without tripping// exhaustive-deps; consumed only by the once-run useState initializers below.@@ -252,9 +253,11 @@ export const useAskUserForm = ({]);const activeQuestion = questions[Number(activeTab)] ?? questions[0];- const isSubmitDisabled = inEscape- ? !escapeText.trim() || submitting || expired- : !allAnswered || expired || submitting;+ const isSubmitDisabled =+ questions.length === 0 ||+ (inEscape+ ? !escapeText.trim() || submitting || expired+ : !allAnswered || expired || submitting);return {activeQuestion,diff --git a/src/features/Conversation/InterventionBar/InterventionContent.tsx b/src/features/Conversation/InterventionBar/InterventionContent.tsxindex ddef30d06c7..53ec39d462c 100644--- a/src/features/Conversation/InterventionBar/InterventionContent.tsx+++ b/src/features/Conversation/InterventionBar/InterventionContent.tsx@@ -3,6 +3,7 @@ import { memo } from 'react';import Intervention from '../Messages/AssistantGroup/Tool/Detail/Intervention';import { type PendingIntervention } from '../store/slices/data/pendingInterventions';import { styles } from './style';+import UserInterventionErrorBoundary from './UserInterventionErrorBoundary';interface InterventionContentProps {actionsPortalTarget: HTMLDivElement | null;@@ -11,17 +12,36 @@ interface InterventionContentProps {const InterventionContent = memo<InterventionContentProps>(({ intervention, actionsPortalTarget }) => {+ const boundaryKey = [+ intervention.apiName,+ intervention.identifier,+ intervention.requestArgs,+ intervention.toolCallId,+ intervention.toolMessageId,+ ].join('|');+return (<div className={styles.content}>- <Intervention+ <UserInterventionErrorBoundaryactionsPortalTarget={actionsPortalTarget}apiName={intervention.apiName}assistantGroupId={intervention.assistantGroupId}- id={intervention.toolMessageId}identifier={intervention.identifier}+ key={boundaryKey}requestArgs={intervention.requestArgs}toolCallId={intervention.toolCallId}- />+ toolMessageId={intervention.toolMessageId}+ >+ <Intervention+ actionsPortalTarget={actionsPortalTarget}+ apiName={intervention.apiName}+ assistantGroupId={intervention.assistantGroupId}+ id={intervention.toolMessageId}+ identifier={intervention.identifier}+ requestArgs={intervention.requestArgs}+ toolCallId={intervention.toolCallId}+ />+ </UserInterventionErrorBoundary></div>);},diff --git a/src/features/Conversation/InterventionBar/UserInterventionErrorBoundary.tsx b/src/features/Conversation/InterventionBar/UserInterventionErrorBoundary.tsxnew file mode 100644index 00000000000..0e6ae84fa08--- /dev/null+++ b/src/features/Conversation/InterventionBar/UserInterventionErrorBoundary.tsx@@ -0,0 +1,164 @@+'use client';++import { safeParseJSON } from '@lobechat/utils';+import { Flexbox, Highlighter, Icon, Text } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { AlertTriangle } from 'lucide-react';+import type { ErrorInfo, ReactNode } from 'react';+import { Component, memo, useMemo } from 'react';+import { createPortal } from 'react-dom';+import { useTranslation } from 'react-i18next';++import { useUserStore } from '@/store/user';+import { toolInterventionSelectors } from '@/store/user/selectors';++import ApprovalActions from '../Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions';++const styles = createStaticStyles(({ css, cssVar }) => ({+ description: css`+ overflow: hidden;+ flex: 1;++ min-width: 0;++ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ icon: css`+ flex: none;+ color: ${cssVar.colorWarning};+ `,+ notice: css`+ display: flex;+ gap: 6px;+ align-items: center;++ min-width: 0;+ padding-block: 2px;++ font-size: 12px;+ line-height: 1.5;+ `,+ title: css`+ flex: none;+ font-weight: 500;+ color: ${cssVar.colorWarning};+ `,+}));++interface UserInterventionFallbackProps {+ actionsPortalTarget?: HTMLDivElement | null;+ apiName: string;+ assistantGroupId?: string;+ identifier: string;+ requestArgs: string;+ toolCallId: string;+ toolMessageId: string;+}++interface UserInterventionErrorBoundaryProps extends UserInterventionFallbackProps {+ children: ReactNode;+}++interface UserInterventionErrorBoundaryState {+ hasError: boolean;+}++const formatRequestArgs = (requestArgs: string) => {+ const parsed = safeParseJSON<unknown>(requestArgs);++ if (parsed === undefined) return requestArgs.trim() || '{}';++ return JSON.stringify(parsed, null, 2);+};++const UserInterventionFallback = memo<UserInterventionFallbackProps>(+ ({+ actionsPortalTarget,+ apiName,+ assistantGroupId,+ identifier,+ requestArgs,+ toolCallId,+ toolMessageId,+ }) => {+ const { t } = useTranslation('chat');+ const approvalMode = useUserStore(toolInterventionSelectors.approvalMode);+ const json = useMemo(() => formatRequestArgs(requestArgs), [requestArgs]);+ const actions = (+ <Flexbox horizontal justify={'flex-end'}>+ <ApprovalActions+ apiName={apiName}+ approvalMode={approvalMode}+ assistantGroupId={assistantGroupId}+ identifier={identifier}+ messageId={toolMessageId}+ toolCallId={toolCallId}+ />+ </Flexbox>+ );++ return (+ <Flexbox gap={8}>+ <div className={styles.notice}>+ <Icon className={styles.icon} icon={AlertTriangle} size={14} />+ <span className={styles.title}>{t('tool.intervention.renderFallback.title')}</span>+ <span className={styles.description}>+ {t('tool.intervention.renderFallback.description')}+ </span>+ </div>+ <Text fontSize={12} type="secondary">+ {identifier} / {apiName} · {t('tool.intervention.renderFallback.rawJson')}+ </Text>+ <Highlighter wrap actionIconSize="small" language="json" variant="borderless">+ {json}+ </Highlighter>+ {actionsPortalTarget ? createPortal(actions, actionsPortalTarget) : actions}+ </Flexbox>+ );+ },+);++UserInterventionFallback.displayName = 'UserInterventionFallback';++class UserInterventionErrorBoundary extends Component<+ UserInterventionErrorBoundaryProps,+ UserInterventionErrorBoundaryState+> {+ public state: UserInterventionErrorBoundaryState = { hasError: false };++ public static getDerivedStateFromError(): UserInterventionErrorBoundaryState {+ return { hasError: true };+ }++ public componentDidCatch(error: Error, errorInfo: ErrorInfo) {+ console.error('[UserInterventionErrorBoundary] Caught error in intervention render:', {+ apiName: this.props.apiName,+ componentStack: errorInfo.componentStack,+ error: error.message,+ identifier: this.props.identifier,+ toolCallId: this.props.toolCallId,+ });+ }++ public render() {+ if (this.state.hasError) {+ return (+ <UserInterventionFallback+ actionsPortalTarget={this.props.actionsPortalTarget}+ apiName={this.props.apiName}+ assistantGroupId={this.props.assistantGroupId}+ identifier={this.props.identifier}+ requestArgs={this.props.requestArgs}+ toolCallId={this.props.toolCallId}+ toolMessageId={this.props.toolMessageId}+ />+ );+ }++ return this.props.children;+ }+}++export default UserInterventionErrorBoundary;