Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): preserve Ask input across turn completion (#4042)
Yuewei-LL6bcea6358d1b
diff --git a/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts b/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.tsindex 9632c71029..6e259f5538 100644--- a/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts+++ b/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts@@ -63,9 +63,10 @@ vi.mock('@/lib/composerDraftStore', () => ({}));import { updateContent as updateMessageContent } from '@/lib/messageService';-import { makerChatStore } from '@/lib/makerChatStore';+import { makerChatStore, type AskUserQuestionItem } from '@/lib/makerChatStore';const SESSION_ID = 'ask-user-done-race';+const getPendingInteractions = vi.fn<() => Promise<unknown[]>>(async () => []);function emptyProjection(sessionId: string) {return {@@ -115,7 +116,7 @@ function installElectronBridge(): void {},send: vi.fn(async () => ({ accepted: true })),generateTitle: vi.fn(async () => ({ title: 't' })),- getPendingInteractions: vi.fn(async () => []),+ getPendingInteractions,setPlanMode: vi.fn(async () => {}),resolveInteraction: vi.fn(async () => ({ accepted: true })),abortSession: vi.fn(async () => {}),@@ -131,13 +132,16 @@ function installElectronBridge(): void {};}-function emitAskUserRequest(requestId: string): void {+function emitAskUserRequest(+ requestId: string,+ questions: AskUserQuestionItem[] = [{ question: '桌面版这次要采用哪种范围?', header: '词典编辑' }],+): void {onInteractionRequest?.({sessionId: SESSION_ID,request: {kind: 'ask_user_question',requestId,- questions: [{ question: '桌面版这次要采用哪种范围?', header: '词典编辑' }],+ questions,},persistId: `persist-${requestId}`,});@@ -164,6 +168,7 @@ function pendingAskStatuses(): string[] {describe('ask_user 与 done 的时序', () => {beforeEach(() => {vi.clearAllMocks();+ getPendingInteractions.mockReset().mockResolvedValue([]);installElectronBridge();makerChatStore.__teardownGlobalListeners();makerChatStore.purgeSession(SESSION_ID);@@ -188,6 +193,71 @@ describe('ask_user 与 done 的时序', () => {expect(pendingAskStatuses()).toEqual(['pending']);});+ it('codex:done 的 Host 快照重放保留答题状态及 questions 引用', async () => {+ makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });+ emitAskUserRequest('ask-replay', [{+ question: 'Pick details',+ header: 'Details',+ multiSelect: true,+ options: [{ label: 'A', description: 'First option' }],+ }]);+ makerChatStore.setAskUserDraft(SESSION_ID, {+ requestId: 'ask-replay', currentIndex: 0, answers: {},+ });+ makerChatStore.setAskUserViewerState(SESSION_ID, 'minimized');+ const before = makerChatStore.getSnapshot(SESSION_ID);+ // A fresh IPC payload, including different object key order, is still the same question.+ const questions: AskUserQuestionItem[] = [{+ options: [{ description: 'First option', label: 'A' }],+ multiSelect: true,+ header: 'Details',+ question: 'Pick details',+ }];+ getPendingInteractions.mockResolvedValue([{+ request: { kind: 'ask_user_question', requestId: 'ask-replay', questions },+ persistId: 'persist-ask-replay',+ }]);++ emitDone('codex');++ // Wait for the actual async snapshot replay, not just the synchronous done reducer.+ await vi.waitFor(() => {+ expect(makerChatStore.getSnapshot(SESSION_ID).messages.find(+ (m) => m.askUserRequestId === 'ask-replay',+ )?.askUserQuestions).toBe(questions);+ });+ const after = makerChatStore.getSnapshot(SESSION_ID);+ // The prompt restores local unsubmitted text/checkboxes whenever questions changes identity.+ expect(after.pendingAskUser).toBe(before.pendingAskUser);+ expect(after.askUserDraft).toBe(before.askUserDraft);+ expect(after.askUserViewerState).toBe('minimized');+ expect(pendingAskStatuses()).toEqual(['pending']);+ });++ it.each([+ ['new request', 'ask-new', [{ question: 'Pick', options: [{ label: 'A' }] }]],+ ['changed question', 'ask-edit', [{ question: 'Different', options: [{ label: 'A' }] }]],+ ['changed option', 'ask-edit', [{ question: 'Pick', options: [{ label: 'B' }] }]],+ ['changed mode', 'ask-edit', [{ question: 'Pick', options: [{ label: 'A' }], multiSelect: true }]],+ ] as const)('%s still initializes a fresh question', (_name, requestId, questions) => {+ emitAskUserRequest('ask-edit', [{ question: 'Pick', options: [{ label: 'A' }] }]);+ makerChatStore.setAskUserDraft(SESSION_ID, {+ requestId: 'ask-edit', currentIndex: 0, answers: {},+ });+ makerChatStore.setAskUserViewerState(SESSION_ID, 'minimized');+ const before = makerChatStore.getSnapshot(SESSION_ID);++ emitAskUserRequest(requestId, questions.map((q) => ({+ ...q, options: q.options.map((option) => ({ ...option })),+ })));++ const after = makerChatStore.getSnapshot(SESSION_ID);+ expect(after.pendingAskUser).not.toBe(before.pendingAskUser);+ expect(after.pendingAskUser?.questions).toEqual(questions);+ expect(after.askUserDraft).toBeNull();+ expect(after.askUserViewerState).toBe('expanded');+ });+it('claude:turn 结束仍将 pending 提问卡标过期', () => {makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'claude-code' });emitAskUserRequest('ask-2');diff --git a/apps/desktop/src/renderer/__tests__/askUserQuestionActionLabels.test.tsx b/apps/desktop/src/renderer/__tests__/askUserQuestionActionLabels.test.tsxindex eb165bc35a..b0ce842ed1 100644--- a/apps/desktop/src/renderer/__tests__/askUserQuestionActionLabels.test.tsx+++ b/apps/desktop/src/renderer/__tests__/askUserQuestionActionLabels.test.tsx@@ -22,6 +22,7 @@ function renderAskUser() {return render(createElement(AskUserQuestionPrompt, {+ sessionId: 'ask-actions',pending,onAnswer,viewerState: 'expanded',diff --git a/apps/desktop/src/renderer/__tests__/askUserQuestionIdentity.test.tsx b/apps/desktop/src/renderer/__tests__/askUserQuestionIdentity.test.tsxnew file mode 100644index 0000000000..85a3a79e2d--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/askUserQuestionIdentity.test.tsx@@ -0,0 +1,157 @@+// @vitest-environment jsdom++import { createElement } from 'react';+import { cleanup, fireEvent, render, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import type { AskUserQuestionItem, PendingAskUser } from '@/lib/makerChatStore';+import { AskUserQuestionPrompt } from '../components/new-chat/AskUserQuestionPrompt';++beforeEach(async () => {+ await i18n.changeLanguage('en');+});++afterEach(() => cleanup());++function makeProps() {+ const pending: PendingAskUser = {+ requestId: 'request-1',+ questions: [+ { question: 'First question', options: [{ label: 'First option' }] },+ {+ question: 'Second question',+ multiSelect: true,+ options: [{ label: 'A' }, { label: 'B' }],+ },+ ],+ };+ return {+ sessionId: 'session-1',+ pending,+ onAnswer: vi.fn(),+ viewerState: 'expanded' as const,+ onViewerStateChange: vi.fn(),+ draft: null,+ onDraftChange: vi.fn(),+ };+}++async function fillBothQuestions(view: ReturnType<typeof render>) {+ fireEvent.click(view.getByText('Type something else…'));+ fireEvent.change(view.getByPlaceholderText('Type your answer…'), {+ target: { value: 'First draft answer' },+ });+ fireEvent.click(view.getByTestId('ask-user-custom-next'));+ await waitFor(() => expect(view.queryByText('Second question')).not.toBeNull());+ await waitFor(() => expect(view.queryByRole('button', { name: /Back/ })).not.toBeNull());+ fireEvent.click(view.getByText('A'));+ fireEvent.click(view.getByText('Type something else…'));+ const input = view.getByPlaceholderText('Type your answer…') as HTMLTextAreaElement;+ fireEvent.change(input, { target: { value: 'Unsubmitted detail' } });+ return input;+}++describe('AskUserQuestionPrompt identity', () => {+ it('keeps text, selections and question progress when the same card is synchronized', async () => {+ const props = makeProps();+ const view = render(createElement(AskUserQuestionPrompt, props));+ const input = await fillBothQuestions(view);++ // The store keeps questions stable for an unchanged Host snapshot. Render+ // the real exported component; the test deliberately supplies no React key.+ view.rerender(createElement(AskUserQuestionPrompt, {+ ...props,+ pending: { ...props.pending },+ }));++ expect(view.getByPlaceholderText('Type your answer…')).toBe(input);+ expect(input.value).toBe('Unsubmitted detail');+ expect(view.queryByText('Second question')).not.toBeNull();+ expect(view.queryByText('2/2')).not.toBeNull();+ fireEvent.click(view.getByRole('button', { name: 'Submit' }));+ expect(props.onAnswer).toHaveBeenCalledWith('request-1', {+ 'First question': 'First draft answer',+ 'Second question': JSON.stringify(['A', 'Unsubmitted detail']),+ });+ });++ it.each([+ { label: 'question text', update: { question: 'Updated second question' } },+ { label: 'options', update: { options: [{ label: 'C' }] } },+ { label: 'selection mode', update: { multiSelect: false } },+ { label: 'header', update: { header: 'Updated header' } },+ { label: 'option description', update: { options: [{ label: 'A', description: 'Updated meaning' }, { label: 'B' }] } },+ { label: 'question count', update: null },+ ])('resets answers when $label changes within the same request', async ({ update }) => {+ const props = makeProps();+ const view = render(createElement(AskUserQuestionPrompt, props));+ const oldInput = await fillBothQuestions(view);+ props.onDraftChange.mockClear();+ const questions: AskUserQuestionItem[] = update+ ? [props.pending.questions[0], { ...props.pending.questions[1], ...update }]+ : [props.pending.questions[0]];++ // The store clears the draft for changed content, even with the same requestId.+ view.rerender(createElement(AskUserQuestionPrompt, {+ ...props,+ pending: { ...props.pending, questions },+ }));++ expect(oldInput.isConnected).toBe(false);+ expect(view.queryByText('First question')).not.toBeNull();+ expect(view.queryByPlaceholderText('Type your answer…')).toBeNull();+ expect(props.onDraftChange).toHaveBeenLastCalledWith({+ requestId: 'request-1', currentIndex: 0, answers: {},+ });++ fireEvent.click(view.getByText('First option'));+ const expectedAnswers: Record<string, string> = { 'First question': 'First option' };+ if (questions.length > 1) {+ const second = questions[1];+ await waitFor(() => expect(view.queryByText(second.question)).not.toBeNull());+ await waitFor(() => expect(view.queryByRole('button', { name: /Back/ })).not.toBeNull());+ const label = second.options![0].label;+ fireEvent.click(view.getByText(label));+ if (second.multiSelect) fireEvent.click(view.getByRole('button', { name: 'Submit' }));+ expectedAnswers[second.question] = second.multiSelect ? JSON.stringify([label]) : label;+ }+ expect(props.onAnswer).toHaveBeenCalledWith('request-1', expectedAnswers);+ });++ it.each([+ { label: 'request', sessionId: 'session-1', requestId: 'request-2' },+ { label: 'session', sessionId: 'session-2', requestId: 'request-1' },+ ])('resets old answers when the $label changes without closing the card', async ({ sessionId, requestId }) => {+ const props = makeProps();+ const view = render(createElement(AskUserQuestionPrompt, props));+ const oldInput = await fillBothQuestions(view);+ props.onDraftChange.mockClear();++ // Even identical question text and array identity must not carry answers+ // into another request/session. A normal close/reopen is not involved.+ view.rerender(createElement(AskUserQuestionPrompt, {+ ...props,+ sessionId,+ pending: { ...props.pending, requestId },+ }));++ expect(oldInput.isConnected).toBe(false);+ expect(view.queryByText('First question')).not.toBeNull();+ expect(view.queryByText('1/2')).not.toBeNull();+ expect(view.queryByPlaceholderText('Type your answer…')).toBeNull();+ expect(props.onDraftChange).toHaveBeenCalledWith({ requestId, currentIndex: 0, answers: {} });++ fireEvent.click(view.getByText('First option'));+ await waitFor(() => expect(view.queryByText('Second question')).not.toBeNull());+ await waitFor(() => expect(view.queryByRole('button', { name: /Back/ })).not.toBeNull());+ expect(view.queryByPlaceholderText('Type your answer…')).toBeNull();+ expect((view.getByRole('button', { name: 'Submit' }) as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(view.getByText('B'));+ fireEvent.click(view.getByRole('button', { name: 'Submit' }));+ expect(props.onAnswer).toHaveBeenCalledWith(requestId, {+ 'First question': 'First option',+ 'Second question': JSON.stringify(['B']),+ });+ });+});diff --git a/apps/desktop/src/renderer/__tests__/askUserQuestionLongAnswer.test.tsx b/apps/desktop/src/renderer/__tests__/askUserQuestionLongAnswer.test.tsxindex 4eeb5b63b1..0ccb83acb5 100644--- a/apps/desktop/src/renderer/__tests__/askUserQuestionLongAnswer.test.tsx+++ b/apps/desktop/src/renderer/__tests__/askUserQuestionLongAnswer.test.tsx@@ -18,6 +18,7 @@ function renderAskUser() {return render(createElement(AskUserQuestionPrompt, {+ sessionId: 'ask-long-answer',pending,onAnswer,viewerState: 'expanded',diff --git a/apps/desktop/src/renderer/__tests__/imeEnterCompositionGuard.test.ts b/apps/desktop/src/renderer/__tests__/imeEnterCompositionGuard.test.tsindex b89fb72e94..7fe6aa8f50 100644--- a/apps/desktop/src/renderer/__tests__/imeEnterCompositionGuard.test.ts+++ b/apps/desktop/src/renderer/__tests__/imeEnterCompositionGuard.test.ts@@ -31,6 +31,7 @@ afterEach(() => {function renderAskUser(pending: PendingAskUser, onAnswer: (requestId: string, answers: Record<string, string>) => void) {return render(createElement(AskUserQuestionPrompt, {+ sessionId: 'ask-ime',pending,onAnswer,viewerState: 'expanded',diff --git a/apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx b/apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsxindex efcbed5f6a..ffa62ac10c 100644--- a/apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx+++ b/apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx@@ -101,6 +101,25 @@ interface AskUserQuestionPromptProps {// ---------------------------------------------------------------------------export function AskUserQuestionPrompt({+ sessionId,+ ...props+}: AskUserQuestionPromptProps & { sessionId: string | undefined }) {+ // Match the store's content comparison, including option order and metadata.+ // Fixed field order avoids treating JSON property order as a new question;+ // absent and empty options are equivalent, as in the reducer.+ const questionsIdentity = props.pending.questions.map((question) => [+ question.question,+ question.header,+ question.multiSelect,+ (question.options ?? []).map((option) => [option.label, option.description]),+ ]);+ const formKey = JSON.stringify([sessionId, props.pending.requestId, questionsIdentity]);+ // Repeated snapshots keep this form mounted. A changed session, request or+ // question starts from its own draft (cleared by the store on content changes).+ return <AskUserQuestionForm key={formKey} {...props} />;+}++function AskUserQuestionForm({pending,onAnswer,viewerState,@@ -120,10 +139,9 @@ export function AskUserQuestionPrompt({// batch — a stale draft from a previous question batch must be ignored.// Note: `requestId` is captured in the lazy initializer closure on first// render; subsequent prop updates do NOT re-run the initializer (that is- // useState's documented behavior). For a brand-new question batch the- // store has already cleared `askUserDraft` to null on the- // `ask_user_question` reducer path, so the lazy init falls through to- // defaults — no stale leak across batches.+ // useState's documented behavior). The public wrapper remounts this form+ // when the session, request or question content changes. For a new or changed+ // question batch the store clears `askUserDraft`, so the form starts fresh.const [currentIndex, setCurrentIndex] = useState<number>(() =>draft && draft.requestId === requestId ? draft.currentIndex : 0,);diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 16a30c9c63..8525bed8d3 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -5025,6 +5025,7 @@ export function CCAgentSessionView({/>) : pendingAskUser ? (<AskUserQuestionPrompt+ sessionId={sessionId}pending={pendingAskUser}onAnswer={answerUserQuestion}viewerState={askUserViewerState}diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex fe5f4b95e4..f69a128475 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -6044,6 +6044,25 @@ export function handleStreamEvent(requestId: string;questions: AskUserQuestionItem[];};+ // Codex done reconciles pending interactions with fresh IPC objects. Keep+ // the same question's identity: AskUserQuestionPrompt restores selections+ // when questions changes, which would erase locally typed, unsubmitted text.+ // Compare fields rather than JSON object key order; changed questions must+ // still take the normal initialization path.+ const previousAsk = state.pendingAskUser;+ const keepAskProgress = previousAsk?.requestId === data.requestId &&+ previousAsk.questions.length === data.questions.length &&+ previousAsk.questions.every((question, index) => {+ const next = data.questions[index];+ return question.question === next.question &&+ question.header === next.header &&+ question.multiSelect === next.multiSelect &&+ (question.options?.length ?? 0) === (next.options?.length ?? 0) &&+ (question.options ?? []).every((option, optionIndex) =>+ option.label === next.options?.[optionIndex]?.label &&+ option.description === next.options?.[optionIndex]?.description,+ );+ });// F1-a: ask_user 消息的落库(+ 在飞 assistant flush)已收口 main// (messagePersistBroadcaster.onInteractionMessage,在 setInteractionListener 里),// renderer 只做 UI:finalize 在飞气泡 + 用 main 下发的 persistId 建 ask_user 气泡@@ -6091,19 +6110,17 @@ export function handleStreamEvent(return {...finalized,- pendingAskUser: {+ pendingAskUser: keepAskProgress ? previousAsk : {requestId: data.requestId,questions: data.questions,},// F-AUQ-MIN-1: Every new pendingAskUser starts expanded — even if the// previous question in this same session was minimized. Folding never// carries across questions.- askUserViewerState: 'expanded',- // F-AUQ-DRAFT: Same logic — a new question batch must never inherit a- // stale draft, even if for some reason the previous draft happened to- // share the same requestId. The component additionally guards via- // `draft.requestId === pending.requestId` before hydrating.- askUserDraft: null,+ askUserViewerState: keepAskProgress ? state.askUserViewerState : 'expanded',+ // Only an unchanged pending request may retain its draft. A new batch+ // or changed question content starts clean, even with the same requestId.+ askUserDraft: keepAskProgress ? state.askUserDraft : null,messages: askMessages,};}