Mental model
Auto-scroll pinning treats following the newest output as a user-controlled mode. A chat view follows each rendered growth only while its distance from the bottom stays within a small tolerance; once the reader moves upward, the client preserves that viewport and exposes a deliberate jump-to-latest control. Reaching the bottom or activating that control restores follow mode.
The stream protocol delivers incremental message parts, but a UI should not issue a scroll command for every token. Layout may update several times before a frame is painted. Observe the transcript's rendered size and coalesce follow-up work to one animation frame. Keep the scroll container stable across UI rerenders so the scroll position and mode belong to the same object.
Theory
For a normal top-to-bottom scroll container, define its distance from the end as:
Here, is scrollHeight in CSS pixels, is clientHeight in CSS pixels, and is scrollTop in CSS pixels. Clamp small negative results to zero because subpixel positions and browser rounding can put the measured bottom a fraction of a pixel past the calculated end. The view is pinned when , where is a small pixel tolerance such as 56 px. Choose it from interaction testing; it is not a model-latency threshold.
This explicit mode matters because distance alone is not enough. As chunks append below an old reading position, the gap grows. The user has already indicated that they are reading older output, so the client must not chase that growing gap. If the reader scrolls back close to the end, or presses the return control, following becomes active again.
CSS scroll anchoring addresses a related but different problem. When content above the viewport changes size, a browser may adjust the scroll position to keep an anchor node visually stable. That behavior protects the current reading position; it does not mean “follow the newest message.” Let normal anchoring handle layout changes while the reader is paused, and avoid adding a second global correction that fights it. When following, an explicit write to scrollTop after the transcript grows has a clear owner and purpose.
For example, a transcript with px, a viewport of px, and px has px. With px, it is close enough to be considered pinned. If a streamed paragraph adds 320 px, one coalesced update sets the position to the new end, px. If the reader instead scrolls upward to px, the gap becomes 630 px and the follow mode pauses. A “Latest response” button gives the reader a predictable way to resume.
Trade-offs
| Choice | When it fits | Cost to watch |
|---|---|---|
| Follow every layout change | A response is short and the reader stays at the end | Repeated smooth animations can lag behind tokens and make the viewport feel slippery |
| Follow only while pinned | Long answers, code blocks, or citations can move older content out of view | Needs a visible return control and careful resume behavior |
| Browser scroll anchoring | Images or earlier messages can resize above a paused viewport | It preserves an anchor; it does not select the newest message for the user |
Use instant position correction during token streaming. Smooth scrolling on every chunk can continuously restart an animation, so the viewport may never arrive at the target. Reserve smooth motion for an intentional “jump to latest” action if that motion is acceptable and does not fight reduced-motion preferences. The button should be a real keyboard-focusable button with a label; visual placement at the bottom alone is not an accessible interaction.
The code below assumes a normal vertical scroll container, a stable transcript element, and an accessible notice button already present in the UI. It measures upward movement to pause, resumes when the measured gap is small, and coalesces content-resize updates. The scrollport should be focusable if the application expects Page Up or Home to control it.
Implementation pattern
typescriptexport function bindStreamFollower(scrollport: HTMLElement,transcript: HTMLElement,latestButton: HTMLButtonElement,thresholdPx = 56,) {let following = false;let frame = 0;let previousTop = scrollport.scrollTop;const gapToEnd = () =>Math.max(0, scrollport.scrollHeight - scrollport.clientHeight - scrollport.scrollTop);const revealLatest = () => {following = true;latestButton.hidden = true;scrollport.scrollTop = scrollport.scrollHeight;};const pauseFollowing = () => {following = false;latestButton.hidden = false;};const scheduleFollow = () => {if (!following || frame !== 0) return;frame = requestAnimationFrame(() => {frame = 0;scrollport.scrollTop = scrollport.scrollHeight;});};const onScroll = () => {if (gapToEnd() <= thresholdPx) following = true;else if (scrollport.scrollTop < previousTop - 1) pauseFollowing();latestButton.hidden = following;previousTop = scrollport.scrollTop;};const onWheel = (event: WheelEvent) => {if (event.deltaY < 0) pauseFollowing();};const onKeyDown = (event: KeyboardEvent) => {if (["PageUp", "Home", "ArrowUp"].includes(event.key)) pauseFollowing();};const observer = new ResizeObserver(scheduleFollow);observer.observe(transcript);scrollport.addEventListener("scroll", onScroll, { passive: true });scrollport.addEventListener("wheel", onWheel, { passive: true });scrollport.addEventListener("keydown", onKeyDown);latestButton.addEventListener("click", revealLatest);revealLatest();return () => {observer.disconnect();cancelAnimationFrame(frame);scrollport.removeEventListener("scroll", onScroll);scrollport.removeEventListener("wheel", onWheel);scrollport.removeEventListener("keydown", onKeyDown);latestButton.removeEventListener("click", revealLatest);};}
Failure modes and misconceptions
- The transcript is replaced on each token. Recreating the scrollport resets its geometry and can drop focus. Keep the scrollport stable and append or reconcile content inside it.
- New content arrives while the reader is paused. Do not move the viewport. Keep the return button visible, and ensure its action scrolls to the current end rather than to the position captured when the button first appeared.
- A smooth scroll is restarted for every token. Use one frame-coalesced instant write while following; use motion only for a discrete user action.
- A reverse flex column or nested scroller is used. The simple distance formula assumes normal vertical flow and the measured element must be the actual scroll owner. Verify the relevant geometry for any reversed layout or nested panel.
- Scroll anchoring is disabled globally to make the view “stable.” That can make images or earlier messages jump while the reader is paused. Change anchoring only for a demonstrated local conflict, then test the saved reading position.
Test a long response while the reader remains pinned, scroll upward during generation, resize an image in an earlier message, use Page Up and the return button, and unmount the component. Assert that a paused viewport does not move, a pinned viewport ends at the latest content, and cleanup disconnects both listeners and the observer.
Decision scenario
A user has scrolled 500 px above the end of a long answer when a tool result adds a large table. The product requirement says new answers should be easy to find without hiding the paragraph being read. Keep follow mode paused, preserve the browser's anchor behavior, and show the “Latest response” control. Resume only after the user returns near the end or activates the button.
Learning outcomes
- Compute distance to the end from scrollHeight, clientHeight, and scrollTop.
- Separate browser anchoring, which protects the viewport, from product follow mode, which tracks new output.
- Coalesce resize-driven scroll writes and pause them when the reader moves upward.
- Verify keyboard return controls, resize behavior, and cleanup as part of the chat interaction.