: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
refactor(posthog_ai): migrate VirtualizedThread from react-window to TanStack Virtual (#67666)
Georgiy Tarasov203684893dc9
diff --git a/frontend/package.json b/frontend/package.jsonindex a1a25374b1a9..7390b831408b 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -149,6 +149,7 @@"@simplewebauthn/browser": "^13.2.2","@stripe/react-stripe-js": "^2.8.0","@stripe/stripe-js": "^4.5.0",+ "@tanstack/react-virtual": "^3.14.3","@testing-library/dom": ">=9.3.4","@tiptap/core": "3.20.1","@tiptap/extension-code-block-lowlight": "3.20.1",diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6a2f18e29b32..6dd80b615fa4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4404,6 +4404,26 @@ snapshots:hash: v1.k794b7964.7d42222ea3b3472183c676ef7a66f546b31dc178c0f160cf857356f64d63ea53.sXR8gsAy2i5_S9Ty1fnLGgnZmP8MGncm1iEt6z2esI8products-posthog-ai-runalertactivity--connection-lost--light:hash: v1.k794b7964.2112a18454f05a8ad2283cf4784f8bfb308c08e971a8c1ba7d1c9f09295b4ecf.DgVdEj2TYus9n65ozaoy2nm_4L6vJx38hJPE3pxq45g+ products-posthog-ai-virtualizedthread--bounded-embed--dark:+ hash: v1.k794b7964.3654eccce875b2647d60ed3d63ef7b931f816bf9a909e882e4124af248bc5237.d_GnZyfxRooS8JpR9PWZPy8voXShxV1MhN_f-y-9sSU+ products-posthog-ai-virtualizedthread--bounded-embed--light:+ hash: v1.k794b7964.69656756a67c0a767697dad493cd8723d1b0b02d6139daa7ccf239e13bbf4b18.Gn-HL-umfDc_UzayRriBJHxgfmh68ZKco5cZHJM8-QQ+ products-posthog-ai-virtualizedthread--empty--dark:+ hash: v1.k794b7964.3c6bd1817f79c0b71b0a35d9b4ad0cb849e535848cfdde260a247512e8809867.LFzd0rlATuBsPxh2yr6hSn3azdZnap1SJakTPsIXrxA+ products-posthog-ai-virtualizedthread--empty--light:+ hash: v1.k794b7964.cba8d5296d97792661212d90a466f4342e6d294f599f9d88c5e8c7fc5fc50276.sEJXRBTpONyFemcwSFRthEN4jGic_598f_-rBcUihdU+ products-posthog-ai-virtualizedthread--flow-mode--dark:+ hash: v1.k794b7964.8ae00f228b650921e150c11dfea6b12dd4bdafdc79fb8719f23e40e4bff5f1b4.nhovHqVlxH4rM2NTbOhJwXIpyim_y4VujH4ULUu8J9c+ products-posthog-ai-virtualizedthread--flow-mode--light:+ hash: v1.k794b7964.a474c06ab48650a728e98b457fcde2507028d41662b6aa4a76306c7313ccc40f.0FJqdKxwms0G3OSIp39fsQXJqh2Pvw3mKHebXnQD7wI+ products-posthog-ai-virtualizedthread--header-footer-only--dark:+ hash: v1.k794b7964.f871490a90f21e7396cf85ca29406ee82b2057eeddc81beb76c45fa1f0b38fec.x2WRDzfjAny2ZHFUSDjdIqxV2ZUVw6nv6LoYAVy3Tek+ products-posthog-ai-virtualizedthread--header-footer-only--light:+ hash: v1.k794b7964.c40751f22ab1f0d2fd0911d01da3dd63993a6ce1c12e5a6ef15a578df56cf38c.i86QjfqJZAIuAAVNayl7ebKkRCugCy3GUmCq1FbtGTg+ products-posthog-ai-virtualizedthread--long-thread--dark:+ hash: v1.k794b7964.db52fa12fc166be411a4be0f4e5a1a0fc9ae83956506095f543208a7a64b5619.QnzV9aSYTYrYtYHqAw55a9D2fhoZo_IvxEYSe2KsXac+ products-posthog-ai-virtualizedthread--long-thread--light:+ hash: v1.k794b7964.0dd9ece6534a30639fe65f18a2aa5830d7ec6b792266dc56c54c86d35a26c21c.SFLgQDaDq9Rs9b86vgkC2een50HyFXWctj7Pksmf8Isproducts-workflows-customerioimportmodal--all-steps-completed--dark:hash: v1.k794b7964.679720cf72d72cd35bb4c4a2e86094627df27ff2798b4244c5d29a6a767f3861.AvZ-0V3qNglzE2ZWUOcEjHFnSe9Qs68t-u03-ytn7VIproducts-workflows-customerioimportmodal--all-steps-completed--light:@@ -6857,17 +6877,17 @@ snapshots:scenes-app-tasks--loading--light:hash: v1.k794b7964.145588aca6bc14073df42b8b3789d46a195bc613e2363deef3f94082dd2f4979._C5LoopHdD4uoMtdsJntgYT_nzwvbKDjTnKqR1EOQtMscenes-app-tasks--mobile-list--dark:- hash: v1.k794b7964.e65c5e289cbb347ed1cc035d3a381c56503b67ef643db47dd2e02f32fac047a8.aNQOxj2nwQyFuzC8E3a1YGPFtaxje7hw1Eb7HbBLyfQ+ hash: v1.k794b7964.a0a985b52a8331bf69fda86b8dc2c7af689a31eaf1990bc693b5f2dbd2ecd4b1.51RqCmZxdfUQHlZ-XD0FywRGawgRagqI9YDwnnYBhrEscenes-app-tasks--mobile-list--light:- hash: v1.k794b7964.a42e7297c99d46bf03e8ba9c7576b164e120a41c914d1d52824823140b8fae92.nCFkmftkVPQYI7UqGBF84D6YQ52LTeSiWkz6w_K_YWM+ hash: v1.k794b7964.50c8ac93976b058d01b73dad46708ba0ef914ca4fdba16327e95828c269937b8.7a_rsE1aagzO9X_AndD14I2F5_XU6tBCzO2zwfrS8-oscenes-app-tasks--mobile-new-task--dark:hash: v1.k794b7964.de22e10e282dd787afc1fc4784d1aef6064b32b7c3bed6b3bced8ba776264cf2.UCqKfpWcRlmvwmvML2DjdyVQCwj3zUZpXlKA8wxMgVsscenes-app-tasks--mobile-new-task--light:hash: v1.k794b7964.cf669044c3c0e2b6d870e588a22f58be3032bec6d90a2c1c3b1ee1412a491661.3mNJ_P0G8pSfhi3oEkjsTKKG7wVSFB9jdY7ujjDXj7kscenes-app-tasks--mobile-task-selected--dark:- hash: v1.k794b7964.7a885468ce6eee10b0835ef0b76f5c5dd45d35d90273d972bcb8023d9c943b62.4O4SeGjvj3rHSH0F5LinWCoJv7oGd0UgG39TRxQQeEo+ hash: v1.k794b7964.d7c9b5029050478dd7cb80b1ed74634374afd58e20d36b5518adb493f34b6301.DfxUOM0JvzedJL83fmS12yK_lfRaxfAcdqu9fGAO0JYscenes-app-tasks--mobile-task-selected--light:- hash: v1.k794b7964.00797fdb57fa653b857ff7fdf25637a36d62cb154d37cecee705687ef02b17d3.M87ub65d6ey1Ny2hpCl6o-NLyohPeBZFZ6Mg7BmEIso+ hash: v1.k794b7964.7ec4174f866286b0f1b2ea6f4a62525a44e1fb90d9b90a252d1c6ef49c70965f.APpNECCS5zOAoFgVr2Boha_nxKW6g3t19T1wv_EWaZ4scenes-app-tasks--new-task--dark:hash: v1.k794b7964.bf8b6abf4b61c5a5a753a4a4b65a68a826083843c72ce5c84874a5f8b1a351f0.4_xbfeooSsTCGwEbJXXSsU9vEwOIJ51xCba_zMO0sL8scenes-app-tasks--new-task--light:diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4883da9a6611..e7ad4437df08 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -792,6 +792,9 @@ importers:'@stripe/stripe-js':specifier: ^4.5.0version: 4.5.0+ '@tanstack/react-virtual':+ specifier: ^3.14.3'@testing-library/dom':specifier: '>=9.3.4'version: 9.3.4@@ -3787,6 +3790,9 @@ importers:'@storybook/react':specifier: 'catalog:'version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])+ '@tanstack/react-virtual':+ specifier: '*''@types/react':specifier: 18.3.27version: 18.3.27@@ -3832,9 +3838,6 @@ importers:react-intersection-observer:specifier: ^9.5.3version: 9.5.3([email protected])- react-window:- specifier: '*'tailwind-merge:specifier: '*'version: 2.2.2@@ -11610,10 +11613,19 @@ packages:react: 18.3.1react-dom: 18.3.1+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-k/cnHPVaOfn46hSbiY6n4Dzf4QjCGWSF40zR5QIIYUqPAjpA6TN7InfYmcMiDVQGP2iUn9xsRbAl8u1v3UmeVQ==}+ peerDependencies:+ react: 18.3.1+ react-dom: 18.3.1+'@tanstack/[email protected]':resolution: {integrity: sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==}engines: {node: '>=12'}+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-VZyW2Uiml5tmBZwPGrSD3Sz73OxzljQMCmzYHsUTPEuTsERf5xwa+uWb01xEzkz3ZSYTjj8NEb/mKHvgKxyZdA==}+'@temporalio/[email protected]':resolution: {integrity: sha512-kKEIrHMTsANiEpDVZd+v3OT6kU20UtcvAK7iibJNzQnoZUGC7XnqdKQlBuGYBxgpJzD9ppGgskXRczW+XU5Kng==}engines: {node: '>= 20.0.0'}@@ -31741,8 +31753,16 @@ snapshots:react: 18.3.1react-dom: 18.3.1([email protected])+ dependencies:+ '@tanstack/virtual-core': 3.17.1+ react: 18.3.1+ react-dom: 18.3.1([email protected])+'@tanstack/[email protected]': {}+ '@tanstack/[email protected]': {}+'@temporalio/[email protected]':dependencies:'@temporalio/client': 1.15.0diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsxindex 0495b16acdb1..259df3505a49 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx@@ -224,9 +224,9 @@ function RunSurfaceComposer({ children }: { children?: ReactNode }): JSX.Elementreturn null // no composer UI supplied (e.g. ReadonlyRunSurface) or pre-bootstrap}return (- <div data-attr="composer" className="px-4 pb-4">- <LemonDivider className="mt-0 mb-3" />- <div className="mx-auto w-full max-w-180 space-y-2">{children}</div>+ <div data-attr="composer" className="px-4 pb-[calc(1rem_+_env(safe-area-inset-bottom))]">+ <LemonDivider className="mt-0 mb-4" />+ <div className="mx-auto w-full max-w-180">{children}</div></div>)}diff --git a/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx b/products/posthog_ai/frontend/components/ThreadView.connection.test.tsxindex c5f8e862ea51..b7ec2b18a214 100644--- a/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx@@ -22,7 +22,7 @@ describe('ThreadView connection state', () => {initKeaTests()logic = runStreamLogic(props)logic.mount()- // virtualized={false} so react-window rows render in document flow under jsdom.+ // virtualized={false} so rows render in document flow under jsdom.render(<Provider><BindLogic logic={runStreamLogic} props={props}>diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsxindex 872335a7b3f8..a17d573b2993 100644--- a/products/posthog_ai/frontend/components/ThreadView.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.tsx@@ -1,5 +1,5 @@import { useValues } from 'kea'-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { memo, useCallback, useEffect, useMemo, useState } from 'react'import { inStorybookTestRunner } from 'lib/utils/dom'@@ -19,6 +19,30 @@ function getThreadItemKey(item: ThreadItem): string {return item.id}+/**+ * Typical rendered height per item type (px, gap excluded). These seed the virtualizer before a row is+ * first measured; the closer they sit to reality, the less the scroll position has to be corrected while+ * scrolling up through unvisited rows — which is what reads as drag/jumping. Rough is fine, order of+ * magnitude matters: a collapsed tool card is ~2 lines, a markdown message is a paragraph or more.+ */+const THREAD_ITEM_HEIGHT_ESTIMATES: Partial<Record<ThreadItem['type'], number>> = {+ human_message: 160,+ assistant_message: 46,+ assistant_thought: 26,+ tool_invocation: 42,+ turn_separator: 24,+ error: 42,+ status: 42,+ compact_boundary: 42,+ task_notification: 26,+ progress: 42,+ debug: 30,+}++function estimateThreadItemHeight(item: ThreadItem): number {+ return THREAD_ITEM_HEIGHT_ESTIMATES[item.type] ?? 56+}+interface ThreadViewProps {/*** Pass `false` when an ancestor already owns scroll (the live Max column + auto-scroller) — rows then@@ -66,13 +90,20 @@ export function ThreadView({runConnectionState,} = 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.+ const anchorItemKey = useMemo(+ () => threadItems.findLast((item) => item.type === 'human_message')?.id ?? null,+ [threadItems]+ )const hasActiveProgressItem = threadItems.some((item) => item.type === 'progress' && item.progressSteps?.some((step) => step.status === 'in_progress'))// Header/footer are kept as memoized leaf components with stable element identity so they don't rebuild// `VirtualizedThread`'s `renderRow` (and re-sweep visible rows) on every streamed frame. Each is wrapped- // in `VirtualizedThread.Row` like the item rows so it gets react-window positioning + height measurement.+ // in `VirtualizedThread.Row` like the item rows so it gets virtualized positioning + height measurement.const { branch, baseBranch, repo } = runArtifactsconst header = useMemo(() =>@@ -124,15 +155,6 @@ export function ThreadView({])- // Rule 11 here: https://x.com/shadcn/status/2070394918720221522 - open scrolled to the top of the last user message.- // `VirtualizedThread` reads this only on first content, so capture it once the thread first has items and never- // recompute as it streams. `-1` (no user message) falls through to open-at-bottom.- const initialTopItemIndexRef = useRef<number | null>(null)- if (initialTopItemIndexRef.current === null && threadItems.length > 0) {- initialTopItemIndexRef.current = threadItems.findLastIndex((item: ThreadItem) => item.type === 'human_message')- }- const initialTopItemIndex = initialTopItemIndexRef.current-const renderItem = useCallback((item: ThreadItem, index: number): JSX.Element => (<VirtualizedThread.Row className={rowClassName}>@@ -153,10 +175,11 @@ export function ThreadView({<VirtualizedThread.Rootitems={threadItems}getItemKey={getThreadItemKey}+ estimateItemHeight={estimateThreadItemHeight}+ anchorItemKey={anchorItemKey}header={header}footer={footer}stickToBottom- initialTopItemIndex={initialTopItemIndex}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.tsxnew file mode 100644index 000000000000..a143e526d825--- /dev/null+++ b/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsx@@ -0,0 +1,221 @@+import type { Meta, StoryObj } from '@storybook/react'+import { useEffect, useRef, useState } from 'react'++import { cn } from 'lib/utils/css-classes'+import { inStorybookTestRunner } from 'lib/utils/dom'++import { VirtualizedThread } from './VirtualizedThread'++// Standalone, logic-free harness for the virtualized thread presenter — no `runStreamLogic`, no real+// `ThreadRow`. Fixtures are deterministic fake messages of varying height, exactly the shape that regressed+// twice (open-at-bottom flicker + the streaming stick-to-bottom crash). Each row is wrapped in+// `VirtualizedThread.Row` like the real consumer does.+const meta: Meta = {+ title: 'Products/PostHog AI/VirtualizedThread',+ tags: ['autodocs'],+}+export default meta++type Story = StoryObj++interface FakeItem {+ id: string+ role: 'user' | 'assistant'+ text: string+}++const LOREM =+ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore ' ++ 'et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut ' ++ 'aliquip ex ea commodo consequat.'++/** Deterministic variable-height content — every 3rd row is long, so rows measure to different heights. */+function makeItems(count: number): FakeItem[] {+ return Array.from({ length: count }, (_, i) => ({+ id: `item-${i}`,+ role: i % 2 === 0 ? 'assistant' : 'user',+ text: i % 3 === 0 ? `#${i} — ${LOREM} ${LOREM}` : `#${i} — ${LOREM.slice(0, 60)}`,+ }))+}++function FakeMessage({ role, text }: { role: FakeItem['role']; text: string }): JSX.Element {+ return (+ <div className={cn('rounded border p-3 bg-surface-primary', role === 'user' && 'ml-8')}>+ <div className="text-xs text-muted mb-1">{role}</div>+ <div className="text-sm">{text}</div>+ </div>+ )+}++const getKey = (item: FakeItem): string => item.id++// Story wrappers use a fixed `w-180` (720px, the thread's own max row width) instead of `w-full`: in the+// visual-regression runtime `#storybook-root` is `inline-block` (it hugs the component), and the virtualized+// rows are absolutely positioned — no intrinsic width — so a percentage width collapses the snapshot to the+// wrapper's 2px border.++/** Long static thread — opens already scrolled to the last message, with no top-frame flicker or crawl. */+export const LongThread: Story = {+ render: () => {+ const items = makeItems(80)+ return (+ <div className="h-[600px] w-180 border rounded overflow-hidden">+ <VirtualizedThread.Root items={items} getItemKey={getKey} stickToBottom>+ {(item) => (+ <VirtualizedThread.Row>+ <FakeMessage role={item.role} text={item.text} />+ </VirtualizedThread.Row>+ )}+ </VirtualizedThread.Root>+ </div>+ )+ },+}++/** Bounded embed (mirrors the inbox `h-[420px] overflow-hidden` detail panel) — the Root owns the only scroll. */+export const BoundedEmbed: Story = {+ render: () => {+ const items = makeItems(40)+ return (+ <div className="h-[420px] w-180 mx-auto border rounded overflow-hidden">+ <VirtualizedThread.Root+ items={items}+ getItemKey={getKey}+ header={+ <VirtualizedThread.Row>+ <div className="text-xs text-muted p-2">Run context header</div>+ </VirtualizedThread.Row>+ }+ stickToBottom+ >+ {(item) => (+ <VirtualizedThread.Row>+ <FakeMessage role={item.role} text={item.text} />+ </VirtualizedThread.Row>+ )}+ </VirtualizedThread.Root>+ </div>+ )+ },+}++/**+ * 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.+ */+export const Streaming: Story = {+ tags: ['test-skip'],+ render: () => {+ const [items, setItems] = useState<FakeItem[]>(() => makeItems(6))+ const [tail, setTail] = useState('Thinking')+ const tickRef = useRef(0)++ useEffect(() => {+ if (inStorybookTestRunner()) {+ return+ }+ const interval = setInterval(() => {+ tickRef.current += 1+ const tick = tickRef.current+ // Alternate between growing the last message (token stream) and appending a new one.+ if (tick % 4 === 0) {+ setItems((prev) => [+ ...prev,+ { id: `stream-${tick}`, role: 'assistant', text: `#${prev.length} — streamed message` },+ ])+ setTail('Thinking')+ } else {+ setTail((prev) => `${prev} ${LOREM.slice(0, 40)}`)+ }+ }, 700)+ return () => clearInterval(interval)+ }, [])++ 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">{tail}…</div>+ </VirtualizedThread.Row>+ }+ stickToBottom+ >+ {(item) => (+ <VirtualizedThread.Row>+ <FakeMessage role={item.role} text={item.text} />+ </VirtualizedThread.Row>+ )}+ </VirtualizedThread.Root>+ </div>+ )+ },+}++/** Empty thread (rowCount 0) — renders an empty scroll container, no rows, stick effects no-op. */+export const Empty: Story = {+ render: () => (+ <div className="h-[300px] w-180 border rounded overflow-hidden">+ <VirtualizedThread.Root items={[] as FakeItem[]} getItemKey={getKey} stickToBottom>+ {(item) => (+ <VirtualizedThread.Row>+ <FakeMessage role={item.role} text={item.text} />+ </VirtualizedThread.Row>+ )}+ </VirtualizedThread.Root>+ </div>+ ),+}++/** Header + footer only (no items) — the offset mapping still resolves both synthetic rows. */+export const HeaderFooterOnly: Story = {+ render: () => (+ <div className="h-[300px] w-180 border rounded overflow-hidden">+ <VirtualizedThread.Root+ items={[] as FakeItem[]}+ getItemKey={getKey}+ header={+ <VirtualizedThread.Row>+ <div className="text-xs text-muted p-2">Run context header</div>+ </VirtualizedThread.Row>+ }+ footer={+ <VirtualizedThread.Row>+ <div className="rounded border p-3 bg-surface-primary text-sm text-muted">Thinking…</div>+ </VirtualizedThread.Row>+ }+ stickToBottom+ >+ {(item) => (+ <VirtualizedThread.Row>+ <FakeMessage role={item.role} text={item.text} />+ </VirtualizedThread.Row>+ )}+ </VirtualizedThread.Root>+ </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.+ */+export const FlowMode: Story = {+ render: () => {+ const items = makeItems(12)+ return (+ <div className="h-[500px] w-180 mx-auto overflow-y-auto border rounded flex flex-col gap-1.5 p-2">+ <VirtualizedThread.Root items={items} getItemKey={getKey} virtualized={false}>+ {(item) => (+ <VirtualizedThread.Row>+ <FakeMessage role={item.role} text={item.text} />+ </VirtualizedThread.Row>+ )}+ </VirtualizedThread.Root>+ </div>+ )+ },+}diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.tsxindex 38de21d8eab8..71c09959971f 100644--- a/products/posthog_ai/frontend/components/VirtualizedThread.tsx+++ b/products/posthog_ai/frontend/components/VirtualizedThread.tsx@@ -1,93 +1,73 @@+import { useVirtualizer } from '@tanstack/react-virtual'import {createContext,CSSProperties,+ memo,ReactNode,- UIEvent,useCallback,useContext,useEffect,+ useLayoutEffect,useMemo,useRef,+ useState,} from 'react'-import { List, RowComponentProps, useDynamicRowHeight, useListRef } from 'react-window'-import { AutoSizer } from 'lib/components/AutoSizer'-import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'import { cn } from 'lib/utils/css-classes'/** Within this many px of the bottom still counts as "pinned" — absorbs iOS momentum/rubber-band jitter. */const BOTTOM_THRESHOLD = 32/**- * At or within this many px of the bottom counts as "already there", so `maybeStickToBottom` skips re-issuing- * a scroll — doing so at the final position cancels macOS's native overscroll bounce and reads as a shake.- * Kept tiny (a scroll snaps exactly to the bottom, so a resting reader is at distance 0); just wide enough to- * absorb fractional-pixel scroll positions. Growth past this still re-pins to the true bottom.+ * 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+ * scroll or a measurement settle repositions rows without re-rendering them.*/-const AT_BOTTOM_EPSILON = 2+const ROW_BASE_STYLE: CSSProperties = { position: 'absolute', top: 0, left: 0, width: '100%' }/**- * Frames the initial settle-to-bottom keeps re-issuing the scroll. With variable row heights a single- * scroll on first content lands short (rows below the fold are estimated until rendered + measured), so a- * freshly refreshed/opened thread needs a few correction frames to reach the true bottom. Bounded so a- * never-settling layout can't loop forever.+ * Virtual keys for the synthetic header/footer rows — reserved prefixes that never collide with a user item+ * key. The footer key is a prefix, not a constant: `getVirtualItemKey` appends the item count to it.*/-const MAX_INITIAL_SCROLL_FRAMES = 30--/**- * Re-issue an initial scroll across frames until its `measure` (bottom → `scrollHeight`, top-pinned row →- * `scrollTop`) holds steady — dynamic row heights land the first pass short. Bounded by- * `MAX_INITIAL_SCROLL_FRAMES`; returns a cleanup that cancels the pending frame.- */-function settleInitialScroll(scrollAction: () => void, measure: () => number): () => void {- let frame = 0- let lastMeasure = -1- let raf = requestAnimationFrame(function settle(): void {- scrollAction()- frame += 1- const measured = measure()- if (measured !== lastMeasure && frame < MAX_INITIAL_SCROLL_FRAMES) {- lastMeasure = measured- raf = requestAnimationFrame(settle)- }- })- return () => cancelAnimationFrame(raf)-}--const EMPTY_STYLE: CSSProperties = {}-const EMPTY_ARIA: Record<string, unknown> = {}+const HEADER_KEY = '__vt_header__'+const FOOTER_KEY = '__vt_footer__'interface RootContextValue {- dynamicRowHeight: ReturnType<typeof useDynamicRowHeight>+ /** The virtualizer's border-box `ResizeObserver` ref — attach to each measured row's outer element. */+ measureElement: (node: Element | null) => void/** Inter-row spacing (px), applied as bottom padding on the measured row so heights include it. */gap: numbermaxWidthClassName: string- /** When false, rows render in document flow (no react-window) and an ancestor owns scroll. */+ /** When false, rows render in document flow (no virtualization) and an ancestor owns scroll. */virtualized: boolean}interface RowContextValue {index: number- style: CSSProperties- ariaAttributes: Record<string, unknown>}const RootContext = createContext<RootContextValue | null>(null)const RowContext = createContext<RowContextValue | null>(null)-interface InternalRowProps {+/**+ * Virtualized row shell: publishes the row index via context and defers content to `renderRow`. Row+ * offsets never pass through React (`directDomUpdates` writes them straight to the DOM), so a mounted row+ * only re-renders when its index or content changes — never on scroll or measurement.+ */+const InternalRow = memo(function InternalRow({+ index,+ renderRow,+}: {+ index: numberrenderRow: (index: number) => ReactNode-}--/** react-window row shell: publishes per-row positioning via context and defers content to `renderRow`. */-function InternalRow({ index, style, ariaAttributes, renderRow }: RowComponentProps<InternalRowProps>): JSX.Element {- const value = useMemo<RowContextValue>(() => ({ index, style, ariaAttributes }), [index, style, ariaAttributes])+}): JSX.Element {+ const value = useMemo<RowContextValue>(() => ({ index }), [index])return <RowContext.Provider value={value}>{renderRow(index)}</RowContext.Provider>-}+})export interface VirtualizedThreadRootProps<T> {items: T[]- /** Stable key per item — used for stick-to-bottom change detection (react-window keys rows by index). */+ /** Stable key per item — keys the measurement cache (correct reuse on prepend/reorder). */getItemKey: (item: T, index: number) => string/** Rendered as a measured leading row (e.g. run context). */header?: ReactNode@@ -97,16 +77,27 @@ export interface VirtualizedThreadRootProps<T> {gap?: number/** Height used until a row is measured. */defaultRowHeight?: number+ /**+ * Per-item pre-measurement height estimate in px (gap excluded — added internally). The closer the+ * estimate to the real row height, the smaller the scroll-position correction applied when an+ * unmeasured row above the viewport gets its first measurement — which is what makes scrolling up+ * through unvisited history feel like dragging. Falls back to `defaultRowHeight`.+ */+ estimateItemHeight?: (item: T, index: number) => numberoverscanCount?: number/** Follow the bottom as rows grow/append; unpins when the user scrolls up. */stickToBottom?: boolean/**- * Item index (0-based within `items`) to align to the top of the viewport on the initial open,- * instead of scrolling to the bottom — e.g. open a task thread at its last user message. The thread- * is left unpinned so stick-to-bottom doesn't immediately pull it back down. `null`/omitted keeps the- * default open-at-bottom behavior. Consumed once, on first content; later changes are ignored.+ * 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.*/- initialTopItemIndex?: number | null+ anchorItemKey?: string | nullmaxWidthClassName?: stringclassName?: string/**@@ -120,10 +111,10 @@ export interface VirtualizedThreadRootProps<T> {}/**- * Embeddable virtualized thread. Fills any height-bounded parent (`h-full`/`flex-1 min-h-0`/fixed) via- * `AutoSizer`, virtualizes rows with react-window, measures dynamic heights, owns its own scroll and an- * optional stick-to-bottom that follows streaming growth. Render rows through the `children` render-prop,- * each wrapped in `VirtualizedThread.Row`.+ * Embeddable virtualized thread. Fills any height-bounded parent (`h-full`/`flex-1 min-h-0`/fixed),+ * virtualizes rows with TanStack Virtual, measures dynamic heights, owns its own scroll and an optional+ * stick-to-bottom that follows streaming growth. Render rows through the `children` render-prop, each+ * wrapped in `VirtualizedThread.Row`.*/function Root<T>({items,@@ -132,27 +123,27 @@ function Root<T>({footer,gap = 6,defaultRowHeight = 56,+ estimateItemHeight,overscanCount = 10,stickToBottom = true,- initialTopItemIndex = null,+ anchorItemKey,maxWidthClassName = 'max-w-180',className,listClassName,virtualized = true,children,}: VirtualizedThreadRootProps<T>): JSX.Element {- // Shared per-row height cache (Map keyed by row index). Survives re-renders and react-window's- // row recycling, so scrolling back to an already-measured row reuses its height without a flash;- // rows are re-measured on resize via `observeRowElements` (see `Row`).- const dynamicRowHeight = useDynamicRowHeight({ defaultRowHeight })- const listRef = useListRef(null)-const hasHeader = header != nullconst hasFooter = footer != nullconst rowCount = items.length + (hasHeader ? 1 : 0) + (hasFooter ? 1 : 0)- const pinnedRef = useRef(stickToBottom)+ 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)+ const prevAnchorKeyRef = useRef<string | null | undefined>(undefined)+ const pendingAnchorScrollRef = useRef<{ index: number; padding: number } | null>(null)const renderRow = useCallback((index: number): ReactNode => {@@ -171,121 +162,183 @@ function Root<T>({[items, header, footer, hasHeader, children])- const scrollToBottom = useCallback((): void => {- if (rowCount === 0) {- return- }- listRef.current?.scrollToRow({ index: rowCount - 1, align: 'end' })- // `scrollToRow` lands a hair short with dynamic row heights, leaving the last line a few px out of- // view; snap to the exact maximum (the browser clamps `scrollTop` to its valid range).- const el = listRef.current?.element- if (el) {- el.scrollTop = el.scrollHeight- }- }, [listRef, rowCount])-- // Align a given item's row to the top of the viewport (used for the initial open-at-last-user-message).- // Header rows shift the item into row-index space, which is what react-window's `scrollToRow` expects.- const scrollItemToTop = useCallback(- (itemIndex: number): void => {- listRef.current?.scrollToRow({ index: itemIndex + (hasHeader ? 1 : 0), align: 'start' })+ // Wrap the user key with the header/footer offset so measurement is cached by a stable key: prepends and+ // replay-reorders reuse a row's measured height instead of re-measuring by index.+ const getVirtualItemKey = useCallback(+ (index: number): string => {+ let i = index+ if (hasHeader) {+ if (i === 0) {+ return HEADER_KEY+ }+ i -= 1+ }+ 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}`},- [listRef, hasHeader]+ [items, getItemKey, hasHeader])- // Re-assert the bottom only when content has pushed it out of view (streaming growth, measurement- // settle, initial open) — so the open scroll converges to the true bottom as rows are measured, while- // a user resting at the final position is left alone. Skipping when already there is what stops the- // re-issued scroll from cancelling macOS's native overscroll bounce (the "shake"). No element yet (the- // first pass before mount) ⇒ scroll unconditionally.- const maybeStickToBottom = useCallback((): void => {- if (!stickToBottom || !pinnedRef.current) {- return- }- const el = listRef.current?.element- if (el && el.scrollHeight - el.scrollTop - el.clientHeight <= AT_BOTTOM_EPSILON) {- return- }- scrollToBottom()- }, [stickToBottom, scrollToBottom, listRef])-- const handleScroll = useCallback(- (event: UIEvent<HTMLDivElement>): void => {- if (!stickToBottom) {- return+ const findVirtualIndexForKey = useCallback(+ (key: string): number => {+ // Scan from the end — the anchor (a recent human message) is near the tail in practice.+ for (let i = rowCount - 1; i >= 0; i--) {+ if (getVirtualItemKey(i) === key) {+ return i+ }}- const el = event.currentTarget- pinnedRef.current = el.scrollHeight - el.scrollTop - el.clientHeight <= BOTTOM_THRESHOLD+ return -1},- [stickToBottom]+ [rowCount, getVirtualItemKey])- const handleRowsRendered = useCallback((): void => {- maybeStickToBottom()- }, [maybeStickToBottom])+ // Measured heights include the gap padding (see `Row`), so estimates must too — otherwise every first+ // measurement carries a built-in error that gets compensated as a scroll-position correction.+ const estimateVirtualRow = useCallback(+ (index: number): number => {+ let i = index+ if (hasHeader) {+ if (i === 0) {+ return defaultRowHeight + gap+ }+ i -= 1+ }+ if (i < items.length) {+ return (estimateItemHeight?.(items[i], i) ?? defaultRowHeight) + gap+ }+ return defaultRowHeight + gap+ },+ [items, hasHeader, estimateItemHeight, defaultRowHeight, gap]+ )- // Re-pin as content appends/streams and as dynamic measurements settle — gated by `maybeStickToBottom`- // so it scrolls only while the bottom is out of view. Pinned by default, so this also scrolls to the- // bottom on open: the first pass fires before rows are measured (they start at `defaultRowHeight`) and- // lands short, then re-fires as ResizeObserver grows the rows until it settles at the true bottom.- const lastKey = items.length > 0 ? getItemKey(items[items.length - 1], items.length - 1) : null- const measuredAverageHeight = dynamicRowHeight.getAverageRowHeight()- useEffect(() => {- if (!virtualized || !stickToBottom || !pinnedRef.current) {- return- }- const raf = requestAnimationFrame(maybeStickToBottom)- return () => cancelAnimationFrame(raf)- }, [virtualized, stickToBottom, maybeStickToBottom, rowCount, lastKey, measuredAverageHeight])+ const virtualizer = useVirtualizer({+ count: rowCount,+ getScrollElement: () => scrollRef.current,+ 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,+ // 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,+ // 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.+ initialOffset: () => {+ const anchorIndex = anchorItemKey != null ? findVirtualIndexForKey(anchorItemKey) : -1+ const limit = anchorIndex >= 0 ? anchorIndex : rowCount+ let total = 0+ for (let i = 0; i < limit; i++) {+ total += estimateVirtualRow(i)+ }+ return total+ },+ }+ : {}),+ })- // First content (open / hard refresh): drive the scroll to the true bottom across a few frames. The- // per-dep effect above fires too few times as the list mounts and rows measure, so a single pass lands- // short of the last messages. Re-pin first so a stray load-time scroll event can't leave it unpinned,- // then re-issue until actually at the bottom (or the frame budget runs out). Runs once; streaming- // growth afterwards is the per-dep effect's job.- useEffect(() => {+ // 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.+ useLayoutEffect(() => {if (!virtualized || !stickToBottom || didInitialScrollRef.current || rowCount === 0) {return}didInitialScrollRef.current = true-- // Open at the top of a specific item (the task thread's last user message) rather than the bottom.- // Leave the thread unpinned so the per-dep stick-to-bottom effect (and its already-queued- // `maybeStickToBottom`, which re-reads `pinnedRef` at frame time) bails instead of yanking it down.- const topTarget =- initialTopItemIndex != null && initialTopItemIndex >= 0 && initialTopItemIndex < items.length- ? initialTopItemIndex- : null- if (topTarget !== null) {- pinnedRef.current = false- return settleInitialScroll(- () => scrollItemToTop(topTarget),- () => listRef.current?.element?.scrollTop ?? 0- )+ const anchorIndex = anchorItemKey != null ? findVirtualIndexForKey(anchorItemKey) : -1+ if (anchorIndex >= 0) {+ virtualizer.scrollToIndex(anchorIndex, { align: 'start' })+ } else {+ 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.+ useLayoutEffect(() => {+ if (!virtualized || items.length === 0) {+ return+ }+ const prev = prevAnchorKeyRef.current+ if (prev === undefined) {+ prevAnchorKeyRef.current = anchorItemKey ?? null+ return}- pinnedRef.current = true- return settleInitialScroll(scrollToBottom, () => listRef.current?.element?.scrollHeight ?? 0)- }, [- virtualized,- stickToBottom,- rowCount,- scrollToBottom,- scrollItemToTop,- initialTopItemIndex,- items.length,- listRef,- ])+ if (anchorItemKey == null || anchorItemKey === prev) {+ return+ }+ prevAnchorKeyRef.current = anchorItemKey+ const anchorIndex = findVirtualIndexForKey(anchorItemKey)+ if (anchorIndex < 0) {+ return+ }+ const isTrailingItem = anchorIndex === (hasHeader ? 1 : 0) + items.length - 1+ if (!isTrailingItem) {+ virtualizer.scrollToIndex(anchorIndex, { align: 'start' })+ 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) {+ 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.+ useLayoutEffect(() => {+ const pending = pendingAnchorScrollRef.current+ if (!pending || pending.padding !== anchorPadding) {+ return+ }+ pendingAnchorScrollRef.current = null+ virtualizer.scrollToIndex(pending.index, { align: 'start' })+ })- // Mobile Safari: the soft keyboard shrinks the visual (not layout) viewport, so a pinned bottom can- // slip behind it. Re-assert on visualViewport changes.+ // Mobile Safari: the soft keyboard shrinks the visual (not layout) viewport, so a pinned bottom can slip+ // behind it. Re-assert on visualViewport changes.useEffect(() => {if (!virtualized || !stickToBottom || typeof window === 'undefined' || !window.visualViewport) {return}const viewport = window.visualViewportconst onViewportChange = (): void => {- if (pinnedRef.current) {- requestAnimationFrame(scrollToBottom)+ if (virtualizer.isAtEnd(BOTTOM_THRESHOLD)) {+ requestAnimationFrame(() => virtualizer.scrollToEnd())}}viewport.addEventListener('resize', onViewportChange)@@ -294,11 +347,11 @@ function Root<T>({viewport.removeEventListener('resize', onViewportChange)viewport.removeEventListener('scroll', onViewportChange)}- }, [virtualized, stickToBottom, scrollToBottom])+ }, [virtualized, stickToBottom, virtualizer])const rootValue = useMemo<RootContextValue>(- () => ({ dynamicRowHeight, gap, maxWidthClassName, virtualized }),- [dynamicRowHeight, gap, maxWidthClassName, virtualized]+ () => ({ measureElement: virtualizer.measureElement, gap, maxWidthClassName, virtualized }),+ [virtualizer, gap, maxWidthClassName, virtualized])// Flow mode: render rows directly so an ancestor scroll container (and its auto-scroller) keeps working.@@ -308,26 +361,17 @@ function Root<T>({return (<RootContext.Provider value={rootValue}>{hasHeader && (- <RowContext.Provider- key="header"- value={{ index: 0, style: EMPTY_STYLE, ariaAttributes: EMPTY_ARIA }}- >+ <RowContext.Provider key="header" value={{ index: 0 }}>{header}</RowContext.Provider>)}{items.map((item, index) => (- <RowContext.Provider- key={getItemKey(item, index)}- value={{ index, style: EMPTY_STYLE, ariaAttributes: EMPTY_ARIA }}- >+ <RowContext.Provider key={getItemKey(item, index)} value={{ index }}>{children(item, index)}</RowContext.Provider>))}{hasFooter && (- <RowContext.Provider- key="footer"- value={{ index: rowCount - 1, style: EMPTY_STYLE, ariaAttributes: EMPTY_ARIA }}- >+ <RowContext.Provider key="footer" value={{ index: rowCount - 1 }}>{footer}</RowContext.Provider>)}@@ -338,38 +382,36 @@ function Root<T>({return (<RootContext.Provider value={rootValue}><div className={cn('flex flex-col h-full min-h-0 w-full', className)}>- <AutoSizer- renderProp={({ height, width }: SizeProps) => {- if (!height || !width) {- return null- }- // react-window sets only `overflowY: auto`, which makes the unset `overflow-x` compute- // to `auto` too — pin it to `hidden` so the thread never scrolls sideways (wide blocks- // like tool output scroll within their own containers).- return (- <List<InternalRowProps>- style={{ height, width, overflowX: 'hidden' }}- className={cn('overscroll-contain', listClassName)}- overscanCount={overscanCount}- rowCount={rowCount}- rowHeight={dynamicRowHeight}- rowComponent={InternalRow}- rowProps={{ renderRow }}- listRef={listRef}- onRowsRendered={handleRowsRendered}- onScroll={handleScroll}- />- )- }}- />+ <div+ ref={scrollRef}+ className={cn('flex-1 min-h-0 overflow-y-auto overflow-x-hidden overscroll-contain', 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}+ />+ )+ })}+ </div>+ </div></div></RootContext.Provider>)}/**- * Row shell for content rendered inside `VirtualizedThread.Root`. Applies react-window positioning, measures- * its own height (gap included via bottom padding), and centers content with the thread's container-query context.+ * Row shell for content rendered inside `VirtualizedThread.Root`. Registers itself with the virtualizer+ * (which measures it and positions it directly in the DOM), measures its own height (gap included via+ * bottom padding), and centers content with the thread's container-query context.*/function Row({ children, className }: { children: ReactNode; className?: string }): JSX.Element {const root = useContext(RootContext)@@ -377,29 +419,36 @@ function Row({ children, className }: { children: ReactNode; className?: stringif (!root || !row) {throw new Error('VirtualizedThread.Row must be rendered inside VirtualizedThread.Root')}- const { dynamicRowHeight, gap, maxWidthClassName, virtualized } = root- const { style, ariaAttributes, index } = row- const rowRef = useRef<HTMLDivElement>(null)-- // Cache + recalc: `observeRowElements` attaches a ResizeObserver to the measured row element and- // writes its border-box height into the shared cache. So when this row's content changes height —- // tool output expand/collapse, streaming markdown, a late-loading image — it is re-measured and the- // list re-lays-out automatically. We observe the outer element (which is never given a fixed height,- // only react-window's position/transform), and the gap padding lives on its child, so the cached- // height always includes inter-row spacing and content growth.- useEffect(() => {- if (virtualized && rowRef.current) {- return dynamicRowHeight.observeRowElements([rowRef.current])- }- }, [virtualized, dynamicRowHeight])+ const { measureElement, gap, maxWidthClassName, virtualized } = root+ const { index } = row++ // Re-registers the node whenever `index` changes: the virtualizer's element cache (which both direct+ // DOM positioning and measurement read) is addressed by the row's *virtual key*, and a row can change+ // key without remounting — the footer's key rotates on every append. Writing `data-index` here (not as+ // a JSX prop) keeps the attribute and the registration in one atomic step, so the virtualizer never+ // reads a stale index off the node.+ const measureRef = useCallback(+ (node: HTMLDivElement | null): void => {+ if (node) {+ node.setAttribute('data-index', String(index))+ }+ measureElement(node)+ },+ [measureElement, index]+ )// Flow mode: transparent — the parent container provides spacing and centering.if (!virtualized) {return <>{children}</>}+ // The outer element carries only the static positioning base (never a fixed height or offset — the+ // virtualizer writes `translate3d` to it directly); TanStack's `measureElement` attaches a border-box+ // `ResizeObserver` to it, so the cached height always tracks content growth — tool output+ // expand/collapse, streaming markdown, a late-loading image — and includes the gap padding on the+ // child. Border-box measurement is transform-safe, so the imperative positioning does not distort it.return (- <div ref={rowRef} style={style} data-index={index} {...ariaAttributes}>+ <div ref={measureRef} style={ROW_BASE_STYLE}><divclassName={cn('w-full mx-auto @container/thread', maxWidthClassName, className)}style={{ paddingBottom: gap }}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsxindex d82ce2292859..92f5f6305388 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx@@ -51,6 +51,7 @@ export function TaskDetailPage({ taskId, isMobile }: TaskDetailPageProps): JSX.Esize="small"icon={<IconExternal />}onClick={() => window.open(`posthog-code://task/${task.id}`, '_blank')}+ className="hidden lg:inline-flex">Open in PostHog Code</LemonButton>diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TasksListColumn.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TasksListColumn.tsxindex b846bd077f93..86f0801f9675 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TasksListColumn.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TasksListColumn.tsx@@ -91,14 +91,13 @@ export function TasksListColumn({ selectedTaskId, isMobile = false }: TasksListC<div className="shrink-0 lg:px-1">{searchInput}</div><LemonDivider className="mb-0 mt-4" /><div className={cn('flex flex-col flex-1 min-h-0', tasks.length > 0 && '-mx-4')}>{content}</div>- <div className="shrink-0 h-20" /><LemonButtontype="primary"icon={<IconPlus />}to={urls.taskNew()}size="large"data-attr="tasks-new-mobile"- className="fixed bottom-4 right-4 z-20 shadow-md"+ className="fixed bottom-[calc(1rem_+_env(safe-area-inset-bottom))] right-4 z-20 shadow-md">New task</LemonButton>diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/VirtualizedTasksList.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/VirtualizedTasksList.tsxindex 04e9c55e1302..05161a01d57a 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/VirtualizedTasksList.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/VirtualizedTasksList.tsx@@ -1,58 +1,16 @@-import { CSSProperties, useEffect, useRef } from 'react'-import { List, useDynamicRowHeight } from 'react-window'+import { useVirtualizer } from '@tanstack/react-virtual'+import { useCallback, useEffect, useRef } from 'react'-import { AutoSizer } from 'lib/components/AutoSizer'import { Spinner } from 'lib/lemon-ui/Spinner'import { Task } from '../../../types/taskTypes'import { TaskListItem } from './TaskListItem'-// Menu-item row height; the dynamic measurer corrects rows whose title wraps to two lines.+// Menu-item row height; the virtualizer's dynamic measurement corrects rows whose title wraps to two lines.const DEFAULT_TASK_ROW_HEIGHT = 40// Start fetching the next page this many rows before the end so it lands before the user hits the bottom.const LOAD_MORE_THRESHOLD = 5-interface TaskRowProps {- tasks: Task[]- selectedTaskId: string | null- dynamicRowHeight: ReturnType<typeof useDynamicRowHeight>-}--function TaskRow({- index,- style,- tasks,- selectedTaskId,- dynamicRowHeight,-}: {- ariaAttributes: Record<string, unknown>- index: number- style: CSSProperties-} & TaskRowProps): JSX.Element {- const rowRef = useRef<HTMLDivElement>(null)-- useEffect(() => {- if (rowRef.current) {- return dynamicRowHeight.observeRowElements([rowRef.current])- }- }, [dynamicRowHeight])-- // The trailing row past the end of `tasks` is the infinite-scroll loader.- const task = tasks[index]-- return (- <div ref={rowRef} style={style} data-index={index} className="px-4 lg:pl-0">- {task ? (- <TaskListItem task={task} isActive={task.id === selectedTaskId} />- ) : (- <div className="flex items-center justify-center py-3">- <Spinner />- </div>- )}- </div>- )-}-interface VirtualizedTasksListProps {tasks: Task[]/** Currently selected task id, used to highlight its row. */@@ -71,31 +29,65 @@ export function VirtualizedTasksList({loadingMore,onLoadMore,}: VirtualizedTasksListProps): JSX.Element {- const dynamicRowHeight = useDynamicRowHeight({ defaultRowHeight: DEFAULT_TASK_ROW_HEIGHT })+ const scrollRef = useRef<HTMLDivElement>(null)++ // Stable per-task keys so pagination appends don't remount already-measured rows.+ const getItemKey = useCallback((index: number): string => tasks[index]?.id ?? '__tasks_loader__', [tasks])++ const virtualizer = useVirtualizer({+ // One extra row hosts the loader spinner while more pages remain.+ count: tasks.length + (hasMore ? 1 : 0),+ getScrollElement: () => scrollRef.current,+ estimateSize: () => DEFAULT_TASK_ROW_HEIGHT,+ overscan: 10,+ paddingStart: 16,+ paddingEnd: 16,+ getItemKey,+ })- // One extra row hosts the loader spinner while more pages remain.- const rowCount = tasks.length + (hasMore ? 1 : 0)+ const virtualItems = virtualizer.getVirtualItems()+ const lastRenderedIndex = virtualItems[virtualItems.length - 1]?.index ?? -1++ useEffect(() => {+ if (hasMore && !loadingMore && lastRenderedIndex >= tasks.length - LOAD_MORE_THRESHOLD) {+ onLoadMore()+ }+ }, [hasMore, loadingMore, lastRenderedIndex, tasks.length, onLoadMore])return (- <AutoSizer- renderProp={({ height, width }) =>- height && width ? (- <List<TaskRowProps>- style={{ height, width }}- className="py-4 overflow-x-hidden"- overscanCount={10}- rowCount={rowCount}- rowHeight={dynamicRowHeight}- rowComponent={TaskRow}- rowProps={{ tasks, selectedTaskId, dynamicRowHeight }}- onRowsRendered={({ stopIndex }) => {- if (hasMore && !loadingMore && stopIndex >= tasks.length - LOAD_MORE_THRESHOLD) {- onLoadMore()- }- }}- />- ) : null- }- />+ <div+ ref={scrollRef}+ className="h-full overflow-y-auto overflow-x-hidden pb-[calc(5rem_+_env(safe-area-inset-bottom))]"+ >+ <div style={{ position: 'relative', width: '100%', height: virtualizer.getTotalSize() }}>+ {virtualItems.map((virtualRow) => {+ const task = tasks[virtualRow.index]++ return (+ <div+ key={virtualRow.key}+ data-index={virtualRow.index}+ ref={virtualizer.measureElement}+ className="px-4 lg:px-0"+ style={{+ position: 'absolute',+ top: 0,+ left: 0,+ width: '100%',+ transform: `translateY(${virtualRow.start}px)`,+ }}+ >+ {task ? (+ <TaskListItem task={task} isActive={task.id === selectedTaskId} />+ ) : (+ <div className="flex items-center justify-center py-3">+ <Spinner />+ </div>+ )}+ </div>+ )+ })}+ </div>+ </div>)}diff --git a/products/posthog_ai/package.json b/products/posthog_ai/package.jsonindex d29dab766708..58d80781288d 100644--- a/products/posthog_ai/package.json+++ b/products/posthog_ai/package.json@@ -5,13 +5,13 @@},"dependencies": {"@posthog/quill-primitives": "workspace:*",+ "@tanstack/react-virtual": "*","eventsource-parser": "*","kea-subscriptions": "catalog:","marked": "*","monaco-editor": "^0.55.1","posthog-js": "catalog:","react-intersection-observer": "^9.5.3",- "react-window": "*","tailwind-merge": "*"},"devDependencies": {