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): preserve composing text when sending messages

DavidShene28cd2dfaff3
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index c989cfabbe..3f90c7cbb5 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -6437,10 +6437,35 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
await finishVoiceRecording({ sendAfterTranscribe: true });
return;
}
+ if (sendInFlightRef.current || sending) return;
+ sendInFlightRef.current = true;
+ setSending(true);
+ const messageWorkLease = remoteSessionStore.acquireSessionMessageWork(sessionId, true);
+ try {
+ let visibleDocument: ComposerDocument | undefined;
+ const inputAtSend = composerInputRef.current;
+ if (!independent && options.documentOverride === undefined && options.draftOverride === undefined && !inputAtSend) {
+ Alert.alert(t('session.screen.operationFailed'), t('session.screen.inputSyncFailed'));
+ return;
+ }
+ if (!independent && options.documentOverride === undefined && options.draftOverride === undefined && inputAtSend?.flushDocument) {
+ const ownerAtFlush = getMobileAuthOwner();
+ const queueEditAtFlush = queueEditingRef.current;
+ const flushScopeAlive = () => isMobileAuthOwnerCurrent(ownerAtFlush)
+ && outboxSessionAliveRef.current === sessionId && deviceIdRef.current === deviceId
+ && composerInputRef.current === inputAtSend && queueEditingRef.current === queueEditAtFlush;
+ try {
+ visibleDocument = await inputAtSend.flushDocument(flushScopeAlive);
+ } catch {
+ if (flushScopeAlive()) Alert.alert(t('session.screen.operationFailed'), t('session.screen.inputSyncFailed'));
+ return;
+ }
+ if (!flushScopeAlive()) return;
+ }
const commandsAtSend = slashCommandsRef.current;
const documentAtSend = independent ? textComposerDocument(options.independentText!) : options.documentOverride
?? (options.draftOverride === undefined
- ? composerDocumentRef.current
+ ? visibleDocument ?? composerDocumentRef.current
: reconcileComposerProjectedText(composerDocumentRef.current, options.draftOverride));
const visibleDraft = composerDocumentProjectedText(documentAtSend);
const body = visibleDraft.trim();
@@ -6462,8 +6487,6 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
}
if (
(!text && attachments.length === 0 && pendingUploads.length === 0) ||
- sendInFlightRef.current ||
- sending ||
!deviceId
) {
if (options.documentOverride) applyComposerDocument(options.documentOverride);
@@ -6476,10 +6499,6 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
}
const connectionDispatchBlockedAtSend = outboxConnectionBlockedNow();
invalidateHistoryRecoveryNavigation();
- sendInFlightRef.current = true;
- setSending(true);
- const messageWorkLease = remoteSessionStore.acquireSessionMessageWork(sessionId, true);
- try {
// 自动恢复中的 error 也是 outbox 的派发门;先清掉会让刚入队的消息在下一帧
// 立刻撞回断链。真正恢复后的 load / connection epoch 会负责清理并唤醒 pump。
if (!connectionDispatchBlockedAtSend) setError(null);
diff --git a/apps/mobile/src/__tests__/composerRichInputHtml.test.ts b/apps/mobile/src/__tests__/composerRichInputHtml.test.ts
index 675b0368ad..b099719206 100644
--- a/apps/mobile/src/__tests__/composerRichInputHtml.test.ts
+++ b/apps/mobile/src/__tests__/composerRichInputHtml.test.ts
@@ -353,6 +353,7 @@ describe('mobile composer rich input HTML', () => {
cindyComposer?: {
applyDocument(value: unknown, focusAfter?: boolean, caret?: { nodeIndex: number; offset: number }): void;
commitPaste(requestId: string, nodes: unknown[]): void;
+ snapshot(requestId: number): void;
setConfig(value: { maxHeight: number }): void;
};
getSelection(): typeof selection;
@@ -406,7 +407,7 @@ describe('mobile composer rich input HTML', () => {
listeners.get('compositionstart')?.();
children[0].nodeValue = 'hello world composing';
listeners.get('input')?.();
- expect(messages).not.toContainEqual({
+ expect(messages).toContainEqual({
type: 'change',
document: { version: 1, nodes: [{ type: 'text', text: 'hello world composing' }] },
});
@@ -439,8 +440,21 @@ describe('mobile composer rich input HTML', () => {
{ type: 'blur' },
]);
- // IME completion may arrive on either side of blur. Keep preedit text
- // private until completion/cancellation, then publish the final DOM once.
+ // #7508 / #7509, unit: visible preedit must reach native before Send.
+ // Earlier coverage deliberately withheld it. A snapshot must also work if
+ // input has not fired yet, without committing/cancelling the IME's DOM.
+ listeners.get('compositionstart')?.();
+ children[0].nodeValue = '자동완성 껐';
+ windowStub.cindyComposer?.snapshot(77);
+ expect(messages.at(-1)).toEqual({ type: 'snapshot', requestId: 77, documentId: 0,
+ document: textComposerDocument('자동완성 껐'), pendingPaste: false });
+ expect(children[0].nodeValue).toBe('자동완성 껐');
+ children[0].nodeValue = '자동완성 껐는데';
+ listeners.get('input')?.();
+ expect(messages.at(-1)).toEqual({ type: 'change', document: textComposerDocument('자동완성 껐는데') });
+
+ // Completion/cancellation can arrive on either side of blur. The native
+ // draft must follow the visible preedit and then the final DOM in both cases.
for (const completion of ['compositionend', 'compositioncancel']) {
for (const blurFirst of [false, true]) {
windowStub.cindyComposer?.applyDocument({
@@ -451,10 +465,11 @@ describe('mobile composer rich input HTML', () => {
listeners.get('compositionstart')?.();
children[0].nodeValue = '草稿候选';
listeners.get('input')?.();
- expect(messages.slice(beforeComposition)).toEqual([]);
+ const preedit = { type: 'change', document: textComposerDocument('草稿候选') };
+ expect(messages.slice(beforeComposition)).toEqual([preedit]);
if (blurFirst) {
listeners.get('blur')?.();
- expect(messages.slice(beforeComposition)).toEqual([{ type: 'blur' }]);
+ expect(messages.slice(beforeComposition)).toEqual([preedit, { type: 'blur' }]);
expect(children[0].nodeValue).toBe('草稿候选');
}
@@ -463,13 +478,13 @@ describe('mobile composer rich input HTML', () => {
listeners.get(completion)?.();
listeners.get('input')?.();
if (!blurFirst) listeners.get('blur')?.();
- const changes = completion === 'compositionend' ? [{
+ const changes = [{
type: 'change',
document: { version: 1, nodes: [{ type: 'text', text: finalText }] },
- }] : [];
+ }];
expect(messages.slice(beforeComposition)).toEqual(blurFirst
- ? [{ type: 'blur' }, ...changes]
- : [...changes, { type: 'blur' }]);
+ ? [preedit, { type: 'blur' }, ...changes]
+ : [preedit, ...changes, { type: 'blur' }]);
// Completion must also unlock ordinary editing after refocusing.
listeners.get('focus')?.();
diff --git a/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx b/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx
index a8e5e22bc0..9aaa165eca 100644
--- a/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx
+++ b/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx
@@ -6,6 +6,7 @@ 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 { createComposerDraftSource } from '@/session/composerDraftSource';
const bridge = vi.hoisted(() => ({
onMessage: (_event: { nativeEvent: { data: string } }) => {},
@@ -72,6 +73,9 @@ function mount(hidden = false) {
}),
setConfig: vi.fn(),
focus: vi.fn(),
+ snapshot: vi.fn((requestId: number) => bridge.onMessage({ nativeEvent: { data: JSON.stringify({
+ type: 'snapshot', requestId, documentId: page.id, document: page.document, pendingPaste: false,
+ }) } })),
ping: vi.fn((id: number) => bridge.onMessage({ nativeEvent: { data: JSON.stringify({ type: 'pong', id }) } })),
};
bridge.inject.mockImplementation((script: string) => runInNewContext(script, { window: { cindyComposer: page } }));
@@ -86,6 +90,82 @@ function mount(hidden = false) {
return { ref, page, send, onChangeDocument, onPasteImagesLoadFailed, renderDocument };
}
+// #7508 / #7509, unit: the real WebView bridge must hand Send the visible document,
+// including preedit, without echoing it back into the IME. Earlier tests only covered
+// unsolicited change events; the minimal missing case is a DOM edit with no change yet.
+it('reads the visible send snapshot and acknowledges it without replacing the editor', async () => {
+ const { ref, page, send, onChangeDocument, renderDocument } = mount();
+ send({ type: 'ready' });
+ page.document = { version: 1, nodes: [
+ { type: 'quote', quote: { text: 'retained reference' } },
+ { type: 'text', text: '자동완성 껐는데 그래도 잘리네' },
+ ] };
+ page.applyDocument.mockClear();
+ let snapshot!: ComposerDocument;
+ await act(async () => { snapshot = await ref.current!.flushDocument!(); });
+ expect(snapshot).toEqual(page.document);
+ expect(onChangeDocument).toHaveBeenLastCalledWith(snapshot);
+ renderDocument(snapshot);
+ expect(page.applyDocument).not.toHaveBeenCalled();
+});
+
+it.each(['replacement', 'termination', 'unmount', 'timeout'] as const)(
+ 'rejects an unavailable send snapshot after %s and ignores a late reply', async reason => {
+ vi.useFakeTimers();
+ const { ref, page, send, renderDocument, onChangeDocument } = mount();
+ send({ type: 'ready' });
+ page.snapshot.mockImplementation(() => {});
+ const oldId = page.id;
+ const result = ref.current!.flushDocument!().then(() => 'accepted', () => 'rejected');
+ const requestId = page.snapshot.mock.lastCall![0];
+ if (reason === 'replacement') renderDocument(textComposerDocument('new draft'));
+ else if (reason === 'termination') act(() => bridge.onRenderProcessGone());
+ else if (reason === 'unmount') { act(() => root!.unmount()); root = undefined; }
+ else act(() => vi.advanceTimersByTime(5000));
+ expect(await result).toBe('rejected');
+ send({ type: 'snapshot', requestId, documentId: oldId, document: textComposerDocument('stale'), pendingPaste: false });
+ expect(onChangeDocument).not.toHaveBeenCalled();
+ },
+);
+
+it('does not submit a partially replaced paste or an editor that has not loaded', async () => {
+ const { ref, page, send, onChangeDocument } = mount();
+ await expect(ref.current!.flushDocument!()).rejects.toThrow();
+ send({ type: 'ready' });
+ page.snapshot.mockImplementation(requestId => send({
+ type: 'snapshot', requestId, documentId: page.id, document: textComposerDocument('partial'), pendingPaste: true,
+ }));
+ await expect(ref.current!.flushDocument!()).rejects.toThrow();
+ expect(onChangeDocument).not.toHaveBeenCalled();
+});
+
+// #7508 review, unit: cancelling queue edit restores the draft synchronously,
+// but its WebView props wait for the next frame. A solicited snapshot can arrive
+// in that gap even without typing; replacement-after-render coverage misses it.
+it('rejects an invalidated send scope before a late snapshot can overwrite the restored draft', async () => {
+ vi.useFakeTimers();
+ const { ref, page, send, onChangeDocument } = mount();
+ send({ type: 'ready' });
+ page.snapshot.mockImplementation(() => {});
+ const editing = { clientId: 'queued-message' };
+ let queueEdit: typeof editing | null = editing;
+ const source = createComposerDraftSource(textComposerDocument('edited queued message'));
+ const unsubscribe = source.subscribe(() => {});
+ onChangeDocument.mockImplementation((document: ComposerDocument) => source.setDocument(document));
+ const result = ref.current!.flushDocument!(() => queueEdit === editing).then(() => 'accepted', () => 'rejected');
+ const requestId = page.snapshot.mock.lastCall![0];
+ queueEdit = null;
+ const restored = textComposerDocument('unsent personal draft');
+ source.setDocument(restored);
+ // Deliberately do not render the restored document or advance its frame yet.
+ send({ type: 'snapshot', requestId, documentId: page.id,
+ document: textComposerDocument('edited queued message'), pendingPaste: false });
+ expect(await result).toBe('rejected');
+ expect(onChangeDocument).not.toHaveBeenCalled();
+ expect(source.getSnapshot().document).toEqual(restored);
+ 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/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index 0418ab0470..842bfb6644 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -261,6 +261,7 @@
"voiceSenderNotReady": "Messages can't be sent right now. Go back and reopen the session.",
"voiceStopAndSend": "End voice input and send",
"sendMessage": "Send remote message",
+ "inputSyncFailed": "Couldn't read the complete input. Your text is still here; please try again.",
"voiceStartInput": "Start voice input",
"stopSession": "Stop remote session",
"sessionNotFoundResync": "Couldn't find the current remote session; sync again before sending.",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index e838797f31..28e339e098 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -261,6 +261,7 @@
"voiceSenderNotReady": "メッセージを送信できません。一度戻ってから、セッションを開き直してください。",
"voiceStopAndSend": "音声入力を終了して送信",
"sendMessage": "リモートメッセージを送信",
+ "inputSyncFailed": "入力内容をすべて読み取れませんでした。内容は保持されています。もう一度お試しください。",
"voiceStartInput": "音声入力を開始",
"stopSession": "リモートセッションを停止",
"sessionNotFoundResync": "現在のリモートセッションが見つかりません。再同期してから送信してください。",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index 06e3c05827..ba35459395 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -257,6 +257,7 @@
"voiceSenderNotReady": "지금은 메시지를 보낼 수 없습니다. 뒤로 갔다가 세션을 다시 여세요.",
"voiceStopAndSend": "음성 입력 종료 후 전송",
"sendMessage": "원격 메시지 보내기",
+ "inputSyncFailed": "입력 내용을 모두 읽지 못했습니다. 내용은 유지되니 다시 시도해 주세요.",
"voiceStartInput": "음성 입력 시작",
"stopSession": "원격 세션 중지",
"sessionNotFoundResync": "현재 원격 세션을 찾을 수 없습니다. 다시 동기화한 후 보내세요.",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index 50f2f001ce..a3567ed000 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -257,6 +257,7 @@
"voiceSenderNotReady": "消息暂时无法发送,请返回后重新进入任务。",
"voiceStopAndSend": "结束语音输入并发送",
"sendMessage": "发送远程消息",
+ "inputSyncFailed": "未能读取完整输入,内容已保留,请重试。",
"voiceStartInput": "开始语音输入",
"stopSession": "停止远程任务",
"sessionNotFoundResync": "未找到当前远程任务,请重新同步后再发送。",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index 70a4e7847d..70adb31496 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -261,6 +261,7 @@
"voiceSenderNotReady": "訊息暫時無法傳送,請返回後重新進入任務。",
"voiceStopAndSend": "結束語音輸入並傳送",
"sendMessage": "傳送遠端訊息",
+ "inputSyncFailed": "未能讀取完整輸入,內容已保留,請重試。",
"voiceStartInput": "開始語音輸入",
"stopSession": "停止遠端任務",
"sessionNotFoundResync": "未找到當前遠端任務,請重新同步後再傳送。",
diff --git a/apps/mobile/src/session/ComposerRichInput.tsx b/apps/mobile/src/session/ComposerRichInput.tsx
index a54b532b9a..56529b4ad2 100644
--- a/apps/mobile/src/session/ComposerRichInput.tsx
+++ b/apps/mobile/src/session/ComposerRichInput.tsx
@@ -29,6 +29,8 @@ import { useComposerWebViewRecovery } from '@/session/useComposerWebViewRecovery
export interface ComposerRichInputHandle {
expand?(): void;
+ /** WebView read barrier; validates the caller's scope before acknowledging the draft. */
+ flushDocument?(isCurrent?: () => boolean): Promise<ComposerDocument>;
getSelection(draft: string): ComposerSelection;
rememberSelection(draft: string, selection: { start: number; end: number }): void;
applyDocumentAndSetSelectionToEnd(document: ComposerDocument): void;
@@ -117,6 +119,22 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
/** 尚未交接给附件上传 hook 的 WebView 粘贴缓存文件。 */
const pendingPastedImageFilesRef = useRef(new Set<string>());
const disposedRef = useRef(false);
+ const snapshotSequenceRef = useRef(0);
+ const pendingSnapshotRef = useRef<{
+ requestId: number;
+ documentId: number;
+ isCurrent?: () => boolean;
+ resolve(document: ComposerDocument): void;
+ reject(error: Error): void;
+ timer: ReturnType<typeof setTimeout>;
+ } | null>(null);
+ const rejectSnapshot = useCallback(() => {
+ const pending = pendingSnapshotRef.current;
+ if (!pending) return;
+ pendingSnapshotRef.current = null;
+ clearTimeout(pending.timer);
+ pending.reject(new Error('COMPOSER_SNAPSHOT_UNAVAILABLE'));
+ }, []);
const initialConfigRef = useRef({
accessibilityLabel,
document,
@@ -157,6 +175,7 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
webViewRef.current?.injectJavaScript(`try { ${script} } catch (_) {} true;`);
}, []);
const recovery = useComposerWebViewRecovery(inject, () => {
+ rejectSnapshot();
readyRef.current = false;
pendingFocusRef.current = false;
if (pendingDocumentRef.current) pendingDocumentRef.current.focusAfter = false;
@@ -179,6 +198,7 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
if (Platform.OS === 'android') webViewRef.current?.requestFocus();
}, [inject]);
const applyDocument = useCallback((value: ComposerDocument, focusAfter = false, caret?: { nodeIndex: number; offset: number }) => {
+ rejectSnapshot();
if (value !== webDocumentRef.current.document && selectionRef.current?.atomRange) selectionRef.current = null;
const documentId = webDocumentRef.current.id + 1;
webDocumentRef.current = { document: value, draft: composerDocumentProjectedText(value), id: documentId };
@@ -188,7 +208,7 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
}
inject(`window.cindyComposer.applyDocument(${JSON.stringify(value)}, ${focusAfter}, ${JSON.stringify(caret) ?? 'null'}, ${documentId});`);
if (focusAfter && Platform.OS === 'android') webViewRef.current?.requestFocus();
- }, [inject]);
+ }, [inject, rejectSnapshot]);
useEffect(() => {
// A native edit may advance again before React commits its previous
@@ -207,6 +227,16 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
useEffect(() => {
if (!forwardedRef) return undefined;
const handle: ComposerRichInputHandle = {
+ flushDocument: (isCurrent) => {
+ if (!readyRef.current || disposedRef.current) return Promise.reject(new Error('COMPOSER_SNAPSHOT_UNAVAILABLE'));
+ rejectSnapshot();
+ return new Promise<ComposerDocument>((resolve, reject) => {
+ const requestId = ++snapshotSequenceRef.current;
+ pendingSnapshotRef.current = { requestId, documentId: webDocumentRef.current.id, isCurrent,
+ resolve, reject, timer: setTimeout(rejectSnapshot, 3000) };
+ inject(`window.cindyComposer.snapshot(${requestId});`);
+ });
+ },
getSelection: (draft) => {
const saved = selectionRef.current;
return saved?.draft === draft
@@ -261,7 +291,7 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
if (typeof forwardedRef === 'function') forwardedRef(null);
else forwardedRef.current = null;
};
- }, [applyDocument, focusEditor, forwardedRef, inject]);
+ }, [applyDocument, focusEditor, forwardedRef, inject, rejectSnapshot]);
const persistPastedImage = useCallback(async (
message: Extract<ComposerWebMessage, { type: 'paste-image' }>,
@@ -318,6 +348,7 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
disposedRef.current = false;
return () => {
disposedRef.current = true;
+ rejectSnapshot();
// sessionId 原地换代时 ComposerRichInput 会重挂载。旧实例的异步图片写盘即使
// 随后落定,也不能再沿旧闭包调用新任务的 onPasteImages / load-failed;先摘掉
// 批次登记,settlePastedImage 会把迟到结果视为已作废。
@@ -327,7 +358,7 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
pendingPastedImageFilesRef.current.clear();
if (pendingUris.length > 0) void deleteComposerPastedImageUris(pendingUris);
};
- }, []);
+ }, [rejectSnapshot]);
const settlePastedImage = useCallback((
requestId: string,
@@ -388,6 +419,7 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
if (!message) return;
if (message.type === 'pong') return recovery.onPong(message.id);
if (message.type === 'ready') {
+ rejectSnapshot();
recovery.onReady();
readyRef.current = true;
inject(`window.cindyComposer.setConfig(${JSON.stringify(runtimeConfig)});`);
@@ -408,16 +440,29 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
}
return;
}
- if (message.type === 'change') {
+ if (message.type === 'change' || message.type === 'snapshot') {
+ const pending = message.type === 'snapshot' ? pendingSnapshotRef.current : null;
+ if (message.type === 'snapshot') {
+ if (!pending || pending.requestId !== message.requestId) return;
+ // Cancellation can restore the caller's draft before its next render.
+ // Reject before touching editor state or invoking the persistence callback.
+ if (pending.isCurrent?.() === false) { rejectSnapshot(); return; }
+ if (message.pendingPaste || message.documentId !== pending.documentId) { rejectSnapshot(); return; }
+ }
if ((message.documentId ?? 0) !== webDocumentRef.current.id) return;
const next = parseStoredComposerDocument(message.document);
- if (!next) return;
+ if (!next) { if (pending) rejectSnapshot(); return; }
const normalized = normalizeComposerDocument(next);
+ if (pending) {
+ pendingSnapshotRef.current = null;
+ clearTimeout(pending.timer);
+ }
if (selectionRef.current?.atomRange) selectionRef.current = null;
webSignatureRef.current = JSON.stringify(normalized);
webDocumentRef.current = { document: normalized, draft: composerDocumentProjectedText(normalized), id: webDocumentRef.current.id };
localDocumentsRef.current.add(normalized);
onChangeDocument(normalized);
+ pending?.resolve(normalized);
return;
}
if (message.type === 'selection') {
@@ -472,7 +517,7 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
}
});
}
- }, [applyDocument, commitPlainTextPaste, focusEditor, hidden, inject, maxHeight, onBlur, onChangeDocument, onFocus, onHeightChange, onPasteImagesLoading, persistPastedImage, runtimeConfig, settlePastedImage, generation, currentGeneration, recovery.onPong, recovery.onReady]);
+ }, [applyDocument, commitPlainTextPaste, focusEditor, hidden, inject, maxHeight, onBlur, onChangeDocument, onFocus, onHeightChange, onPasteImagesLoading, persistPastedImage, runtimeConfig, settlePastedImage, generation, currentGeneration, recovery.onPong, recovery.onReady, rejectSnapshot]);
const heightStyle = useAnimatedStyle(() => ({ height: animatedHeight?.value ?? height }));
return (
diff --git a/apps/mobile/src/session/composerRichInputHtml.ts b/apps/mobile/src/session/composerRichInputHtml.ts
index b0e9a0a804..6458e2e140 100644
--- a/apps/mobile/src/session/composerRichInputHtml.ts
+++ b/apps/mobile/src/session/composerRichInputHtml.ts
@@ -39,7 +39,7 @@ export interface ComposerRichInputConfig {
/**
* The editor intentionally has no network dependencies. Native owns the
* semantic document; this page owns IME/selection and reports normalized DOM
- * changes after composition commits.
+ * changes without replacing the active IME's DOM on native acknowledgements.
*/
export function buildComposerRichInputHtml(config: ComposerRichInputConfig): string {
const bootstrap = JSON.stringify(config).replace(/</g, '\\u003c');
@@ -186,8 +186,7 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): str
};
const render = (documentValue, focusAfter) => {
// Programmatic DOM replace (inserting a directory chip, applying a draft)
- // can drop compositionend. If composing stays true, later input is visible
- // but never posted, so the send button stays disabled.
+ // can drop compositionend. Clear its selection guard for the new document.
composing = false;
applying = true;
reportUserSelection = false;
@@ -309,7 +308,9 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): str
post({ type: 'height', height });
};
const notify = () => {
- if (applying || composing) return;
+ // Preedit is visible draft content too. Native acknowledges these documents
+ // without rendering them back into this DOM, preserving the IME and caret.
+ if (applying) return;
const value = readDocument();
const signature = JSON.stringify(value);
if (signature !== lastSignature) {
@@ -579,6 +580,12 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): str
window.cindyComposer = {
ping(id) { post({ type: 'pong', id }); },
+ snapshot(requestId) {
+ // A read barrier, not a blur/DOM replacement: Send must await this reply,
+ // even if the last input/change event is still crossing the native bridge.
+ const pendingPaste = Array.from(pasteMarkers.values()).some(({ marker }) => root.contains(marker));
+ post({ type: 'snapshot', requestId, documentId, document: readDocument(), pendingPaste });
+ },
applyDocument(value, focusAfter, caret, nextDocumentId) {
if (Number.isSafeInteger(nextDocumentId)) documentId = nextDocumentId;
render(value, focusAfter === true && !caret);
diff --git a/apps/mobile/src/session/composerRichInputProtocol.ts b/apps/mobile/src/session/composerRichInputProtocol.ts
index c9081f5503..d6645353cf 100644
--- a/apps/mobile/src/session/composerRichInputProtocol.ts
+++ b/apps/mobile/src/session/composerRichInputProtocol.ts
@@ -11,6 +11,7 @@ export type ComposerWebMessage =
| { type: 'pong'; id: number }
| { type: 'height'; height: number }
| { type: 'change'; document: unknown; documentId?: number }
+ | { type: 'snapshot'; requestId: number; documentId: number; document: unknown; pendingPaste: boolean }
| { type: 'selection'; documentId: number; before: ComposerSelectionPrefix; through: ComposerSelectionPrefix }
| { type: 'paste-text-request'; requestId: string; text?: string }
| { type: 'paste-images-start'; requestId: string; count: number }
@@ -56,6 +57,11 @@ export function parseComposerWebMessage(raw: string): ComposerWebMessage | null
return { type: 'change', document: message.document,
...(message.documentId === undefined ? {} : { documentId: message.documentId as number }) };
}
+ if (message.type === 'snapshot') {
+ if (!isOffset(message.requestId) || !isOffset(message.documentId) || typeof message.pendingPaste !== 'boolean') return null;
+ return { type: 'snapshot', requestId: message.requestId, documentId: message.documentId,
+ document: message.document, pendingPaste: message.pendingPaste };
+ }
if (message.type === 'selection') {
if (!isOffset(message.documentId) || !isPrefix(message.before) || !isPrefix(message.through)) return null;
return { type: 'selection', documentId: message.documentId, before: message.before, through: message.through };
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index 0be24e3fbe..ff914508e1 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -113,6 +113,22 @@ pnpm --filter mobile test:smoke
## 专项入口
+### Android 组字与发送快照
+
+WebView 输入框把屏幕可见的组字文本同步为草稿;React Native 接受本地编辑的回传时不重写
+DOM,保留输入法组字与光标。点击发送后,在发送防重锁内等待编辑器返回当前完整
+`ComposerDocument`,再做空内容判断、命令解析和入队,不依赖失焦或 `compositionend` 的顺序。
+等待期间账号、设备、任务、编辑器或排队编辑目标变化时取消本次提交;读取失败、超时或
+粘贴尚未替换完成时保留输入并提示重试,不回退到旧草稿发送。语音结果、独立快捷发送和
+显式传入的文档保持各自的快照来源,iOS 原生编辑器保留现有原生路径。
+快照回包在写回编辑器状态或草稿之前核对调用方作用域;不能只在 `await` 返回后检查,
+否则取消排队编辑与下一帧渲染之间到达的旧快照会覆盖已恢复的原草稿。
+
+实现:`ComposerRichInput.tsx`、`composerRichInputHtml.ts` 与 `app/sessions/[sessionId].tsx`;
+回归:`composerRichInputLifecycle.test.tsx`、`composerRichInputHtml.test.ts`。Android 模拟器
+可用 mock 模式配合 CDP `Input.imeSetComposition` 检查点击原生发送按钮后的完整文本;
+它不替代三星真机键盘或真实跨设备送达验收。
+
### 相册选图与 iCloud 原图
iOS 的系统选图器在确认后立即把选中项交给现有附件队列。首帧预览只读取本机小缩略图,