:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(posthog-ai): stop long chats from freezing the page when they open (#111489)
Shy Alter70f8ea6c0eb9
diff --git a/frontend/src/layout/navigation-3000/Navigation.tsx b/frontend/src/layout/navigation-3000/Navigation.tsxindex 64df3f5d3841..5663eb9a839a 100644--- a/frontend/src/layout/navigation-3000/Navigation.tsx+++ b/frontend/src/layout/navigation-3000/Navigation.tsx@@ -1,7 +1,7 @@import './Navigation.scss'import { useActions, useMountedLogic, useValues } from 'kea'-import { ReactNode, useCallback, useEffect, useRef } from 'react'+import { ReactNode, useCallback, useEffect, useLayoutEffect, useRef } from 'react'import { mcpHintLogic } from 'lib/components/MCPHint/mcpHintLogic'import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'@@ -118,6 +118,15 @@ export function Navigation({const noPaddingScene = sceneConfig?.layout === 'app-raw-no-header' || sceneConfig?.layout === 'app-raw'+ const todayPhoneBodyClass = todayPhone && mode === 'full'+ useLayoutEffect(() => {+ if (!todayPhoneBodyClass) {+ return+ }+ document.body.classList.add('has-today-phone-layout')+ return () => document.body.classList.remove('has-today-phone-layout')+ }, [todayPhoneBodyClass])+if (mode !== 'full') {const showMinimalNavigation = mode === 'minimal' || mode === 'zen'return (diff --git a/frontend/src/layout/today/TodayShell.scss b/frontend/src/layout/today/TodayShell.scssindex cae08972525c..fd7aa50865b3 100644--- a/frontend/src/layout/today/TodayShell.scss+++ b/frontend/src/layout/today/TodayShell.scss@@ -119,11 +119,11 @@}}-body:has(.TodayAppLayout--phone) :is(input, textarea, select) {+body.has-today-phone-layout :is(input, textarea, select) {font-size: 1rem;}-body:has(.TodayAppLayout--phone) .Toastify__toast-container--bottom-right {+body.has-today-phone-layout .Toastify__toast-container--bottom-right {bottom: calc(84px + env(safe-area-inset-bottom));}diff --git a/products/posthog_ai/frontend/components/FlowRows.tsx b/products/posthog_ai/frontend/components/FlowRows.tsxnew file mode 100644index 000000000000..d0f468bda88a--- /dev/null+++ b/products/posthog_ai/frontend/components/FlowRows.tsx@@ -0,0 +1,87 @@+import { useActions, useValues } from 'kea'+import { type ReactNode, memo, useCallback, useId, useLayoutEffect, useMemo, useRef } from 'react'++import { flowRowsLogic } from '../logics/flowRowsLogic'+import { deriveFlowWindow, renderedFlowRanges } from '../utils/flowWindow'+import { FlowScrollKeeper } from './FlowScrollKeeper'+import { VirtualizedThreadRowContext, type VirtualizedThreadRowContextValue } from './VirtualizedThreadRowContext'++const FlowRow = memo(function FlowRow({ index, children }: { index: number; children: ReactNode }): JSX.Element {+ const value = useMemo<VirtualizedThreadRowContextValue>(() => ({ index }), [index])+ return <VirtualizedThreadRowContext.Provider value={value}>{children}</VirtualizedThreadRowContext.Provider>+})++const FlowItemRow = memo(function FlowItemRow<T>({+ index,+ item,+ render,+}: {+ index: number+ item: T+ render: (item: T, index: number) => ReactNode+}): JSX.Element {+ return <FlowRow index={index}>{render(item, index)}</FlowRow>+}) as <T>(props: { index: number; item: T; render: (item: T, index: number) => ReactNode }) => JSX.Element++export interface FlowRowsProps<T> {+ items: T[]+ getItemKey: (item: T, index: number) => string+ header: ReactNode+ footer: ReactNode+ footerIndex: number+ render: (item: T, index: number) => ReactNode+}++/**+ * The rows of a flow-mode thread, in document flow. The newest rows render at once and the older+ * rows fill in between frames (see `flowRowsLogic`), so opening a long thread never freezes the page.+ */+export function FlowRows<T>({ items, getItemKey, header, footer, footerIndex, render }: FlowRowsProps<T>): JSX.Element {+ const keeperRef = useRef<FlowScrollKeeper>(null)+ const readerScrollTop = useCallback((): number | null => keeperRef.current?.readerScrollTop() ?? null, [])+ const logic = flowRowsLogic({ flowKey: useId(), readerScrollTop })+ const { flowWindow } = useValues(logic)+ const { syncWindow, chunkCommitted } = useActions(logic)+ // Derived during render, so a long append never renders in full for one frame before the window catches up.+ const current = deriveFlowWindow(flowWindow, items, getItemKey)++ useLayoutEffect(() => {+ if (current !== flowWindow) {+ syncWindow(current)+ }+ }, [current, flowWindow, syncWindow])++ useLayoutEffect(() => {+ chunkCommitted(performance.now())+ }, [current.fillStep, chunkCommitted])++ const rows: JSX.Element[] = []+ for (const [from, to] of renderedFlowRanges(current)) {+ for (let index = from; index < to; index++) {+ const item = items[index]+ rows.push(<FlowItemRow key={getItemKey(item, index)} index={index} item={item} render={render} />)+ }+ }++ return (+ <>+ <FlowScrollKeeper+ ref={keeperRef}+ fillStep={current.fillStep}+ holdTop={current.fillAtStart}+ filling={current.holes.length > 0}+ />+ {header != null && current.holes[0]?.[0] !== 0 && (+ <FlowRow key="header" index={0}>+ {header}+ </FlowRow>+ )}+ {rows}+ {footer != null && (+ <FlowRow key="footer" index={footerIndex}>+ {footer}+ </FlowRow>+ )}+ </>+ )+}diff --git a/products/posthog_ai/frontend/components/FlowScrollKeeper.tsx b/products/posthog_ai/frontend/components/FlowScrollKeeper.tsxnew file mode 100644index 000000000000..0bc0fc5dbd51--- /dev/null+++ b/products/posthog_ai/frontend/components/FlowScrollKeeper.tsx@@ -0,0 +1,127 @@+import { Component, createRef } from 'react'++function findScrollParent(node: Element): HTMLElement | null {+ let current = node.parentElement+ while (current) {+ const { overflowY } = getComputedStyle(current)+ if (overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay') {+ return current+ }+ current = current.parentElement+ }+ return document.scrollingElement instanceof HTMLElement ? document.scrollingElement : null+}++/** The first element in `parent` whose bottom edge is below `viewportTop`. Rows stack in document order. */+function findFirstVisibleChild(parent: Element, viewportTop: number): Element | null {+ const children = parent.children+ let low = 0+ let high = children.length - 1+ let found: Element | null = null+ while (low <= high) {+ const middle = (low + high) >> 1+ let probe = middle+ // Hidden elements have an empty rect, so the search reads the next element in the DOM.+ while (probe <= high && children[probe].getClientRects().length === 0) {+ probe+++ }+ if (probe > high) {+ high = middle - 1+ continue+ }+ if (children[probe].getBoundingClientRect().bottom > viewportTop) {+ found = children[probe]+ high = middle - 1+ } else {+ low = probe + 1+ }+ }+ return found+}++interface FlowScrollKeeperProps {+ fillStep: number+ /** The fill step rendered the oldest rows for a reader who went to the top, so the view goes to the top. */+ holdTop: boolean+ filling: boolean+}++interface FlowScrollSnapshot {+ scroller: HTMLElement+ atTop: boolean+ atBottom: boolean+ anchor: Element | null+ anchorTop: number+}++/**+ * Keeps the reader's view in place while a fill step adds older rows above it. Before the commit it+ * notes the first row in view, and after the commit it scrolls by the distance that row moved. Growth+ * below that row, such as a streamed reply, does not move it, so it does not move the view.+ *+ * A reader at the bottom stays at the bottom. A fill step that renders the oldest rows for a reader who+ * went to the top puts the view at the top, so the reader sees the start of the thread.+ */+export class FlowScrollKeeper extends Component<FlowScrollKeeperProps> {+ private sentinel = createRef<HTMLSpanElement>()+ // The browser rounds `scrollTop`. Carrying the rounding into the next step stops a long fill from drifting.+ private remainder = 0++ override getSnapshotBeforeUpdate(previous: Readonly<FlowScrollKeeperProps>): FlowScrollSnapshot | null {+ const sentinel = this.sentinel.current+ if (this.props.fillStep === previous.fillStep || !sentinel?.parentElement) {+ return null+ }+ const scroller = findScrollParent(sentinel)+ if (!scroller) {+ return null+ }+ if (this.props.holdTop) {+ return { scroller, atTop: true, atBottom: false, anchor: null, anchorTop: 0 }+ }+ if (scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 1) {+ return { scroller, atTop: false, atBottom: true, anchor: null, anchorTop: 0 }+ }+ const viewportTop = scroller === document.scrollingElement ? 0 : scroller.getBoundingClientRect().top+ const anchor = findFirstVisibleChild(sentinel.parentElement, viewportTop)+ return anchor+ ? { scroller, atTop: false, atBottom: false, anchor, anchorTop: anchor.getBoundingClientRect().top }+ : null+ }++ override componentDidUpdate(+ _previous: Readonly<FlowScrollKeeperProps>,+ _state: unknown,+ snapshot: FlowScrollSnapshot | null+ ): void {+ if (!snapshot) {+ return+ }+ const { scroller, atTop, atBottom, anchor, anchorTop } = snapshot+ if (atTop) {+ scroller.scrollTop = 0+ return+ }+ if (atBottom) {+ scroller.scrollTop = scroller.scrollHeight+ return+ }+ if (!anchor?.isConnected) {+ return+ }+ // Correct from the current position: the browser's own scroll anchoring may already have moved it.+ const target = scroller.scrollTop + anchor.getBoundingClientRect().top - anchorTop + this.remainder+ scroller.scrollTop = target+ this.remainder = Math.max(-1, Math.min(1, target - scroller.scrollTop))+ }++ readerScrollTop(): number | null {+ const sentinel = this.sentinel.current+ const scroller = sentinel ? findScrollParent(sentinel) : null+ return scroller ? scroller.scrollTop : null+ }++ override render(): JSX.Element | null {+ return this.props.filling ? <span hidden ref={this.sentinel} /> : null+ }+}diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.test.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.test.tsxnew file mode 100644index 000000000000..470ab6a52520--- /dev/null+++ b/products/posthog_ai/frontend/components/VirtualizedThread.test.tsx@@ -0,0 +1,75 @@+import '@testing-library/jest-dom'++import { act, cleanup, render } from '@testing-library/react'++import { initKeaTests } from '~/test/init'++import { FLOW_INITIAL_ROWS } from '../utils/flowWindow'+import { VirtualizedThread } from './VirtualizedThread'++function thread(items: string[]): JSX.Element {+ return (+ <div data-attr="thread">+ <VirtualizedThread.Root items={items} getItemKey={(item) => item} virtualized={false}>+ {(item) => (+ <VirtualizedThread.Row>+ <p>{item}</p>+ </VirtualizedThread.Row>+ )}+ </VirtualizedThread.Root>+ </div>+ )+}++function rows(from: number, to: number): string[] {+ return Array.from({ length: to - from }, (_, index) => `row-${from + index}`)+}++function renderedRows(container: HTMLElement): string[] {+ return Array.from(container.querySelectorAll('p')).map((row) => row.textContent ?? '')+}++describe('VirtualizedThread flow mode', () => {+ beforeEach(() => {+ jest.useFakeTimers()+ initKeaTests()+ })++ afterEach(() => {+ cleanup()+ jest.useRealTimers()+ })++ it('shows the newest rows first, keeps bulk appends small, then fills in the full history in order', () => {+ const history = rows(0, 300)+ const { container, rerender } = render(thread(history))++ const firstPaint = renderedRows(container)+ expect(firstPaint.at(-1)).toBe('row-299')+ expect(firstPaint).not.toContain('row-0')++ const streamed = [...history, 'row-300']+ rerender(thread(streamed))+ expect(renderedRows(container).at(-1)).toBe('row-300')++ act(() => {+ jest.runOnlyPendingTimers()+ })+ const beforeAppend = renderedRows(container)++ // A history replay that lands in several commits appends hundreds of rows to a thread mid-fill.+ const appended = [...streamed, ...rows(301, 700)]+ rerender(thread(appended))+ const afterAppend = renderedRows(container)+ expect(afterAppend.at(-1)).toBe('row-699')+ expect(afterAppend.length - beforeAppend.length).toBeLessThanOrEqual(FLOW_INITIAL_ROWS)+ expect(afterAppend).toEqual(expect.arrayContaining(beforeAppend))++ for (let step = 0; step < 100 && renderedRows(container).length < appended.length; step++) {+ act(() => {+ jest.runOnlyPendingTimers()+ })+ }+ expect(renderedRows(container)).toEqual(appended)+ })+})diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.tsxindex 58610d9e894d..ede5c9fa4654 100644--- a/products/posthog_ai/frontend/components/VirtualizedThread.tsx+++ b/products/posthog_ai/frontend/components/VirtualizedThread.tsx@@ -15,6 +15,9 @@ import {import { cn } from 'lib/utils/css-classes'+import { FlowRows } from './FlowRows'+import { VirtualizedThreadRowContext, type VirtualizedThreadRowContextValue } from './VirtualizedThreadRowContext'+/*** 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*@@ -110,12 +113,7 @@ interface RootContextValue {virtualized: boolean}-interface RowContextValue {- index: number-}-const RootContext = createContext<RootContextValue | null>(null)-const RowContext = createContext<RowContextValue | null>(null)/*** Virtualized row shell: publishes the row index via context and defers content to `renderRow`. Row@@ -129,27 +127,10 @@ const InternalRow = memo(function InternalRow({index: numberrenderRow: (index: number) => ReactNode}): JSX.Element {- const value = useMemo<RowContextValue>(() => ({ index }), [index])- return <RowContext.Provider value={value}>{renderRow(index)}</RowContext.Provider>-})--const FlowRow = memo(function FlowRow({ index, children }: { index: number; children: ReactNode }): JSX.Element {- const value = useMemo<RowContextValue>(() => ({ index }), [index])- return <RowContext.Provider value={value}>{children}</RowContext.Provider>+ const value = useMemo<VirtualizedThreadRowContextValue>(() => ({ index }), [index])+ return <VirtualizedThreadRowContext.Provider value={value}>{renderRow(index)}</VirtualizedThreadRowContext.Provider>})-const FlowItemRow = memo(function FlowItemRow<T>({- index,- item,- render,-}: {- index: number- item: T- render: (item: T, index: number) => ReactNode-}): JSX.Element {- return <FlowRow index={index}>{render(item, index)}</FlowRow>-}) as <T>(props: { index: number; item: T; render: (item: T, index: number) => ReactNode }) => JSX.Element-export interface VirtualizedThreadRootProps<T> {items: T[]/** Stable key per item — keys the measurement cache (correct reuse on prepend/reorder). */@@ -933,19 +914,14 @@ function Root<T>({if (!virtualized) {return (<RootContext.Provider value={rootValue}>- {hasHeader && (- <FlowRow key="header" index={0}>- {header}- </FlowRow>- )}- {items.map((item, index) => (- <FlowItemRow key={getItemKey(item, index)} index={index} item={item} render={children} />- ))}- {hasFooter && (- <FlowRow key="footer" index={rowCount - 1}>- {footer}- </FlowRow>- )}+ <FlowRows+ items={items}+ getItemKey={getItemKey}+ header={hasHeader ? header : null}+ footer={hasFooter ? footer : null}+ footerIndex={rowCount - 1}+ render={children}+ /></RootContext.Provider>)}@@ -986,7 +962,7 @@ function Root<T>({*/function Row({ children, className }: { children: ReactNode; className?: string }): JSX.Element {const root = useContext(RootContext)- const row = useContext(RowContext)+ const row = useContext(VirtualizedThreadRowContext)if (!root || !row) {throw new Error('VirtualizedThread.Row must be rendered inside VirtualizedThread.Root')}diff --git a/products/posthog_ai/frontend/components/VirtualizedThreadRowContext.ts b/products/posthog_ai/frontend/components/VirtualizedThreadRowContext.tsnew file mode 100644index 000000000000..cd02ff051500--- /dev/null+++ b/products/posthog_ai/frontend/components/VirtualizedThreadRowContext.ts@@ -0,0 +1,8 @@+import { createContext } from 'react'++export interface VirtualizedThreadRowContextValue {+ index: number+}++/** The index of the row a `VirtualizedThread.Row` renders in, in both virtualized and flow mode. */+export const VirtualizedThreadRowContext = createContext<VirtualizedThreadRowContextValue | null>(null)diff --git a/products/posthog_ai/frontend/logics/flowRowsLogic.ts b/products/posthog_ai/frontend/logics/flowRowsLogic.tsnew file mode 100644index 000000000000..0d1a5b59c7bb--- /dev/null+++ b/products/posthog_ai/frontend/logics/flowRowsLogic.ts@@ -0,0 +1,190 @@+import { LogicWrapper, MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'++import { FLOW_INITIAL_ROWS, type FlowWindow, fillFlowWindow } from '../utils/flowWindow'++/** Time budget per fill step, under the 50 ms long-task line. */+const FLOW_CHUNK_BUDGET_MS = 40+const FLOW_MIN_CHUNK_ROWS = 4+const FLOW_MAX_CHUNK_ROWS = 256+/** The fill waits this long after input, so a keystroke or a scroll never waits for a fill step. */+const FLOW_INPUT_PAUSE_MS = 200+/** A reader who scrolls this close to the oldest rendered row gets more rows while scrolling, so there is no wall. */+const FLOW_SCROLL_BUFFER_PX = 3000+/**+ * A reader at the top who has not scrolled for this long got there by a jump (Home, the scrollbar) and+ * wants the start of the thread. A reader who scrolled there wants the rows just above.+ */+const FLOW_SCROLL_GESTURE_MS = 500+/** How long after a key that jumps to the start the fill keeps rendering the oldest rows first. */+const FLOW_JUMP_TO_START_MS = 1500+const FLOW_POLL_MS = 50+/** A smooth scroll to the top can stop a little short of it. Within this distance a jump counts as arrived. */+const FLOW_JUMP_ARRIVED_PX = 400+const FLOW_INPUT_EVENTS = ['wheel', 'touchmove', 'keydown', 'pointerdown', 'pointermove'] as const+const FLOW_SCROLL_KEYS = new Set(['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', ' '])++export interface FlowRowsLogicProps {+ flowKey: string+ /** The reader's `scrollTop` in the scroll container, read from the DOM by the component. */+ readerScrollTop?: () => number | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface flowRowsLogicValues {+ flowWindow: FlowWindow | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface flowRowsLogicActions {+ chunkCommitted: (committedAt: number) => {+ committedAt: number+ }+ fillChunk: (+ rows: number,+ atStart: boolean+ ) => {+ atStart: boolean+ rows: number+ }+ scheduleNextChunk: () => {+ value: true+ }+ syncWindow: (flowWindow: FlowWindow) => {+ flowWindow: FlowWindow+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface flowRowsLogicMeta {+ key: string+}++export type flowRowsLogicType = MakeLogicType<+ flowRowsLogicValues,+ flowRowsLogicActions,+ FlowRowsLogicProps,+ flowRowsLogicMeta+>++/**+ * The render window of one flow-mode thread. A long thread opens with only its newest rows, then+ * renders the older rows in small steps between frames, so the page never freezes on one huge commit.+ */+export const flowRowsLogic: LogicWrapper<flowRowsLogicType> = kea<flowRowsLogicType>([+ props({} as FlowRowsLogicProps),+ key((props) => props.flowKey),+ path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'flowRowsLogic', key]),+ actions({+ syncWindow: (flowWindow: FlowWindow) => ({ flowWindow }),+ fillChunk: (rows: number, atStart: boolean) => ({ rows, atStart }),+ chunkCommitted: (committedAt: number) => ({ committedAt }),+ scheduleNextChunk: true,+ }),+ reducers({+ flowWindow: [+ null as FlowWindow | null,+ {+ syncWindow: (_, { flowWindow }) => flowWindow,+ fillChunk: (state, { rows, atStart }) => (state ? fillFlowWindow(state, rows, atStart) : state),+ },+ ],+ }),+ listeners(({ actions, values, cache, props }) => ({+ syncWindow: () => {+ actions.scheduleNextChunk()+ },+ chunkCommitted: ({ committedAt }) => {+ if (cache.chunkStartedAt !== null) {+ const elapsed = Math.max(1, committedAt - cache.chunkStartedAt)+ cache.chunkStartedAt = null+ cache.chunkRows = Math.min(+ FLOW_MAX_CHUNK_ROWS,+ Math.max(FLOW_MIN_CHUNK_ROWS, Math.round((cache.chunkRows * FLOW_CHUNK_BUDGET_MS) / elapsed))+ )+ }+ actions.scheduleNextChunk()+ },+ scheduleNextChunk: () => {+ if (!values.flowWindow?.holes.length) {+ cache.disposables.dispose('nextChunk')+ return+ }+ cache.disposables.add(() => {+ let timer: ReturnType<typeof setTimeout>+ const renderNextChunk = (): void => {+ const now = performance.now()+ const jumping = now - cache.lastJumpToStartAt < FLOW_JUMP_TO_START_MS+ const scrollTop = props.readerScrollTop?.() ?? null+ const seekingStart =+ scrollTop !== null &&+ (jumping+ ? scrollTop <= FLOW_JUMP_ARRIVED_PX+ : scrollTop <= 0 && now - cache.lastScrollGestureAt > FLOW_SCROLL_GESTURE_MS)+ const typingWait = FLOW_INPUT_PAUSE_MS - (now - cache.lastInputAt)+ const scrollWait =+ scrollTop !== null && scrollTop <= FLOW_SCROLL_BUFFER_PX+ ? 0+ : FLOW_INPUT_PAUSE_MS - (now - cache.lastScrollGestureAt)+ // A jump key starts a smooth scroll, and rows added under it cancel it. Wait until it arrives.+ // While the reader scrolls, check often, so rows arrive soon after they near the oldest one.+ const wait = seekingStart+ ? 0+ : jumping+ ? FLOW_POLL_MS+ : Math.max(typingWait, scrollWait > 0 ? Math.min(scrollWait, FLOW_POLL_MS) : 0)+ if (wait > 0) {+ timer = setTimeout(renderNextChunk, wait)+ return+ }+ cache.chunkStartedAt = now+ actions.fillChunk(cache.chunkRows, seekingStart)+ }+ timer = setTimeout(renderNextChunk, 0)+ return () => clearTimeout(timer)+ }, 'nextChunk')+ },+ })),+ afterMount(({ cache }) => {+ cache.chunkRows = FLOW_INITIAL_ROWS+ cache.chunkStartedAt = null+ cache.lastInputAt = -Infinity+ cache.lastScrollGestureAt = -Infinity+ cache.lastJumpToStartAt = -Infinity+ cache.disposables.add(() => {+ const noteInput = (event: Event): void => {+ // A pointer that moves without a pressed button is a hover, not an interaction.+ if (event.type === 'pointermove' && (event as PointerEvent).buttons === 0) {+ return+ }+ if (event.type === 'keydown') {+ const { key, metaKey, ctrlKey, target } = event as KeyboardEvent+ // In a text field these keys move the caret, so they say nothing about the thread.+ const inTextField =+ target instanceof HTMLElement &&+ (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName))+ if (!inTextField && (key === 'Home' || (key === 'ArrowUp' && (metaKey || ctrlKey)))) {+ cache.lastJumpToStartAt = performance.now()+ return+ }+ }+ const scrollGesture =+ event.type === 'wheel' ||+ event.type === 'touchmove' ||+ (event.type === 'keydown' && FLOW_SCROLL_KEYS.has((event as KeyboardEvent).key))+ if (scrollGesture) {+ cache.lastScrollGestureAt = performance.now()+ } else {+ cache.lastInputAt = performance.now()+ }+ }+ for (const type of FLOW_INPUT_EVENTS) {+ window.addEventListener(type, noteInput, { capture: true, passive: true })+ }+ return () => {+ for (const type of FLOW_INPUT_EVENTS) {+ window.removeEventListener(type, noteInput, { capture: true })+ }+ }+ })+ }),+])diff --git a/products/posthog_ai/frontend/utils/flowWindow.ts b/products/posthog_ai/frontend/utils/flowWindow.tsnew file mode 100644index 000000000000..2cec4e03c3a2--- /dev/null+++ b/products/posthog_ai/frontend/utils/flowWindow.ts@@ -0,0 +1,107 @@+/** Rows a flow-mode thread renders at once when it opens or receives a bulk append. */+export const FLOW_INITIAL_ROWS = 24+/** An append of more rows than this renders only its newest rows at once. */+export const FLOW_BULK_APPEND_ROWS = 48++/** A half-open `[from, to)` range of row indexes. */+export type FlowRange = readonly [number, number]++/**+ * Which rows of a flow-mode thread are in the DOM. `holes` are the ranges not rendered yet, sorted+ * and disjoint. A fill step renders rows from the end of the last hole, so the rows nearest the+ * newest content arrive first.+ */+export interface FlowWindow {+ length: number+ firstKey: string | null+ holes: readonly FlowRange[]+ /** Counts fill steps, so the scroll keeper can tell a fill commit from any other commit. */+ fillStep: number+ /** The last fill step rendered the oldest rows, for a reader who went to the top of the thread. */+ fillAtStart: boolean+}++function openWindow(length: number, firstKey: string | null, previous: FlowWindow | null): FlowWindow {+ const tailStart = Math.max(0, length - FLOW_INITIAL_ROWS)+ return {+ length,+ firstKey,+ holes: tailStart > 0 ? [[0, tailStart]] : [],+ fillStep: previous?.fillStep ?? 0,+ fillAtStart: false,+ }+}++/**+ * Computes the window for the current rows from the previous window. Returns `previous` itself while+ * the row count and the first row stay the same, so a caller can compare by identity.+ */+export function deriveFlowWindow<T>(+ previous: FlowWindow | null,+ items: readonly T[],+ getItemKey: (item: T, index: number) => string+): FlowWindow {+ const length = items.length+ const firstKey = length > 0 ? getItemKey(items[0], 0) : null+ if (previous && previous.length === length && previous.firstKey === firstKey) {+ return previous+ }+ if (!previous || previous.length === 0 || previous.firstKey !== firstKey) {+ return openWindow(length, firstKey, previous)+ }+ const holes: [number, number][] = []+ for (const [from, to] of previous.holes) {+ const end = Math.min(to, length)+ if (from < end) {+ holes.push([from, end])+ }+ }+ const appendedFrom = previous.length+ const appendedTo = length - FLOW_INITIAL_ROWS+ if (length - previous.length > FLOW_BULK_APPEND_ROWS && appendedFrom < appendedTo) {+ const last = holes.at(-1)+ if (last && last[1] === appendedFrom) {+ last[1] = appendedTo+ } else {+ holes.push([appendedFrom, appendedTo])+ }+ }+ return { ...previous, length, firstKey, holes }+}++/**+ * Renders up to `rows` more rows. A normal step takes them from the end of the last hole, next to the+ * newest rows. A step `atStart` takes them from the start of the first hole, so the oldest rows render first.+ */+export function fillFlowWindow(window: FlowWindow, rows: number, atStart = false): FlowWindow {+ if (window.holes.length === 0) {+ return window+ }+ const holes = [...window.holes]+ if (atStart) {+ const [from, to] = holes[0]+ const start = Math.min(to, from + rows)+ holes.splice(0, 1, ...(start < to ? [[start, to] as const] : []))+ } else {+ const [from, to] = holes[holes.length - 1]+ const end = Math.max(from, to - rows)+ holes.splice(-1, 1, ...(from < end ? [[from, end] as const] : []))+ }+ return { ...window, holes, fillStep: window.fillStep + 1, fillAtStart: atStart }+}++/** The rendered ranges, in order: everything outside the holes. */+export function renderedFlowRanges(window: FlowWindow): FlowRange[] {+ const ranges: FlowRange[] = []+ let cursor = 0+ for (const [from, to] of window.holes) {+ if (cursor < from) {+ ranges.push([cursor, from])+ }+ cursor = to+ }+ if (cursor < window.length) {+ ranges.push([cursor, window.length])+ }+ return ranges+}