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): pin run thread to bottom while a turn is active (#73256)

Georgiy Tarasovc579d1748964
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e513c6bfd42d..b0a8d893053a 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4822,6 +4822,18 @@ snapshots:
hash: v1.k794b7964.410f559d98dc233ee8047dd8cfd5ce5f16bf47298ac0f3ea7c38e21913f3e79e._jbCcWpMORUlIHh_Te_m_hWib0TJ1zlg4bw-cm35FTI
products-posthog-ai-runalertactivity--connection-lost--light:
hash: v1.k794b7964.6a54547f7784b2a6ddcdde131600ed37ee2abdb56180e9cff603e8a7a3e395bf.cUg8KJHc-L7D6KFrCng16YTN5A0-WRMfw75cElwkroI
+ products-posthog-ai-virtualizedthread--anchored-open--dark:
+ hash: v1.k794b7964.eecc3dde9e8475fb8f20f259880edae96e2750529897fc326c44d33ce20e0885.hQlXYcfwZ9CiFajcBHUg9oY6h2QcGrm91CkXVIht-OE
+ products-posthog-ai-virtualizedthread--anchored-open--light:
+ hash: v1.k794b7964.1b0387275217fb820cbbe4a18caa5cde4be9521d4e296933e80e8f78a9914490.3TrbyabUGN-G6zrsTie8aaMDWrYs1wWMW7OIANOjsbE
+ products-posthog-ai-virtualizedthread--anchored-open-mid-turn--dark:
+ hash: v1.k794b7964.eecc3dde9e8475fb8f20f259880edae96e2750529897fc326c44d33ce20e0885.jUSUfoNAuVJvfWe8M9IRRg_CirdzkCKjQjoVsutO9vY
+ products-posthog-ai-virtualizedthread--anchored-open-mid-turn--light:
+ hash: v1.k794b7964.1b0387275217fb820cbbe4a18caa5cde4be9521d4e296933e80e8f78a9914490.qUuhFOn4BwbL8REUimYFdxCpOmg64Cj1HJD2Ovwdan0
+ products-posthog-ai-virtualizedthread--anchored-open-mid-turn-long-tail--dark:
+ hash: v1.k794b7964.eecc3dde9e8475fb8f20f259880edae96e2750529897fc326c44d33ce20e0885.Hyd9-RXxKAGa7JXvG9Cv21bjzvWXoDPIMvIHoZdgOiI
+ products-posthog-ai-virtualizedthread--anchored-open-mid-turn-long-tail--light:
+ hash: v1.k794b7964.1b0387275217fb820cbbe4a18caa5cde4be9521d4e296933e80e8f78a9914490.GzLtfWliK_BpYQaIRNcr_FZMwJsgTDtmCKzTN7YA0Do
products-posthog-ai-virtualizedthread--bounded-embed--dark:
hash: v1.k794b7964.252ed79bcc1090bd563f70c1cc024708ee80db603cd9befef05589e36b3b91fe.twGDMp1FHmr8OyTgi-2ks6hFRxl0KlA6WzNw8YRYhFI
products-posthog-ai-virtualizedthread--bounded-embed--light:
@@ -4842,6 +4854,10 @@ snapshots:
hash: v1.k794b7964.ab407d100e82b2804ac63958c38fc48af75120b67e9158c9b280487b2245687e.kZn1-gur30DNFrP7TDua5UGXGu6HziGnAVPc9Zz3wMU
products-posthog-ai-virtualizedthread--long-thread--light:
hash: v1.k794b7964.ea4454f7d7d4dc076ff61362f178cfa010fda1c721696790f03057e864699826.drgUhmxnD0Dt_wm7kKiSeLzeU3WrrNcDJPwFY_rxnec
+ products-posthog-ai-virtualizedthread--streaming--dark:
+ hash: v1.k794b7964.c4ebc83f695831769cc95475925e983a71d5909636818ff2153e2dc7df5450a1.9VcSQPoSe9fMttmpga5INPhkJySlhF35v8dHEs52L90
+ products-posthog-ai-virtualizedthread--streaming--light:
+ hash: v1.k794b7964.e731151aea72bc9d5f4248dd2548e03fe07336fb29b2110d1e348020985ef9d1.NMSw9HS1VJuLZsmgp29MVPo708vTot8RLCqFv8IC7RQ
products-subscriptions-subscription-delivery-history--empty--dark:
hash: v1.k794b7964.267363ce3a0453be58b96ef2c00446ae4aaf5ed42b02472c495b3c468f25e18f.PjabhWWV-dc6vzuSl_wdoaQ2VAB35IG84kOVKe5eaA4
products-subscriptions-subscription-delivery-history--empty--light:
diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsx
index a17d573b2993..011053a32656 100644
--- a/products/posthog_ai/frontend/components/ThreadView.tsx
+++ b/products/posthog_ai/frontend/components/ThreadView.tsx
@@ -88,11 +88,12 @@ export function ThreadView({
currentRunStatus,
contextUsage,
runConnectionState,
+ logBootstrapLoading,
} = useValues(runStreamLogic)
const turnCancelled = currentRunStatus === 'cancelled'
// The last human message anchors the thread. Reopening a saved conversation lands on it — the last
- // meaningful turn, response below — rather than the absolute bottom; a fresh send (the key changing)
- // pins it to the top of the viewport with space reserved below for the streaming response.
+ // meaningful turn, response below — when at least a viewport of content follows it (otherwise the
+ // bottom); a fresh send (a new key) pins the thread to the bottom to follow the streaming response.
const anchorItemKey = useMemo(
() => threadItems.findLast((item) => item.type === 'human_message')?.id ?? null,
[threadItems]
@@ -177,9 +178,15 @@ export function ThreadView({
getItemKey={getThreadItemKey}
estimateItemHeight={estimateThreadItemHeight}
anchorItemKey={anchorItemKey}
+ // The history replay folds in over several commits (debug rows land before the human turns);
+ // the opening scroll must wait for the full log or it opens at the bottom of a partial thread.
+ itemsLoading={logBootstrapLoading}
header={header}
footer={footer}
stickToBottom
+ // Provisioning counts too: the optimistic "spinning up" window is part of the turn, so the
+ // thread is already pinned when the first streamed rows land.
+ turnActive={streamPhase !== 'idle'}
virtualized={virtualized}
className={className}
listClassName={listClassName}
diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsx
index a143e526d825..2e8835298644 100644
--- a/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsx
+++ b/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsx
@@ -100,11 +100,50 @@ export const BoundedEmbed: Story = {
}
/**
- * Streaming — a timer appends items and grows the height of the last message; the viewport stays pinned to the
- * bottom. This exercises the height-only-growth stick path, the case `anchorTo: 'end'` does not cover. Timers
- * are non-deterministic, so this story is skipped in the visual-regression run.
+ * 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.
*/
export const Streaming: Story = {
+ render: () => {
+ const items = [
+ ...makeItems(6),
+ { id: 'stream-4', role: 'assistant' as const, text: '#6 — streamed message' },
+ { id: 'stream-8', role: 'assistant' as const, text: '#7 — streamed message' },
+ ]
+ return (
+ <div className="h-[600px] w-180 border rounded overflow-hidden">
+ <VirtualizedThread.Root
+ items={items}
+ getItemKey={getKey}
+ footer={
+ <VirtualizedThread.Row>
+ <div className="rounded border p-3 bg-surface-primary text-sm text-muted">
+ Thinking {LOREM.slice(0, 40)}…
+ </div>
+ </VirtualizedThread.Row>
+ }
+ stickToBottom
+ turnActive
+ >
+ {(item) => (
+ <VirtualizedThread.Row>
+ <FakeMessage role={item.role} text={item.text} />
+ </VirtualizedThread.Row>
+ )}
+ </VirtualizedThread.Root>
+ </div>
+ )
+ },
+}
+
+/**
+ * Streaming, live timers — appends items and grows the height of the last message; the viewport stays pinned
+ * to the bottom (`turnActive` simulates the agent working, which is what gates append-following). This
+ * exercises the height-only-growth stick path. Debugging only: timers make it non-deterministic, so it is
+ * excluded from the visual-regression run (`test-skip`) — capture `Streaming` instead.
+ */
+export const StreamingDebug: Story = {
tags: ['test-skip'],
render: () => {
const [items, setItems] = useState<FakeItem[]>(() => makeItems(6))
@@ -143,6 +182,7 @@ export const Streaming: Story = {
</VirtualizedThread.Row>
}
stickToBottom
+ turnActive
>
{(item) => (
<VirtualizedThread.Row>
@@ -199,6 +239,323 @@ export const HeaderFooterOnly: Story = {
),
}
+/**
+ * Anchored open — mirrors reopening a saved conversation: the thread mounts with all items already present
+ * and `anchorItemKey` pointing at the last "user" message, which has more than a viewport of content after
+ * it. Must land with the anchor at the top of the viewport, not at the bottom. The height estimate is a
+ * deliberate undershoot (46px vs ~200px real), the same skew the real `THREAD_ITEM_HEIGHT_ESTIMATES` has.
+ * The 400px wrapper is intentionally shorter than the canvas so the bounded container — and where the
+ * scroll landed inside it — is visible in the snapshot.
+ */
+export const AnchoredOpen: Story = {
+ render: () => {
+ // 30 items; the anchor "user" message is #21, followed by 8 long rows (several viewports of tail).
+ const items = makeItems(30).map((item, i) => {
+ if (i === 21) {
+ return {
+ ...item,
+ role: 'user' as const,
+ text: `#${i} (user, the anchor) — EXPECTED ON OPEN: this message sits at the TOP of the viewport, because more than a viewport of response follows it.`,
+ }
+ }
+ if (i > 21) {
+ return {
+ ...item,
+ role: 'assistant' as const,
+ text:
+ i === 29
+ ? `#${i} — EXPECTED: the end of the thread stays below the fold, reached by scrolling down. ${LOREM}`
+ : `#${i} — response under the anchor; visible below it or below the fold. ${LOREM} ${LOREM}`,
+ }
+ }
+ return item
+ })
+ return (
+ <div className="h-[400px] w-180 border rounded overflow-hidden">
+ <VirtualizedThread.Root
+ items={items}
+ getItemKey={getKey}
+ estimateItemHeight={() => 46}
+ anchorItemKey="item-21"
+ stickToBottom
+ >
+ {(item) => (
+ <VirtualizedThread.Row>
+ <FakeMessage role={item.role} text={item.text} />
+ </VirtualizedThread.Row>
+ )}
+ </VirtualizedThread.Root>
+ </div>
+ )
+ },
+}
+
+/**
+ * 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
+ * container visible in the snapshot.
+ */
+export const AnchoredOpenMidTurn: Story = {
+ render: () => {
+ const items = makeItems(30).map((item, i) => {
+ if (i === 27) {
+ return {
+ ...item,
+ role: 'user' as const,
+ text: `#${i} (user, the anchor) — EXPECTED ON OPEN: NOT at the top. Less than a viewport of response follows, so the thread opens clamped to the BOTTOM, pinned — no whitespace is reserved to push this row higher.`,
+ }
+ }
+ if (i > 27) {
+ return {
+ ...item,
+ role: 'assistant' as const,
+ text:
+ i === 29
+ ? `#${i} — EXPECTED: this last row sits at the bottom edge of the viewport on open.`
+ : `#${i} — short response under the anchor. ${LOREM.slice(0, 80)}`,
+ }
+ }
+ return item
+ })
+ return (
+ <div className="h-[400px] w-180 border rounded overflow-hidden">
+ <VirtualizedThread.Root
+ items={items}
+ getItemKey={getKey}
+ estimateItemHeight={() => 46}
+ anchorItemKey="item-27"
+ stickToBottom
+ turnActive
+ >
+ {(item) => (
+ <VirtualizedThread.Row>
+ <FakeMessage role={item.role} text={item.text} />
+ </VirtualizedThread.Row>
+ )}
+ </VirtualizedThread.Root>
+ </div>
+ )
+ },
+}
+
+/**
+ * Anchored open, mid-turn, live timers — the same short-tail open as `AnchoredOpenMidTurn`, but a timer
+ * keeps appending streamed rows: the thread opens at the bottom, pinned, and follows the appends.
+ * Debugging only: excluded from the visual-regression run (`test-skip`) — capture `AnchoredOpenMidTurn`
+ * instead.
+ */
+export const AnchoredOpenMidTurnDebug: Story = {
+ tags: ['test-skip'],
+ render: () => {
+ const [items, setItems] = useState<FakeItem[]>(() =>
+ makeItems(30).map((item, i) => (i >= 27 ? { ...item, text: `#${i} — ${LOREM} ${LOREM}` } : item))
+ )
+ useEffect(() => {
+ if (inStorybookTestRunner()) {
+ return
+ }
+ const interval = setInterval(() => {
+ setItems((prev) => [
+ ...prev,
+ { id: `stream-${prev.length}`, role: 'assistant', text: `#${prev.length} — streamed` },
+ ])
+ }, 700)
+ return () => clearInterval(interval)
+ }, [])
+ return (
+ <div className="h-[600px] w-180 border rounded overflow-hidden">
+ <VirtualizedThread.Root
+ items={items}
+ getItemKey={getKey}
+ estimateItemHeight={() => 46}
+ anchorItemKey="item-27"
+ stickToBottom
+ turnActive
+ >
+ {(item) => (
+ <VirtualizedThread.Row>
+ <FakeMessage role={item.role} text={item.text} />
+ </VirtualizedThread.Row>
+ )}
+ </VirtualizedThread.Root>
+ </div>
+ )
+ },
+}
+
+/**
+ * Anchored open, mid-turn with a long tail — reopening a thread the agent is still working on, with more
+ * than a viewport of response already under the anchor. This is a reading position: the anchor must land at
+ * the top of the viewport and stay there — streaming below must not steal the view. Static and
+ * deterministic, so the visual-regression run captures it. The 400px wrapper keeps the bounded container
+ * visible in the snapshot.
+ */
+export const AnchoredOpenMidTurnLongTail: Story = {
+ render: () => {
+ const items = makeItems(30).map((item, i) => {
+ if (i === 21) {
+ return {
+ ...item,
+ role: 'user' as const,
+ text: `#${i} (user, the anchor) — EXPECTED ON OPEN (mid-turn): at the TOP of the viewport, and it STAYS there — the stream growing below must not steal this reading position.`,
+ }
+ }
+ if (i > 21) {
+ return {
+ ...item,
+ role: 'assistant' as const,
+ text: `#${i} — in-progress response under the anchor; the tail already exceeds a viewport. ${LOREM} ${LOREM}`,
+ }
+ }
+ return item
+ })
+ return (
+ <div className="h-[400px] w-180 border rounded overflow-hidden">
+ <VirtualizedThread.Root
+ items={items}
+ getItemKey={getKey}
+ estimateItemHeight={() => 46}
+ anchorItemKey="item-21"
+ stickToBottom
+ turnActive
+ >
+ {(item) => (
+ <VirtualizedThread.Row>
+ <FakeMessage role={item.role} text={item.text} />
+ </VirtualizedThread.Row>
+ )}
+ </VirtualizedThread.Root>
+ </div>
+ )
+ },
+}
+
+/**
+ * Deferred open — simulates the history replay: the thread mounts with a few rows and `itemsLoading`,
+ * more rows fold in over two ticks, then loading clears with the full thread. The once-only opening
+ * scroll must wait for the final commit and land on the anchor ("user" #21 at the top) — spending it on a
+ * partial commit is the bug that opened every debug-logs-on thread at the bottom. Debugging only: the
+ * phase timers make it non-deterministic for capture (`test-skip`).
+ */
+export const DeferredOpenDebug: Story = {
+ tags: ['test-skip'],
+ render: () => {
+ // The tail after the anchor is all-assistant (a long response), so the dynamically derived
+ // anchor — the last "user" item, like the real consumer — stays #21 across every phase.
+ const full = makeItems(30).map((item, i) =>
+ i >= 21
+ ? {
+ ...item,
+ role: i === 21 ? ('user' as const) : ('assistant' as const),
+ text: `#${i} — ${LOREM} ${LOREM}`,
+ }
+ : item
+ )
+ const [phase, setPhase] = useState(0)
+ useEffect(() => {
+ if (inStorybookTestRunner()) {
+ return
+ }
+ const t1 = setTimeout(() => setPhase(1), 400)
+ const t2 = setTimeout(() => setPhase(2), 900)
+ return () => {
+ clearTimeout(t1)
+ clearTimeout(t2)
+ }
+ }, [])
+ const items = phase === 0 ? full.slice(0, 3) : phase === 1 ? full.slice(0, 12) : full
+ const lastUser = items.findLast((item) => item.role === 'user')
+ return (
+ <div className="h-[600px] w-180 border rounded overflow-hidden">
+ <VirtualizedThread.Root
+ items={items}
+ getItemKey={getKey}
+ estimateItemHeight={() => 46}
+ anchorItemKey={lastUser?.id ?? null}
+ itemsLoading={phase < 2}
+ stickToBottom
+ >
+ {(item) => (
+ <VirtualizedThread.Row>
+ <FakeMessage role={item.role} text={item.text} />
+ </VirtualizedThread.Row>
+ )}
+ </VirtualizedThread.Root>
+ </div>
+ )
+ },
+}
+
+/**
+ * Send and anchor-jump — interactive harness for the two anchor-change behaviors. "Send" appends a new
+ * "user" message and points `anchorItemKey` at it (a *novel* key = a fresh send): the thread must pin to
+ * the bottom and follow the streamed response, with the sent message riding up naturally. "Jump to first
+ * user message" re-points the anchor at an *existing* key (a replayed turn): the thread must scroll that
+ * row to the top without pinning. Debugging only (`test-skip`): both are transitions, not landings.
+ */
+export const SendAndJumpDebug: Story = {
+ tags: ['test-skip'],
+ render: () => {
+ const [items, setItems] = useState<FakeItem[]>(() => makeItems(30))
+ const [anchorKey, setAnchorKey] = useState<string>('item-29')
+ const [turnActive, setTurnActive] = useState(false)
+ const seqRef = useRef(0)
+
+ useEffect(() => {
+ if (!turnActive || inStorybookTestRunner()) {
+ return
+ }
+ const interval = setInterval(() => {
+ setItems((prev) => [
+ ...prev,
+ { id: `stream-${prev.length}`, role: 'assistant', text: `#${prev.length} — streamed response` },
+ ])
+ }, 700)
+ return () => clearInterval(interval)
+ }, [turnActive])
+
+ const send = (): void => {
+ const id = `sent-${seqRef.current++}`
+ setItems((prev) => [...prev, { id, role: 'user', text: `sent message ${id}` }])
+ setAnchorKey(id)
+ setTurnActive(true)
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex gap-2">
+ <button className="border rounded px-2 py-1" onClick={send}>
+ Send
+ </button>
+ <button className="border rounded px-2 py-1" onClick={() => setAnchorKey('item-1')}>
+ Jump to first user message
+ </button>
+ <button className="border rounded px-2 py-1" onClick={() => setTurnActive(false)}>
+ End turn
+ </button>
+ </div>
+ <div className="h-[600px] w-180 border rounded overflow-hidden">
+ <VirtualizedThread.Root
+ items={items}
+ getItemKey={getKey}
+ anchorItemKey={anchorKey}
+ stickToBottom
+ turnActive={turnActive}
+ >
+ {(item) => (
+ <VirtualizedThread.Row>
+ <FakeMessage role={item.role} text={item.text} />
+ </VirtualizedThread.Row>
+ )}
+ </VirtualizedThread.Root>
+ </div>
+ </div>
+ )
+ },
+}
+
/**
* Flow mode (`virtualized={false}`) — rows render into document flow with no chrome, no scroll container, no
* measurement. An ancestor owns scroll (here, a plain bounded div). This is the Max live-column path.
diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
index 71c09959971f..9661beaa1f1c 100644
--- a/products/posthog_ai/frontend/components/VirtualizedThread.tsx
+++ b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
@@ -1,4 +1,4 @@
-import { useVirtualizer } from '@tanstack/react-virtual'
+import { elementScroll, useVirtualizer } from '@tanstack/react-virtual'
import {
createContext,
CSSProperties,
@@ -15,9 +15,70 @@ import {
import { cn } from 'lib/utils/css-classes'
-/** Within this many px of the bottom still counts as "pinned" — absorbs iOS momentum/rubber-band jitter. */
+/**
+ * Slack the virtualizer core is allowed to treat as "at the end" while the thread is pinned, so its own
+ * growth compensation still smooths streaming that lands between our follow writes. Deliberately *not*
+ * used to decide whether the reader is at the bottom — see `AT_BOTTOM_EPSILON`.
+ */
const BOTTOM_THRESHOLD = 32
+/**
+ * `scrollEndThreshold` while unpinned. The core compares it against `getVirtualDistanceFromEnd()`, which
+ * clamps at 0 — so 0 would still compensate at the exact end. A negative threshold is the only value that
+ * distance can never satisfy, which is what "while the reader is away, no measurement may move the view"
+ * requires.
+ */
+const NO_END_COMPENSATION = -1
+
+/**
+ * How close to the bottom the reader has to be to count as *there* — subpixel only. A band here would
+ * make the bottom sticky: an upward gesture that stops inside it gets re-pinned and yanked back on the
+ * next streamed frame, which reads as the view shaking against the gesture. Zero would be stricter still,
+ * but fractional layout/zoom leaves the true bottom a half-pixel short, so re-pinning would be unreachable.
+ */
+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
+
+/**
+ * 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
+ * scroll to the same offset from being swallowed for long.
+ */
+const PROGRAMMATIC_SCROLL_MATCH_MS = 200
+
+/**
+ * The settle window after an anchor landing: how often and how many times the landing is re-asserted
+ * against the anchor's (re-measured) offset. Needed because the core's scroll reconciler has a blind
+ * spot — once its target stops moving, an offset nudge from a late row measurement is rewritten by
+ * neither of its branches, so it idles to its timeout and leaves the drift in place. Any reader scroll
+ * cancels the window immediately.
+ */
+const ANCHOR_SETTLE_INTERVAL_MS = 250
+const ANCHOR_SETTLE_CHECKS = 8
+
+/** Drift below this is indistinguishable from subpixel rounding — not worth a corrective write. */
+const ANCHOR_SETTLE_TOLERANCE_PX = 2
+
+/**
+ * How long a bottom arrival is ignored by the re-pin test after a programmatic anchor landing. On the
+ * landing commit rows are still estimates, so the scroll clamps against a range that grows as rows
+ * measure — the settle touches the exact bottom transiently, and each touch emits a scroll event that is
+ * indistinguishable from the reader arriving there. Position-based disambiguation is racy (the settle
+ * also emits not-at-bottom events between the touches), so the window is temporal: the reconciler holds
+ * a stable anchor target within a few frames, and an explicit downward gesture clears the block early.
+ */
+const BOTTOM_REPIN_BLOCK_MS = 600
+
+/**
+ * How long the thread keeps following after a turn reports done. The turn's last rows land after the
+ * flag drops: token usage and cost arrive on their own stream frames, and the footer swaps to them a
+ * commit or two later. Without the grace that tail renders just below the fold. Overshooting is harmless —
+ * an upward gesture unpins instantly, grace or not.
+ */
+const FOLLOW_GRACE_MS = 1000
+
/**
* Static base for measured rows under `directDomUpdates`: the virtualizer writes each row's `translate3d`
* (and the container's height) directly to the DOM, so React renders no per-row offset at all — a pure
@@ -87,17 +148,33 @@ export interface VirtualizedThreadRootProps<T> {
overscanCount?: number
/** Follow the bottom as rows grow/append; unpins when the user scrolls up. */
stickToBottom?: boolean
+ /**
+ * True while the agent is actively working a turn (streaming output into the thread). Gates
+ * bottom-following: while active, streamed rows keep pulling the view down — as long as the thread is
+ * pinned, which it is whenever the reader is at the bottom — until the user scrolls up, which unpins.
+ * Unpinning is absolute: nothing moves the view again (not the follow write, not the virtualizer's own
+ * growth compensation) until the reader scrolls all the way back to the bottom, which re-pins. Follow
+ * outlasts the flag by a moment so the turn's trailing usage/cost row lands in view. While inactive,
+ * streamed rows never move the view.
+ */
+ turnActive?: boolean
/**
* Key of the row the reader's attention anchors to — the last human message, typically. Two behaviors
- * hang off it. Open: the thread opens with this row at the top of the viewport (the last meaningful
- * turn, its response below) instead of the absolute bottom; clamping degrades to the bottom when
- * little content follows. Change to a new non-null value (a fresh send): the row is scrolled to the
- * top with bottom padding reserved so it can anchor there — the "sent message pins to the top, the
- * response streams into the space below" chat pattern. The reserve also moves the true end below the
- * viewport, so stick-to-bottom stops following until the user deliberately returns to the bottom, and
- * it persists until the next anchor.
+ * hang off it. Open: when at least a viewport of content follows this row, the thread opens with it
+ * at the top of the viewport (the last meaningful turn, its response below), mid-turn included; with
+ * less content the scroll clamps and the thread opens at the bottom — no padding is ever reserved to
+ * force the row higher. Change to a new non-null value (a fresh send): the thread pins to the bottom
+ * and follows the streaming answer; the sent message rides up naturally as the response grows.
*/
anchorItemKey?: string | null
+ /**
+ * True while `items` are still being assembled (a history replay in flight). Defers the once-only
+ * opening scroll and the anchor-key adoption: partial fold commits can carry renderable items —
+ * debug/console rows land well before the history's human turns — and spending the open on one of
+ * those opens every thread at the bottom instead of its anchor. Cleared-on-error semantics are the
+ * caller's job: while true the thread never takes its opening scroll.
+ */
+ itemsLoading?: boolean
maxWidthClassName?: string
className?: string
/**
@@ -126,7 +203,9 @@ function Root<T>({
estimateItemHeight,
overscanCount = 10,
stickToBottom = true,
+ turnActive = false,
anchorItemKey,
+ itemsLoading = false,
maxWidthClassName = 'max-w-180',
className,
listClassName,
@@ -139,11 +218,52 @@ function Root<T>({
const scrollRef = useRef<HTMLDivElement>(null)
const didInitialScrollRef = useRef(false)
- // Bottom padding reserved by the anchor-on-send behavior (`anchorItemKey`), fed to the virtualizer as
- // `paddingEnd`. `undefined` in the prev-key ref means "thread not yet populated".
- const [anchorPadding, setAnchorPadding] = useState(0)
+ // Bottom-pinning state (see `turnActive`). Explicit rather than position-derived: during fast
+ // streaming the scroll position transiently lags the growing content past any at-bottom threshold,
+ // so "is the user at the bottom right now" cannot distinguish "scrolled away" from "content briefly
+ // outran the follow scroll". Starts pinned: a thread that opens onto an active turn follows from the
+ // first frame, and it stays inert while no turn is active. A ref rather than state because every
+ // reader of it needs the value in the same tick as the gesture — the scroll listener, the per-commit
+ // follow effect, and the virtualizer options, which `useVirtualizer` re-reads on every render.
+ const pinnedRef = useRef(true)
+ // Highest offset the reader has reached since the last pin — the yardstick the unpin test measures
+ // against. A high-water mark rather than the previous event's offset because a slow drag (scrollbar,
+ // touch, a trackpad crawl) moves a couple of px per scroll event and would walk hundreds of px away
+ // from the bottom without any single event ever crossing a per-event delta.
+ const peakTopRef = useRef(0)
+ // Until when bottom arrivals may not re-pin (see `BOTTOM_REPIN_BLOCK_MS`). Armed by programmatic
+ // anchor landings; cleared early by an explicit downward gesture.
+ const bottomRepinBlockedUntilRef = useRef(0)
+ // Recent scroll writes software performed — ours (follow, landings) or the virtualizer core's
+ // (`scrollToFn` routes through here). The scroll listener uses them to tell content-driven movement
+ // from the reader's: during a fast stream the core writes `scrollTop` many times a frame from its
+ // own bookkeeping (measurement compensations, end anchoring), and any of those can move the offset
+ // *up* — a lagging internal offset, a row measuring smaller than its estimate — which is byte-for-
+ // byte what an upward gesture looks like. The values recorded are the *applied* offsets (read back
+ // after the write), so a write the browser clamped still matches its event; a short ring rather
+ // than one entry, because a measurement storm can land several writes before their events flush.
+ const programmaticScrollsRef = useRef<{ value: number; at: number }[]>([])
+ // Item keys of the previous populated commit — how the anchor-change effect tells a fresh send (the
+ // key did not exist before) from a replayed anchor (it did). See that effect for why position can't.
+ const prevItemKeysRef = useRef<Set<string> | null>(null)
+ // When the reader last scrolled (a scroll event no programmatic write explains, or a wheel/touch
+ // gesture). The anchor settle loop stands down the moment this passes its start time.
+ 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)
+ // 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)
+ const prevTurnActiveRef = useRef(turnActive)
+ const following = turnActive || followGrace
+ // Read by the scroll listener without re-subscribing it per render.
+ const followingRef = useRef(following)
+ followingRef.current = following
+ // Read by the open-decision loop without re-arming it per commit.
+ const itemsLengthRef = useRef(items.length)
+ itemsLengthRef.current = items.length
+ // `undefined` means "thread not yet populated" — the anchor-change effect adopts the first real key.
const prevAnchorKeyRef = useRef<string | null | undefined>(undefined)
- const pendingAnchorScrollRef = useRef<{ index: number; padding: number } | null>(null)
const renderRow = useCallback(
(index: number): ReactNode => {
@@ -176,12 +296,14 @@ function Root<T>({
if (i < items.length) {
return getItemKey(items[i], i)
}
- // The item count rides in the footer key: TanStack detects "append at the end" (the
- // `followOnAppend` stick) by a last-key change, and a constant footer key would mask every item
- // append behind it — count grows, last key stays the footer — silently breaking follow while the
- // footer (the streaming case's thinking indicator) is visible. The cost is one estimate-sized
- // frame per append while the always-mounted footer re-measures under its new key.
- return `${FOOTER_KEY}${items.length}`
+ // Constant, and it has to be: the core reads an append off the row *count* alone
+ // (`didCountChange || edge keys differ`), so appends reach its end-anchoring without the
+ // footer key rotating. Rotating it — which an earlier `followOnAppend` config did need, and
+ // that option is off now — charged a scroll correction per appended row: a fresh key misses
+ // the measurement cache, the always-mounted footer falls back to `defaultRowHeight` for a
+ // frame, and the core's at-end compensation applies that estimate error to the scroll offset.
+ // Tens of px of shove per streamed row, right where the reader is trying to scroll away.
+ return FOOTER_KEY
},
[items, getItemKey, hasHeader]
)
@@ -224,25 +346,64 @@ function Root<T>({
estimateSize: estimateVirtualRow,
overscan: overscanCount,
getItemKey: getVirtualItemKey,
- paddingEnd: anchorPadding,
// The virtualizer writes container height + row offsets to the DOM itself, in the same tick as each
// 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.
+ 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)
+ }
+ },
// No `gap` — inter-row spacing is baked into the measured row height via `paddingBottom` (see `Row`).
...(stickToBottom
? {
- // The core owns stick-to-bottom entirely: `anchorTo: 'end'` re-anchors on count/edge-key
- // change (append/prepend/reorder), `followOnAppend` scrolls to new rows when at the end,
- // and the core's resize handling compensates height-only growth (token streaming) while
- // within `scrollEndThreshold` of the end — and stops the moment the user scrolls away.
- anchorTo: 'end' as const,
- followOnAppend: 'auto' as const,
- scrollEndThreshold: BOTTOM_THRESHOLD,
+ // `anchorTo: 'end'` re-anchors on count/edge-key change (append/prepend/reorder) and the
+ // core's resize handling compensates height-only growth (token streaming) while within
+ // `scrollEndThreshold` of the end. Bottom-pinning itself is owned by the explicit
+ // pinned-state effects below, not the core (`followOnAppend` stays off). End-anchoring
+ // is strictly a pinned-state behavior: its key/count anchoring applies on every append
+ // with no threshold check, so with it always on, a reader away from the bottom is glued
+ // back to the end whenever rows land — it overrode the opening anchor scroll within
+ // milliseconds while a history replay was still folding in. Off during `itemsLoading`
+ // too: end-anchoring each partial fold walks the core's *internal* offset to the
+ // bottom, and that internal offset only re-syncs via async scroll events — so the
+ // opening anchor scroll lands, the next measurement batch compensates against the
+ // stale bottom offset, and the landing is yanked straight back down.
+ anchorTo: itemsLoading || !pinnedRef.current ? ('start' as const) : ('end' as const),
+ // The core's growth compensation (`resizeItem` re-applying a row's growth to the scroll
+ // offset whenever that offset is within this many px of the end) writes `scrollTop`
+ // synchronously, with no scroll-direction check and no knowledge of our pinned flag. At
+ // 32px that turns the bottom of the thread into flypaper: an upward gesture that stops
+ // inside the band is shoved back down by the next streamed token, the shove arrives as
+ // a downward scroll, and the re-pin test below reads *that* as the reader coming back.
+ // So the band exists only while we consider ourselves pinned, where it does its real
+ // job of smoothing growth that lands between our follow writes; unpinned, nothing but
+ // the reader may move the view — which is also what lets the re-pin test trust downward
+ // motion. Read from the ref, not from state: `useVirtualizer` calls `setOptions` during
+ // render, so the ref applies with no extra render per toggle mid-stream, and `setPinned`
+ // below covers the sub-frame window before that render happens.
+ scrollEndThreshold: pinnedRef.current && !itemsLoading ? BOTTOM_THRESHOLD : NO_END_COMPENSATION,
// Seed the virtual offset so the very first render window already emits the right rows
// (not a blank top frame): the anchor row's estimated start when opening onto an anchor,
// past the end for a plain bottom open. Summing the row estimates keeps this exact
// whatever `estimateItemHeight` returns; the pre-paint `scrollToIndex` below lands it.
+ // The seed is the core's *internal* offset only — nothing scrolls the DOM to it — so it
+ // is valid solely when the opening scroll runs in the same commit and converges the two.
+ // Mounting mid-load (the open deferred, the DOM resting at 0) it must be 0: any other
+ // value desyncs internal from DOM, and every first row measurement then "compensates"
+ // the phantom position, deterministically dragging the real scroll toward it.
initialOffset: () => {
+ if (itemsLoading) {
+ return 0
+ }
const anchorIndex = anchorItemKey != null ? findVirtualIndexForKey(anchorItemKey) : -1
const limit = anchorIndex >= 0 ? anchorIndex : rowCount
let total = 0
@@ -255,35 +416,203 @@ function Root<T>({
: {}),
})
+ // The only way to flip pinning. Two pins have to move together and in the same tick as the gesture:
+ // ours, and the core's at-end growth compensation, which is a second pin we do not otherwise control.
+ // Writing the option here is not a duplicate of the render-time value — it is the bridge across one
+ // frame. Unpinning originates in a passive wheel/touch/scroll listener, so React schedules the render
+ // that would carry the new option for after the current task, while the ResizeObserver that grows the
+ // streaming row fires inside it: without this write the core gets one more shove in, on exactly the
+ // frame the reader's gesture starts.
+ const setPinned = useCallback(
+ (next: boolean): void => {
+ if (pinnedRef.current === next) {
+ return
+ }
+ pinnedRef.current = next
+ virtualizer.options.scrollEndThreshold = next ? BOTTOM_THRESHOLD : NO_END_COMPENSATION
+ virtualizer.options.anchorTo = next ? 'end' : 'start'
+ if (next) {
+ peakTopRef.current = scrollRef.current?.scrollTop ?? 0
+ }
+ },
+ [virtualizer]
+ )
+
+ // Every scroll the component performs itself goes through here. The peak records where the *reader*
+ // has been, so a landing we caused — a replayed anchor jumping to a row mid-thread, the initial open,
+ // a follow write — has to reset it; otherwise the scroll event our own jump emits reads as the reader
+ // walking away and unpins on the spot (the slack is sub-pixel, it forgives nothing).
+ 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)
+ }
+ }, [])
+
+ // 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
+ // freshest measurements; stands down permanently the moment the reader scrolls or the thread pins
+ // (a pinned thread belongs to the follow effect).
+ const scheduleAnchorSettle = useCallback(
+ (anchorIndex: number): void => {
+ const startedAt = performance.now()
+ let remaining = ANCHOR_SETTLE_CHECKS
+ const tick = (): void => {
+ const el = scrollRef.current
+ if (!el || lastUserScrollAtRef.current > startedAt || pinnedRef.current) {
+ return
+ }
+ const target = virtualizer.getOffsetForIndex(anchorIndex, 'start')?.[0]
+ if (target !== undefined && Math.abs(el.scrollTop - target) > ANCHOR_SETTLE_TOLERANCE_PX) {
+ virtualizer.scrollToIndex(anchorIndex, { align: 'start' })
+ noteProgrammaticScroll()
+ }
+ remaining -= 1
+ if (remaining > 0) {
+ setTimeout(tick, ANCHOR_SETTLE_INTERVAL_MS)
+ }
+ }
+ setTimeout(tick, ANCHOR_SETTLE_INTERVAL_MS)
+ },
+ [virtualizer, noteProgrammaticScroll]
+ )
+
+ // The open's top-or-bottom verdict, re-taken once real measurements exist. The opening commit only
+ // has estimates for the rows under the anchor (they render and measure a few frames later), and the
+ // estimates habitually undershoot real markdown — deciding from them alone opens threads with a
+ // viewport of response at the bottom instead of on the question. So the open lands on the anchor
+ // provisionally (the scroll clamps to the bottom by itself when content is truly short) and this
+ // loop settles the verdict: enough content measured below ⇒ the anchor stands; the window ending
+ // still short — or the live stream appending before it ends, which makes the open a live-edge open —
+ // ⇒ a bottom open, pinned. Stops the moment the reader scrolls: their position, their call.
+ const scheduleOpenDecision = useCallback(
+ (anchorIndex: number): void => {
+ const startedAt = performance.now()
+ const itemsAtOpen = itemsLengthRef.current
+ let remaining = ANCHOR_SETTLE_CHECKS
+ const commitBottomOpen = (el: HTMLElement): void => {
+ el.scrollTop = el.scrollHeight
+ noteProgrammaticScroll()
+ setPinned(true)
+ }
+ const tick = (): void => {
+ const el = scrollRef.current
+ if (!el || lastUserScrollAtRef.current > startedAt || pinnedRef.current) {
+ return
+ }
+ const viewport = el.clientHeight
+ const totalSize = virtualizer.getTotalSize()
+ const anchorStart = virtualizer.measurementsCache[anchorIndex]?.start
+ const contentBelow = anchorStart !== undefined ? totalSize - anchorStart : 0
+ if (viewport > 0 && contentBelow >= viewport) {
+ return
+ }
+ if (itemsLengthRef.current !== itemsAtOpen) {
+ commitBottomOpen(el)
+ return
+ }
+ remaining -= 1
+ if (remaining > 0) {
+ setTimeout(tick, ANCHOR_SETTLE_INTERVAL_MS)
+ return
+ }
+ commitBottomOpen(el)
+ }
+ setTimeout(tick, ANCHOR_SETTLE_INTERVAL_MS)
+ },
+ [virtualizer, noteProgrammaticScroll, setPinned]
+ )
+
// Initial open (once): land before the browser paints, so a long thread never shows a top-frame
- // flicker or a visible crawl. Reopen where the reader left off: with an anchor (the last human
- // message) the thread opens on the last meaningful turn — anchor row at the top, its response below —
- // not the absolute bottom; scroll clamping degrades this to the bottom when little content follows the
- // anchor. No anchor ⇒ plain bottom open. TanStack's built-in RAF reconciliation holds the landing
- // steady as rows measure — replacing the old settle loop.
+ // flicker or a visible crawl. A thread that already has messages opens on its last meaningful turn —
+ // the anchor row (the last human message) at the top of the viewport, its response below — whether or
+ // not the agent is still working on it: a reader arriving mid-turn wants the question that was asked,
+ // not the tail of the answer to it. That is only possible when at least a viewport of content follows
+ // the anchor; with less, the scroll clamps and the open is a plain bottom open — no padding is ever
+ // reserved to force the anchor higher, the message just sits wherever the content puts it. No anchor
+ // ⇒ bottom open too.
+ //
+ // Whether the landing starts pinned follows from its kind: an anchor at the top is a reading
+ // position, so it unpins and streaming must not steal it; a bottom open pins, following from the
+ // first frame whenever a turn is live.
+ // Waits for the items to finish assembling, not merely for one to exist: the run-context header and
+ // the thinking footer can commit before any message does, and with debug rows enabled the history
+ // replay's earliest fold commits carry renderable console items long before the human turns land.
+ // Spending the once-only open on such a commit finds no anchor and opens the thread at the bottom.
useLayoutEffect(() => {
- if (!virtualized || !stickToBottom || didInitialScrollRef.current || rowCount === 0) {
+ if (!virtualized || !stickToBottom || didInitialScrollRef.current || itemsLoading || items.length === 0) {
return
}
didInitialScrollRef.current = true
const anchorIndex = anchorItemKey != null ? findVirtualIndexForKey(anchorItemKey) : -1
+ const el = scrollRef.current
if (anchorIndex >= 0) {
+ // Provisional anchor landing — this commit only has estimates for the rows under the anchor,
+ // so whether the thread is really "top" or "bottom" shaped is decided by the decision loop
+ // once measurements land (see `scheduleOpenDecision`). The scroll itself is safe under
+ // either truth: a genuinely short thread clamps to the bottom on its own. The reconciler
+ // this arms re-targets a *stable* offset — rows above the anchor don't move when the tail
+ // grows — so it settles in a frame or two; the settle loop then covers the drift the
+ // reconciler can't (see `scheduleAnchorSettle`).
virtualizer.scrollToIndex(anchorIndex, { align: 'start' })
+ noteProgrammaticScroll()
+ setPinned(false)
+ bottomRepinBlockedUntilRef.current = performance.now() + BOTTOM_REPIN_BLOCK_MS
+ scheduleAnchorSettle(anchorIndex)
+ scheduleOpenDecision(anchorIndex)
+ return
+ }
+ if (turnActive && el) {
+ // Deliberately not `scrollToIndex` for a thread that is already streaming: that arms the
+ // core's reconciler against a target that never stabilizes — it recomputes the growing end
+ // every frame for up to five seconds, with no notion of a user gesture cancelling it, so
+ // every upward scroll the reader attempts in that window is undone. The follow effect below
+ // owns the landing instead: it holds the bottom as rows measure and yields the moment the
+ // reader scrolls away.
+ el.scrollTop = el.scrollHeight
} else {
+ // Settled thread: nothing is growing, so the reconciler's target stabilizes within a frame
+ // or two, and it is the accurate way to land on the last row's end while rows are
+ // unmeasured.
virtualizer.scrollToIndex(rowCount - 1, { align: 'end' })
}
- }, [virtualized, stickToBottom, rowCount, virtualizer, anchorItemKey, findVirtualIndexForKey])
-
- // Anchor-on-change (see `anchorItemKey`): a key change means a new anchor row landed. A *trailing*
- // anchor (nothing after it yet) is a fresh send — reserve enough bottom padding for the row to reach
- // the top of the viewport (via the paired effect below, once the padding is in the DOM) so the
- // response streams into the space below. An anchor that already has content after it (a replayed
- // turn) just scrolls — reserving there would leave dead whitespace under a finished response. The
- // first populated commit only adopts the key: the initial-open effect above owns that scroll.
+ noteProgrammaticScroll()
+ setPinned(true)
+ }, [
+ virtualized,
+ stickToBottom,
+ rowCount,
+ virtualizer,
+ turnActive,
+ anchorItemKey,
+ itemsLoading,
+ findVirtualIndexForKey,
+ noteProgrammaticScroll,
+ setPinned,
+ scheduleAnchorSettle,
+ scheduleOpenDecision,
+ items.length,
+ ])
+
+ // Anchor-on-change (see `anchorItemKey`): a key change means a new anchor row landed. An anchor the
+ // thread has never held before is a fresh send — pin to the bottom and follow the answer from there;
+ // the sent message rides up naturally as the response streams in. An anchor whose key already
+ // existed (a replayed turn) just scrolls to it. Novelty, not position: the fold inserts a sent
+ // message at the *turn start*, behind any debug/status rows the turn already carries, so on a send
+ // the anchor is frequently not the trailing item and any is-it-last test classifies the send by
+ // whichever frames happened to land first. The first populated commit only adopts the key: the
+ // initial-open effect above owns that scroll.
+ // Gated on `itemsLoading` like the initial open — adopting mid-replay would pin the pre-history
+ // anchor value (typically null) and misread the full history's anchor as a fresh send.
useLayoutEffect(() => {
- if (!virtualized || items.length === 0) {
+ if (!virtualized || itemsLoading || items.length === 0) {
return
}
+ const prevKeys = prevItemKeysRef.current
+ prevItemKeysRef.current = new Set(items.map((item, index) => getItemKey(item, index)))
const prev = prevAnchorKeyRef.current
if (prev === undefined) {
prevAnchorKeyRef.current = anchorItemKey ?? null
@@ -297,49 +626,212 @@ function Root<T>({
if (anchorIndex < 0) {
return
}
- const isTrailingItem = anchorIndex === (hasHeader ? 1 : 0) + items.length - 1
- if (!isTrailingItem) {
+ const isFreshSend = prevKeys === null || !prevKeys.has(anchorItemKey)
+ if (!isFreshSend) {
virtualizer.scrollToIndex(anchorIndex, { align: 'start' })
+ noteProgrammaticScroll()
+ // Same estimate-clamp settle as the initial open: the landing may touch the bottom
+ // transiently, and those touches must not read as the reader arriving there.
+ bottomRepinBlockedUntilRef.current = performance.now() + BOTTOM_REPIN_BLOCK_MS
+ scheduleAnchorSettle(anchorIndex)
return
}
- // `getTotalSize()` first: it recomputes the measurements, so the `measurementsCache` read below
- // reflects this commit's rows (including the anchor row's just-taken first measurement).
- const totalSize = virtualizer.getTotalSize()
- const anchorStart = virtualizer.measurementsCache[anchorIndex]?.start
- const viewport = scrollRef.current?.clientHeight ?? 0
- if (anchorStart === undefined || viewport === 0) {
+ // Sending is an explicit request to follow the answer, wherever the reader had scrolled to
+ // while composing — pin and land on the bottom now rather than leaving it to the reader; the
+ // follow effect keeps it there as the turn streams.
+ setPinned(true)
+ const el = scrollRef.current
+ if (el) {
+ el.scrollTop = el.scrollHeight
+ noteProgrammaticScroll()
+ }
+ }, [
+ virtualized,
+ items,
+ getItemKey,
+ anchorItemKey,
+ itemsLoading,
+ findVirtualIndexForKey,
+ virtualizer,
+ setPinned,
+ noteProgrammaticScroll,
+ scheduleAnchorSettle,
+ ])
+
+ // Pin/unpin from what the reader did, not from where they ended up. Movement that the scroll range
+ // itself doesn't explain is the reader; everything else is content shifting under them. Asymmetric on
+ // purpose: leaving takes the smallest upward movement, because a gesture the view fights is the whole
+ // complaint, while returning takes an actual arrival at the bottom, because anything looser re-arms
+ // the follow while the reader is still reading a few lines up.
+ //
+ // The wheel and touch listeners catch the *first* frame — they fire before the scroll they cause, and
+ // they register even when the offset can't move (already at the top, or the frame's growth cancels the
+ // gesture out). The scroll listener catches everything without a gesture event: scrollbar drags,
+ // PageUp, momentum.
+ useEffect(() => {
+ const el = scrollRef.current
+ if (!virtualized || !stickToBottom || !el) {
return
}
- // Content below the anchor's top edge, excluding the currently reserved padding — the new reserve
- // must top it up to a full viewport so the anchor row can sit flush at the top.
- const contentBelow = totalSize - anchorPadding - anchorStart
- const padding = Math.max(0, Math.ceil(viewport - contentBelow))
- pendingAnchorScrollRef.current = { index: anchorIndex, padding }
- setAnchorPadding(padding)
- }, [virtualized, items.length, anchorItemKey, findVirtualIndexForKey, virtualizer, anchorPadding, hasHeader])
-
- // Runs every commit: performs the pending anchor scroll only once the reserved padding is committed to
- // the DOM — scrolling earlier would clamp against the un-padded scroll range and land short of the top.
+ peakTopRef.current = el.scrollTop
+ let touchStartY: number | null = null
+ let touchStartX: number | null = null
+ const onWheel = (event: WheelEvent): void => {
+ if (event.deltaY !== 0) {
+ lastUserScrollAtRef.current = performance.now()
+ }
+ if (event.deltaY < 0) {
+ setPinned(false)
+ } else if (event.deltaY > 0) {
+ // An explicit downward gesture is unambiguous — the reader heading for the bottom must
+ // not be told "not yet" by the post-landing block.
+ bottomRepinBlockedUntilRef.current = 0
+ }
+ }
+ const onTouchStart = (event: TouchEvent): void => {
+ const touch = event.touches[0]
+ touchStartY = touch?.clientY ?? null
+ touchStartX = touch?.clientX ?? null
+ }
+ // A finger moving *down* scrolls the content up. Vertical dominance is required so a horizontal
+ // swipe across a wide tool card or code block doesn't read as leaving the bottom.
+ const onTouchMove = (event: TouchEvent): void => {
+ const touch = event.touches[0]
+ if (!touch || touchStartY === null || touchStartX === null) {
+ return
+ }
+ const deltaY = touch.clientY - touchStartY
+ if (Math.abs(deltaY) > Math.abs(touch.clientX - touchStartX)) {
+ lastUserScrollAtRef.current = performance.now()
+ if (deltaY > 0) {
+ setPinned(false)
+ } else if (deltaY < 0) {
+ // Finger moving up scrolls the content down — the same explicit "heading for the
+ // bottom" signal as a downward wheel, so it clears the post-landing block too.
+ bottomRepinBlockedUntilRef.current = 0
+ }
+ }
+ }
+ const onScroll = (): void => {
+ const top = el.scrollTop
+ 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
+ // browser clamps `scrollTop` down with it. That
+ // is an offset decrease nobody asked for, and reading it as a gesture would unpin the thread
+ // mid-turn every time a tool finished. A clamp can never pull below the new maximum, so the
+ // maximum is the line between "the content moved" and "the reader moved". Growth needs no
+ // such correction: it moves `scrollHeight`, never `scrollTop`.
+ peakTopRef.current = Math.min(peakTopRef.current, maxTop)
+ // An event that lands where software recently wrote is a write echoing back, not the reader
+ // (see `programmaticScrollsRef`) — adopt the position and decide nothing from it. A reader
+ // gesture racing this window still lands on a different offset (or came in as a wheel/touch
+ // event, which unpins before any scroll event fires).
+ const now = performance.now()
+ const writes = programmaticScrollsRef.current
+ while (writes.length > 0 && now - writes[0].at >= PROGRAMMATIC_SCROLL_MATCH_MS) {
+ writes.shift()
+ }
+ const prevEventTop = lastScrollEventTopRef.current
+ lastScrollEventTopRef.current = top
+ if (writes.some((write) => Math.abs(top - Math.min(Math.max(0, write.value), maxTop)) <= UNPIN_SLACK)) {
+ peakTopRef.current = top
+ return
+ }
+ // A downward move that lands exactly on the (new) maximum is the shrink clamp again — no
+ // write explains it because the browser performed it, and counting it as the reader would
+ // cancel a settle loop the moment a tool card above collapses.
+ const isShrinkClamp = prevEventTop !== null && top < prevEventTop && top >= maxTop - UNPIN_SLACK
+ if (!isShrinkClamp) {
+ lastUserScrollAtRef.current = performance.now()
+ }
+ if (pinnedRef.current) {
+ if (top < peakTopRef.current - UNPIN_SLACK) {
+ setPinned(false)
+ } else {
+ peakTopRef.current = Math.max(peakTopRef.current, top)
+ }
+ return
+ }
+ if (
+ followingRef.current &&
+ maxTop - top <= AT_BOTTOM_EPSILON &&
+ performance.now() >= bottomRepinBlockedUntilRef.current
+ ) {
+ setPinned(true)
+ }
+ }
+ el.addEventListener('wheel', onWheel, { passive: true })
+ el.addEventListener('touchstart', onTouchStart, { passive: true })
+ el.addEventListener('touchmove', onTouchMove, { passive: true })
+ el.addEventListener('scroll', onScroll, { passive: true })
+ return () => {
+ el.removeEventListener('wheel', onWheel)
+ el.removeEventListener('touchstart', onTouchStart)
+ el.removeEventListener('touchmove', onTouchMove)
+ el.removeEventListener('scroll', onScroll)
+ }
+ // 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.
+ }, [virtualized, stickToBottom, setPinned])
+
+ // The turn's tail arrives after the turn is over — usage and cost come on their own stream frames and
+ // the footer swaps to them a commit or two later — so following has to outlast `turnActive` by a beat
+ // or that last row renders just below the fold. Timed rather than keyed on the content itself: what
+ // lands after a turn ends is open-ended, and the grace costs nothing because an upward gesture unpins
+ // through it just the same.
+ useEffect(() => {
+ const wasActive = prevTurnActiveRef.current
+ prevTurnActiveRef.current = turnActive
+ if (turnActive || !wasActive) {
+ setFollowGrace(false)
+ return
+ }
+ setFollowGrace(true)
+ const timeout = setTimeout(() => setFollowGrace(false), FOLLOW_GRACE_MS)
+ return () => clearTimeout(timeout)
+ }, [turnActive])
+
+ // Runs every commit: while a turn is live (or just ended, see above) and the reader is pinned, keep
+ // the bottom in view. Each streamed frame is a commit, so this needs no other trigger; the core's
+ // at-end resize compensation smooths growth that lands between commits. Writes `scrollTop` directly
+ // instead of `scrollToEnd()`: the latter arms the core's multi-frame scroll reconciler, which
+ // re-targets the (growing) end every frame and overrides the user's attempt to scroll away —
+ // exactly the gesture that must win here.
useLayoutEffect(() => {
- const pending = pendingAnchorScrollRef.current
- if (!pending || pending.padding !== anchorPadding) {
+ // Inert while items are still assembling: following a partial fold would walk the scroll to the
+ // bottom of a thread whose open — which owns the landing — hasn't happened yet.
+ if (!virtualized || !stickToBottom || itemsLoading || !following || !pinnedRef.current) {
return
}
- pendingAnchorScrollRef.current = null
- virtualizer.scrollToIndex(pending.index, { align: 'start' })
+ const el = scrollRef.current
+ if (el && el.scrollHeight - el.scrollTop - el.clientHeight > AT_BOTTOM_EPSILON) {
+ el.scrollTop = el.scrollHeight
+ noteProgrammaticScroll()
+ }
})
// Mobile Safari: the soft keyboard shrinks the visual (not layout) viewport, so a pinned bottom can slip
- // behind it. Re-assert on visualViewport changes.
+ // behind it. Re-assert on visualViewport changes — for a reader who is actually pinned; a proximity
+ // check here would be the last place a bottom band could yank back someone who scrolled away.
useEffect(() => {
if (!virtualized || !stickToBottom || typeof window === 'undefined' || !window.visualViewport) {
return
}
const viewport = window.visualViewport
const onViewportChange = (): void => {
- if (virtualizer.isAtEnd(BOTTOM_THRESHOLD)) {
- requestAnimationFrame(() => virtualizer.scrollToEnd())
+ if (!pinnedRef.current) {
+ return
}
+ // By hand, not `scrollToEnd()`, for the same reason the follow effect writes `scrollTop`
+ // itself: that call arms the core's multi-frame reconciler, which the reader cannot interrupt.
+ requestAnimationFrame(() => {
+ const el = scrollRef.current
+ if (el && el.scrollHeight - el.scrollTop - el.clientHeight > AT_BOTTOM_EPSILON) {
+ el.scrollTop = el.scrollHeight
+ noteProgrammaticScroll()
+ }
+ })
}
viewport.addEventListener('resize', onViewportChange)
viewport.addEventListener('scroll', onViewportChange)
@@ -347,7 +839,7 @@ function Root<T>({
viewport.removeEventListener('resize', onViewportChange)
viewport.removeEventListener('scroll', onViewportChange)
}
- }, [virtualized, stickToBottom, virtualizer])
+ }, [virtualized, stickToBottom, noteProgrammaticScroll])
const rootValue = useMemo<RootContextValue>(
() => ({ measureElement: virtualizer.measureElement, gap, maxWidthClassName, virtualized }),
@@ -382,25 +874,25 @@ function Root<T>({
return (
<RootContext.Provider value={rootValue}>
<div className={cn('flex flex-col h-full min-h-0 w-full', className)}>
+ {/*
+ * `overflow-anchor: none` because the virtualizer already owns every row's position and
+ * compensates content growth itself. Chrome's native scroll anchoring would compensate the
+ * same growth a second time — the rows are absolutely positioned inside the scroller, so
+ * they are anchor candidates, not excluded — and two independent corrections for one
+ * resize is a shake by construction.
+ */}
<div
ref={scrollRef}
- className={cn('flex-1 min-h-0 overflow-y-auto overflow-x-hidden overscroll-contain', listClassName)}
+ className={cn(
+ 'flex-1 min-h-0 overflow-y-auto overflow-x-hidden overscroll-contain [overflow-anchor:none]',
+ listClassName
+ )}
>
{/* Height is written imperatively by the virtualizer (`containerRef` + `directDomUpdates`). */}
<div ref={virtualizer.containerRef} style={{ position: 'relative', width: '100%' }}>
- {virtualizer.getVirtualItems().map((vi) => {
- const key = String(vi.key)
- return (
- <InternalRow
- // The footer's virtual key rotates per append (see `getVirtualItemKey`) but its React
- // identity must not — remounting it would reset footer-local state (e.g. the thinking
- // indicator's rotation timer) on every appended row.
- key={key.startsWith(FOOTER_KEY) ? FOOTER_KEY : key}
- index={vi.index}
- renderRow={renderRow}
- />
- )
- })}
+ {virtualizer.getVirtualItems().map((vi) => (
+ <InternalRow key={String(vi.key)} index={vi.index} renderRow={renderRow} />
+ ))}
</div>
</div>
</div>