Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): invalidate queued editor changes when restoring drafts

DavidShend8113792fe09
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 3f90c7cbb5..166a592207 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -7985,6 +7985,11 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
} else {
discardQueueEditTransientAttachments(editing);
}
+ // Rotate the editor document id now: late IME changes must not overwrite
+ // the restored draft while its React update waits for the next frame.
+ composerInputRef.current?.applyDocumentAndSetSelection(
+ editing.stashedDocument, composerDocumentProjectedText(editing.stashedDocument).length,
+ );
applyComposerDocument(editing.stashedDocument);
attachmentsRef.current = [...editing.stashedAttachments];
setAttachments([...editing.stashedAttachments]);
diff --git a/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx b/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx
index 9aaa165eca..17b0b6fdba 100644
--- a/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx
+++ b/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx
@@ -2,12 +2,34 @@
import { act, createElement, createRef } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { runInNewContext } from 'node:vm';
+import { readFileSync } from 'node:fs';
+import ts from 'typescript';
import { afterEach, expect, it, vi } from 'vitest';
import { Platform } from 'react-native';
import { ComposerRichInput, type ComposerRichInputHandle } from '@/session/ComposerRichInput';
-import { textComposerDocument, type ComposerDocument } from '@/session/composerDocument';
+import { composerDocumentProjectedText, textComposerDocument, type ComposerDocument } from '@/session/composerDocument';
import { createComposerDraftSource } from '@/session/composerDraftSource';
+// Execute the page's real cancellation/persistence callbacks with the mounted
+// editor below, without importing the unrelated native/network page UI.
+const pageSource = ts.createSourceFile('session.tsx', readFileSync('app/sessions/[sessionId].tsx', 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+const pageCallbacks = new Map<string, string>();
+function collectPageCallbacks(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && ['cancelQueueEdit', 'applyComposerDocument', 'applyRichComposerChange'].includes(node.name.getText(pageSource))
+ && node.initializer && ts.isCallExpression(node.initializer)) {
+ pageCallbacks.set(node.name.getText(pageSource), ts.transpileModule(`(${node.initializer.arguments[0].getText(pageSource)})`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText);
+ }
+ ts.forEachChild(node, collectPageCallbacks);
+}
+collectPageCallbacks(pageSource);
+function pageCallback(name: string, bindings: Record<string, unknown>) {
+ const compiled = pageCallbacks.get(name);
+ if (!compiled) throw new Error(`Missing page callback: ${name}`);
+ return runInNewContext(compiled, bindings);
+}
+
const bridge = vi.hoisted(() => ({
onMessage: (_event: { nativeEvent: { data: string } }) => {},
onContentProcessDidTerminate: () => {},
@@ -166,6 +188,61 @@ it('rejects an invalidated send scope before a late snapshot can overwrite the r
unsubscribe();
});
+// #7536 review, unit: a queued IME change can arrive after cancelQueueEdit but
+// before its scheduled React frame. Snapshot guards do not cover this unsolicited
+// message; the restored personal draft must survive in memory and persistence.
+it('cancels queue edit before a late change can overwrite the restored personal draft', () => {
+ vi.useFakeTimers();
+ Platform.OS = 'android';
+ const { ref, page, send, onChangeDocument, renderDocument } = mount();
+ send({ type: 'ready' });
+ const edited = textComposerDocument('edited queued message');
+ const stashed = textComposerDocument('unsent personal draft');
+ renderDocument(edited);
+ const oldId = page.id;
+ const source = createComposerDraftSource(edited);
+ const publish = vi.fn();
+ const unsubscribe = source.subscribe(publish);
+ const composerDocumentRef = { current: edited };
+ const queueEditingRef = { current: { clientId: 'queue-1', stashedDocument: stashed, stashedAttachments: [] } };
+ const saveComposerDocumentDraft = vi.fn();
+ const saveComposerDraft = vi.fn();
+ const applyComposerDocument = pageCallback('applyComposerDocument', {
+ composerDocumentRef, draftRef: { current: '' }, pendingSkillSelectionRef: { current: null },
+ composerDocumentProjectedText, composerDraftSource: source, sessionId: 'task',
+ voiceDictionaryLearningTrackerRef: { current: null }, saveComposerDocumentDraft, saveComposerDraft,
+ });
+ onChangeDocument.mockImplementation(pageCallback('applyRichComposerChange', { applyComposerDocument, queueEditingRef }));
+ const cancel = pageCallback('cancelQueueEdit', {
+ queueEditingRef, composerInputRef: ref, composerDocumentProjectedText,
+ setQueueEditing: vi.fn(), queueEditLockOwnerRef: { current: null },
+ queueEditSaveOwnerRef: { current: null }, queueEditSaveInFlightRef: { current: null },
+ discardQueueEditTransientAttachments: vi.fn(), applyComposerDocument,
+ attachmentsRef: { current: [] }, setAttachments: vi.fn(),
+ });
+ try {
+ act(() => cancel());
+ // Do not render the restored props or advance the scheduled frame.
+ send({ type: 'change', documentId: oldId, document: edited });
+ expect(onChangeDocument).not.toHaveBeenCalled();
+ expect(composerDocumentRef.current).toEqual(stashed);
+ expect(source.getSnapshot().document).toEqual(stashed);
+ expect(saveComposerDocumentDraft).toHaveBeenCalledExactlyOnceWith('task', stashed);
+ expect(saveComposerDraft).toHaveBeenCalledExactlyOnceWith('task', 'unsent personal draft');
+ expect(publish).not.toHaveBeenCalled();
+ expect(bridge.requestFocus).not.toHaveBeenCalled();
+ expect(page.applyDocument.mock.lastCall?.[1]).toBe(false);
+ // The new document remains editable; rejecting stale messages must not
+ // permanently suppress normal input after cancellation.
+ const continued = textComposerDocument('unsent personal draft continued');
+ send({ type: 'change', documentId: page.id, document: continued });
+ expect(composerDocumentRef.current).toEqual(continued);
+ expect(saveComposerDocumentDraft).toHaveBeenLastCalledWith('task', continued);
+ } finally {
+ unsubscribe();
+ }
+});
+
it('never writes an older native edit back over later typing, but applies external replacements', () => {
const { page, send, onChangeDocument, renderDocument } = mount();
send({ type: 'ready' });
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index ff914508e1..38e8ab1ddf 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -123,6 +123,8 @@ DOM,保留输入法组字与光标。点击发送后,在发送防重锁内
显式传入的文档保持各自的快照来源,iOS 原生编辑器保留现有原生路径。
快照回包在写回编辑器状态或草稿之前核对调用方作用域;不能只在 `await` 返回后检查,
否则取消排队编辑与下一帧渲染之间到达的旧快照会覆盖已恢复的原草稿。
+取消排队编辑时同步向编辑器应用暂存的个人草稿,立即轮换文档标识;不能只等待下一帧
+传入新 props,否则迟到的普通 `change` 消息也可能写回旧内容。恢复不主动聚焦或弹出键盘。
实现:`ComposerRichInput.tsx`、`composerRichInputHtml.ts` 与 `app/sessions/[sessionId].tsx`;
回归:`composerRichInputLifecycle.test.tsx`、`composerRichInputHtml.test.ts`。Android 模拟器