Diagnosing and fixing the chat auto-scroll layout jitter (the 'shake bug')
How unthrottled DOM scroll calls during LLM token streaming created competing animation frames, sub-pixel layout jitter, and scroll hijacking—and how rAF batching resolved it.
The Problem & Symptoms
When adding real streaming token output to the /chat console, users noticed a severe visual defect: whenever the assistant streamed a long markdown response or emitted tool-call blocks, the message thread would violently jitter and shake vertically by 2 to 6 pixels per frame. Worse, if the operator tried to scroll up to inspect a previously generated JSON schema or tool result, the container would aggressively fight their scrollwheel and snap back to the bottom.
Root Cause Diagnosis
The Implemented Fix
// app/(content)/chat/page.tsx
const handleScroll = React.useCallback(() => {
const el = scrollContainerRef.current;
if (!el) return;
const distanceToBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
// Yield auto-scroll if operator has scrolled up to inspect previous content
isAtBottomRef.current = distanceToBottom <= 80;
}, []);
const scheduleScrollToBottom = React.useCallback((force: boolean = false) => {
if (!force && !isAtBottomRef.current) return;
if (rafScrollIdRef.current !== null) {
cancelAnimationFrame(rafScrollIdRef.current);
}
rafScrollIdRef.current = requestAnimationFrame(() => {
rafScrollIdRef.current = null;
const el = scrollContainerRef.current;
if (!el) return;
if (force || isAtBottomRef.current) {
el.scrollTo({
top: el.scrollHeight,
behavior: "smooth",
});
}
});
}, []);