From 01accc005e10e469f19a351541dba3b89a6bcb32 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Feb 2026 15:51:14 -0800 Subject: [PATCH] Defer chat auto-scroll to animation frame - Queue tail-to-bottom scrolling with `requestAnimationFrame` to avoid redundant scroll calls - Preserve user scroll position by checking auto-scroll intent before running - Cancel any pending frame on unmount to prevent stale callbacks --- apps/web/src/components/ChatView.tsx | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 6d2a06561a..de86991812 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -402,6 +402,7 @@ export default function ChatView({ threadId }: ChatViewProps) { >(() => readLastInvokedScriptByProjectFromStorage()); const messagesScrollRef = useRef(null); const shouldAutoScrollRef = useRef(true); + const pendingAutoScrollFrameRef = useRef(null); const textareaRef = useRef(null); const composerCommandInputRef = useRef(null); const composerImagesRef = useRef([]); @@ -1102,6 +1103,14 @@ export default function ChatView({ threadId }: ChatViewProps) { scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, behavior }); shouldAutoScrollRef.current = true; }, []); + const requestAutoTailToBottom = useCallback(() => { + if (pendingAutoScrollFrameRef.current !== null) return; + pendingAutoScrollFrameRef.current = window.requestAnimationFrame(() => { + pendingAutoScrollFrameRef.current = null; + if (!shouldAutoScrollRef.current) return; + scrollMessagesToBottom(); + }); + }, [scrollMessagesToBottom]); const onMessagesScroll = useCallback(() => { const scrollContainer = messagesScrollRef.current; if (!scrollContainer) return; @@ -1113,8 +1122,16 @@ export default function ChatView({ threadId }: ChatViewProps) { }, [activeThread?.id, scrollMessagesToBottom]); useLayoutEffect(() => { if (!shouldAutoScrollRef.current) return; - scrollMessagesToBottom(); - }, [activeThread?.messages, workLogCount, scrollMessagesToBottom]); + requestAutoTailToBottom(); + }, [activeThread?.messages, workLogCount, requestAutoTailToBottom]); + useEffect( + () => () => { + if (pendingAutoScrollFrameRef.current === null) return; + window.cancelAnimationFrame(pendingAutoScrollFrameRef.current); + pendingAutoScrollFrameRef.current = null; + }, + [], + ); useEffect(() => { setExpandedWorkGroups({});