Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(interactions): 保留异步询问输入并支持跨轮次补充回复
Dash5d2cb12cd6b8
diff --git a/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts b/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.tsindex 81cc8371a7..695471a114 100644--- a/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts+++ b/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts@@ -11,6 +11,9 @@ vi.mock('@/lib/messageService', () => ({list: vi.fn(async () => []),create: vi.fn(async () => ({}) as unknown),updateContent: vi.fn(async () => ({}) as unknown),+ aroundClientId: vi.fn(async (_sessionId: string, clientId: string) => [{+ clientId, role: 'ask_user', content: { requestId: 'async-1', status: 'cancelled' },+ }]),}));vi.mock('@/lib/sessionService', () => ({@@ -22,6 +25,7 @@ vi.mock('@/lib/sessionService', () => ({contextTokens: 0,contextWindow: 0,totalCostUsd: 0,+ model: 'test', effort: 'medium', permissionMode: 'ask', workingDir: '/repo',})),update: vi.fn(async () => ({})),touchUserSend: vi.fn(async () => ({})),@@ -64,7 +68,7 @@ vi.mock('@/lib/composerDraftStore', () => ({}),}));-import { updateContent as updateMessageContent } from '@/lib/messageService';+import { aroundClientId, updateContent as updateMessageContent } from '@/lib/messageService';import { makerChatStore, type AskUserQuestionItem } from '@/lib/makerChatStore';const SESSION_ID = 'ask-user-done-race';@@ -101,6 +105,9 @@ function installElectronBridge(): void {input: {getProjection: vi.fn(async (sessionId: string) => emptyProjection(sessionId)),enqueue: vi.fn(async (sessionId: string) => emptyProjection(sessionId)),+ steer: vi.fn(async () => false),+ stop: vi.fn(async (sessionId: string) => ({ ...emptyProjection(sessionId), queuePaused: true })),+ resume: vi.fn(async (sessionId: string) => emptyProjection(sessionId)),},onInputProjection: vi.fn(() => vi.fn()),onEvent: (cb: (data: unknown) => void) => {@@ -137,6 +144,7 @@ function installElectronBridge(): void {function emitAskUserRequest(requestId: string,questions: AskUserQuestionItem[] = [{ question: '桌面版这次要采用哪种范围?', header: '词典编辑' }],+ delivery?: 'async',): void {onInteractionRequest?.({sessionId: SESSION_ID,@@ -144,6 +152,7 @@ function emitAskUserRequest(kind: 'ask_user_question',requestId,questions,+ delivery,},persistId: `persist-${requestId}`,});@@ -183,6 +192,78 @@ describe('ask_user 与 done 的时序', () => {vi.restoreAllMocks();});+ it.each(['codex', 'claude-code', 'pi'] as const)('%s keeps an edited async draft after expiry and replacement, then sends the original question', async (agentKind) => {+ makerChatStore.setSessionRuntime(SESSION_ID, { agentKind });+ emitAskUserRequest('async-1', [{ question: 'Original?' }], 'async');+ const draft = { requestId: 'async-1', currentIndex: 0, answers: {}, started: true, customInput: 'Typing' };+ makerChatStore.setAskUserDraft(SESSION_ID, draft);+ onInteractionDismissed?.({ sessionId: SESSION_ID, requestId: 'async-1', reason: 'turn_completed' });+ emitAskUserRequest('async-2', [{ question: 'New?' }], 'async');+ expect(makerChatStore.getLightSnapshot(SESSION_ID).pendingAskUser?.requestId).toBe('async-1');+ expect(makerChatStore.getLightSnapshot(SESSION_ID).askUserDraft).toBe(draft);+ vi.mocked(window.electronAPI.maker.resolveInteraction).mockResolvedValueOnce({ accepted: false });+ makerChatStore.answerUserQuestion(SESSION_ID, 'async-1', { 'Original?': 'Finished' });+ await vi.waitFor(() => expect(window.electronAPI.maker.input.enqueue).toHaveBeenCalledOnce());+ const queued = vi.mocked(window.electronAPI.maker.input.enqueue).mock.calls[0][1];+ expect(queued.text).toBe('> Original?\n\nFinished');+ expect(makerChatStore.getLightSnapshot(SESSION_ID).pendingAskUser?.requestId).toBe('async-2');+ });++ it('does not protect untouched cards or synchronous drafts', () => {+ emitAskUserRequest('untouched', [{ question: 'Q?' }], 'async');+ makerChatStore.setAskUserDraft(SESSION_ID, { requestId: 'untouched', currentIndex: 0, answers: {} });+ onInteractionDismissed?.({ sessionId: SESSION_ID, requestId: 'untouched', reason: 'turn_completed' });+ expect(makerChatStore.getLightSnapshot(SESSION_ID).pendingAskUser).toBeNull();+ emitAskUserRequest('sync');+ makerChatStore.setAskUserDraft(SESSION_ID, { requestId: 'sync', currentIndex: 0, answers: {}, started: true });+ onInteractionDismissed?.({ sessionId: SESSION_ID, requestId: 'sync', reason: 'session_closed' });+ expect(makerChatStore.getLightSnapshot(SESSION_ID).pendingAskUser).toBeNull();+ });++ it.each(['close', 'stop', 'accepted-elsewhere', 'unknown'] as const)('handles protected reply boundaries: %s', async (action) => {+ emitAskUserRequest('async-1', [{ question: 'Original?' }], 'async');+ makerChatStore.setAskUserDraft(SESSION_ID, { requestId: 'async-1', currentIndex: 0, answers: {}, started: true });+ if (action === 'stop') {+ makerChatStore.stopSession(SESSION_ID);+ await vi.waitFor(() => expect(makerChatStore.getLightSnapshot(SESSION_ID).pendingAskUser?.resumeOnSubmit).toBe(true));+ vi.mocked(window.electronAPI.maker.input.enqueue).mockResolvedValueOnce({ ...emptyProjection(SESSION_ID), queuePaused: true } as never);+ } else {+ onInteractionDismissed?.({ sessionId: SESSION_ID, requestId: 'async-1', reason: 'turn_completed' });+ }+ vi.mocked(window.electronAPI.maker.resolveInteraction).mockResolvedValueOnce({ accepted: false });+ if (action === 'accepted-elsewhere' || action === 'unknown') {+ vi.mocked(aroundClientId).mockResolvedValueOnce([{+ clientId: 'persist-async-1', role: 'ask_user', content: {+ requestId: 'async-1', status: action === 'unknown' ? 'pending' : 'answered',+ },+ }] as never);+ }+ makerChatStore.answerUserQuestion(SESSION_ID, 'async-1', action === 'close' ? {} : { 'Original?': 'Finished' });+ if (action === 'unknown') {+ await vi.waitFor(() => expect(aroundClientId).toHaveBeenCalled());+ expect(makerChatStore.getLightSnapshot(SESSION_ID).pendingAskUser?.requestId).toBe('async-1');+ } else {+ await vi.waitFor(() => expect(makerChatStore.getLightSnapshot(SESSION_ID).pendingAskUser).toBeNull());+ }+ expect(window.electronAPI.maker.input.enqueue).toHaveBeenCalledTimes(action === 'stop' ? 1 : 0);+ expect(window.electronAPI.maker.input.resume).toHaveBeenCalledTimes(action === 'stop' ? 1 : 0);+ });++ it('keeps the same delivery ID when a supplemental receipt is lost and retried', async () => {+ emitAskUserRequest('async-1', [{ question: 'Original?' }], 'async');+ makerChatStore.setAskUserDraft(SESSION_ID, { requestId: 'async-1', currentIndex: 0, answers: {}, started: true });+ onInteractionDismissed?.({ sessionId: SESSION_ID, requestId: 'async-1', reason: 'turn_completed' });+ vi.mocked(window.electronAPI.maker.resolveInteraction).mockResolvedValue({ accepted: false });+ vi.mocked(window.electronAPI.maker.input.enqueue).mockRejectedValueOnce(new Error('lost receipt'));+ makerChatStore.answerUserQuestion(SESSION_ID, 'async-1', { 'Original?': 'Finished' });+ await vi.waitFor(() => expect(window.electronAPI.maker.input.enqueue).toHaveBeenCalledOnce());+ expect(makerChatStore.getLightSnapshot(SESSION_ID).pendingAskUser?.requestId).toBe('async-1');+ makerChatStore.answerUserQuestion(SESSION_ID, 'async-1', { 'Original?': 'Finished' });+ await vi.waitFor(() => expect(window.electronAPI.maker.input.enqueue).toHaveBeenCalledTimes(2));+ const calls = vi.mocked(window.electronAPI.maker.input.enqueue).mock.calls;+ expect(calls[0][1].clientId).toBe(calls[1][1].clientId);+ });+it('codex:done 不吞掉未答提问卡', () => {makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });emitAskUserRequest('ask-1');diff --git a/apps/desktop/src/renderer/__tests__/askUserQuestionIdentity.test.tsx b/apps/desktop/src/renderer/__tests__/askUserQuestionIdentity.test.tsxindex 85a3a79e2d..5dbc897f83 100644--- a/apps/desktop/src/renderer/__tests__/askUserQuestionIdentity.test.tsx+++ b/apps/desktop/src/renderer/__tests__/askUserQuestionIdentity.test.tsx@@ -53,6 +53,32 @@ async function fillBothQuestions(view: ReturnType<typeof render>) {}describe('AskUserQuestionPrompt identity', () => {+ it('starts protection on IME composition, but not focus or opening the text field', () => {+ const props = makeProps();+ const view = render(createElement(AskUserQuestionPrompt, props));+ fireEvent.click(view.getByText('Type something else…'));+ const input = view.getByPlaceholderText('Type your answer…');+ fireEvent.focus(input);+ expect(props.onDraftChange.mock.lastCall?.[0]?.started).not.toBe(true);+ fireEvent.compositionStart(input);+ expect(props.onDraftChange.mock.lastCall?.[0]?.started).toBe(true);+ fireEvent.change(input, { target: { value: '正在输入' } });+ fireEvent.change(input, { target: { value: '' } });+ fireEvent.blur(input);+ expect(props.onDraftChange.mock.lastCall?.[0]).toMatchObject({ started: true, customInput: '' });+ });++ it('restores an unfinished field after leaving and returning to the task', () => {+ const props = makeProps();+ const view = render(createElement(AskUserQuestionPrompt, props));+ fireEvent.click(view.getByText('Type something else…'));+ fireEvent.change(view.getByPlaceholderText('Type your answer…'), { target: { value: 'Not finished' } });+ const draft = props.onDraftChange.mock.lastCall?.[0];+ view.unmount();+ const restored = render(createElement(AskUserQuestionPrompt, { ...props, draft }));+ expect((restored.getByPlaceholderText('Type your answer…') as HTMLTextAreaElement).value).toBe('Not finished');+ });+it('keeps text, selections and question progress when the same card is synchronized', async () => {const props = makeProps();const view = render(createElement(AskUserQuestionPrompt, props));@@ -103,6 +129,7 @@ describe('AskUserQuestionPrompt identity', () => {expect(view.queryByPlaceholderText('Type your answer…')).toBeNull();expect(props.onDraftChange).toHaveBeenLastCalledWith({requestId: 'request-1', currentIndex: 0, answers: {},+ started: false, customInput: '', selectedLabels: [], showCustomInput: false,});fireEvent.click(view.getByText('First option'));@@ -140,7 +167,8 @@ describe('AskUserQuestionPrompt identity', () => {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: {} });+ expect(props.onDraftChange).toHaveBeenCalledWith({ requestId, currentIndex: 0, answers: {},+ started: false, customInput: '', selectedLabels: [], showCustomInput: false });fireEvent.click(view.getByText('First option'));await waitFor(() => expect(view.queryByText('Second question')).not.toBeNull());diff --git a/apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx b/apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsxindex 8ae7fe2294..be096c5871 100644--- a/apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx+++ b/apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx@@ -153,10 +153,18 @@ function AskUserQuestionForm({draft && draft.requestId === requestId ? draft.answers : {},);// Multi-select: set of selected labels for current question- const [selectedLabels, setSelectedLabels] = useState<Set<string>>(new Set());+ const [selectedLabels, setSelectedLabels] = useState<Set<string>>(() => new Set(draft?.selectedLabels ?? []));// Custom input- const [customInput, setCustomInput] = useState('');- const [showCustomInput, setShowCustomInput] = useState(false);+ const [customInput, setCustomInput] = useState(draft?.customInput ?? '');+ const [showCustomInput, setShowCustomInput] = useState(draft?.showCustomInput ?? false);+ const startedRef = useRef(draft?.started === true);+ const draftRef = useRef<AskUserDraft>({ requestId, currentIndex, answers });+ draftRef.current = { requestId, currentIndex, answers, customInput, showCustomInput,+ selectedLabels: [...selectedLabels], started: startedRef.current };+ const markStarted = useCallback(() => {+ startedRef.current = true;+ onDraftChange({ ...draftRef.current, started: true });+ }, [onDraftChange]);const cardRef = useRef<HTMLElement | null>(null);const setCardNode = useCallback((node: HTMLElement | null) => {cardRef.current = node;@@ -220,25 +228,20 @@ function AskUserQuestionForm({);// ── Restore multi-select state when navigating back ──+ const restoredIndexRef = useRef(currentIndex);useEffect(() => {+ if (draft?.customInput !== undefined && restoredIndexRef.current === currentIndex) return;+ restoredIndexRef.current = currentIndex;const result = computeSelectionForIndex(currentIndex, answers);setSelectedLabels(result.labels);setCustomInput(result.custom);setShowCustomInput(result.showCustom);}, [currentIndex, computeSelectionForIndex, answers]);- // ── F-AUQ-DRAFT: write wizard progress back to the per-session store on- // every change so a session-switch unmount doesn't lose it. The store has- // an equality short-circuit (same requestId + currentIndex + answers- // identity) so the first effect run after a hydrating mount is a no-op- // (we initialized from the very same draft object). Derived state- // (selectedLabels / customInput / showCustomInput) is intentionally NOT- // persisted — `computeSelectionForIndex` rebuilds it from `answers` on- // mount via the effect above, so persisting it would create a second- // source of truth that could drift. ──+ // Save the unfinished field as well as completed answers across unmounts.useEffect(() => {- onDraftChange({ requestId, currentIndex, answers });- }, [requestId, currentIndex, answers, onDraftChange]);+ onDraftChange(draftRef.current);+ }, [requestId, currentIndex, answers, customInput, selectedLabels, showCustomInput, onDraftChange]);// ── Snapshot current buttons before animation starts ──const snapshotButtons = useCallback(() => {@@ -274,12 +277,12 @@ function AskUserQuestionForm({<div className={skipClass}>{t('chat.askUserQuestion.skip')}</div>{showNext && (<div className={nextClass}>- {isLastQuestion ? t('chat.askUserQuestion.submit') : t('chat.askUserQuestion.next')}+ {isLastQuestion ? t(pending.resumeOnSubmit ? 'chat.askUserQuestion.sendAndContinue' : 'chat.askUserQuestion.submit') : t('chat.askUserQuestion.next')}</div>)}</>);- }, [currentIndex, isMultiSelect, isLastQuestion, existingAnswer, selectedLabels, customInput, t]);+ }, [currentIndex, isMultiSelect, isLastQuestion, existingAnswer, selectedLabels, customInput, pending.resumeOnSubmit, t]);// ── Advance to next question or submit all ──const advance = useCallback(@@ -324,20 +327,22 @@ function AskUserQuestionForm({// ── Single-select: click option -> advance ──const handleSingleSelect = useCallback((label: string) => {+ markStarted();advance(label);},- [advance],+ [advance, markStarted],);// ── Multi-select: toggle checkbox ──const handleToggle = useCallback((label: string) => {+ markStarted();setSelectedLabels((prev) => {const next = new Set(prev);if (next.has(label)) next.delete(label);else next.add(label);return next;});- }, []);+ }, [markStarted]);// ── Multi-select: Next button → encode as JSON array string ──const handleNext = useCallback(() => {@@ -483,6 +488,12 @@ function AskUserQuestionForm({const footerActions = (<div className="flex gap-2.5">+ {pending.delivery === 'async' && startedRef.current && (+ <Button variant="secondary" palette="confirmation" size="lg" compact+ type="button" onClick={() => onAnswer(requestId, {})}>+ {t('chat.askUserQuestion.close')}+ </Button>+ )}{isAnimating ? (buttonsSnapshotRef.current) : (@@ -535,7 +546,7 @@ function AskUserQuestionForm({: existingAnswer === undefined}>- {isLastQuestion ? t('chat.askUserQuestion.submit') : t('chat.askUserQuestion.next')}+ {isLastQuestion ? t(pending.resumeOnSubmit ? 'chat.askUserQuestion.sendAndContinue' : 'chat.askUserQuestion.submit') : t('chat.askUserQuestion.next')}</Button>)}</>@@ -581,7 +592,8 @@ function AskUserQuestionForm({<AutoGrowingAnswerTextareatextareaRef={inputRef}value={customInput}- onChange={(e) => setCustomInput(e.target.value)}+ onCompositionStart={markStarted}+ onChange={(e) => { markStarted(); setCustomInput(e.target.value); }}onKeyDown={(e) => {if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {e.preventDefault();@@ -620,7 +632,7 @@ function AskUserQuestionForm({)}>{isLastQuestion ? (- t('chat.askUserQuestion.submit')+ t(pending.resumeOnSubmit ? 'chat.askUserQuestion.sendAndContinue' : 'chat.askUserQuestion.submit')) : (<ArrowRight size={15} strokeWidth={2} aria-hidden="true" />)}@@ -773,7 +785,8 @@ function AskUserQuestionForm({<AutoGrowingAnswerTextareatextareaRef={inputRef}value={customInput}- onChange={(e) => setCustomInput(e.target.value)}+ onCompositionStart={markStarted}+ onChange={(e) => { markStarted(); setCustomInput(e.target.value); }}onKeyDown={(e) => {if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {e.preventDefault();@@ -808,7 +821,7 @@ function AskUserQuestionForm({)}>{isLastQuestion ? (- t('chat.askUserQuestion.submit')+ t(pending.resumeOnSubmit ? 'chat.askUserQuestion.sendAndContinue' : 'chat.askUserQuestion.submit')) : (<ArrowRight size={17} strokeWidth={2} aria-hidden="true" />)}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 29d0366fd0..a447117329 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -10781,6 +10781,8 @@"skip": "Skip","next": "Next","submit": "Submit",+ "sendAndContinue": "Send and continue",+ "close": "Close","customAnswer": "Type something else…","answerPlaceholder": "Type your answer…"},diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex a3cfedc0ac..59cb1c7c6e 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -10737,6 +10737,8 @@"skip": "スキップ","next": "次へ","submit": "送信",+ "sendAndContinue": "送信して続行",+ "close": "閉じる","customAnswer": "別の回答を入力…","answerPlaceholder": "回答を入力…"},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 70a398cc63..48c2b24554 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -10737,6 +10737,8 @@"skip": "건너뛰기","next": "다음","submit": "제출",+ "sendAndContinue": "보내고 계속",+ "close": "닫기","customAnswer": "다른 답변 입력…","answerPlaceholder": "답변을 입력하세요…"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 9f64ca372a..48cfd9ffe7 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -10737,6 +10737,8 @@"skip": "跳过","next": "下一题","submit": "提交",+ "sendAndContinue": "发送并继续",+ "close": "关闭","customAnswer": "输入其他回答…","answerPlaceholder": "请输入回答…"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex fa576e1ee5..bc1eebe33d 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -10736,6 +10736,8 @@"skip": "跳過","next": "下一題","submit": "提交",+ "sendAndContinue": "傳送並繼續",+ "close": "關閉","customAnswer": "輸入其他回答…","answerPlaceholder": "請輸入回答…"},diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex c7888c3530..3d9fb20c98 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -1,4 +1,5 @@import { readBotTaskResults } from '@cindy/maker-shared/botCollaboration';+import { asyncQuestionNeedsSupplement, formatAsyncQuestionSupplement } from '@cindy/maker-shared/interaction';import { readTokenSpeedSnapshot, type TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';import { remotePluginSetupErrorCode, type PluginSetupCommandError } from './pluginSetupCommandError';export type { PluginSetupCommandError } from './pluginSetupCommandError';@@ -773,6 +774,9 @@ export interface PendingPermission {export interface PendingAskUser {requestId: string;questions: AskUserQuestionItem[];+ delivery?: 'async';+ persistId?: string;+ resumeOnSubmit?: boolean;}export type PluginSetupAction = GhostSetupAllowedAction;@@ -857,6 +861,10 @@ export interface AskUserDraft {requestId: string;currentIndex: number;answers: Record<string, string>;+ started?: boolean;+ customInput?: string;+ selectedLabels?: string[];+ showCustomInput?: boolean;}/** FP-3: Pending plan-review data for the Plan Viewer Card. */@@ -2444,6 +2452,7 @@ function cancelRemoteOptimisticSendsForRemoteClear(queueAbortPending: false,queueInteractionLocks: [],queueEditLocks: [],+ protectedAskUser: opts.historicalHydration ? state.protectedAskUser : undefined,};});}@@ -2688,6 +2697,8 @@ export interface SessionChatState {* See AskUserDraft typedef for the staleness contract.*/askUserDraft: AskUserDraft | null;+ /** Local editing survives provider dismissal; it is not a pending Host interaction. */+ protectedAskUser?: { pending: PendingAskUser; draft: AskUserDraft };/** FP-3: Currently pending plan-review; null when none. */pendingPlanReview: PendingPlanReview | null;/** issue_confirm: 提交 GitHub issue 前的确认卡片; null when none. */@@ -3691,6 +3702,7 @@ function _isSessionBusy(sessionId: string, s: SessionChatState): boolean {hasBackgroundAgentWork(sessionId, s) ||s.pendingPermission ||s.pendingAskUser ||+ s.protectedAskUser ||hasPendingPluginSetupInteraction(s.pendingPluginSetup, s.pendingPluginSetupQueue) ||s.pendingPlanReview ||s.pendingIssueConfirm ||@@ -3819,7 +3831,6 @@ function updateIslandsAfterAroundMerge(// 块完全落在主段更老一侧:与既有孤岛合并(经块连通的孤岛合并成一座)或新建一座。let mergedOldestClientId: string | null = null;let mergedNewestClientId: string | null = null;- let mergedAny = false;const next: LoadedWindowIsland[] = [];for (const island of islands) {const oldestIdx = messageIndexByClientId(messages, island.oldestClientId);@@ -3830,7 +3841,6 @@ function updateIslandsAfterAroundMerge(next.push(island);continue;}- mergedAny = true;if (mergedOldestClientId === null || oldestIdx < blockStart) {mergedOldestClientId = island.oldestClientId;}@@ -4156,8 +4166,7 @@ function persistTurnErrorDeferredTracked(): void {// 必须在 live error 已经 setState 之后调用,这样抓到的是这一代横幅的 epoch。const epoch = _liveErrorEpoch.get(sessionId) ?? 0;- let pending: Promise<string | undefined>;- pending = makerApiFor(sessionId)+ const pending: Promise<string | undefined> = makerApiFor(sessionId).input.persistTurnErrorDeferred(sessionId, errData, agentMeta).then((persistId) => {const id = typeof persistId === 'string' && persistId ? persistId : undefined;@@ -6656,6 +6665,7 @@ export function handleStreamEvent(}if (state.pendingAskUser?.requestId === data.requestId ||+ state.protectedAskUser?.pending.requestId === data.requestId ||state.messages.some((m) => m.role === 'ask_user' && m.askUserRequestId === data.requestId)) {// resolved + answers → 翻成 answered 并填答案(与答题端 answerUserQuestion 同款 reply / answers,@@ -6666,6 +6676,8 @@ export function handleStreamEvent(const askUserReply = answers && !dismissed ? formatAskUserReply(answers) : '';return {...state,+ protectedAskUser: data.reason === 'resolved' && !dismissed && state.protectedAskUser?.pending.requestId === data.requestId+ ? undefined : state.protectedAskUser,pendingAskUser:state.pendingAskUser?.requestId === data.requestId ? null : state.pendingAskUser,askUserViewerState:@@ -6728,6 +6740,7 @@ export function handleStreamEvent(const data = event.data as {requestId: string;questions: AskUserQuestionItem[];+ delivery?: 'async';};// Codex done reconciles pending interactions with fresh IPC objects. Keep// the same question's identity: AskUserQuestionPrompt restores selections@@ -6798,6 +6811,8 @@ export function handleStreamEvent(pendingAskUser: keepAskProgress ? previousAsk : {requestId: data.requestId,questions: data.questions,+ delivery: data.delivery,+ persistId: event.persistId,},// F-AUQ-MIN-1: Every new pendingAskUser starts expanded — even if the// previous question in this same session was minimized. Folding never@@ -8467,10 +8482,11 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {}if (request.kind === 'ask_user_question') {- const data: CCAgentAskUserQuestionPayload = {+ const data: CCAgentAskUserQuestionPayload & { delivery?: 'async' } = {sessionId,requestId: request.requestId,questions: request.questions as CCAgentAskUserQuestionPayload['questions'],+ ...(request.delivery === 'async' ? { delivery: 'async' as const } : {}),};setState(sessionId, (s) =>handleStreamEvent(s, { sessionId, type: 'ask_user_question', data, persistId }),@@ -9703,6 +9719,19 @@ function subscribe(sessionId: string, cb: () => void): () => void {};}+const resumeQuestionPresentations = new WeakMap<PendingAskUser, PendingAskUser>();+function visibleAskUser(state: SessionChatState): PendingAskUser | null {+ const pending = state.protectedAskUser?.pending;+ if (!pending) return state.pendingAskUser;+ if (state.agentStatus.isRunning && !state.turnStoppedByUser && !state.queuePaused) return pending;+ let presentation = resumeQuestionPresentations.get(pending);+ if (!presentation) {+ presentation = { ...pending, resumeOnSubmit: true };+ resumeQuestionPresentations.set(pending, presentation);+ }+ return presentation;+}+function selectLightState(state: SessionChatState): SessionChatLightState {return {agentSwitchIntent: state.agentSwitchIntent,@@ -9727,15 +9756,15 @@ function selectLightState(state: SessionChatState): SessionChatLightState {historyWindowHasIsland: state.historyWindowIslands.length > 0,isFirstMessage: state.isFirstMessage,historyLoaded: state.historyLoaded,- pendingPermission: state.pendingPermission,- pendingAskUser: state.pendingAskUser,+ pendingPermission: state.protectedAskUser ? null : state.pendingPermission,+ pendingAskUser: visibleAskUser(state),pendingPluginSetup: state.pendingPluginSetup,pluginSetupViewerState: state.pluginSetupViewerState,pluginSetupCommandInFlight: state.pluginSetupCommandInFlight,pluginSetupCommandError: state.pluginSetupCommandError,askUserViewerState: state.askUserViewerState,- askUserDraft: state.askUserDraft,- pendingPlanReview: state.pendingPlanReview,+ askUserDraft: state.protectedAskUser?.draft ?? state.askUserDraft,+ pendingPlanReview: state.protectedAskUser ? null : state.pendingPlanReview,pendingIssueConfirm: state.pendingIssueConfirm,pendingInputHandoff: state.pendingInputHandoff,pendingRenameSessionsConfirm: state.pendingRenameSessionsConfirm,@@ -11180,8 +11209,9 @@ async function pumpRemoteOptimisticSends(sessionId: string): Promise<void> {if (existing) return existing;// Self-reference is intentional: a detached clear/owner generation must not// keep draining after a newer pump replaces this Promise in the registry.- // eslint-disable-next-line prefer-constlet run!: Promise<void>;+ // TypeScript needs definite assignment for the async closure's self-reference.+ // eslint-disable-next-line prefer-construn = (async () => {while (true) {const record = firstUnacceptedRemoteOptimisticSend(sessionId);@@ -16219,6 +16249,7 @@ async function clearSessionAfterGuardImpl(sessionId: string, clearedAt: string):askUserViewerState: 'expanded',// F-AUQ-DRAFT: Clear session also wipes any in-progress draft.askUserDraft: null,+ protectedAskUser: undefined,pendingPlanReview: null,pendingIssueConfirm: null,pendingInputHandoff: null,@@ -16504,6 +16535,11 @@ function answerUserQuestion(answers: Record<string, string>,): void {if (!sessionId) return;+ const state = getOrCreateState(sessionId);+ if (state.protectedAskUser?.pending.requestId === requestId) {+ void sendProtectedQuestionSupplement(sessionId, requestId, answers);+ return;+ }if (getOrCreateState(sessionId).pendingAskUser?.requestId !== requestId) return;const submittedAnswers = { ...answers };const replySummary = formatAskUserReply(submittedAnswers);@@ -16511,6 +16547,7 @@ function answerUserQuestion(kind: 'ask_user_question', answers: submittedAnswers,}, () => setState(sessionId, (s) => ({...s,+ protectedAskUser: s.protectedAskUser?.pending.requestId === requestId ? undefined : s.protectedAskUser,pendingAskUser: s.pendingAskUser?.requestId === requestId ? null : s.pendingAskUser,askUserViewerState: s.pendingAskUser?.requestId === requestId ? 'expanded' : s.askUserViewerState,askUserDraft: s.pendingAskUser?.requestId === requestId ? null : s.askUserDraft,@@ -16524,6 +16561,94 @@ function answerUserQuestion(// local sessions. A late renderer write must not overwrite a winning decision.}+/** Expired async questions are submitted through the ordinary, idempotent user-input path. */+async function sendProtectedQuestionSupplement(sessionId: string, requestId: string, answers: Record<string, string>): Promise<void> {+ const state = getOrCreateState(sessionId);+ const protectedQuestion = state.protectedAskUser;+ if (protectedQuestion?.pending.requestId !== requestId) return;+ const text = formatAsyncQuestionSupplement(protectedQuestion.pending.questions, answers);+ const clear = () => setState(sessionId, (s) => s.protectedAskUser?.pending.requestId === requestId+ ? { ...s, protectedAskUser: undefined } : s);+ const key = `${sessionId}:${requestId}:supplement`;+ if (questionDecisionsInFlight.has(key)) return;+ questionDecisionsInFlight.add(key);+ const owner = getDataOwnerGeneration();+ const epoch = _messagesEpoch.get(sessionId) ?? 0;+ const authority = _inputProjectionAuthorityEpoch.get(sessionId) ?? 0;+ const origin = getStickySessionDeviceId(sessionId);+ const current = () => isDataOwnerGenerationCurrent(owner) &&+ (_messagesEpoch.get(sessionId) ?? 0) === epoch &&+ (_inputProjectionAuthorityEpoch.get(sessionId) ?? 0) === authority && getStickySessionDeviceId(sessionId) === origin &&+ sessions.get(sessionId)?.protectedAskUser?.pending.requestId === requestId;+ try {+ const needsSupplement = await asyncQuestionNeedsSupplement(+ () => makerApiFor(sessionId).resolveInteraction(requestId, { kind: 'ask_user_question', answers }),+ async () => {+ if (!current()) return undefined;+ const persistId = protectedQuestion.pending.persistId;+ if (!persistId) return undefined;+ const rows = origin+ ? await aroundMessagesByClientIdForDevice(origin, sessionId, persistId, { radius: 0 })+ : await aroundMessagesByClientIdFor(sessionId, persistId, { radius: 0 });+ return rows.find((row) => row.clientId === persistId && row.role === 'ask_user')?.content;+ }, requestId,+ );+ if (!current()) return;+ if (!needsSupplement) {+ setState(sessionId, (s) => ({ ...s, protectedAskUser: undefined,+ pendingAskUser: s.pendingAskUser?.requestId === requestId ? null : s.pendingAskUser,+ askUserDraft: s.askUserDraft?.requestId === requestId ? null : s.askUserDraft,+ }));+ return;+ }+ if (!text) { clear(); return; }+ const session = await getSessionFor(sessionId);+ // Exact retries share an ID; an edited answer is a new supplemental input.+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));+ const answerId = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');+ if (!current()) return;+ const queued = buildQueuedMessage(sessionId, text, session.model, session.effort,+ session.permissionMode, session.workingDir ?? '', undefined, undefined, undefined,+ { clientId: `question-reply:${requestId}:${answerId}`, createdAt: new Date().toISOString() });+ queued.createOpts = { ...queued.createOpts, planMode: false,+ agentKind: dbAgentKindToMakerKind(session.agentKind, state.agentKind),+ ...(session.sdkSessionId ? { resumeSessionId: session.sdkSessionId } : {}),+ ...(session.remoteHostId ? { remoteHostId: session.remoteHostId } : {}),+ };+ const operation = beginInputProjectionOperation(sessionId, origin);+ // A false steer is a definite rejection. An exception/unknown receipt must+ // never cause a second delivery through enqueue.+ if (state.agentStatus.isRunning && !state.turnStoppedByUser) {+ const steered = await operation.api.input.steer(sessionId, queued, {+ touchUserSend: true, ...getRemoteInputClearBoundaryOpts(sessionId),+ });+ if (steered === true) {+ if (current()) clear();+ return;+ }+ if (steered !== false) throw new Error('Supplement receipt unavailable');+ }+ if (!current()) return;+ let projection = await operation.api.input.enqueue(sessionId, queued, {+ sendAtMs: Date.now(), ...getRemoteInputClearBoundaryOpts(sessionId),+ });+ if (!current()) return;+ if (projection.queuePaused && (state.turnStoppedByUser || state.queuePaused)) {+ projection = await operation.api.input.resume(sessionId, getRemoteInputClearBoundaryOpts(sessionId));+ }+ if (!current()) return;+ applyInputProjectionOperationResponse(sessionId, operation, projection);+ clear();+ } catch (error) {+ if (current()) {+ log.warn('Async question supplement was not confirmed', error);+ toast.warning(i18n.t('newChat.permissionPrompt.submissionFailed'));+ }+ } finally {+ questionDecisionsInFlight.delete(key);+ }+}+function respondToPluginSetup(sessionId: string,requestId: string,@@ -17171,17 +17296,24 @@ function setPluginSetupViewerState(sessionId: string, next: PluginSetupViewerStafunction setAskUserDraft(sessionId: string, next: AskUserDraft | null): void {if (!sessionId) return;setState(sessionId, (s) => {- const prev = s.askUserDraft;+ const prev = s.protectedAskUser?.draft ?? s.askUserDraft;if (prev === next) return s;if (prev &&next &&prev.requestId === next.requestId &&prev.currentIndex === next.currentIndex &&- prev.answers === next.answers+ prev.answers === next.answers &&+ prev.started === next.started && prev.customInput === next.customInput &&+ prev.showCustomInput === next.showCustomInput &&+ JSON.stringify(prev.selectedLabels) === JSON.stringify(next.selectedLabels)) {return s;}+ const pending = s.protectedAskUser?.pending ?? s.pendingAskUser;+ if (next && pending?.requestId === next.requestId && pending.delivery === 'async' && next.started) {+ return { ...s, protectedAskUser: { pending, draft: next } };+ }return { ...s, askUserDraft: next };});}diff --git a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsxindex da803eec8f..464f432b17 100644--- a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx+++ b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx@@ -11,6 +11,10 @@ import { clearAllInteractionDrafts, readAskUserDraft, readPlanReviewDraft } fromimport { forwardNavigationLock } from '@/utils/navigationLock';const { resolveInteraction, invoke, push } = vi.hoisted(() => ({ resolveInteraction: vi.fn(), invoke: vi.fn(), push: vi.fn() }));+const asyncReply = vi.hoisted(() => ({+ getSession: vi.fn(), aroundMessagesByClientId: vi.fn(),+ input: { steer: vi.fn(), enqueue: vi.fn(), resume: vi.fn() },+}));const { routeParams } = vi.hoisted(() => ({ routeParams: {} as { deviceId?: string; sessionId?: string } }));const { textLayouts } = vi.hoisted(() => ({ textLayouts: new Map<string, (event: { nativeEvent: { lines: unknown[] } }) => void>() }));vi.mock('expo-router', async () => {@@ -21,7 +25,7 @@ vi.mock('expo-router', async () => {});vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ invoke }) }));vi.mock('@/device-link/useMobileMakerTransport', () => ({- useMobileMakerTransport: () => ({ resolveInteraction }),+ useMobileMakerTransport: () => ({ resolveInteraction, ...asyncReply }),}));// 代输入 card has its own tests; its native modules (clipboard, secure store) are out of scope here.vi.mock('@/inputHandoff/InputHandoffCard', () => ({ InputHandoffCard: () => null }));@@ -96,6 +100,68 @@ async function type(id: string, value: string) {});}+it.each(['send', 'close', 'stopped', 'stopped-empty', 'already-answered', 'unconfirmed', 'unknown-steer'])('retains edited async answers across expiry and new questions: %s', async (action) => {+ remoteSessionStore.setPendingInteractions('s1', [{+ persistId: 'original-row',+ request: { kind: 'ask_user_question', requestId, delivery: 'async', questions: [{ question: 'Original?' }] },+ }]);+ await act(async () => root.render(<Harness />));+ await type('interaction.ask.textInput', 'Writing');+ await type('interaction.ask.textInput', '');+ const input = host.querySelector('[data-testid="interaction.ask.textInput"]');+ await act(async () => remoteSessionStore.setPendingInteractions('s1', [{+ request: { kind: 'ask_user_question', requestId: 'new-question', questions: [{ question: 'New?' }] },+ }]));+ expect(host.querySelector('[data-testid="interaction.ask.textInput"]')).toBe(input);+ expect(host.textContent).toContain('Original?');+ await type('interaction.ask.textInput', 'Finished');+ resolveInteraction.mockResolvedValue({ accepted: false });+ asyncReply.aroundMessagesByClientId.mockResolvedValue([{+ clientId: 'original-row', role: 'ask_user', content: {+ requestId, status: action === 'already-answered' ? 'answered' : action === 'unconfirmed' ? 'pending' : 'cancelled',+ },+ }]);+ asyncReply.getSession.mockResolvedValue({ id: 's1', agentKind: 'codex', model: 'test', effort: 'medium',+ permissionMode: 'ask', workingDir: '/repo' });+ asyncReply.input.steer.mockResolvedValue(action === 'unknown-steer' ? undefined : false);+ const projection = remoteSessionStore.getInputProjection('s1');+ asyncReply.input.enqueue.mockResolvedValue({ ...projection, queuePaused: action === 'stopped' });+ asyncReply.input.resume.mockResolvedValue({ ...projection, queuePaused: false });+ if (action === 'stopped') {+ await act(async () => remoteSessionStore.setInputProjection('s1', { ...projection, queuePaused: true }));+ expect(host.textContent).toContain('interaction.panel.sendAndContinue');+ }+ if (action === 'stopped-empty') {+ expect(host.textContent).toContain('interaction.panel.sendAndContinue');+ expect(asyncReply.input.enqueue).not.toHaveBeenCalled();+ }+ await click(action === 'close' ? 'interaction.ask.closeButton' : 'interaction.ask.submitButton');+ if (action === 'unconfirmed' || action === 'unknown-steer') {+ expect(host.textContent).toContain('Original?');+ expect(readAskUserDraft(requestId)?.customInput).toBe('Finished');+ expect(onError).toHaveBeenLastCalledWith('interaction.panel.decisionNotAccepted');+ } else {+ expect(onError.mock.calls).toEqual([[null]]);+ expect(host.textContent).toContain('New?');+ }+ if (action === 'send' || action === 'stopped' || action === 'stopped-empty') {+ expect(asyncReply.input.enqueue).toHaveBeenCalledOnce();+ expect(asyncReply.input.enqueue.mock.calls[0][1]).toMatchObject({+ clientId: expect.stringMatching(/^question-reply:codex:test:0:[a-f0-9]{64}$/), text: '> Original?\n\nFinished',+ });+ expect(asyncReply.input.resume).toHaveBeenCalledTimes(action === 'stopped' ? 1 : 0);+ } else expect(asyncReply.input.enqueue).not.toHaveBeenCalled();+});++it('does not retain an untouched async card', async () => {+ remoteSessionStore.setPendingInteractions('s1', [{+ request: { kind: 'ask_user_question', requestId, delivery: 'async', questions: [{ question: 'Original?' }] },+ }]);+ await act(async () => root.render(<Harness />));+ await act(async () => remoteSessionStore.setPendingInteractions('s1', []));+ expect(host.querySelector('[data-testid="interaction.ask.card"]')).toBeNull();+});+it.each(['permission', 'ask_user_question', 'plan_review'])('lets a shared guest submit %s through its decision button', async (kind) => {remoteSessionStore.setPendingInteractions('s1', [{ request: {kind, requestId, toolName: 'Read', input: { path: '/tmp/test.txt' },diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex dc4fd8cfc4..90cd671aab 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -138,6 +138,34 @@ function pending(kind: string, requestId?: string, persistId?: string): PendingIdescribe('remoteSessionStore', () => {beforeEach(() => remoteSessionStore.clear());+ it('keeps an edited async question across disconnection but removes it on explicit history clearing', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const item: PendingInteraction = { persistId: 'p1',+ request: { kind: 'ask_user_question', requestId: 'q1', delivery: 'async', questions: [{ question: 'Q?' }] } };+ remoteSessionStore.setPendingInteractions('s1', [item]);+ remoteSessionStore.protectAsyncQuestion('s1', item);+ remoteSessionStore.applyRemotePush('dev-1', 'maker:interaction-dismissed', {+ sessionId: 's1', requestId: 'q1', reason: 'resolved', decision: { dismissed: true },+ });+ const visible = remoteSessionStore.getVisiblePendingInteractions('s1');+ expect(remoteSessionStore.getVisiblePendingInteractions('s1')).toBe(visible);+ remoteSessionStore.markDeviceOffline('dev-1');+ expect(remoteSessionStore.getPendingInteractions('s1')).toHaveLength(0);+ expect(remoteSessionStore.getVisiblePendingInteractions('s1')[0]).toMatchObject({ retainedDraft: true });+ remoteSessionStore.invalidateSessionMessageWindow('s1', 'dev-1');+ expect(remoteSessionStore.getVisiblePendingInteractions('s1')).toHaveLength(0);+ });++ it.each(['deleted', 'archived', 'logout'] as const)('drops protected cards on %s', (action) => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ remoteSessionStore.protectAsyncQuestion('s1', { request: {+ kind: 'ask_user_question', requestId: 'q1', delivery: 'async',+ } });+ if (action === 'logout') remoteSessionStore.clear();+ else remoteSessionStore.applySessionPatch('dev-1', 's1', { status: action });+ expect(remoteSessionStore.getVisiblePendingInteractions('s1')).toHaveLength(0);+ });+it('keeps Make mirrors for transport while excluding them from visible session snapshots', () => {remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('make', { source: 'cindy-make' }),diff --git a/apps/mobile/src/i18n/locales/en/interaction.json b/apps/mobile/src/i18n/locales/en/interaction.jsonindex 125db69256..ec1a7fd1b2 100644--- a/apps/mobile/src/i18n/locales/en/interaction.json+++ b/apps/mobile/src/i18n/locales/en/interaction.json@@ -75,6 +75,8 @@"next": "Next","answerRequired": "Select or enter an answer to continue.","submit": "Submit",+ "sendAndContinue": "Send and continue",+ "closeAnswer": "Close","planReviewTitle": "Review Claude's plan","planExpand": "Expand plan","planEditHint": "Use edit mode to adjust the plan",diff --git a/apps/mobile/src/i18n/locales/ja/interaction.json b/apps/mobile/src/i18n/locales/ja/interaction.jsonindex c287f192b3..ede5e80bf2 100644--- a/apps/mobile/src/i18n/locales/ja/interaction.json+++ b/apps/mobile/src/i18n/locales/ja/interaction.json@@ -75,6 +75,8 @@"next": "次へ","answerRequired": "回答を選択または入力すると続行できます。","submit": "送信",+ "sendAndContinue": "送信して続行",+ "closeAnswer": "閉じる","planReviewTitle": "Claude のプランを確認","planExpand": "プランを展開","planEditHint": "編集モードでプランを調整",diff --git a/apps/mobile/src/i18n/locales/ko/interaction.json b/apps/mobile/src/i18n/locales/ko/interaction.jsonindex 7f6a530cd7..5bf31638bd 100644--- a/apps/mobile/src/i18n/locales/ko/interaction.json+++ b/apps/mobile/src/i18n/locales/ko/interaction.json@@ -75,6 +75,8 @@"next": "다음","answerRequired": "답변을 선택하거나 입력해야 계속할 수 있습니다.","submit": "제출",+ "sendAndContinue": "보내고 계속",+ "closeAnswer": "닫기","planReviewTitle": "Claude의 플랜 검토","planExpand": "플랜 펼치기","planEditHint": "편집 모드로 플랜 조정",diff --git a/apps/mobile/src/i18n/locales/zh-CN/interaction.json b/apps/mobile/src/i18n/locales/zh-CN/interaction.jsonindex abad5ec7a6..89d2d22cae 100644--- a/apps/mobile/src/i18n/locales/zh-CN/interaction.json+++ b/apps/mobile/src/i18n/locales/zh-CN/interaction.json@@ -75,6 +75,8 @@"next": "下一步","answerRequired": "选择或输入回答后才能继续。","submit": "提交",+ "sendAndContinue": "发送并继续",+ "closeAnswer": "关闭","planReviewTitle": "审阅 Claude 的计划","planExpand": "展开计划","planEditHint": "使用编辑模式调整计划",diff --git a/apps/mobile/src/i18n/locales/zh-TW/interaction.json b/apps/mobile/src/i18n/locales/zh-TW/interaction.jsonindex 088417aa1d..39081d2371 100644--- a/apps/mobile/src/i18n/locales/zh-TW/interaction.json+++ b/apps/mobile/src/i18n/locales/zh-TW/interaction.json@@ -75,6 +75,8 @@"next": "下一步","answerRequired": "選擇或輸入回答後才能繼續。","submit": "提交",+ "sendAndContinue": "傳送並繼續",+ "closeAnswer": "關閉","planReviewTitle": "審閱 Claude 的計劃","planExpand": "展開計劃","planEditHint": "使用編輯模式調整計劃",diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsxindex f9ad4fbcc7..dad8f92bad 100644--- a/apps/mobile/src/session/InteractionPanel.tsx+++ b/apps/mobile/src/session/InteractionPanel.tsx@@ -1,4 +1,6 @@import { PluginSetupNativeActions } from '@/plugins/PluginSetupNativeActions';+import { sha256 } from '@noble/hashes/sha256';+import { bytesToHex } from '@noble/hashes/utils';import { InputHandoffCard } from '@/inputHandoff/InputHandoffCard';import { parseInputHandoffSnapshotLike } from '@/inputHandoff/inputHandoffNative';import { mobilePluginSetupActions } from '@/plugins/pluginSetupActions';@@ -35,6 +37,8 @@ import {import { Text, TextInput } from '@/components/AppText';import { formatRemoteError } from '@/device-link/remoteStatus';import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';+import { asyncQuestionNeedsSupplement, formatAsyncQuestionSupplement } from '@cindy/maker-shared/interaction';+import { buildQueuedTextMessage } from '@/session/inputProjection';import {answerKey,buildAskQuestionReviewPresentation,@@ -84,7 +88,7 @@ import {buildInteractionTouchLayout,type InteractionTouchLayout,} from '@/session/interactionTouchLayout';-import { remoteSessionStore, useRemoteDeviceIdentity } from '@/session/remoteSessionStore';+import { remoteSessionStore, useRemoteDeviceIdentity, useSessionInputProjection, useSessionRunStatus } from '@/session/remoteSessionStore';import type { PendingInteraction } from '@/session/types';import { fontWeight, iconStroke, lineHeight, monoFont, useTheme, useThemedStyles, type ThemeColors } from '@/theme';import { iconSize, radius, spacing, typeScale } from '@/theme/tokens';@@ -218,6 +222,7 @@ function InteractionPanelContent({};const fallbackInteraction = sortedInteractions[0] ?? null;const activeInteraction = useMemo(() => {+ if (fallbackInteraction?.retainedDraft) return fallbackInteraction;if (!activeRequestId) return fallbackInteraction;return sortedInteractions.find((item) => readRequestId(item) === activeRequestId) ?? fallbackInteraction;}, [activeRequestId, fallbackInteraction, sortedInteractions]);@@ -529,6 +534,8 @@ function InteractionItem({}) {const { t } = useTranslation();const maker = useMobileMakerTransport(deviceId);+ const inputProjection = useSessionInputProjection(sessionId);+ const runStatus = useSessionRunStatus(sessionId);const [busy, setBusy] = useState(false);const submittingRequestIdRef = useRef<string | null>(null);const requestId = readRequestId(item);@@ -545,7 +552,7 @@ function InteractionItem({// expectedRevision 裁决(旧快照会被改判成重新体检而非取消),抢先撤卡会在// 取消其实没生效时留下一张被抑制、再也灌不回来的幽灵卡 —— 那类卡走非乐观// 路径,等被控端 dismiss 推送为准。- const optimisticDismiss = options.optimisticDismiss !== false;+ const optimisticDismiss = options.optimisticDismiss !== false && item.retainedDraft !== true;submittingRequestIdRef.current = currentRequestId;setBusy(true);onError(null);@@ -554,9 +561,55 @@ function InteractionItem({// 登记在途抑制,防权威快照 / push 重放在被控端确认前把同卡灌回闪回;保留// item 快照,真失败时原卡复原供重试。const itemSnapshot = item;+ // The retained object is scoped to this controller/account/task. Clearing or+ // replacing it invalidates in-flight work without tying a reply to a view's+ // mount lifetime (the user may switch tasks while it is being delivered).+ const current = () => !item.retainedDraft || (+ remoteSessionStore.getVisiblePendingInteractions(sessionId).includes(item) &&+ (inputProjection.queuePaused || !remoteSessionStore.getInputProjection(sessionId).queuePaused)+ );if (optimisticDismiss) remoteSessionStore.beginOptimisticInteractionDismiss(sessionId, currentRequestId);try {- await resolveInteractionResilient(maker, sessionId, currentRequestId, decision);+ if (item.retainedDraft) {+ const needsSupplement = await asyncQuestionNeedsSupplement(+ () => maker.resolveInteraction(currentRequestId, decision),+ async () => {+ if (!current() || !item.persistId) return undefined;+ const rows = await maker.aroundMessagesByClientId(sessionId, item.persistId, { radius: 0 });+ return rows.find((row) => row.clientId === item.persistId && row.role === 'ask_user')?.content;+ }, currentRequestId,+ );+ if (!current()) return;+ const text = formatAsyncQuestionSupplement(normalizeAskQuestions(item.request.questions),+ (decision.answers ?? {}) as Record<string, string>);+ if (needsSupplement && text) {+ const session = await maker.getSession(sessionId);+ if (!current()) return;+ const answerId = bytesToHex(sha256(text));+ const queued = buildQueuedTextMessage(session, text, new Date(), `question-reply:${currentRequestId}:${answerId}`, { planMode: false });+ // Only a definite negative ACK permits enqueue after steer.+ const steered = inputProjection.queuePaused ? false+ : await maker.input.steer(sessionId, queued, { touchUserSend: true });+ if (steered !== true && steered !== false) throw new Error('Supplement receipt unavailable');+ if (!steered) {+ if (!current()) return;+ let projection = await maker.input.enqueue(sessionId, queued, { sendAtMs: Date.now() });+ if (!current()) return;+ if (projection.queuePaused && inputProjection.queuePaused) {+ projection = await maker.input.resume(sessionId);+ }+ if (!current()) return;+ remoteSessionStore.setInputProjection(sessionId, projection);+ }+ }+ } else {+ await resolveInteractionResilient(maker, sessionId, currentRequestId, decision);+ }+ if (item.retainedDraft) {+ remoteSessionStore.dismissInteraction(sessionId, currentRequestId);+ remoteSessionStore.settleOptimisticInteractionDismiss(sessionId, currentRequestId, { kind: 'confirmed' });+ }+ remoteSessionStore.releaseProtectedQuestion(sessionId, currentRequestId);if (kind === 'ask_user_question') clearAskUserDraft(currentRequestId);if (kind === 'plan_review') clearPlanReviewDraft(currentRequestId);if (optimisticDismiss) {@@ -573,6 +626,7 @@ function InteractionItem({);}} catch (err) {+ if (item.retainedDraft && !current()) return;// resolveInteractionResilient 已带弱网重试 + pending 列表权威分辨,走到// 这里就是决定确未生效:复原卡片 + 报错。if (optimisticDismiss) {@@ -581,7 +635,7 @@ function InteractionItem({item: itemSnapshot,});}- onError(formatRemoteError(err));+ onError(item.retainedDraft ? t('interaction.panel.decisionNotAccepted') : formatRemoteError(err));} finally {if (submittingRequestIdRef.current === currentRequestId) {submittingRequestIdRef.current = null;@@ -616,6 +670,8 @@ function InteractionItem({busy={busy}item={item}onDecision={(decision) => void submitDecision(decision)}+ onStartAnswer={() => remoteSessionStore.protectAsyncQuestion(sessionId, item)}+ resumeOnSubmit={item.retainedDraft && (inputProjection.queuePaused || !runStatus.isRunning)}touchLayout={touchLayout}/>);@@ -921,6 +977,8 @@ type AskUserQuestionCardProps = {busy: boolean;item: PendingInteraction;onDecision(decision: Record<string, unknown>): void;+ onStartAnswer(): void;+ resumeOnSubmit?: boolean;touchLayout: InteractionTouchLayout;};@@ -936,6 +994,8 @@ function AskUserQuestionForm({busy,item,onDecision,+ onStartAnswer,+ resumeOnSubmit,questions,questionsIdentity,touchLayout,@@ -1036,7 +1096,7 @@ function AskUserQuestionForm({const nextAnswers = { ...answers, [currentAnswerKey]: answer };setAnswers(nextAnswers);if (isLast) {- draftCompletedRef.current = true;+ draftCompletedRef.current = !item.retainedDraft;// Optimistic dismissal unmounts this form immediately. Save the final// choice now so a refused/lost receipt can restore exactly this draft.const finalSelection = selectionFromAnswer({ ...current, options }, answer);@@ -1072,6 +1132,7 @@ function AskUserQuestionForm({};const toggleLabel = (label: string) => {+ onStartAnswer();if (!isMulti) {setShowCustomInput(false);setCustomInput('');@@ -1161,7 +1222,9 @@ function AskUserQuestionForm({<TextInputaccessibilityLabel={t('interaction.panel.customAnswerInputAccessibility')}autoFocus- onChangeText={setCustomInput}+ editable={!busy}+ onKeyPress={({ nativeEvent }) => { if (nativeEvent.key.length === 1) onStartAnswer(); }}+ onChangeText={(text) => { onStartAnswer(); setCustomInput(text); }}placeholder={t('interaction.panel.customAnswerPlaceholder')}placeholderTextColor={colors.textPlaceholder}style={styles.inlineInput}@@ -1203,7 +1266,9 @@ function AskUserQuestionForm({<TextInputaccessibilityLabel={t('interaction.panel.answerInput')}autoFocus- onChangeText={setCustomInput}+ editable={!busy}+ onKeyPress={({ nativeEvent }) => { if (nativeEvent.key.length === 1) onStartAnswer(); }}+ onChangeText={(text) => { onStartAnswer(); setCustomInput(text); }}placeholder={t('interaction.panel.answerInput')}placeholderTextColor={colors.textPlaceholder}style={styles.inlineInput}@@ -1214,6 +1279,13 @@ function AskUserQuestionForm({)}<InteractionActions touchLayout={touchLayout}>+ {item.retainedDraft ? (+ <ResolveButton busy={busy} label={t('interaction.panel.closeAnswer')}+ accessibilityLabel={t('interaction.panel.closeAnswer')}+ onPress={() => onDecision(buildAskUserQuestionDecision({}))}+ requestId={requestId} touchStyle={resolveButtonLayoutStyle(touchLayout, 'secondary', companion)}+ testID="interaction.ask.closeButton" variant="secondary" />+ ) : null}{currentIndex > 0 ? (<InteractionTouchButtonaccessibilityLabel={t('interaction.panel.previous')}@@ -1246,10 +1318,10 @@ function AskUserQuestionForm({/>{isMulti ? (<ResolveButton- accessibilityLabel={isLast ? t('interaction.panel.submitAnswerAccessibility') : t('interaction.panel.next')}+ accessibilityLabel={isLast ? t(resumeOnSubmit ? 'interaction.panel.sendAndContinue' : 'interaction.panel.submitAnswerAccessibility') : t('interaction.panel.next')}busy={busy}invalidReason={!canSubmitMulti ? t('interaction.panel.answerRequired') : null}- label={isLast ? t('interaction.panel.submit') : t('interaction.panel.next')}+ label={isLast ? t(resumeOnSubmit ? 'interaction.panel.sendAndContinue' : 'interaction.panel.submit') : t('interaction.panel.next')}onPress={submitMulti}requestId={requestId}touchStyle={resolveButtonLayoutStyle(touchLayout, 'primary', companion)}@@ -1258,10 +1330,10 @@ function AskUserQuestionForm({/>) : (<ResolveButton- accessibilityLabel={isLast ? t('interaction.panel.submitAnswerAccessibility') : t('interaction.panel.next')}+ accessibilityLabel={isLast ? t(resumeOnSubmit ? 'interaction.panel.sendAndContinue' : 'interaction.panel.submitAnswerAccessibility') : t('interaction.panel.next')}busy={busy}invalidReason={!canSubmitSingle ? t('interaction.panel.answerRequired') : null}- label={isLast ? t('interaction.panel.submit') : t('interaction.panel.next')}+ label={isLast ? t(resumeOnSubmit ? 'interaction.panel.sendAndContinue' : 'interaction.panel.submit') : t('interaction.panel.next')}onPress={submitSingle}requestId={requestId}touchStyle={resolveButtonLayoutStyle(touchLayout, 'primary', companion)}diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 84a3c7dadd..435d8f579e 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -252,6 +252,9 @@ const listMessageKeys = new Map<string, Set<string>>();// overwrite a newer live state with the first stale 0/N snapshot.const livePlanSnapshots = new Map<string, Map<string, LivePlanSnapshot>>();const pendingInteractions = new Map<string, PendingInteraction[]>();+// Editing is local to the controller. It must not keep a provider turn alive.+const protectedQuestions = new Map<string, PendingInteraction>();+const visibleInteractionCache = new Map<string, { raw: PendingInteraction[]; protected?: PendingInteraction; result: PendingInteraction[] }>();/*** 这个会话的 pending 列表当前是不是**权威**的(来自被控端的一次全量快照)。*@@ -1038,6 +1041,7 @@ function sessionStoreProtected(sessionId: string, includeVisible = true): booleaif (readSessionRunStatus(sessionId).isRunning) return true;if (sessionMakerTurnRunning.get(sessionId) === true) return true;if ((pendingInteractions.get(sessionId)?.length ?? 0) > 0) return true;+ if (protectedQuestions.has(sessionId)) return true;if ((inputProjections.get(sessionId)?.pendingQueue.length ?? 0) > 0) return true;if (sessionMessageLifecycle.hasLocalWork(sessionId)) return true;if (retentionForSession(sessionId) === 'regular' && hasComposerDraft(sessionId)) return true;@@ -1123,6 +1127,8 @@ function invalidateSessionMessageWindowState(}function removeSessionRuntimeState(sessionId: string): void {+ protectedQuestions.delete(sessionId);+ visibleInteractionCache.delete(sessionId);void clearHistoryDisk(undefined, sessionId);clearRemoteHistoryViews(undefined, sessionId);invalidateSessionMessageWindowState(sessionId, false);@@ -3268,9 +3274,11 @@ export const remoteSessionStore = {* 清内存与磁盘预览并登记一次刷新;页面可见时立即 load,隐藏时下次打开再拉。*/invalidateSessionMessageWindow(sessionId: string, deviceId?: string): void {+ const removedDraft = protectedQuestions.delete(sessionId);+ visibleInteractionCache.delete(sessionId);void clearHistoryDisk(deviceId, sessionId);resetRemoteHistoryViews(deviceId, sessionId);- const changed = invalidateSessionMessageWindowState(sessionId, true);+ const changed = invalidateSessionMessageWindowState(sessionId, true) || removedDraft;clearSessionMessageCache(sessionId, deviceId);if (changed) {bumpMessageVersion(sessionId);@@ -3525,6 +3533,8 @@ export const remoteSessionStore = {}let shouldReseedAfterPatch = false;if (patch.status === 'deleted' || patch.status === 'archived') {+ protectedQuestions.delete(sessionId);+ visibleInteractionCache.delete(sessionId);void clearHistoryDisk(deviceId, sessionId);clearRemoteHistoryViews(deviceId, sessionId);shard.sessions = shard.sessions.filter((s) => s.id !== sessionId);@@ -4775,6 +4785,9 @@ export const remoteSessionStore = {const sessionId = readString(payload, 'sessionId');const requestId = readString(payload, 'requestId');if (sessionId && requestId) {+ if (payload.reason === 'resolved' && !(isRecord(payload.decision) && payload.decision.dismissed === true)) {+ this.releaseProtectedQuestion(sessionId, requestId);+ }// 注意:这里**不**提前回收延长抑制条目——push 到达只说明被控端已确认,// 不排除仍有「决定提交前发出、此刻还在途」的旧 getPendingInteractions// 快照晚于本 push 返回(弱网高发);提前回收会让那份旧快照把已解决的卡@@ -5303,6 +5316,8 @@ export const remoteSessionStore = {listMessageKeys.clear();emptySessionMessageStructureTokens.clear();livePlanSnapshots.clear();+ protectedQuestions.clear();+ visibleInteractionCache.clear();if (pendingInteractions.size > 0) {pendingInteractions.clear();bumpHomeStatusVersion();@@ -5559,6 +5574,31 @@ export const remoteSessionStore = {return pendingInteractions.get(sessionId) ?? emptyPendingInteractions;},+ protectAsyncQuestion(sessionId: string, item: PendingInteraction): void {+ if (item.request.kind !== 'ask_user_question' || item.request.delivery !== 'async') return;+ if (protectedQuestions.get(sessionId)?.request.requestId === item.request.requestId) return;+ protectedQuestions.set(sessionId, { ...item, retainedDraft: true });+ emit();+ },++ releaseProtectedQuestion(sessionId: string, requestId: string): void {+ if (protectedQuestions.get(sessionId)?.request.requestId !== requestId) return;+ protectedQuestions.delete(sessionId);+ visibleInteractionCache.delete(sessionId);+ emit();+ },++ getVisiblePendingInteractions(sessionId: string): PendingInteraction[] {+ const raw = this.getPendingInteractions(sessionId);+ const retained = protectedQuestions.get(sessionId);+ if (!retained) return raw;+ const cached = visibleInteractionCache.get(sessionId);+ if (cached?.raw === raw && cached.protected === retained) return cached.result;+ const result = [retained, ...raw.filter((item) => item.request.requestId !== retained.request.requestId)];+ visibleInteractionCache.set(sessionId, { raw, protected: retained, result });+ return result;+ },+/*** pending 列表当前是否权威(见 pendingInteractionsAuthoritative 的注释)。* 空列表要用来做清理判断时必须先问这里。@@ -6274,7 +6314,7 @@ export function useRemoteNewMakerWorktreeBranchPreference(export function useSessionPendingInteractions(sessionId: string): PendingInteraction[] {return useSyncExternalStore(remoteSessionStore.subscribe,- () => remoteSessionStore.getPendingInteractions(sessionId),+ () => remoteSessionStore.getVisiblePendingInteractions(sessionId),);}diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.tsindex 8b1d733927..4571bb1d1e 100644--- a/apps/mobile/src/session/types.ts+++ b/apps/mobile/src/session/types.ts@@ -310,6 +310,8 @@ export interface InputProjection {}export interface PendingInteraction {+ /** Controller-only draft retention; never sent to the Host. */+ retainedDraft?: boolean;request: {kind?: string;requestId?: string;diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex 4764976f88..bae7ebdc96 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -358,8 +358,9 @@ sessionRunningRetry 就停。每次因 replacement 关闭而重新入队都计触发定时任务的成功收口。回归见 `agents/codex/index.test.ts` 的 pending confirmation与 human continuation 用例,以及 Desktop `sessionEventPipeline.test.ts`。Codex 异步提问使用 `agentMessage.delivery=async` 与结构化 `questions` 接入同一提问- 流程,不把回退正文当成最终回答。未回答的异步问题不保留产品边界,原轮次结束时自动- 收起卡片、不代选答案,迟到回答不得续跑。结束前已提交的回答优先通过 `turn/steer`+ 流程,不把回退正文当成最终回答。未回答的异步问题不保留产品边界,原轮次结束时撤销+ 原生请求;未操作的卡片自动收起、不代选答案,也不提供历史回答入口。原生请求的迟到+ 回答不得续跑;已编辑草稿的显式补充发送见下文。结束前已提交的回答优先通过 `turn/steer`送入原轮次;发送与结束竞态导致原轮次明确拒绝接收时复用人工续跑,发送结果不确定时提示错误且不自动重发。Stop、失败、关闭及被替换问题的迟到回答不得续跑。协议与前缀稳定性实测见 `agents/codex/async-user-input.native.test.ts`,@@ -379,7 +380,7 @@ sessionRunningRetry 就停。每次因 replacement 关闭而重新入队都计回归见 `session.async-user-questions.test.ts`、MCP `asyncUserQuestionTool.test.ts`;两种真实 harness 配本地假模型的投递与稳定前缀实测见`agents/shared/async-user-questions.native.test.ts`。- 同步与异步问题共用卡片时,同步问题优先:已有同步问题等待时不再显示异步卡片,+ 宿主的同步与异步问题共用卡片时,同步问题优先:已有同步问题等待时不再显示异步卡片,同步问题后到时收起未回答的异步卡片,避免遮住阻塞执行的问题。三个 harness 均只保留最新一张待回答的异步卡片:显示新卡片前先将旧卡片标为被替换,旧答案即使在原轮次结束前到达也不得投递或清除新卡片。Codex 的同步工具结果@@ -394,6 +395,19 @@ sessionRunningRetry 就停。每次因 replacement 关闭而重新入队都计阻塞交互或生命周期等待,未回答也不能暂停工具循环检测/零事件看门狗。字段缺省仍按同步等待处理;Codex 本机/SSH 共用同一 adapter,手机卡片仍走既有宿主交互通道。回归见 `session.tool-loop.test.ts`、`session.turn-stall.test.ts`。+ **已开始回答的异步卡片保护(桌面、手机及远控共用)。** 用户输入文字(含中文组词)+ 或手动选择选项时锁存本端草稿;仅聚焦、展开输入框及默认预选不算。停顿、失焦、+ 删空、切任务、原轮次结束及新请求到来均不撤销保护,新请求排在当前输入后面。+ 原生请求照常撤销,不延长 provider turn;草稿只保存在本端内存,不增加历史回答、+ 跨设备草稿同步或重启恢复。提交、主动关闭、任务清空/删除或账号切换才释放草稿;+ 原问题被其他端确认回答时也收敛。+ 提交先尝试原生回答;拒绝/回执丢失时读取原问题的宿主消息行,已回答则不重复发送,+ 只有确认 cancelled 才把原问题与答案作为普通用户补充,复用 steer/输入队列和+ 来源标记。结果未知时保留草稿;同一原问题的同文补充使用相同 clientId,修改正文后+ 使用新 ID。Stop 不自动续跑,用户点击「发送并继续」才恢复暂停队列;关闭或空答案+ 不触发补充执行。UI 草稿不属于宿主 pending interaction,不影响工具循环检测或调度。+ 回归见 Desktop `askUserDoneRace.test.ts`、`askUserQuestionIdentity.test.tsx`,+ Mobile `InteractionPanelReceipt.test.tsx` 及 shared `interaction.test.ts`。Codex `functions.exec` yield 没有协议级 execution handle(cell / wait 活在`codex-rs` daemon),近期检测只能是 adapter 内、用真实 rollout fixture 锁死的启发式,用来铸造有界 claim,再由宿主确定性开续段让模型 wait 同一 cell。diff --git a/packages/maker-shared/src/__tests__/interaction.test.ts b/packages/maker-shared/src/__tests__/interaction.test.tsindex e02ccebe09..c67e1d7acb 100644--- a/packages/maker-shared/src/__tests__/interaction.test.ts+++ b/packages/maker-shared/src/__tests__/interaction.test.ts@@ -1,5 +1,7 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import {+ asyncQuestionNeedsSupplement,+ formatAsyncQuestionSupplement,buildAskQuestionProgressSummary,buildAskQuestionReviewPresentation,buildAskUserQuestionDecision,@@ -37,6 +39,33 @@ import {} from '../interaction.js';describe('interaction shared model', () => {+ it('keeps original questions attached to late answers without including skipped questions', () => {+ expect(formatAsyncQuestionSupplement([{ question: 'Scope?\nDetails?', header: 'Scope' }, { question: 'Skipped?' }],+ { Scope: 'Mobile too', 'Skipped?': '' })).toBe('> Scope?\n> Details?\n\nMobile too');+ expect(formatAsyncQuestionSupplement([{ question: 'Q?' }], {})).toBe('');+ });++ it('never supplements an accepted native answer', async () => {+ const read = vi.fn();+ expect(await asyncQuestionNeedsSupplement(async () => ({ accepted: true }), read, 'q1')).toBe(false);+ expect(read).not.toHaveBeenCalled();+ });++ it.each(['answered', 'cancelled', 'pending', 'missing'])('checks the original Host row after a lost receipt: %s', async (status) => {+ const result = asyncQuestionNeedsSupplement(async () => { throw new Error('lost receipt'); },+ async () => status === 'missing' ? undefined : JSON.stringify({ requestId: 'q1', status }), 'q1');+ if (status === 'answered') expect(await result).toBe(false);+ else if (status === 'cancelled') expect(await result).toBe(true);+ else await expect(result).rejects.toThrow('not confirmed');+ });++ it('does not deliver against a different question or a still-pending paused question', async () => {+ await expect(asyncQuestionNeedsSupplement(async () => ({ accepted: false }),+ async () => ({ requestId: 'other', status: 'cancelled' }), 'q1')).rejects.toThrow();+ await expect(asyncQuestionNeedsSupplement(async () => ({ accepted: false }),+ async () => ({ requestId: 'q1', status: 'pending' }), 'q1')).rejects.toThrow();+ });+it('builds resolve action presentation for requestId, busy, invalid, and confirm states', () => {expect(buildInteractionResolveActionPresentation({label: '允许一次',diff --git a/packages/maker-shared/src/interaction.ts b/packages/maker-shared/src/interaction.tsindex 490e326e3f..23e6d9e226 100644--- a/packages/maker-shared/src/interaction.ts+++ b/packages/maker-shared/src/interaction.ts@@ -7,6 +7,8 @@ export interface InteractionRequestLike {}export interface PendingInteractionLike {+ /** Local presentation only: an answer already being edited keeps focus. */+ retainedDraft?: boolean;request: InteractionRequestLike;persistId?: string;}@@ -18,6 +20,50 @@ export interface AskQuestion {multiSelect?: boolean;}+/** A late answer is ordinary user input, with the original question attached. */+export function formatAsyncQuestionSupplement(+ questions: readonly AskQuestion[],+ answers: Record<string, string>,+): string {+ const replies = questions.flatMap((q) => {+ const answer = answers[q.question] ?? (q.header ? answers[q.header] : undefined);+ return typeof answer === 'string' && answer.trim()+ ? [{ question: q.question, answer: answer.trim() }] : [];+ });+ return replies.map(({ question, answer }) => `${question.split('\n').map((line) => `> ${line}`).join('\n')}\n\n${answer}`).join('\n\n');+}++/** Only a confirmed cancellation permits delivery as a new user message. A+ * missing pending request alone cannot distinguish expiry from an accepted+ * answer whose receipt was lost (including an answer on another device). */+export async function asyncQuestionNeedsSupplement(+ resolve: () => Promise<{ accepted: boolean } | void>,+ readMessage: () => Promise<unknown>,+ requestId: string,+): Promise<boolean> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ const receipt = await Promise.race([+ resolve(),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error('Interaction receipt timeout')), 15_000);+ }),+ ]);+ if (receipt && receipt.accepted === true) return false;+ } catch {+ // Read the original Host row before deciding whether another delivery is safe.+ } finally {+ if (timer) clearTimeout(timer);+ }+ const raw = await readMessage();+ const content = typeof raw === 'string' ? JSON.parse(raw) : raw;+ if (content && typeof content === 'object' && 'requestId' in content && content.requestId === requestId && 'status' in content) {+ if (content.status === 'answered') return false;+ if (content.status === 'cancelled') return true;+ }+ throw new Error('Interaction decision was not confirmed');+}+export interface IssueDraft {title: string;body: string;@@ -805,7 +851,8 @@ export function sortPendingInteractions(): PendingInteractionLike[] {return interactions.map((item, index) => ({ item, index }))- .sort((a, b) => interactionPriority(a.item) - interactionPriority(b.item) || a.index - b.index)+ .sort((a, b) => Number(b.item.retainedDraft === true) - Number(a.item.retainedDraft === true)+ || interactionPriority(a.item) - interactionPriority(b.item) || a.index - b.index).map(({ item }) => item);}