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.

feat(llma): virtualize the sandbox thread with a reusable VirtualizedThread (#65831)

Georgiy Tarasovf82218c952cc
diff --git a/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx b/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx
index 83df9118ee17..b9faadb610fc 100644
--- a/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx
+++ b/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx
@@ -190,7 +190,7 @@ function TaskLogBody({
if (task && runId) {
return (
- <div className="h-[calc(100vh-22rem)] min-h-[420px] w-full overflow-y-auto rounded border border-primary bg-surface-primary">
+ <div className="h-[calc(100dvh-22rem)] min-h-[420px] w-full overflow-hidden rounded border border-primary bg-surface-primary">
{/* In-progress runs stream live; terminal runs show the static replay. */}
<SandboxRunViewer taskId={task.id} runId={runId} replayOnly={replayOnly} />
</div>
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index 19f635b83e91..6bd96cfe37c3 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -136,7 +136,8 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul
logic={sandboxStreamLogic}
props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}
>
- <SandboxThreadView />
+ {/* The live Max column owns scroll via ThreadAutoScroller — render rows in flow, not virtualized. */}
+ <SandboxThreadView virtualized={false} />
</BindLogic>
</div>
)
@@ -156,7 +157,7 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul
logic={sandboxStreamLogic}
props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}
>
- <SandboxThreadView />
+ <SandboxThreadView virtualized={false} />
</BindLogic>
</div>
)
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a4228009f91f..2913751fb572 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3808,6 +3808,9 @@ importers:
react-dom:
specifier: 18.3.1
version: 18.3.1([email protected])
+ react-window:
+ specifier: '*'
tailwind-merge:
specifier: '*'
version: 2.2.2
diff --git a/products/posthog_ai/frontend/sandbox/ActivityPrimitives.tsx b/products/posthog_ai/frontend/sandbox/ActivityPrimitives.tsx
index 5ab60f4e24be..ed87f47343bd 100644
--- a/products/posthog_ai/frontend/sandbox/ActivityPrimitives.tsx
+++ b/products/posthog_ai/frontend/sandbox/ActivityPrimitives.tsx
@@ -1,7 +1,7 @@
import clsx from 'clsx'
import React, { useLayoutEffect, useState } from 'react'
-import { IconCheck, IconChevronRight, IconX } from '@posthog/icons'
+import { IconCheck, IconChevronDown, IconChevronRight, IconX } from '@posthog/icons'
import { LemonButton, Spinner } from '@posthog/lemon-ui'
import { MarkdownMessage } from './MarkdownMessage'
@@ -122,7 +122,7 @@ export function ActivityHeader({
return (
<div
className={clsx(
- 'transition-all duration-500 flex select-none min-w-0',
+ 'group/activity-header transition-all duration-500 flex select-none min-w-0',
(isPending || isFailed) && 'text-muted',
!isInProgress && !isPending && !isFailed && 'text-default',
hasDetails ? 'cursor-pointer' : 'cursor-default',
@@ -130,21 +130,44 @@ export function ActivityHeader({
hasDetails && isDetailsExpanded && 'bg-fill-button-tertiary-active'
)}
onClick={hasDetails ? onToggleDetails : undefined}
+ onKeyDown={
+ hasDetails
+ ? (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ onToggleDetails()
+ }
+ }
+ : undefined
+ }
+ role={hasDetails ? 'button' : undefined}
+ tabIndex={hasDetails ? 0 : undefined}
+ aria-expanded={hasDetails ? isDetailsExpanded : undefined}
aria-label={hasDetails ? (isDetailsExpanded ? 'Collapse history' : 'Expand history') : undefined}
>
{icon && (
- <div className="flex items-center justify-center size-5">
- {isInProgress && animate ? (
- <ShimmeringContent>{icon}</ShimmeringContent>
- ) : (
- <span className={clsx('inline-flex', isInProgress && 'text-muted')}>{icon}</span>
+ <div className="relative flex items-center justify-center size-5 shrink-0 overflow-hidden">
+ <span
+ className={clsx(
+ 'inline-flex transition-all duration-200 ease-out',
+ isInProgress && 'text-muted',
+ hasDetails &&
+ 'group-hover/activity-header:-translate-x-1 group-hover/activity-header:scale-90 group-hover/activity-header:opacity-0 group-focus-within/activity-header:-translate-x-1 group-focus-within/activity-header:scale-90 group-focus-within/activity-header:opacity-0'
+ )}
+ >
+ {isInProgress && animate ? <ShimmeringContent>{icon}</ShimmeringContent> : icon}
+ </span>
+ {hasDetails && (
+ <span className="absolute inline-flex translate-x-1 scale-90 text-tertiary opacity-0 transition-all duration-200 ease-out group-hover/activity-header:translate-x-0 group-hover/activity-header:scale-100 group-hover/activity-header:text-primary group-hover/activity-header:opacity-100 group-focus-within/activity-header:translate-x-0 group-focus-within/activity-header:scale-100 group-focus-within/activity-header:text-primary group-focus-within/activity-header:opacity-100">
+ <IconChevronDown className="size-5" />
+ </span>
)}
</div>
)}
<div className="flex items-center gap-1 flex-1 min-w-0 h-full">
{children ? (
// The title/subtitle column grows to fill the row, so the subtitle (second line) gets the
- // full available width before it truncates and the chevron stays pinned to the right.
+ // full available width before it truncates.
<div className="flex flex-col flex-1 min-w-0">
{/* Status icon rides the first line with the title; the second line is the subtitle. */}
<div className="flex items-center gap-1 min-w-0">
@@ -156,15 +179,6 @@ export function ActivityHeader({
) : (
<div className="min-w-0">{titleNode}</div>
)}
- {hasDetails && (
- <div className="relative shrink-0 flex flex-col items-start justify-center h-full">
- <button className="inline-flex items-center hover:opacity-70 transition-opacity shrink-0 cursor-pointer">
- <span className={clsx('transform transition-transform', isDetailsExpanded && 'rotate-90')}>
- <IconChevronRight />
- </span>
- </button>
- </div>
- )}
{!children && statusIcon}
</div>
</div>
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx b/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx
index 14bb8b1279a4..3d624ef8bdf6 100644
--- a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx
+++ b/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx
@@ -73,12 +73,7 @@ function SandboxRunViewerContent({
const showSpinner = bootstrapLoading && threadItems.length === 0
return (
- <div
- className={cn(
- '@container/thread flex flex-col items-stretch w-full max-w-180 self-center gap-1.5 grow mx-auto',
- className
- )}
- >
+ <div className={cn('flex flex-col h-full min-h-0 w-full', className)}>
{showSpinner ? (
<div className="flex justify-center py-8">
<Spinner className="text-2xl" />
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxThreadRow.tsx b/products/posthog_ai/frontend/sandbox/components/SandboxThreadRow.tsx
new file mode 100644
index 000000000000..d5b94d23a5c9
--- /dev/null
+++ b/products/posthog_ai/frontend/sandbox/components/SandboxThreadRow.tsx
@@ -0,0 +1,164 @@
+import { memo } from 'react'
+
+import { IconWrench } from '@posthog/icons'
+
+import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-assistant-messages'
+
+import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/sandbox/types/sandboxToolTypes'
+
+import { MarkdownMessage } from '../MarkdownMessage'
+import { AssistantFailureMessage } from '../messages/AssistantFailureMessage'
+import { MessageTemplate } from '../messages/MessageTemplate'
+import { ReasoningAnswer } from '../messages/ReasoningAnswer'
+import { SandboxActivity } from '../SandboxActivity'
+import { sandboxStreamLogic } from '../sandboxStreamLogic'
+import { SandboxCompactBoundaryItem, SandboxStatusItem, SandboxTaskNotificationItem } from '../SandboxThreadItems'
+import { resolveToolCall } from '../sandboxToolResolver'
+import type { SandboxProgressStep, ThreadItem as SandboxThreadItem } from '../types/sandboxStreamTypes'
+import { SandboxToolCall } from './tool/SandboxToolCall'
+
+type ToolInvocations = typeof sandboxStreamLogic.values.toolInvocations
+
+/** Maps a raw merged `ToolInvocation` into the flat `SandboxToolCallMessage` the registry renderers read. */
+function toolInvocationToMessage(invocation: ReturnType<ToolInvocations['get']>): SandboxToolCallMessage | null {
+ if (!invocation) {
+ return null
+ }
+ const resolved = resolveToolCall(invocation)
+ return {
+ id: invocation.toolCallId,
+ resolvedKey: resolved.resolvedKey,
+ rawServerName: invocation.rawServerName,
+ rawToolName: invocation.rawToolName,
+ innerToolName: resolved.innerToolName,
+ claudeToolName: resolved.claudeToolName,
+ rawInput: invocation.input,
+ innerInput: resolved.innerInput,
+ rawOutput: invocation.output,
+ content: invocation.contentBlocks,
+ status: invocation.status,
+ title: invocation.title,
+ kind: invocation.kind,
+ locations: invocation.locations,
+ error: invocation.error,
+ }
+}
+
+function progressStepText(step: SandboxProgressStep): string {
+ return step.detail ? `${step.label}\n\n${step.detail}` : step.label
+}
+
+function resolveSandboxProgressState(steps: SandboxProgressStep[]): ExecutionStatus {
+ if (steps.some((step) => step.status === 'failed')) {
+ return ExecutionStatus.Failed
+ }
+ if (steps.some((step) => step.status === 'in_progress')) {
+ return ExecutionStatus.InProgress
+ }
+ if (steps.length > 0 && steps.every((step) => step.status === 'pending')) {
+ return ExecutionStatus.Pending
+ }
+ return ExecutionStatus.Completed
+}
+
+function resolveSandboxProgressHeadline(steps: SandboxProgressStep[]): string {
+ const active = steps.find((step) => step.status === 'in_progress')
+ if (active) {
+ return active.label
+ }
+ return steps.at(-1)?.label ?? 'Working'
+}
+
+function SandboxProgressItem({ item }: { item: SandboxThreadItem }): JSX.Element | null {
+ const steps = item.progressSteps ?? []
+ if (!steps.length) {
+ return null
+ }
+
+ const headline = resolveSandboxProgressHeadline(steps)
+ const substeps = steps.length > 1 ? steps.map(progressStepText) : []
+ const state = resolveSandboxProgressState(steps)
+
+ return (
+ <SandboxActivity
+ id={item.id}
+ content={headline}
+ substeps={substeps}
+ state={state}
+ icon={<IconWrench />}
+ showCompletionIcon={true}
+ />
+ )
+}
+
+export interface SandboxThreadRowProps {
+ item: SandboxThreadItem
+ /** Last item in the thread — drives reasoning collapse alongside `isThinking`. */
+ isLast: boolean
+ isThinking: boolean
+ toolInvocations: ToolInvocations
+ turnComplete: boolean
+ turnCancelled: boolean
+}
+
+/**
+ * Renders a single sandbox thread item by type. Memoized and keyed by stable `item.id` so a re-projected
+ * `threadItems` array only re-renders rows whose data actually changed.
+ */
+export const SandboxThreadRow = memo(function SandboxThreadRow({
+ item,
+ isLast,
+ isThinking,
+ toolInvocations,
+ turnComplete,
+ turnCancelled,
+}: SandboxThreadRowProps): JSX.Element | null {
+ if (item.type === 'human_message') {
+ return (
+ <MessageTemplate type="human">
+ <MarkdownMessage content={item.text || '*No text.*'} id={item.id} />
+ </MessageTemplate>
+ )
+ }
+ if (item.type === 'assistant_message') {
+ return (
+ <MessageTemplate type="ai">
+ <MarkdownMessage content={item.text ?? ''} id={item.id} />
+ </MessageTemplate>
+ )
+ }
+ if (item.type === 'assistant_thought') {
+ // Empty chunks prime the stream before any reasoning text arrives — skip them so a contentless
+ // "Thought" never shows; the bottom indicator covers that gap.
+ if (!item.text?.trim()) {
+ return null
+ }
+ // Collapse to "Thought" once a later block starts or the run stops thinking — mirrors the LangGraph
+ // thread's reasoning-complete rule.
+ const completed = !isLast || !isThinking
+ return <ReasoningAnswer content={item.text} id={item.id} completed={completed} showCompletionIcon={false} />
+ }
+ if (item.type === 'tool_invocation' && item.toolCallId) {
+ const message = toolInvocationToMessage(toolInvocations.get(item.toolCallId))
+ if (!message) {
+ return null
+ }
+ return <SandboxToolCall message={message} turnComplete={turnComplete} turnCancelled={turnCancelled} />
+ }
+ if (item.type === 'error') {
+ return <AssistantFailureMessage id={item.id} content={item.errorMessage} />
+ }
+ if (item.type === 'status') {
+ return <SandboxStatusItem item={item} />
+ }
+ if (item.type === 'compact_boundary') {
+ return <SandboxCompactBoundaryItem item={item} />
+ }
+ if (item.type === 'task_notification') {
+ return <SandboxTaskNotificationItem item={item} />
+ }
+ if (item.type === 'progress') {
+ return <SandboxProgressItem item={item} />
+ }
+ return null
+})
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxThreadView.tsx b/products/posthog_ai/frontend/sandbox/components/SandboxThreadView.tsx
index f0f8506b1022..d3b0c3daac51 100644
--- a/products/posthog_ai/frontend/sandbox/components/SandboxThreadView.tsx
+++ b/products/posthog_ai/frontend/sandbox/components/SandboxThreadView.tsx
@@ -1,51 +1,18 @@
import { useValues } from 'kea'
-import { useMemo } from 'react'
+import { memo, useCallback, useMemo } from 'react'
-import { IconWrench } from '@posthog/icons'
-
-import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-assistant-messages'
-
-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/sandbox/types/sandboxToolTypes'
-
-import { MarkdownMessage } from '../MarkdownMessage'
-import { AssistantFailureMessage } from '../messages/AssistantFailureMessage'
-import { MessageTemplate } from '../messages/MessageTemplate'
import { ReasoningAnswer } from '../messages/ReasoningAnswer'
-import { SandboxActivity } from '../SandboxActivity'
import { SandboxPullRequestCard } from '../SandboxPullRequestCard'
import { SandboxRunContext } from '../SandboxRunContext'
import { sandboxStreamLogic } from '../sandboxStreamLogic'
-import { SandboxCompactBoundaryItem, SandboxStatusItem, SandboxTaskNotificationItem } from '../SandboxThreadItems'
-import { resolveToolCall } from '../sandboxToolResolver'
-import type { SandboxProgressStep, ThreadItem as SandboxThreadItem } from '../types/sandboxStreamTypes'
+import type { ThreadItem } from '../types/sandboxStreamTypes'
import { getRandomThinkingMessage } from '../utils/thinkingMessages'
-import { SandboxToolCall } from './tool/SandboxToolCall'
+import { SandboxThreadRow } from './SandboxThreadRow'
+import { VirtualizedThread } from './VirtualizedThread'
-/** Maps a raw merged `ToolInvocation` into the flat `SandboxToolCallMessage` the registry renderers read. */
-function toolInvocationToMessage(
- invocation: ReturnType<typeof sandboxStreamLogic.values.toolInvocations.get>
-): SandboxToolCallMessage | null {
- if (!invocation) {
- return null
- }
- const resolved = resolveToolCall(invocation)
- return {
- id: invocation.toolCallId,
- resolvedKey: resolved.resolvedKey,
- rawServerName: invocation.rawServerName,
- rawToolName: invocation.rawToolName,
- innerToolName: resolved.innerToolName,
- claudeToolName: resolved.claudeToolName,
- rawInput: invocation.input,
- innerInput: resolved.innerInput,
- rawOutput: invocation.output,
- content: invocation.contentBlocks,
- status: invocation.status,
- title: invocation.title,
- kind: invocation.kind,
- locations: invocation.locations,
- error: invocation.error,
- }
+/** Stable row key — defined at module scope so `getItemKey` never changes identity across renders. */
+function getThreadItemKey(item: ThreadItem): string {
+ return item.id
}
/**
@@ -54,156 +21,116 @@ function toolInvocationToMessage(
* instance is bound above it — a live PostHog AI conversation or a read-only run viewer — and
* dispatches tool cards through the sandbox tool registry. Conversation-agnostic by design: it knows
* only the bound stream logic, never langgraph vs sandbox or the conversation.
+ *
+ * Rows are virtualized through `VirtualizedThread`, which owns scroll and stick-to-bottom; the leading
+ * run context and trailing thinking indicator / PR card ride along as the header/footer rows. Pass
+ * `virtualized={false}` when an ancestor already owns scroll (the live Max column + auto-scroller) — rows
+ * then render in document flow, unchanged from the pre-virtualized layout.
*/
-export function SandboxThreadView(): JSX.Element {
- // Drive the thinking indicator from real agent progress: show the latest `_posthog/progress`
- // message while the run is active, falling back to the canned rotation.
- const {
- threadItems,
- toolInvocations,
- currentProgress,
- isThinking,
- streamPhase,
- runArtifacts,
- turnComplete,
- currentRunStatus,
- } = useValues(sandboxStreamLogic)
+export function SandboxThreadView({ virtualized = true }: { virtualized?: boolean } = {}): JSX.Element {
+ const { threadItems, toolInvocations, isThinking, streamPhase, runArtifacts, turnComplete, currentRunStatus } =
+ useValues(sandboxStreamLogic)
const turnCancelled = currentRunStatus === 'cancelled'
const hasActiveProgressItem = threadItems.some(
(item) => item.type === 'progress' && item.progressSteps?.some((step) => step.status === 'in_progress')
)
- return (
- <>
- {runArtifacts.branch && (
- <SandboxRunContext
- branch={runArtifacts.branch}
- baseBranch={runArtifacts.baseBranch}
- repo={runArtifacts.repo}
- />
- )}
- {threadItems.map((item, index) => {
- if (item.type === 'human_message') {
- return (
- <MessageTemplate key={item.id} type="human">
- <MarkdownMessage content={item.text || '*No text.*'} id={item.id} />
- </MessageTemplate>
- )
- }
- if (item.type === 'assistant_message') {
- return (
- <MessageTemplate key={item.id} type="ai">
- <MarkdownMessage content={item.text ?? ''} id={item.id} />
- </MessageTemplate>
- )
- }
- if (item.type === 'assistant_thought') {
- // Empty chunks prime the stream before any reasoning text arrives — skip them so
- // a contentless "Thought" never shows; the bottom indicator covers that gap.
- if (!item.text?.trim()) {
- return null
- }
- // Collapse to "Thought" once a later block starts or the run stops thinking —
- // mirrors the LangGraph thread's reasoning-complete rule.
- const completed = index !== threadItems.length - 1 || !isThinking
- return (
- <ReasoningAnswer
- key={item.id}
- content={item.text}
- id={item.id}
- completed={completed}
- showCompletionIcon={false}
- />
- )
- }
- if (item.type === 'tool_invocation' && item.toolCallId) {
- const message = toolInvocationToMessage(toolInvocations.get(item.toolCallId))
- if (!message) {
- return null
- }
- return (
- <SandboxToolCall
- key={item.id}
- message={message}
- turnComplete={turnComplete}
- turnCancelled={turnCancelled}
- />
- )
- }
- if (item.type === 'error') {
- return <AssistantFailureMessage key={item.id} id={item.id} content={item.errorMessage} />
- }
- if (item.type === 'status') {
- return <SandboxStatusItem key={item.id} item={item} />
- }
- if (item.type === 'compact_boundary') {
- return <SandboxCompactBoundaryItem key={item.id} item={item} />
- }
- if (item.type === 'task_notification') {
- return <SandboxTaskNotificationItem key={item.id} item={item} />
- }
- if (item.type === 'progress') {
- return <SandboxProgressItem key={item.id} item={item} />
- }
- return null
- })}
- {streamPhase === 'thinking' && !hasActiveProgressItem && (
- <SandboxThinkingIndicator progress={currentProgress} />
- )}
- {/* Post-turn only: a reconnect refetch can fold in a pr_url mid-run, so gate on !isThinking. */}
- {!isThinking && runArtifacts.prUrl && (
- <SandboxPullRequestCard prUrl={runArtifacts.prUrl} branch={runArtifacts.branch} />
- )}
- </>
+ // 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.
+ const { branch, baseBranch, repo } = runArtifacts
+ const header = useMemo(
+ () =>
+ branch ? (
+ <VirtualizedThread.Row>
+ <SandboxThreadHeader branch={branch} baseBranch={baseBranch} repo={repo} />
+ </VirtualizedThread.Row>
+ ) : undefined,
+ [branch, baseBranch, repo]
)
-}
-function progressStepText(step: SandboxProgressStep): string {
- return step.detail ? `${step.label}\n\n${step.detail}` : step.label
-}
+ const showThinking = streamPhase === 'thinking' && !hasActiveProgressItem
+ // Post-turn only: a reconnect refetch can fold in a pr_url mid-run, so gate on !isThinking.
+ const pullRequestUrl = !isThinking ? runArtifacts.prUrl : undefined
+ const footer = useMemo(
+ () =>
+ showThinking || pullRequestUrl ? (
+ <VirtualizedThread.Row>
+ <SandboxThreadFooter
+ showThinking={showThinking}
+ pullRequestUrl={pullRequestUrl}
+ prBranch={branch}
+ />
+ </VirtualizedThread.Row>
+ ) : undefined,
+ [showThinking, pullRequestUrl, branch]
+ )
-function resolveSandboxProgressState(steps: SandboxProgressStep[]): ExecutionStatus {
- if (steps.some((step) => step.status === 'failed')) {
- return ExecutionStatus.Failed
- }
- if (steps.some((step) => step.status === 'in_progress')) {
- return ExecutionStatus.InProgress
- }
- if (steps.length > 0 && steps.every((step) => step.status === 'pending')) {
- return ExecutionStatus.Pending
- }
- return ExecutionStatus.Completed
-}
+ const renderItem = useCallback(
+ (item: ThreadItem, index: number): JSX.Element => (
+ <VirtualizedThread.Row>
+ <SandboxThreadRow
+ item={item}
+ isLast={index === threadItems.length - 1}
+ isThinking={isThinking}
+ toolInvocations={toolInvocations}
+ turnComplete={turnComplete}
+ turnCancelled={turnCancelled}
+ />
+ </VirtualizedThread.Row>
+ ),
+ [threadItems.length, isThinking, toolInvocations, turnComplete, turnCancelled]
+ )
-function resolveSandboxProgressHeadline(steps: SandboxProgressStep[]): string {
- const active = steps.find((step) => step.status === 'in_progress')
- if (active) {
- return active.label
- }
- return steps.at(-1)?.label ?? 'Working'
+ return (
+ <VirtualizedThread.Root
+ items={threadItems}
+ getItemKey={getThreadItemKey}
+ header={header}
+ footer={footer}
+ stickToBottom
+ virtualized={virtualized}
+ >
+ {renderItem}
+ </VirtualizedThread.Root>
+ )
}
-function SandboxProgressItem({ item }: { item: SandboxThreadItem }): JSX.Element | null {
- const steps = item.progressSteps ?? []
- if (!steps.length) {
- return null
- }
-
- const headline = resolveSandboxProgressHeadline(steps)
- const substeps = steps.length > 1 ? steps.map(progressStepText) : []
- const state = resolveSandboxProgressState(steps)
+/** Leading run-context row. Memoized so it only re-renders when the run's branch/repo refs change. */
+const SandboxThreadHeader = memo(function SandboxThreadHeader({
+ branch,
+ baseBranch,
+ repo,
+}: {
+ branch: string
+ baseBranch?: string
+ repo?: string
+}): JSX.Element {
+ return <SandboxRunContext branch={branch} baseBranch={baseBranch} repo={repo} />
+})
+/**
+ * Trailing row: the "what's it doing now" thinking line and/or the produced PR card. Subscribes to
+ * `currentProgress` itself so the frequently-updating progress text stays isolated here — it never
+ * re-renders `SandboxThreadView` or destabilizes the footer's element identity during streaming.
+ */
+const SandboxThreadFooter = memo(function SandboxThreadFooter({
+ showThinking,
+ pullRequestUrl,
+ prBranch,
+}: {
+ showThinking: boolean
+ pullRequestUrl?: string
+ prBranch?: string
+}): JSX.Element {
+ const { currentProgress } = useValues(sandboxStreamLogic)
return (
- <SandboxActivity
- id={item.id}
- content={headline}
- substeps={substeps}
- state={state}
- icon={<IconWrench />}
- showCompletionIcon={true}
- />
+ <>
+ {showThinking && <SandboxThinkingIndicator progress={currentProgress} />}
+ {pullRequestUrl && <SandboxPullRequestCard prUrl={pullRequestUrl} branch={prBranch} />}
+ </>
)
-}
+})
/**
* Bottom-of-thread "what's it doing right now" line for sandbox conversations. Reflects the latest
diff --git a/products/posthog_ai/frontend/sandbox/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/sandbox/components/VirtualizedThread.tsx
new file mode 100644
index 000000000000..d17205e508bd
--- /dev/null
+++ b/products/posthog_ai/frontend/sandbox/components/VirtualizedThread.tsx
@@ -0,0 +1,300 @@
+import {
+ createContext,
+ CSSProperties,
+ ReactNode,
+ UIEvent,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+} 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
+
+const EMPTY_STYLE: CSSProperties = {}
+const EMPTY_ARIA: Record<string, unknown> = {}
+
+interface RootContextValue {
+ dynamicRowHeight: ReturnType<typeof useDynamicRowHeight>
+ /** Inter-row spacing (px), applied as bottom padding on the measured row so heights include it. */
+ gap: number
+ maxWidthClassName: string
+ /** When false, rows render in document flow (no react-window) 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 {
+ renderRow: (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])
+ 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). */
+ getItemKey: (item: T, index: number) => string
+ /** Rendered as a measured leading row (e.g. run context). */
+ header?: ReactNode
+ /** Rendered as a measured trailing row (e.g. thinking indicator, PR card). */
+ footer?: ReactNode
+ /** Inter-row spacing in px (default 6, matching `gap-1.5`). */
+ gap?: number
+ /** Height used until a row is measured. */
+ defaultRowHeight?: number
+ overscanCount?: number
+ /** Follow the bottom as rows grow/append; unpins when the user scrolls up. */
+ stickToBottom?: boolean
+ maxWidthClassName?: string
+ className?: string
+ /**
+ * Virtualize and own scroll (default `true` — requires a height-bounded parent). Pass `false` to render
+ * rows in document flow and let an ancestor own the scroll (e.g. an external auto-scroller); the wrapper
+ * adds no chrome in this mode, so the parent supplies layout (gap, centering, container query).
+ */
+ virtualized?: boolean
+ children: (item: T, index: number) => ReactNode
+}
+
+/**
+ * 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`.
+ */
+function Root<T>({
+ items,
+ getItemKey,
+ header,
+ footer,
+ gap = 6,
+ defaultRowHeight = 56,
+ overscanCount = 10,
+ stickToBottom = true,
+ maxWidthClassName = 'max-w-180',
+ className,
+ 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 != null
+ const hasFooter = footer != null
+ const rowCount = items.length + (hasHeader ? 1 : 0) + (hasFooter ? 1 : 0)
+
+ const pinnedRef = useRef(stickToBottom)
+
+ const renderRow = useCallback(
+ (index: number): ReactNode => {
+ let i = index
+ if (hasHeader) {
+ if (i === 0) {
+ return header
+ }
+ i -= 1
+ }
+ if (i < items.length) {
+ return children(items[i], i)
+ }
+ return footer
+ },
+ [items, header, footer, hasHeader, children]
+ )
+
+ const scrollToBottom = useCallback((): void => {
+ if (rowCount > 0) {
+ listRef.current?.scrollToRow({ index: rowCount - 1, align: 'end' })
+ }
+ }, [listRef, rowCount])
+
+ const handleScroll = useCallback(
+ (event: UIEvent<HTMLDivElement>): void => {
+ if (!stickToBottom) {
+ return
+ }
+ const el = event.currentTarget
+ pinnedRef.current = el.scrollHeight - el.scrollTop - el.clientHeight <= BOTTOM_THRESHOLD
+ },
+ [stickToBottom]
+ )
+
+ const handleRowsRendered = useCallback((): void => {
+ // Re-assert while pinned so a growing last row (streaming) keeps the bottom in view.
+ if (stickToBottom && pinnedRef.current) {
+ scrollToBottom()
+ }
+ }, [stickToBottom, scrollToBottom])
+
+ // Scroll on append / last-item change while pinned — and as dynamic measurements settle. Pinned by
+ // default, so this also scrolls to the bottom on open. The first scroll fires before rows are measured
+ // (they start at `defaultRowHeight`) and lands short; depending on the measured average row height
+ // re-fires it as ResizeObserver grows the rows, so it settles at the true bottom. The same signal keeps
+ // a streaming last row pinned as it grows.
+ 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(scrollToBottom)
+ return () => cancelAnimationFrame(raf)
+ }, [virtualized, stickToBottom, scrollToBottom, rowCount, lastKey, measuredAverageHeight])
+
+ // 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.visualViewport
+ const onViewportChange = (): void => {
+ if (pinnedRef.current) {
+ requestAnimationFrame(scrollToBottom)
+ }
+ }
+ viewport.addEventListener('resize', onViewportChange)
+ viewport.addEventListener('scroll', onViewportChange)
+ return () => {
+ viewport.removeEventListener('resize', onViewportChange)
+ viewport.removeEventListener('scroll', onViewportChange)
+ }
+ }, [virtualized, stickToBottom, scrollToBottom])
+
+ const rootValue = useMemo<RootContextValue>(
+ () => ({ dynamicRowHeight, gap, maxWidthClassName, virtualized }),
+ [dynamicRowHeight, gap, maxWidthClassName, virtualized]
+ )
+
+ // Flow mode: render rows directly so an ancestor scroll container (and its auto-scroller) keeps working.
+ // No chrome here — the parent supplies gap/centering/container-query context, matching the pre-virtualized
+ // layout exactly.
+ if (!virtualized) {
+ return (
+ <RootContext.Provider value={rootValue}>
+ {hasHeader && (
+ <RowContext.Provider
+ key="header"
+ value={{ index: 0, style: EMPTY_STYLE, ariaAttributes: EMPTY_ARIA }}
+ >
+ {header}
+ </RowContext.Provider>
+ )}
+ {items.map((item, index) => (
+ <RowContext.Provider
+ key={getItemKey(item, index)}
+ value={{ index, style: EMPTY_STYLE, ariaAttributes: EMPTY_ARIA }}
+ >
+ {children(item, index)}
+ </RowContext.Provider>
+ ))}
+ {hasFooter && (
+ <RowContext.Provider
+ key="footer"
+ value={{ index: rowCount - 1, style: EMPTY_STYLE, ariaAttributes: EMPTY_ARIA }}
+ >
+ {footer}
+ </RowContext.Provider>
+ )}
+ </RootContext.Provider>
+ )
+ }
+
+ 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="overscroll-contain"
+ overscanCount={overscanCount}
+ rowCount={rowCount}
+ rowHeight={dynamicRowHeight}
+ rowComponent={InternalRow}
+ rowProps={{ renderRow }}
+ listRef={listRef}
+ onRowsRendered={handleRowsRendered}
+ onScroll={handleScroll}
+ />
+ )
+ }}
+ />
+ </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.
+ */
+function Row({ children, className }: { children: ReactNode; className?: string }): JSX.Element {
+ const root = useContext(RootContext)
+ const row = useContext(RowContext)
+ if (!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])
+
+ // Flow mode: transparent — the parent container provides spacing and centering.
+ if (!virtualized) {
+ return <>{children}</>
+ }
+
+ return (
+ <div ref={rowRef} style={style} data-index={index} {...ariaAttributes}>
+ <div
+ className={cn('w-full mx-auto @container/thread', maxWidthClassName, className)}
+ style={{ paddingBottom: gap }}
+ >
+ {children}
+ </div>
+ </div>
+ )
+}
+
+export const VirtualizedThread = { Root, Row }
diff --git a/products/posthog_ai/package.json b/products/posthog_ai/package.json
index 41f77d049072..aa1ac2db8014 100644
--- a/products/posthog_ai/package.json
+++ b/products/posthog_ai/package.json
@@ -8,6 +8,7 @@
"kea-subscriptions": "catalog:",
"marked": "*",
"posthog-js": "catalog:",
+ "react-window": "*",
"tailwind-merge": "*"
},
"devDependencies": {
diff --git a/products/tasks/frontend/components/TaskDetailPage.tsx b/products/tasks/frontend/components/TaskDetailPage.tsx
index dc925db5ffa9..46cdca9b028e 100644
--- a/products/tasks/frontend/components/TaskDetailPage.tsx
+++ b/products/tasks/frontend/components/TaskDetailPage.tsx
@@ -363,7 +363,7 @@ function TaskRunLogState({
}
if (taskId && selectedRun) {
return (
- <div className="flex-1 min-h-0 overflow-hidden max-w-6xl mx-auto w-full">
+ <div className="flex-1 min-h-0 overflow-hidden -mr-4 pr-4">
<TaskRunChat taskId={taskId} runId={selectedRun.id} />
</div>
)
diff --git a/products/tasks/frontend/components/TaskRunChat.tsx b/products/tasks/frontend/components/TaskRunChat.tsx
index ef5418cba2b7..f80db8c37505 100644
--- a/products/tasks/frontend/components/TaskRunChat.tsx
+++ b/products/tasks/frontend/components/TaskRunChat.tsx
@@ -69,7 +69,7 @@ function TaskRunChatContent({ taskId, runId }: TaskRunChatProps): JSX.Element {
return (
<div className="flex flex-col h-full overflow-hidden">
- <div className="flex-1 overflow-y-auto flex flex-col gap-3">
+ <div className="flex-1 min-h-0">
{isLogPending ? (
<TaskRunLogSkeleton />
) : showBootstrapError && bootstrapError?.status === 404 ? (
@@ -91,41 +91,53 @@ function TaskRunChatContent({ taskId, runId }: TaskRunChatProps): JSX.Element {
)}
</div>
- {!isBlockingBootstrapState && <SandboxResourcesBar />}
+ {!isBlockingBootstrapState && (
+ <div className="w-full max-w-180 mx-auto">
+ <SandboxResourcesBar />
+ </div>
+ )}
{pendingPermissionRequest && !isTerminal && !isBlockingBootstrapState && (
<div className="border-t px-4 py-3">
- {isQuestion ? (
- <SandboxQuestionInput streamKey={runId} request={pendingPermissionRequest} />
- ) : (
- <SandboxPermissionInput streamKey={runId} request={pendingPermissionRequest} />
- )}
+ <div className="w-full max-w-180 mx-auto">
+ {isQuestion ? (
+ <SandboxQuestionInput streamKey={runId} request={pendingPermissionRequest} />
+ ) : (
+ <SandboxPermissionInput streamKey={runId} request={pendingPermissionRequest} />
+ )}
+ </div>
</div>
)}
{!isTerminal && !pendingPermissionRequest && !isBlockingBootstrapState && (
- <div className="border-t px-4 py-3 flex gap-2 items-end">
- <LemonTextArea
- className="flex-1"
- value={composerText}
- onChange={setComposerText}
- placeholder="Send a follow-up message…"
- minRows={1}
- maxRows={8}
- onPressCmdEnter={handleSend}
- />
- <LemonButton
- type="primary"
- onClick={handleSend}
- loading={sendingMessage}
- disabledReason={!composerText.trim() ? 'Type a message first' : undefined}
- >
- Send
- </LemonButton>
+ <div className="border-t px-4 py-3">
+ <div className="w-full max-w-180 mx-auto flex gap-2 items-end">
+ <LemonTextArea
+ className="flex-1"
+ value={composerText}
+ onChange={setComposerText}
+ placeholder="Send a follow-up message…"
+ minRows={1}
+ maxRows={8}
+ onPressCmdEnter={handleSend}
+ />
+ <LemonButton
+ type="primary"
+ onClick={handleSend}
+ loading={sendingMessage}
+ disabledReason={!composerText.trim() ? 'Type a message first' : undefined}
+ >
+ Send
+ </LemonButton>
+ </div>
</div>
)}
- {!isBlockingBootstrapState && <SandboxContextUsage />}
+ {!isBlockingBootstrapState && (
+ <div className="w-full max-w-180 mx-auto">
+ <SandboxContextUsage />
+ </div>
+ )}
</div>
)
}