Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(mobile): 语音输入体验对齐桌面——布局守恒、录音计时胶囊、按下即录 (#730)

Dashd5eaf80e14e5
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 59063e8c16..9bf0354df0 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -259,6 +259,7 @@ import {
VoiceMicWaveCaret,
resolveMobileComposerVoiceButtonPlacement,
} from '@/session/MobileComposerInputRow';
+import { VoiceRecordingPillContent, useMobileVoiceRecordingTimer } from '@/session/VoiceRecordingPill';
import { useComposerCardTransition } from '@/session/useComposerCardTransition';
import { useComposerResize } from '@/session/useComposerResize';
import { useMobileKeyboardState } from '@/session/useMobileKeyboardState';
@@ -1611,26 +1612,56 @@ export default function SessionScreen() {
voiceState,
]);
const compactComposer = composerLayout.density === 'compact';
- const composerSendSlotIsStop = composerLayout.stop.visible && composerLayout.send.disabled && !sending;
+ // 「按下即录」的乐观反馈(对齐桌面 activeRecording = listening || longPressActive):
+ // pressIn 发起启动的同时置 pending,胶囊立刻展开计时,不等 ASR/权限链路把 state
+ // 翻到 listening——否则启动慢时按钮有一段「按了没反应」。启动完成(成功进
+ // listening / 失败报错)后由 finally 收回;成功路径收回时 listening 已为 true,
+ // 计时输入保持连续,不会闪断重置。声明在槽位 flags 之前:pending 期就要占住发送槽。
+ const [voiceStartPending, setVoiceStartPending] = useState(false);
+ // pending 的世代号:本组件会随 sessionId 复用,上一个会话的启动收尾不能把
+ // 当前会话刚展开的乐观胶囊收掉——finally 只在世代未前进时清 pending。
+ const voiceStartPendingSeqRef = useRef(0);
+ // pressIn 已起录的标记:同一次手势的松手(onPress)不能再被当作「再点一下停止」。
+ const voiceStartedOnPressInRef = useRef(false);
+ // 发送槽双语义(对齐桌面 ChatInput 的主槽判定,voice busy = listening|submitting|refining):
+ // 任务执行中且发送不可用、又没有语音在进行时,停止任务顶替发送位;语音一旦开始,
+ // 发送键回到发送位(录音期=「结束并发送」,润色期=禁用态占位),停止任务退到
+ // 语音按钮**左边**的独立槽。语音按钮由此永远是发送槽的左邻,右缘位置与是否有
+ // 草稿/是否录音/任务是否执行全部无关——录音胶囊只向左生长,「原地再点一下」
+ // 永远是停止录音,不会误停任务。
+ const composerSendSlotIsStop = composerLayout.stop.visible
+ && composerLayout.send.disabled
+ && !sending
+ && !voiceIsBusy
+ && !voiceStartPending;
// 降级 composer(未同步/离线):输入框可编辑并持续保存草稿,但发送禁用,
// 直到 currentSession 和远端连接恢复后自动恢复可发送。
const composerSendDisabled = composerLayout.send.disabled;
const composerShowInlineStop = composerLayout.stop.visible && !composerSendSlotIsStop && !sending;
const composerHasPayload = composerHasText || attachments.length > 0 || pendingUploads.length > 0 || composerQuoteCount > 0;
- const composerShowSendButton = composerLayout.send.visible && (!voiceIsListening || composerHasPayload);
- const composerFloatingVoiceButtonStyle = composerShowInlineStop && composerShowSendButton
- ? styles.composerFloatingVoiceButtonWithInlineStop
- : undefined;
+ // send.visible 在语音生命周期内恒 true(sessionOperation.ts),这里不再按
+ // voiceIsListening 二次过滤——那正是「首段转写落地瞬间发送键冒出来」的跳变源。
+ // 乐观 pending 期(state 还是 idle)同样要占住发送槽:否则空草稿按下语音时
+ // 胶囊先在 12pt 档展开,listening 一到发送键出现又整体跳到 52pt 档。
+ const composerShowSendButton = composerLayout.send.visible || voiceStartPending;
const composerVoicePlacement = voiceUiAvailable
? resolveMobileComposerVoiceButtonPlacement({
// 行尾有发送或占发送位的停止按钮时让位;附件-only(无文字)同样命中。
hasTrailingAction: composerSendSlotIsStop || composerShowSendButton,
})
: undefined;
+ // 录音计时(红点+m:ss 胶囊);pillWidth 同时驱动语音按钮与工具排占位 slot,
+ // 胶囊展开时把左邻的停止任务按钮推开,而不是盖住它。expanded 含乐观 pending
+ // (按下即展开),counting 只认真实采集(listening)——启动链路(权限弹窗等)
+ // 不计入录音时长,pending 期显示静止的 0:00。
+ const voiceRecordingTimer = useMobileVoiceRecordingTimer({
+ expanded: voiceIsListening || voiceStartPending,
+ counting: voiceIsListening,
+ });
const composerEffectiveContentHeight = composerInputContentHeight;
const voiceDraftShowsListeningPrompt = voiceIsListening && draft.length === 0;
// 状态行只承载错误信息;「正在听 / 转写中」不再占一行,对齐桌面版——
- // 录音状态由输入框内的语音按钮形态(Mic / Square / spinner)表达。
+ // 录音状态由输入框内的语音按钮形态(Mic / 红点计时胶囊 / spinner)表达。
const voiceStatusVisible = voiceUiAvailable && Boolean(voiceError);
const nativeShellLayout = useMemo(() => buildSessionNativeShellLayout({
attachmentPickerOpen: false,
@@ -1827,10 +1858,14 @@ export default function SessionScreen() {
/>
) : null}
<ComposerToolbarSpacer />
+ {/* 工具排右段顺序:[停止任务][语音占位][发送槽]。停止任务在语音左边
+ (对齐桌面),语音占位宽度随录音胶囊(红点+计时)展开,把停止任务
+ 推开——语音右缘与发送槽的邻接关系全程不变。 */}
+ {renderComposerInlineStop()}
{composerVoicePlacement?.inline || composerVoicePlacement?.floating
- ? <ComposerToolbarVoiceSlot />
+ ? <ComposerToolbarVoiceSlot width={voiceRecordingTimer.pillWidth} />
: null}
- {renderComposerTrailingActions()}
+ {renderComposerSendSlot()}
</>
);
const renderComposerInputOverlay = () => voiceIsListening ? (
@@ -1869,7 +1904,7 @@ export default function SessionScreen() {
>
{voiceDraftShowsListeningPrompt ? (
<View style={styles.voiceDraftListeningPrompt}>
- <VoiceMicWaveCaret color={colors.statusReady} testID="session.voiceMicCaret" />
+ <VoiceMicWaveCaret color={colors.textPrimary} testID="session.voiceMicCaret" />
<Text style={styles.voiceDraftListeningText}>{composerLayout.input.placeholder}</Text>
</View>
) : (
@@ -1890,7 +1925,7 @@ export default function SessionScreen() {
},
]}
>
- <VoiceMicWaveCaret color={colors.statusReady} testID="session.voiceMicCaret" />
+ <VoiceMicWaveCaret color={colors.textPrimary} testID="session.voiceMicCaret" />
</View>
</View>
)}
@@ -1968,18 +2003,19 @@ export default function SessionScreen() {
applyComposerDraft(value, queueEditingRef.current ? { persist: false } : undefined);
}, [applyComposerDraft]);
- const moveComposerCaretToEnd = useCallback(() => {
- composerInputRef.current?.setSelectionToEnd();
- }, []);
-
+ // 听写期间只滚动覆盖层跟随最新文字,**不碰隐藏编辑器的 caret**(2026-07-28):
+ // 旧实现每段转写都把选区挪到末尾,而富文本编辑器的选区操作底层是 WebView
+ // 程序化 focus,配合 keyboardDisplayRequiresUserAction={false} 会在点语音的
+ // 同时弹出软键盘。#551 之前这个 focus 表现为「听写刚开始就被掐断」(focus 即
+ // 停听写),#551 修掉掐断后它幸存为弹键盘。听写中输入框本就隐藏(覆盖层渲染
+ // 草稿),caret 无意义;落焦统一放在听写结束点(finishVoiceRecording)。
useEffect(() => {
if (!voiceIsListening) return undefined;
const frame = requestAnimationFrame(() => {
- moveComposerCaretToEnd();
voiceDraftScrollRef.current?.scrollToEnd({ animated: false });
});
return () => cancelAnimationFrame(frame);
- }, [composerInputContentHeight, composerInputVisibleHeight, draft, moveComposerCaretToEnd, voiceIsListening]);
+ }, [composerInputContentHeight, composerInputVisibleHeight, draft, voiceIsListening]);
useEffect(() => {
if (voiceIsListening && draft.length > 0) return;
@@ -3711,8 +3747,11 @@ export default function SessionScreen() {
const latestDraft = await controller.stop();
await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
setVoiceState('done');
+ // 听写结束落焦(既有行为,显式 focus 承担弹键盘语义):focus 的 web 侧
+ // 实现即 placeCaretAtEnd,caret 落在转写文字末尾。听写**进行中**禁止任何
+ // 程序化 focus(见 voiceIsListening 滚动效应的注释)。
requestAnimationFrame(() => {
- moveComposerCaretToEnd();
+ composerInputRef.current?.focus();
});
// chat-text-quote:纯引用(无转写文字、无附件)也要发出去——发送按钮在
// quote-only 时可见,漏了引用会变成「点发送只停了录音、消息没发」。
@@ -3733,7 +3772,7 @@ export default function SessionScreen() {
} finally {
voiceStopInFlightRef.current = false;
}
- }, [attachments.length, moveComposerCaretToEnd, t, voiceState]);
+ }, [attachments.length, t, voiceState]);
const openVoiceSettings = useCallback(() => {
void Linking.openSettings().catch((err) => {
@@ -3757,11 +3796,13 @@ export default function SessionScreen() {
}
}, [finishVoiceRecording, startVoiceRecording, voiceState]);
- // Speculative warm-up on touch-down of the mic button (audio session + ASR
- // connect, see mobileVoicePrewarm): both cold-start costs overlap the press
- // gesture instead of following the tap. Skipped when the tap will stop the
+ // Touch-down of the mic button = start recording (desktop pointerdown 同款,
+ // 2026-07-27 定案):按下瞬间起录,开头一个字不丢;松手 <320ms 视为「点击开始」
+ // (录音继续),≥320ms(onLongPress 成立)后松手走停止/拖发。预热(audio session
+ // + ASR connect)仍在最前,与启动重叠。Skipped when the tap will stop the
// current recording rather than start a new one.
const handleVoiceButtonPressIn = useCallback(() => {
+ voiceStartedOnPressInRef.current = false;
if (voiceIsProcessing) return;
if (voiceRecordingActiveRef.current || voiceState === 'listening') return;
if (!deviceId || !isMobileRealtimeAudioAvailable()) return;
@@ -3774,7 +3815,19 @@ export default function SessionScreen() {
refreshAccessToken: () => auth.refreshAccessToken(),
apiFetch: auth.apiFetch,
});
- }, [deviceId, voiceIsProcessing, voiceState]);
+ // 启动已在途/停止在途时不重复发起,也不把这次按下标成「已起录」——
+ // 否则松手的 onPress 会被吞掉,用户失去 toggle 能力。
+ if (voiceStartupInFlightRef.current || voiceStopInFlightRef.current) return;
+ voiceStartedOnPressInRef.current = true;
+ const pendingSeq = ++voiceStartPendingSeqRef.current;
+ setVoiceStartPending(true);
+ void startVoiceRecording()
+ .catch(() => undefined)
+ .finally(() => {
+ // 只收自己世代的 pending:切会话后旧启动的收尾不能塌掉新录音的胶囊。
+ if (voiceStartPendingSeqRef.current === pendingSeq) setVoiceStartPending(false);
+ });
+ }, [deviceId, startVoiceRecording, voiceIsProcessing, voiceState]);
const renderComposerVoiceButton = (buttonStyle?: StyleProp<ViewStyle>) => (
<RouteActionButton
@@ -3790,6 +3843,8 @@ export default function SessionScreen() {
voiceLongPressActiveRef.current = true;
voiceSuppressNextPressRef.current = true;
measureSendButtonTarget();
+ // 录音已在 pressIn 起了;这里只兜 pressIn 守卫路径没起成的边缘
+ // (startVoiceRecording 自带重入守卫,重复调用无害)。
if (!voiceRecordingActiveRef.current) void startVoiceRecording();
}}
onPress={() => {
@@ -3797,10 +3852,19 @@ export default function SessionScreen() {
voiceSuppressNextPressRef.current = false;
return;
}
+ if (voiceStartedOnPressInRef.current) {
+ // 本次按下已在 pressIn 起录:这次松手属于同一手势,不再当作
+ // 「再点一下停止」;下一次完整点击才会 toggle 停止。
+ voiceStartedOnPressInRef.current = false;
+ return;
+ }
toggleVoiceRecording();
}}
onPressOut={(event) => {
if (!voiceLongPressActiveRef.current) return;
+ // 长按路径在此收尾,本次按下的生命周期结束;标记同步清掉,
+ // 手势取消(onTouchCancel)不再重复处理。
+ voiceStartedOnPressInRef.current = false;
const shouldSend = updateVoiceReleaseToSendTarget(event);
voiceLongPressActiveRef.current = false;
voiceSuppressNextPressRef.current = true;
@@ -3812,19 +3876,30 @@ export default function SessionScreen() {
void finishVoiceRecording({ sendAfterTranscribe: shouldSend });
}}
onResponderMove={updateVoiceReleaseToSendTarget}
+ onTouchCancel={() => {
+ // 手势被系统/滚动打断(responder termination):撤销这次按下误触发的
+ // 录音——用户本意是滚动列表,不能留下一个还在采集的麦克风(review P1)。
+ // 正常松手(含拖出按钮后松开)不走这里,对齐桌面「pointercancel 才撤销」。
+ if (!voiceStartedOnPressInRef.current) return;
+ voiceStartedOnPressInRef.current = false;
+ cancelVoiceForAppBackground();
+ }}
style={[
styles.composerInlineToolButton,
buttonStyle,
- composerLayout.voice.active && styles.composerToolButtonPrimary,
+ // 胶囊底色跟随计时内容(含 pressIn 乐观 pending 期),不只 listening——
+ // 否则按下瞬间胶囊已展开、底色却要等 ASR 连上才变,闪一次半成品态。
+ voiceRecordingTimer.label !== null && styles.composerToolButtonPrimary,
+ voiceRecordingTimer.label !== null && { width: voiceRecordingTimer.pillWidth },
]}
testID="session.voiceButton"
>
{voiceIsProcessing ? (
<ActivityIndicator color={colors.textSecondary} size="small" />
- ) : voiceIsListening ? (
- // 录音停止:红色描边方块(对齐桌面 activeRecording 的 --settings-badge-error),
- // 与「停止任务」的中性色实心方块区分开。
- <Square color={colors.statusRecording} size={iconSize.sm} strokeWidth={iconStroke.regular} />
+ ) : voiceRecordingTimer.label !== null ? (
+ // 录音中:胶囊展开为脉冲红点 + 计时(对齐桌面 activeRecording 形态),
+ // 点胶囊任意位置停止录音;右缘锚定不动,只向左生长。
+ <VoiceRecordingPillContent label={voiceRecordingTimer.label} testID="session.voiceRecordingPill" />
) : (
<Mic color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
)}
@@ -4784,63 +4859,46 @@ export default function SessionScreen() {
/>
) : null);
- const renderComposerTrailingActions = () => (
+ // 停止任务按钮(实心中性方块)。两处使用:语音/发送左边的独立槽(inline)、
+ // 发送位顶替(sendSlotIsStop);同一颗按钮的两个宿主位置,样式与行为一致。
+ const renderComposerStopButton = () => (
+ <RouteActionButton
+ accessibilityLabel={t('session.screen.stopSession')}
+ accessibilityHint={composerLayout.stop.disabledReason ?? undefined}
+ disabled={composerLayout.stop.disabled}
+ hitSlop={COMPOSER_CONTROL_HIT_SLOP}
+ onPress={stopSession}
+ pressedStyle={styles.sendButtonPressed}
+ style={[
+ styles.sendButton,
+ composerLayout.stop.disabled && styles.sendButtonInactive,
+ ]}
+ testID="session.stopButton"
+ >
+ {stopPending ? (
+ <ActivityIndicator color={composerLayout.stop.disabled ? colors.textSecondary : colors.ctaText} size="small" />
+ ) : (
+ <Square
+ color={composerLayout.stop.disabled ? colors.textSecondary : colors.ctaText}
+ // 停止钮实心 Square:10px 填充块语义(非阶梯图标),零描边即语义本身
+ // (designTokenDiscipline ALLOWLIST 登记豁免)。
+ size={10}
+ strokeWidth={0}
+ fill={composerLayout.stop.disabled ? colors.textSecondary : colors.ctaText}
+ />
+ )}
+ </RouteActionButton>
+ );
+
+ // 停止任务次槽:渲染在语音按钮**左边**(对齐桌面 2026-07-25 定案),不夹在
+ // 语音与发送之间——右对齐按钮组里语音永远是发送槽的左邻,录音胶囊只向左
+ // 生长,「原地再点一下」永远是停止录音,不会误停任务。
+ const renderComposerInlineStop = () => composerShowInlineStop ? renderComposerStopButton() : null;
+
+ const renderComposerSendSlot = () => (
<>
- {composerShowInlineStop ? (
- <RouteActionButton
- accessibilityLabel={t('session.screen.stopSession')}
- accessibilityHint={composerLayout.stop.disabledReason ?? undefined}
- disabled={composerLayout.stop.disabled}
- hitSlop={COMPOSER_CONTROL_HIT_SLOP}
- onPress={stopSession}
- pressedStyle={styles.sendButtonPressed}
- style={[
- styles.sendButton,
- composerLayout.stop.disabled && styles.sendButtonInactive,
- ]}
- testID="session.stopButton"
- >
- {stopPending ? (
- <ActivityIndicator color={composerLayout.stop.disabled ? colors.textSecondary : colors.ctaText} size="small" />
- ) : (
- <Square
- color={composerLayout.stop.disabled ? colors.textSecondary : colors.ctaText}
- // 停止钮实心 Square:10px 填充块语义(非阶梯图标),零描边即语义本身
- // (designTokenDiscipline ALLOWLIST 登记豁免)。
- size={10}
- strokeWidth={0}
- fill={composerLayout.stop.disabled ? colors.textSecondary : colors.ctaText}
- />
- )}
- </RouteActionButton>
- ) : null}
{composerSendSlotIsStop ? (
- <RouteActionButton
- accessibilityLabel={t('session.screen.stopSession')}
- accessibilityHint={composerLayout.stop.disabledReason ?? undefined}
- disabled={composerLayout.stop.disabled}
- hitSlop={COMPOSER_CONTROL_HIT_SLOP}
- onPress={stopSession}
- pressedStyle={styles.sendButtonPressed}
- style={[
- styles.sendButton,
- composerLayout.stop.disabled && styles.sendButtonInactive,
- ]}
- testID="session.stopButton"
- >
- {stopPending ? (
- <ActivityIndicator color={composerLayout.stop.disabled ? colors.textSecondary : colors.ctaText} size="small" />
- ) : (
- <Square
- color={composerLayout.stop.disabled ? colors.textSecondary : colors.ctaText}
- // 停止钮实心 Square:10px 填充块语义(非阶梯图标),零描边即语义本身
- // (designTokenDiscipline ALLOWLIST 登记豁免)。
- size={10}
- strokeWidth={0}
- fill={composerLayout.stop.disabled ? colors.textSecondary : colors.ctaText}
- />
- )}
- </RouteActionButton>
+ renderComposerStopButton()
) : composerShowSendButton ? (
<RouteActionButton
ref={sendButtonRef}
@@ -4871,6 +4929,19 @@ export default function SessionScreen() {
</>
);
+ // 简洁态(非卡片)输入行行尾的按钮组:[停止任务][语音占位][发送槽]。
+ // 语音按钮本体是 absolute 锚点浮标(右缘 52pt 档),占位 slot 在 flex 流里
+ // 为它留出与发送槽相邻的位置,停止任务被推到占位左边,不落进语音的命中带。
+ const renderComposerTrailingActions = () => (
+ <>
+ {renderComposerInlineStop()}
+ {composerShowInlineStop && composerVoicePlacement?.floating
+ ? <ComposerToolbarVoiceSlot width={voiceRecordingTimer.pillWidth} />
+ : null}
+ {renderComposerSendSlot()}
+ </>
+ );
+
const resumeQueue = () => {
void runQueueAction(() => maker.input.resume(sessionId));
};
@@ -7146,7 +7217,6 @@ export default function SessionScreen() {
compact={compactComposer && !composerCardActive}
editable={!composerLayout.input.disabled}
floatingVoiceButton={voiceUiAvailable ? renderComposerVoiceButton : undefined}
- floatingVoiceButtonStyle={composerFloatingVoiceButtonStyle}
cursorColor={colors.inputCaret}
inputFrameHeight={composerResize.frameHeight}
// 听写期间把输入区撑到 44pt 触控目标:命中层盖在 inputFrame 上,
@@ -7708,6 +7778,8 @@ interface RouteActionButtonProps {
onPressIn?: PressableProps['onPressIn'];
onPressOut?: PressableProps['onPressOut'];
onResponderMove?: PressableProps['onResponderMove'];
+ /** responder 被系统/滚动终止时的回调(正常松手不触发);语音按钮用它撤销按下即录。 */
+ onTouchCancel?: PressableProps['onTouchCancel'];
pressedStyle?: StyleProp<ViewStyle>;
style?: StyleProp<ViewStyle>;
testID?: string;
@@ -7729,6 +7801,7 @@ const RouteActionButton = forwardRef<View, RouteActionButtonProps>(function Rout
onPressIn,
onPressOut,
onResponderMove,
+ onTouchCancel,
pressedStyle,
style,
testID,
@@ -7757,6 +7830,7 @@ const RouteActionButton = forwardRef<View, RouteActionButtonProps>(function Rout
onPressIn={interactionDisabled ? undefined : onPressIn}
onPressOut={interactionDisabled ? undefined : onPressOut}
onResponderMove={interactionDisabled ? undefined : onResponderMove}
+ onTouchCancel={interactionDisabled ? undefined : onTouchCancel}
style={({ pressed }) => [
style,
pressed && resolvedPressedStyle,
@@ -8361,9 +8435,6 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
height: 34,
width: 34,
},
- composerFloatingVoiceButtonWithInlineStop: {
- right: spacing.md + (MOBILE_COMPOSER_CONTROL_SIZE * 2) + (MOBILE_COMPOSER_TOOL_GAP * 2),
- },
composerToolButtonActive: {
backgroundColor: colors.surfaceChip,
borderColor: colors.borderStrong,
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index d74f0a1214..fbab0ecdcf 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -39,7 +39,6 @@ import {
Plus,
Scan,
Settings,
- Square,
Target,
X,
Zap,
@@ -184,6 +183,7 @@ import {
VoiceMicWaveCaret,
resolveMobileComposerVoiceButtonPlacement,
} from '@/session/MobileComposerInputRow';
+import { VoiceRecordingPillContent, useMobileVoiceRecordingTimer } from '@/session/VoiceRecordingPill';
import { useComposerCardTransition } from '@/session/useComposerCardTransition';
import { useComposerResize } from '@/session/useComposerResize';
import { useMobileKeyboardState } from '@/session/useMobileKeyboardState';
@@ -757,7 +757,23 @@ export default function NewRemoteSessionScreen() {
[draft, draftContent],
);
const composerHasMessage = draft.firstMessage.trim().length > 0;
- const composerShowCreateButton = composerHasMessage || attachments.length > 0 || pendingUploads.length > 0;
+ // 「按下即录」的乐观反馈(与会话页/桌面同款,详见 [sessionId].tsx 同名状态注释)。
+ // 声明在 composerShowCreateButton 之前:pending 期就要占住创建槽。
+ const [voiceStartPending, setVoiceStartPending] = useState(false);
+ const voiceStartPendingSeqRef = useRef(0);
+ const voiceStartedOnPressInRef = useRef(false);
+ // 语音生命周期内创建按钮常驻(与会话页发送槽同理,对齐桌面):录音中点创建
+ // = 结束录音并用转写创建(create() 已有 listening 分支);否则首段转写落地的
+ // 瞬间按钮冒出来,右对齐工具排会把语音胶囊整格推左。乐观 pending 期同理占位,
+ // 避免胶囊先在 12pt 档展开、listening 一到又跳 52pt 档。voiceIsBusy 在下方
+ // 声明,这里直接展开同一表达式,避免声明顺序对调。
+ const composerShowCreateButton = composerHasMessage
+ || attachments.length > 0
+ || pendingUploads.length > 0
+ || voiceStartPending
+ || voiceState === 'listening'
+ || voiceState === 'submitting'
+ || voiceState === 'refining';
const voiceUiAvailable = shouldShowMobileVoiceUi(Platform.OS);
const voiceIsListening = voiceState === 'listening';
const voiceIsProcessing = voiceState === 'submitting' || voiceState === 'refining';
@@ -766,12 +782,21 @@ export default function NewRemoteSessionScreen() {
const deviceSelectorDisabled = creating || voiceIsProcessing || !deviceHasChoices;
// 上传中不再挡创建:附件走乐观管线(pendingUploads),create() 内部会 await 全部
// 在途上传落定后再组首条消息,抢点创建不会丢图(#589 的 attachmentBusy 门由此取代)。
- const canCreate = !createValidation && !creating && !voiceIsProcessing;
+ // listening 时豁免「缺正文/附件」校验:此刻点创建 = 结束录音并用转写创建
+ // (create() 的 listening 分支),最终转写在 create() 内部重新校验;不豁免的话
+ // 空草稿录音期间创建按钮永远按不动,「点创建停录并创建」形同虚设(review P1)。
+ const canCreate = (!createValidation || voiceIsListening) && !creating && !voiceIsProcessing;
const voiceIsBusy = voiceIsListening || voiceIsProcessing;
+ // 录音计时(红点+m:ss 胶囊,与会话页/桌面同形态);pillWidth 同步驱动工具排占位。
+ // counting 只认真实采集,启动链路(权限弹窗等)不计入时长,pending 期显示 0:00。
+ const voiceRecordingTimer = useMobileVoiceRecordingTimer({
+ expanded: voiceIsListening || voiceStartPending,
+ counting: voiceIsListening,
+ });
// 手机语音只保留官方托管路径,错误引导仅剩系统麦克风权限一条。
const canOpenVoiceSettings = isMobileVoiceMicPermissionError(voiceError);
// 状态行只承载错误信息;「正在听 / 转写中」不再占一行,对齐桌面版——
- // 录音状态由输入框内的语音按钮形态(Mic / Square / spinner)表达。
+ // 录音状态由输入框内的语音按钮形态(Mic / 红点计时胶囊 / spinner)表达。
const voiceStatusVisible = voiceUiAvailable && Boolean(voiceError);
const composerVoicePlacement = voiceUiAvailable
? resolveMobileComposerVoiceButtonPlacement({
@@ -1657,11 +1682,12 @@ export default function NewRemoteSessionScreen() {
}
}, [finishVoiceRecording, startVoiceRecording, voiceState]);
- // Speculative warm-up on touch-down of the mic button (audio session + ASR
- // connect, see mobileVoicePrewarm): both cold-start costs overlap the press
- // gesture instead of following the tap. Skipped when the tap will stop the
- // current recording rather than start a new one.
+ // Touch-down of the mic button = start recording (desktop pointerdown 同款,
+ // 2026-07-27 定案):按下瞬间起录,开头一个字不丢;松手属于同一手势,由
+ // voiceStartedOnPressInRef 吞掉 onPress 的 toggle。预热仍在最前,与启动重叠。
+ // Skipped when the tap will stop the current recording rather than start a new one.
const handleVoiceButtonPressIn = useCallback(() => {
+ voiceStartedOnPressInRef.current = false;
if (creating || voiceIsProcessing) return;
if (voiceRecordingActiveRef.current || voiceState === 'listening') return;
if (!selectedDeviceId || !isMobileRealtimeAudioAvailable()) return;
@@ -1674,7 +1700,18 @@ export default function NewRemoteSessionScreen() {
refreshAccessToken: () => auth.refreshAccessToken(),
apiFetch: auth.apiFetch,
});
- }, [creating, selectedDeviceId, voiceIsProcessing, voiceState]);
+ // 启动已在途/停止在途时不重复发起,也不把这次按下标成「已起录」。
+ if (voiceStartupInFlightRef.current || voiceStopInFlightRef.current) return;
+ voiceStartedOnPressInRef.current = true;
+ const pendingSeq = ++voiceStartPendingSeqRef.current;
+ setVoiceStartPending(true);
+ void startVoiceRecording()
+ .catch(() => undefined)
+ .finally(() => {
+ // 只收自己世代的 pending(与会话页同款守卫)。
+ if (voiceStartPendingSeqRef.current === pendingSeq) setVoiceStartPending(false);
+ });
+ }, [creating, selectedDeviceId, startVoiceRecording, voiceIsProcessing, voiceState]);
useEffect(() => {
return () => {
@@ -1807,7 +1844,7 @@ export default function NewRemoteSessionScreen() {
</Pressable>
<ComposerToolbarSpacer />
{composerVoicePlacement?.inline || composerVoicePlacement?.floating
- ? <ComposerToolbarVoiceSlot />
+ ? <ComposerToolbarVoiceSlot width={voiceRecordingTimer.pillWidth} />
: null}
{composerShowCreateButton ? renderCreateButton() : null}
</>
@@ -1833,7 +1870,7 @@ export default function NewRemoteSessionScreen() {
>
{voiceDraftShowsListeningPrompt ? (
<View style={styles.voiceDraftListeningPrompt}>
- <VoiceMicWaveCaret color={colors.statusReady} testID="newSession.voiceMicCaret" />
+ <VoiceMicWaveCaret color={colors.textPrimary} testID="newSession.voiceMicCaret" />
<Text style={styles.voiceDraftListeningText}>{composerListeningPlaceholder}</Text>
</View>
) : (
@@ -1854,7 +1891,7 @@ export default function NewRemoteSessionScreen() {
},
]}
>
- <VoiceMicWaveCaret color={colors.statusReady} testID="newSession.voiceMicCaret" />
+ <VoiceMicWaveCaret color={colors.textPrimary} testID="newSession.voiceMicCaret" />
</View>
</View>
)}
@@ -1868,12 +1905,28 @@ export default function NewRemoteSessionScreen() {
accessibilityState={{ busy: voiceIsProcessing || undefined, disabled: creating || undefined }}
disabled={creating || voiceIsProcessing}
hitSlop={10}
- onPress={toggleVoiceRecording}
+ onPress={() => {
+ if (voiceStartedOnPressInRef.current) {
+ // 本次按下已在 pressIn 起录:松手不当作「再点一下停止」。
+ voiceStartedOnPressInRef.current = false;
+ return;
+ }
+ toggleVoiceRecording();
+ }}
onPressIn={handleVoiceButtonPressIn}
+ onTouchCancel={() => {
+ // 手势被系统/滚动打断:撤销这次按下误触发的录音(与会话页同语义,
+ // 正常松手不触发;cancelVoiceForDeviceSwitch 会作废在途启动并释放音频)。
+ if (!voiceStartedOnPressInRef.current) return;
+ voiceStartedOnPressInRef.current = false;
+ cancelVoiceForDeviceSwitch();
+ }}
style={({ pressed }) => [
styles.composerIconButton,
buttonStyle,
- voiceIsListening && styles.composerIconButtonActive,
+ // 胶囊底色跟随计时内容(含 pressIn 乐观 pending 期),不只 listening。
+ voiceRecordingTimer.label !== null && styles.composerIconButtonActive,
+ voiceRecordingTimer.label !== null && { width: voiceRecordingTimer.pillWidth },
(creating || voiceIsProcessing) && styles.disabled,
pressed && styles.pressed,
]}
@@ -1881,10 +1934,9 @@ export default function NewRemoteSessionScreen() {
>
{voiceIsProcessing ? (
<ActivityIndicator color={colors.textSecondary} size="small" />
- ) : voiceIsListening ? (
- // 录音停止:红色描边方块(对齐桌面 activeRecording 的 --settings-badge-error),
- // 与「停止任务」的中性色实心方块区分开。
- <Square color={colors.statusRecording} size={iconSize.sm} strokeWidth={iconStroke.regular} />
+ ) : voiceRecordingTimer.label !== null ? (
+ // 录音中:胶囊展开为脉冲红点 + 计时(对齐桌面/会话页),点胶囊任意位置停止。
+ <VoiceRecordingPillContent label={voiceRecordingTimer.label} testID="newSession.voiceRecordingPill" />
) : (
<Mic color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
)}
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index b1af62ee6d..fdb98e6f11 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -860,10 +860,17 @@ describe('new session composer surface', () => {
expect(newSource).not.toContain('testID="newSession.permissionButton"');
expect(newSource).not.toContain('testID="newSession.permissionPanel"');
expect(newSource).not.toContain('testID="newSession.modelPickerPanel"');
- expect(newSource).toContain('const composerShowCreateButton = composerHasMessage || attachments.length > 0 || pendingUploads.length > 0;');
- expect(newSource).toContain('const canCreate = !createValidation && !creating && !voiceIsProcessing;');
+ // 语音生命周期内创建按钮常驻(2026-07-25 对齐桌面):录音中点创建=结束录音并
+ // 用转写创建;否则首段转写落地瞬间按钮冒出来会把语音胶囊整格推左。
+ expect(newSource).toContain("|| voiceStartPending\n || voiceState === 'listening'\n || voiceState === 'submitting'\n || voiceState === 'refining';");
+ // listening 时豁免缺正文校验:点创建 = 停录并用最终转写创建(review P1)。
+ expect(newSource).toContain('const canCreate = (!createValidation || voiceIsListening) && !creating && !voiceIsProcessing;');
+ expect(newSource).toContain('const composerShowCreateButton = composerHasMessage');
expect(newSource).toContain('const deviceSelectorDisabled = creating || voiceIsProcessing || !deviceHasChoices;');
- expect(voiceButtonSource).toContain('onPress={toggleVoiceRecording}');
+ // 按下即录(pressIn 起录):同一手势的松手由 voiceStartedOnPressInRef 吞掉,
+ // 不再直接把 onPress 绑到 toggle。
+ expect(voiceButtonSource).toContain('voiceStartedOnPressInRef.current = false;');
+ expect(voiceButtonSource).toContain('toggleVoiceRecording();');
expect(voiceButtonSource).toContain('disabled={creating || voiceIsProcessing}');
expect(newSource).toContain('const startVoiceRecording = useCallback(async () => {');
expect(newSource).toContain('const voiceStartupInFlightRef = useRef(false);');
@@ -921,7 +928,8 @@ describe('new session composer surface', () => {
expect(newSource).toContain("import { buildSessionComposerLayout } from '@/session/sessionComposerLayout';");
expect(newSource).toContain('const composerListeningPlaceholder = buildSessionComposerLayout({');
expect(newSource).toContain('<Text style={styles.voiceDraftListeningText}>{composerListeningPlaceholder}</Text>');
- expect(newSource).toContain('<VoiceMicWaveCaret color={colors.statusReady} testID="newSession.voiceMicCaret" />');
+ // 听写 mic 波形 caret 用正文色(对齐桌面 --chat-input-text,2026-07-28 用户定案),不用 statusReady 蓝绿。
+ expect(newSource).toContain('<VoiceMicWaveCaret color={colors.textPrimary} testID="newSession.voiceMicCaret" />');
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 });');
diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index 2c373009cf..a2a7e69ab1 100644
--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
@@ -21,7 +21,7 @@ describe('mobile session composer desktop-first surface', () => {
const composerInputEnd = source.indexOf('/>', source.indexOf('value={draft}', composerInputStart)) + 2;
const composerInputSource = source.slice(composerInputStart, composerInputEnd);
const attachmentButtonStart = source.indexOf('const renderComposerAttachmentButton = () => (');
- const attachmentButtonEnd = source.indexOf('const renderComposerTrailingActions = () => (', attachmentButtonStart);
+ const attachmentButtonEnd = source.indexOf('const renderComposerStopButton = () => (', attachmentButtonStart);
const attachmentButtonSource = source.slice(attachmentButtonStart, attachmentButtonEnd);
const trailingActionsStart = attachmentButtonEnd;
const trailingActionsEnd = source.indexOf('const resumeQueue = () => {', trailingActionsStart);
@@ -30,7 +30,6 @@ describe('mobile session composer desktop-first surface', () => {
const voiceButtonEnd = source.indexOf('const removeRemoteFileAttachment = useCallback', voiceButtonStart);
const voiceButtonSource = source.slice(voiceButtonStart, voiceButtonEnd);
const floatingVoiceIndex = composerInputSource.indexOf('floatingVoiceButton={voiceUiAvailable ? renderComposerVoiceButton : undefined}');
- const floatingVoiceStyleIndex = composerInputSource.indexOf('floatingVoiceButtonStyle={composerFloatingVoiceButtonStyle}');
const sendIndex = composerInputSource.indexOf('trailing={composerCardActive ? null : renderComposerTrailingActions()}');
const composerSurfaceStart = source.indexOf('composerSurface: {');
// composerOverlayPanel 已随「模型下拉改 ModelPickerSheet 浮窗」删除,锚到下一个样式键。
@@ -287,7 +286,8 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('const composerHasText = draft.trim().length > 0;');
expect(source).toContain('const composerQuoteCount = composerDocumentQuotes(composerDocument).length;');
expect(source).toContain('const composerHasPayload = composerHasText || attachments.length > 0 || pendingUploads.length > 0 || composerQuoteCount > 0;');
- expect(source).toContain('const composerShowSendButton = composerLayout.send.visible && (!voiceIsListening || composerHasPayload);');
+ 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('if (options.sendAfterTranscribe && (composerDocumentHasContent(latestDocument) || attachments.length > 0))');
@@ -300,10 +300,12 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('const composerVoicePlacement = voiceUiAvailable');
expect(source).toContain('hasTrailingAction: composerSendSlotIsStop || composerShowSendButton');
expect(source).toContain('const renderComposerVoiceButton = (buttonStyle?: StyleProp<ViewStyle>) => (');
- // 录音状态由语音按钮形态表达(Mic / Square / spinner),状态行只承载错误。
+ // 录音状态由语音按钮形态表达(Mic / 红点计时胶囊 / spinner),状态行只承载错误。
expect(source).toContain('const voiceStatusVisible = voiceUiAvailable && Boolean(voiceError);');
- expect(voiceButtonSource).toContain(') : voiceIsListening ? (');
- expect(voiceButtonSource).toContain('<Square');
+ expect(voiceButtonSource).toContain(') : voiceRecordingTimer.label !== null ? (');
+ expect(voiceButtonSource).toContain('<VoiceRecordingPillContent');
+ // 录音中语音按钮展开成红点+计时胶囊,右缘锚定、只向左生长;旧的红框 Square 形态不再使用。
+ expect(voiceButtonSource).not.toContain('<Square');
expect(voiceStatusIndex).toBeGreaterThan(-1);
expect(composerScrollIndex).toBeGreaterThan(-1);
expect(voiceStatusIndex).toBeLessThan(composerScrollIndex);
@@ -316,7 +318,11 @@ describe('mobile session composer desktop-first surface', () => {
expect(sharedSource).toContain('ref={inputRef as never}');
expect(source).toContain('ref={voiceDraftScrollRef}');
expect(source).toContain('contentContainerStyle={styles.voiceDraftOverlayContent}');
- expect(source).toContain('composerInputRef.current?.setSelectionToEnd();');
+ // 听写期间禁止碰隐藏编辑器的 caret(2026-07-28):setSelectionToEnd 底层是
+ // focusEditor,WebView 程序化 focus + keyboardDisplayRequiresUserAction=false
+ // 会在点语音的同时弹出软键盘。听写文字由覆盖层渲染,caret 只在用户点输入框
+ // (停止听写并有意打字)时由 WebKit 按触点放置。
+ expect(source).not.toContain('setSelectionToEnd');
expect(source).toContain('voiceDraftScrollRef.current?.scrollToEnd({ animated: false });');
expect(source).toContain('caretHidden={voiceIsListening}');
expect(source).toContain('const handleComposerInputPressIn = useCallback(() => {');
@@ -400,7 +406,7 @@ describe('mobile session composer desktop-first surface', () => {
);
expect(finishVoiceSource).toContain('voiceStopInFlightRef.current = false;');
expect(composerInputSource).toContain('floatingVoiceButton={voiceUiAvailable ? renderComposerVoiceButton : undefined}');
- expect(composerInputSource).toContain('floatingVoiceButtonStyle={composerFloatingVoiceButtonStyle}');
+ expect(composerInputSource).not.toContain('floatingVoiceButtonStyle=');
expect(composerInputSource).toContain('voicePlacement={composerVoicePlacement}');
expect(sharedSource).toContain('voicePlacement?.inline || voicePlacement?.floating');
expect(sharedSource).toContain('styles.voiceButtonAnchor,');
@@ -409,16 +415,33 @@ describe('mobile session composer desktop-first surface', () => {
// 录音中语音按钮以「红色停止方块」可见,禁止任何 opacity:0 隐藏样式回归
// (旧 gestureAnchor 设计曾把听写中的按钮隐藏,会让停止录音无可见控件)。
expect(source).not.toContain('composerInlineToolButtonGestureAnchor');
- expect(source).toContain('const composerFloatingVoiceButtonStyle = composerShowInlineStop && composerShowSendButton');
- expect(source).toContain('styles.composerFloatingVoiceButtonWithInlineStop');
- expect(source).toContain('composerFloatingVoiceButtonWithInlineStop: {');
- expect(source).toContain('right: spacing.md + (MOBILE_COMPOSER_CONTROL_SIZE * 2) + (MOBILE_COMPOSER_TOOL_GAP * 2)');
+ // 语音锚点只剩两档(12 / 52):停止任务在语音左边后,第三档(92)已删除。
+ // 若回归三档,录音期间首段转写落地会让语音按钮整格横跳,原位正好变成停止任务。
+ expect(source).not.toContain('composerFloatingVoiceButtonWithInlineStop');
+ expect(source).not.toContain('composerFloatingVoiceButtonStyle');
+ // 槽位顺序不变量(对齐桌面 2026-07-25 定案):停止任务 → 语音占位 → 发送槽。
+ const toolbarStart = source.indexOf('const renderComposerToolbar = () => (');
+ const toolbarEnd = source.indexOf('const renderComposerInputOverlay', toolbarStart);
+ const toolbarSource = source.slice(toolbarStart, toolbarEnd);
+ const toolbarInlineStopIndex = toolbarSource.indexOf('{renderComposerInlineStop()}');
+ const toolbarVoiceSlotIndex = toolbarSource.indexOf('<ComposerToolbarVoiceSlot width={voiceRecordingTimer.pillWidth} />');
+ const toolbarSendSlotIndex = toolbarSource.indexOf('{renderComposerSendSlot()}');
+ expect(toolbarInlineStopIndex).toBeGreaterThan(-1);
+ expect(toolbarVoiceSlotIndex).toBeGreaterThan(toolbarInlineStopIndex);
+ expect(toolbarSendSlotIndex).toBeGreaterThan(toolbarVoiceSlotIndex);
+ const trailingFragmentStart = source.indexOf('const renderComposerTrailingActions = () => (');
+ const trailingFragmentEnd = source.indexOf('const resumeQueue = () => {', trailingFragmentStart);
+ const trailingFragmentSource = source.slice(trailingFragmentStart, trailingFragmentEnd);
+ const trailingInlineStopIndex = trailingFragmentSource.indexOf('{renderComposerInlineStop()}');
+ const trailingVoiceSlotIndex = trailingFragmentSource.indexOf('<ComposerToolbarVoiceSlot width={voiceRecordingTimer.pillWidth} />');
+ const trailingSendSlotIndex = trailingFragmentSource.indexOf('{renderComposerSendSlot()}');
+ expect(trailingInlineStopIndex).toBeGreaterThan(-1);
+ expect(trailingVoiceSlotIndex).toBeGreaterThan(trailingInlineStopIndex);
+ expect(trailingSendSlotIndex).toBeGreaterThan(trailingVoiceSlotIndex);
expect(voiceButtonSource).toContain('buttonStyle');
expect(floatingVoiceIndex).toBeGreaterThan(-1);
- expect(floatingVoiceStyleIndex).toBeGreaterThan(-1);
expect(sendIndex).toBeGreaterThan(-1);
expect(floatingVoiceIndex).toBeLessThan(sendIndex);
- expect(floatingVoiceStyleIndex).toBeLessThan(sendIndex);
expect(inlineButtonStyle).toContain('height: 34');
expect(inlineButtonStyle).toContain('width: 34');
expect(inlineButtonStyle).not.toContain('height: 36');
@@ -541,7 +564,7 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).not.toContain('<Text style={styles.voiceCancelText}>设置</Text>');
});
- it('projects mobile voice feedback into the composer draft without adding a recording timer', () => {
+ it('projects mobile voice feedback into the composer draft with the recording timer pill', () => {
const source = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
const sharedSource = readTextLf(resolve(process.cwd(), 'src/session/MobileComposerInputRow.tsx'), 'utf8');
const voiceStart = source.indexOf('const startVoiceRecording = useCallback(async () => {');
@@ -586,6 +609,21 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('testID="session.voiceStatus"');
expect(source).not.toContain('mobileVoiceStateLabel(voiceState)');
expect(source).toContain('const canOpenVoiceSettings = isMobileVoiceMicPermissionError(voiceError);');
+ // 录音计时胶囊(红点 + m:ss,2026-07-25 用户定案对齐桌面)走共享 VoiceRecordingPill;
+ // 计时/宽度状态集中在 useMobileVoiceRecordingTimer,页面不得再自造 duration 状态。
+ expect(source).toContain("import { VoiceRecordingPillContent, useMobileVoiceRecordingTimer } from '@/session/VoiceRecordingPill';");
+ // 计时输入含 pressIn 乐观 pending(按下即录的即时反馈,对齐桌面 activeRecording)。
+ // expanded 含乐观 pending(按下即展开),counting 只认真实采集——启动链路
+ // (权限弹窗等)不计入录音时长(review P1)。
+ expect(source).toContain('expanded: voiceIsListening || voiceStartPending,');
+ expect(source).toContain('counting: voiceIsListening,');
+ expect(source).toContain('const voiceStartedOnPressInRef = useRef(false);');
+ // pending 世代守卫:切会话后旧启动收尾不得塌掉新录音的乐观胶囊(review P1)。
+ expect(source).toContain('if (voiceStartPendingSeqRef.current === pendingSeq) setVoiceStartPending(false);');
+ // 手势被系统/滚动打断时撤销按下即录(review P1)。
+ expect(source).toContain('cancelVoiceForAppBackground();');
+ expect(source).toContain('testID="session.voiceRecordingPill"');
+ expect(source).toContain('{ width: voiceRecordingTimer.pillWidth }');
expect(source).not.toContain('voiceDuration');
expect(source).not.toContain('recordingDuration');
expect(source).not.toContain('formatVoiceDuration');
diff --git a/apps/mobile/src/__tests__/sessionComposerLayout.test.ts b/apps/mobile/src/__tests__/sessionComposerLayout.test.ts
index 5934ebaf63..44a081e562 100644
--- a/apps/mobile/src/__tests__/sessionComposerLayout.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerLayout.test.ts
@@ -177,8 +177,10 @@ describe('sessionComposerLayout', () => {
expect(layout.statusText).toBe('正在听');
});
- it('keeps the composer editable while listening and waits for text before showing send', () => {
- const layout = buildSessionComposerLayout({
+ it('keeps the send slot present through the whole voice lifecycle', () => {
+ // 语音生命周期内发送槽常驻(对齐桌面主槽永远占位,2026-07-25 定案):
+ // listening 即使草稿空也可按(结束录音并发送),润色期禁用占位,布局不塌。
+ const listening = buildSessionComposerLayout({
attachmentBusy: false,
attachmentCount: 0,
attachmentPickerOpen: false,
@@ -189,20 +191,35 @@ describe('sessionComposerLayout', () => {
voiceState: 'listening',
});
- expect(layout.primaryAction).toBe('none');
- expect(layout.send).toEqual({
- disabled: true,
- disabledReason: '输入文字、添加附件或引用后才能发送。',
+ expect(listening.send).toEqual({
+ disabled: false,
+ disabledReason: null,
label: '发送',
- visible: false,
+ visible: true,
});
- expect(layout.input).toMatchObject({
+ expect(listening.input).toMatchObject({
disabled: false,
disabledReason: null,
placeholder: '正在听……',
});
- expect(layout.guidanceText).toBe('正在听,文字出现后会显示发送;点输入框可结束语音并弹出键盘。');
- expect(layout.statusText).toBe('正在听');
+ expect(listening.guidanceText).toBe('正在听;点发送会结束语音并发送识别的文字,点输入框可结束语音并弹出键盘。');
+ expect(listening.statusText).toBe('正在听');
+
+ const refining = buildSessionComposerLayout({
+ attachmentBusy: false,
+ attachmentCount: 0,
+ attachmentPickerOpen: false,
+ canStop: false,
+ draftText: '',
+ queueBusy: false,
+ sending: false,
+ voiceState: 'refining',
+ });
+ expect(refining.send).toMatchObject({
+ disabled: true,
+ disabledReason: '语音正在处理,完成后再发送。',
+ visible: true,
+ });
});
it('hides stop in the normal idle composer but keeps running work stoppable while send is primary', () => {
diff --git a/apps/mobile/src/session/ComposerRichInput.tsx b/apps/mobile/src/session/ComposerRichInput.tsx
index 34f13ad217..689cc48451 100644
--- a/apps/mobile/src/session/ComposerRichInput.tsx
+++ b/apps/mobile/src/session/ComposerRichInput.tsx
@@ -24,7 +24,6 @@ export interface ComposerRichInputHandle {
blur(): void;
focus(): void;
insertNode(node: ComposerNode): void;
- setSelectionToEnd(): void;
}
export interface ComposerRichInputProps {
@@ -176,7 +175,11 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
}
inject(`window.cindyComposer.insertNode(${JSON.stringify(node)});`);
},
- setSelectionToEnd: focusEditor,
+ // 注意:曾有过 setSelectionToEnd: focusEditor 的别名——web 侧 placeCaretAtEnd
+ // 必须 root.focus(),而 keyboardDisplayRequiresUserAction={false} 让任何程序化
+ // focus 都会弹软键盘。「只挪选区不聚焦」在这个 WebView 编辑器上不成立,需要
+ // caret 在末尾的调用方请显式用 focus / applyDocumentAndSetSelectionToEnd,
+ // 并自行承担弹键盘的语义。
};
if (typeof forwardedRef === 'function') forwardedRef(handle);
else forwardedRef.current = handle;
diff --git a/apps/mobile/src/session/MobileComposerInputRow.tsx b/apps/mobile/src/session/MobileComposerInputRow.tsx
index 9c8362b8b9..eee17b6938 100644
--- a/apps/mobile/src/session/MobileComposerInputRow.tsx
+++ b/apps/mobile/src/session/MobileComposerInputRow.tsx
@@ -332,13 +332,15 @@ export function ComposerToolbarSpacer() {
}
/**
- * card 工具排中语音按钮的等宽占位。真实语音按钮由 MobileComposerInputRow
- * 以 absolute 锚点渲染(保证两态同一实例、位置平滑过渡),工具排用本占位
- * 在 flex 流里为它留出位置。
+ * 工具排 / 输入行 flex 流中语音按钮的等宽占位。真实语音按钮由
+ * MobileComposerInputRow 以 absolute 锚点渲染(保证两态同一实例、位置平滑
+ * 过渡),流内用本占位为它留出位置。录音中胶囊(红点+计时)比常态宽,由
+ * `width` 传入当前胶囊宽度(useMobileVoiceRecordingTimer.pillWidth),占位随
+ * 之变宽把左邻按钮推开——胶囊只向左生长,右缘(与发送键的邻接关系)不动。
*/
-export function ComposerToolbarVoiceSlot() {
+export function ComposerToolbarVoiceSlot({ width }: { width?: number }) {
const styles = useThemedStyles(makeMobileComposerInputRowStyles);
- return <View style={styles.toolbarVoiceSlot} />;
+ return <View style={[styles.toolbarVoiceSlot, width != null && { width }]} />;
}
export interface ComposerResizeGrabberProps {
diff --git a/apps/mobile/src/session/VoiceRecordingPill.tsx b/apps/mobile/src/session/VoiceRecordingPill.tsx
new file mode 100644
index 0000000000..3f5b03ed90
--- /dev/null
+++ b/apps/mobile/src/session/VoiceRecordingPill.tsx
@@ -0,0 +1,164 @@
+import { Animated, Easing, LayoutAnimation, Platform, UIManager, View } from 'react-native';
+import { useEffect, useRef, useState } from 'react';
+import { Text } from '@/components/AppText';
+import { getCachedReduceMotionEnabled, useReduceMotionEnabled } from '@/hooks/useReduceMotion';
+import { useThemedStyles, type ThemeColors } from '@/theme';
+import { radius, typeScale } from '@/theme/tokens';
+import { MOBILE_COMPOSER_CONTROL_SIZE } from '@/session/MobileComposerInputRow';
+
+// 旧架构 Android 需要显式开启 LayoutAnimation;新架构(Fabric)下该开关是 no-op。
+// 与 useComposerCardTransition / collapseAnimation 相同的模块级开关——本模块可能
+// 在两者都未加载时独立使用,不能依赖别处的副作用(review 反馈)。
+if (Platform.OS === 'android' && UIManager.setLayoutAnimationEnabledExperimental) {
+ UIManager.setLayoutAnimationEnabledExperimental(true);
+}
+
+/**
+ * 录音中语音按钮的胶囊宽度(对齐桌面 VoiceInputButton 的红点+计时展开形态)。
+ * 宽度是**驱动值**而非测量值:计时文本用 tabular-nums 定宽数字,宽度只取决于
+ * 字符数(m:ss / mm:ss 两档),按钮与工具排占位 slot 从同一常量取值,推开左邻
+ * 的停止按钮时零帧延迟、不会出现"胶囊先展开一帧盖住停止钮再弹开"的闪烁。
+ * 估值按 iOS SF Pro / Android Roboto 的 13pt tabular 数字宽度取上限,内容居中,
+ * 平台间 ±2pt 的差异被对称留白吸收。
+ */
+export const MOBILE_VOICE_RECORDING_PILL_WIDTH = 72;
+export const MOBILE_VOICE_RECORDING_PILL_WIDTH_WIDE = 80;
+
+/** 录音计时:从录音开始逐秒累计,格式 m:ss(对齐桌面 recTimeText)。 */
+export function formatVoiceRecordingTime(seconds: number): string {
+ const minutes = Math.floor(seconds / 60);
+ const remainder = seconds % 60;
+ return `${minutes}:${String(remainder).padStart(2, '0')}`;
+}
+
+export interface MobileVoiceRecordingTimerInput {
+ /** 胶囊是否展开(含按下即录的乐观 pending 期,展开时显示红点+计时)。 */
+ expanded: boolean;
+ /**
+ * 是否正在真实采集音频(listening)。计时只在此期间走秒:启动链路
+ * (权限弹窗/凭证/ASR 连接)不算录音时长,否则首次授权慢时胶囊一出现
+ * 就已经显示好几秒(review 反馈)。pending 期展开显示静止的 0:00。
+ */
+ counting: boolean;
+}
+
+export interface MobileVoiceRecordingTimer {
+ /** m:ss 计时文本;非展开态为 null(按钮应显示 Mic / spinner)。 */
+ label: string | null;
+ /** 语音按钮与工具排占位 slot 的当前应有宽度。 */
+ pillWidth: number;
+}
+
+/**
+ * 录音计时状态。counting 翻 true 时从 0 重新计时,expanded 翻 false 清零。
+ * 同时在展开态翻转与宽度换档的下一帧布局注册一次 LayoutAnimation
+ * (一次性瞬态、用户触发、有明确结束,符合动效红线;240ms 对齐桌面胶囊
+ * 展开时长),让胶囊展开/收回与左邻按钮的让位在同一段运动里完成。
+ */
+export function useMobileVoiceRecordingTimer(
+ { expanded, counting }: MobileVoiceRecordingTimerInput,
+): MobileVoiceRecordingTimer {
+ const [seconds, setSeconds] = useState(0);
+
+ useEffect(() => {
+ if (!counting) {
+ if (!expanded) setSeconds(0);
+ return;
+ }
+ setSeconds(0);
+ const timer = setInterval(() => {
+ setSeconds((current) => current + 1);
+ }, 1000);
+ return () => clearInterval(timer);
+ }, [counting, expanded]);
+
+ const label = expanded ? formatVoiceRecordingTime(seconds) : null;
+ const pillWidth = label === null
+ ? MOBILE_COMPOSER_CONTROL_SIZE
+ : label.length > 4
+ ? MOBILE_VOICE_RECORDING_PILL_WIDTH_WIDE
+ : MOBILE_VOICE_RECORDING_PILL_WIDTH;
+
+ const prevWidthRef = useRef(pillWidth);
+ if (prevWidthRef.current !== pillWidth) {
+ prevWidthRef.current = pillWidth;
+ // reduce-motion 降级为直切,对齐桌面 prefers-reduced-motion 下
+ // pillTransition = undefined 的行为。按 useReduceMotion 的约定,null
+ // (首帧未查到)也按不播处理——缓存模块加载即预热,实际命中窗口极小。
+ if (getCachedReduceMotionEnabled() === false) {
+ LayoutAnimation.configureNext({
+ duration: 240,
+ update: { type: 'easeInEaseOut' },
+ });
+ }
+ }
+
+ return { label, pillWidth };
+}
+
+/**
+ * 录音中胶囊的内容:脉冲红点 + m:ss 计时(对齐桌面 activeRecording 的
+ * 红点 animate-pulse + tabular-nums 计时)。宿主按钮负责胶囊外形
+ * (surfaceChip 底、pill 圆角、宽度取 useMobileVoiceRecordingTimer.pillWidth)。
+ */
+export function VoiceRecordingPillContent({ label, testID }: { label: string; testID?: string }) {
+ const styles = useThemedStyles(makeVoiceRecordingPillStyles);
+ const pulse = useRef(new Animated.Value(1)).current;
+ const reduceMotion = useReduceMotionEnabled();
+
+ useEffect(() => {
+ // 与桌面 animate-pulse 同节奏(2s 往返、透明度 1↔0.5);opacity-only + native
+ // driver,常驻循环动画的 compositor 约束(工程规范 §7 的 RN 对应物)满足。
+ // reduce-motion 时不起循环,红点常亮(对齐桌面 motion-reduce:animate-none);
+ // 循环动画按 hook 约定「只有 === false 才播」。
+ if (reduceMotion !== false) {
+ pulse.setValue(1);
+ return;
+ }
+ const loop = Animated.loop(
+ Animated.sequence([
+ Animated.timing(pulse, {
+ duration: 1000,
+ easing: Easing.inOut(Easing.ease),
+ toValue: 0.5,
+ useNativeDriver: true,
+ }),
+ Animated.timing(pulse, {
+ duration: 1000,
+ easing: Easing.inOut(Easing.ease),
+ toValue: 1,
+ useNativeDriver: true,
+ }),
+ ]),
+ );
+ loop.start();
+ return () => loop.stop();
+ }, [pulse, reduceMotion]);
+
+ return (
+ <View pointerEvents="none" style={styles.pillContent} testID={testID}>
+ <Animated.View style={[styles.recordingDot, { opacity: pulse }]} />
+ <Text style={styles.timeText}>{label}</Text>
+ </View>
+ );
+}
+
+const makeVoiceRecordingPillStyles = (colors: ThemeColors) => ({
+ pillContent: {
+ alignItems: 'center' as const,
+ flexDirection: 'row' as const,
+ gap: 6,
+ justifyContent: 'center' as const,
+ },
+ recordingDot: {
+ backgroundColor: colors.statusRecording,
+ borderRadius: radius.pill,
+ height: 8,
+ width: 8,
+ },
+ timeText: {
+ color: colors.textPrimary,
+ fontSize: typeScale.footnote,
+ fontVariant: ['tabular-nums' as const],
+ },
+});
diff --git a/packages/maker-shared/src/__tests__/sessionOperation.test.ts b/packages/maker-shared/src/__tests__/sessionOperation.test.ts
index f06e639bc7..7f5cc5b5c1 100644
--- a/packages/maker-shared/src/__tests__/sessionOperation.test.ts
+++ b/packages/maker-shared/src/__tests__/sessionOperation.test.ts
@@ -285,8 +285,10 @@ describe('shared session composer action model', () => {
expect(runningWithDraft.guidanceText).toBe('点发送后会进入桌面端队列,按当前会话设置执行。');
});
- it('keeps the composer editable while voice input is listening but waits for text before showing send', () => {
- const layout = buildSessionComposerLayout({
+ it('keeps the send slot present and usable through the whole voice lifecycle', () => {
+ // 语音生命周期内发送槽常驻(对齐桌面主槽永远占位):转写落地前后布局不变,
+ // 否则首段转写让发送键冒出来的瞬间,语音按钮整格左移、原位变成停止任务。
+ const listening = buildSessionComposerLayout({
attachmentBusy: false,
attachmentCount: 0,
attachmentPickerOpen: false,
@@ -297,20 +299,52 @@ describe('shared session composer action model', () => {
voiceState: 'listening',
});
- expect(layout.primaryAction).toBe('none');
- expect(layout.send).toEqual({
- disabled: true,
- disabledReason: '输入文字、添加附件或引用后才能发送。',
+ // listening + 空草稿:发送可见且可按,语义是「结束录音并发送」(finish-and-send)。
+ expect(listening.send).toEqual({
+ disabled: false,
+ disabledReason: null,
label: '发送',
- visible: false,
+ visible: true,
});
- expect(layout.input).toMatchObject({
+ expect(listening.input).toMatchObject({
disabled: false,
disabledReason: null,
placeholder: '正在听……',
});
- expect(layout.guidanceText).toBe('正在听,文字出现后会显示发送;点输入框可结束语音并弹出键盘。');
- expect(layout.statusText).toBe('正在听');
+ expect(listening.guidanceText).toBe('正在听;点发送会结束语音并发送识别的文字,点输入框可结束语音并弹出键盘。');
+ expect(listening.statusText).toBe('正在听');
+
+ // submitting/refining + 空草稿:转写还没落地,发送保持可见但禁用,布局不塌。
+ for (const voiceState of ['submitting', 'refining'] as const) {
+ const processing = buildSessionComposerLayout({
+ attachmentBusy: false,
+ attachmentCount: 0,
+ attachmentPickerOpen: false,
+ canStop: false,
+ draftText: '',
+ queueBusy: false,
+ sending: false,
+ voiceState,
+ });
+ expect(processing.send).toMatchObject({
+ disabled: true,
+ disabledReason: '语音正在处理,完成后再发送。',
+ visible: true,
+ });
+ }
+
+ // 语音结束(done)且草稿仍空:发送槽随语音生命周期一起收场。
+ const doneEmpty = buildSessionComposerLayout({
+ attachmentBusy: false,
+ attachmentCount: 0,
+ attachmentPickerOpen: false,
+ canStop: false,
+ draftText: '',
+ queueBusy: false,
+ sending: false,
+ voiceState: 'done',
+ });
+ expect(doneEmpty.send.visible).toBe(false);
});
it('marks busy operations with disabled reasons without changing layout shape', () => {
diff --git a/packages/maker-shared/src/sessionOperation.ts b/packages/maker-shared/src/sessionOperation.ts
index 82175c1e0d..0348755f65 100644
--- a/packages/maker-shared/src/sessionOperation.ts
+++ b/packages/maker-shared/src/sessionOperation.ts
@@ -144,7 +144,12 @@ export function buildSessionComposerLayout(input: SessionComposerLayoutInput): S
const hasAttachments = input.attachmentCount > 0;
const hasQuotes = (input.quoteCount ?? 0) > 0;
const canSend = hasDraft || hasAttachments || hasQuotes;
- const sendVisible = canSend || input.sending;
+ // 语音生命周期(listening/submitting/refining)内发送槽常驻(对齐桌面主槽永远占位):
+ // 录音期间发送键就是「结束并发送」,转写落地前后布局都不变——否则首段转写让 canSend
+ // 翻 true 的瞬间发送键才冒出来,右对齐按钮组整体左移,语音按钮让出的位置正好被
+ // 停止任务按钮占据,手指原地再点一下会误停任务。
+ const voiceBusy = isVoiceInputBusy(input.voiceState);
+ const sendVisible = canSend || input.sending || voiceBusy;
const stopVisible = input.canStop || input.queueBusy;
const sendUnavailableReason = normalizeOptionalReason(input.sendUnavailableReason);
const voiceLabel = composerVoiceStateLabel(input.voiceState);
@@ -178,15 +183,23 @@ export function buildSessionComposerLayout(input: SessionComposerLayoutInput): S
send: {
// attachmentBusy 必须挡发送:附件仍在异步上传时(典型:粘贴图片,无系统
// picker 遮挡、UI 完全可交互),抢发会发出不含该附件的消息并把图滞留托盘。
- disabled: input.sending || input.attachmentBusy || sendUnavailableReason !== null || !canSend,
+ // listening 期间即使草稿还空着也可按(语义是「结束录音并发送」,对齐桌面
+ // finish-and-send);submitting/refining 期间转写还没落地,禁用等润色完成。
+ disabled: input.sending
+ || input.attachmentBusy
+ || sendUnavailableReason !== null
+ || isVoiceInputProcessing(input.voiceState)
+ || (!canSend && input.voiceState !== 'listening'),
disabledReason: input.sending
? '消息正在发送到电脑端。'
: input.attachmentBusy
? '附件上传中,完成后再发送。'
: sendUnavailableReason
- ?? (canSend
- ? null
- : '输入文字、添加附件或引用后才能发送。'),
+ ?? (isVoiceInputProcessing(input.voiceState)
+ ? '语音正在处理,完成后再发送。'
+ : canSend || input.voiceState === 'listening'
+ ? null
+ : '输入文字、添加附件或引用后才能发送。'),
label: input.sending ? '发送中' : '发送',
visible: sendVisible,
},
@@ -349,7 +362,7 @@ function buildComposerGuidanceText(input: SessionComposerLayoutInput): string {
if (input.voiceState === 'listening' && hasDraft) {
return '点发送会结束语音并发送当前文字;点输入框会结束语音并弹出键盘。';
}
- if (input.voiceState === 'listening') return '正在听,文字出现后会显示发送;点输入框可结束语音并弹出键盘。';
+ if (input.voiceState === 'listening') return '正在听;点发送会结束语音并发送识别的文字,点输入框可结束语音并弹出键盘。';
if (input.voiceState === 'submitting') return '正在转写语音,输入框会暂时锁定。';
if (input.voiceState === 'refining') return '正在润色语音,完成后会更新输入框。';
if (input.attachmentBusy) return '正在检查或上传附件,完成后会出现在附件列表。';