Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(posthog-ai): stop the chat thread freezing while a reply streams (#111402)

Shy Alter571f3e573c9a
diff --git a/products/posthog_ai/frontend/components/ThreadActivityGroup.stories.tsx b/products/posthog_ai/frontend/components/ThreadActivityGroup.stories.tsx
index 0ddf6aab36c5..5047bfba4acb 100644
--- a/products/posthog_ai/frontend/components/ThreadActivityGroup.stories.tsx
+++ b/products/posthog_ai/frontend/components/ThreadActivityGroup.stories.tsx
@@ -49,7 +49,7 @@ const meta: Meta<typeof ThreadActivityGroup> = {
item={item}
isLast={false}
isThinking={false}
- toolInvocations={tools}
+ invocation={item.toolCallId ? tools.get(item.toolCallId) : undefined}
turnComplete
turnCancelled={false}
/>
diff --git a/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx b/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx
index 8f14c1e877d0..288e8ec04d08 100644
--- a/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx
+++ b/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx
@@ -1,3 +1,5 @@
+import { memo } from 'react'
+
import { IconChevronRight, IconSpinner } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
@@ -8,9 +10,9 @@ import { QuillActivityGroup } from './quill/QuillActivityGroup'
import { useQuillThread } from './quill/quillThreadContext'
import { type ActivityGroupProps, useActivityGroup } from './useActivityGroup'
-export function ThreadActivityGroup(props: ActivityGroupProps): JSX.Element {
+export const ThreadActivityGroup = memo(function ThreadActivityGroup(props: ActivityGroupProps): JSX.Element {
return useQuillThread() ? <QuillActivityGroup {...props} /> : <LemonThreadActivityGroup {...props} />
-}
+})
function LemonThreadActivityGroup(props: ActivityGroupProps): JSX.Element {
const { group, toolInvocations, active, waitingForInput = false, renderItem } = props
diff --git a/products/posthog_ai/frontend/components/ThreadRow.tsx b/products/posthog_ai/frontend/components/ThreadRow.tsx
index f6dddf87dfd2..7cd4105ae847 100644
--- a/products/posthog_ai/frontend/components/ThreadRow.tsx
+++ b/products/posthog_ai/frontend/components/ThreadRow.tsx
@@ -10,12 +10,11 @@ import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-
import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
-import { runStreamLogic } from '../logics/runStreamLogic'
import { DebugMessage } from '../messages/DebugMessage'
import { MarkdownMessage } from '../messages/MarkdownMessage'
import { MessageTemplate } from '../messages/MessageTemplate'
import { ReasoningAnswer } from '../messages/ReasoningAnswer'
-import type { ProgressStep, ThreadItem } from '../types/streamTypes'
+import type { ProgressStep, ThreadItem, ToolInvocation } from '../types/streamTypes'
import { resolveToolCall } from '../utils/toolResolver'
import { userMessageDisplayText } from '../utils/userMessageDisplay'
import { Activity } from './ActivityPrimitives'
@@ -27,10 +26,8 @@ import { ThreadAttachments } from './ThreadAttachments'
import { CompactBoundaryItem, ConversationClearedItem, StatusItem, TaskNotificationItem } from './ThreadItems'
import { ToolCallCard } from './tool/ToolCallCard'
-type ToolInvocations = typeof runStreamLogic.values.toolInvocations
-
/** Maps a raw merged `ToolInvocation` into the flat `ToolCallMessage` the registry renderers read. */
-function toolInvocationToMessage(invocation: ReturnType<ToolInvocations['get']>): ToolCallMessage | null {
+function toolInvocationToMessage(invocation: ToolInvocation | undefined): ToolCallMessage | null {
if (!invocation) {
return null
}
@@ -107,7 +104,7 @@ export interface ThreadRowProps {
/** Last item in the thread — drives reasoning collapse alongside `isThinking`. */
isLast: boolean
isThinking: boolean
- toolInvocations: ToolInvocations
+ invocation?: ToolInvocation
turnComplete: boolean
turnCancelled: boolean
/** The current run reached a terminal status; only then is the last error the run's ending. */
@@ -144,7 +141,7 @@ export const ThreadRow = memo(function ThreadRow({
item,
isLast,
isThinking,
- toolInvocations,
+ invocation,
turnComplete,
turnCancelled,
runEnded = true,
@@ -188,7 +185,7 @@ export const ThreadRow = memo(function ThreadRow({
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))
+ const message = toolInvocationToMessage(invocation)
if (!message) {
return null
}
diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsx
index 557a68dd5564..e99aedf65e69 100644
--- a/products/posthog_ai/frontend/components/ThreadView.tsx
+++ b/products/posthog_ai/frontend/components/ThreadView.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { type ReactNode, memo, useCallback, useEffect, useMemo, useState } from 'react'
+import { type ReactNode, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { cn } from 'lib/utils/css-classes'
import { inStorybookTestRunner } from 'lib/utils/dom'
@@ -12,6 +12,8 @@ import {
groupToolRuns,
isRunningStatus,
isStartupStatus,
+ reuseActivityGroups,
+ type ThreadActivityGroup as ThreadActivityGroupItem,
type ThreadDisplayItem,
} from '../utils/groupThreadActivity'
import { getRandomThinkingMessage } from '../utils/thinkingMessages'
@@ -24,14 +26,14 @@ import { type ThreadSkin, ThreadSkinContext } from './quill/quillThreadContext'
import { RunAlertActivity } from './RunAlertActivity'
import { RunContext } from './RunContext'
import { ThreadActivityGroup } from './ThreadActivityGroup'
-import { ThreadRow } from './ThreadRow'
+import { ThreadRow, type ThreadRowProps } from './ThreadRow'
import { lookupToolRenderer } from './tool/toolRegistry'
import { TurnReveal } from './TurnReveal'
import { VirtualizedThread } from './VirtualizedThread'
/** Stable row key — defined at module scope so `getItemKey` never changes identity across renders. */
-function getThreadItemKey(item: ThreadDisplayItem): string {
- return item.id
+function getThreadRowKey(row: ThreadViewRow): string {
+ return row.item.id
}
/**
@@ -72,7 +74,7 @@ function quillRowShowsProgress(item: ThreadDisplayItem, toolInvocations: Readonl
}
}
-function estimateThreadItemHeight(item: ThreadDisplayItem): number {
+function estimateThreadRowHeight({ item }: ThreadViewRow): number {
if (item.type === 'activity_group') {
return 48
}
@@ -151,23 +153,30 @@ export function ThreadView({
// A replayed error from an earlier run in the chain is not this run's ending while a newer run is
// still going, so it keeps the softer title.
const runEnded = isTerminalRunStatus(currentRunStatus)
- const displayItems = useMemo(() => {
- const pinnedToolIds = new Set<string>()
- const widgetToolIds = new Set<string>()
+ const { pinnedToolIds, widgetToolIds } = useMemo(() => {
+ const pinned = new Set<string>()
+ const widgets = new Set<string>()
for (const [id, invocation] of toolInvocations) {
const resolved = resolveToolCall(invocation)
const entry = lookupToolRenderer(resolved.resolvedKey, !!resolved.innerToolName)
if (entry.pinned) {
- pinnedToolIds.add(id)
+ pinned.add(id)
} else if (entry.keepVisible) {
- widgetToolIds.add(id)
+ widgets.add(id)
}
}
- if (skin === 'quill') {
- return groupToolRuns(threadItems, toolInvocations, { pinnedToolIds, widgetToolIds, settled: !isThinking })
- }
- return groupThreadActivity(threadItems, new Set([...pinnedToolIds, ...widgetToolIds]))
- }, [threadItems, toolInvocations, skin, isThinking])
+ return { pinnedToolIds: pinned, widgetToolIds: widgets }
+ }, [toolInvocations])
+ const previousDisplayItems = useRef<ThreadDisplayItem[]>([])
+ const displayItems = useMemo(() => {
+ const grouped =
+ skin === 'quill'
+ ? groupToolRuns(threadItems, toolInvocations, { pinnedToolIds, widgetToolIds, settled: !isThinking })
+ : groupThreadActivity(threadItems, new Set([...pinnedToolIds, ...widgetToolIds]))
+ const reconciled = reuseActivityGroups(previousDisplayItems.current, grouped)
+ previousDisplayItems.current = reconciled
+ return reconciled
+ }, [threadItems, toolInvocations, pinnedToolIds, widgetToolIds, skin, isThinking])
// The last human message anchors the thread. Reopening a saved conversation lands on it — the last
// meaningful turn, response below — when at least a viewport of content follows it (otherwise the
// bottom); a fresh send (a new key) pins the thread to the bottom to follow the streaming response.
@@ -176,11 +185,21 @@ export function ThreadView({
[threadItems]
)
// Only computed when a trailer renderer is supplied — bare ThreadViews pay nothing.
- const trailers = useMemo(
- () => (renderTurnTrailer ? computeTurnTrailers(threadItems) : null),
- [threadItems, renderTurnTrailer]
- )
+ const previousTrailers = useRef<Map<string, TurnTrailer> | null>(null)
+ const trailers = useMemo(() => {
+ const next = renderTurnTrailer
+ ? reuseTurnTrailers(previousTrailers.current, computeTurnTrailers(threadItems))
+ : null
+ previousTrailers.current = next
+ return next
+ }, [threadItems, renderTurnTrailer])
const revealGroups = useMemo(() => mapRowsToRevealGroup(displayItems), [displayItems])
+ const previousRows = useRef<ThreadViewRow[]>([])
+ const rows = useMemo(() => {
+ const next = buildThreadViewRows(previousRows.current, displayItems, toolInvocations, trailers, revealGroups)
+ previousRows.current = next
+ return next
+ }, [displayItems, toolInvocations, trailers, revealGroups])
const [turnHoverStore] = useState(() => new TurnHoverStore())
// Header/footer are kept as memoized leaf components with stable element identity so they don't rebuild
@@ -240,71 +259,55 @@ export function ThreadView({
)
const renderItem = useCallback(
- (item: ThreadDisplayItem, index: number): JSX.Element => {
+ ({ item, isLast, turnId, invocation, groupInvocations, trailer }: ThreadViewRow): JSX.Element => {
if (item.type === 'activity_group') {
- const isLast = index === displayItems.length - 1
return (
- <VirtualizedThread.Row className={rowClassName}>
- <TurnReveal store={turnHoverStore} turnId={revealGroups.get(item.id)}>
- <ThreadActivityGroup
- group={item}
- toolInvocations={toolInvocations}
- active={isLast && isThinking}
- waitingForInput={isLast && !!pendingPermissionRequest}
- cancelled={isLast && (turnCancelled || currentRunStatus === 'failed')}
- renderItem={(activity) => (
- <ThreadRow
- item={activity}
- isLast={false}
- isThinking={false}
- toolInvocations={toolInvocations}
- turnComplete={turnComplete}
- turnCancelled={turnCancelled}
- />
- )}
- />
- </TurnReveal>
- </VirtualizedThread.Row>
+ <ActivityGroupRow
+ group={item}
+ rowClassName={rowClassName}
+ turnHoverStore={turnHoverStore}
+ turnId={turnId}
+ toolInvocations={groupInvocations ?? EMPTY_INVOCATIONS}
+ active={isLast && isThinking}
+ waitingForInput={isLast && !!pendingPermissionRequest}
+ cancelled={isLast && (turnCancelled || currentRunStatus === 'failed')}
+ turnComplete={turnComplete}
+ turnCancelled={turnCancelled}
+ />
)
}
if (item.type === 'turn_separator' && renderTurnTrailer) {
- const trailer = trailers?.get(item.id)
return (
- <VirtualizedThread.Row className={rowClassName}>
- {trailer ? (
- <TurnReveal store={turnHoverStore} turnId={item.id}>
- {renderTurnTrailer(trailer)}
- </TurnReveal>
- ) : null}
- </VirtualizedThread.Row>
+ <TurnTrailerRow
+ turnId={item.id}
+ trailer={trailer}
+ renderTurnTrailer={renderTurnTrailer}
+ rowClassName={rowClassName}
+ turnHoverStore={turnHoverStore}
+ />
)
}
return (
- <VirtualizedThread.Row className={rowClassName}>
- <TurnReveal store={turnHoverStore} turnId={revealGroups.get(item.id)}>
- <ThreadRow
- item={item}
- isLast={index === displayItems.length - 1}
- isThinking={isThinking}
- toolInvocations={toolInvocations}
- turnComplete={turnComplete}
- turnCancelled={turnCancelled}
- runEnded={runEnded}
- />
- </TurnReveal>
- </VirtualizedThread.Row>
+ <ItemRow
+ item={item}
+ rowClassName={rowClassName}
+ turnHoverStore={turnHoverStore}
+ turnId={turnId}
+ isLast={isLast}
+ isThinking={isThinking}
+ invocation={invocation}
+ turnComplete={turnComplete}
+ turnCancelled={turnCancelled}
+ runEnded={runEnded}
+ />
)
},
[
- displayItems.length,
isThinking,
- toolInvocations,
turnComplete,
turnCancelled,
rowClassName,
renderTurnTrailer,
- trailers,
- revealGroups,
turnHoverStore,
pendingPermissionRequest,
currentRunStatus,
@@ -316,9 +319,9 @@ export function ThreadView({
<VirtualizedThread.Root
key={scrollRestorationKey}
scrollRestorationKey={scrollRestorationKey}
- items={displayItems}
- getItemKey={getThreadItemKey}
- estimateItemHeight={estimateThreadItemHeight}
+ items={rows}
+ getItemKey={getThreadRowKey}
+ estimateItemHeight={estimateThreadRowHeight}
anchorItemKey={anchorItemKey}
// The history replay folds in over several commits (debug rows land before the human turns);
// the opening scroll must wait for the full log or it opens at the bottom of a partial thread.
@@ -355,6 +358,192 @@ export function ThreadView({
)
}
+function reuseTurnTrailers(
+ previous: Map<string, TurnTrailer> | null,
+ next: Map<string, TurnTrailer>
+): Map<string, TurnTrailer> {
+ if (!previous) {
+ return next
+ }
+ for (const [id, trailer] of next) {
+ const old = previous.get(id)
+ if (
+ old &&
+ old.turnIndex === trailer.turnIndex &&
+ old.isLastTurn === trailer.isLastTurn &&
+ old.turnText === trailer.turnText &&
+ old.traceId === trailer.traceId &&
+ old.timestamp === trailer.timestamp
+ ) {
+ next.set(id, old)
+ }
+ }
+ return next
+}
+
+const EMPTY_INVOCATIONS: Map<string, ToolInvocation> = new Map()
+
+interface ThreadViewRow {
+ item: ThreadDisplayItem
+ isLast: boolean
+ turnId?: string
+ invocation?: ToolInvocation
+ groupInvocations?: Map<string, ToolInvocation>
+ trailer?: TurnTrailer
+}
+
+function sameInvocations(a: Map<string, ToolInvocation> | undefined, b: Map<string, ToolInvocation>): boolean {
+ if (!a || a.size !== b.size) {
+ return false
+ }
+ for (const [id, invocation] of b) {
+ if (a.get(id) !== invocation) {
+ return false
+ }
+ }
+ return true
+}
+
+function buildThreadViewRows(
+ previous: ThreadViewRow[],
+ displayItems: ThreadDisplayItem[],
+ toolInvocations: Map<string, ToolInvocation>,
+ trailers: Map<string, TurnTrailer> | null,
+ revealGroups: Map<string, string>
+): ThreadViewRow[] {
+ const previousById = new Map<string, ThreadViewRow>()
+ for (const row of previous) {
+ previousById.set(row.item.id, row)
+ }
+ return displayItems.map((item, index) => {
+ const old = previousById.get(item.id)
+ let groupInvocations: Map<string, ToolInvocation> | undefined
+ if (item.type === 'activity_group') {
+ groupInvocations = new Map()
+ for (const activity of item.items) {
+ const call = activity.toolCallId ? toolInvocations.get(activity.toolCallId) : undefined
+ if (call) {
+ groupInvocations.set(activity.toolCallId!, call)
+ }
+ }
+ if (sameInvocations(old?.groupInvocations, groupInvocations)) {
+ groupInvocations = old!.groupInvocations
+ }
+ }
+ const row: ThreadViewRow = {
+ item,
+ isLast: index === displayItems.length - 1,
+ turnId: revealGroups.get(item.id),
+ invocation:
+ item.type !== 'activity_group' && item.toolCallId ? toolInvocations.get(item.toolCallId) : undefined,
+ groupInvocations,
+ trailer: trailers?.get(item.id),
+ }
+ return old &&
+ old.item === row.item &&
+ old.isLast === row.isLast &&
+ old.turnId === row.turnId &&
+ old.invocation === row.invocation &&
+ old.groupInvocations === row.groupInvocations &&
+ old.trailer === row.trailer
+ ? old
+ : row
+ })
+}
+
+interface RowShellProps {
+ rowClassName?: string
+ turnHoverStore: TurnHoverStore
+}
+
+const ActivityGroupRow = memo(function ActivityGroupRow({
+ group,
+ rowClassName,
+ turnHoverStore,
+ turnId,
+ toolInvocations,
+ active,
+ waitingForInput,
+ cancelled,
+ turnComplete,
+ turnCancelled,
+}: RowShellProps & {
+ group: ThreadActivityGroupItem
+ turnId: string | undefined
+ toolInvocations: Map<string, ToolInvocation>
+ active: boolean
+ waitingForInput: boolean
+ cancelled: boolean
+ turnComplete: boolean
+ turnCancelled: boolean
+}): JSX.Element {
+ const renderGroupItem = useCallback(
+ (activity: ThreadItem): JSX.Element => (
+ <ThreadRow
+ item={activity}
+ isLast={false}
+ isThinking={false}
+ invocation={activity.toolCallId ? toolInvocations.get(activity.toolCallId) : undefined}
+ turnComplete={turnComplete}
+ turnCancelled={turnCancelled}
+ />
+ ),
+ [toolInvocations, turnComplete, turnCancelled]
+ )
+ return (
+ <VirtualizedThread.Row className={rowClassName}>
+ <TurnReveal store={turnHoverStore} turnId={turnId}>
+ <ThreadActivityGroup
+ group={group}
+ toolInvocations={toolInvocations}
+ active={active}
+ waitingForInput={waitingForInput}
+ cancelled={cancelled}
+ renderItem={renderGroupItem}
+ />
+ </TurnReveal>
+ </VirtualizedThread.Row>
+ )
+})
+
+const TurnTrailerRow = memo(function TurnTrailerRow({
+ turnId,
+ trailer,
+ renderTurnTrailer,
+ rowClassName,
+ turnHoverStore,
+}: RowShellProps & {
+ turnId: string
+ trailer: TurnTrailer | undefined
+ renderTurnTrailer: (trailer: TurnTrailer) => JSX.Element | null
+}): JSX.Element {
+ return (
+ <VirtualizedThread.Row className={rowClassName}>
+ {trailer ? (
+ <TurnReveal store={turnHoverStore} turnId={turnId}>
+ {renderTurnTrailer(trailer)}
+ </TurnReveal>
+ ) : null}
+ </VirtualizedThread.Row>
+ )
+})
+
+const ItemRow = memo(function ItemRow({
+ item,
+ rowClassName,
+ turnHoverStore,
+ turnId,
+ ...rowProps
+}: RowShellProps & Omit<ThreadRowProps, 'item'> & { item: ThreadItem; turnId: string | undefined }): JSX.Element {
+ return (
+ <VirtualizedThread.Row className={rowClassName}>
+ <TurnReveal store={turnHoverStore} turnId={turnId}>
+ <ThreadRow item={item} {...rowProps} />
+ </TurnReveal>
+ </VirtualizedThread.Row>
+ )
+})
+
/** Leading run-context row. Memoized so it only re-renders when the run's branch/repo refs change. */
const ThreadHeader = memo(function ThreadHeader({
branch,
diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
index 8897af7ccbcf..58610d9e894d 100644
--- a/products/posthog_ai/frontend/components/VirtualizedThread.tsx
+++ b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
@@ -133,6 +133,23 @@ const InternalRow = memo(function InternalRow({
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 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). */
@@ -896,17 +913,18 @@ function Root<T>({
}
}, [virtualized, stickToBottom, noteProgrammaticScroll])
+ const lastIndex = virtualized ? rowCount - 1 : -1
const rootValue = useMemo<RootContextValue>(
() => ({
measureElement: virtualizer.measureElement,
gap,
- lastIndex: rowCount - 1,
+ lastIndex,
maxWidthClassName,
virtualized,
isFollowing: stickToBottom && (!virtualized || pinned),
pauseFollowing: () => setPinned(false),
}),
- [virtualizer, gap, rowCount, maxWidthClassName, virtualized, stickToBottom, pinned, setPinned]
+ [virtualizer, gap, lastIndex, maxWidthClassName, virtualized, stickToBottom, pinned, setPinned]
)
// Flow mode: render rows directly so an ancestor scroll container (and its auto-scroller) keeps working.
@@ -916,19 +934,17 @@ function Root<T>({
return (
<RootContext.Provider value={rootValue}>
{hasHeader && (
- <RowContext.Provider key="header" value={{ index: 0 }}>
+ <FlowRow key="header" index={0}>
{header}
- </RowContext.Provider>
+ </FlowRow>
)}
{items.map((item, index) => (
- <RowContext.Provider key={getItemKey(item, index)} value={{ index }}>
- {children(item, index)}
- </RowContext.Provider>
+ <FlowItemRow key={getItemKey(item, index)} index={index} item={item} render={children} />
))}
{hasFooter && (
- <RowContext.Provider key="footer" value={{ index: rowCount - 1 }}>
+ <FlowRow key="footer" index={rowCount - 1}>
{footer}
- </RowContext.Provider>
+ </FlowRow>
)}
</RootContext.Provider>
)
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index e81bae4282d6..d951a4835ea1 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -28,7 +28,11 @@ import { resolveToolCall } from '../utils/toolResolver'
import { computeTurnTrailers } from '../utils/turnTrailers'
import { attachedContextLogic } from './attachedContextLogic'
import {
+ appendToRunLog,
+ emptyRunLog,
extractRunArtifacts,
+ type FoldCheckpoint,
+ foldLogFromCheckpoint,
foldLogToThread,
mapHttpStatusToStreamError,
MAX_CUMULATIVE_RECONNECT_ATTEMPTS,
@@ -277,6 +281,45 @@ describe('runStreamLogic', () => {
expect(result.threadItems.find((item) => item.id === 'missing-start')?.startedAt).toBeUndefined()
})
+ it('folds the same thread when it resumes from the last completed turn', () => {
+ const frames: [StoredLogEntry, 'live' | 'replay'][] = [
+ [notification('_posthog/run_started', {}), 'replay'],
+ [notification('_posthog/user_message', { content: 'first question' }), 'replay'],
+ [sessionUpdate({ sessionUpdate: 'tool_call', toolCallId: 'slow', status: 'in_progress' }), 'replay'],
+ [sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'slow', title: 'Reading' }), 'replay'],
+ [sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'first answer' } }), 'replay'],
+ [notification('_client/human_message', { content: 'queued follow-up' }), 'live'],
+ [notification('_posthog/turn_complete', { traceId: 'trace-1' }), 'live'],
+ [notification('_posthog/user_message', { content: 'queued follow-up' }), 'live'],
+ [sessionUpdate({ sessionUpdate: 'user_message_chunk', content: { text: 'queued follow-up' } }), 'live'],
+ [sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'slow', status: 'completed' }), 'live'],
+ [sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'second ' } }), 'live'],
+ [notification('_posthog/console', { level: 'debug', message: 'tick' }), 'live'],
+ [sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'answer' } }), 'live'],
+ [notification('_posthog/turn_complete', { traceId: 'trace-2' }), 'live'],
+ [notification('_client/human_message', { content: 'third question' }), 'live'],
+ [sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'slow', rawOutput: 'late' }), 'live'],
+ [sessionUpdate({ sessionUpdate: 'tool_call', toolCallId: 'fast', status: 'in_progress' }), 'live'],
+ [sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'third' } }), 'live'],
+ [sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'slow', status: 'failed' }), 'live'],
+ [sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'fast', status: 'completed' }), 'live'],
+ [sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'third answer' } }), 'live'],
+ ]
+ const options = { isResumeRun: false, taskId: 'task-1' }
+
+ let log = emptyRunLog()
+ let checkpoint: FoldCheckpoint | null = null
+ frames.forEach(([entry, source], index) => {
+ log = appendToRunLog(log, [
+ { source, entry: { ...entry, timestamp: new Date((index + 1) * 1000).toISOString() } },
+ ])
+ const resumed = foldLogFromCheckpoint(log.entries, options, checkpoint)
+ checkpoint = resumed.checkpoint
+ expect(resumed.folded).toEqual(foldLogToThread(log.entries, options))
+ })
+ expect(checkpoint!.entries.at(-1)?.entry.notification.params).toEqual({ traceId: 'trace-2' })
+ })
+
it.each([
{
label: 'a debug row stays whole',
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index ede76c0a28da..b0dc1dd0c561 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -73,6 +73,7 @@ import {
parseAvailableCommands,
} from '../types/wireTypes'
import { extractContextBlockLines } from '../utils/posthogContextBlock'
+import { reconcileThreadItems, reconcileToolInvocations } from '../utils/reconcileFoldedThread'
import { extractAgentToolName, getClaudeCodeMeta, resolveToolCall } from '../utils/toolResolver'
import { computeTurnTrailers } from '../utils/turnTrailers'
import { attachedContextLogic } from './attachedContextLogic'
@@ -653,11 +654,12 @@ export function extractDenialReason(meta: unknown): string | undefined {
* assistant-message and agent-thought streams, which both buffer incremental chunks this way.
*/
function findLastBufferIndex(state: ThreadItem[], id: string, type: ThreadItemType, incompleteOnly: boolean): number {
+ const prefix = `${id}@`
for (let i = state.length - 1; i >= 0; i--) {
const item = state[i]
if (
item.type === type &&
- (item.id === id || item.id.startsWith(`${id}@`)) &&
+ (item.id === id || item.id.startsWith(prefix)) &&
(!incompleteOnly || !item.complete)
) {
return i
@@ -673,13 +675,23 @@ function findLastBufferIndex(state: ThreadItem[], id: string, type: ThreadItemTy
* send the agent has not taken up yet sinks below the whole answer before it renders, so it splits
* the halves the same way and is passed over too.
*/
-function onlyDebugRowsFollow(state: ThreadItem[], idx: number, waitingIds: ReadonlySet<string>): boolean {
- for (let i = idx + 1; i < state.length; i++) {
- if (state[i].type !== 'debug' && !waitingIds.has(state[i].id)) {
- return false
+function findContinuableBuffer(
+ state: ThreadItem[],
+ id: string,
+ type: ThreadItemType,
+ waitingIds: ReadonlySet<string>
+): number {
+ const prefix = `${id}@`
+ for (let i = state.length - 1; i >= 0; i--) {
+ const item = state[i]
+ if (item.type === type && (item.id === id || item.id.startsWith(prefix))) {
+ return item.complete ? -1 : i
+ }
+ if (item.type !== 'debug' && !waitingIds.has(item.id)) {
+ return -1
}
}
- return true
+ return -1
}
// The agent takes a queued or steering send up at the next turn boundary, so a placeholder that
@@ -1486,6 +1498,73 @@ function readPendingRunMessage(state: unknown, runId: string): PendingRunMessage
: null
}
+const NO_IDS: ReadonlySet<string> = new Set()
+
+export interface FoldOptions {
+ isResumeRun: boolean
+ pendingMessage?: PendingRunMessage | null
+ taskId?: string | null
+}
+
+export interface FoldCheckpoint {
+ entries: StoredEntry[]
+ options: FoldOptions
+ items: ThreadItem[]
+ invocations: Map<string, ToolInvocation>
+ rememberedHumanTexts: Map<string, number>
+ waitingSends: { id: string; text: string; turns: number }[]
+ pairedSends: Map<string, number>
+ toolItemIds: Set<string>
+ counters: {
+ humanCount: number
+ bubbleSeq: number
+ separatorSeq: number
+ errorSeq: number
+ statusSeq: number
+ compactSeq: number
+ clearedSeq: number
+ taskSeq: number
+ consoleSeq: number
+ contextSeq: number
+ openAssistantMessages: number
+ }
+ importedRun: boolean
+ pendingMessageSeen: boolean
+ pendingInsertionIndex: number | undefined
+ bufferedAttachments: ThreadAttachment[]
+}
+
+function sameFoldOptions(a: FoldOptions, b: FoldOptions): boolean {
+ return (
+ a.isResumeRun === b.isResumeRun &&
+ (a.taskId ?? null) === (b.taskId ?? null) &&
+ (a.pendingMessage?.runId ?? null) === (b.pendingMessage?.runId ?? null) &&
+ (a.pendingMessage?.id ?? null) === (b.pendingMessage?.id ?? null) &&
+ (a.pendingMessage?.text ?? null) === (b.pendingMessage?.text ?? null)
+ )
+}
+
+function canResumeFold(checkpoint: FoldCheckpoint, entries: StoredEntry[], options: FoldOptions): boolean {
+ if (checkpoint.entries.length > entries.length || !sameFoldOptions(checkpoint.options, options)) {
+ return false
+ }
+ for (let index = 0; index < checkpoint.entries.length; index++) {
+ if (checkpoint.entries[index] !== entries[index]) {
+ return false
+ }
+ }
+ return true
+}
+
+function lastTurnCompleteIndex(entries: StoredEntry[]): number {
+ for (let index = entries.length - 1; index >= 0; index--) {
+ if (entries[index].entry.notification?.method === '_posthog/turn_complete') {
+ return index
+ }
+ }
+ return -1
+}
+
/**
* Pure projection: fold the ordered log into the rendered thread (and the tool-invocation map the
* renderer looks up). The fold rules (chunk buffering with the tail rule, tool-update merge,
@@ -1493,39 +1572,49 @@ function readPendingRunMessage(state: unknown, runId: string): PendingRunMessage
* across re-folds. `isResumeRun` drives the §6 resume-context filter; per-entry `source` decides
* whether a wire user turn renders (replay) or is left to the live echo (live).
*/
-export function foldLogToThread(
+export function foldLogToThread(entries: StoredEntry[], options: FoldOptions): FoldedThread {
+ return foldLogFromCheckpoint(entries, options, null).folded
+}
+
+export function foldLogFromCheckpoint(
entries: StoredEntry[],
- options: { isResumeRun: boolean; pendingMessage?: PendingRunMessage | null; taskId?: string | null }
-): FoldedThread {
- let items: ThreadItem[] = []
- const invocations = new Map<string, ToolInvocation>()
+ options: FoldOptions,
+ checkpoint: FoldCheckpoint | null
+): { folded: FoldedThread; checkpoint: FoldCheckpoint | null } {
+ const resume = checkpoint && canResumeFold(checkpoint, entries, options) ? checkpoint : null
+ const checkpointIndex = lastTurnCompleteIndex(entries)
+ let nextCheckpoint = resume && resume.entries.length - 1 === checkpointIndex ? resume : null
+ let items: ThreadItem[] = resume ? [...resume.items] : []
+ const invocations = new Map<string, ToolInvocation>(resume?.invocations)
// Texts already rendered by a `_posthog/user_message`, so a later identical `user_message_chunk`
// (resume chains persist the same turn in both forms) is consumed once rather than doubled.
- const rememberedHumanTexts = new Map<string, number>()
+ const rememberedHumanTexts = new Map<string, number>(resume?.rememberedHumanTexts)
// Placeholders the composer drew for sends the agent has not taken up, in send order. A queued or
// steering send is echoed only when the agent takes it up, which is a turn later than the bubble,
// so the pairing outlives that turn. Text is what an echo matches on, because a client echo
// carries no id, and send order keeps repeated sends of one text apart.
- const waitingSends: { id: string; text: string; turns: number }[] = []
+ const waitingSends: { id: string; text: string; turns: number }[] = resume
+ ? resume.waitingSends.map((send) => ({ ...send }))
+ : []
// Sends this turn already paired, counted per text so the same send's second wire form takes no
// further placeholder while a second send of that text still takes its own.
- const pairedSends = new Map<string, number>()
- let humanCount = 0
- let bubbleSeq = 0
- let separatorSeq = 0
- let errorSeq = 0
- let statusSeq = 0
- let compactSeq = 0
- let clearedSeq = 0
- let taskSeq = 0
- let consoleSeq = 0
- let contextSeq = 0
+ const pairedSends = new Map<string, number>(resume?.pairedSends)
+ let humanCount = resume?.counters.humanCount ?? 0
+ let bubbleSeq = resume?.counters.bubbleSeq ?? 0
+ let separatorSeq = resume?.counters.separatorSeq ?? 0
+ let errorSeq = resume?.counters.errorSeq ?? 0
+ let statusSeq = resume?.counters.statusSeq ?? 0
+ let compactSeq = resume?.counters.compactSeq ?? 0
+ let clearedSeq = resume?.counters.clearedSeq ?? 0
+ let taskSeq = resume?.counters.taskSeq ?? 0
+ let consoleSeq = resume?.counters.consoleSeq ?? 0
+ let contextSeq = resume?.counters.contextSeq ?? 0
let timestamp: number | undefined
- let importedRun = false
+ let importedRun = resume?.importedRun ?? false
let entryRunId: string | undefined
- let pendingMessageSeen = false
- let pendingInsertionIndex: number | undefined
- let bufferedAttachments: ThreadAttachment[] = []
+ let pendingMessageSeen = resume?.pendingMessageSeen ?? false
+ let pendingInsertionIndex: number | undefined = resume?.pendingInsertionIndex
+ let bufferedAttachments: ThreadAttachment[] = resume ? [...resume.bufferedAttachments] : []
/**
* A wire turn opens with its message, so that is where a message goes by default. A send the
@@ -1590,9 +1679,39 @@ export function foldLogToThread(
const waitingSendIds = (): ReadonlySet<string> =>
new Set(waitingSends.filter((send) => send.turns < SETTLED_AFTER_TURNS).map((send) => send.id))
+ const toolItemIds = new Set<string>(resume?.toolItemIds)
+ let openAssistantMessages = resume?.counters.openAssistantMessages ?? 0
+
+ const takeCheckpoint = (index: number): FoldCheckpoint => ({
+ entries: entries.slice(0, index + 1),
+ options,
+ items: [...items],
+ invocations: new Map(invocations),
+ rememberedHumanTexts: new Map(rememberedHumanTexts),
+ waitingSends: waitingSends.map((send) => ({ ...send })),
+ pairedSends: new Map(pairedSends),
+ toolItemIds: new Set(toolItemIds),
+ counters: {
+ humanCount,
+ bubbleSeq,
+ separatorSeq,
+ errorSeq,
+ statusSeq,
+ compactSeq,
+ clearedSeq,
+ taskSeq,
+ consoleSeq,
+ contextSeq,
+ openAssistantMessages,
+ },
+ importedRun,
+ pendingMessageSeen,
+ pendingInsertionIndex,
+ bufferedAttachments: [...bufferedAttachments],
+ })
const appendChunk = (id: string, type: ThreadItemType, delta: string): void => {
- const idx = findLastBufferIndex(items, id, type, false)
+ const idx = findContinuableBuffer(items, id, type, waitingSends.length > 0 ? waitingSendIds() : NO_IDS)
// Continue the matched buffer only while it's incomplete and only debug rows followed it;
// otherwise (no buffer, a finalized one, or one interrupted by a tool call/separator) start
// a fresh bubble so text resuming after an interruption renders in chronological order.
@@ -1600,7 +1719,10 @@ export function foldLogToThread(
// the S3 replay always does, since the backend drops chunks), so the bare fallback id would
// collide as a React key across messages. The continuation lookup matches the `${id}@`
// prefix, so it still works.
- if (idx === -1 || items[idx].complete || !onlyDebugRowsFollow(items, idx, waitingSendIds())) {
+ if (idx === -1) {
+ if (type === 'assistant_message') {
+ openAssistantMessages++
+ }
items.push({
id: `${id}@${bubbleSeq++}`,
type,
@@ -1618,8 +1740,8 @@ export function foldLogToThread(
}
const finalizeMessage = (id: string, text: string): void => {
- let idx = findLastBufferIndex(items, id, 'assistant_message', true)
- if (idx === -1) {
+ let idx = openAssistantMessages > 0 ? findLastBufferIndex(items, id, 'assistant_message', true) : -1
+ if (idx === -1 && openAssistantMessages > 0) {
// The wire isn't consistent about carrying `messageId` across a message's chunks and its
// closing `agent_message` (the chunks often have one, the finalize doesn't, or vice
// versa), so an id-keyed lookup can miss the buffer the chunks opened. Fall back to the
@@ -1649,11 +1771,13 @@ export function foldLogToThread(
})
return
}
+ openAssistantMessages--
items[idx] = { ...items[idx], text, complete: true, ...(timestamp !== undefined && { endedAt: timestamp }) }
}
const upsertInvocationItem = (toolCallId: string, hasStart = true): void => {
- if (!items.some((item) => item.type === 'tool_invocation' && item.toolCallId === toolCallId)) {
+ if (!toolItemIds.has(toolCallId)) {
+ toolItemIds.add(toolCallId)
items.push({
id: toolCallId,
type: 'tool_invocation',
@@ -1752,8 +1876,12 @@ export function foldLogToThread(
if (!existing && !subagentParentToolCallId(update._meta)) {
upsertInvocationItem(next.toolCallId, false)
}
- if (timestamp !== undefined && (next.status === 'completed' || next.status === 'failed')) {
- const index = items.findIndex((item) => item.toolCallId === next.toolCallId)
+ if (
+ timestamp !== undefined &&
+ (next.status === 'completed' || next.status === 'failed') &&
+ toolItemIds.has(next.toolCallId)
+ ) {
+ const index = items.findLastIndex((item) => item.toolCallId === next.toolCallId)
if (index !== -1) {
items[index] = { ...items[index], endedAt: timestamp }
}
@@ -1789,7 +1917,8 @@ export function foldLogToThread(
...(sourceRunId ? { sourceRunId } : {}),
})
}
- for (const { entry, source } of entries) {
+ for (let index = resume ? resume.entries.length : 0; index < entries.length; index++) {
+ const { entry, source } = entries[index]
entryRunId = entry.source_run_id ?? options.pendingMessage?.runId
if (
options.pendingMessage &&
@@ -1841,6 +1970,9 @@ export function foldLogToThread(
})
pairedSends.clear()
waitingSends.forEach((send) => (send.turns += 1))
+ if (index === checkpointIndex) {
+ nextCheckpoint = takeCheckpoint(index)
+ }
continue
}
if (method === '_posthog/progress') {
@@ -2080,7 +2212,7 @@ export function foldLogToThread(
complete: true,
})
}
- return { threadItems: items, toolInvocations: invocations }
+ return { folded: { threadItems: items, toolInvocations: invocations }, checkpoint: nextCheckpoint }
}
/**
@@ -3111,7 +3243,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
},
],
}),
- selectors({
+ selectors(({ cache }) => ({
respondingToPermission: [
(s) => [s.permissionResponseRequestIds, s.pendingPermissionRequest],
(ids: Set<string>, record: PermissionRequestRecord | null): boolean =>
@@ -3128,7 +3260,29 @@ export const runStreamLogic = kea<runStreamLogicType>([
isResumeRun: boolean,
pendingMessage: PendingRunMessage | null,
taskId: string | null
- ): FoldedThread => foldLogToThread(log.entries, { isResumeRun, pendingMessage, taskId }),
+ ): FoldedThread => {
+ const previousCheckpoint: FoldCheckpoint | null = cache.foldCheckpoint ?? null
+ const { folded, checkpoint } = foldLogFromCheckpoint(
+ log.entries,
+ { isResumeRun, pendingMessage, taskId },
+ previousCheckpoint
+ )
+ const previous: FoldedThread | undefined = cache.previousFoldedThread
+ const reconciled: FoldedThread = {
+ threadItems: reconcileThreadItems(previous?.threadItems, folded.threadItems),
+ toolInvocations: reconcileToolInvocations(previous?.toolInvocations, folded.toolInvocations),
+ }
+ if (checkpoint && checkpoint !== previousCheckpoint) {
+ checkpoint.items = reconcileThreadItems(reconciled.threadItems, checkpoint.items)
+ checkpoint.invocations = reconcileToolInvocations(
+ reconciled.toolInvocations,
+ checkpoint.invocations
+ )
+ }
+ cache.foldCheckpoint = checkpoint
+ cache.previousFoldedThread = reconciled
+ return reconciled
+ },
],
errorTraceIds: [
(s) => [s.threadItems],
@@ -3354,7 +3508,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
return null
},
],
- }),
+ })),
listeners(({ values, actions, cache, props }) => {
const sessionNow = (): RunStreamRecovery | undefined => cache.recoverySession
const endedKey = (projectId: number, taskId: string, runId: string): string => `${projectId}:${taskId}:${runId}`
diff --git a/products/posthog_ai/frontend/utils/groupThreadActivity.ts b/products/posthog_ai/frontend/utils/groupThreadActivity.ts
index 5fe207f2e3bd..a57fe016ed22 100644
--- a/products/posthog_ai/frontend/utils/groupThreadActivity.ts
+++ b/products/posthog_ai/frontend/utils/groupThreadActivity.ts
@@ -152,6 +152,31 @@ export function groupToolRuns(
return result
}
+export function reuseActivityGroups(previous: ThreadDisplayItem[], next: ThreadDisplayItem[]): ThreadDisplayItem[] {
+ const previousGroups = new Map<string, ThreadActivityGroup>()
+ for (const item of previous) {
+ if (item.type === 'activity_group') {
+ previousGroups.set(item.id, item)
+ }
+ }
+ if (previousGroups.size === 0) {
+ return next
+ }
+ return next.map((item) => {
+ if (item.type !== 'activity_group') {
+ return item
+ }
+ const old = previousGroups.get(item.id)
+ return old &&
+ old.startedAt === item.startedAt &&
+ old.endedAt === item.endedAt &&
+ old.items.length === item.items.length &&
+ old.items.every((row, index) => row === item.items[index])
+ ? old
+ : item
+ })
+}
+
/** Groups over 10 items show the first 2 and last 3; the middle opens with one click. */
export const ACTIVITY_WINDOW_LIMIT = 10
/** Identical consecutive calls fold into one row only from this many, and only in the hidden middle. */
diff --git a/products/posthog_ai/frontend/utils/reconcileFoldedThread.ts b/products/posthog_ai/frontend/utils/reconcileFoldedThread.ts
new file mode 100644
index 000000000000..5acbe6d86274
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/reconcileFoldedThread.ts
@@ -0,0 +1,92 @@
+import type { ThreadItem, ToolInvocation } from '../types/streamTypes'
+
+const MAX_COMPARE_DEPTH = 4
+
+function isPlainObject(value: object): value is Record<string, unknown> {
+ const proto = Object.getPrototypeOf(value)
+ return proto === Object.prototype || proto === null
+}
+
+function sameValue(a: unknown, b: unknown, depth: number): boolean {
+ if (a === b) {
+ return true
+ }
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {
+ return a !== a && b !== b
+ }
+ if (depth <= 0) {
+ return false
+ }
+ if (Array.isArray(a)) {
+ if (!Array.isArray(b) || a.length !== b.length) {
+ return false
+ }
+ for (let index = 0; index < a.length; index++) {
+ if (!sameValue(a[index], b[index], depth - 1)) {
+ return false
+ }
+ }
+ return true
+ }
+ if (Array.isArray(b) || !isPlainObject(a) || !isPlainObject(b)) {
+ return false
+ }
+ return sameRecord(a, b, depth)
+}
+
+function sameRecord(a: Record<string, unknown>, b: Record<string, unknown>, depth: number): boolean {
+ let keyCount = 0
+ for (const key in a) {
+ keyCount++
+ if (!(key in b) || !sameValue(a[key], b[key], depth - 1)) {
+ return false
+ }
+ }
+ for (const _key in b) {
+ keyCount--
+ }
+ return keyCount === 0
+}
+
+function reuse<T>(previous: T | undefined, next: T): T {
+ return previous !== undefined && sameValue(previous, next, MAX_COMPARE_DEPTH) ? previous : next
+}
+
+export function reconcileThreadItems(previous: ThreadItem[] | undefined, next: ThreadItem[]): ThreadItem[] {
+ if (!previous || previous.length === 0) {
+ return next
+ }
+ const previousById = new Map<string, ThreadItem>()
+ for (const item of previous) {
+ previousById.set(item.id, item)
+ }
+ let unchanged = previous.length === next.length
+ const result = next.map((item, index) => {
+ const kept = reuse(previousById.get(item.id), item)
+ if (unchanged && kept !== previous[index]) {
+ unchanged = false
+ }
+ return kept
+ })
+ return unchanged ? previous : result
+}
+
+export function reconcileToolInvocations(
+ previous: Map<string, ToolInvocation> | undefined,
+ next: Map<string, ToolInvocation>
+): Map<string, ToolInvocation> {
+ if (!previous || previous.size === 0) {
+ return next
+ }
+ let unchanged = previous.size === next.size
+ const result = new Map<string, ToolInvocation>()
+ for (const [id, invocation] of next) {
+ const previousInvocation = previous.get(id)
+ const kept = reuse(previousInvocation, invocation)
+ if (unchanged && kept !== previousInvocation) {
+ unchanged = false
+ }
+ result.set(id, kept)
+ }
+ return unchanged ? previous : result
+}