Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 修复语音听写的换行错位与「刚开始就被掐断」 (#551)
Dash909ee5804ab6
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex f221ca9223..00e4004434 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -246,10 +246,12 @@ import {ComposerToolbarSpacer,ComposerToolbarVoiceSlot,MOBILE_COMPOSER_CONTROL_SIZE,+ MOBILE_COMPOSER_DRAFT_TEXT_STYLE,MOBILE_COMPOSER_INPUT_LINE_HEIGHT,MOBILE_COMPOSER_INPUT_MAX_HEIGHT,MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT,MOBILE_COMPOSER_INPUT_VERTICAL_PADDING,+ MOBILE_COMPOSER_MIN_TOUCH_TARGET,MOBILE_COMPOSER_TOOL_GAP,MobileComposerInputRow,VoiceMicWaveCaret,@@ -301,6 +303,7 @@ import {resolveComposerVoiceHoldActive,shouldArmComposerVoiceHold,} from '@/session/composerVoiceHold';+import { COMPOSER_TEXT_HORIZONTAL_PADDING } from '@/session/composerTextMetrics';import {isMobileRealtimeAudioAvailable,prewarmMobileRealtimeAudio,@@ -1817,52 +1820,68 @@ export default function SessionScreen() {</>);const renderComposerInputOverlay = () => voiceIsListening ? (- <ScrollView- ref={voiceDraftScrollRef}- contentContainerStyle={styles.voiceDraftOverlayContent}- onContentSizeChange={() => {- requestAnimationFrame(() => {- voiceDraftScrollRef.current?.scrollToEnd({ animated: false });- });- }}- onLayout={() => {- requestAnimationFrame(() => {- voiceDraftScrollRef.current?.scrollToEnd({ animated: false });- });- }}- pointerEvents="none"- scrollEnabled={composerInputScrollEnabled}- showsVerticalScrollIndicator={false}+ // 「点输入区 = 想打字 → 停止听写」由这层 RN 覆盖层承接。听写期间真正盖在输入区上的+ // 就是它;底下的富文本 WebView 此刻是 hidden(opacity 0),iOS hitTest 会跳过 alpha≈0+ // 的 view,它根本收不到触摸——把停听写挂在 WebView 的 focus / touch 上都不成立+ // (focus 还会被 WKWebView 自己恢复焦点误触发,掐断刚开始的听写)。+ <Pressable+ accessibilityLabel={t('session.common.voiceStopRecording')}+ accessibilityRole="button"+ // onPressIn 给手指「触摸即停」的即时手感;onPress 是无障碍激活(VoiceOver /+ // TalkBack 的 activate 只走 onPress,不会派发 onPressIn)的唯一入口,两者都要挂。+ // handler 幂等:finishVoiceRecording 有 voiceStopInFlight 门,重复调用是 no-op。+ onPress={handleComposerInputPressIn}+ onPressIn={handleComposerInputPressIn}style={styles.voiceDraftOverlay}+ testID="session.voiceDraftOverlay">- {voiceDraftShowsListeningPrompt ? (- <View style={styles.voiceDraftListeningPrompt}>- <VoiceMicWaveCaret color={colors.statusReady} testID="session.voiceMicCaret" />- <Text style={styles.voiceDraftListeningText}>{composerLayout.input.placeholder}</Text>- </View>- ) : (- <View style={styles.voiceDraftMeasuredBlock}>- <Text- onTextLayout={handleVoiceDraftTextLayout}- style={styles.voiceDraftText}- >- {draft}- </Text>- <View- pointerEvents="none"- style={[- styles.voiceDraftCaretOverlay,- {- left: voiceDraftCaretFrame.left,- top: voiceDraftCaretFrame.top,- },- ]}- >+ <ScrollView+ ref={voiceDraftScrollRef}+ contentContainerStyle={styles.voiceDraftOverlayContent}+ onContentSizeChange={() => {+ requestAnimationFrame(() => {+ voiceDraftScrollRef.current?.scrollToEnd({ animated: false });+ });+ }}+ onLayout={() => {+ requestAnimationFrame(() => {+ voiceDraftScrollRef.current?.scrollToEnd({ animated: false });+ });+ }}+ pointerEvents="none"+ scrollEnabled={composerInputScrollEnabled}+ showsVerticalScrollIndicator={false}+ style={styles.voiceDraftScroll}+ >+ {voiceDraftShowsListeningPrompt ? (+ <View style={styles.voiceDraftListeningPrompt}><VoiceMicWaveCaret color={colors.statusReady} testID="session.voiceMicCaret" />+ <Text style={styles.voiceDraftListeningText}>{composerLayout.input.placeholder}</Text></View>- </View>- )}- </ScrollView>+ ) : (+ <View style={styles.voiceDraftMeasuredBlock}>+ <Text+ onTextLayout={handleVoiceDraftTextLayout}+ style={styles.voiceDraftText}+ >+ {draft}+ </Text>+ <View+ pointerEvents="none"+ style={[+ styles.voiceDraftCaretOverlay,+ {+ left: voiceDraftCaretFrame.left,+ top: voiceDraftCaretFrame.top,+ },+ ]}+ >+ <VoiceMicWaveCaret color={colors.statusReady} testID="session.voiceMicCaret" />+ </View>+ </View>+ )}+ </ScrollView>+ </Pressable>) : null;const measureSendButtonTarget = useCallback(() => {sendButtonRef.current?.measureInWindow((x, y, width, height) => {@@ -7096,6 +7115,9 @@ export default function SessionScreen() {floatingVoiceButtonStyle={composerFloatingVoiceButtonStyle}cursorColor={colors.inputCaret}inputFrameHeight={composerResize.frameHeight}+ // 听写期间把输入区撑到 44pt 触控目标:命中层盖在 inputFrame 上,+ // hitSlop 越不过父边界(见常量注释)。+ inputFrameMinHeight={voiceIsListening ? MOBILE_COMPOSER_MIN_TOUCH_TARGET : undefined}inputElement={(<ComposerRichInputref={composerInputRef}@@ -7111,10 +7133,7 @@ export default function SessionScreen() {setComposerVoiceHoldArmed(false);}}onChangeDocument={applyRichComposerChange}- onFocus={() => {- setComposerFocused(true);- handleComposerInputPressIn();- }}+ onFocus={() => setComposerFocused(true)}onHeightChange={handleComposerRichInputHeight}onPasteImages={(uris) => void addPastedImageAttachments(uris)}onPasteImagesLoading={beginPastePlaceholders}@@ -7134,7 +7153,7 @@ export default function SessionScreen() {/>)}inputOverlay={renderComposerInputOverlay()}- inputStyle={[styles.sessionComposerInput, voiceIsListening && styles.inputVoiceHidden]}+ inputStyle={voiceIsListening ? styles.inputVoiceHidden : undefined}inputTestID="session.composerInput"leading={renderComposerCollapsedAttachmentBadge()}maxHeight={composerResize.inputMaxHeight}@@ -8319,16 +8338,17 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({backgroundColor: colors.surfaceChip,borderColor: colors.borderStrong,},- sessionComposerInput: {- fontSize: typeScale.listBody,- lineHeight: lineHeight.listBody,- },voiceDraftOverlay: {...StyleSheet.absoluteFill,overflow: 'hidden',},+ // 草稿滚动层填满外层触摸区(外层负责「点输入区停听写」,自身 pointerEvents 关闭)。+ voiceDraftScroll: {+ flex: 1,+ },+ // 内边距与真实输入框同源:差一点就会让听写文字与非听写文字左右错位、换行位置不同。voiceDraftOverlayContent: {- paddingHorizontal: spacing.xs,+ paddingHorizontal: COMPOSER_TEXT_HORIZONTAL_PADDING,paddingVertical: COMPOSER_INPUT_VERTICAL_PADDING,},voiceDraftMeasuredBlock: {@@ -8338,10 +8358,11 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({voiceDraftCaretOverlay: {position: 'absolute',},+ // 草稿层的文本档必须与真实 TextInput 完全一致,否则换行位置错开、超出的行被裁在+ // 框外(见 MOBILE_COMPOSER_DRAFT_TEXT_STYLE)。voiceDraftText: {color: colors.textPrimary,- fontSize: typeScale.body,- lineHeight: COMPOSER_INPUT_LINE_HEIGHT,+ ...MOBILE_COMPOSER_DRAFT_TEXT_STYLE,},voiceDraftListeningPrompt: {alignItems: 'center',@@ -8350,8 +8371,7 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({},voiceDraftListeningText: {color: colors.statusReady,- fontSize: typeScale.body,- lineHeight: COMPOSER_INPUT_LINE_HEIGHT,+ ...MOBILE_COMPOSER_DRAFT_TEXT_STYLE,},palettePanel: {backgroundColor: colors.surfaceElevated,diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 9d7819a41d..4d25cfa60e 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -174,10 +174,12 @@ import {ComposerToolbarSpacer,ComposerToolbarVoiceSlot,MOBILE_COMPOSER_CONTROL_SIZE,+ MOBILE_COMPOSER_DRAFT_TEXT_STYLE,MOBILE_COMPOSER_INPUT_LINE_HEIGHT,MOBILE_COMPOSER_INPUT_MAX_HEIGHT,MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT,MOBILE_COMPOSER_INPUT_VERTICAL_PADDING,+ MOBILE_COMPOSER_MIN_TOUCH_TARGET,MobileComposerInputRow,VoiceMicWaveCaret,resolveMobileComposerVoiceButtonPlacement,@@ -195,6 +197,7 @@ import {resolveComposerVoiceHoldActive,shouldArmComposerVoiceHold,} from '@/session/composerVoiceHold';+import { COMPOSER_TEXT_HORIZONTAL_PADDING } from '@/session/composerTextMetrics';import {isMobileRealtimeAudioAvailable,prewarmMobileRealtimeAudio,@@ -2804,8 +2807,11 @@ export default function NewRemoteSessionScreen() {inputRef={firstMessageInputRef}leading={renderComposerCollapsedAttachmentBadge()}inputFrameHeight={composerResize.frameHeight}+ // 听写期间把输入区撑到 44pt 触控目标:此时「点输入区停止听写」的命中层+ // 是这层输入区自身(TextInput 的 onPressIn),单行时只有 28pt。+ inputFrameMinHeight={voiceIsListening ? MOBILE_COMPOSER_MIN_TOUCH_TARGET : undefined}inputOverlay={renderComposerInputOverlay()}- inputStyle={[styles.sessionComposerInput, voiceIsListening && styles.inputVoiceHidden]}+ inputStyle={voiceIsListening ? styles.inputVoiceHidden : undefined}inputTestID="newSession.firstMessageInput"maxHeight={composerResize.inputMaxHeight}multilineShape={!composerCardActive && composerInputIsMultiline}@@ -3533,8 +3539,9 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({...StyleSheet.absoluteFill,overflow: 'hidden',},+ // 内边距与真实输入框同源:差一点就会让听写文字与非听写文字左右错位、换行位置不同。voiceDraftOverlayContent: {- paddingHorizontal: spacing.xs,+ paddingHorizontal: COMPOSER_TEXT_HORIZONTAL_PADDING,paddingVertical: MOBILE_COMPOSER_INPUT_VERTICAL_PADDING,},voiceDraftMeasuredBlock: {@@ -3544,10 +3551,11 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({voiceDraftCaretOverlay: {position: 'absolute',},+ // 草稿层的文本档必须与真实 TextInput 完全一致,否则换行位置错开、超出的行被裁在+ // 框外(见 MOBILE_COMPOSER_DRAFT_TEXT_STYLE)。voiceDraftText: {color: colors.textPrimary,- fontSize: typeScale.body,- lineHeight: MOBILE_COMPOSER_INPUT_LINE_HEIGHT,+ ...MOBILE_COMPOSER_DRAFT_TEXT_STYLE,},voiceDraftListeningPrompt: {alignItems: 'center',@@ -3556,8 +3564,7 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({},voiceDraftListeningText: {color: colors.statusReady,- fontSize: typeScale.body,- lineHeight: MOBILE_COMPOSER_INPUT_LINE_HEIGHT,+ ...MOBILE_COMPOSER_DRAFT_TEXT_STYLE,},composerToolbarWrap: {position: 'relative',@@ -3587,10 +3594,6 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({lineHeight: lineHeight.caption,minWidth: 0,},- sessionComposerInput: {- fontSize: typeScale.listBody,- lineHeight: lineHeight.listBody,- },inputVoiceHidden: {color: 'transparent',},diff --git a/apps/mobile/src/__tests__/composerRichInputHtml.test.ts b/apps/mobile/src/__tests__/composerRichInputHtml.test.tsindex 759a1d2b89..1fd09b1ecc 100644--- a/apps/mobile/src/__tests__/composerRichInputHtml.test.ts+++ b/apps/mobile/src/__tests__/composerRichInputHtml.test.ts@@ -93,6 +93,48 @@ describe('mobile composer rich input HTML', () => {expect(selectSource).not.toContain('composerInputRef.current?.focus();');});+ /**+ * 「点输入区 = 想打字 → 停止听写」必须由听写期间盖在输入区上的 RN 覆盖层承接:+ * - 挂 WebView 的 focus 不行:WKWebView 在输入区展开、拿到 native 焦点后会自己恢复+ * DOM 焦点并派发 focus,收起态点语音、输入框展开的那一拍就把刚开始的听写掐断;+ * - 挂 WebView 内的触摸也不行:听写期间富文本编辑器是 hidden(opacity 0),iOS hitTest+ * 跳过 alpha≈0 的 view,它根本收不到触摸。+ * 两条都由 2026-07 的实机日志确认。+ */+ it('stops dictation from the RN draft overlay instead of WebView focus', () => {+ const screenSource = readFileSync(+ resolve(process.cwd(), 'app/sessions/[sessionId].tsx'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+ const overlayStart = screenSource.indexOf('const renderComposerInputOverlay = ');+ const overlaySource = screenSource.slice(+ overlayStart,+ screenSource.indexOf('const measureSendButtonTarget', overlayStart),+ );++ expect(overlaySource).toContain('onPressIn={handleComposerInputPressIn}');+ // 无障碍激活(VoiceOver / TalkBack)只走 onPress,不会派发 onPressIn:两者都必须挂,+ // 否则读屏用户按下这个「停止录音」按钮不会有任何反应。+ expect(overlaySource).toContain('onPress={handleComposerInputPressIn}');+ // 单行听写时 inputFrame 只有 28pt,命中层必须靠父容器撑到 44pt 触控目标——+ // hitSlop 无效(RN 的命中区不会越过父视图边界),所以不许再用它顶替。+ expect(overlaySource).not.toContain('hitSlop');+ expect(screenSource).toContain('inputFrameMinHeight={voiceIsListening ? MOBILE_COMPOSER_MIN_TOUCH_TARGET : undefined}');++ // hidden 的富文本编辑器必须同时从两端的无障碍树里摘掉:opacity: 0 不隐藏读屏焦点,+ // 而它的 focus 已不再停听写,焦点留在那里会让读屏用户卡在「按了没反应」的输入框上。+ const inputSource = readFileSync(+ resolve(process.cwd(), 'src/session/ComposerRichInput.tsx'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+ expect(inputSource).toContain('accessibilityElementsHidden={hidden}');+ expect(inputSource).toContain("importantForAccessibility={hidden ? 'no-hide-descendants' : 'auto'}");+ expect(overlaySource).toContain('testID="session.voiceDraftOverlay"');+ // 草稿滚动层本身不吃触摸,交给外层覆盖层。+ expect(overlaySource).toContain('pointerEvents="none"');+ expect(screenSource).toContain('onFocus={() => setComposerFocused(true)}');+ });+it('rejects malformed image messages at the WebView boundary', () => {expect(parseComposerWebMessage(JSON.stringify({ type: 'paste-images-start', count: '2' }))).toBeNull();expect(parseComposerWebMessage(JSON.stringify({diff --git a/apps/mobile/src/__tests__/composerVoiceDraftMetrics.test.ts b/apps/mobile/src/__tests__/composerVoiceDraftMetrics.test.tsnew file mode 100644index 0000000000..baa72fd10e--- /dev/null+++ b/apps/mobile/src/__tests__/composerVoiceDraftMetrics.test.ts@@ -0,0 +1,113 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';++/**+ * Composer 三个文本渲染器的度量一致性守护。+ *+ * 同一段草稿文字可能由三处画出来:新建会话页的原生 TextInput、会话页的 WebView 富文本+ * 编辑器、语音听写期间盖在上面的草稿覆盖层。前两者撑起输入区高度,第三者只是展示层。+ *+ * 背景(2026-07 修复):三处曾各写一份档位——原生 14/20(页面覆盖)、WebView CSS 字面+ * 15/22 且无水平内边距、听写层 16/22。后果是听写层提前一行换行,新起的那行落在框外被+ * overflow hidden 裁掉(说到第二行看不到新内容,要等输入框也换行才补出来),听写文字与+ * 非听写文字的字号、左右起点也明显不同。+ *+ * 因此字号 / 行高 / 内边距只许来自 composerTextMetrics 一个正本。+ */++const ROOT = process.cwd();+const METRICS = 'src/session/composerTextMetrics.ts';+const COMPOSER_ROW = 'src/session/MobileComposerInputRow.tsx';+const RICH_INPUT_HTML = 'src/session/composerRichInputHtml.ts';+const COMPOSER_PAGES = ['app/sessions/new.tsx', 'app/sessions/[sessionId].tsx'];+const DRAFT_TEXT_STYLES = ['voiceDraftText', 'voiceDraftListeningText'];++function read(rel: string): string {+ // 归一化换行:Windows checkout 是 CRLF,styleBlock 的 `\n <name>:` 锚点会全部失配。+ return readFileSync(join(ROOT, rel), 'utf8').replace(/\r\n/g, '\n');+}++/**+ * 取 StyleSheet 里某个样式键的对象字面量内容(这些块内部没有嵌套对象)。+ * 锚定「行首两空格缩进」以命中样式表条目,不误吃同名的函数参数对象。+ */+function styleBlock(source: string, name: string): string {+ const match = new RegExp(`\\n {2}${name}:\\s*\\{([^}]*)\\}`).exec(source);+ expect(match, `未找到样式 ${name}`).not.toBeNull();+ return match![1];+}++describe('composer voice draft text metrics', () => {+ it('derives the shared composer metrics from the design tokens', () => {+ const source = read(METRICS);+ expect(source).toContain('export const COMPOSER_TEXT_FONT_SIZE = typeScale.code;');+ expect(source).toContain('export const COMPOSER_TEXT_LINE_HEIGHT = lineHeight.body;');+ expect(source).toContain('export const COMPOSER_TEXT_HORIZONTAL_PADDING = spacing.xs;');+ // WebView HTML 生成器与 node 单测都要 import 本文件,不能把 react-native 拖进来。+ expect(source).not.toMatch(/from 'react-native'/);+ });++ it('exposes the shared metrics as the composer row draft text style', () => {+ const source = read(COMPOSER_ROW);+ expect(source).toContain('export const MOBILE_COMPOSER_DRAFT_TEXT_STYLE = COMPOSER_TEXT_STYLE;');+ // 单行盒高与文本行高同源:「单行」必须正好装一行文字。+ expect(source).toContain('export const MOBILE_COMPOSER_INPUT_LINE_HEIGHT = COMPOSER_TEXT_LINE_HEIGHT;');+ });++ it('renders the real composer TextInput with the shared metrics', () => {+ const block = styleBlock(read(COMPOSER_ROW), 'input');+ expect(block).toContain('...COMPOSER_TEXT_STYLE');+ expect(block).toContain('paddingHorizontal: COMPOSER_TEXT_HORIZONTAL_PADDING');+ });++ it('renders the WebView rich composer with the shared metrics instead of CSS literals', () => {+ const source = read(RICH_INPUT_HTML);+ expect(source).toContain('font-size: ${COMPOSER_TEXT_FONT_SIZE}px');+ expect(source).toContain('line-height: ${COMPOSER_TEXT_LINE_HEIGHT}px');+ expect(source).toContain('padding: ${COMPOSER_TEXT_VERTICAL_PADDING}px ${COMPOSER_TEXT_HORIZONTAL_PADDING}px');+ // #editor 的排版不得回退成字面量(CSS 不在 typographyTokenDiscipline 的扫描面内)。+ const editorBlock = /#editor \{([^}]*)\}/.exec(source)?.[1] ?? '';+ expect(editorBlock).not.toMatch(/font-size:\s*\d/);+ expect(editorBlock).not.toMatch(/line-height:\s*\d/);+ });++ it('keeps every voice draft overlay text on the shared draft text style', () => {+ for (const rel of COMPOSER_PAGES) {+ const source = read(rel);+ for (const name of DRAFT_TEXT_STYLES) {+ const block = styleBlock(source, name);+ expect(block, `${rel} ${name} 必须复用输入框档位`).toContain('...MOBILE_COMPOSER_DRAFT_TEXT_STYLE');+ expect(block, `${rel} ${name} 不得自带字号 / 行高`).not.toMatch(/fontSize|lineHeight/);+ }+ const overlayContent = styleBlock(source, 'voiceDraftOverlayContent');+ expect(overlayContent, `${rel} 覆盖层水平内边距必须与输入框同源`)+ .toContain('paddingHorizontal: COMPOSER_TEXT_HORIZONTAL_PADDING');+ }+ });++ /**+ * 听写期间「点输入区停止听写」的命中层盖在 inputFrame 上,单行时只有 28pt;+ * 触控目标要 ≥44pt(mobile-design-guide),且只能靠父容器撑起——RN 的 hitSlop+ * 不会越过父视图边界。两个页面都要撑,否则各自的听写停止都点不准。+ */+ it('raises the input frame to the touch target while dictating', () => {+ const row = read(COMPOSER_ROW);+ expect(row).toContain('export const MOBILE_COMPOSER_MIN_TOUCH_TARGET = 44;');+ // 显式 height 会压过 minHeight(manual 定高时 frameHeight 可能小于触控目标),+ // 数值高度必须先 clamp,否则命中区又被压回 28pt。+ expect(row).toContain('Math.max(inputFrameHeight, inputFrameMinHeight)');+ expect(row).toContain('resolvedInputFrameHeight != null && { height: resolvedInputFrameHeight }');+ for (const rel of COMPOSER_PAGES) {+ expect(read(rel), `${rel} 听写期间必须把输入区撑到触控目标`)+ .toContain('inputFrameMinHeight={voiceIsListening ? MOBILE_COMPOSER_MIN_TOUCH_TARGET : undefined}');+ }+ });++ it('forbids page-level font overrides on the composer input', () => {+ for (const rel of COMPOSER_PAGES) {+ expect(read(rel), `${rel} 不得再用页面样式覆盖输入框字号 / 行高`)+ .not.toContain('sessionComposerInput');+ }+ });+});diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.tsindex 5946d7e391..b1af62ee6d 100644--- a/apps/mobile/src/__tests__/newSession.test.ts+++ b/apps/mobile/src/__tests__/newSession.test.ts@@ -758,11 +758,11 @@ describe('new session composer surface', () => {const modelPillEnd = newSource.indexOf('modelPillText:', modelPillStart);const modelPillStyle = newSource.slice(modelPillStart, modelPillEnd);const modelPillTextStart = newSource.indexOf('modelPillText: {');- const modelPillTextEnd = newSource.indexOf('sessionComposerInput:', modelPillTextStart);+ const modelPillTextEnd = newSource.indexOf('inputVoiceHidden:', modelPillTextStart);const modelPillTextStyle = newSource.slice(modelPillTextStart, modelPillTextEnd);- const sessionComposerInputStart = newSource.indexOf('sessionComposerInput: {');- const sessionComposerInputEnd = newSource.indexOf('inputVoiceHidden:', sessionComposerInputStart);- const sessionComposerInputStyle = newSource.slice(sessionComposerInputStart, sessionComposerInputEnd);+ const voiceDraftTextStart = newSource.indexOf('voiceDraftText: {');+ const voiceDraftTextEnd = newSource.indexOf('voiceDraftListeningPrompt:', voiceDraftTextStart);+ const voiceDraftTextStyle = newSource.slice(voiceDraftTextStart, voiceDraftTextEnd);const sendButtonStart = newSource.indexOf('sendButton: {');const sendButtonEnd = newSource.indexOf('sendButtonDisabled:', sendButtonStart);const sendButtonStyle = newSource.slice(sendButtonStart, sendButtonEnd);@@ -811,7 +811,7 @@ describe('new session composer surface', () => {expect(newComposerSource).toContain('selectionColor={colors.inputCaret}');expect(newComposerSource).toContain('inputRef={firstMessageInputRef}');expect(newComposerSource).toContain('inputOverlay={renderComposerInputOverlay()}');- expect(newComposerSource).toContain('inputStyle={[styles.sessionComposerInput, voiceIsListening && styles.inputVoiceHidden]}');+ expect(newComposerSource).toContain('inputStyle={voiceIsListening ? styles.inputVoiceHidden : undefined}');expect(newComposerSource).toContain('onChangeText={setFirstMessageDraft}');expect(newComposerSource).toContain('onContentSizeChange={handleFirstMessageInputContentSizeChange}');expect(newComposerSource).toContain("placeholder={voiceIsListening ? '' : composerPlaceholder}");@@ -841,8 +841,11 @@ describe('new session composer surface', () => {expect(modelPillTextStyle).toContain('color: colors.textPrimary');expect(modelPillTextStyle).toContain('fontSize: typeScale.caption');expect(modelPillTextStyle).toContain('fontWeight: fontWeight.semibold');- expect(sessionComposerInputStyle).toContain('fontSize: typeScale.listBody');- expect(sessionComposerInputStyle).toContain('lineHeight: lineHeight.listBody');+ // 输入框字号档由 MobileComposerInputRow 统一持有(MOBILE_COMPOSER_DRAFT_TEXT_STYLE),+ // 页面不再覆盖;语音草稿覆盖层必须引用同一档,否则换行位置与输入框错开(见+ // composerVoiceDraftMetrics.test.ts)。+ expect(newSource).not.toContain('sessionComposerInput');+ expect(voiceDraftTextStyle).toContain('...MOBILE_COMPOSER_DRAFT_TEXT_STYLE');expect(sendButtonStyle).toContain('backgroundColor: colors.cta');expect(sendButtonStyle).toContain('borderColor: colors.cta');expect(sendButtonStyle).toContain('borderWidth: StyleSheet.hairlineWidth');diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.tsindex d788dd46b2..2c373009cf 100644--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts@@ -182,10 +182,12 @@ describe('mobile session composer desktop-first surface', () => {expect(inputStyle).toContain('borderWidth: 0');expect(inputStyle).not.toContain('borderColor: colors.border');expect(inputStyle).not.toContain('borderRadius: radius.pill');- expect(inputStyle).toContain('lineHeight: MOBILE_COMPOSER_INPUT_LINE_HEIGHT');+ // 字号 / 行高 / 水平内边距走 composerTextMetrics:WebView 富文本编辑器与语音听写+ // 覆盖层共用同一份度量,三边换行位置必须逐字一致(见 composerVoiceDraftMetrics.test.ts)。+ expect(inputStyle).toContain('...COMPOSER_TEXT_STYLE');expect(inputStyle).toContain('maxHeight: MOBILE_COMPOSER_INPUT_MAX_HEIGHT');expect(inputStyle).toContain('minHeight: MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT');- expect(inputStyle).toContain('paddingHorizontal: spacing.xs');+ expect(inputStyle).toContain('paddingHorizontal: COMPOSER_TEXT_HORIZONTAL_PADDING');expect(inputStyle).toContain('paddingVertical: MOBILE_COMPOSER_INPUT_VERTICAL_PADDING');expect(inputStyle).toContain("textAlignVertical: 'top'");// Composer input is a single stable, always-multiline, always-inline instance (no compact↔expanded@@ -321,13 +323,13 @@ describe('mobile session composer desktop-first surface', () => {expect(source).toContain('onPressIn={handleComposerInputPressIn}');expect(source).toContain("placeholder={voiceIsListening ? '' : composerLayout.input.placeholder}");expect(source).toContain('placeholderTextColor={colors.textTertiary}');- expect(source).toContain('voiceIsListening && styles.inputVoiceHidden');+ expect(source).toContain('inputStyle={voiceIsListening ? styles.inputVoiceHidden : undefined}');expect(source).toContain('styles.voiceDraftOverlay');expect(voiceDraftOverlayStyle).toContain('...StyleSheet.absoluteFill');expect(voiceDraftOverlayStyle).toContain("overflow: 'hidden'");expect(voiceDraftOverlayContentStyle).not.toContain('minHeight: COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT');expect(voiceDraftOverlayContentStyle).not.toContain("alignItems: 'flex-start'");- expect(voiceDraftOverlayContentStyle).toContain('paddingHorizontal: spacing.xs');+ expect(voiceDraftOverlayContentStyle).toContain('paddingHorizontal: COMPOSER_TEXT_HORIZONTAL_PADDING');expect(voiceDraftOverlayContentStyle).toContain('paddingVertical: COMPOSER_INPUT_VERTICAL_PADDING');expect(voiceDraftOverlayContentStyle).not.toContain("width: '100%'");expect(voiceDraftMeasuredBlockStyle).not.toContain("alignSelf: 'flex-start'");diff --git a/apps/mobile/src/session/ComposerRichInput.tsx b/apps/mobile/src/session/ComposerRichInput.tsxindex a4dcde40d7..34f13ad217 100644--- a/apps/mobile/src/session/ComposerRichInput.tsx+++ b/apps/mobile/src/session/ComposerRichInput.tsx@@ -12,6 +12,7 @@ import {} from '@/session/composerDocument';import { composerNodesForBoundedPlainTextPaste } from '@/session/composerPaste';import { buildComposerRichInputHtml, type ComposerRichInputTheme } from '@/session/composerRichInputHtml';+import { COMPOSER_SINGLE_LINE_HEIGHT } from '@/session/composerTextMetrics';import {parseComposerWebMessage,type ComposerWebMessage,@@ -326,7 +327,9 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRicreturn;}if (message.type === 'height') {- if (Number.isFinite(message.height)) onHeightChange?.(Math.max(28, Math.min(maxHeight, message.height)));+ if (Number.isFinite(message.height)) {+ onHeightChange?.(Math.max(COMPOSER_SINGLE_LINE_HEIGHT, Math.min(maxHeight, message.height)));+ }return;}if (message.type === 'focus') return onFocus?.();@@ -361,6 +364,13 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRicref={webViewRef}accessibilityHint={accessibilityHint}accessibilityLabel={accessibilityLabel}+ // hidden 期间(语音听写)把整棵子树从无障碍树里摘掉。opacity: 0 只影响视觉与+ // hitTest,读屏焦点仍能落到这个不可见的 textbox 上;而它的 focus 已不再停止听写+ // (停听写只认覆盖层的真实触摸),读屏用户会卡在一个「按了没反应」的输入框里。+ // iOS 用 accessibilityElementsHidden,Android 用 importantForAccessibility,+ // 两端都要给,少一个就会在该平台留下幽灵焦点。+ accessibilityElementsHidden={hidden}+ importantForAccessibility={hidden ? 'no-hide-descendants' : 'auto'}allowFileAccess={false}// iOS 给 WKWebView 里的可编辑区域挂一条系统表单导航条(上一项 / 下一项 /// 完成),iOS 26 起画成键盘上方的独立浮动胶囊。composer 只有这一个字段,@@ -406,6 +416,6 @@ const styles = StyleSheet.create({// react-native-webview defaults the native child to flex: 1. Override it// because this composer drives the child with an explicit measured height.flex: 0,- minHeight: 28,+ minHeight: COMPOSER_SINGLE_LINE_HEIGHT,},});diff --git a/apps/mobile/src/session/MobileComposerInputRow.tsx b/apps/mobile/src/session/MobileComposerInputRow.tsxindex 826ad7d6ad..9c8362b8b9 100644--- a/apps/mobile/src/session/MobileComposerInputRow.tsx+++ b/apps/mobile/src/session/MobileComposerInputRow.tsx@@ -17,16 +17,39 @@ import { Mic } from 'lucide-react-native';import { useCallback, useEffect, useRef, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import { iconSize, iconStroke, useThemedStyles, type ThemeColors } from '@/theme';-import { radius, spacing, typeScale } from '@/theme/tokens';+import { radius, spacing } from '@/theme/tokens';+import {+ COMPOSER_SINGLE_LINE_HEIGHT,+ COMPOSER_TEXT_HORIZONTAL_PADDING,+ COMPOSER_TEXT_LINE_HEIGHT,+ COMPOSER_TEXT_STYLE,+ COMPOSER_TEXT_VERTICAL_PADDING,+} from '@/session/composerTextMetrics';-export const MOBILE_COMPOSER_INPUT_LINE_HEIGHT = 22;-export const MOBILE_COMPOSER_INPUT_VERTICAL_PADDING = 3;-export const MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT = 28;+/**+ * Composer 草稿文本的排版档。正本在 `composerTextMetrics`——原生输入框、WebView 富文本+ * 编辑器与语音听写覆盖层共用同一档,任一处漂移都会让听写文字与真实输入框换行位置错开+ * (详见该文件注释)。此处只做转出,页面按既有名字引用。+ */+export const MOBILE_COMPOSER_DRAFT_TEXT_STYLE = COMPOSER_TEXT_STYLE;++/**+ * 输入区的单行**内容高度**(不含上下内边距) = 单行文字行高:两者同源,保证「单行」+ * 正好装一行文字。含内边距的单行可视高度是 MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT。+ */+export const MOBILE_COMPOSER_INPUT_LINE_HEIGHT = COMPOSER_TEXT_LINE_HEIGHT;+export const MOBILE_COMPOSER_INPUT_VERTICAL_PADDING = COMPOSER_TEXT_VERTICAL_PADDING;+export const MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT = COMPOSER_SINGLE_LINE_HEIGHT;export const MOBILE_COMPOSER_INPUT_MAX_VISIBLE_LINES = 12;export const MOBILE_COMPOSER_INPUT_MAX_HEIGHT = (MOBILE_COMPOSER_INPUT_LINE_HEIGHT * MOBILE_COMPOSER_INPUT_MAX_VISIBLE_LINES)+ (MOBILE_COMPOSER_INPUT_VERTICAL_PADDING * 2);export const MOBILE_COMPOSER_CONTROL_SIZE = 34;export const MOBILE_COMPOSER_TOOL_GAP = 6;+/**+ * 触控目标下限(mobile-design-guide「主操作命中区 ≥ 44×44」,iOS HIG 同值)。+ * 语音听写期间「点输入区停止听写」的命中层用它撑起 inputFrame(见 inputFrameMinHeight)。+ */+export const MOBILE_COMPOSER_MIN_TOUCH_TARGET = 44;const isExpoGo =Constants.executionEnvironment === ExecutionEnvironment.StoreClient;/** 语音按钮 absolute 锚点距 composer 内容区右缘的距离(voiceButtonAnchor.right);@@ -85,6 +108,12 @@ export interface MobileComposerInputRowProps {* null / undefined 走内容自动增长(现状行为)。*/inputFrameHeight?: number | Animated.Value | null;+ /**+ * 输入区(inputFrame)的最小高度。给语音听写用:听写期间「点输入区停止听写」的命中层+ * 盖在 inputFrame 上,而单行听写时 inputFrame 只有 28pt,不满足触控目标 44pt;+ * hitSlop 解决不了——RN 的命中区不会越过父视图边界,必须让父容器本身够高。+ */+ inputFrameMinHeight?: number;/** Rich composer replacement for the plain TextInput. */inputElement?: ReactNode;inputOverlay?: ReactNode;@@ -158,6 +187,7 @@ export function MobileComposerInputRow({floatingVoiceButton,floatingVoiceButtonStyle,inputFrameHeight,+ inputFrameMinHeight,inputElement,inputOverlay,inputRef,@@ -189,6 +219,13 @@ export function MobileComposerInputRow({}: MobileComposerInputRowProps) {const styles = useThemedStyles(makeMobileComposerInputRowStyles);const cardLayout = cardActive === true;+ // RN 里显式 height 压过 minHeight:manual 定高(用户拖过高度)时 frameHeight 可能小于+ // inputFrameMinHeight,直接铺开会把听写停止命中区又压回不足 44pt。数值高度在这里+ // 先 clamp;拖拽中的 Animated 值无法在 JS 侧 clamp(会打断跟手),那一瞬保持动画值,+ // 松手结算成数值后重新受本 clamp 约束。+ const resolvedInputFrameHeight = typeof inputFrameHeight === 'number' && inputFrameMinHeight != null+ ? Math.max(inputFrameHeight, inputFrameMinHeight)+ : inputFrameHeight;// useCallback 稳定引用,避免每次 render 都向原生 TextInputWrapper diff 新函数 prop。// images-loading:原生刚检测到图片粘贴意图(数据还在后台读),先画占位;// images:原生侧已阻止默认粘贴,上抛进附件链路(占位在此兑现);@@ -255,7 +292,8 @@ export function MobileComposerInputRow({<Animated.Viewstyle={[styles.inputFrame,- inputFrameHeight != null && { height: inputFrameHeight },+ inputFrameMinHeight != null && { minHeight: inputFrameMinHeight },+ resolvedInputFrameHeight != null && { height: resolvedInputFrameHeight },]}>{inputElement ?? (onPasteImages && !isExpoGo ? (@@ -518,16 +556,17 @@ const makeMobileComposerInputRowStyles = (colors: ThemeColors) => ({height: MOBILE_COMPOSER_CONTROL_SIZE,width: MOBILE_COMPOSER_CONTROL_SIZE,},+ // 字号 / 行高 / 水平内边距全部走 composerTextMetrics:WebView 富文本编辑器与语音+ // 听写覆盖层用同一份度量,三边换行位置必须逐字一致(见该文件注释)。input: {backgroundColor: 'transparent',borderWidth: 0,color: colors.textPrimary,flex: 1,- fontSize: typeScale.body,- lineHeight: MOBILE_COMPOSER_INPUT_LINE_HEIGHT,+ ...COMPOSER_TEXT_STYLE,maxHeight: MOBILE_COMPOSER_INPUT_MAX_HEIGHT,minHeight: MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT,- paddingHorizontal: spacing.xs,+ paddingHorizontal: COMPOSER_TEXT_HORIZONTAL_PADDING,paddingVertical: MOBILE_COMPOSER_INPUT_VERTICAL_PADDING,textAlignVertical: 'top',},diff --git a/apps/mobile/src/session/composerRichInputHtml.ts b/apps/mobile/src/session/composerRichInputHtml.tsindex 2688f3ff98..246e2ed8dc 100644--- a/apps/mobile/src/session/composerRichInputHtml.ts+++ b/apps/mobile/src/session/composerRichInputHtml.ts@@ -6,6 +6,13 @@ import {MAX_PASTED_IMAGE_NAME_CHARS,SUPPORTED_PASTED_IMAGE_MIME_TYPES,} from '@/session/composerRichInputProtocol';+import {+ COMPOSER_SINGLE_LINE_HEIGHT,+ COMPOSER_TEXT_FONT_SIZE,+ COMPOSER_TEXT_HORIZONTAL_PADDING,+ COMPOSER_TEXT_LINE_HEIGHT,+ COMPOSER_TEXT_VERTICAL_PADDING,+} from '@/session/composerTextMetrics';export interface ComposerRichInputTheme {background: string;@@ -40,10 +47,15 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): str* { box-sizing: border-box; }html, body { margin: 0; padding: 0; background: transparent; overflow: hidden; }body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }+ /* 字号 / 行高 / 内边距来自 composerTextMetrics(与原生输入框、语音听写覆盖层同源):+ 任一处漂移都会让同一段文字在两个渲染器里换行位置不同,听写时新起的行被裁在框外。 */#editor {- color: var(--text); caret-color: var(--focus); font-size: 15px; line-height: 22px;- min-height: 28px; max-height: var(--max-height); overflow-y: auto; outline: none;- padding: 3px 0; white-space: pre-wrap; overflow-wrap: anywhere; -webkit-user-select: text;+ color: var(--text); caret-color: var(--focus);+ font-size: ${COMPOSER_TEXT_FONT_SIZE}px; line-height: ${COMPOSER_TEXT_LINE_HEIGHT}px;+ min-height: ${COMPOSER_SINGLE_LINE_HEIGHT}px; max-height: var(--max-height);+ overflow-y: auto; outline: none;+ padding: ${COMPOSER_TEXT_VERTICAL_PADDING}px ${COMPOSER_TEXT_HORIZONTAL_PADDING}px;+ white-space: pre-wrap; overflow-wrap: anywhere; -webkit-user-select: text;}#editor:empty::before { content: attr(data-placeholder); color: var(--placeholder); pointer-events: none; }.atom {@@ -190,7 +202,7 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): strwalk(root, nodes);return { version: 1, nodes };};- const reportHeight = () => post({ type: 'height', height: Math.min(config.maxHeight, Math.max(28, root.scrollHeight)) });+ const reportHeight = () => post({ type: 'height', height: Math.min(config.maxHeight, Math.max(${COMPOSER_SINGLE_LINE_HEIGHT}, root.scrollHeight)) });const notify = () => {if (applying || composing) return;const value = readDocument();diff --git a/apps/mobile/src/session/composerRichInputProtocol.ts b/apps/mobile/src/session/composerRichInputProtocol.tsindex 47b2e54053..993b963e57 100644--- a/apps/mobile/src/session/composerRichInputProtocol.ts+++ b/apps/mobile/src/session/composerRichInputProtocol.ts@@ -1,4 +1,10 @@export type ComposerWebMessage =+ /**+ * focus 只代表「编辑器现在有 DOM 焦点」,**不代表用户点了输入框**:WKWebView 在输入区+ * 展开、拿到 native 焦点后会自己恢复 DOM 焦点并派发它。用户意图类动作(如「点输入框+ * → 停止语音听写」)不能挂在这里,否则收起态点语音、输入框展开的瞬间就会误触发,把刚+ * 开始的听写掐断(2026-07 实机日志确认)。+ */| { type: 'ready' | 'focus' | 'blur' }| { type: 'height'; height: number }| { type: 'change'; document: unknown }diff --git a/apps/mobile/src/session/composerTextMetrics.ts b/apps/mobile/src/session/composerTextMetrics.tsnew file mode 100644index 0000000000..ad48cbf112--- /dev/null+++ b/apps/mobile/src/session/composerTextMetrics.ts@@ -0,0 +1,40 @@+/**+ * Composer 文本度量 —— 输入框本体与语音听写覆盖层的**唯一**来源。+ *+ * 为什么必须集中:一段草稿文字在同一个 composer 里可能由三个渲染器画出来——+ * 1. 新建会话页的原生 `TextInput`;+ * 2. 会话页的 WebView 富文本编辑器(`composerRichInputHtml` 的 CSS);+ * 3. 语音听写期间盖在上面的草稿覆盖层(`Text` + absoluteFill)。+ *+ * 输入区可视高度由 1/2 的内容高度撑起,3 只是展示层(overflow hidden)。字号、行高或+ * 水平内边距任一处不同,同一段文字的换行位置就不同:覆盖层先换行时新起的那行落在框外+ * 被裁掉(表现为「说到第二行看不到新内容,要等输入框也换行才补出来」),反向则露出空行;+ * 内边距不同还会让听写与非听写的文字左右错位。+ *+ * 2026-07 收敛前这三处分别是 14/20、15/22(CSS 字面量)、16/22,且 WebView 无水平内边距。+ * 新增消费方一律引用本文件,不要各自写档位;本文件刻意不依赖 react-native,便于 WebView+ * HTML 生成器与 node 环境单测直接 import。+ */+import { lineHeight, spacing, typeScale } from '@/theme/tokens';++/** 输入文本字号(排版阶梯 typeScale.code)。 */+export const COMPOSER_TEXT_FONT_SIZE = typeScale.code;+/**+ * 单行文字的行高(排版阶梯 lineHeight.body),**不含内边距**;+ * 也是 COMPOSER_SINGLE_LINE_HEIGHT 的基数(见下)。+ */+export const COMPOSER_TEXT_LINE_HEIGHT = lineHeight.body;+/** 输入文本左右内边距:三个渲染器必须一致,否则听写与非听写的文字左右错位。 */+export const COMPOSER_TEXT_HORIZONTAL_PADDING = spacing.xs;+/** 输入文本上下内边距(单行行高之外的呼吸)。 */+export const COMPOSER_TEXT_VERTICAL_PADDING = 3;++/** 单行输入区的可视高度 = 单行行高 + 上下内边距;原生输入框与 WebView 编辑器同源。 */+export const COMPOSER_SINGLE_LINE_HEIGHT =+ COMPOSER_TEXT_LINE_HEIGHT + (COMPOSER_TEXT_VERTICAL_PADDING * 2);++/** RN 样式片段:`...COMPOSER_TEXT_STYLE` 一次展开字号 + 行高,不给漂移留缝。 */+export const COMPOSER_TEXT_STYLE = {+ fontSize: COMPOSER_TEXT_FONT_SIZE,+ lineHeight: COMPOSER_TEXT_LINE_HEIGHT,+};