Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 提问卡片自定义回答在截图返回或请求重新拉取后不再丢失 (#6082)
Dash61981d6ecb8e
diff --git a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsxindex af56c1378b..da803eec8f 100644--- a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx+++ b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx@@ -271,6 +271,55 @@ it.each([false, true])('restores the last answer after a rejected receipt and clexpect(readAskUserDraft(requestId)).toBeNull();});+it('keeps a typed custom answer when the pending request is refetched or the card remounts', async () => {+ const pending = () => [{ request: {+ kind: 'ask_user_question', requestId,+ questions: [{ question: 'Spine license?', options: [{ label: 'Yes' }, { label: 'No' }] }],+ } }];+ remoteSessionStore.setPendingInteractions('s1', pending());+ await act(async () => root.render(<Harness />));+ const input = () => host.querySelector<HTMLInputElement>('[data-testid="interaction.ask.customInput"]');+ await click('interaction.ask.showCustomButton');+ await act(async () => {+ input()!.value = 'No, figure it out';+ input()!.dispatchEvent(new Event('input', { bubbles: true }));+ });+ // 回到前台后重新拉取待处理请求:内容相同但对象引用全新。+ await act(async () => remoteSessionStore.setPendingInteractions('s1', pending()));+ expect(input()?.value).toBe('No, figure it out');+ await act(async () => root.render(null));+ await act(async () => root.render(<Harness />));+ expect(input()?.value).toBe('No, figure it out');+});++it('starts over when the same request replaces its questions', async () => {+ const first = { question: 'First?', options: [{ label: 'Yes' }, { label: 'No' }] };+ const second = { question: 'Second?', options: [{ label: 'A' }, { label: 'B' }] };+ remoteSessionStore.setPendingInteractions('s1', [{ request: { kind: 'ask_user_question', requestId, questions: [first, second] } }]);+ await act(async () => root.render(<Harness />));+ const question = () => (host.textContent!.includes('Second?') ? 'Second?' : host.textContent!.includes('First?') ? 'First?' : null);+ const input = () => host.querySelector<HTMLInputElement>('[data-testid="interaction.ask.customInput"]');+ await click('interaction.ask.option.1');+ await click('interaction.ask.submitButton');+ expect(question()).toBe('Second?');+ await click('interaction.ask.showCustomButton');+ await act(async () => {+ input()!.value = 'Old payload answer';+ input()!.dispatchEvent(new Event('input', { bubbles: true }));+ });+ // 同一 requestId 的问题从两道变成一道:旧题号与输入都不能带进新内容。+ await act(async () => remoteSessionStore.setPendingInteractions('s1', [{ request: {+ kind: 'ask_user_question', requestId, questions: [first],+ } }]));+ expect(question()).toBe('First?');+ expect(input()).toBeNull();+ resolveInteraction.mockResolvedValueOnce({ accepted: true });+ await click('interaction.ask.option.2');+ await click('interaction.ask.submitButton');+ expect(resolveInteraction).toHaveBeenCalledTimes(1);+ expect(resolveInteraction.mock.calls[0][1]).toMatchObject({ answers: { 'First?': 'No' } });+});+it.each(['allowOnce', 'deny'])('companion permission preserves complete evidence and %s receipt', async (action) => {const content = 'unique-complete-payload-' + 'x'.repeat(800);diff --git a/apps/mobile/src/__tests__/interactionModel.test.ts b/apps/mobile/src/__tests__/interactionModel.test.tsindex ecd06e3f19..5d69f97279 100644--- a/apps/mobile/src/__tests__/interactionModel.test.ts+++ b/apps/mobile/src/__tests__/interactionModel.test.ts@@ -44,7 +44,7 @@ import {sortPendingInteractions,togglePendingInteractionCollapsed,} from '@/session/interactionModel';-import { clearAskUserDraft, saveAskUserDraft } from '@/session/interactionDraftStore';+import { askQuestionsIdentity, clearAskUserDraft, saveAskUserDraft } from '@/session/interactionDraftStore';import type { PendingInteraction } from '@/session/types';/** prune 的权威性开关:全量快照到手 = 权威;离线清空投影 = 非权威。 */@@ -581,10 +581,12 @@ describe('interactionModel', () => {expect(first.accessibilityLabel).toContain('第一问是什么');// 进入第二问后,读屏念的必须是第二问 —— 这条钉的就是 label 本身,不是渲染代码文本。+ const identity = askQuestionsIdentity(normalizeAskQuestions(item.request.questions));saveAskUserDraft('ask-label-1', {answers: {},currentIndex: 1,customInput: '',+ questionsIdentity: identity,selectedLabels: [],showCustomInput: false,});@@ -596,6 +598,18 @@ describe('interactionModel', () => {expect(second.summaryText).toBe('第二问是什么');expect(second.accessibilityLabel).toContain('第二问是什么');expect(second.accessibilityLabel).not.toContain('第一问是什么');++ // 收起期间同一 requestId 换了问题:旧草稿的进度不能带进新内容,摘要回到第一问。+ const replaced = buildCollapsedPendingInteractionPresentation({+ item: { request: {+ kind: 'ask_user_question',+ requestId: 'ask-label-1',+ questions: [{ question: '新的第一问' }, { question: '新的第二问' }],+ } } as unknown as PendingInteraction,+ queueTitle: '等待回答',+ requestId: 'ask-label-1',+ });+ expect(replaced.summaryText).toBe('新的第一问');clearAskUserDraft('ask-label-1');// 没有专属摘要的卡(手机端答不了的那类)退回队列标题,标签不留空。diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsxindex 4dae68e125..f9ad4fbcc7 100644--- a/apps/mobile/src/session/InteractionPanel.tsx+++ b/apps/mobile/src/session/InteractionPanel.tsx@@ -72,9 +72,10 @@ import {type RemotePluginSetupStep,} from '@/session/interactionModel';import {+ askQuestionsIdentity,clearAskUserDraft,clearPlanReviewDraft,- readAskUserDraft,+ readAskUserDraftFor,readPlanReviewDraft,saveAskUserDraft,savePlanReviewDraft,@@ -916,30 +917,47 @@ function PermissionEvidence({);}-function AskUserQuestionCard({- busy,- item,- onDecision,- touchLayout,-}: {+type AskUserQuestionCardProps = {busy: boolean;item: PendingInteraction;onDecision(decision: Record<string, unknown>): void;touchLayout: InteractionTouchLayout;-}) {+};++function AskUserQuestionCard(props: AskUserQuestionCardProps) {+ const questions = useMemo(() => normalizeAskQuestions(props.item.request.questions), [props.item.request.questions]);+ // 与桌面 AskUserQuestionPrompt 同口径:内容相同的重新拉取保持挂载与输入;+ // 同一 requestId 的问题内容真变了,则重挂并丢弃旧内容的草稿。+ const questionsIdentity = askQuestionsIdentity(questions);+ return <AskUserQuestionForm key={questionsIdentity} {...props} questions={questions} questionsIdentity={questionsIdentity} />;+}++function AskUserQuestionForm({+ busy,+ item,+ onDecision,+ questions,+ questionsIdentity,+ touchLayout,+}: AskUserQuestionCardProps & { questions: AskQuestion[]; questionsIdentity: string }) {const styles = useInteractionStyles();const { colors } = useTheme();const { t, i18n: i18nInstance } = useTranslation();const companion = useContext(CompanionInteractionContext);const requestId = readRequestId(item) ?? '';- const questions = useMemo(() => normalizeAskQuestions(item.request.questions), [item.request.questions]);const draftCompletedRef = useRef(false);- const skipNextQuestionSyncRef = useRef(false);- const [currentIndex, setCurrentIndex] = useState(0);- const [answers, setAnswers] = useState<Record<string, string>>({});- const [selectedLabels, setSelectedLabels] = useState<Set<string>>(new Set());- const [customInput, setCustomInput] = useState('');- const [showCustomInput, setShowCustomInput] = useState(false);+ // 表单按 requestId + 问题内容挂载,草稿在首帧同步恢复,+ // 避免先渲染空状态再被同步 effect 覆盖。+ const [initialDraft] = useState(() => readAskUserDraftFor(requestId, questionsIdentity));+ const [currentIndex, setCurrentIndex] = useState(() =>+ Math.min(initialDraft?.currentIndex ?? 0, Math.max(0, questions.length - 1)));+ const [answers, setAnswers] = useState<Record<string, string>>(() => initialDraft?.answers ?? {});+ const [selectedLabels, setSelectedLabels] = useState<Set<string>>(() => new Set(initialDraft?.selectedLabels ?? []));+ const [customInput, setCustomInput] = useState(() => initialDraft?.customInput ?? '');+ const [showCustomInput, setShowCustomInput] = useState(() => initialDraft?.showCustomInput ?? false);+ // 选中态/自定义输入已对应的题号。只在切题时从 answers 回填:请求被重新拉取+ // (截图后回到前台等)会换掉 current/answers 的引用,不能因此清掉正在输入的内容。+ const syncedIndexRef = useRef(currentIndex);const presentation = useMemo(() => buildAskQuestionReviewPresentation({currentIndex,questions,@@ -947,22 +965,8 @@ function AskUserQuestionCard({const current = presentation.current;useEffect(() => {- draftCompletedRef.current = false;- const draft = readAskUserDraft(requestId);- skipNextQuestionSyncRef.current = !!draft;- setCurrentIndex(Math.min(draft?.currentIndex ?? 0, Math.max(0, questions.length - 1)));- setAnswers(draft?.answers ?? {});- setSelectedLabels(new Set(draft?.selectedLabels ?? []));- setCustomInput(draft?.customInput ?? '');- setShowCustomInput(draft?.showCustomInput ?? false);- }, [questions.length, requestId]);-- useEffect(() => {- if (!current) return;- if (skipNextQuestionSyncRef.current) {- skipNextQuestionSyncRef.current = false;- return;- }+ if (!current || syncedIndexRef.current === currentIndex) return;+ syncedIndexRef.current = currentIndex;const next = selectionFromAnswer({ ...current, options: visibleAskOptions(current.options) },answers[answerKey(current)],@@ -970,7 +974,7 @@ function AskUserQuestionCard({setSelectedLabels(next.selectedLabels);setCustomInput(next.customInput);setShowCustomInput(next.showCustomInput);- }, [answers, current]);+ }, [answers, current, currentIndex]);useEffect(() => {if (!requestId || draftCompletedRef.current) return;@@ -978,6 +982,7 @@ function AskUserQuestionCard({answers,currentIndex,customInput,+ questionsIdentity,selectedLabels: [...selectedLabels],showCustomInput,});@@ -1038,6 +1043,7 @@ function AskUserQuestionCard({saveAskUserDraft(requestId, {answers: nextAnswers, currentIndex,customInput: finalSelection.customInput,+ questionsIdentity,selectedLabels: [...finalSelection.selectedLabels],showCustomInput: finalSelection.showCustomInput,});@@ -1169,7 +1175,6 @@ function AskUserQuestionCard({disabled={busy}onPress={() => {if (!isMulti) {- skipNextQuestionSyncRef.current = true;clearCurrentAnswer();setSelectedLabels(new Set());}diff --git a/apps/mobile/src/session/interactionDraftStore.ts b/apps/mobile/src/session/interactionDraftStore.tsindex a83ef5b26e..a9a4f39679 100644--- a/apps/mobile/src/session/interactionDraftStore.ts+++ b/apps/mobile/src/session/interactionDraftStore.ts@@ -1,7 +1,11 @@+import type { AskQuestion } from '@cindy/maker-shared/interaction';+export interface AskUserDraft {answers: Record<string, string>;currentIndex: number;customInput: string;+ /** 保存草稿时的问题内容;同一 requestId 的问题变了,旧草稿不再恢复。 */+ questionsIdentity?: string;selectedLabels: string[];showCustomInput: boolean;}@@ -20,6 +24,22 @@ export function readAskUserDraft(requestId: string): AskUserDraft | null {return draft ? cloneDraft(draft) : null;}+/** 与桌面 AskUserQuestionPrompt 同口径的问题内容标识(字段顺序固定,缺省 options 等同空)。 */+export function askQuestionsIdentity(questions: AskQuestion[]): string {+ return JSON.stringify(questions.map((question) => [+ question.question,+ question.header,+ question.multiSelect,+ (question.options ?? []).map((option) => [option.label, option.description]),+ ]));+}++/** 只返回与当前问题内容一致的草稿:同一 requestId 的问题变了,旧草稿视为不存在。 */+export function readAskUserDraftFor(requestId: string, questionsIdentity: string): AskUserDraft | null {+ const draft = readAskUserDraft(requestId);+ return draft?.questionsIdentity === questionsIdentity ? draft : null;+}+export function saveAskUserDraft(requestId: string, draft: AskUserDraft): void {if (!requestId) return;askUserDrafts.set(requestId, cloneDraft(draft));@@ -53,6 +73,7 @@ function cloneDraft(draft: AskUserDraft): AskUserDraft {answers: { ...draft.answers },currentIndex: Math.max(0, Math.floor(draft.currentIndex)),customInput: draft.customInput,+ ...(draft.questionsIdentity !== undefined ? { questionsIdentity: draft.questionsIdentity } : {}),selectedLabels: [...draft.selectedLabels],showCustomInput: draft.showCustomInput,};diff --git a/apps/mobile/src/session/interactionModel.ts b/apps/mobile/src/session/interactionModel.tsindex a75f1bc80f..e657a0f400 100644--- a/apps/mobile/src/session/interactionModel.ts+++ b/apps/mobile/src/session/interactionModel.ts@@ -11,7 +11,7 @@ import {type PermissionReviewPresentation,} from '@cindy/maker-shared/interaction';import { i18n } from '@/i18n';-import { readAskUserDraft } from '@/session/interactionDraftStore';+import { askQuestionsIdentity, readAskUserDraftFor } from '@/session/interactionDraftStore';export {answerKey,@@ -216,7 +216,10 @@ export function buildCollapsedPendingInteractionPresentation(input: {requestId: string | null | undefined;}): { accessibilityLabel: string; summaryText: string | null } {const questionIndex = input.requestId- ? readAskUserDraft(input.requestId)?.currentIndex ?? 0+ ? readAskUserDraftFor(+ input.requestId,+ askQuestionsIdentity(sharedNormalizeAskQuestions(input.item.request.questions)),+ )?.currentIndex ?? 0: 0;const summaryText = pendingInteractionSummaryText(input.item, questionIndex);return {