Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 从当前光标插入语音转写 (#3989)
Dashcb80ab883564
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 40cfa85860..4d969c9c5d 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -59,7 +59,6 @@ import {type PressableProps,type StyleProp,type TextInputContentSizeChangeEvent,- type TextLayoutEvent,type ViewStyle,} from 'react-native';import { Text, TextInput } from '@/components/AppText';@@ -278,12 +277,14 @@ import {migrateLegacyComposerDraft,normalizeComposerDocument,reconcileComposerProjectedText,+ reconcileComposerVoiceDraft,replaceComposerTextRange,serializeComposerDocument,sessionLinkComposerNode,slashCommandTextNode,textComposerDocument,type ComposerDocument,+ type ComposerVoiceDraftUpdate,} from '@/session/composerDocument';import { boundAgentReferenceText } from '@cindy/maker-shared/agent-input-projection';import {@@ -646,7 +647,6 @@ const COMPOSER_STACK_GAP_HEIGHT = 4;const COMPOSER_INPUT_ROW_CHROME_HEIGHT = 22;// 聚焦卡片形态的 row chrome:paddingTop 26 + paddingBottom 8 + 层间 gap 8 + 工具排 ~36。const COMPOSER_CARD_ROW_CHROME_HEIGHT = 78;-const COMPOSER_VOICE_CARET_GAP = 2;// 重开且检测到有新内容时,只拉最新小窗对账(比首开整窗 80 便宜很多);payload 过大再逐档退。const REOPEN_MESSAGE_WINDOW_LIMITS = [20, 10, 5, 1] as const;// session-tail-banner「重试」短窗口隐藏的超时兜底(接管信号全部丢失时恢复错误入口);@@ -2732,7 +2732,9 @@ export default function SessionScreen() {applyComposerDraft(value, queueEditingRef.current ? { persist: false } : undefined);}, [applyComposerDraft]);- const writeVoiceDraft = useComposerVoiceDraftWriter(sessionId, setComposerDraft);+ const writeVoiceDraft = useComposerVoiceDraftWriter(sessionId, (update: ComposerVoiceDraftUpdate) => {+ applyRichComposerChange(reconcileComposerVoiceDraft(composerDocumentRef.current, update));+ });useEffect(() => {const tracker = createMobileVoiceDictionaryLearningTracker({@@ -4803,6 +4805,11 @@ export default function SessionScreen() {return;}const startController = async () => {+ const initialDraft = draftRef.current;+ const initialDocument = composerDocumentRef.current;+ const input = composerInputRef.current;+ const initialSelection = input?.getSelection(initialDraft)+ ?? { start: initialDraft.length, end: initialDraft.length };const controller = createMobileVoiceControllerSession({credential,...(prewarmedVoice ? { asr: prewarmedVoice.asr } : {}),@@ -4811,11 +4818,15 @@ export default function SessionScreen() {voiceContext.createRefinerTarget(providerId, options),warmRefiner: (input: { system: string; user: unknown; promptCacheKey: string }) =>voiceContext.warmRefiner(input),- initialDraft: draftRef.current,- refinementContext: buildMobileVoiceSessionRefinementContext(draftRef.current, renderItems),+ initialDraft,+ initialSelection,+ refinementContext: buildMobileVoiceSessionRefinementContext(initialDraft, renderItems, initialSelection),localVoiceInputHistory,readCurrentDraft: () => draftRef.current,- onDraftChanged: writeVoiceDraft,+ onDraftChanged: (text, selection, replacement) => {+ if (selection) input?.rememberSelection(text, selection);+ writeVoiceDraft({ draft: text, initialDocument, initialSelection, insertionEnd: selection?.end, replacement });+ },onStateChanged: setVoiceState,onError: (message) => {setVoiceState('error');@@ -5015,20 +5026,22 @@ export default function SessionScreen() {// stop() can deliver an empty final transcript through onDraftChanged before// resolving. Capture the rich document first so quote/reference atoms survive.const documentBeforeStop = composerDocumentRef.current;+ const inputBeforeStop = composerInputRef.current;const latestDraft = await controller.stop();await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);setVoiceState('done');- // 听写结束落焦(既有行为,显式 focus 承担弹键盘语义):focus 的 web 侧- // 实现即 placeCaretAtEnd,caret 落在转写文字末尾。听写**进行中**禁止任何- // 程序化 focus(见 voiceIsListening 滚动效应的注释)。- requestAnimationFrame(() => {- composerInputRef.current?.focus();- });// chat-text-quote:纯引用(无转写文字、无附件)也要发出去——发送按钮在// quote-only 时可见,漏了引用会变成「点发送只停了录音、消息没发」。const latestDocument = latestDraft.trim()- ? reconcileComposerProjectedText(documentBeforeStop, latestDraft)+ ? reconcileComposerProjectedText(composerDocumentRef.current, latestDraft): documentBeforeStop;+ // Focus only after dictation ends, with the caret after the inserted text.+ const insertionEnd = composerInputRef.current?.getSelection(latestDraft).end ?? latestDraft.length;+ requestAnimationFrame(() => {+ if (inputBeforeStop && composerInputRef.current === inputBeforeStop && draftRef.current === latestDraft) {+ inputBeforeStop.applyDocumentAndFocusSelection(composerDocumentRef.current, insertionEnd);+ }+ });if (options.sendAfterTranscribe && (composerDocumentHasContent(latestDocument) || attachments.length > 0)) {const sendLatest = sendLatestRef.current;if (!sendLatest) throw new Error(t('session.screen.voiceSenderNotReady'));@@ -10080,6 +10093,8 @@ function SessionComposerInput({const [composerFocused, setComposerFocused] = useState(false);const [composerInputContentHeight, setComposerInputContentHeight] = useState(COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT);const [voiceDraftCaretFrame, setVoiceDraftCaretFrame] = useState({ left: 0, top: 0 });+ const voiceDraftCaretRef = useRef<View>(null);+ const voiceDraftMeasuredBlockRef = useRef<View>(null);const composerScrollViewRef = useRef<ScrollView>(null);const composerScrollEnabledRef = useRef(false);const voiceDraftScrollRef = useRef<ScrollView>(null);@@ -10272,19 +10287,15 @@ function SessionComposerInput({Math.abs(currentHeight - nextHeight) < 1 ? currentHeight : nextHeight));}, []);- const handleVoiceDraftTextLayout = useCallback((event: TextLayoutEvent) => {- const lines = event.nativeEvent.lines;- const lastLine = lines[lines.length - 1];- if (!lastLine) return;- const nextFrame = {- left: Math.max(0, Math.round(lastLine.x + lastLine.width + COMPOSER_VOICE_CARET_GAP)),- top: Math.max(0, Math.round(lastLine.y + ((lastLine.height - COMPOSER_INPUT_LINE_HEIGHT) / 2))),- };- setVoiceDraftCaretFrame((currentFrame) => (- currentFrame.left === nextFrame.left && currentFrame.top === nextFrame.top- ? currentFrame- : nextFrame- ));+ const handleVoiceDraftTextLayout = useCallback(() => {+ const block = voiceDraftMeasuredBlockRef.current;+ const caret = voiceDraftCaretRef.current;+ if (!block || !caret) return;+ caret.measureLayout(block, (x, y) => {+ if (caret !== voiceDraftCaretRef.current || block !== voiceDraftMeasuredBlockRef.current) return;+ const nextFrame = { left: Math.max(0, Math.round(x)), top: Math.max(0, Math.round(y)) };+ setVoiceDraftCaretFrame((current) => current.left === nextFrame.left && current.top === nextFrame.top ? current : nextFrame);+ }, () => undefined);}, []);const renderComposerResizeHandle = () => (@@ -10297,6 +10308,7 @@ function SessionComposerInput({/>);+ const voiceDraftInsertionEnd = composerInputRef.current?.getSelection(draft).end ?? draft.length;const renderComposerInputOverlay = () => voiceIsListening ? (// 「点输入区 = 想打字 → 停止听写」由这层 RN 覆盖层承接。听写期间真正盖在输入区上的// 就是它;底下的富文本 WebView 此刻是 hidden(opacity 0),iOS hitTest 会跳过 alpha≈0@@ -10321,12 +10333,12 @@ function SessionComposerInput({]}onContentSizeChange={() => {requestAnimationFrame(() => {- voiceDraftScrollRef.current?.scrollToEnd({ animated: false });+ voiceDraftScrollRef.current?.scrollTo({ y: voiceDraftCaretFrame.top, animated: false });});}}onLayout={() => {requestAnimationFrame(() => {- voiceDraftScrollRef.current?.scrollToEnd({ animated: false });+ voiceDraftScrollRef.current?.scrollTo({ y: voiceDraftCaretFrame.top, animated: false });});}}pointerEvents="none"@@ -10340,25 +10352,12 @@ function SessionComposerInput({<Text style={styles.voiceDraftListeningText}>{composerLayout.input.placeholder}</Text></View>) : (- <View style={styles.voiceDraftMeasuredBlock}>- <Text- onTextLayout={handleVoiceDraftTextLayout}- style={styles.voiceDraftText}- >- {draft}+ <View ref={voiceDraftMeasuredBlockRef} collapsable={false} style={styles.voiceDraftMeasuredBlock}>+ <Text onTextLayout={handleVoiceDraftTextLayout} style={styles.voiceDraftText}>+ {draft.slice(0, voiceDraftInsertionEnd)}+ <VoiceMicWaveCaret color={colors.textPrimary} testID="session.voiceMicCaret" viewRef={voiceDraftCaretRef} />+ {draft.slice(voiceDraftInsertionEnd)}</Text>- <View- pointerEvents="none"- style={[- styles.voiceDraftCaretOverlay,- {- left: voiceDraftCaretFrame.left,- top: voiceDraftCaretFrame.top,- },- ]}- >- <VoiceMicWaveCaret color={colors.textPrimary} testID="session.voiceMicCaret" />- </View></View>)}</ScrollView>@@ -10374,10 +10373,10 @@ function SessionComposerInput({useEffect(() => {if (!voiceIsListening) return undefined;const frame = requestAnimationFrame(() => {- voiceDraftScrollRef.current?.scrollToEnd({ animated: false });+ voiceDraftScrollRef.current?.scrollTo({ y: voiceDraftCaretFrame.top, animated: false });});return () => cancelAnimationFrame(frame);- }, [composerInputContentHeight, composerInputVisibleHeight, draft, voiceIsListening]);+ }, [composerInputContentHeight, composerInputVisibleHeight, draft, voiceDraftCaretFrame.top, voiceIsListening]);useEffect(() => {if (voiceIsListening && draft.length > 0) return;@@ -10744,11 +10743,15 @@ function readRecord(value: unknown): Record<string, unknown> | null {function buildMobileVoiceSessionRefinementContext(draftText: string,items: readonly MobileMessageRenderItem[],+ selection: { start: number; end: number },) {- const selectionBefore = takeRefinementContextTail(draftText);+ const selectionBefore = takeRefinementContextTail(draftText.slice(0, selection.start));+ const selectionAfter = draftText.slice(selection.end, selection.end + 1200);const replyToMessage = findLastAssistantMessageText(items);return {selectionBefore: selectionBefore || undefined,+ selectedText: draftText.slice(selection.start, selection.end).slice(0, 1200) || undefined,+ selectionAfter: selectionAfter || undefined,replyToMessage: replyToMessage || undefined,};}@@ -11574,9 +11577,6 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({minHeight: COMPOSER_INPUT_LINE_HEIGHT,position: 'relative',},- voiceDraftCaretOverlay: {- position: 'absolute',- },// 草稿层的文本档必须与真实 TextInput 完全一致,否则换行位置错开、超出的行被裁在// 框外(见 MOBILE_COMPOSER_DRAFT_TEXT_STYLE)。voiceDraftText: {diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 2cfd56de45..5489cbafed 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -27,7 +27,6 @@ import {useWindowDimensions,type StyleProp,type TextInputContentSizeChangeEvent,- type TextLayoutEvent,type ViewStyle,} from 'react-native';import { Text } from '@/components/AppText';@@ -331,7 +330,6 @@ import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';const COMPOSER_INPUT_MULTILINE_CONTENT_THRESHOLD = 34;-const COMPOSER_VOICE_CARET_GAP = 2;// composer 除输入区外的 chrome 高度估算(输入行上下 padding + 边框),// 只用于给拖拽调高的上限留余量,与会话页同量级。const COMPOSER_RESIZE_CHROME_HEIGHT = 34;@@ -697,6 +695,7 @@ export default function NewRemoteSessionScreen() {const userTouchedDeviceRef = useRef(false);const userTouchedWorkspaceRef = useRef(false);const firstMessageRef = useRef(draft.firstMessage);+ const firstMessageSelectionRef = useRef({ start: draft.firstMessage.length, end: draft.firstMessage.length });const firstMessageInputRef = useRef<NativeTextInput>(null);const voiceDraftScrollRef = useRef<ScrollView>(null);const voiceRecordingActiveRef = useRef(false);@@ -712,6 +711,8 @@ export default function NewRemoteSessionScreen() {const [firstMessageInputContentHeight, setFirstMessageInputContentHeight] = useState(MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT);const [firstMessageInputFocused, setFirstMessageInputFocused] = useState(false);const [voiceDraftCaretFrame, setVoiceDraftCaretFrame] = useState({ left: 0, top: 0 });+ const voiceDraftCaretRef = useRef<View>(null);+ const voiceDraftMeasuredBlockRef = useRef<View>(null);// 自动默认运行配置(跟随最近会话 / 区域默认 / 列表最上面)的守卫:用户一旦手动选过模型,就不再自动覆盖;// 记录已自动应用过的设备,切设备时(未手动选过)按新设备重算。const userTouchedRuntimeRef = useRef(false);@@ -1593,19 +1594,15 @@ export default function NewRemoteSessionScreen() {));}, []);- const handleVoiceDraftTextLayout = useCallback((event: TextLayoutEvent) => {- const lines = event.nativeEvent.lines;- const lastLine = lines[lines.length - 1];- if (!lastLine) return;- const nextFrame = {- left: Math.max(0, Math.round(lastLine.x + lastLine.width + COMPOSER_VOICE_CARET_GAP)),- top: Math.max(0, Math.round(lastLine.y + ((lastLine.height - MOBILE_COMPOSER_INPUT_LINE_HEIGHT) / 2))),- };- setVoiceDraftCaretFrame((currentFrame) => (- currentFrame.left === nextFrame.left && currentFrame.top === nextFrame.top- ? currentFrame- : nextFrame- ));+ const handleVoiceDraftTextLayout = useCallback(() => {+ const block = voiceDraftMeasuredBlockRef.current;+ const caret = voiceDraftCaretRef.current;+ if (!block || !caret) return;+ caret.measureLayout(block, (x, y) => {+ if (caret !== voiceDraftCaretRef.current || block !== voiceDraftMeasuredBlockRef.current) return;+ const nextFrame = { left: Math.max(0, Math.round(x)), top: Math.max(0, Math.round(y)) };+ setVoiceDraftCaretFrame((current) => current.left === nextFrame.left && current.top === nextFrame.top ? current : nextFrame);+ }, () => undefined);}, []);const cancelVoiceForDeviceSwitch = useCallback(() => {@@ -3122,6 +3119,7 @@ export default function NewRemoteSessionScreen() {// used to add 0.6–4.4s before the mic could open.void openLink(selectedDeviceId).catch(() => undefined);const currentDraft = firstMessageRef.current;+ const initialSelection = { ...firstMessageSelectionRef.current };// Claim the connection prewarmed at pressIn (if any): its credential is// already resolved and its ASR WebSocket already connecting, so the// handshake overlaps the press gesture instead of following it.@@ -3163,7 +3161,8 @@ export default function NewRemoteSessionScreen() {}return;}- const selectionBefore = takeRefinementContextTail(currentDraft) || undefined;+ const selectionBefore = takeRefinementContextTail(currentDraft.slice(0, initialSelection.start));+ const selectionAfter = currentDraft.slice(initialSelection.end, initialSelection.end + 1200);const controller = createMobileVoiceControllerSession({credential,...(prewarmedVoice ? { asr: prewarmedVoice.asr } : {}),@@ -3173,10 +3172,18 @@ export default function NewRemoteSessionScreen() {warmRefiner: (input: { system: string; user: unknown; promptCacheKey: string }) =>voiceContext.warmRefiner(input),initialDraft: currentDraft,- refinementContext: selectionBefore ? { selectionBefore } : undefined,+ initialSelection,+ refinementContext: {+ selectionBefore: selectionBefore || undefined,+ selectedText: currentDraft.slice(initialSelection.start, initialSelection.end).slice(0, 1200) || undefined,+ selectionAfter: selectionAfter || undefined,+ },localVoiceInputHistory,readCurrentDraft: () => firstMessageRef.current,- onDraftChanged: setFirstMessageDraft,+ onDraftChanged: (text, selection) => {+ if (selection) firstMessageSelectionRef.current = selection;+ setFirstMessageDraft(text);+ },onStateChanged: setVoiceState,onError: (message) => {setVoiceState('error');@@ -3273,8 +3280,7 @@ export default function NewRemoteSessionScreen() {await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);setVoiceState('done');requestAnimationFrame(() => {- const end = latestDraft.length;- firstMessageInputRef.current?.setNativeProps({ selection: { start: end, end } });+ firstMessageInputRef.current?.setNativeProps({ selection: firstMessageSelectionRef.current });});return latestDraft;} catch (err) {@@ -3357,12 +3363,11 @@ export default function NewRemoteSessionScreen() {useEffect(() => {if (!voiceIsListening) return undefined;const frame = requestAnimationFrame(() => {- const end = firstMessageRef.current.length;- firstMessageInputRef.current?.setNativeProps({ selection: { start: end, end } });- voiceDraftScrollRef.current?.scrollToEnd({ animated: false });+ firstMessageInputRef.current?.setNativeProps({ selection: firstMessageSelectionRef.current });+ voiceDraftScrollRef.current?.scrollTo({ y: voiceDraftCaretFrame.top, animated: false });});return () => cancelAnimationFrame(frame);- }, [composerInputContentHeight, draft.firstMessage, voiceIsListening]);+ }, [composerInputContentHeight, draft.firstMessage, voiceDraftCaretFrame.top, voiceIsListening]);useEffect(() => {if (voiceIsListening && draft.firstMessage.length > 0) return;@@ -3529,12 +3534,12 @@ export default function NewRemoteSessionScreen() {]}onContentSizeChange={() => {requestAnimationFrame(() => {- voiceDraftScrollRef.current?.scrollToEnd({ animated: false });+ voiceDraftScrollRef.current?.scrollTo({ y: voiceDraftCaretFrame.top, animated: false });});}}onLayout={() => {requestAnimationFrame(() => {- voiceDraftScrollRef.current?.scrollToEnd({ animated: false });+ voiceDraftScrollRef.current?.scrollTo({ y: voiceDraftCaretFrame.top, animated: false });});}}pointerEvents="none"@@ -3548,25 +3553,12 @@ export default function NewRemoteSessionScreen() {<Text style={styles.voiceDraftListeningText}>{composerListeningPlaceholder}</Text></View>) : (- <View style={styles.voiceDraftMeasuredBlock}>- <Text- onTextLayout={handleVoiceDraftTextLayout}- style={styles.voiceDraftText}- >- {draft.firstMessage}+ <View ref={voiceDraftMeasuredBlockRef} collapsable={false} style={styles.voiceDraftMeasuredBlock}>+ <Text onTextLayout={handleVoiceDraftTextLayout} style={styles.voiceDraftText}>+ {draft.firstMessage.slice(0, firstMessageSelectionRef.current.end)}+ <VoiceMicWaveCaret color={colors.textPrimary} testID="newSession.voiceMicCaret" viewRef={voiceDraftCaretRef} />+ {draft.firstMessage.slice(firstMessageSelectionRef.current.end)}</Text>- <View- pointerEvents="none"- style={[- styles.voiceDraftCaretOverlay,- {- left: voiceDraftCaretFrame.left,- top: voiceDraftCaretFrame.top,- },- ]}- >- <VoiceMicWaveCaret color={colors.textPrimary} testID="newSession.voiceMicCaret" />- </View></View>)}</ScrollView>@@ -5828,6 +5820,11 @@ export default function NewRemoteSessionScreen() {setComposerVoiceHoldArmed(false);}}onChangeText={setFirstMessageDraft}+ onSelectionChange={(event) => {+ if (!voiceRecordingActiveRef.current && !voiceStopInFlightRef.current) {+ firstMessageSelectionRef.current = event.nativeEvent.selection;+ }+ }}onContentSizeChange={handleFirstMessageInputContentSizeChange}onFocus={() => setFirstMessageInputFocused(true)}onPasteImages={(uris) => void addPastedImageAttachments(uris)}@@ -6759,9 +6756,6 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({minHeight: MOBILE_COMPOSER_INPUT_LINE_HEIGHT,position: 'relative',},- voiceDraftCaretOverlay: {- position: 'absolute',- },// 草稿层的文本档必须与真实 TextInput 完全一致,否则换行位置错开、超出的行被裁在// 框外(见 MOBILE_COMPOSER_DRAFT_TEXT_STYLE)。voiceDraftText: {diff --git a/apps/mobile/src/__tests__/composerDocument.test.ts b/apps/mobile/src/__tests__/composerDocument.test.tsindex fbf55d38f8..030ecbf7ac 100644--- a/apps/mobile/src/__tests__/composerDocument.test.ts+++ b/apps/mobile/src/__tests__/composerDocument.test.ts@@ -5,6 +5,8 @@ import {composerDocumentFromEncodedMessage,composerDocumentFromSerializedMessage,composerDocumentProjectedText,+ composerCaretPosition,+ composerSelectionOffset,hydrateComposerMessageReferenceBodies,isLongComposerPaste,mentionComposerNode,@@ -13,6 +15,8 @@ import {pastedTextComposerNode,parseStoredComposerDocument,reconcileComposerProjectedText,+ reconcileComposerVoiceDraft,+ type ComposerDocument,removeComposerNode,replaceComposerTextRange,serializeComposerDocument,@@ -22,6 +26,77 @@ import {} from '@/session/composerDocument';describe('mobile composer document', () => {+ it.each([+ [0, 2, 0, 1, 'voice'],+ [1, 1, 0, 1, 'avoiceb'],+ [1, 1, 0, 0, 'avoice|b'],+ [1, 1, 1, 1, 'a|voiceb'],+ [0, 1, 0, 0, 'voice|b'],+ [1, 2, 1, 1, 'a|voice'],+ ])('replaces structural voice selection [%i, %i] atoms [%i, %i]', (start, end, atomStart, atomEnd, expected) => {+ const initialDocument: ComposerDocument = { version: 1, nodes: [+ { type: 'text', text: 'a' }, { type: 'quote', quote: { text: 'quote' } }, { type: 'text', text: 'b' },+ ] };+ const result = reconcileComposerVoiceDraft(initialDocument, {+ draft: 'ab'.slice(0, start) + 'voice' + 'ab'.slice(end), initialDocument,+ initialSelection: { start, end, atomRange: { start: atomStart, end: atomEnd } }, insertionEnd: start + 5,+ });+ expect(result.nodes.map((node) => node.type === 'quote' ? '|' : node.type === 'text' ? node.text : '?').join('')).toBe(expected);+ });++ it('removes only the selected quote among consecutive zero-width atoms', () => {+ const initialDocument: ComposerDocument = { version: 1, nodes: ['one', 'two', 'three'].map((text) => ({ type: 'quote', quote: { text } })) };+ const result = reconcileComposerVoiceDraft(initialDocument, {+ draft: 'voice', initialDocument, initialSelection: { start: 0, end: 0, atomRange: { start: 1, end: 2 } }, insertionEnd: 5,+ });+ expect(result.nodes).toEqual([initialDocument.nodes[0], { type: 'text', text: 'voice' }, initialDocument.nodes[2]]);+ expect(serializeComposerDocument(result).text).not.toContain('two');+ });++ it('keeps repeated streaming text on the original side of an unselected quote', () => {+ const initialDocument: ComposerDocument = { version: 1, nodes: [+ { type: 'text', text: 'a' }, { type: 'quote', quote: { text: 'quote' } }, { type: 'text', text: 'a' },+ ] };+ const update = { draft: 'aa', initialDocument, initialSelection: { start: 0, end: 1, atomRange: { start: 0, end: 0 } }, insertionEnd: 1 };+ const first = reconcileComposerVoiceDraft(initialDocument, update);+ const next = reconcileComposerVoiceDraft(first, { ...update, draft: 'aaa', replacement: { start: 0, end: 1, text: 'aa' } });+ expect(next.nodes).toEqual([{ type: 'text', text: 'aa' }, initialDocument.nodes[1], { type: 'text', text: 'a' }]);+ });++ it('does not reuse captured atom selection after the document was edited', () => {+ const initialDocument: ComposerDocument = { version: 1, nodes: [{ type: 'quote', quote: { text: 'keep' } }] };+ const edited = appendComposerNode(initialDocument, { type: 'text', text: 'typed' });+ const result = reconcileComposerVoiceDraft(edited, {+ draft: 'typed\nvoice', initialDocument, initialSelection: { start: 0, end: 0, atomRange: { start: 0, end: 1 } }, insertionEnd: 11,+ });+ expect(result.nodes[0]).toEqual(initialDocument.nodes[0]);+ expect(composerDocumentProjectedText(result)).toBe('typed\nvoice');+ });++ it('resolves compact prefixes through long pasted content and semantic reference projections', () => {+ const document = { version: 1 as const, nodes: [+ { type: 'text' as const, text: '前🙂后' },+ { type: 'quote' as const, quote: { text: '引用' } },+ { type: 'pasted-text' as const, text: '文'.repeat(4_000_000), display: '长文本' },+ { type: 'session-link' as const, href: 'https://example.com/task', label: '标题', titled: true },+ ] };+ expect(composerSelectionOffset(document, { textLength: 3, atomCount: 1 })).toBe(3);+ expect(composerSelectionOffset(document, { textLength: 4, atomCount: 2 })).toBe(4_000_004);+ expect(composerSelectionOffset(document, { textLength: 4, atomCount: 3 }))+ .toBe(composerDocumentProjectedText(document).length);+ expect(composerSelectionOffset(document, { textLength: 5, atomCount: 0 })).toBeNull();+ expect(composerSelectionOffset(document, { textLength: 0, atomCount: 4 })).toBeNull();+ });+ it('locates a dictated caret using projected chip lengths and skips zero-width quotes', () => {+ const document = { version: 1 as const, nodes: [+ { type: 'quote' as const, quote: { text: '引用' } },+ { type: 'session-link' as const, href: 'https://example.com/task', label: '标题', titled: true },+ { type: 'text' as const, text: '插入后文' },+ ] };+ const prefix = '[标题](https://example.com/task)';+ expect(composerCaretPosition(document, prefix.length + 2)).toEqual({ nodeIndex: 2, offset: 2 });+ expect(composerCaretPosition(textComposerDocument('甲🙂乙'), 3)).toEqual({ nodeIndex: 0, offset: 3 });+ });it('roundtrips interleaved quote and text nodes without leaking private markers', () => {const quoteA = { text: 'alpha' };const quoteB = { text: 'beta', sourcePath: 'src/b.ts', startLine: 4, endLine: 5 };diff --git a/apps/mobile/src/__tests__/composerRichInputHtml.test.ts b/apps/mobile/src/__tests__/composerRichInputHtml.test.tsindex 36dd67bf49..275723cfd8 100644--- a/apps/mobile/src/__tests__/composerRichInputHtml.test.ts+++ b/apps/mobile/src/__tests__/composerRichInputHtml.test.ts@@ -61,6 +61,35 @@ describe('mobile composer rich input HTML', () => {expect(html).not.toContain('https://');});+ it('counts selection prefixes without cloning or reading atom payloads', () => {+ const text = (nodeValue: string) => ({ nodeType: 3, nodeValue });+ const element = (tagName: string, childNodes: unknown[], atom = false) => ({+ nodeType: 1, tagName, childNodes, classList: { contains: (name: string) => atom && name === 'atom' },+ get dataset() { throw new Error('selection must not read semantic payloads'); },+ });+ const suffix = text('\u200B🙂尾');+ const root = element('DIV', [element('DIV', [text('前')]), element('SPAN', [], true), suffix]);+ const source = html.slice(html.indexOf('const prefixAt ='), html.indexOf('const reportSelection ='));+ const measure = (container: unknown, offset: number) => runInNewContext(+ source + '; prefixAt(container, offset);',+ { root, container, offset, CARET_ANCHOR: '\u200B', Node: { TEXT_NODE: 3, ELEMENT_NODE: 1 } },+ );+ expect(measure(root, 1)).toEqual({ textLength: 2, atomCount: 0 });+ expect(measure(suffix, 3)).toEqual({ textLength: 4, atomCount: 1 });+ expect(source).not.toContain('cloneContents');+ const message = { type: 'selection', documentId: 7, before: measure(root, 1), through: measure(suffix, 3) };+ expect(JSON.stringify(message).length).toBeLessThan(160);+ expect(parseComposerWebMessage(JSON.stringify(message))).toEqual(message);+ expect(parseComposerWebMessage(JSON.stringify({ ...message, documentId: -1 }))).toBeNull();+ expect(parseComposerWebMessage(JSON.stringify({ ...message, before: { textLength: -1, atomCount: 0 } }))).toBeNull();+ const slashTail = text('b\u200B');+ const slash = element('SPAN', [text('/a'), element('BR', []), slashTail]);+ slash.classList.contains = (name) => name === 'slash';+ root.childNodes = [slash, text('尾')];+ expect(measure(slashTail, 0)).toEqual({ textLength: 2, atomCount: 0 });+ expect(measure(root, 1)).toEqual({ textLength: 4, atomCount: 0 });+ });+it('initializes on the Android WebView 85 API baseline', () => {const legacyHtml = buildComposerRichInputHtml({accessibilityLabel: '输入消息',@@ -245,6 +274,7 @@ describe('mobile composer rich input HTML', () => {},};const documentStub = {+ addEventListener() {},createComment(value: string) {return createNode(8, value);},@@ -283,7 +313,7 @@ describe('mobile composer rich input HTML', () => {const windowStub: {ReactNativeWebView: { postMessage(payload: string): void };cindyComposer?: {- applyDocument(value: unknown, focusAfter?: boolean): void;+ applyDocument(value: unknown, focusAfter?: boolean, caret?: { nodeIndex: number; offset: number }): void;commitPaste(requestId: string, nodes: unknown[]): void;setConfig(value: { maxHeight: number }): void;};@@ -393,6 +423,15 @@ describe('mobile composer rich input HTML', () => {},});expect(legacyHtml).not.toContain('replaceChildren');+ windowStub.cindyComposer?.applyDocument({+ version: 1,+ nodes: [+ { type: 'pasted-text', text: 'long raw text', display: 'chip' },+ { type: 'text', text: 'dictated suffix' },+ ],+ }, true, { nodeIndex: 1, offset: 8 });+ expect(selection.anchorNode).toBe(children[2]);+ expect(selection.anchorOffset).toBe(8);expect(legacyHtml).not.toContain('.flatMap(');});@@ -462,7 +501,7 @@ describe('mobile composer rich input HTML', () => {expect(inputSource).toContain('applyDocumentAndSetSelectionToEnd(document: ComposerDocument): void;');expect(inputSource).toContain('applyDocumentAndSetSelectionToEnd: (value) => {');expect(inputSource).toContain('applyDocument(value, true);');- expect(inputSource).toContain('if (pending) applyDocument(pending.document, pending.focusAfter);');+ expect(inputSource).toContain('if (pending) applyDocument(pending.document, pending.focusAfter, pending.caret);');expect(inputSource).toContain('pendingNodeInsertionsRef.current.push(node);');expect(inputSource).toContain('for (const node of pendingNodeInsertions)');expect(selectSource).toContain('queueEditingRef.current ? { persist: false } : undefined');diff --git a/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx b/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsxnew file mode 100644index 0000000000..bcf073a40e--- /dev/null+++ b/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx@@ -0,0 +1,115 @@+// @vitest-environment jsdom+import { act, createElement, createRef } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { runInNewContext } from 'node:vm';+import { afterEach, expect, it, vi } from 'vitest';+import { ComposerRichInput, type ComposerRichInputHandle } from '@/session/ComposerRichInput';+import { textComposerDocument, type ComposerDocument } from '@/session/composerDocument';++const bridge = vi.hoisted(() => ({+ onMessage: (_event: { nativeEvent: { data: string } }) => {},+ inject: vi.fn(),+}));+vi.mock('react-native', () => ({ Platform: { OS: 'ios' }, StyleSheet: { create: (styles: unknown) => styles } }));+vi.mock('react-native-webview', async () => {+ const { forwardRef, useImperativeHandle } = await import('react');+ return { WebView: forwardRef((props: { onMessage: typeof bridge.onMessage }, ref) => {+ bridge.onMessage = props.onMessage;+ useImperativeHandle(ref, () => ({ injectJavaScript: bridge.inject }));+ return null;+ }) };+});+vi.mock('react-native-reanimated', () => ({+ default: { View: ({ children }: { children: unknown }) => children },+ useAnimatedStyle: (factory: () => unknown) => factory(),+}));+vi.mock('expo-file-system', () => ({ File: class {}, Paths: { cache: '/unused' } }));+vi.mock('expo-clipboard', () => ({}));++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+let root: Root | undefined;+afterEach(() => { act(() => root?.unmount()); root = undefined; bridge.inject.mockReset(); });++function mount(hidden = false) {+ const ref = createRef<ComposerRichInputHandle>();+ const onChangeDocument = vi.fn();+ const page = {+ id: 0,+ document: textComposerDocument('initial'),+ applyDocument: vi.fn((document: ComposerDocument, _focus: boolean, _caret: unknown, id: number) => {+ page.document = document;+ page.id = id;+ }),+ setConfig: vi.fn(),+ focus: vi.fn(),+ };+ bridge.inject.mockImplementation((script: string) => runInNewContext(script, { window: { cindyComposer: page } }));+ root = createRoot(document.createElement('div'));+ act(() => root!.render(createElement(ComposerRichInput, {+ ref, document: page.document, hidden, onChangeDocument,+ accessibilityLabel: 'input', placeholder: '', height: 40, maxHeight: 264,+ theme: { background: '#fff', border: '#aaa', chip: '#ddd', focus: '#555', placeholder: '#777', text: '#111', textSecondary: '#333' },+ })));+ const send = (message: unknown) => act(() => bridge.onMessage({ nativeEvent: { data: JSON.stringify(message) } }));+ return { ref, page, send, onChangeDocument };+}++it('restores the latest accepted draft on every ready and accepts only the new document id', () => {+ const { ref, page, send, onChangeDocument } = mount();+ send({ type: 'ready' });+ const firstId = page.id;+ expect(firstId).toBeGreaterThan(0);+ const edited = textComposerDocument('typed before reload');+ // The parent has not rerendered its initial prop yet.+ send({ type: 'change', documentId: firstId, document: edited });+ page.id = 0;+ page.document = textComposerDocument('initial');+ send({ type: 'ready' });+ expect(page.document).toEqual(edited);+ expect(page.id).toBeGreaterThan(firstId);+ expect(page.applyDocument.mock.lastCall?.[1]).toBe(false);+ const restoredId = page.id;+ const afterReload = textComposerDocument('typed after reload');+ send({ type: 'change', documentId: restoredId, document: afterReload });+ send({ type: 'selection', documentId: restoredId, before: { textLength: 3, atomCount: 0 }, through: { textLength: 3, atomCount: 0 } });+ expect(onChangeDocument).toHaveBeenLastCalledWith(afterReload);+ expect(ref.current?.getSelection('typed after reload')).toEqual({ start: 3, end: 3, atomRange: { start: 0, end: 0 } });+ send({ type: 'change', documentId: firstId, document: edited });+ send({ type: 'selection', documentId: firstId, before: { textLength: 0, atomCount: 0 }, through: { textLength: 0, atomCount: 0 } });+ expect(onChangeDocument).toHaveBeenCalledTimes(2);+ expect(ref.current?.getSelection('typed after reload')).toEqual({ start: 3, end: 3, atomRange: { start: 0, end: 0 } });+});++it('retains structural endpoints when only a zero-width quote is selected', () => {+ const { ref, page, send } = mount();+ send({ type: 'ready' });+ send({ type: 'change', documentId: page.id, document: {+ version: 1, nodes: [{ type: 'quote', quote: { text: 'selected quote' } }],+ } });+ send({ type: 'selection', documentId: page.id, before: { textLength: 0, atomCount: 0 }, through: { textLength: 0, atomCount: 1 } });+ expect(ref.current?.getSelection('')).toEqual({ start: 0, end: 0, atomRange: { start: 0, end: 1 } });+ send({ type: 'change', documentId: page.id, document: textComposerDocument('') });+ expect(ref.current?.getSelection('')).toEqual({ start: 0, end: 0 });+});++it('keeps pending caret intent on first ready but does not replay it on reload', () => {+ const { ref, page, send } = mount();+ act(() => ref.current?.applyDocumentAndFocusSelection(textComposerDocument('inserted suffix'), 8));+ send({ type: 'ready' });+ expect(page.applyDocument.mock.lastCall?.slice(1, 3)).toEqual([true, { nodeIndex: 0, offset: 8 }]);+ send({ type: 'ready' });+ expect(page.applyDocument.mock.lastCall?.slice(1, 3)).toEqual([false, null]);+});++it('restores a hidden dictation draft without focusing or losing its saved insertion end', () => {+ const { ref, page, send } = mount(true);+ send({ type: 'ready' });+ send({ type: 'change', documentId: page.id, document: textComposerDocument('voice suffix') });+ act(() => ref.current?.rememberSelection('voice suffix', { start: 5, end: 5 }));+ send({ type: 'ready' });+ expect(page.document).toEqual(textComposerDocument('voice suffix'));+ expect(page.applyDocument.mock.lastCall?.[1]).toBe(false);+ expect(page.focus).not.toHaveBeenCalled();+ send({ type: 'selection', documentId: page.id, before: { textLength: 0, atomCount: 0 }, through: { textLength: 0, atomCount: 0 } });+ expect(ref.current?.getSelection('voice suffix')).toEqual({ start: 5, end: 5 });+});diff --git a/apps/mobile/src/__tests__/mobileVoiceController.test.ts b/apps/mobile/src/__tests__/mobileVoiceController.test.tsindex 4ac3409996..8588bc0fef 100644--- a/apps/mobile/src/__tests__/mobileVoiceController.test.ts+++ b/apps/mobile/src/__tests__/mobileVoiceController.test.ts@@ -15,6 +15,7 @@ import type {import type { StoredMobileVoiceCredential } from '@/session/mobileVoiceCredentialStore';import { createMobileVoiceControllerSession } from '@/session/mobileVoiceController';import { mobileVoiceEmptyTranscriptError } from '@/session/mobileVoiceInput';+import { composerDocumentProjectedText, reconcileComposerVoiceDraft, serializeComposerDocument, type ComposerDocument } from '@/session/composerDocument';vi.mock('@/session/mobileRealtimeAudio', () => ({startMobileRealtimeAudio: vi.fn(),@@ -147,6 +148,86 @@ function credential(): StoredMobileVoiceCredential {}describe('mobileVoiceController', () => {+ it.each([false, true])('removes selected quotes even when the first identical transcript arrives at stop (partials=%s)', async (partials) => {+ const initialDocument: ComposerDocument = { version: 1, nodes: [+ { type: 'quote', quote: { text: 'selected quote' } }, { type: 'text', text: 'raw final' },+ ] };+ const initialSelection = { start: 0, end: 9, atomRange: { start: 0, end: 1 } };+ let document = initialDocument;+ const asr = new FakeAsrProvider();+ const config = credential();+ config.settings!.refinementEnabled = false;+ const session = createMobileVoiceControllerSession({+ credential: config, asr, initialDraft: 'raw final', initialSelection,+ readCurrentDraft: () => composerDocumentProjectedText(document),+ startAudio: async () => async () => undefined,+ onDraftChanged: (draft, selection, replacement) => {+ document = reconcileComposerVoiceDraft(document, { draft, initialDocument, initialSelection, insertionEnd: selection?.end, replacement });+ },+ });+ await session.start();+ if (partials) {+ asr.emit({ type: 'partial', text: 'raw draft', at: Date.now() });+ expect(serializeComposerDocument(document).text).toBe('raw draft');+ }+ expect(await session.stop()).toBe('raw final');+ expect(serializeComposerDocument(document).text).toBe('raw final');+ });++ it.each([+ ['甲乙', 0, 0, '', '甲乙'],+ ['甲乙', 1, 1, '甲', '乙'],+ ['甲乙', 2, 2, '甲乙', ''],+ ['甲旧词乙', 1, 3, '甲', '乙'],+ ['🙂\n乙', 3, 3, '🙂\n', '乙'],+ ])('keeps streaming ASR and refinement at selection in %s [%s, %s]', async (initialDraft, start, end, prefix, suffix) => {+ let draft = initialDraft;+ const drafts: string[] = [];+ const selections: Array<{ start: number; end: number } | undefined> = [];+ const asr = new FakeAsrProvider();+ const session = createMobileVoiceControllerSession({+ credential: credential(),+ initialDraft,+ initialSelection: { start, end },+ readCurrentDraft: () => draft,+ asr,+ refiner: {+ async refine(input) {+ input.onPartial?.('润色中');+ return { accepted: true, sourceSegmentIds: input.segmentIds, basedOnText: input.text,+ refinedText: '润色完成', elapsedMs: 1 };+ },+ },+ startAudio: async () => async () => undefined,+ onDraftChanged: (text, selection) => {+ draft = text;+ drafts.push(text);+ selections.push(selection);+ },+ });+ await session.start();+ asr.emit({ type: 'partial', text: '识别中', at: Date.now() });+ expect(draft).toBe(prefix + '识别中' + suffix);+ expect(await session.stop()).toBe(prefix + '润色完成' + suffix);+ expect(drafts).toEqual(['识别中', 'raw final', '润色中', '润色完成'].map((text) => prefix + text + suffix));+ expect(selections.at(-1)).toEqual({ start: prefix.length + 4, end: prefix.length + 4 });+ });++ it('preserves typing that changed the selected draft before the first ASR result', async () => {+ let draft = '用户刚修改';+ const asr = new FakeAsrProvider();+ const session = createMobileVoiceControllerSession({+ credential: credential(), initialDraft: '原选区', initialSelection: { start: 0, end: 3 },+ readCurrentDraft: () => draft, asr, refiner: null,+ startAudio: async () => async () => undefined,+ onDraftChanged: (text) => { draft = text; },+ });+ await session.start();+ asr.emit({ type: 'partial', text: '转写', at: Date.now() });+ expect(draft).toBe('用户刚修改\n转写');+ expect(await session.stop()).toBe('用户刚修改\nraw final');+ });+it('propagates and localizes empty-transcript failures from stop()', async () => {const errors: string[] = [];const states: string[] = [];@@ -320,6 +401,77 @@ describe('mobileVoiceController', () => {}});+ it('rebases deferred partials onto edits outside the published voice range', async () => {+ vi.useFakeTimers();+ try {+ let draft = '前 后';+ const asr = new FakeAsrProvider();+ const session = createMobileVoiceControllerSession({+ credential: credential(), initialDraft: draft, initialSelection: { start: 1, end: 1 },+ readCurrentDraft: () => draft, asr, refiner: null,+ startAudio: async () => async () => undefined,+ onDraftChanged: (text) => { draft = text; },+ });+ await session.start();+ asr.emit({ type: 'partial', text: 'one', at: Date.now() });+ asr.emit({ type: 'partial', text: 'one two', at: Date.now() });+ draft = '前one 用户修改后文';+ vi.advanceTimersByTime(80);+ expect(draft).toBe('前one two 用户修改后文');+ asr.emit({ type: 'stable', text: 'final', at: Date.now() });+ expect(draft).toBe('前final 用户修改后文');+ await session.cancel();+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not rebase an internal pending draft when no external draft reader exists', async () => {+ vi.useFakeTimers();+ try {+ const asr = new FakeAsrProvider();+ const drafts: string[] = [];+ const session = createMobileVoiceControllerSession({+ credential: credential(), initialDraft: '', asr, refiner: null,+ startAudio: async () => async () => undefined,+ onDraftChanged: (text) => { drafts.push(text); },+ });+ await session.start();+ asr.emit({ type: 'partial', text: 'one', at: Date.now() });+ asr.emit({ type: 'partial', text: 'one two', at: Date.now() });+ expect(session.currentDraft()).toBe('one two');+ vi.advanceTimersByTime(80);+ expect(drafts).toEqual(['one', 'one two']);+ await session.cancel();+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not resurrect a pending partial after cancellation with an external suffix edit', async () => {+ vi.useFakeTimers();+ try {+ const asr = new FakeAsrProvider();+ let draft = '前 后';+ const session = createMobileVoiceControllerSession({+ credential: credential(), initialDraft: draft, initialSelection: { start: 1, end: 1 },+ readCurrentDraft: () => draft, asr, refiner: null,+ startAudio: async () => async () => undefined,+ onDraftChanged: (text) => { draft = text; },+ });+ await session.start();+ asr.emit({ type: 'partial', text: 'one', at: Date.now() });+ asr.emit({ type: 'partial', text: 'one two', at: Date.now() });+ draft = '前one 用户修改后文';+ await session.cancel();+ vi.advanceTimersByTime(80);+ expect(session.currentDraft()).toBe('前one 用户修改后文');+ expect(draft).toBe('前one 用户修改后文');+ } finally {+ vi.useRealTimers();+ }+ });+it('projects realtime ASR and streaming refinement into one composer insertion', async () => {const drafts: string[] = [];const states: string[] = [];diff --git a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.tsindex 5cacc06924..0f7ae17e2f 100644--- a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts+++ b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts@@ -304,8 +304,10 @@ describe('native e2e environment', () => {);expect(sessionScreen).toContain('const latestDocument = latestDraft.trim()');expect(sessionScreen).toContain('readCurrentDraft: () => draftRef.current');- expect(sessionScreen).toContain('onDraftChanged: writeVoiceDraft');- expect(sessionScreen).toContain('useComposerVoiceDraftWriter(sessionId, setComposerDraft)');+ expect(sessionScreen).toContain('if (selection) input?.rememberSelection(text, selection);');+ expect(sessionScreen).toContain('writeVoiceDraft({ draft: text, initialDocument, initialSelection, insertionEnd: selection?.end, replacement });');+ expect(sessionScreen).toContain('reconcileComposerVoiceDraft(composerDocumentRef.current, update)');+ expect(sessionScreen).toContain('reconcileComposerProjectedText(composerDocumentRef.current, latestDraft)');expect(sessionScreen).toContain('createMobileVoiceControllerSession({');expect(sessionScreen).not.toContain('await sendLatest({ draftOverride: latestDraft });');});diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.tsindex 4963fb8621..04242d6373 100644--- a/apps/mobile/src/__tests__/newSession.test.ts+++ b/apps/mobile/src/__tests__/newSession.test.ts@@ -1778,8 +1778,12 @@ describe('new session composer surface', () => {expect(newSource).toContain('voiceDraftListeningText: {\n color: colors.textTertiary,');expect(newSource).not.toContain('voiceDraftListeningText: {\n color: colors.statusReady,');expect(newSource).toContain('const voiceDraftShowsListeningPrompt = voiceIsListening && draft.firstMessage.length === 0;');- expect(newSource).toContain('firstMessageInputRef.current?.setNativeProps({ selection: { start: end, end } });');- expect(newSource).toContain('voiceDraftScrollRef.current?.scrollToEnd({ animated: false });');+ expect(newSource).toContain('firstMessageInputRef.current?.setNativeProps({ selection: firstMessageSelectionRef.current });');+ expect(newSource).toContain('voiceDraftScrollRef.current?.scrollTo({ y: voiceDraftCaretFrame.top, animated: false });');+ expect(newSource).toContain('draft.firstMessage.slice(0, firstMessageSelectionRef.current.end)');+ expect(newSource).toContain('draft.firstMessage.slice(firstMessageSelectionRef.current.end)');+ expect(newSource).toContain('caret.measureLayout(block, (x, y) => {');+ expect(newSource).toContain('viewRef={voiceDraftCaretRef}');expect(sharedSource).toContain('export function VoiceMicWaveCaret');expect(newSource).toContain('const creatingRef = useRef(false);');expect(createSource).toContain('|| voiceStartupInFlightRef.current');diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.tsindex 0ad14919a8..653e449355 100644--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts@@ -137,11 +137,8 @@ describe('mobile session composer desktop-first surface', () => {const voiceDraftOverlayContentEnd = source.indexOf('voiceDraftMeasuredBlock:', voiceDraftOverlayContentStart);const voiceDraftOverlayContentStyle = source.slice(voiceDraftOverlayContentStart, voiceDraftOverlayContentEnd);const voiceDraftMeasuredBlockStart = source.indexOf('voiceDraftMeasuredBlock: {');- const voiceDraftMeasuredBlockEnd = source.indexOf('voiceDraftCaretOverlay:', voiceDraftMeasuredBlockStart);+ const voiceDraftMeasuredBlockEnd = source.indexOf('voiceDraftText:', voiceDraftMeasuredBlockStart);const voiceDraftMeasuredBlockStyle = source.slice(voiceDraftMeasuredBlockStart, voiceDraftMeasuredBlockEnd);- const voiceDraftCaretOverlayStart = source.indexOf('voiceDraftCaretOverlay: {');- const voiceDraftCaretOverlayEnd = source.indexOf('voiceDraftText:', voiceDraftCaretOverlayStart);- const voiceDraftCaretOverlayStyle = source.slice(voiceDraftCaretOverlayStart, voiceDraftCaretOverlayEnd);const voiceDraftTextStyleStart = source.indexOf('voiceDraftText: {');const voiceDraftTextStyleEnd = source.indexOf('voiceDraftListeningPrompt:', voiceDraftTextStyleStart);const voiceDraftTextStyle = source.slice(voiceDraftTextStyleStart, voiceDraftTextStyleEnd);@@ -340,7 +337,7 @@ describe('mobile session composer desktop-first surface', () => {expect(source).toContain('const COMPOSER_STATUS_ROW_RESERVED_HEIGHT = 28;');expect(source).toContain('const COMPOSER_STACK_GAP_HEIGHT = 4;');expect(source).toContain('const COMPOSER_INPUT_ROW_CHROME_HEIGHT = 22;');- expect(source).toContain('const COMPOSER_VOICE_CARET_GAP = 2;');+ expect(voiceMicCaretStyle).toContain('marginLeft: 2');expect(source).not.toContain('const COMPOSER_VOICE_CARET_RESERVED_WIDTH');expect(source).not.toContain('const COMPOSER_VOICE_OVERLAY_HORIZONTAL_PADDING');expect(source).toContain('const composerInputIsMultiline = composerResize.dragging');@@ -401,7 +398,7 @@ describe('mobile session composer desktop-first surface', () => {expect(source).toContain('const composerShowSendButton = composerLayout.send.visible || voiceStartPending;');expect(source).not.toContain('composerLayout.send.visible && (!voiceIsListening || composerHasPayload)');expect(source).toContain('const latestDocument = latestDraft.trim()');- expect(source).toContain('reconcileComposerProjectedText(documentBeforeStop, latestDraft)');+ expect(source).toContain('reconcileComposerProjectedText(composerDocumentRef.current, latestDraft)');expect(source).toContain('if (options.sendAfterTranscribe && (composerDocumentHasContent(latestDocument) || attachments.length > 0))');expect(source).toContain('const currentTurnStreaming = useMemo(');expect(source).toContain('const canStopCurrentRun = (remoteSessionRunning || currentTurnStreaming)');@@ -441,7 +438,7 @@ describe('mobile session composer desktop-first surface', () => {// 会在点语音的同时弹出软键盘。听写文字由覆盖层渲染,caret 只在用户点输入框// (停止听写并有意打字)时由 WebKit 按触点放置。expect(source).not.toContain('setSelectionToEnd');- expect(source).toContain('voiceDraftScrollRef.current?.scrollToEnd({ animated: false });');+ expect(source).toContain('voiceDraftScrollRef.current?.scrollTo({ y: voiceDraftCaretFrame.top, animated: false });');expect(source).toContain('caretHidden={voiceIsListening}');expect(source).toContain('const handleComposerInputPressIn = useCallback(() => {');expect(source).toContain('onPressIn={handleComposerInputPressIn}');@@ -462,7 +459,7 @@ describe('mobile session composer desktop-first surface', () => {expect(voiceDraftMeasuredBlockStyle).not.toContain('paddingRight: COMPOSER_VOICE_CARET_RESERVED_WIDTH');expect(voiceDraftMeasuredBlockStyle).toContain("position: 'relative'");expect(voiceDraftMeasuredBlockStyle).not.toContain("width: '100%'");- expect(voiceDraftCaretOverlayStyle).toContain("position: 'absolute'");+ expect(source).not.toContain('voiceDraftCaretOverlay:');expect(voiceDraftTextStyle).not.toContain("alignSelf: 'flex-start'");expect(voiceDraftTextStyle).toContain('color: colors.textPrimary');expect(voiceDraftTextStyle).not.toContain("color: 'transparent'");@@ -475,18 +472,17 @@ describe('mobile session composer desktop-first surface', () => {expect(source).not.toContain('paddingRight: COMPOSER_VOICE_CARET_RESERVED_WIDTH');expect(voiceMicCaretStyle).toContain('height: MOBILE_COMPOSER_INPUT_LINE_HEIGHT');expect(voiceMicCaretStyle).toContain("justifyContent: 'center'");- expect(source.match(/voiceDraftScrollRef\.current\?\.scrollToEnd\(\{ animated: false \}\);/g)?.length ?? 0)+ expect(source.match(/voiceDraftScrollRef\.current\?\.scrollTo\(\{ y: voiceDraftCaretFrame.top, animated: false \}\);/g)?.length ?? 0).toBeGreaterThanOrEqual(3);expect(source).toContain('const [voiceDraftCaretFrame, setVoiceDraftCaretFrame] = useState({ left: 0, top: 0 });');expect(source).not.toContain('const [composerTextInputFrameWidth, setComposerTextInputFrameWidth] = useState(0);');expect(source).not.toContain('const [voiceDraftContentHeight, setVoiceDraftContentHeight] = useState(COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT);');expect(source).not.toContain('const handleComposerTextInputFrameLayout = useCallback((event: LayoutChangeEvent) => {');expect(source).not.toContain('onLayout={handleComposerTextInputFrameLayout}');- expect(source).toContain('const handleVoiceDraftTextLayout = useCallback((event: TextLayoutEvent) => {');- expect(source).toContain('const lastLine = lines[lines.length - 1];');- expect(source).toContain('lastLine.x + lastLine.width + COMPOSER_VOICE_CARET_GAP');+ expect(source).toContain('const handleVoiceDraftTextLayout = useCallback(() => {');+ expect(source).toContain('caret.measureLayout(block, (x, y) => {');expect(source).not.toContain('voiceDraftBlockWidth - COMPOSER_VOICE_CARET_WIDTH - COMPOSER_VOICE_CARET_EDGE_INSET');- expect(source).toContain('lastLine.y + ((lastLine.height - COMPOSER_INPUT_LINE_HEIGHT) / 2)');+ expect(source).toContain('top: Math.max(0, Math.round(y))');expect(source).not.toContain('setVoiceDraftContentHeight((currentHeight) => (');expect(source).toContain('const voiceDraftShowsListeningPrompt = voiceIsListening && draft.length === 0;');expect(source).toContain('styles.voiceDraftListeningPrompt');@@ -507,10 +503,9 @@ describe('mobile session composer desktop-first surface', () => {expect(source).not.toContain('textBreakStrategy="simple"');expect(source).not.toContain('android_hyphenationFrequency="none"');expect(source).toContain('onTextLayout={handleVoiceDraftTextLayout}');- expect(voiceDraftTextSource).toContain('{draft}');- expect(source).toContain('styles.voiceDraftCaretOverlay');- expect(source).toContain('left: voiceDraftCaretFrame.left');- expect(source).toContain('top: voiceDraftCaretFrame.top');+ expect(voiceDraftTextSource).toContain('{draft.slice(0, voiceDraftInsertionEnd)}');+ expect(voiceDraftTextSource).toContain('viewRef={voiceDraftCaretRef}');+ expect(voiceDraftTextSource).toContain('{draft.slice(voiceDraftInsertionEnd)}');expect(source).not.toContain('voiceMicCaretInline');expect(source).not.toContain('<VoiceMicWaveCaret color={colors.statusReady} inline />');// 语音态占位文案就是普通态 TextInput 的 placeholder,必须与 placeholderTextColor 同源,@@ -738,8 +733,13 @@ describe('mobile session composer desktop-first surface', () => {+ " startupSeq = voiceStartupSeqRef.current + 1;",);expect(voiceSource).toContain('voiceStartupInFlightRef.current = false;');- expect(voiceSource).toContain('onDraftChanged: writeVoiceDraft');- expect(source).toContain('useComposerVoiceDraftWriter(sessionId, setComposerDraft)');+ expect(voiceSource).toContain('if (selection) input?.rememberSelection(text, selection);');+ expect(voiceSource).toContain('writeVoiceDraft({ draft: text, initialDocument, initialSelection, insertionEnd: selection?.end, replacement });');+ expect(source).toContain('draft.slice(0, voiceDraftInsertionEnd)');+ expect(source).toContain('draft.slice(voiceDraftInsertionEnd)');+ expect(source).toContain('caret.measureLayout(block, (x, y) => {');+ expect(source).toContain('viewRef={voiceDraftCaretRef}');+ expect(source).toContain('useComposerVoiceDraftWriter(sessionId, (update: ComposerVoiceDraftUpdate) =>');expect(voiceSource).toContain('isMobileRealtimeAudioAvailable()');expect(voiceSource.indexOf('isMobileRealtimeAudioAvailable()')).toBeLessThan(voiceSource.indexOf('resolveMobileVoiceRecordingPermission({'),diff --git a/apps/mobile/src/session/ComposerRichInput.tsx b/apps/mobile/src/session/ComposerRichInput.tsxindex 3c3153641c..29a2324fc9 100644--- a/apps/mobile/src/session/ComposerRichInput.tsx+++ b/apps/mobile/src/session/ComposerRichInput.tsx@@ -6,8 +6,12 @@ import { File, Paths } from 'expo-file-system';import * as Clipboard from 'expo-clipboard';import {normalizeComposerDocument,+ composerDocumentProjectedText,+ composerCaretPosition,+ composerSelectionOffset,parseStoredComposerDocument,type ComposerDocument,+ type ComposerSelection,type ComposerNode,type ResolvedSessionLinkSemantic,} from '@/session/composerDocument';@@ -22,7 +26,10 @@ import { COMPOSER_PASTED_IMAGE_FILE_PREFIX } from '@/session/pastedImageAttachmeimport { registerMobileMessageWebView } from '@/session/mobileMessageWebViewMetrics';export interface ComposerRichInputHandle {+ getSelection(draft: string): ComposerSelection;+ rememberSelection(draft: string, selection: { start: number; end: number }): void;applyDocumentAndSetSelectionToEnd(document: ComposerDocument): void;+ applyDocumentAndFocusSelection(document: ComposerDocument, offset: number): void;blur(): void;focus(): void;insertNode(node: ComposerNode): void;@@ -86,9 +93,13 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRicuseEffect(() => registerMobileMessageWebView('composer'), []);const readyRef = useRef(false);const webSignatureRef = useRef('');+ const projectedDraft = useMemo(() => composerDocumentProjectedText(document), [document]);+ const webDocumentRef = useRef({ document, draft: projectedDraft, id: 0 });+ const selectionRef = useRef<(ComposerSelection & { draft: string }) | null>(null);const pendingDocumentRef = useRef<{document: ComposerDocument;focusAfter: boolean;+ caret?: { nodeIndex: number; offset: number };} | null>(null);const pendingFocusRef = useRef(false);const pendingNodeInsertionsRef = useRef<ComposerNode[]>([]);@@ -144,12 +155,15 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic}inject('window.cindyComposer.focus();');}, [inject]);- const applyDocument = useCallback((value: ComposerDocument, focusAfter = false) => {+ const applyDocument = useCallback((value: ComposerDocument, focusAfter = false, caret?: { nodeIndex: number; offset: number }) => {+ 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 };if (!readyRef.current) {- pendingDocumentRef.current = { document: value, focusAfter };+ pendingDocumentRef.current = { document: value, focusAfter, caret };return;}- inject(`window.cindyComposer.applyDocument(${JSON.stringify(value)}, ${focusAfter});`);+ inject(`window.cindyComposer.applyDocument(${JSON.stringify(value)}, ${focusAfter}, ${JSON.stringify(caret) ?? 'null'}, ${documentId});`);}, [inject]);useEffect(() => {@@ -165,10 +179,24 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRicuseEffect(() => {if (!forwardedRef) return undefined;const handle: ComposerRichInputHandle = {+ getSelection: (draft) => {+ const saved = selectionRef.current;+ return saved?.draft === draft+ ? { start: saved.start, end: saved.end, ...(saved.atomRange ? { atomRange: saved.atomRange } : {}) }+ : { start: draft.length, end: draft.length };+ },+ // Cache the dictated range without focusing the hidden editor (which opens the keyboard).+ rememberSelection: (draft, selection) => {+ selectionRef.current = { draft, ...selection };+ },applyDocumentAndSetSelectionToEnd: (value) => {webSignatureRef.current = JSON.stringify(value);applyDocument(value, true);},+ applyDocumentAndFocusSelection: (value, offset) => {+ webSignatureRef.current = JSON.stringify(value);+ applyDocument(value, true, composerCaretPosition(value, offset));+ },blur: () => {pendingFocusRef.current = false;if (pendingDocumentRef.current?.focusAfter) {@@ -327,7 +355,10 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRicinject(`window.cindyComposer.setConfig(${JSON.stringify(runtimeConfig)});`);const pending = pendingDocumentRef.current;pendingDocumentRef.current = null;- if (pending) applyDocument(pending.document, pending.focusAfter);+ if (pending) applyDocument(pending.document, pending.focusAfter, pending.caret);+ // A reloaded page starts at id 0; restore the latest accepted draft and+ // synchronize its id through the same path, without replaying focus.+ else applyDocument(webDocumentRef.current.document);const pendingNodeInsertions = pendingNodeInsertionsRef.current;pendingNodeInsertionsRef.current = [];for (const node of pendingNodeInsertions) {@@ -340,13 +371,27 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRicreturn;}if (message.type === 'change') {+ if ((message.documentId ?? 0) !== webDocumentRef.current.id) return;const next = parseStoredComposerDocument(message.document);if (!next) return;const normalized = normalizeComposerDocument(next);+ if (selectionRef.current?.atomRange) selectionRef.current = null;webSignatureRef.current = JSON.stringify(normalized);+ webDocumentRef.current = { document: normalized, draft: composerDocumentProjectedText(normalized), id: webDocumentRef.current.id };onChangeDocument(normalized);return;}+ if (message.type === 'selection') {+ const current = webDocumentRef.current;+ if (hidden || message.documentId !== current.id) return;+ const start = composerSelectionOffset(current.document, message.before);+ const end = composerSelectionOffset(current.document, message.through);+ if (start !== null && end !== null && start <= end && end <= current.draft.length) {+ selectionRef.current = { draft: current.draft, start, end,+ atomRange: { start: message.before.atomCount, end: message.through.atomCount } };+ }+ return;+ }if (message.type === 'height') {if (Number.isFinite(message.height)) {onHeightChange?.(Math.max(COMPOSER_SINGLE_LINE_HEIGHT, Math.min(maxHeight, message.height)));@@ -378,7 +423,7 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic.then((uri) => settlePastedImage(message.requestId, message.index, uri)).catch(() => settlePastedImage(message.requestId, message.index));}- }, [applyDocument, commitPlainTextPaste, focusEditor, inject, maxHeight, onBlur, onChangeDocument, onFocus, onHeightChange, onPasteImagesLoading, persistPastedImage, runtimeConfig, settlePastedImage]);+ }, [applyDocument, commitPlainTextPaste, focusEditor, hidden, inject, maxHeight, onBlur, onChangeDocument, onFocus, onHeightChange, onPasteImagesLoading, persistPastedImage, runtimeConfig, settlePastedImage]);const heightStyle = useAnimatedStyle(() => ({ height: animatedHeight?.value ?? height }));return (diff --git a/apps/mobile/src/session/MobileComposerInputRow.tsx b/apps/mobile/src/session/MobileComposerInputRow.tsxindex 51a5f1f6b0..c5d70f1b33 100644--- a/apps/mobile/src/session/MobileComposerInputRow.tsx+++ b/apps/mobile/src/session/MobileComposerInputRow.tsx@@ -17,7 +17,7 @@ import type { PanGesture } from 'react-native-gesture-handler';import Constants, { ExecutionEnvironment } from 'expo-constants';import { TextInputWrapper, type PasteEventPayload } from 'expo-paste-input';import { Mic } from 'lucide-react-native';-import { useCallback, useEffect, useRef, type ReactNode } from 'react';+import { useCallback, useEffect, useRef, type ReactNode, type Ref } from 'react';import { useTranslation } from 'react-i18next';import { iconSize, iconStroke, useThemedStyles, type ThemeColors } from '@/theme';import { radius, spacing } from '@/theme/tokens';@@ -131,6 +131,7 @@ export interface MobileComposerInputRowProps {multilineShape?: boolean;onBlur?: TextInputProps['onBlur'];onChangeText: (value: string) => void;+ onSelectionChange?: TextInputProps['onSelectionChange'];onContentSizeChange?: TextInputProps['onContentSizeChange'];onFocus?: TextInputProps['onFocus'];/**@@ -205,6 +206,7 @@ export function MobileComposerInputRow({multilineShape,onBlur,onChangeText,+ onSelectionChange,onContentSizeChange,onFocus,onPasteImages,@@ -262,6 +264,7 @@ export function MobileComposerInputRow({multiline={multiline}onBlur={onBlur}onChangeText={onChangeText}+ onSelectionChange={onSelectionChange}onContentSizeChange={onContentSizeChange}onFocus={onFocus}onPressIn={onPressIn}@@ -448,7 +451,7 @@ export function ComposerResizeGrabber({ onAdjust, panHandlers, gesture, visible,);}-export function VoiceMicWaveCaret({ color, testID }: { color: string; testID?: string }) {+export function VoiceMicWaveCaret({ color, testID, viewRef }: { color: string; testID?: string; viewRef?: Ref<View> }) {const styles = useThemedStyles(makeMobileComposerInputRowStyles);const bar1 = useRef(new Animated.Value(0)).current;const bar2 = useRef(new Animated.Value(0)).current;@@ -496,6 +499,8 @@ export function VoiceMicWaveCaret({ color, testID }: { color: string; testID?: s<ViewpointerEvents="none"style={styles.voiceMicCaret}+ ref={viewRef}+ collapsable={false}testID={testID}><Mic color={color} size={iconSize.lg} strokeWidth={iconStroke.regular} />diff --git a/apps/mobile/src/session/composerDocument.ts b/apps/mobile/src/session/composerDocument.tsindex 3c5d95e23b..f45a7b8739 100644--- a/apps/mobile/src/session/composerDocument.ts+++ b/apps/mobile/src/session/composerDocument.ts@@ -28,6 +28,21 @@ export const MOBILE_LONG_PASTE_LINE_THRESHOLD = 24;export const MOBILE_LONG_PASTE_CHAR_THRESHOLD = 4_000;export const MOBILE_LONG_PASTE_MAX_CHARS = 2_000_000;+export interface ComposerSelection {+ start: number;+ end: number;+ /** Counts of atoms before each endpoint distinguish zero-width quote boundaries. */+ atomRange?: { start: number; end: number };+}++export interface ComposerVoiceDraftUpdate {+ draft: string;+ initialDocument: ComposerDocument;+ initialSelection: ComposerSelection;+ insertionEnd?: number;+ replacement?: { start: number; end: number; text: string };+}+export interface ComposerTextNode {type: 'text';text: string;@@ -182,6 +197,35 @@ export function composerDocumentsEqual(});}+/** Locate a projected caret in the flat semantic nodes rendered by the editor. */+export function composerCaretPosition(document: ComposerDocument, offset: number): { nodeIndex: number; offset: number } {+ let remaining = Math.max(0, offset);+ for (let nodeIndex = 0; nodeIndex < document.nodes.length; nodeIndex += 1) {+ const node = document.nodes[nodeIndex];+ const length = composerNodeProjectedText(node).length;+ if (remaining < length || (node.type === 'text' && remaining === length)) {+ return { nodeIndex, offset: remaining };+ }+ remaining -= length;+ }+ return { nodeIndex: document.nodes.length, offset: 0 };+}++/** Compact DOM prefixes count text and atoms separately, without copying atom payloads. */+export function composerSelectionOffset(+ document: ComposerDocument,+ prefix: { textLength: number; atomCount: number },+): number | null {+ let atomCount = 0;+ let textLength = 0;+ let offset = prefix.textLength;+ for (const node of document.nodes) {+ if (node.type === 'text') textLength += node.text.length;+ else if (atomCount++ < prefix.atomCount) offset += composerNodeProjectedText(node).length;+ }+ return prefix.atomCount <= atomCount && prefix.textLength <= textLength ? offset : null;+}+/** Visible editable projection. Quote atoms intentionally contribute no text. */export function composerDocumentProjectedText(document: ComposerDocument): string {return document.nodes.map((node) => {@@ -239,6 +283,20 @@ export function composerDocumentQuotes(document: ComposerDocument): ChatQuote[]return document.nodes.flatMap((node) => (node.type === 'quote' ? [node.quote] : []));}+/** The captured structural selection is valid only until the document changes. */+export function reconcileComposerVoiceDraft(document: ComposerDocument, update: ComposerVoiceDraftUpdate): ComposerDocument {+ const { draft, initialDocument, initialSelection, insertionEnd } = update;+ if (update.replacement) {+ const { start, end, text } = update.replacement;+ return replaceComposerTextRange(document, start, end, [{ type: 'text', text }]);+ }+ if (document === initialDocument && insertionEnd !== undefined) {+ return replaceComposerTextRange(document, initialSelection.start, initialSelection.end,+ [{ type: 'text', text: draft.slice(initialSelection.start, insertionEnd) }], initialSelection.atomRange);+ }+ return reconcileComposerProjectedText(document, draft);+}+export function appendComposerNode(document: ComposerDocument,node: ComposerNode,@@ -267,18 +325,26 @@ export function replaceComposerTextRange(from: number,to: number,replacement: readonly ComposerNode[],+ atomRange?: { start: number; end: number },): ComposerDocument {const start = Math.max(0, Math.min(from, to));const end = Math.max(start, Math.max(from, to));const before: ComposerNode[] = [];const after: ComposerNode[] = [];let offset = 0;+ let atomIndex = 0;for (const node of document.nodes) {const text = composerNodeProjectedText(node);const nodeStart = offset;const nodeEnd = nodeStart + text.length;offset = nodeEnd;+ const currentAtom = node.type === 'text' ? atomIndex : atomIndex++;+ if (node.type === 'quote' && atomRange) {+ if (currentAtom < atomRange.start) before.push(node);+ else if (currentAtom >= atomRange.end) after.push(node);+ continue;+ }if (nodeEnd <= start) {before.push(node);@@ -300,7 +366,7 @@ export function replaceComposerTextRange(}}- if (start >= offset) before.push(...document.nodes.slice(before.length));+ if (!atomRange && start >= offset) before.push(...document.nodes.slice(before.length));return normalizeComposerDocument({ version: 1, nodes: [...before, ...replacement, ...after] });}diff --git a/apps/mobile/src/session/composerDraftSource.ts b/apps/mobile/src/session/composerDraftSource.tsindex d39bcbf839..602906ff0e 100644--- a/apps/mobile/src/session/composerDraftSource.ts+++ b/apps/mobile/src/session/composerDraftSource.ts@@ -31,7 +31,7 @@ export function createComposerDraftSource(document: ComposerDocument) {export type ComposerDraftSource = ReturnType<typeof createComposerDraftSource>;/** A running voice controller follows source replacement within its task only. */-export function useComposerVoiceDraftWriter(sessionId: string, writeDraft: (draft: string) => void) {+export function useComposerVoiceDraftWriter<T>(sessionId: string, writeDraft: (draft: T) => void) {const owner = useMemo(() => ({ sessionId }), [sessionId]);const latest = useRef<{ owner: typeof owner; writeDraft: typeof writeDraft } | null>(null);latest.current = { owner, writeDraft };@@ -41,7 +41,7 @@ export function useComposerVoiceDraftWriter(sessionId: string, writeDraft: (drafif (latest.current?.owner === owner) latest.current = null;};}, [owner]);- return useCallback((draft: string) => {+ return useCallback((draft: T) => {const current = latest.current;if (current?.owner === owner) current.writeDraft(draft);}, [owner]);diff --git a/apps/mobile/src/session/composerRichInputHtml.ts b/apps/mobile/src/session/composerRichInputHtml.tsindex 67d7c8495e..f5c602c668 100644--- a/apps/mobile/src/session/composerRichInputHtml.ts+++ b/apps/mobile/src/session/composerRichInputHtml.ts@@ -120,6 +120,8 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): strapplyConfig(config);let applying = false;+ let reportUserSelection = false;+ let documentId = 0;let composing = false;let lastSignature = '';let pasteRequestSequence = 0;@@ -188,6 +190,7 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): str// but never posted, so the send button stays disabled.composing = false;applying = true;+ reportUserSelection = false;// Android WebView 85 lacks the modern child-replacement API; use legacy DOM primitives.const fragment = document.createDocumentFragment();flattenDomNodes(documentValue.nodes).forEach((node) => fragment.appendChild(node));@@ -241,6 +244,62 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): strwalk(root, nodes);return { version: 1, nodes };};+ // Count prefixes without cloning DOM or decoding atom payloads. Native owns+ // each atom's projected length, including long pasted text and titled links.+ const prefixAt = (container, offset) => {+ let textLength = 0, atomCount = 0, lastText = false, stopped = false;+ const addText = (text, end, rawText) => {+ let length = end;+ if (!rawText) for (let at = text.indexOf(CARET_ANCHOR); at >= 0 && at < end; at = text.indexOf(CARET_ANCHOR, at + 1)) length--;+ textLength += length;+ if (length) lastText = true;+ };+ const visit = (parent, rawText = false) => {+ const children = parent.childNodes;+ for (let index = 0; index < children.length; index++) {+ if (parent === container && index === offset) { stopped = true; return; }+ const child = children[index];+ if (child.nodeType === Node.TEXT_NODE) {+ const text = child.nodeValue || '';+ addText(text, child === container ? offset : text.length, rawText);+ if (child === container) { stopped = true; return; }+ } else if (child.nodeType === Node.ELEMENT_NODE) {+ // walk serializes slash spans via textContent, without block/BR separators.+ if (rawText || child.classList.contains('slash')) {+ visit(child, true);+ if (stopped) return;+ continue;+ }+ if (child.classList.contains('atom')) { atomCount++; lastText = false; continue; }+ if (child.tagName === 'BR') { textLength++; lastText = true; continue; }+ const beforeText = textLength, beforeAtoms = atomCount;+ visit(child);+ if (stopped) return;+ if (/^(DIV|P|LI)$/.test(child.tagName) && index < children.length - 1+ && (textLength !== beforeText || atomCount !== beforeAtoms || lastText)) {+ textLength++; lastText = true;+ }+ }+ }+ if (parent === container) stopped = true;+ };+ visit(root);+ return { textLength, atomCount };+ };+ const reportSelection = () => {+ if (applying || composing || !reportUserSelection) return;+ const selection = window.getSelection();+ if (!selection || !selection.rangeCount) return;+ const range = selection.getRangeAt(0);+ if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return;+ post({ type: 'selection', documentId,+ before: prefixAt(range.startContainer, range.startOffset),+ through: prefixAt(range.endContainer, range.endOffset) });+ };+ document.addEventListener('selectionchange', reportSelection);+ ['touchstart', 'mousedown', 'keydown', 'input'].forEach((name) => {+ root.addEventListener(name, () => { reportUserSelection = true; });+ });let lastReportedHeight = null;const reportHeight = () => {const height = Math.min(config.maxHeight, Math.max(${COMPOSER_SINGLE_LINE_HEIGHT}, root.scrollHeight));@@ -255,9 +314,10 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): strconst signature = JSON.stringify(value);if (signature !== lastSignature) {lastSignature = signature;- post({ type: 'change', document: value });+ post(Object.assign({ type: 'change', document: value }, documentId ? { documentId } : {}));}reportHeight();+ reportSelection();};const setCaretAfter = (node, selection) => {const range = document.createRange();@@ -443,7 +503,7 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): strroot.addEventListener('compositionend', () => { composing = false; notify(); });root.addEventListener('compositioncancel', () => { composing = false; notify(); });root.addEventListener('focus', () => post({ type: 'focus' }));- root.addEventListener('blur', () => post({ type: 'blur' }));+ root.addEventListener('blur', () => { reportSelection(); post({ type: 'blur' }); });root.addEventListener('keydown', (event) => {const backward = event.key === 'Backspace';if (!backward && event.key !== 'Delete') return;@@ -511,8 +571,29 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): str}, { passive: false });window.cindyComposer = {- applyDocument(value, focusAfter) { render(value, focusAfter === true); },- focus() { placeCaretAtEnd(); },+ applyDocument(value, focusAfter, caret, nextDocumentId) {+ if (Number.isSafeInteger(nextDocumentId)) documentId = nextDocumentId;+ render(value, focusAfter === true && !caret);+ if (!focusAfter || !caret) return;+ root.focus();+ const nodes = Array.from(root.childNodes).filter((node) => !isEmptyCaretAnchor(node));+ const node = nodes[caret.nodeIndex];+ const selection = window.getSelection();+ if (!node || !selection) { placeCaretAtEnd(); return; }+ reportUserSelection = true;+ if (node.nodeType !== Node.TEXT_NODE && !node.classList.contains('slash')) {+ setCaretAfter(node, selection);+ } else {+ const textNode = node.nodeType === Node.TEXT_NODE ? node : node.firstChild;+ const range = document.createRange();+ range.setStart(textNode, Math.min(caret.offset, (textNode.nodeValue || '').length));+ range.collapse(true);+ selection.removeAllRanges();+ selection.addRange(range);+ }+ reportSelection();+ },+ focus() { reportUserSelection = true; placeCaretAtEnd(); },blur() { root.blur(); },insertNode(node) { insertAtSelection(node); },commitPaste(requestId, nodes) { commitPaste(requestId, nodes); },diff --git a/apps/mobile/src/session/composerRichInputProtocol.ts b/apps/mobile/src/session/composerRichInputProtocol.tsindex 993b963e57..989412bcc3 100644--- a/apps/mobile/src/session/composerRichInputProtocol.ts+++ b/apps/mobile/src/session/composerRichInputProtocol.ts@@ -1,3 +1,5 @@+export interface ComposerSelectionPrefix { textLength: number; atomCount: number }+export type ComposerWebMessage =/*** focus 只代表「编辑器现在有 DOM 焦点」,**不代表用户点了输入框**:WKWebView 在输入区@@ -7,7 +9,8 @@ export type ComposerWebMessage =*/| { type: 'ready' | 'focus' | 'blur' }| { type: 'height'; height: number }- | { type: 'change'; document: unknown }+ | { type: 'change'; document: unknown; documentId?: number }+ | { type: 'selection'; documentId: number; before: ComposerSelectionPrefix; through: ComposerSelectionPrefix }| { type: 'paste-text-request'; requestId: string; text?: string }| { type: 'paste-images-start'; requestId: string; count: number }| { type: 'paste-image'; requestId: string; base64: string; mimeType: string; name: string; index: number }@@ -47,7 +50,13 @@ export function parseComposerWebMessage(raw: string): ComposerWebMessage | null: null;}if (message.type === 'change') {- return { type: 'change', document: message.document };+ if (message.documentId !== undefined && !isOffset(message.documentId)) return null;+ return { type: 'change', document: message.document,+ ...(message.documentId === undefined ? {} : { documentId: message.documentId as number }) };+ }+ 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 };}if (message.type === 'paste-text-request') {if (@@ -102,6 +111,16 @@ export function parseComposerWebMessage(raw: string): ComposerWebMessage | null}}+function isOffset(value: unknown): value is number {+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;+}++function isPrefix(value: unknown): value is ComposerSelectionPrefix {+ if (!value || typeof value !== 'object') return false;+ const prefix = value as Record<string, unknown>;+ return isOffset(prefix.textLength) && isOffset(prefix.atomCount);+}+function isValidRequestId(value: unknown): value is string {return typeof value === 'string'&& value.length > 0diff --git a/apps/mobile/src/session/mobileVoiceController.ts b/apps/mobile/src/session/mobileVoiceController.tsindex 45f0e805b7..b924b64311 100644--- a/apps/mobile/src/session/mobileVoiceController.ts+++ b/apps/mobile/src/session/mobileVoiceController.ts@@ -20,6 +20,8 @@ import { createMobileAsrProvider } from '@/session/mobileRealtimeAsrProvider';import { CINDY_MANAGED_REFINER_PROVIDER } from '@/session/mobileCindyVoiceSession';import {appendVoiceTranscriptDraftWithRange,+ insertVoiceTranscriptDraftWithRange,+ type MobileVoiceSelection,buildMobileVoiceRefinementContext,makeMobileRefinerPromptCacheKey,MobileLiteLlmTextModelClient,@@ -55,6 +57,7 @@ export type MobileVoiceControllerSession = {type MobileVoiceControllerOptions = {credential: StoredMobileVoiceCredential;initialDraft: string;+ initialSelection?: MobileVoiceSelection;refinementContext?: DictationRefinementContext;localVoiceInputHistory?: readonly string[];asr?: AsrProvider;@@ -75,7 +78,7 @@ type MobileVoiceControllerOptions = {}) => Promise<void>;startAudio?: StartRealtimeAudio;readCurrentDraft?: () => string;- onDraftChanged: (draft: string) => void;+ onDraftChanged: (draft: string, selection?: MobileVoiceSelection, replacement?: MobileVoiceDraftInsertion) => void;onStateChanged?: (state: VoiceInputState) => void;onError?: (message: string) => void;onReadyForStartCue?: () => void;@@ -197,6 +200,7 @@ export function createMobileVoiceControllerSession(let asrStartError: unknown = null;let audioFailureError: Error | null = null;let voiceInsertion: MobileVoiceDraftInsertion | null = null;+ let publishedVoiceInsertion: MobileVoiceDraftInsertion | null = null;let voiceInsertionSegmentIds: string[] = [];let voiceInsertionTouched = false;let historyEntryId: string | null = null;@@ -207,6 +211,14 @@ export function createMobileVoiceControllerSession(const readCurrentDraft = (): string => {const visibleDraft = options.readCurrentDraft?.() ?? latestDraft;+ if (+ options.readCurrentDraft && pendingDraftToPublish !== null+ && visibleDraft !== lastPublishedDraft+ && voiceInsertion && publishedVoiceInsertion+ && isInsertionIntact(visibleDraft, publishedVoiceInsertion)+ ) {+ return replaceInsertionText(visibleDraft, publishedVoiceInsertion, voiceInsertion.text);+ }if (visibleDraft === lastPublishedDraft&& (pendingDraftToPublish !== null || draftPublishThrottleTimer !== null)@@ -218,20 +230,29 @@ export function createMobileVoiceControllerSession(const publishDraftNow = (draft: string): void => {pendingDraftToPublish = null;- if (lastPublishedDraft === draft) return;+ // The first insertion can change selected atoms even when its text is identical.+ if (lastPublishedDraft === draft && (!voiceInsertion || publishedVoiceInsertion)) return;+ const replacement = publishedVoiceInsertion && voiceInsertion+ ? { ...publishedVoiceInsertion, text: voiceInsertion.text }+ : undefined;lastPublishedDraft = draft;- options.onDraftChanged(draft);+ publishedVoiceInsertion = voiceInsertion ? { ...voiceInsertion } : null;+ options.onDraftChanged(draft, voiceInsertion+ ? { start: voiceInsertion.end, end: voiceInsertion.end }+ : undefined, replacement);};const publishPendingDraftNow = (): void => {const pending = pendingDraftToPublish;if (pending === null) return;- if (voiceInsertion && !isInsertionIntact(readCurrentDraft(), voiceInsertion)) {+ const currentDraft = readCurrentDraft();+ if (voiceInsertion && !isInsertionIntact(currentDraft, voiceInsertion)) {voiceInsertionTouched = true;pendingDraftToPublish = null;return;}- publishDraftNow(pending);+ latestDraft = currentDraft;+ publishDraftNow(currentDraft);};const cancelPendingDraftPublish = (): void => {@@ -316,7 +337,11 @@ export function createMobileVoiceControllerSession(return buildEditableRange(voiceInsertion, segmentIds, voiceInsertionTouched);}- const result = appendVoiceTranscriptDraftWithRange(currentDraft, normalized);+ // A selection belongs to its captured draft. If typing changed that draft+ // before the first ASR result, preserve the edit instead of replacing stale offsets.+ const result = options.initialSelection && currentDraft === baseDraft+ ? insertVoiceTranscriptDraftWithRange(currentDraft, normalized, options.initialSelection)+ : appendVoiceTranscriptDraftWithRange(currentDraft, normalized);if (!result.insertion) return undefined;voiceInsertion = result.insertion;voiceInsertionSegmentIds = segmentIds;diff --git a/apps/mobile/src/session/mobileVoiceInput.ts b/apps/mobile/src/session/mobileVoiceInput.tsindex 795929f76e..122e972e7a 100644--- a/apps/mobile/src/session/mobileVoiceInput.ts+++ b/apps/mobile/src/session/mobileVoiceInput.ts@@ -74,6 +74,26 @@ export interface MobileVoiceDraftInsertion {text: string;}+export interface MobileVoiceSelection {+ start: number;+ end: number;+}++export function insertVoiceTranscriptDraftWithRange(+ current: string,+ transcript: string,+ selection: MobileVoiceSelection,+): { draft: string; insertion: MobileVoiceDraftInsertion | null } {+ const text = transcript.trim();+ if (!text) return { draft: current, insertion: null };+ const start = Math.max(0, Math.min(current.length, selection.start));+ const end = Math.max(start, Math.min(current.length, selection.end));+ return {+ draft: current.slice(0, start) + text + current.slice(end),+ insertion: { start, end: start + text.length, text },+ };+}+interface VoicePresignResult {putUrl: string;key: string;