diff --git a/frontend/src/features/assistant/application/AssistantContinuousConversationService.ts b/frontend/src/features/assistant/application/AssistantContinuousConversationService.ts index ec77ded9..ade4e149 100644 --- a/frontend/src/features/assistant/application/AssistantContinuousConversationService.ts +++ b/frontend/src/features/assistant/application/AssistantContinuousConversationService.ts @@ -69,10 +69,28 @@ export class AssistantContinuousConversationService implements AssistantApplicat private replyText: string | null = null; private soundLevel: number | null = null; /** 本次开麦以来的问答历史,追加不覆盖;startTurn() 清空,跟 replyText 各管各的 - * ——replyText 是当前这一轮的气泡内容,turns 是完整历史。 */ + * ——replyText 是当前这一轮的气泡内容,turns 是完整历史。气泡列表由 turns 推导 + * (每轮一条用户句 + 一条助手句)。连续模式一次 voice.stream.start 不带 + * request_id,服务端回显的 request_id 恒为空,所以轮次只能按到达顺序排: + * 每个 voice.asr.completed 追加一轮,随后的 reply/question 写进当前这轮。 + * 后端(realtime 在 speech_started 打断、composed 在 VAD 打断)都保证上一轮 + * 回复在下一轮转写前落地,顺序天然正确;turns 推导的意义在于让"追问"和它 + * 的流式回复落在同一轮同一个气泡里,而不是用 request_id 做跨轮关联。 */ private turns: ConversationTurnRecord[] = []; - /** 免提长对话里已落屏的对白,追加用户句和助手句,供 UI 气泡展示。 */ - private messages: VoiceChatMessage[] = []; + /** 回复/追问先于任何 transcript 到达(正常流程不会发生)时挂在这里的零散助手句, + * getMessages() 里接在 turns 推导结果后面,避免乱序把内容丢掉。 */ + private orphanMessages: VoiceChatMessage[] = []; + /** 当前是否正在流式输出一条回复(voice.dialogue.reply done=false 起、 + * done=true 止)。连续模式同一时刻最多只有一条回复在流,所以一个布尔就够; + * 展示层据此给最后一条助手气泡加波形。composed 代理打断回复时只发 + * voice.tts.canceled 而不会再补 done=true,所以 tts.canceled 也要清它。 */ + private replyStreaming = false; + /** 最后一条轮次的回复是否已收尾(收到 done=true)。连续模式没有 per-turn + * request_id,回复只能按到达顺序归属;当最后一条轮次已经回复完成、又来一条 + * 新回复时,这条属于"还没到的新一轮"(它的转写可能晚到或被 VAD 跳过)—— + * 必须开一个占位轮挂上去,否则会覆盖上一条已完成的回复(改前实测:上一条 + * 回复被后一条覆盖成一样的内容)。 */ + private lastTurnReplyDone = false; /** endTurn() 主动关闭连接期间为 true,让 handleClose 认出这是预期内的挂断。 */ private endingCall = false; private idleTimer: ReturnType | null = null; @@ -144,8 +162,30 @@ export class AssistantContinuousConversationService implements AssistantApplicat return this.soundLevel; } + /** 由 turns 推导气泡列表:每轮一条用户句 + 一条助手句(回复未到就还没有)。 + * 顺序跟随 turns(到达顺序);追问和它的流式回复落在同一轮同一个气泡里,不会 + * 出现同一句回答两个气泡。正在流式输出时,最后一条助手气泡带 pending 波形。 */ getMessages(): readonly VoiceChatMessage[] { - return this.messages; + const messages: VoiceChatMessage[] = []; + for (const turn of this.turns) { + // 占位轮(回复先于转写到达)还没有用户句,不渲染空的用户气泡。 + if (turn.transcript.length > 0) { + messages.push({ id: `${turn.id}:user`, role: 'user', text: turn.transcript }); + } + if (turn.replyText !== null && turn.replyText.length > 0) { + messages.push({ id: `${turn.id}:assistant`, role: 'assistant', text: turn.replyText }); + } + } + messages.push(...this.orphanMessages); + if (this.replyStreaming) { + for (let index = messages.length - 1; index >= 0; index -= 1) { + if (messages[index].role === 'assistant') { + messages[index] = { ...messages[index], pending: true }; + break; + } + } + } + return messages; } getTurns(): readonly ConversationTurnRecord[] { @@ -162,7 +202,9 @@ export class AssistantContinuousConversationService implements AssistantApplicat this.replyText = null; this.soundLevel = null; this.turns = []; - this.messages = []; + this.orphanMessages = []; + this.replyStreaming = false; + this.lastTurnReplyDone = false; // 上一通电话可能是在暂停期间被空闲超时兜底挂断的,muted 只在用户手动 // togglePause() 里恢复;不在这里清一次,新开的电话会继承上一通的静音, // UI 显示 listening 但麦克风帧全被吞掉。 @@ -377,15 +419,27 @@ export class AssistantContinuousConversationService implements AssistantApplicat case 'voice.asr.completed': // 听到一句真实语音:这是空闲计时器真正要等的信号,重新给一个完整窗口。 this.armIdleTimer(); - this.appendUserMessage(message.payload.transcript); - this.turns = [ - ...this.turns, - { - id: message.request_id ?? `turn-${this.turns.length}`, - replyText: null, - transcript: message.payload.transcript, - }, - ]; + const transcript = message.payload.transcript.trim(); + if (transcript.length > 0) { + const last = this.turns[this.turns.length - 1]; + if (last !== undefined && last.transcript === '' && last.replyText !== null) { + // 上一条回复先于它的转写到达,开过占位轮:现在把转写补进同一轮。 + this.turns = this.turns.map((turn, i) => + i === this.turns.length - 1 ? { ...turn, transcript } : turn, + ); + } else { + this.turns = [ + ...this.turns, + { + id: message.request_id ?? `turn-${this.turns.length}`, + replyText: null, + transcript, + }, + ]; + // 新一轮等着它自己的回复。 + this.lastTurnReplyDone = false; + } + } this.notifyListeners(); return; case 'voice.command.result': { @@ -408,24 +462,37 @@ export class AssistantContinuousConversationService implements AssistantApplicat case 'voice.dialogue.question': // 缺字段/地点歧义之类的追问,对当前这轮来说就是系统的回复——记进历史, // 不然标题过了这一阵子就变回通用文案,这句追问在记录里再也找不到。 - this.updateLastTurnReply(message.request_id, message.payload.speech_text); - this.upsertAssistantMessage(message.payload.question_id, message.payload.speech_text); + // 追问本身就是这轮回复的文字:后续 voice.dialogue.reply 的流式文字还会 + // 继续写进同一轮。这里不再单独生成一个 question_id 气泡——否则同一句 + // 追问会以两个气泡重复出现(改前实测)。 + if (this.turns.length === 0) { + this.upsertOrphanQuestion(message.payload.question_id, message.payload.speech_text); + } else { + this.writeTurnReply(message.request_id, message.payload.speech_text, false); + } this.setState({ conversationId: message.conversation_id, phase: 'asking', speechText: message.payload.speech_text, }); return; - case 'voice.dialogue.reply': + case 'voice.dialogue.reply': { this.replyText = message.payload.speech_text; - this.updateLastTurnReply(message.request_id, message.payload.speech_text); - this.upsertAssistantMessage( - message.payload.reply_id, - message.payload.speech_text, - !message.payload.done, - ); + this.replyStreaming = !message.payload.done; + if (this.turns.length === 0) { + // 回复先于任何 transcript 到达(正常流程不会发生):没有轮次可写, + // 挂到零散气泡列表兜底。 + this.upsertOrphanReply(message.payload.reply_id, message.payload.speech_text); + } else { + this.writeTurnReply( + message.request_id, + message.payload.speech_text, + message.payload.done, + ); + } this.notifyListeners(); return; + } case 'voice.tts.start': this.playbackGeneration += 1; this.canceledAudioId = null; @@ -466,6 +533,14 @@ export class AssistantContinuousConversationService implements AssistantApplicat } this.canceledAudioId = message.audio_id || this.currentAudioId; this.currentAudioId = null; + // composed 代理打断回复时只发 voice.tts.canceled、不会再补 done=true, + // 所以这里要顺手清掉流式标记,否则被打断那条气泡的波形会一直跳。 + this.replyStreaming = false; + // 同理必须把这轮标记成"回复已收尾":被打断的轮次不会再收到 done=true, + // 用户接着开口后,下一轮的回复如果抢在它自己的转写前到达,writeTurnReply + // 得能认出"上一轮已经完了"才会开占位轮,否则会把被打断轮次的部分回复 + // 覆盖成下一轮的内容(实测复现:被打断轮次的文字变成了下一轮的回答)。 + this.lastTurnReplyDone = true; void this.stopPlaybackImmediately(); this.setState({ conversationId: message.conversation_id, phase: 'interrupted' }); return; @@ -626,49 +701,70 @@ export class AssistantContinuousConversationService implements AssistantApplicat return this.connection; } - /** speech_text 是累计到目前为止的完整文字(不是增量),直接覆盖对应轮次即可。 - * 必须按 request_id 找到它真正所属的那一轮,不能想当然地假设"最后一轮"—— - * 麦克风连续开着,用户可能在上一轮的回复还没到达前就已经开口问了下一句, - * asr.completed 先把新一轮 push 进 turns,这条迟到的回复到达时"最后一轮" - * 已经变成了下一轮,会把上一轮的回复错记成下一轮的(下一轮回复还没来时 - * 显示的会是上一轮内容)。找不到匹配 id(服务端没带 request_id 这种理论上 - * 不该发生的情况)时退化成更新最后一轮,好歹不丢内容。 */ - private updateLastTurnReply(requestId: string | undefined, replyText: string): void { + /** 把一条助手消息(回复/追问)写进它所属的轮次。连续模式没有 per-turn + * request_id,回复只能按到达顺序归属到"当前轮"(最后一条): + * - 正常:最后一条轮次的回复还没完成,直接写进去(done 驱动波形)。 + * - 上一轮已回复完成、又来一条新回复:说明它属于"还没到的新一轮"(转写 + * 晚到或被 VAD 跳过)。必须开一个占位轮挂上去,等它的 asr 到了再补 + * 转写——否则会覆盖上一条已完成的回复(改前实测:上一条回复被后一条 + * 覆盖成一样的内容)。 + * request_id 分支只为向前兼容:万一后端将来给连续模式的每条消息带上独立 + * request_id,就能按它认轮次。 */ + private writeTurnReply(requestId: string | undefined, replyText: string, done: boolean): void { if (this.turns.length === 0) { return; } - const targetIndex = - requestId !== undefined ? this.turns.findIndex((turn) => turn.id === requestId) : -1; - const index = targetIndex === -1 ? this.turns.length - 1 : targetIndex; + if (requestId !== undefined) { + const found = this.turns.findIndex((turn) => turn.id === requestId); + if (found >= 0) { + this.turns = this.turns.map((turn, i) => (i === found ? { ...turn, replyText } : turn)); + this.lastTurnReplyDone = done; + return; + } + } + if (this.lastTurnReplyDone) { + this.turns = [...this.turns, { id: `turn-${this.turns.length}`, replyText, transcript: '' }]; + this.lastTurnReplyDone = done; + return; + } + const index = this.turns.length - 1; this.turns = this.turns.map((turn, i) => (i === index ? { ...turn, replyText } : turn)); + this.lastTurnReplyDone = done; } - private appendUserMessage(transcript: string): void { - const text = transcript.trim(); + /** 零散助手句(回复先于任何转写到达时的兜底):同 id 覆盖;波形由 + * getMessages() 里的 replyStreaming 统一决定,这里不再单独带 pending。 */ + private upsertOrphanReply(id: string, speechText: string): void { + const text = speechText.trim(); if (text.length === 0) { return; } - this.messages = [ - ...this.messages, - { id: `user-${this.messages.length + 1}`, role: 'user', text }, - ]; - this.notifyListeners(); + const next: VoiceChatMessage = { id, role: 'assistant', text }; + const existing = this.orphanMessages.findIndex((message) => message.id === id); + if (existing >= 0) { + this.orphanMessages = this.orphanMessages.map((message, index) => + index === existing ? next : message, + ); + return; + } + this.orphanMessages = [...this.orphanMessages, next]; } - private upsertAssistantMessage(id: string, speechText: string, pending = false): void { - const text = speechText.trim(); - if (text.length === 0) { + /** 追问先于任何转写到达时的兜底:有轮次可写时一律走 writeTurnReply, + * 这里只在 turns 为空时把内容挂到零散列表。 */ + private upsertOrphanQuestion(questionId: string, speechText: string): void { + if (this.turns.length > 0 || speechText.trim().length === 0) { return; } - const next: VoiceChatMessage = pending - ? { id, role: 'assistant', text, pending: true } - : { id, role: 'assistant', text }; - const existing = this.messages.findIndex((message) => message.id === id); + const text = speechText.trim(); + const existing = this.orphanMessages.findIndex((message) => message.id === questionId); if (existing >= 0) { - this.messages = this.messages.map((message, index) => (index === existing ? next : message)); + this.orphanMessages = this.orphanMessages.map((message, index) => + index === existing ? { ...message, text } : message, + ); return; } - this.messages = [...this.messages, next]; + this.orphanMessages = [...this.orphanMessages, { id: questionId, role: 'assistant', text }]; } private armIdleTimer(): void { diff --git a/frontend/src/features/assistant/presentation/VoiceCallScreen.tsx b/frontend/src/features/assistant/presentation/VoiceCallScreen.tsx index d95f543d..9b2f4d95 100644 --- a/frontend/src/features/assistant/presentation/VoiceCallScreen.tsx +++ b/frontend/src/features/assistant/presentation/VoiceCallScreen.tsx @@ -36,6 +36,10 @@ const TALK_SCALE = { duration: 650, from: 1, to: 1.14 }; const VOICEPRINT_BAR_COUNT = 9; const VOICEPRINT_TICK_MS = 80; const BUBBLE_VOICEPRINT_BARS = 5; +/** normalizeLevel 之后的能量下限:低于它视为安静。安静待听时球里不画声纹条 + * (只保留呼吸缩放),避免"点点点"在每次回答结束后一直跳;TTS 或用户开口 + * 时麦克风电平抬起来,声纹条才出现。 */ +const ORB_SOUND_FLOOR = 0.16; const CALL_BACKGROUND = '#0E241F'; const CALL_GLOW = '#18443A'; const CALL_VIGNETTE = '#071310'; @@ -61,7 +65,6 @@ export function VoiceCallScreen({ onLayout, onMomentumScrollBegin, onMomentumScrollEnd, - onScroll, onScrollBeginDrag, onScrollEndDrag, onTurnsLayout, @@ -69,6 +72,11 @@ export function VoiceCallScreen({ transcriptRef, } = usePinnedTranscriptScroll(); const [scale] = useState(() => new Animated.Value(1)); + // 声纹条只在"正在说话"或实际有声时出现:连续模式麦克风常开,安静时的 dBFS + // 也会让条子一直小幅跳动,看起来像回答结束后还有一串点点点。 + const orbWaveVisible = + status === 'speaking' || + (status === 'listening' && normalizeLevel(soundLevel) >= ORB_SOUND_FLOOR); useEffect(() => { scale.stopAnimation(); @@ -121,10 +129,8 @@ export function VoiceCallScreen({ onLayout={onLayout} onMomentumScrollBegin={onMomentumScrollBegin} onMomentumScrollEnd={onMomentumScrollEnd} - onScroll={onScroll} onScrollBeginDrag={onScrollBeginDrag} onScrollEndDrag={onScrollEndDrag} - scrollEventThrottle={16} showsVerticalScrollIndicator={false} style={styles.transcript} testID="voice-call-transcript" @@ -218,16 +224,18 @@ export function VoiceCallScreen({ ]} > {status === 'listening' || status === 'speaking' ? ( - + orbWaveVisible ? ( + + ) : null ) : null} diff --git a/frontend/src/features/assistant/presentation/usePinnedTranscriptScroll.ts b/frontend/src/features/assistant/presentation/usePinnedTranscriptScroll.ts index 3163e73c..2ec86f59 100644 --- a/frontend/src/features/assistant/presentation/usePinnedTranscriptScroll.ts +++ b/frontend/src/features/assistant/presentation/usePinnedTranscriptScroll.ts @@ -33,13 +33,23 @@ export function isPinnedToBottom({ return distanceFromBottom <= threshold; } +/** + * 对白列表的贴底滚动: + * - 短对白靠顶部空白(topSpacer)贴在声纹球上方,不滚动; + * - 超出一屏后,只要用户还贴在底部附近,新内容一到就跳到底部; + * - "是否贴底"只在真实手势结束时重新判定(onScrollEndDrag / + * onMomentumScrollEnd),绝不从 onScroll 里判——程序化 scrollToEnd 也会 + * 触发 onScroll,从那儿判会把我们自己的滚动误认成用户滑走,列表从此不再 + * 自动跟随(改前实测:流式出字途中停摆,新句子被压到屏幕外)。 + * - 拖动开始到手势结束期间(interacting)不抢滚动,放手后若还在底部再补跳; + * - 跳底用 animated:false:流式出字很密集,动画滚动会跟下一次内容变化互相 + * 打断,看起来像卡住不动。 + */ export function usePinnedTranscriptScroll() { const transcriptRef = useRef(null); const pinnedRef = useRef(true); const interactingRef = useRef(false); - const ignoreProgrammaticScrollRef = useRef(false); const idleTimerRef = useRef | null>(null); - const ignoreTimerRef = useRef | null>(null); const viewportHeightRef = useRef(0); const turnsHeightRef = useRef(0); const [topSpacer, setTopSpacer] = useState(0); @@ -57,12 +67,23 @@ export function usePinnedTranscriptScroll() { idleTimerRef.current = null; }; - const clearIgnoreTimer = () => { - if (ignoreTimerRef.current === null) { - return; - } - clearTimeout(ignoreTimerRef.current); - ignoreTimerRef.current = null; + const scrollToLatest = () => { + // Android 上 onContentSizeChange 触发时原生 ScrollView 有时还没把新内容 + // 高度提交完,直接跳会落不到底;延后两帧再跳。用 animated:false 而不是 + // 动画滚动——流式出字很密集,动画会跟下一次内容变化互相打断,看起来 + // 像卡住不动。 + // 排队和执行隔着两帧,这两帧之间用户完全可能已经按下手指开始拖动—— + // followLatestIfPinned() 里的判断只在排队那一刻查过一次,执行前必须 + // 再查一遍,否则一次流式出字排的跳底会在用户已经在拖动时突然把内容 + // 摁回最下面(改前实测:流式输出期间完全无法上拉,看起来像强制贴底)。 + requestAnimationFrame(() => { + requestAnimationFrame(() => { + if (interactingRef.current || !pinnedRef.current) { + return; + } + transcriptRef.current?.scrollToEnd({ animated: false }); + }); + }); }; const followLatestIfPinned = () => { @@ -75,13 +96,7 @@ export function usePinnedTranscriptScroll() { if (!pinnedRef.current) { return; } - ignoreProgrammaticScrollRef.current = true; - transcriptRef.current?.scrollToEnd({ animated: true }); - clearIgnoreTimer(); - ignoreTimerRef.current = setTimeout(() => { - ignoreProgrammaticScrollRef.current = false; - ignoreTimerRef.current = null; - }, TRANSCRIPT_IDLE_MS); + scrollToLatest(); }; const markInteracting = () => { @@ -97,7 +112,6 @@ export function usePinnedTranscriptScroll() { useEffect(() => { return () => { clearIdleTimer(); - clearIgnoreTimer(); }; }, []); @@ -113,12 +127,25 @@ export function usePinnedTranscriptScroll() { followLatestIfPinned(); }; + /** 只有真实手势的滚动事件才算数:拖动结束或惯性滚动结束时的位置决定贴不贴底。 */ + const settlePinFromEvent = (event: NativeSyntheticEvent) => { + const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent; + pinnedRef.current = isPinnedToBottom({ + contentHeight: contentSize.height, + offsetY: contentOffset.y, + viewportHeight: layoutMeasurement.height, + }); + }; + const onScrollBeginDrag = () => { markInteracting(); }; - const onScrollEndDrag = () => { + const onScrollEndDrag = (event: NativeSyntheticEvent) => { + settlePinFromEvent(event); clearIdleTimer(); + // Android 上放手不一定有惯性滚动(onMomentumScrollEnd 可能不来),用短延迟 + // 兜底恢复跟随;iOS 有惯性时 onMomentumScrollBegin 会先清掉这个计时器。 idleTimerRef.current = setTimeout(markIdle, TRANSCRIPT_IDLE_MS); }; @@ -126,24 +153,12 @@ export function usePinnedTranscriptScroll() { markInteracting(); }; - const onMomentumScrollEnd = () => { + const onMomentumScrollEnd = (event: NativeSyntheticEvent) => { + settlePinFromEvent(event); clearIdleTimer(); markIdle(); }; - const onScroll = (event: NativeSyntheticEvent) => { - const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent; - viewportHeightRef.current = layoutMeasurement.height; - if (ignoreProgrammaticScrollRef.current) { - return; - } - pinnedRef.current = isPinnedToBottom({ - contentHeight: contentSize.height, - offsetY: contentOffset.y, - viewportHeight: layoutMeasurement.height, - }); - }; - const onContentSizeChange = (_width: number, _height: number) => { followLatestIfPinned(); }; @@ -153,7 +168,6 @@ export function usePinnedTranscriptScroll() { onLayout, onMomentumScrollBegin, onMomentumScrollEnd, - onScroll, onScrollBeginDrag, onScrollEndDrag, onTurnsLayout, diff --git a/frontend/tests/unit/features/assistant/application/AssistantContinuousConversationService.test.ts b/frontend/tests/unit/features/assistant/application/AssistantContinuousConversationService.test.ts index f0e49fc3..a3068779 100644 --- a/frontend/tests/unit/features/assistant/application/AssistantContinuousConversationService.test.ts +++ b/frontend/tests/unit/features/assistant/application/AssistantContinuousConversationService.test.ts @@ -249,9 +249,9 @@ describe('AssistantContinuousConversationService', () => { await flushAsync(); expect(service.getMessages()).toEqual([ - { id: 'user-1', role: 'user', text: '明天几点开会' }, - { id: 'reply_1', role: 'assistant', text: '明天下午三点' }, - { id: 'user-3', role: 'user', text: '谁参加' }, + { id: 'req_1:user', role: 'user', text: '明天几点开会' }, + { id: 'req_1:assistant', role: 'assistant', text: '明天下午三点' }, + { id: 'req_2:user', role: 'user', text: '谁参加' }, ]); }); @@ -314,6 +314,13 @@ describe('AssistantContinuousConversationService', () => { { id: 'req_1', replyText: '明天下午三点', transcript: '明天几点开会' }, { id: 'req_2', replyText: null, transcript: '谁参加' }, ]); + // 气泡列表必须跟着轮次走:req_1 的回复虽然迟到,仍排在其所属用户句下面, + // 而不是被追加到 req_2 的用户句后面(追加顺序的 messages 会排错)。 + expect(service.getMessages()).toEqual([ + { id: 'req_1:user', role: 'user', text: '明天几点开会' }, + { id: 'req_1:assistant', role: 'assistant', text: '明天下午三点' }, + { id: 'req_2:user', role: 'user', text: '谁参加' }, + ]); }); it.each([ @@ -347,13 +354,296 @@ describe('AssistantContinuousConversationService', () => { await flushAsync(); expect(service.getMessages()).toEqual([ - { id: 'user-1', role: 'user', text: '帮我订会议室' }, - { id: 'q_1', role: 'assistant', text: speechText }, + { id: 'req_1:user', role: 'user', text: '帮我订会议室' }, + { id: 'req_1:assistant', role: 'assistant', text: speechText }, ]); expect(service.getState()).toMatchObject({ phase: 'asking' }); }, ); + it('renders a clarifying question and its streamed reply as a single assistant bubble', async () => { + // 真实后端在追问轮会先发 voice.dialogue.question,再发同文字的流式 + // voice.dialogue.reply 片段(直到 done)。改前会生成 question_id 和 + // reply_id 两个气泡、同一句回答重复出现;现在必须合并成同一轮的一个气泡, + // 且流式期间带 pending 波形、done 后摘掉。 + const fake = createFakeConnection(); + const deps = createDeps({ connection: fake.connection }); + const service = createService(deps); + + await startListening(fake, service); + fake.emitMessage({ + conversation_id: 'conv_001', + request_id: 'req_1', + payload: { duration_ms: 800, language: 'zh', transcript: '帮我订会议室' }, + type: 'voice.asr.completed', + } as AssistantServerMessage); + fake.emitMessage({ + conversation_id: 'conv_001', + request_id: 'req_1', + payload: { + candidates: [], + question_id: 'q_1', + question_kind: 'missing_field', + speech_text: '你是想订哪一天的会议室?', + }, + type: 'voice.dialogue.question', + } as AssistantServerMessage); + await flushAsync(); + expect(service.getMessages()).toEqual([ + { id: 'req_1:user', role: 'user', text: '帮我订会议室' }, + { id: 'req_1:assistant', role: 'assistant', text: '你是想订哪一天的会议室?' }, + ]); + + fake.emitMessage({ + conversation_id: 'conv_001', + request_id: 'req_1', + payload: { done: false, reply_id: 'reply_1', speech_text: '你是想订哪一' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + await flushAsync(); + expect(service.getMessages()).toEqual([ + { id: 'req_1:user', role: 'user', text: '帮我订会议室' }, + { + id: 'req_1:assistant', + pending: true, + role: 'assistant', + text: '你是想订哪一', + }, + ]); + + fake.emitMessage({ + conversation_id: 'conv_001', + request_id: 'req_1', + payload: { done: true, reply_id: 'reply_1', speech_text: '你是想订哪一天的会议室?' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + await flushAsync(); + expect(service.getMessages()).toEqual([ + { id: 'req_1:user', role: 'user', text: '帮我订会议室' }, + { id: 'req_1:assistant', role: 'assistant', text: '你是想订哪一天的会议室?' }, + ]); + }); + + it('keeps the streaming waveform on the interrupted turn until its reply is done', async () => { + // 用户没等上一轮回复播完就开口(barge-in):下一轮用户句先落地,上一轮 + // 的气泡仍按轮次排在其用户句下面,pending 波形保留到该轮 done=true 才摘。 + const fake = createFakeConnection(); + const deps = createDeps({ connection: fake.connection }); + const service = createService(deps); + + await startListening(fake, service); + fake.emitMessage({ + conversation_id: 'conv_001', + request_id: 'req_1', + payload: { duration_ms: 800, language: 'zh', transcript: '明天几点开会' }, + type: 'voice.asr.completed', + } as AssistantServerMessage); + fake.emitMessage({ + conversation_id: 'conv_001', + request_id: 'req_1', + payload: { done: false, reply_id: 'reply_1', speech_text: '明天下午三' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + fake.emitMessage({ + conversation_id: 'conv_001', + request_id: 'req_2', + payload: { duration_ms: 500, language: 'zh', transcript: '算了换个话题' }, + type: 'voice.asr.completed', + } as AssistantServerMessage); + await flushAsync(); + + expect(service.getMessages()).toEqual([ + { id: 'req_1:user', role: 'user', text: '明天几点开会' }, + { id: 'req_1:assistant', pending: true, role: 'assistant', text: '明天下午三' }, + { id: 'req_2:user', role: 'user', text: '算了换个话题' }, + ]); + + fake.emitMessage({ + conversation_id: 'conv_001', + request_id: 'req_1', + payload: { done: true, reply_id: 'reply_1', speech_text: '明天下午三点' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + await flushAsync(); + + expect(service.getMessages()).toEqual([ + { id: 'req_1:user', role: 'user', text: '明天几点开会' }, + { id: 'req_1:assistant', role: 'assistant', text: '明天下午三点' }, + { id: 'req_2:user', role: 'user', text: '算了换个话题' }, + ]); + }); + + it('does not let a later reply overwrite the previous completed turn', async () => { + // 改前实测的覆盖 bug:上一轮回复已完成(done=true)之后、下一轮转写还没到, + // 后一条回复先到达时会被写进"最后一条轮次",把上一条已完成的回复覆盖成 + // 跟后一条一样的内容。现在必须开一个占位轮挂住新回复,等它的转写到了再 + // 合并进同一轮。 + const fake = createFakeConnection(); + const deps = createDeps({ connection: fake.connection }); + const service = createService(deps); + + await startListening(fake, service); + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { duration_ms: 800, language: 'zh', transcript: '明天几点开会' }, + type: 'voice.asr.completed', + } as AssistantServerMessage); + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { done: false, reply_id: 'reply_1', speech_text: '明天下午三' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { done: true, reply_id: 'reply_1', speech_text: '明天下午三点' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + await flushAsync(); + expect(service.getMessages()).toEqual([ + { id: 'turn-0:user', role: 'user', text: '明天几点开会' }, + { id: 'turn-0:assistant', role: 'assistant', text: '明天下午三点' }, + ]); + + // 第二轮回复先于第二轮转写到达(转写晚到或被 VAD 跳过):上一条回复不能被覆盖。 + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { done: false, reply_id: 'reply_2', speech_text: '张' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + await flushAsync(); + expect(service.getMessages()).toEqual([ + { id: 'turn-0:user', role: 'user', text: '明天几点开会' }, + { id: 'turn-0:assistant', role: 'assistant', text: '明天下午三点' }, + { id: 'turn-1:assistant', pending: true, role: 'assistant', text: '张' }, + ]); + + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { done: true, reply_id: 'reply_2', speech_text: '张三' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + await flushAsync(); + + // 转写迟到:合并进占位轮,最终每条回复都挂在它自己的用户句下面。 + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { duration_ms: 500, language: 'zh', transcript: '谁参加' }, + type: 'voice.asr.completed', + } as AssistantServerMessage); + await flushAsync(); + + expect(service.getMessages()).toEqual([ + { id: 'turn-0:user', role: 'user', text: '明天几点开会' }, + { id: 'turn-0:assistant', role: 'assistant', text: '明天下午三点' }, + { id: 'turn-1:user', role: 'user', text: '谁参加' }, + { id: 'turn-1:assistant', role: 'assistant', text: '张三' }, + ]); + }); + + it('clears the streaming waveform when a barge-in arrives as tts.canceled without done', async () => { + // composed 代理打断回复时只发 voice.tts.canceled、不会再补 voice.dialogue.reply + // 的 done=true(realtime 代理会补)。改前 pending 只认 done=true,被打断那条 + // 气泡的波形会一直跳——回归:tts.canceled 也要摘掉波形。 + const fake = createFakeConnection(); + const deps = createDeps({ connection: fake.connection }); + const service = createService(deps); + + await startListening(fake, service); + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { duration_ms: 800, language: 'zh', transcript: '明天几点开会' }, + type: 'voice.asr.completed', + } as AssistantServerMessage); + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { done: false, reply_id: 'reply_1', speech_text: '明天下午三' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + await flushAsync(); + expect(service.getMessages()).toEqual([ + { id: 'turn-0:user', role: 'user', text: '明天几点开会' }, + { id: 'turn-0:assistant', pending: true, role: 'assistant', text: '明天下午三' }, + ]); + + // 用户开口打断:只收到 tts.canceled,没有 done=true。 + fake.emitMessage({ + audio_id: 'audio_001', + conversation_id: 'conv_001', + type: 'voice.tts.canceled', + } as AssistantServerMessage); + await flushAsync(); + + expect(service.getMessages()).toEqual([ + { id: 'turn-0:user', role: 'user', text: '明天几点开会' }, + { id: 'turn-0:assistant', role: 'assistant', text: '明天下午三' }, + ]); + expect(service.getState()).toEqual({ conversationId: 'conv_001', phase: 'interrupted' }); + }); + + it('does not let a reply after a barge-in overwrite the interrupted turn', async () => { + // 被打断的轮次不会再收到 done=true(tts.canceled 顶替它),如果不把 + // lastTurnReplyDone 标记成已收尾,下一轮抢跑的回复会被写进这条被打断的 + // 轮次,把它的部分回复整段覆盖成下一轮的答案。 + const fake = createFakeConnection(); + const deps = createDeps({ connection: fake.connection }); + const service = createService(deps); + + await startListening(fake, service); + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { duration_ms: 800, language: 'zh', transcript: '明天几点开会' }, + type: 'voice.asr.completed', + } as AssistantServerMessage); + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { done: false, reply_id: 'reply_1', speech_text: '明天下午三' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + await flushAsync(); + + // 打断:只收到 tts.canceled,没有 done=true。 + fake.emitMessage({ + audio_id: 'audio_001', + conversation_id: 'conv_001', + type: 'voice.tts.canceled', + } as AssistantServerMessage); + await flushAsync(); + + // 打断后用户立刻说新一句,新一句的回复先到,转写还没到——跟"回复抢跑" + // 那个已修的 bug 一样的时序,只是发生在被打断的轮次后面。 + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { done: false, reply_id: 'reply_2', speech_text: '张' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + await flushAsync(); + + expect(service.getMessages()).toEqual([ + { id: 'turn-0:user', role: 'user', text: '明天几点开会' }, + { id: 'turn-0:assistant', role: 'assistant', text: '明天下午三' }, + { id: 'turn-1:assistant', pending: true, role: 'assistant', text: '张' }, + ]); + + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { done: true, reply_id: 'reply_2', speech_text: '张三' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { duration_ms: 500, language: 'zh', transcript: '谁参加' }, + type: 'voice.asr.completed', + } as AssistantServerMessage); + await flushAsync(); + + expect(service.getMessages()).toEqual([ + { id: 'turn-0:user', role: 'user', text: '明天几点开会' }, + { id: 'turn-0:assistant', role: 'assistant', text: '明天下午三' }, + { id: 'turn-1:user', role: 'user', text: '谁参加' }, + { id: 'turn-1:assistant', role: 'assistant', text: '张三' }, + ]); + }); + it('records an assistant bubble even when a reply arrives before any transcript', async () => { const fake = createFakeConnection(); const deps = createDeps({ connection: fake.connection }); @@ -371,6 +661,85 @@ describe('AssistantContinuousConversationService', () => { expect(service.getMessages()).toEqual([{ id: 'reply_1', role: 'assistant', text: '好的' }]); }); + it('ignores a reply that arrives before any transcript with blank speech text', async () => { + const fake = createFakeConnection(); + const deps = createDeps({ connection: fake.connection }); + const service = createService(deps); + + await startListening(fake, service); + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { done: true, reply_id: 'reply_1', speech_text: ' ' }, + type: 'voice.dialogue.reply', + } as AssistantServerMessage); + await flushAsync(); + + expect(service.getMessages()).toEqual([]); + }); + + it('records a clarifying question as an orphan bubble when it arrives before any transcript', async () => { + // voice.dialogue.question 跟 voice.dialogue.reply 一样,正常流程不会先于 + // 任何 transcript 到达,但要是真的发生了,得挂到零散气泡列表兜底,而不是 + // 丢掉。同一个 question_id 再来一次要原地更新,不能变成两条气泡。 + const fake = createFakeConnection(); + const deps = createDeps({ connection: fake.connection }); + const service = createService(deps); + + await startListening(fake, service); + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { + candidates: [], + question_id: 'q_1', + question_kind: 'missing_field', + speech_text: '你是想订哪一天的会议室?', + }, + type: 'voice.dialogue.question', + } as AssistantServerMessage); + await flushAsync(); + + expect(service.getMessages()).toEqual([ + { id: 'q_1', role: 'assistant', text: '你是想订哪一天的会议室?' }, + ]); + + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { + candidates: [], + question_id: 'q_1', + question_kind: 'missing_field', + speech_text: '你是想订哪一天的会议室,上午还是下午?', + }, + type: 'voice.dialogue.question', + } as AssistantServerMessage); + await flushAsync(); + + expect(service.getMessages()).toEqual([ + { id: 'q_1', role: 'assistant', text: '你是想订哪一天的会议室,上午还是下午?' }, + ]); + }); + + it('ignores a question that arrives before any transcript with blank speech text', async () => { + const fake = createFakeConnection(); + const deps = createDeps({ connection: fake.connection }); + const service = createService(deps); + + await startListening(fake, service); + fake.emitMessage({ + conversation_id: 'conv_001', + payload: { + candidates: [], + question_id: 'q_1', + question_kind: 'missing_field', + speech_text: ' ', + }, + type: 'voice.dialogue.question', + } as AssistantServerMessage); + await flushAsync(); + + expect(service.getMessages()).toEqual([]); + }); + it('clears turn history when a new call starts', async () => { const fake = createFakeConnection(); const deps = createDeps({ connection: fake.connection }); diff --git a/frontend/tests/unit/features/assistant/presentation/VoiceCallScreen.test.tsx b/frontend/tests/unit/features/assistant/presentation/VoiceCallScreen.test.tsx index 69cb8f3c..dd0a6a7d 100644 --- a/frontend/tests/unit/features/assistant/presentation/VoiceCallScreen.test.tsx +++ b/frontend/tests/unit/features/assistant/presentation/VoiceCallScreen.test.tsx @@ -111,12 +111,22 @@ describe('VoiceCallScreen', () => { }); it('puts a live waveform inside the orb while listening or speaking', () => { - renderScreen({ status: 'listening' }); + // listening 但实际有声(麦克风电平抬起来)时显示声纹条。 + renderScreen({ soundLevel: -20, status: 'listening' }); expect(screen.getByTestId('voice-call-orb-wave')).toBeTruthy(); - renderScreen({ status: 'speaking', title: '正在回复' }); + renderScreen({ soundLevel: -30, status: 'speaking', title: '正在回复' }); expect(screen.getAllByTestId('voice-call-orb-wave').length).toBeGreaterThan(0); }); + it('hides the orb waveform in silence so dots do not keep bouncing after an answer', () => { + // 连续模式麦克风常开:回答结束、环境安静时声纹条必须消失,只留呼吸缩放, + // 否则看起来像回答结束后还有一串点点点一直跳。 + renderScreen({ status: 'listening' }); + expect(screen.queryByTestId('voice-call-orb-wave')).toBeNull(); + renderScreen({ soundLevel: -60, status: 'listening' }); + expect(screen.queryByTestId('voice-call-orb-wave')).toBeNull(); + }); + it('raises the center bars when the microphone is loud', () => { renderScreen({ soundLevel: -8, status: 'listening' }); diff --git a/frontend/tests/unit/features/assistant/presentation/usePinnedTranscriptScroll.test.ts b/frontend/tests/unit/features/assistant/presentation/usePinnedTranscriptScroll.test.ts index acb2b567..01fa84e7 100644 --- a/frontend/tests/unit/features/assistant/presentation/usePinnedTranscriptScroll.test.ts +++ b/frontend/tests/unit/features/assistant/presentation/usePinnedTranscriptScroll.test.ts @@ -92,6 +92,13 @@ describe('usePinnedTranscriptScroll', () => { jest.useRealTimers(); }); + // scrollToLatest 用双重 requestAnimationFrame 延后两帧,测试里把这两帧走完。 + function flushFrames() { + act(() => { + jest.advanceTimersByTime(40); + }); + } + it('pads short turns instead of asking ScrollView to pack them with flex-end', () => { const { result } = renderHook(() => usePinnedTranscriptScroll()); const scrollToEnd = jest.fn(); @@ -113,6 +120,7 @@ describe('usePinnedTranscriptScroll', () => { }); it('drops the spacer once turns overflow so chronological order stays top to bottom', () => { + jest.useFakeTimers(); const { result } = renderHook(() => usePinnedTranscriptScroll()); const scrollToEnd = jest.fn(); result.current.transcriptRef.current = { scrollToEnd } as unknown as ScrollView; @@ -121,12 +129,13 @@ describe('usePinnedTranscriptScroll', () => { result.current.onLayout(layoutEvent(400)); result.current.onTurnsLayout(layoutEvent(2000)); }); + flushFrames(); expect(result.current.topSpacer).toBe(0); - expect(scrollToEnd).toHaveBeenCalledWith({ animated: true }); + expect(scrollToEnd).toHaveBeenCalledWith({ animated: false }); }); - it('does not follow the latest turn after the user scrolls up', () => { + it('does not follow the latest turn after the user scrolls up and stops away from the bottom', () => { jest.useFakeTimers(); const { result } = renderHook(() => usePinnedTranscriptScroll()); const scrollToEnd = jest.fn(); @@ -136,24 +145,86 @@ describe('usePinnedTranscriptScroll', () => { result.current.onLayout(layoutEvent(400)); result.current.onTurnsLayout(layoutEvent(2000)); }); + flushFrames(); expect(scrollToEnd).toHaveBeenCalledTimes(1); + // 用户上滑到顶部附近放手:贴底标记必须在手势结束时按真实位置重新判定, + // 之后新内容不能再把列表拽回底部。 act(() => { + result.current.onScrollBeginDrag(); + result.current.onScrollEndDrag( + scrollEvent({ contentHeight: 2000, offsetY: 0, viewportHeight: 400 }), + ); jest.advanceTimersByTime(TRANSCRIPT_IDLE_MS); }); + expect(scrollToEnd).toHaveBeenCalledTimes(1); act(() => { - result.current.onScroll( - scrollEvent({ contentHeight: 2000, offsetY: 0, viewportHeight: 400 }), - ); + result.current.onTurnsLayout(layoutEvent(2200)); result.current.onContentSizeChange(390, 2200); + }); + flushFrames(); + + expect(scrollToEnd).toHaveBeenCalledTimes(1); + }); + + it('keeps following while the user is mid-drag even if content grows', () => { + jest.useFakeTimers(); + const { result } = renderHook(() => usePinnedTranscriptScroll()); + const scrollToEnd = jest.fn(); + result.current.transcriptRef.current = { scrollToEnd } as unknown as ScrollView; + + act(() => { + result.current.onLayout(layoutEvent(400)); + result.current.onTurnsLayout(layoutEvent(2000)); + }); + flushFrames(); + expect(scrollToEnd).toHaveBeenCalledTimes(1); + + act(() => { + result.current.onScrollBeginDrag(); result.current.onTurnsLayout(layoutEvent(2200)); + result.current.onContentSizeChange(390, 2200); }); + flushFrames(); + // 拖动中不抢滚动:不自动跳底。 expect(scrollToEnd).toHaveBeenCalledTimes(1); }); + it('cancels a queued scroll-to-bottom if the user starts dragging before it fires', () => { + // 改前回归:onContentSizeChange 排队的 scrollToEnd() 隔着两帧才执行, + // 执行前不会复查 interactingRef——如果用户在这两帧之内按下手指开始拖动, + // 排队的那次跳底照样会在拖动中途把内容摁回最下面。流式出字期间 + // onContentSizeChange 触发得很密集,这个窗口几乎连续重开,体感就是 + // "流式输出时完全无法上拉"。 + jest.useFakeTimers(); + const { result } = renderHook(() => usePinnedTranscriptScroll()); + const scrollToEnd = jest.fn(); + result.current.transcriptRef.current = { scrollToEnd } as unknown as ScrollView; + + act(() => { + result.current.onLayout(layoutEvent(400)); + result.current.onTurnsLayout(layoutEvent(2000)); + }); + flushFrames(); + expect(scrollToEnd).toHaveBeenCalledTimes(1); + scrollToEnd.mockClear(); + + act(() => { + // 流式吐字触发一次内容增长:排队一次跳底(两帧后才执行)。 + result.current.onTurnsLayout(layoutEvent(2200)); + result.current.onContentSizeChange(390, 2200); + // 排队好的跳底还没执行,用户已经按下手指开始上拉。 + result.current.onScrollBeginDrag(); + }); + flushFrames(); + + expect(scrollToEnd).not.toHaveBeenCalled(); + }); + it('follows the latest turn on content size change while still pinned', () => { + jest.useFakeTimers(); const { result } = renderHook(() => usePinnedTranscriptScroll()); const scrollToEnd = jest.fn(); result.current.transcriptRef.current = { scrollToEnd } as unknown as ScrollView; @@ -162,19 +233,22 @@ describe('usePinnedTranscriptScroll', () => { result.current.onLayout(layoutEvent(400)); result.current.onTurnsLayout(layoutEvent(2000)); }); + flushFrames(); scrollToEnd.mockClear(); act(() => { result.current.onContentSizeChange(390, 2100); }); + flushFrames(); - expect(scrollToEnd).toHaveBeenCalledWith({ animated: true }); + expect(scrollToEnd).toHaveBeenCalledWith({ animated: false }); }); it.each(['ios', 'android'] as const)( 'does not steal an upward drag on %s before the first onScroll', (os) => { Platform.OS = os; + jest.useFakeTimers(); const { result } = renderHook(() => usePinnedTranscriptScroll()); const scrollToEnd = jest.fn(); result.current.transcriptRef.current = { scrollToEnd } as unknown as ScrollView; @@ -183,6 +257,7 @@ describe('usePinnedTranscriptScroll', () => { result.current.onLayout(layoutEvent(400)); result.current.onTurnsLayout(layoutEvent(2000)); }); + flushFrames(); expect(scrollToEnd).toHaveBeenCalledTimes(1); act(() => { @@ -191,6 +266,7 @@ describe('usePinnedTranscriptScroll', () => { result.current.onTurnsLayout(layoutEvent(2200)); result.current.onContentSizeChange(390, 2200); }); + flushFrames(); expect(scrollToEnd).toHaveBeenCalledTimes(1); }, @@ -208,15 +284,27 @@ describe('usePinnedTranscriptScroll', () => { act(() => { result.current.onLayout(layoutEvent(400)); result.current.onTurnsLayout(layoutEvent(2000)); + }); + flushFrames(); + expect(scrollToEnd).toHaveBeenCalledTimes(1); + scrollToEnd.mockClear(); + + act(() => { result.current.onScrollBeginDrag(); result.current.onTurnsLayout(layoutEvent(2100)); }); - expect(scrollToEnd).toHaveBeenCalledTimes(1); + flushFrames(); + // 拖动期间内容继续长高也不抢滚动。 + expect(scrollToEnd).not.toHaveBeenCalled(); act(() => { - result.current.onMomentumScrollEnd(); + result.current.onMomentumScrollEnd( + scrollEvent({ contentHeight: 2100, offsetY: 1700, viewportHeight: 400 }), + ); }); - expect(scrollToEnd).toHaveBeenCalledTimes(2); + flushFrames(); + // 惯性滚动停在底部附近:贴底,恢复跟随并补跳到底部。 + expect(scrollToEnd).toHaveBeenCalledTimes(1); }, ); @@ -230,20 +318,33 @@ describe('usePinnedTranscriptScroll', () => { act(() => { result.current.onLayout(layoutEvent(400)); result.current.onTurnsLayout(layoutEvent(2000)); + }); + flushFrames(); + expect(scrollToEnd).toHaveBeenCalledTimes(1); + scrollToEnd.mockClear(); + + act(() => { result.current.onScrollBeginDrag(); - result.current.onScrollEndDrag(); + result.current.onScrollEndDrag( + scrollEvent({ contentHeight: 2000, offsetY: 1600, viewportHeight: 400 }), + ); result.current.onTurnsLayout(layoutEvent(2100)); }); - expect(scrollToEnd).toHaveBeenCalledTimes(1); + flushFrames(); + expect(scrollToEnd).not.toHaveBeenCalled(); + // 放手 180ms 后兜底恢复跟随:idle 计时器 + 双重 rAF 都要走完。 act(() => { jest.advanceTimersByTime(TRANSCRIPT_IDLE_MS); }); - expect(scrollToEnd).toHaveBeenCalledTimes(2); + flushFrames(); + expect(scrollToEnd).toHaveBeenCalledTimes(1); }); - it('ignores programmatic scroll so follow-latest does not unpin itself', () => { - Platform.OS = 'ios'; + it('does not unpin itself: programmatic content growth keeps following while pinned', () => { + // 改前回归:程序化 scrollToEnd 产生的 onScroll 事件被当成"用户滑走", + // pinnedRef 被置 false,之后新内容再也不自动跟随。现在贴底只在真实手势 + // 结束时判定,程序化增长不会改变贴底状态。 jest.useFakeTimers(); const { result } = renderHook(() => usePinnedTranscriptScroll()); const scrollToEnd = jest.fn(); @@ -253,14 +354,24 @@ describe('usePinnedTranscriptScroll', () => { result.current.onLayout(layoutEvent(400)); result.current.onTurnsLayout(layoutEvent(2000)); }); + flushFrames(); expect(scrollToEnd).toHaveBeenCalledTimes(1); + scrollToEnd.mockClear(); act(() => { - result.current.onScroll( - scrollEvent({ contentHeight: 2000, offsetY: 0, viewportHeight: 400 }), - ); - result.current.onTurnsLayout(layoutEvent(2100)); + result.current.onTurnsLayout(layoutEvent(2200)); + result.current.onContentSizeChange(390, 2200); + }); + flushFrames(); + // 贴底状态没有被程序化增长改掉:内容一变高就继续跳底。 + expect(scrollToEnd).toHaveBeenCalledTimes(2); + scrollToEnd.mockClear(); + + act(() => { + result.current.onTurnsLayout(layoutEvent(2400)); + result.current.onContentSizeChange(390, 2400); }); + flushFrames(); expect(scrollToEnd).toHaveBeenCalledTimes(2); }); });