:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop/sessions): stop threads yanking readers back to the bottom (#78603)
Adam Leithd36ce8b1cfe2
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsxindex 1a7f55a7938d..84826ecfccce 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx@@ -68,8 +68,13 @@ import {completedTurnTimestamp,countFlatRows,type FlatThreadRow,+ FOLLOWING_END,flattenTurnRows,+ nextThreadFollowState,SCROLL_PREVIOUS_ITEM_PEEK,+ SCROLL_UP_KEYS,+ sampleThreadScroll,+ type ThreadFollowState,type ThreadItem,type ThreadScrollResume,type TurnRow,@@ -740,7 +745,7 @@ const ThreadRow = memo(function ThreadRow({});/**- * Keeps the view pinned to the bottom from prompt submit until the user scrolls away.+ * Keeps the view pinned to the bottom until the user scrolls away, re-arming on each prompt submit.** The engine's own follow mode isn't enough on its own:* - It only re-engages within `scrollEdgeThreshold` of the exact bottom, so a submit from anywhere@@ -751,10 +756,20 @@ const ThreadRow = memo(function ThreadRow({* autoscrolling" and silently demote itself to `free-scrolling` mid-reply. While armed, any* commit that leaves content below the fold re-issues `scrollToEnd` to recapture follow.*- * User scroll intent (wheel, touch, pointer, keys — same signals the engine listens to) disarms- * the pin; the next submit or the scroll-to-bottom button re-engages following.+ * It arms on mount so a thread the reader is only watching — a cloud task streaming into a command+ * center panel, with no prompt sent from here — still follows. Scrolling upward disarms it, which+ * is the half the engine gets wrong: the engine re-derives follow from scroll position and so+ * overrules the gesture. Scrolling back down to the end re-arms it, a submit or the+ * scroll-to-bottom button re-arms it from anywhere.*/-function ThreadAutoFollow({ items }: { items: ConversationItem[] }) {+function ThreadAutoFollow({+ items,+ followRef,+}: {+ items: ConversationItem[];+ /** Owned by the body so the scroll-to-bottom button can re-arm the pin too. */+ followRef: RefObject<ThreadFollowState>;+}) {const { scrollToEnd } = useChatMessageScroller();const { end } = useChatMessageScrollerScrollable();const lastItem = items.at(-1);@@ -764,7 +779,6 @@ function ThreadAutoFollow({ items }: { items: ConversationItem[] }) {[items],);const prevCountRef = useRef(userMessageCount);- const armedRef = useRef(false);const probeRef = useRef<HTMLSpanElement>(null);useLayoutEffect(() => {@@ -772,35 +786,55 @@ function ThreadAutoFollow({ items }: { items: ConversationItem[] }) {prevCountRef.current = userMessageCount;if (previous === 0 || userMessageCount <= previous) return;if (lastItem?.type !== "user_message") return;- armedRef.current = true;+ followRef.current = FOLLOWING_END;scrollToEnd({ behavior: "auto" });- }, [userMessageCount, lastItem, scrollToEnd]);+ }, [userMessageCount, lastItem, scrollToEnd, followRef]);useEffect(() => {const viewport = probeRef.current?.closest('[data-slot="chat-message-scroller"]')?.querySelector('[data-slot="chat-message-scroller-viewport"]');- if (!viewport) return;- const disarm = () => {- armedRef.current = false;+ if (!(viewport instanceof HTMLElement)) return;++ // An upward gesture too small to register as a direction change below still means the reader+ // is reading, not following.+ const leaveEnd = () => {+ if (followRef.current.leftEnd || viewport.scrollTop <= 0) return;+ followRef.current = { following: false, leftEnd: true };};- const events = ["wheel", "touchmove", "pointerdown", "keydown"] as const;- for (const event of events) {- viewport.addEventListener(event, disarm, { passive: true });- }+ const onWheel = (event: Event) => {+ if ((event as WheelEvent).deltaY < 0) leaveEnd();+ };+ const onKeyDown = (event: Event) => {+ if (SCROLL_UP_KEYS.has((event as KeyboardEvent).key)) leaveEnd();+ };+ // Direction, not position: the reader who scrolls back to the bottom while the agent keeps+ // appending never lands on the exact end, so following has to resume from the gesture.+ let lastScrollTop = viewport.scrollTop;+ const onScroll = () => {+ const sample = sampleThreadScroll(viewport, lastScrollTop);+ lastScrollTop = viewport.scrollTop;+ followRef.current = nextThreadFollowState(followRef.current, sample);+ };++ viewport.addEventListener("wheel", onWheel, { passive: true });+ viewport.addEventListener("touchmove", leaveEnd, { passive: true });+ viewport.addEventListener("keydown", onKeyDown, { passive: true });+ viewport.addEventListener("scroll", onScroll, { passive: true });return () => {- for (const event of events) {- viewport.removeEventListener(event, disarm);- }+ viewport.removeEventListener("wheel", onWheel);+ viewport.removeEventListener("touchmove", leaveEnd);+ viewport.removeEventListener("keydown", onKeyDown);+ viewport.removeEventListener("scroll", onScroll);};- }, []);+ }, [followRef]);// biome-ignore lint/correctness/useExhaustiveDependencies: re-check on every streamed change — `end` alone doesn't re-notify while it stays true across commits.useEffect(() => {- if (armedRef.current && end) {+ if (followRef.current.following && end) {scrollToEnd({ behavior: "auto" });}- }, [items, end, scrollToEnd]);+ }, [items, end, scrollToEnd, followRef]);return <span ref={probeRef} className="hidden" aria-hidden="true" />;}@@ -973,6 +1007,8 @@ function ThreadScrollBody({}));}, [rows]);+ const autoFollowRef = useRef<ThreadFollowState>(FOLLOWING_END);+// `group/thread` so the footer's hover-reveal (opacity-50 → 100 on group-hover) tracks the thread,// mirroring the legacy ConversationView container. `@container/thread` makes the thread's own// width the query basis for everything inside it — the panel is resizable and splittable, so the@@ -983,7 +1019,7 @@ function ThreadScrollBody({onPointerDownCapture={onUserInteract}><MessageMinimap items={items} />- <ThreadAutoFollow items={items} />+ <ThreadAutoFollow items={items} followRef={autoFollowRef} /><ThreadScrollStateRecorder stateRef={resumeStateRef} /><ChatMessageScrollerViewport><ChatMessageScrollerContent@@ -1009,7 +1045,12 @@ function ThreadScrollBody({)}</ChatMessageScrollerContent></ChatMessageScrollerViewport>- <ChatMessageScrollerButton />+ {/* Re-arms the pin as well as scrolling: the button is the reader saying "follow again". */}+ <ChatMessageScrollerButton+ onClick={() => {+ autoFollowRef.current = FOLLOWING_END;+ }}+ /></ChatMessageScroller>);}@@ -1348,11 +1389,12 @@ function ChatThreadRenderer({// engine's own follow would fight it, so it only auto-scrolls when non-virtualized.autoScroll={!virtualized}defaultScrollPosition="end"- // Default is 8px: with the thread's bottom padding you're rarely that close, so- // auto-follow ("following-bottom") would disengage on any stray trackpad wheel and- // never re-engage. Within this band the engine recaptures follow on the next content- // change; deliberate upward flicks travel past it and stay free-scrolling.- scrollEdgeThreshold={100}+ // `scrollEdgeThreshold` is left at the engine's tight default on purpose. The engine+ // re-enters "following-bottom" on *every* scroll event taken within the band, which+ // overrides the free-scrolling its own wheel handler just set — so a wide band traps a+ // reader scrolling up out of the bottom, and streamed content yanks them back each+ // frame. `ThreadAutoFollow` is what keeps the thread pinned across the band's width;+ // unlike the engine it only lets go on a real gesture.scrollPreviousItemPeek={SCROLL_PREVIOUS_ITEM_PEEK}>{virtualized ? (diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsxindex c1e77a5f383f..d247dc1a2728 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx@@ -9,9 +9,15 @@ import { MessageMinimap } from "@posthog/ui/features/sessions/components/chat-thimport {computeStickyAnchor,type FlatThreadRow,+ FOLLOWING_END,+ nextThreadFollowState,SCROLL_PREVIOUS_ITEM_PEEK,+ SCROLL_UP_KEYS,type StickyAnchorEntry,type StickyAnchorState,+ sampleThreadScroll,+ THREAD_AT_END_THRESHOLD,+ type ThreadFollowState,type ThreadScrollResume,} from "@posthog/ui/features/sessions/components/chat-thread/threadVirtualization";import {@@ -20,8 +26,10 @@ import {} from "@posthog/ui/features/sessions/constants";import { useVirtualizer, type Virtualizer } from "@tanstack/react-virtual";import {+ type KeyboardEvent as ReactKeyboardEvent,type MouseEvent as ReactMouseEvent,type ReactNode,+ type WheelEvent as ReactWheelEvent,type RefObject,useCallback,useEffect,@@ -35,11 +43,6 @@ import {// tuning these rows share (same item mix, same measure-then-settle churn).const ESTIMATED_ROW_SIZE = 80;const OVERSCAN = 12;-/** Matches the Provider's `scrollEdgeThreshold` so "at bottom" agrees between engine and windowing. */-const AT_BOTTOM_THRESHOLD = 100;-// A real upward drift, not a 1-frame measure transient: the DOM bottom sits this far below the-// viewport. Well above any single append's measure gap.-const FAR_DRIFT_THRESHOLD = 400;/** Top of the virtual coordinate space — stands in for the non-virtualized content's `py-4`. */const PADDING_START = 16;/** Frames a programmatic scroll keeps re-issuing while rows around the target still measure. */@@ -84,15 +87,15 @@ function useReservedFooterHeight(/*** Programmatic scrolls that survive measurement drift. Rows are estimated until they mount, so a* single `scrollToEnd`/`scrollToIndex` lands short; both helpers re-issue across frames until the- * target offset stops moving. `isAtBottomRef` is the follow flag the rest of the body reads.+ * target offset stops moving. `followRef` is the follow state the rest of the body reads.*/function useSettleControls(virtualizer: ThreadVirtualizer,viewportRef: RefObject<HTMLDivElement | null>,) {- // Starts true; the mount-position effect below flips it if the handoff state says the reader was- // parked above the fold.- const isAtBottomRef = useRef(true);+ // Starts following; the mount-position effect below flips it if the handoff state says the reader+ // was parked above the fold.+ const followRef = useRef<ThreadFollowState>(FOLLOWING_END);const settleRafRef = useRef<number | null>(null);const cancelSettle = useCallback(() => {@@ -104,12 +107,12 @@ function useSettleControls(const settleAtEnd = useCallback(() => {cancelSettle();- isAtBottomRef.current = true;+ followRef.current = FOLLOWING_END;let attempts = 0;const step = () => {virtualizer.scrollToEnd();if (- virtualizer.isAtEnd(AT_BOTTOM_THRESHOLD) ||+ virtualizer.isAtEnd(THREAD_AT_END_THRESHOLD) ||++attempts > SETTLE_AT_END_ATTEMPTS) {settleRafRef.current = null;@@ -123,7 +126,9 @@ function useSettleControls(const settleToIndex = useCallback((index: number) => {cancelSettle();- isAtBottomRef.current = false;+ // A jump is the reader choosing a spot in the thread; streamed content must not pull them off+ // it, even when the target happens to sit inside the at-end tolerance.+ followRef.current = { following: false, leftEnd: true };virtualizer.scrollToIndex(index, { align: "start" });let attempts = 0;const step = () => {@@ -149,9 +154,20 @@ function useSettleControls([virtualizer, viewportRef, cancelSettle],);+ /**+ * An upward gesture: leave following until the reader scrolls back down into the end tolerance.+ * Ignored when there is nothing above to reach — a stray wheel over a thread that fits the+ * viewport would otherwise kill following with no scroll event left to undo it.+ */+ const leaveEnd = useCallback(() => {+ if (followRef.current.leftEnd) return;+ if ((viewportRef.current?.scrollTop ?? 0) <= 0) return;+ followRef.current = { following: false, leftEnd: true };+ }, [viewportRef]);+useEffect(() => cancelSettle, [cancelSettle]);- return { isAtBottomRef, settleAtEnd, settleToIndex };+ return { followRef, leaveEnd, settleAtEnd, settleToIndex };}/**@@ -226,20 +242,20 @@ function useFollowBottom({virtualizer,totalSize,items,- isAtBottomRef,+ followRef,settleAtEnd,}: {virtualizer: ThreadVirtualizer;totalSize: number;items: ConversationItem[];- isAtBottomRef: RefObject<boolean>;+ followRef: RefObject<ThreadFollowState>;settleAtEnd: () => void;}) {// biome-ignore lint/correctness/useExhaustiveDependencies: totalSize is the trigger, not a body dependencyuseLayoutEffect(() => {- if (!isAtBottomRef.current) return;+ if (!followRef.current.following) return;virtualizer.scrollToEnd();- }, [totalSize, virtualizer, isAtBottomRef]);+ }, [totalSize, virtualizer, followRef]);const lastItem = items.at(-1);const userMessageCount = useMemo(@@ -258,12 +274,12 @@ function useFollowBottom({useEffect(() => {const handleVisibilityChange = () => {- if (!document.hidden && isAtBottomRef.current) settleAtEnd();+ if (!document.hidden && followRef.current.following) settleAtEnd();};document.addEventListener("visibilitychange", handleVisibilityChange);return () =>document.removeEventListener("visibilitychange", handleVisibilityChange);- }, [settleAtEnd, isAtBottomRef]);+ }, [settleAtEnd, followRef]);}/**@@ -316,13 +332,13 @@ export function VirtualThreadScrollBody({overscan: OVERSCAN,anchorTo: "end",followOnAppend: true,- scrollEndThreshold: AT_BOTTOM_THRESHOLD,+ scrollEndThreshold: THREAD_AT_END_THRESHOLD,paddingStart: PADDING_START,paddingEnd: footerHeight,getItemKey: (index) => flatRows[index]?.key ?? index,});- const { isAtBottomRef, settleAtEnd, settleToIndex } = useSettleControls(+ const { followRef, leaveEnd, settleAtEnd, settleToIndex } = useSettleControls(virtualizer,viewportRef,);@@ -381,33 +397,19 @@ export function VirtualThreadScrollBody({const handleScroll = useCallback(() => {const el = viewportRef.current;- const scrollTop = el?.scrollTop ?? 0;- // Tolerate sub-pixel jitter; only a real upward move counts as leaving end.- const scrolledUp = scrollTop < lastScrollTopRef.current - 1;- lastScrollTopRef.current = scrollTop;-- const atEnd = virtualizer.isAtEnd(AT_BOTTOM_THRESHOLD);- // Genuine far drift (not a 1-frame measure transient): the DOM bottom sits well below the- // viewport, so follow can't get silently stuck mid-thread.- const farFromEnd = el- ? el.scrollHeight - el.clientHeight - scrollTop > FAR_DRIFT_THRESHOLD- : false;- // Hysteresis: each append measures taller than the estimate, so for one frame isAtEnd reads- // false before followOnAppend/anchorTo re-pin. Re-arm at the end; only clear on a real upward- // scroll or a genuine drift.- if (atEnd) {- isAtBottomRef.current = true;- } else if (scrolledUp || farFromEnd) {- isAtBottomRef.current = false;+ if (el) {+ const sample = sampleThreadScroll(el, lastScrollTopRef.current);+ lastScrollTopRef.current = el.scrollTop;+ followRef.current = nextThreadFollowState(followRef.current, sample);}scheduleStickyRecompute();- }, [virtualizer, scheduleStickyRecompute, isAtBottomRef]);+ }, [scheduleStickyRecompute, followRef]);useFollowBottom({virtualizer,totalSize,items,- isAtBottomRef,+ followRef,settleAtEnd,});@@ -424,7 +426,20 @@ export function VirtualThreadScrollBody({onJump={jumpToMessage}anchorId={stickyState.anchorId}/>- <ChatMessageScrollerViewport ref={viewportRef} onScroll={handleScroll}>+ <ChatMessageScrollerViewport+ ref={viewportRef}+ onScroll={handleScroll}+ // Reading upward is intent, not geometry: these catch a gesture too small to register as+ // a direction change in the scroll handler, which would otherwise still measure "at the+ // end" and let the next streamed chunk undo it.+ onWheelCapture={(event: ReactWheelEvent) => {+ if (event.deltaY < 0) leaveEnd();+ }}+ onTouchMoveCapture={leaveEnd}+ onKeyDownCapture={(event: ReactKeyboardEvent) => {+ if (SCROLL_UP_KEYS.has(event.key)) leaveEnd();+ }}+ >{/* `block` overrides the content's flex+gap layout — spacing moves into the rows(pb-4) and the virtual paddings, so translateY offsets are the whole layout. */}<ChatMessageScrollerContentdiff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.tsindex bde5e6795470..5da454893568 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts@@ -6,7 +6,10 @@ import {computeStickyAnchor,countFlatRows,flattenTurnRows,+ nextThreadFollowState,type StickyAnchorEntry,+ sampleThreadScroll,+ type ThreadScrollSample,type TurnRow,} from "./threadVirtualization";@@ -180,6 +183,118 @@ describe("countFlatRows", () => {});});+describe("nextThreadFollowState", () => {+ const sample = (+ over: Partial<ThreadScrollSample> = {},+ ): ThreadScrollSample => ({+ atEnd: false,+ atExactEnd: false,+ scrolledUp: false,+ scrolledDown: false,+ farFromEnd: false,+ ...over,+ });++ it.each([+ [+ "holds following while an append measures short of the end",+ { following: true, leftEnd: false },+ sample(),+ { following: true, leftEnd: false },+ ],+ [+ "drops following once the reader scrolls up past the tolerance",+ { following: true, leftEnd: false },+ sample({ scrolledUp: true }),+ { following: false, leftEnd: false },+ ],+ [+ "drops following when the end has drifted far below the fold",+ { following: true, leftEnd: false },+ sample({ farFromEnd: true }),+ { following: false, leftEnd: false },+ ],+ [+ "re-arms inside the tolerance when the reader never left the end",+ { following: false, leftEnd: false },+ sample({ atEnd: true }),+ { following: true, leftEnd: false },+ ],+ [+ "stays off when streamed content grows past a reader parked inside the tolerance",+ { following: false, leftEnd: true },+ sample({ atEnd: true }),+ { following: false, leftEnd: true },+ ],+ [+ "resumes when the reader scrolls back down into the tolerance",+ { following: false, leftEnd: true },+ sample({ atEnd: true, scrolledDown: true }),+ { following: true, leftEnd: false },+ ],+ [+ "ignores a downward scroll that stops short of the tolerance",+ { following: false, leftEnd: true },+ sample({ scrolledDown: true }),+ { following: false, leftEnd: true },+ ],+ [+ "resumes once the reader is back against the bottom",+ { following: false, leftEnd: true },+ sample({ atEnd: true, atExactEnd: true }),+ { following: true, leftEnd: false },+ ],+ [+ "drops following on an upward scroll that stays inside the tolerance",+ { following: true, leftEnd: false },+ sample({ atEnd: true, scrolledUp: true }),+ { following: false, leftEnd: false },+ ],+ ])("%s", (_name, state, event, expected) => {+ expect(nextThreadFollowState(state, event)).toEqual(expected);+ });+});++describe("sampleThreadScroll", () => {+ // Scroll range is 0..1500.+ const viewport = (scrollTop: number) => ({+ scrollTop,+ scrollHeight: 2000,+ clientHeight: 500,+ });++ it.each([+ [+ "a downward move that stops just short of the bottom",+ 1450,+ 1400,+ { atEnd: true, atExactEnd: false, scrolledDown: true },+ ],+ [+ "a downward move that stops outside the tolerance",+ 1300,+ 1200,+ { atEnd: false, atExactEnd: false, scrolledDown: true },+ ],+ [+ "sub-pixel drift, which is neither direction",+ 900,+ 900.5,+ { atEnd: false, atExactEnd: false, scrolledDown: false },+ ],+ [+ "the true bottom",+ 1500,+ 1450,+ { atEnd: true, atExactEnd: true, scrolledDown: true },+ ],+ ])("measures %s", (_name, scrollTop, previous, expected) => {+ expect(sampleThreadScroll(viewport(scrollTop), previous)).toMatchObject(+ expected,+ );+ });+});+describe("computeStickyAnchor", () => {const entries: StickyAnchorEntry[] = [{ id: "u1", start: 0, end: 100 },diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.tsindex 22ad5ce3ff2b..ac01f36a443d 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts@@ -149,6 +149,91 @@ export function countFlatRows(rows: TurnRow[]): number {return count;}+/**+ * Tolerance for calling the viewport "at the end". Generous because rows are estimated until they+ * mount and streamed content keeps appending, so the reader who has just scrolled down as far as+ * the wheel takes them is routinely tens of pixels short of the true bottom.+ */+export const THREAD_AT_END_THRESHOLD = 100;+/** Slack for sub-pixel scroll positions when deciding the viewport is hard against the bottom. */+export const THREAD_AT_EXACT_END_EPSILON = 1;+/** Movement below this is measurement noise, not a direction the reader chose. */+export const THREAD_SCROLL_DIRECTION_EPSILON = 1;+/**+ * A real upward drift, not a 1-frame measure transient: the DOM bottom sits this far below the+ * viewport. Well above any single append's measure gap.+ */+export const THREAD_FAR_DRIFT_THRESHOLD = 400;++/** Keys that move the viewport upward, so pressing them reads as leaving the end. */+export const SCROLL_UP_KEYS = new Set(["ArrowUp", "PageUp", "Home"]);++/** Whether a thread body re-pins to the bottom as content arrives. */+export interface ThreadFollowState {+ following: boolean;+ /**+ * The reader deliberately moved off the end. Held until they move back down into the end+ * tolerance, so streamed content that keeps growing under them never re-arms following on its+ * own — the reader's own downward gesture is what asks for it back.+ */+ leftEnd: boolean;+}++/** The follow state a thread starts in, and the one an explicit scroll-to-bottom restores. */+export const FOLLOWING_END: ThreadFollowState = {+ following: true,+ leftEnd: false,+};++/** A scroll event's geometry, as a thread body measures it. */+export interface ThreadScrollSample {+ /** Inside the at-end tolerance — a little above the bottom still counts, to absorb measure drift. */+ atEnd: boolean;+ /** Hard against the bottom, which always means following. */+ atExactEnd: boolean;+ /** The viewport moved upward since the previous sample. */+ scrolledUp: boolean;+ /** The viewport moved downward since the previous sample. */+ scrolledDown: boolean;+ /** Far enough below the fold that following is stuck mid-thread rather than measuring. */+ farFromEnd: boolean;+}++/** Measure one scroll position against the previous one. */+export function sampleThreadScroll(+ el: { scrollTop: number; scrollHeight: number; clientHeight: number },+ previousScrollTop: number,+): ThreadScrollSample {+ const distanceFromEnd = el.scrollHeight - el.clientHeight - el.scrollTop;+ const delta = el.scrollTop - previousScrollTop;+ return {+ atEnd: distanceFromEnd <= THREAD_AT_END_THRESHOLD,+ atExactEnd: distanceFromEnd <= THREAD_AT_EXACT_END_EPSILON,+ scrolledUp: delta < -THREAD_SCROLL_DIRECTION_EPSILON,+ scrolledDown: delta > THREAD_SCROLL_DIRECTION_EPSILON,+ farFromEnd: distanceFromEnd > THREAD_FAR_DRIFT_THRESHOLD,+ };+}++/** Fold one scroll sample into the follow state. */+export function nextThreadFollowState(+ state: ThreadFollowState,+ sample: ThreadScrollSample,+): ThreadFollowState {+ if (sample.atExactEnd) return FOLLOWING_END;+ // An upward move is intent even inside the tolerance, so a short gesture off the bottom isn't+ // undone by the scroll event it produced.+ if (sample.scrolledUp) return { following: false, leftEnd: state.leftEnd };+ if (state.leftEnd) {+ // Scrolling back down into the tolerance is the reader asking to follow again. Geometry alone+ // must not do it: streamed appends push the bottom away without the reader moving.+ return sample.atEnd && sample.scrolledDown ? FOLLOWING_END : state;+ }+ if (sample.atEnd) return FOLLOWING_END;+ if (sample.farFromEnd) return { following: false, leftEnd: false };+ return state;+}+/** A user-message row's measured extent in the scroll space, in row order. */export interface StickyAnchorEntry {id: string;