Skip to content

: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.

fix(posthog-ai): keep a reader's scroll while the thread follows a turn (#114773)

Phil Haackf5d57923d596
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1131bebcf4a4..819ab9c9e976 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7703,9 +7703,9 @@ snapshots:
products-posthog-ai-virtualizedthread--remembered-position--light:
hash: v1.k794b7964.fcd3d3ae2a58e891ec3fb4b224d8674f1591e349a990e0211aee29c9bf6f8d01.ThH9PVDZc4Ziy5_MNxrvijx6pRk5muGoa3ul6PgEEZw
products-posthog-ai-virtualizedthread--streaming--dark:
- hash: v1.k794b7964.b82eb1f4dc8701cf771e98d9214e6b72878727e5f68feac99a7a2a97d120c8a7.yrNrQvDVMHhEcXBq_FC0zykgDZ33RIRP6hHC95RFdEc
+ hash: v1.k794b7964.f9cc08ddbb3329fbf77e6b772b80154652c7e7f8213a3d1e294f03157d65a247.H1DCML5PjOATF21LJKDpGu8nM5x6ONrPcBnDSHc8Ttc
products-posthog-ai-virtualizedthread--streaming--light:
- hash: v1.k794b7964.abd616bcda408ecf3fd0dfcaa1595491e88913000ad61893414d3536612ee3b5.94VJLVoiR9MVKJHF7FbnLu64DXBRbUpQLLoXu1Z74As
+ hash: v1.k794b7964.ea4454f7d7d4dc076ff61362f178cfa010fda1c721696790f03057e864699826.hnmbIF4uWE6aOZa6Mh0YIKu3s9LZvaKO-uHtdqrz14k
products-signals-self-driving-intro-modal--default--dark:
hash: v1.k794b7964.e72031a3a874ed6a1825089edff6147a3ea0d74c20c74951f8b5d38d92f54464.WQmsYZby7Raw1OaQn_oKtu1eASs_te6AgRALWXM6xLE
products-signals-self-driving-intro-modal--default--light:
diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsx
index 6a37afe4e63a..f91860487bcb 100644
--- a/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsx
+++ b/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsx
@@ -130,8 +130,9 @@ export const BoundedEmbed: Story = {
/**
* Streaming, static snapshot — the same mid-stream state as `StreamingDebug` (a few settled messages, a
- * partially streamed tail, `turnActive`) frozen at a fixed tick, so the visual-regression run captures the
- * bottom-pinned streaming posture without timers.
+ * partially streamed tail, `turnActive`) frozen at a fixed tick, without timers. The test runner scrolls every
+ * scroller to the top before its screenshot, and that scroll unpins the thread, so the snapshot shows the top
+ * of the thread rather than the bottom-pinned posture.
*/
export const Streaming: Story = {
render: () => {
@@ -322,8 +323,9 @@ export const AnchoredOpen: Story = {
/**
* Anchored open, mid-turn with a short tail — reopening a thread the agent is still working on, with less
* than a viewport of response under the anchor. The top is unreachable, so this must open at the bottom,
- * pinned (no padding is reserved to force the anchor higher). Static (`turnActive` but no timers), so the
- * visual-regression run captures the clamped landing without flakes. The 400px wrapper keeps the bounded
+ * pinned (no padding is reserved to force the anchor higher). Static (`turnActive` but no timers). The test
+ * runner scrolls every scroller to the top before its screenshot, and that scroll unpins the thread, so the
+ * snapshot shows the top of the thread rather than the clamped landing. The 400px wrapper keeps the bounded
* container visible in the snapshot.
*/
export const AnchoredOpenMidTurn: Story = {
diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
index ede5c9fa4654..3e4f0a6c2338 100644
--- a/products/posthog_ai/frontend/components/VirtualizedThread.tsx
+++ b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
@@ -44,6 +44,16 @@ const AT_BOTTOM_EPSILON = 1
/** The core snaps its own scroll writes to within 1.5px of their target — below that is never the reader. */
const UNPIN_SLACK = 1.5
+/**
+ * True when the offset moved after the last scroll event `onScroll` handled or the last software write
+ * (`lastSeenTop`). The browser dispatches scroll events once per frame, so a timer can run after a reader's
+ * scroll and before its event. A timer write there erases the reader's scroll, and `onScroll` then takes the
+ * late event for the write's echo. A hidden scroller reads 0 and fires no event, so it never reports a move.
+ */
+function hasUnseenScroll(el: HTMLElement, lastSeenTop: number): boolean {
+ return el.clientHeight > 0 && Math.abs(el.scrollTop - lastSeenTop) > UNPIN_SLACK
+}
+
/**
* How long a recorded programmatic scroll write explains the scroll event it causes. Events land on the
* next frame; the window only needs to survive frame jank, and staying short keeps a coincidental user
@@ -257,6 +267,8 @@ function Root<T>({
const lastUserScrollAtRef = useRef(0)
// The previous scroll event's offset — how the listener recognizes a shrink clamp (see `onScroll`).
const lastScrollEventTopRef = useRef<number | null>(null)
+ // The offset as of the last scroll event or software scroll write (see `hasUnseenScroll`).
+ const lastSeenTopRef = useRef(0)
// Keeps following for a beat after the turn reports done, so the trailing usage/cost row lands in
// view (see `FOLLOW_GRACE_MS`).
const [followGrace, setFollowGrace] = useState(false)
@@ -271,6 +283,15 @@ function Root<T>({
// `undefined` means "thread not yet populated" — the anchor-change effect adopts the first real key.
const prevAnchorKeyRef = useRef<string | null | undefined>(undefined)
+ const recordScrollWrite = useCallback((applied: number): void => {
+ lastSeenTopRef.current = applied
+ const writes = programmaticScrollsRef.current
+ writes.push({ value: applied, at: performance.now() })
+ if (writes.length > 12) {
+ writes.splice(0, writes.length - 12)
+ }
+ }, [])
+
const renderRow = useCallback(
(index: number): ReactNode => {
let i = index
@@ -357,17 +378,12 @@ function Root<T>({
// measurement — no stale-offset overlap while rows measure, and React re-renders only on range change.
directDomUpdates: true,
// The default `elementScroll`, wrapped so every scroll write the core performs is recorded for
- // the scroll listener's programmatic-vs-reader test (see `programmaticScrollsRef`). Recorded
- // *after* the write, from the element — `scrollTo` applies synchronously, so this is the value
- // the write actually produced, clamping included.
+ // the scroll listener's programmatic-vs-reader test (see `programmaticScrollsRef`) and for
+ // `hasUnseenScroll` (see `lastSeenTopRef`). Recorded *after* the write, from the element — `scrollTo`
+ // applies synchronously, so this is the value the write actually produced, clamping included.
scrollToFn: (offset, options, instance) => {
elementScroll(offset, options, instance)
- const applied = instance.scrollElement?.scrollTop ?? offset + (options.adjustments ?? 0)
- const writes = programmaticScrollsRef.current
- writes.push({ value: applied, at: performance.now() })
- if (writes.length > 12) {
- writes.splice(0, writes.length - 12)
- }
+ recordScrollWrite(instance.scrollElement?.scrollTop ?? offset + (options.adjustments ?? 0))
},
// No `gap` — inter-row spacing is baked into the measured row height via `paddingBottom` (see `Row`).
...(stickToBottom
@@ -487,12 +503,8 @@ function Root<T>({
const noteProgrammaticScroll = useCallback((): void => {
const top = scrollRef.current?.scrollTop ?? 0
peakTopRef.current = top
- const writes = programmaticScrollsRef.current
- writes.push({ value: top, at: performance.now() })
- if (writes.length > 12) {
- writes.splice(0, writes.length - 12)
- }
- }, [])
+ recordScrollWrite(top)
+ }, [recordScrollWrite])
// Hold an unpinned anchor landing steady while the thread's measurements settle (see the settle
// constants). Re-asserts via `scrollToIndex` so the corrective write re-computes the offset from the
@@ -508,7 +520,11 @@ function Root<T>({
return
}
const target = virtualizer.getOffsetForIndex(anchorIndex, 'start')?.[0]
- if (target !== undefined && Math.abs(el.scrollTop - target) > ANCHOR_SETTLE_TOLERANCE_PX) {
+ if (
+ target !== undefined &&
+ !hasUnseenScroll(el, lastSeenTopRef.current) &&
+ Math.abs(el.scrollTop - target) > ANCHOR_SETTLE_TOLERANCE_PX
+ ) {
virtualizer.scrollToIndex(anchorIndex, { align: 'start' })
noteProgrammaticScroll()
}
@@ -552,16 +568,13 @@ function Root<T>({
if (viewport > 0 && contentBelow >= viewport) {
return
}
- if (itemsLengthRef.current !== itemsAtOpen) {
- commitBottomOpen(el)
- return
- }
remaining -= 1
- if (remaining > 0) {
+ const verdictDue = itemsLengthRef.current !== itemsAtOpen || remaining === 0
+ if (verdictDue && !hasUnseenScroll(el, lastSeenTopRef.current)) {
+ commitBottomOpen(el)
+ } else if (remaining > 0) {
setTimeout(tick, ANCHOR_SETTLE_INTERVAL_MS)
- return
}
- commitBottomOpen(el)
}
setTimeout(tick, ANCHOR_SETTLE_INTERVAL_MS)
},
@@ -767,6 +780,7 @@ function Root<T>({
}
const onScroll = (): void => {
const top = el.scrollTop
+ lastSeenTopRef.current = top
const maxTop = Math.max(0, el.scrollHeight - el.clientHeight)
// Content shrinking under the reader — a tool card's accordion collapsing the moment the tool
// completes, which on this surface is every finished tool — lowers the scroll range, and the
@@ -817,12 +831,16 @@ function Root<T>({
el.addEventListener('wheel', onWheel, { passive: true })
el.addEventListener('touchstart', onTouchStart, { passive: true })
el.addEventListener('touchmove', onTouchMove, { passive: true })
- el.addEventListener('scroll', onScroll, { passive: true })
+ // Capture phase, so this listener runs before the virtualizer's own scroll listener on the same
+ // element. That listener re-renders this component synchronously when the reader's scroll changes the
+ // rendered range, and the follow effect in that re-render would write the bottom back while the
+ // thread still counts as pinned.
+ el.addEventListener('scroll', onScroll, { passive: true, capture: true })
return () => {
el.removeEventListener('wheel', onWheel)
el.removeEventListener('touchstart', onTouchStart)
el.removeEventListener('touchmove', onTouchMove)
- el.removeEventListener('scroll', onScroll)
+ el.removeEventListener('scroll', onScroll, { capture: true })
}
// Deliberately not keyed on the pinned state: re-subscribing mid-gesture would reset the peak
// baseline, which is the one thing that has to survive a gesture.