diff --git a/src/components/ClaudeCodeSession.tsx b/src/components/ClaudeCodeSession.tsx index ff57445c..3a8424d4 100644 --- a/src/components/ClaudeCodeSession.tsx +++ b/src/components/ClaudeCodeSession.tsx @@ -248,57 +248,47 @@ const ClaudeCodeSessionInner: React.FC = ({ }); // ✅ Refactored: Use custom Hook for smart auto-scroll - const { parentRef, userScrolled, setUserScrolled, setShouldAutoScroll } = - useSmartAutoScroll({ - displayableMessages, - isLoading - }); + const { parentRef, contentRef, userScrolled, setUserScrolled, setShouldAutoScroll, isStuckToBottom } = + useSmartAutoScroll(); // Fix: Scroll to bottom when session history is loaded // Also re-trigger when message count changes significantly (e.g., streaming adds many messages) const hasScrolledToBottomRef = useRef(null); const lastScrolledMessageCountRef = useRef(0); + const sessionMessagesRef = useRef(null); useEffect(() => { - // Check if we have messages and parentRef is attached - if (displayableMessages.length > 0 && parentRef.current) { - const currentSessionId = session?.id || 'new_session'; - const currentCount = displayableMessages.length; - - // Determine if we should scroll: - // 1. First time for this session (initial history load) - const isFirstTimeForSession = hasScrolledToBottomRef.current !== currentSessionId; - // 2. Message count jumped significantly (e.g., streaming added many messages at once) - const countDelta = currentCount - lastScrolledMessageCountRef.current; - const significantCountChange = lastScrolledMessageCountRef.current > 0 && countDelta >= 5; - - if (isFirstTimeForSession || significantCountChange) { - // Use a small delay to ensure virtualizer has calculated sizes - const timer = setTimeout(() => { - if (parentRef.current) { - // Force scroll to bottom - parentRef.current.scrollTop = parentRef.current.scrollHeight; - - // Sync with smart auto-scroll state - setUserScrolled(false); - setShouldAutoScroll(true); - - // Mark as done for this session - hasScrolledToBottomRef.current = currentSessionId; - lastScrolledMessageCountRef.current = currentCount; - - // Schedule a follow-up scroll to handle virtualizer re-measurements - setTimeout(() => { - if (parentRef.current) { - parentRef.current.scrollTop = parentRef.current.scrollHeight; - } - }, 200); - } - }, 150); // 150ms delay for stability + if (displayableMessages.length === 0) return; - return () => clearTimeout(timer); - } - } + const currentSessionId = session?.id || 'new_session'; + const currentCount = displayableMessages.length; + + // Determine if we should scroll: + // 1. First time for this session (initial history load) + const isFirstTimeForSession = hasScrolledToBottomRef.current !== currentSessionId; + // 2. Message count jumped significantly (e.g., streaming added many messages at once) + const countDelta = currentCount - lastScrolledMessageCountRef.current; + const significantCountChange = lastScrolledMessageCountRef.current > 0 && countDelta >= 5; + + if (!isFirstTimeForSession && !significantCountChange) return; + + // Mark as done for this session + hasScrolledToBottomRef.current = currentSessionId; + lastScrolledMessageCountRef.current = currentCount; + + // Sync with smart auto-scroll state + setUserScrolled(false); + setShouldAutoScroll(true); + + // 交给虚拟列表的 scrollToBottom:它先把目标行渲染出来,再按真实 scrollHeight 落底。 + // 这里曾经直接写 parentRef.scrollTop = scrollHeight(还在 200ms 后补一次), + // 但那是在虚拟列表尚未测量出真实高度时写的,落点必然不对, + // 随后测量修正又把位置拉回去,就是肉眼看到的上下抖。 + const timer = setTimeout(() => { + sessionMessagesRef.current?.scrollToBottom(); + }, 50); + + return () => clearTimeout(timer); }, [displayableMessages.length, session?.id, setUserScrolled, setShouldAutoScroll]); // ============================================================================ @@ -323,7 +313,6 @@ const ClaudeCodeSessionInner: React.FC = ({ const unlistenRefs = useRef([]); const hasActiveSessionRef = useRef(false); const floatingPromptRef = useRef(null); - const sessionMessagesRef = useRef(null); const queuedPromptsRef = useRef>([]); const isMountedRef = useRef(true); const isListeningRef = useRef(false); @@ -976,6 +965,8 @@ const ClaudeCodeSessionInner: React.FC = ({ isLoading={isLoading} error={error} parentRef={parentRef} + contentRef={contentRef} + isStuckToBottom={isStuckToBottom} onCancel={handleCancelExecution} /> diff --git a/src/components/message/SubagentMessageGroup.tsx b/src/components/message/SubagentMessageGroup.tsx index 2da4df62..9ebadfec 100644 --- a/src/components/message/SubagentMessageGroup.tsx +++ b/src/components/message/SubagentMessageGroup.tsx @@ -7,7 +7,6 @@ import React, { useState } from "react"; import { Bot, ChevronDown, ChevronUp } from "lucide-react"; -import { motion, AnimatePresence } from "framer-motion"; import { cn } from "@/lib/utils"; import { AIMessage } from "./AIMessage"; import { UserMessage } from "./UserMessage"; @@ -117,16 +116,13 @@ export const SubagentMessageGroup: React.FC = ({ - {/* 子代理消息列表(可折叠) */} - - {isExpanded && ( - + {/* 子代理消息列表(可折叠) + 这里刻意不做 height 动画:这个块位于虚拟列表的行内部, + animate={{height:'auto'}} 会让行高连续多帧变化,而虚拟列表测量的 + 正是这个元素——每帧都要重测并重排后续所有行,同时反复触发贴底补偿。 + 展开/收起一次到位,只留一次高度变化。 */} + {isExpanded && ( +
{/* 渲染子代理消息 */} {subagentMessages.length > 0 ? ( @@ -177,9 +173,8 @@ export const SubagentMessageGroup: React.FC = ({
)}
-
- )} -
+ + )} ); diff --git a/src/components/message/ThinkingBlock.tsx b/src/components/message/ThinkingBlock.tsx index 7d3d3127..dd357b64 100644 --- a/src/components/message/ThinkingBlock.tsx +++ b/src/components/message/ThinkingBlock.tsx @@ -163,23 +163,26 @@ export const ThinkingBlock: React.FC = ({ - {/* Content - 可展开/收起 */} -
+ {/* Content - 可展开/收起 + 这里刻意不做高度动画(原来是 max-h-0 ↔ max-h-[500px] 配 transition-all): + 这个块在虚拟列表的行内部,高度动画意味着连续 300ms、每帧都在改行高, + 虚拟列表每帧都要重测并重排后续所有行,同时触发贴底逻辑反复补偿。 + 展开/收起一次到位,只留一次高度变化。 */} + {isOpen && (
-
- {renderContent()} +
+
+ {renderContent()} +
-
+ )}
); }; diff --git a/src/components/session/SessionMessages.tsx b/src/components/session/SessionMessages.tsx index f2a94cab..b201c8ee 100644 --- a/src/components/session/SessionMessages.tsx +++ b/src/components/session/SessionMessages.tsx @@ -1,5 +1,4 @@ -import React, { useImperativeHandle, forwardRef, useEffect, useRef } from "react"; -import { motion, AnimatePresence } from "framer-motion"; +import React, { useImperativeHandle, forwardRef } from "react"; import { useVirtualizer } from "@tanstack/react-virtual"; import { StreamMessageV2 } from "@/components/message"; import type { MessageGroup } from "@/lib/subagentGrouping"; @@ -7,67 +6,55 @@ import { useSession } from "@/contexts/SessionContext"; import { CliProcessingIndicator } from "./CliProcessingIndicator"; /** - * ✅ MeasurableItem: 自动监听高度变化的虚拟列表项 - * - * 使用 ResizeObserver 并在内容变化时自动通知虚拟列表重新测量。 - * 仅对正在流式输出的消息进行防抖,历史消息立即更新以防止滚动抖动。 + * 列表上下留白。 + * + * 这两段留白必须计入虚拟列表容器的高度,否则「容器高度」和「虚拟列表认为的总高度」 + * 不是同一个坐标系:虚拟列表会把最后一行放到 padding 之外,滚动高度与内容高度对不上, + * 底部就会出现一段滚不到内容的假空白。 */ -const MeasurableItem = ({ virtualItem, measureElement, isStreaming, children, ...props }: any) => { - const elRef = useRef(null); - const measureRef = useRef(measureElement); - - // 保持 measureElement 引用最新 - useEffect(() => { - measureRef.current = measureElement; - }, [measureElement]); - - useEffect(() => { - const el = elRef.current; - if (!el) return; - - // 初始测量 - 立即执行确保占位准确 - measureRef.current(el); - - let frameId: number; - - // 创建观察者 - const observer = new ResizeObserver(() => { - if (isStreaming) { - // ✅ 流式消息:使用防抖,避免每帧重绘导致的性能问题 - cancelAnimationFrame(frameId); - frameId = requestAnimationFrame(() => { - if (elRef.current) { - measureRef.current(elRef.current); - } - }); - } else { - // ✅ 历史消息:立即响应(通过 rAF 避免 Loop 错误),确保向上滚动时高度修正及时,减少抖动 - requestAnimationFrame(() => { - if (elRef.current) { - measureRef.current(elRef.current); - } - }); - } - }); - - observer.observe(el); +const GUTTER_TOP = 16; +const GUTTER_BOTTOM = 22; - return () => { - observer.disconnect(); - cancelAnimationFrame(frameId); - }; - }, [isStreaming]); // 添加 isStreaming 依赖 +/** + * 未测量行的初始高度估计。真实高度会在挂载后由 ResizeObserver 测量并覆盖。 + * 这里刻意用一个固定常量而不是按消息类型猜(原来 200/400/60 的猜法既不准又要遍历 + * 每条消息的子块,等于每次布局都做一遍 O(消息数) 的无用功)。 + */ +const DEFAULT_ESTIMATE = 200; - return ( - - {children} - - ); -}; +/** + * VirtualRow: 虚拟列表行。 + * + * 只做两件事:按 virtualItem.start 绝对定位,以及把元素交给虚拟列表的 measureElement。 + * + * 不需要自己写 ResizeObserver:传给 measureElement 时虚拟列表内部已经为每个元素 + * 建了一个 ResizeObserver,并且会把 entry.borderBoxSize 一起传进去算高度 + * (borderBoxSize 不受 transform 影响,比 getBoundingClientRect 更准)。 + * 原来这里额外挂了一层观察者,等于每行测两遍,属于白白的开销。 + * + * 也刻意不用 transform 做入场动画:位移看着是「每来一条新消息整列抖一下」, + * 而 scale 会污染高度测量。 + */ +const VirtualRow = ({ + index, + start, + measureElement, + children, +}: { + index: number; + start: number; + measureElement: (element: HTMLDivElement | null) => void; + children: React.ReactNode; +}) => ( +
+ {children} +
+); export interface SessionMessagesRef { scrollToPrompt: (promptIndex: number) => void; @@ -93,6 +80,10 @@ interface SessionMessagesProps { isLoading: boolean; error?: string | null; parentRef: React.RefObject; + /** 滚动内容容器,用于监听内容高度增长以保持贴底(由 useSmartAutoScroll 提供) */ + contentRef?: React.Ref; + /** 当前是否贴底(由 useSmartAutoScroll 提供),决定虚拟列表要不要自己补偿滚动位置 */ + isStuckToBottom?: () => boolean; /** 取消执行回调 - 用于CLI风格处理指示器 */ onCancel?: () => void; } @@ -102,6 +93,8 @@ export const SessionMessages = forwardRef { // ✅ 从 SessionContext 获取配置和回调,避免 Props Drilling @@ -112,92 +105,50 @@ export const SessionMessages = forwardRef parentRef.current, - estimateSize: (index) => { - // ✅ Dynamic height estimation based on message group type - const messageGroup = messageGroups[index]; - if (!messageGroup) return 200; - - // For subagent groups, estimate larger height - if (messageGroup.type === 'subagent') { - return 400; // Subagent groups are typically larger - } - - // For aggregated groups, estimate height based on content - if (messageGroup.type === 'aggregated') { - // Base height for bubble padding etc - let height = 60; - messageGroup.messages.forEach(msg => { - // Add height for thinking blocks - if (msg.type === 'thinking' || (msg.message?.content && Array.isArray(msg.message.content) && msg.message.content.some((c:any) => c.type === 'thinking'))) { - height += 100; - } - // Add height for tool calls - if (msg.message?.content && Array.isArray(msg.message.content)) { - const toolCalls = msg.message.content.filter((c:any) => c.type === 'tool_use'); - height += toolCalls.length * 60; - - // Add height for tool results (if visible) - const toolResults = msg.message.content.filter((c:any) => c.type === 'tool_result'); - height += toolResults.length * 40; - } - }); - return Math.max(height, 100); - } - - // For normal messages, estimate based on message type - const message = messageGroup.message; - if (!message) return 200; - - // Estimate different heights for different message types - if (message.type === 'system') return 80; // System messages are smaller - if (message.type === 'user') return 150; // User prompts are medium - if (message.type === 'assistant') { - // Assistant messages with code blocks are larger - const hasCodeBlock = message.content && typeof message.content === 'string' && - message.content.includes('```'); - return hasCodeBlock ? 300 : 200; - } - return 200; // Default fallback - }, - overscan: 12, // ✅ OPTIMIZED: Increased to 12 to prevent blank areas during fast scrolling - measureElement: (element) => { - // Ensure element is fully rendered before measurement - return element?.getBoundingClientRect().height ?? 200; - }, + estimateSize: () => DEFAULT_ESTIMATE, + // 多渲染几屏,避免快速滚动时进入尚未测量的区域而出现空白 + overscan: 12, + // 刻意不覆盖 measureElement:库默认实现会在可用时使用 ResizeObserver 的 + // borderBoxSize(不受 transform 影响),退回到 getBoundingClientRect 也够用。 + // 之前自定义成 getBoundingClientRect().height,会把入场动画的 scale 一起量进去, + // 导致每行先记一个偏小的高度、动画结束后再修正一次,看起来就是每来一条消息抖一下。 }); + // 行高变化时是否让虚拟列表自己补偿 scrollTop。 + // + // 注意这是 Virtualizer 实例上的属性,不是构造选项——3.13 的 resizeItem 只读 + // this.shouldAdjustScrollPositionOnItemSizeChange,不会从 options 取。 + // + // - 贴底时返回 false:此时位置由 useSmartAutoScroll 独家负责。否则流式输出的 + // 最后一行往往比视口还高,它的 start 一直小于 scrollTop,虚拟列表每测量一次 + // 就补偿一次,和贴底互相拉锯——表现就是原地上下抖。 + // - 用户翻历史时返回 true(走库的默认判断):否则上方某行一变高(工具结果加载完、 + // 图片撑开),用户正在看的内容就会被顶走。 + rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = isStuckToBottom + ? () => !isStuckToBottom() + : undefined; + useImperativeHandle(ref, () => ({ scrollToBottom: () => { if (messageGroups.length === 0) return; - // Use virtualizer's scrollToIndex for reliable scrolling to the last item + // 先让虚拟列表把目标行渲染出来(此时可能还在用估计高度) rowVirtualizer.scrollToIndex(messageGroups.length - 1, { align: 'end', behavior: 'auto', }); - // Schedule rAF-based follow-up scrolls to handle the virtualizer's - // progressive height re-measurements. After scrollToIndex renders the - // target items, the virtualizer measures their actual heights which may - // differ from estimates, shifting the total scrollHeight. - // Uses requestAnimationFrame to sync with rendering cycle and checks - // whether we actually reached the bottom before each follow-up scroll. - const followUpDelays = [50, 150, 300, 500]; - followUpDelays.forEach((delay) => { - setTimeout(() => { - requestAnimationFrame(() => { - if (parentRef.current) { - const { scrollTop, scrollHeight, clientHeight } = parentRef.current; - // Only scroll if we haven't reached the true bottom yet - if (scrollHeight - scrollTop - clientHeight > 1) { - parentRef.current.scrollTo({ - top: scrollHeight, - behavior: 'auto', - }); - } - } - }); - }, delay); + // 双 rAF 保证这一帧已经完成布局与测量,再按真实 scrollHeight 精确落底。 + // 原来用 50/150/300/500ms 四次定时器反复纠偏,每次都可能和流式输出的滚动打架。 + // 后续内容增长由 contentRef 上的 ResizeObserver 持续贴底,不再需要轮询。 + requestAnimationFrame(() => { + requestAnimationFrame(() => { + const el = parentRef.current; + if (!el) return; + if (el.scrollHeight - el.scrollTop - el.clientHeight > 1) { + el.scrollTo({ top: el.scrollHeight, behavior: 'auto' }); + } + }); }); }, scrollToPrompt: (promptIndex: number) => { @@ -294,22 +245,27 @@ export const SessionMessages = forwardRef -
- + {/* contentRef 覆盖 rail + 指示器 + 错误条的全部内容,高度变化时用于保持贴底 */} +
+
{rowVirtualizer.getVirtualItems().map((virtualItem) => { const messageGroup = messageGroups[virtualItem.index]; @@ -328,19 +284,11 @@ export const SessionMessages = forwardRef {/* ✅ 架构优化: StreamMessageV2 现在从 SessionContext 获取数据 */} - + ); })} - +
+ + {/* CLI风格的处理状态指示器 - 显示在消息列表底部 */} + 0} + onCancel={onCancel} + /> + + {/* Error indicator - 移除固定 marginBottom,因为输入框不再是 fixed 定位 */} + {error && ( +
+ {error} +
+ )}
- - {/* CLI风格的处理状态指示器 - 显示在消息列表底部 */} - 0} - onCancel={onCancel} - /> - - {/* Error indicator - 移除固定 marginBottom,因为输入框不再是 fixed 定位 */} - {error && ( - - {error} - - )}
); }); diff --git a/src/hooks/useSmartAutoScroll.ts b/src/hooks/useSmartAutoScroll.ts index 99cbd276..545e938c 100644 --- a/src/hooks/useSmartAutoScroll.ts +++ b/src/hooks/useSmartAutoScroll.ts @@ -1,253 +1,199 @@ /** * 智能自动滚动 Hook * - * 从 ClaudeCodeSession 提取(原 166-170 状态,305-435 逻辑) - * 提供智能滚动管理:用户手动滚动检测、自动滚动到底部、流式输出滚动 + * 设计原则(重构后): + * + * 1. **只有一个滚动驱动源**。原实现有 5 个 useEffect 同时抢着写 scrollTop—— + * 一个 100ms 的 rAF 循环、一个 8 次的 setInterval、两个 hash 触发的延迟滚动, + * 还混着 behavior:'smooth' 和 'auto'。任何一个正在跑的平滑动画都会被下一个 + * 写操作打断,于是列表就一直在上下抖。现在改为:内容高度变化(ResizeObserver) + * → 瞬时贴底,仅此一条路径。 + * + * 2. **只用瞬时滚动**。smooth 滚动是异步的,滚到一半又被重新定目标就会来回晃。 + * 自动贴底一律 scrollTop = scrollHeight。用户主动触发的滚动 + * (跳到底部按钮、跳到某个 prompt)仍然可以用 smooth,因为那时没有竞争写入者。 + * + * 3. **"用户是否离开了底部"只能靠真实输入事件判断,不能靠距底部的距离**。 + * 这一条是踩过坑的:初始加载时虚拟列表会把估计高度逐行换成实测高度, + * rail 每帧能变化几百像素;流式输出时最后一行也在持续长高。这两种情况下 + * "距底部距离"每帧都会超出容差,如果拿它当"用户在翻历史"的依据, + * 就会在第一次贴底之后立刻把自己关掉,之后再也不跟随输出。 + * 现在只监听 wheel / touch / 滚动条拖拽 / 翻页键,程序自身和内容增长 + * 引起的位置变化一律不改判定。 + * + * 4. **不再对最后一条消息做 JSON.stringify 算哈希**。原实现每次渲染都要把整条消息 + * 序列化一遍求长度,流式输出时每个 chunk 都触发一次,既浪费又会引发一次延迟的 + * 平滑滚动。现在改用 ResizeObserver 观察真实高度。 */ -import { useRef, useState, useEffect, useMemo } from 'react'; -import type { ClaudeStreamMessage } from '@/types/claude'; +import { useCallback, useEffect, useRef, useState } from 'react'; -interface SmartAutoScrollConfig { - /** 可显示的消息列表(用于触发滚动) */ - displayableMessages: ClaudeStreamMessage[]; - /** 是否正在加载(流式输出时) */ - isLoading: boolean; -} +/** 距离底部多少像素以内算“已经贴底” */ +const BOTTOM_TOLERANCE = 24; -/** - * 计算消息的内容哈希,用于检测内容变化 - */ -function getLastMessageContentHash(messages: ClaudeStreamMessage[]): string { - if (messages.length === 0) return ''; - const lastMsg = messages[messages.length - 1]; - // 简单地使用内容长度和类型作为哈希 - const contentLength = JSON.stringify(lastMsg.message?.content || '').length; - return `${messages.length}-${lastMsg.type}-${contentLength}`; -} +/** 一次用户输入之后多久内发生的滚动,算作用户滚动 */ +const GESTURE_WINDOW_MS = 250; + +/** 会直接改变滚动位置的按键 */ +const SCROLL_KEYS = new Set([ + 'ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' ', +]); interface SmartAutoScrollReturn { /** 滚动容器 ref */ parentRef: React.RefObject; + /** 滚动内容容器 ref(回调式,由 SessionMessages 挂在内容包装元素上) */ + contentRef: (node: HTMLDivElement | null) => void; /** 用户是否手动滚动离开底部 */ userScrolled: boolean; /** 设置用户滚动状态 */ setUserScrolled: (scrolled: boolean) => void; /** 设置自动滚动状态 */ setShouldAutoScroll: (should: boolean) => void; + /** + * 当前是否贴底(读 ref,不触发渲染)。 + * + * 虚拟列表需要它来决定"行高变化时要不要自动补偿滚动位置": + * 贴底时由本 hook 负责位置,虚拟列表再补偿一次就会和贴底互相打架; + * 用户翻历史时则相反,必须让虚拟列表补偿,否则上面的行一旦变高, + * 用户正在看的内容就会被顶走。 + */ + isStuckToBottom: () => boolean; } /** * 智能自动滚动 Hook * - * @param config - 配置对象 - * @returns 滚动管理对象 - * * @example - * const { parentRef, userScrolled, setUserScrolled, shouldAutoScroll, setShouldAutoScroll } = - * useSmartAutoScroll({ - * displayableMessages, - * isLoading - * }); + * const { parentRef, contentRef, userScrolled, setUserScrolled, setShouldAutoScroll } = + * useSmartAutoScroll(); */ -export function useSmartAutoScroll(config: SmartAutoScrollConfig): SmartAutoScrollReturn { - const { displayableMessages, isLoading } = config; - - // Scroll state - const [userScrolled, setUserScrolled] = useState(false); - const [shouldAutoScroll, setShouldAutoScroll] = useState(true); +export function useSmartAutoScroll(): SmartAutoScrollReturn { + const [userScrolled, setUserScrolledState] = useState(false); - // Refs const parentRef = useRef(null); - const lastScrollPositionRef = useRef(0); - const isAutoScrollingRef = useRef(false); // Track if scroll was initiated by code - const autoScrollTimerRef = useRef | null>(null); // Timer for resetting auto-scroll flag - const prevMessageCountRef = useRef(0); // Track previous message count for new message detection - - // 计算最后一条消息的内容哈希,用于检测内容变化 - const lastMessageHash = useMemo( - () => getLastMessageContentHash(displayableMessages), - [displayableMessages] - ); - - // Helper to perform auto-scroll safely - const performAutoScroll = (behavior: ScrollBehavior = 'smooth') => { - if (parentRef.current) { - const scrollElement = parentRef.current; - // Check if we actually need to scroll to avoid unnecessary events - const { scrollTop, scrollHeight, clientHeight } = scrollElement; - const targetScrollTop = scrollHeight - clientHeight; - - if (Math.abs(scrollTop - targetScrollTop) > 1) { // Small tolerance - // Set the flag and use a timeout to reset it, avoiding race conditions - // where a single scrollTo triggers multiple scroll events - isAutoScrollingRef.current = true; - if (autoScrollTimerRef.current) { - clearTimeout(autoScrollTimerRef.current); - } - // Use longer timeout for smooth scrolling to cover the animation duration (~300ms), - // preventing false "user scrolled" detections from animation-triggered scroll events. - // Use shorter timeout for instant scrolling to allow quick user scroll detection. - const flagTimeout = behavior === 'smooth' ? 300 : 80; - autoScrollTimerRef.current = setTimeout(() => { - isAutoScrollingRef.current = false; - autoScrollTimerRef.current = null; - }, flagTimeout); - - scrollElement.scrollTo({ - top: targetScrollTop, - behavior - }); - } + /** 是否处于"贴底"状态。作为唯一事实来源,避免它和 state 不同步 */ + const stuckRef = useRef(true); + const observerRef = useRef(null); + /** 最近一次真实用户输入的时间戳 */ + const lastGestureRef = useRef(-Infinity); + /** 是否正按着鼠标(拖滚动条时 pointermove 可能收不到) */ + const pointerDownRef = useRef(false); + + /** 瞬时贴底。没有竞争写入者时不做多余操作。 */ + const stickToBottom = useCallback(() => { + const el = parentRef.current; + if (!el || !stuckRef.current) return; + // scrollTop 会被浏览器 clamp 到最大值,直接赋值即可 + if (el.scrollHeight - el.scrollTop - el.clientHeight > 1) { + el.scrollTop = el.scrollHeight; } - }; + }, []); - // Smart scroll detection - detect when user manually scrolls + /** + * 内容高度变化的监听挂在"内容包装元素"上,而不是滚动容器本身: + * 滚动容器的高度是固定的,内容包装元素才会随消息增长。 + * 用回调 ref 而不是 RefObject,是为了在 SessionMessages 条件挂载/重新挂载时 + * 都能正确接上观察者。 + */ + const contentRef = useCallback((node: HTMLDivElement | null) => { + observerRef.current?.disconnect(); + observerRef.current = null; + if (!node) return; + + const observer = new ResizeObserver(() => { + // ResizeObserver 回调在布局之后、绘制之前执行,这里写 scrollTop 不会闪烁 + stickToBottom(); + }); + observer.observe(node); + observerRef.current = observer; + }, [stickToBottom]); + + // 监听用户滚动,维护贴底状态 useEffect(() => { - const scrollElement = parentRef.current; - if (!scrollElement) return; + const el = parentRef.current; + if (!el) return; - const handleScroll = () => { - // 1. Check if this scroll event was triggered by our auto-scroll - // The flag is now reset via timeout, so all events within the timeout window are ignored - if (isAutoScrollingRef.current) { - lastScrollPositionRef.current = scrollElement.scrollTop; - return; - } + const markGesture = () => { + lastGestureRef.current = performance.now(); + }; + const onKeyDown = (e: KeyboardEvent) => { + if (SCROLL_KEYS.has(e.key)) markGesture(); + }; + const onPointerDown = () => { + pointerDownRef.current = true; + markGesture(); + }; + const onPointerUp = () => { + pointerDownRef.current = false; + }; - const { scrollTop, scrollHeight, clientHeight } = scrollElement; - - // 2. Calculate distance from bottom - const distanceFromBottom = scrollHeight - scrollTop - clientHeight; - // Use a forgiving threshold (150px) to account for virtualizer measurement errors - const isAtBottom = distanceFromBottom <= 150; - - // 3. Determine user intent - // If user is not at bottom, they are viewing history -> Stop auto scroll - if (!isAtBottom) { - setUserScrolled(true); - setShouldAutoScroll(false); - } else { - // User is at bottom (or scrolled back to bottom) -> Resume auto scroll - setUserScrolled(false); - setShouldAutoScroll(true); + const handleScroll = () => { + const node = parentRef.current; + if (!node) return; + + // 只有用户真的在操作时才重新判定;内容增长、虚拟列表重测、 + // 以及本 hook 自己的贴底写入都不改变贴底状态 + const isUserDriven = pointerDownRef.current + || performance.now() - lastGestureRef.current < GESTURE_WINDOW_MS; + if (!isUserDriven) return; + + const distance = node.scrollHeight - node.scrollTop - node.clientHeight; + const atBottom = distance <= BOTTOM_TOLERANCE; + if (atBottom !== stuckRef.current) { + stuckRef.current = atBottom; + setUserScrolledState(!atBottom); } - - lastScrollPositionRef.current = scrollTop; }; - scrollElement.addEventListener('scroll', handleScroll, { passive: true }); + el.addEventListener('wheel', markGesture, { passive: true }); + el.addEventListener('touchstart', markGesture, { passive: true }); + el.addEventListener('touchmove', markGesture, { passive: true }); + el.addEventListener('pointerdown', onPointerDown, { passive: true }); + el.addEventListener('keydown', onKeyDown); + el.addEventListener('scroll', handleScroll, { passive: true }); + window.addEventListener('pointerup', onPointerUp); + window.addEventListener('pointercancel', onPointerUp); return () => { - scrollElement.removeEventListener('scroll', handleScroll); + el.removeEventListener('wheel', markGesture); + el.removeEventListener('touchstart', markGesture); + el.removeEventListener('touchmove', markGesture); + el.removeEventListener('pointerdown', onPointerDown); + el.removeEventListener('keydown', onKeyDown); + el.removeEventListener('scroll', handleScroll); + window.removeEventListener('pointerup', onPointerUp); + window.removeEventListener('pointercancel', onPointerUp); }; - }, []); // Empty deps - event listener only needs to be registered once + }, []); - // Cleanup timer on unmount + // 卸载时断开观察者 useEffect(() => { return () => { - if (autoScrollTimerRef.current) { - clearTimeout(autoScrollTimerRef.current); - } + observerRef.current?.disconnect(); + observerRef.current = null; }; }, []); - // Track message count changes and auto-enable scroll when new messages appear - useEffect(() => { - const currentCount = displayableMessages.length; - const prevCount = prevMessageCountRef.current; - prevMessageCountRef.current = currentCount; - - // When new messages arrive (count increased) and we were near the bottom, re-enable auto-scroll - if (currentCount > prevCount && prevCount > 0) { - if (parentRef.current) { - const { scrollTop, scrollHeight, clientHeight } = parentRef.current; - const distanceFromBottom = scrollHeight - scrollTop - clientHeight; - // If user was within a generous range of the bottom, re-enable auto-scroll - if (distanceFromBottom <= 300) { - setUserScrolled(false); - setShouldAutoScroll(true); - } - } - } - }, [displayableMessages.length]); - - // Smart auto-scroll for new messages (initial load or update) - // Uses lastMessageHash instead of displayableMessages.length to ensure - // content changes during streaming also trigger scrolling - useEffect(() => { - if (displayableMessages.length > 0 && shouldAutoScroll && !userScrolled) { - const timeoutId = setTimeout(() => { - // Use rAF to ensure scroll happens after DOM updates are painted - requestAnimationFrame(() => performAutoScroll()); - }, 100); - - return () => clearTimeout(timeoutId); - } - }, [lastMessageHash, shouldAutoScroll, userScrolled]); - - // Enhanced streaming scroll - use requestAnimationFrame for smoother - // rendering-synced scrolling instead of raw setInterval. - // rAF ensures scroll operations align with the browser's paint cycle, - // reducing jank and improving coordination with the virtualizer. - useEffect(() => { - if (isLoading && shouldAutoScroll && !userScrolled) { - // Immediate scroll on update - performAutoScroll('auto'); - - // rAF-based loop throttled to ~100ms for rendering-synced scroll updates - let rafId: number; - let lastScrollTime = 0; - - const tick = (timestamp: number) => { - if (timestamp - lastScrollTime >= 100) { - performAutoScroll('auto'); - lastScrollTime = timestamp; - } - rafId = requestAnimationFrame(tick); - }; - - rafId = requestAnimationFrame(tick); - - return () => cancelAnimationFrame(rafId); - } - }, [isLoading, shouldAutoScroll, userScrolled]); - - // 当消息内容变化时触发额外滚动(确保流式输出时跟踪最新内容) - // 进入历史会话/初次渲染时,虚拟列表的测量会在短时间内不断修正高度,导致首次滚动不到真正的底部。 - // 在非流式状态下提供一个短暂的"粘底"窗口,确保最终停在最新消息处。 - useEffect(() => { - if (isLoading) return; - if (!shouldAutoScroll || userScrolled || displayableMessages.length === 0) return; - - let ticks = 0; - const intervalId = setInterval(() => { - ticks += 1; - // Use rAF to sync scroll with the rendering cycle, ensuring the - // virtualizer's height re-measurements are applied before scrolling - requestAnimationFrame(() => performAutoScroll('auto')); - if (ticks >= 8) { - clearInterval(intervalId); - } - }, 100); + // 对外保持原有的语义:external(false) = 停止自动滚动并标记为用户滚动 + const setUserScrolled = useCallback((scrolled: boolean) => { + stuckRef.current = !scrolled; + setUserScrolledState(scrolled); + }, []); - return () => clearInterval(intervalId); - }, [lastMessageHash, isLoading, shouldAutoScroll, userScrolled, displayableMessages.length]); + const setShouldAutoScroll = useCallback((should: boolean) => { + stuckRef.current = should; + if (should) setUserScrolledState(false); + }, []); - useEffect(() => { - if (shouldAutoScroll && !userScrolled && displayableMessages.length > 0) { - // 使用 requestAnimationFrame 确保在 DOM 更新后滚动 - const frameId = requestAnimationFrame(() => { - performAutoScroll(); - }); - return () => cancelAnimationFrame(frameId); - } - }, [lastMessageHash]); + const isStuckToBottom = useCallback(() => stuckRef.current, []); return { parentRef, + contentRef, userScrolled, setUserScrolled, - setShouldAutoScroll + setShouldAutoScroll, + isStuckToBottom, }; }