: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): collapse tool_call_update snapshots in run stream log (#67634)
Georgiy Tarasov6f71d20da62e
diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.mdindex 5d30b0c247c1..85b483ac2649 100644--- a/products/posthog_ai/frontend/AGENTS.md+++ b/products/posthog_ai/frontend/AGENTS.md@@ -111,7 +111,10 @@ The heart of the surface:- **SSE connection** — a `fetch` body reader pumped through `eventsource-parser`; a reconnect resumes afterthe last Redis stream id via `Last-Event-ID` (capped exponential backoff + cumulative cap).- **Ordered, append-only `log` is the single source of truth** — every wire frame (plus a few synthetic- client entries) is appended, never keyed or per-entry deduped.+ client entries) is appended, never keyed or per-entry deduped — with one exception: superseded+ `tool_call_update` frames are field-wise merged per `toolCallId` (`appendToRunLog`). Each update carries+ the full accumulated `rawOutput`/`content` snapshot, so retaining every one balloons memory by orders of+ magnitude while the fold only ever renders the merged latest.- **Pure projection** `foldLogToThread(entries) → { threadItems, toolInvocations }`, memoized on `log`identity, derives the rendered thread.- **Keyed by `streamKey`** so concurrent streams stay independent.diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex f9a018184009..1e4bd5f3e2b9 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -690,6 +690,91 @@ describe('runStreamLogic', () => {})})+ describe('tool_call_update collapse', () => {+ it('retains one merged update entry per tool call without losing early-update fields or duplicating content', async () => {+ // The agent re-sends the full accumulated output on every update — retaining each+ // snapshot in the log is the memory balloon this pins. A verbatim keep-latest would pass+ // the length check but drop the rawInput that arrived only on the first update.+ const frames: StoredLogEntry[] = [+ sessionUpdate({ sessionUpdate: 'tool_call', toolCallId: 't1', rawInput: {}, status: 'pending' }),+ sessionUpdate({+ sessionUpdate: 'tool_call_update',+ toolCallId: 't1',+ rawInput: { command: 'ls -la' },+ status: 'in_progress',+ }),+ sessionUpdate({+ sessionUpdate: 'tool_call_update',+ toolCallId: 't1',+ content: [{ type: 'text', text: 'chunk1' }],+ rawOutput: 'chunk1',+ }),+ sessionUpdate({+ sessionUpdate: 'tool_call_update',+ toolCallId: 't1',+ content: [+ { type: 'text', text: 'chunk1' },+ { type: 'text', text: 'chunk2' },+ ],+ rawOutput: 'chunk1chunk2',+ }),+ // Terminal status-only update: must not erase the accumulated content/output.+ sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'completed' }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ expect(logic.values.log.entries).toHaveLength(2)++ const invocation = logic.values.toolInvocations.get('t1')+ expect(invocation?.status).toEqual('completed')+ expect(invocation?.input).toEqual({ command: 'ls -la' })+ expect(invocation?.output).toEqual('chunk1chunk2')+ // Cumulative content replaces — appending would render chunk1 twice.+ expect(invocation?.contentBlocks).toEqual([+ { type: 'text', text: 'chunk1' },+ { type: 'text', text: 'chunk2' },+ ])+ })++ it('collapses interleaved updates of concurrent tool calls independently', async () => {+ // Dropping a superseded entry shifts later indexes — a stale toolUpdateIndex would merge+ // one tool call's update into another's entry.+ const frames: StoredLogEntry[] = [+ sessionUpdate({ sessionUpdate: 'tool_call', toolCallId: 'a', rawInput: {}, status: 'in_progress' }),+ sessionUpdate({ sessionUpdate: 'tool_call', toolCallId: 'b', rawInput: {}, status: 'in_progress' }),+ sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'a', rawOutput: 'a1' }),+ sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'b', rawOutput: 'b1' }),+ sessionUpdate({+ sessionUpdate: 'tool_call_update',+ toolCallId: 'a',+ rawOutput: 'a1a2',+ status: 'completed',+ }),+ sessionUpdate({+ sessionUpdate: 'tool_call_update',+ toolCallId: 'b',+ rawOutput: 'b1b2',+ status: 'failed',+ }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ expect(logic.values.log.entries).toHaveLength(4)+ expect(logic.values.toolInvocations.get('a')).toEqual(+ expect.objectContaining({ status: 'completed', output: 'a1a2' })+ )+ expect(logic.values.toolInvocations.get('b')).toEqual(+ expect.objectContaining({ status: 'failed', output: 'b1b2' })+ )+ })+ })+describe('pushHumanMessage', () => {it('appends a human_message item ordered before subsequently ingested assistant frames', async () => {await expectLogic(logic, () => {diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex 1b35d17bc7df..cc4c4eead961 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -642,16 +642,126 @@ export interface StoredEntry {}/**- * Ordered, append-only raw-frame log, in render order — the single source of truth. `threadItems`- * and `toolInvocations` are pure projections of it (see `foldLogToThread`). Frames are appended,+ * Ordered raw-frame log, in render order — the single source of truth. `threadItems` and+ * `toolInvocations` are pure projections of it (see `foldLogToThread`). Frames are appended,* never keyed or per-entry deduped: the only place two independently-identified sources overlap is* the bootstrap seam (the S3 history vs. the live SSE, which is connected *before* the history loads* so no frame is gapped), and that one overlap is reconciled once by `dedupeBufferedAgainstHistory`* before the live tail is appended. Steady-state live frames resume exactly after the last-seen* Redis id (exclusive), so they never re-deliver — a plain append therefore cannot double the thread.+ *+ * One principled exception to append-only: `tool_call_update` frames. The agent re-sends the full+ * accumulated `rawOutput`/`content` snapshot on every update (a long-running tool call can emit+ * thousands, each hundreds of KB), and neither the S3 log nor the live stream trims them — retaining+ * every superseded snapshot balloons renderer memory by orders of magnitude while the fold only ever+ * renders the merged latest. `appendToRunLog` therefore keeps a single field-wise-merged update entry+ * per `toolCallId` (see `mergeToolCallUpdateEntries`); `toolUpdateIndex` locates it in O(1).*/export interface RunLog {entries: StoredEntry[]+ /** Index into `entries` of the retained (merged) `tool_call_update` entry per toolCallId. */+ toolUpdateIndex: Record<string, number>+}++export function emptyRunLog(): RunLog {+ return { entries: [], toolUpdateIndex: {} }+}++/** The non-empty toolCallId of a `tool_call_update` frame, or null for every other frame. */+function toolCallUpdateKey(stored: StoredEntry): string | null {+ const notification = stored.entry.notification+ if (notification.method !== 'session/update') {+ return null+ }+ const update = notification.params?.update+ if (!isRecord(update) || update.sessionUpdate !== 'tool_call_update') {+ return null+ }+ return typeof update.toolCallId === 'string' && update.toolCallId ? update.toolCallId : null+}++/**+ * Field-wise merge of a superseded `tool_call_update` entry into its successor for the same tool+ * call — the log-level twin of `handleToolCallUpdate`'s fold precedence, so folding the one merged+ * entry yields the same invocation as folding both in sequence. Newer fields win when present;+ * absent fields fall back to the older update. Verbatim keep-latest would lose data: the wire sends+ * *partial* updates (e.g. `rawInput` streams in on an early update and the terminal update omits it).+ */+function mergeToolCallUpdateEntries(older: StoredEntry, newer: StoredEntry): StoredEntry {+ const olderNotification = older.entry.notification+ const newerNotification = newer.entry.notification+ const olderUpdateRaw = olderNotification.params?.update+ const newerUpdateRaw = newerNotification.params?.update+ const olderUpdate = isRecord(olderUpdateRaw) ? olderUpdateRaw : {}+ const newerUpdate = isRecord(newerUpdateRaw) ? newerUpdateRaw : {}++ const base = { ...olderUpdate }+ // `rawInput`/`input` are one logical field in the fold (`rawInput ?? input`) — a newer value for+ // either supersedes both, so a stale older `rawInput` can't shadow a newer `input`.+ if ((newerUpdate.rawInput && typeof newerUpdate.rawInput === 'object') || isRecord(newerUpdate.input)) {+ delete base.rawInput+ delete base.input+ }+ const mergedUpdate: Record<string, unknown> = { ...base, ...newerUpdate }+ // Content replaces only when the newer update actually carries blocks — the fold ignores an+ // empty list, so an explicitly-empty newer `content` must not erase the older blocks.+ const olderContent = Array.isArray(olderUpdate.content) ? olderUpdate.content : []+ const newerContent = Array.isArray(newerUpdate.content) ? newerUpdate.content : []+ if (olderContent.length > 0 && newerContent.length === 0) {+ mergedUpdate.content = olderContent+ }++ return {+ source: newer.source,+ entry: {+ ...newer.entry,+ notification: {+ ...newerNotification,+ // The fold reads the envelope-level error for failed updates — carry the older one+ // forward when the newer frame doesn't restate it.+ ...(newerNotification.error == null && olderNotification.error != null+ ? { error: olderNotification.error }+ : {}),+ params: { ...newerNotification.params, update: mergedUpdate },+ },+ },+ }+}++/**+ * Append frames to the log, collapsing superseded `tool_call_update` snapshots per toolCallId (see+ * the `RunLog` doc). The merged entry moves to the tail — where the latest update would sit — which+ * never reorders thread items: a tool card's position comes from its creating `tool_call` frame,+ * not from updates. Every ingest source (`live`, `replay`, `client`) funnels through here, so the+ * collapse covers both the live stream and the bootstrap history replay.+ */+export function appendToRunLog(state: RunLog, incoming: StoredEntry[]): RunLog {+ if (incoming.length === 0) {+ return state+ }+ const entries = [...state.entries]+ const toolUpdateIndex = { ...state.toolUpdateIndex }+ for (const stored of incoming) {+ const toolCallId = toolCallUpdateKey(stored)+ const priorIdx = toolCallId !== null ? toolUpdateIndex[toolCallId] : undefined+ if (toolCallId === null || priorIdx === undefined) {+ if (toolCallId !== null) {+ toolUpdateIndex[toolCallId] = entries.length+ }+ entries.push(stored)+ continue+ }+ const merged = mergeToolCallUpdateEntries(entries[priorIdx], stored)+ entries.splice(priorIdx, 1)+ for (const [id, idx] of Object.entries(toolUpdateIndex)) {+ if (idx > priorIdx) {+ toolUpdateIndex[id] = idx - 1+ }+ }+ toolUpdateIndex[toolCallId] = entries.length+ entries.push(merged)+ }+ return { entries, toolUpdateIndex }}/**@@ -870,7 +980,9 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:progress: update.progress ?? existing.progress,output: update.rawOutput ?? existing.output,locations: (update.locations as { path: string; line?: number }[] | undefined) ?? existing.locations,- contentBlocks: [...existing.contentBlocks, ...updateContent],+ // ACP update semantics: a present `content` replaces the collection (the agent re-sends+ // the full accumulated blocks) — appending would duplicate every prior snapshot.+ contentBlocks: updateContent.length > 0 ? updateContent : existing.contentBlocks,error: errorMessage !== undefined ? { message: errorMessage } : existing.error,...(rawInput ? { input: rawInput } : {}),...(update._meta ? { meta: update._meta } : {}),@@ -1324,18 +1436,18 @@ export const runStreamLogic = kea<runStreamLogicType>([reset: () => null,},],- // The single source of truth: an ordered, append-only log of every ingested frame (plus- // client-injected synthetic entries). `threadItems` and `toolInvocations` are pure- // projections of it (see the selectors). The bootstrap seam is reconciled once before its- // live tail is appended (see `bootstrapRun` / `dedupeBufferedAgainstHistory`), and- // steady-state live frames resume exclusively after the last-seen Redis id, so a plain- // append never doubles the thread.+ // The single source of truth: an ordered log of every ingested frame (plus client-injected+ // synthetic entries). `threadItems` and `toolInvocations` are pure projections of it (see+ // the selectors). The bootstrap seam is reconciled once before its live tail is appended+ // (see `bootstrapRun` / `dedupeBufferedAgainstHistory`), and steady-state live frames+ // resume exclusively after the last-seen Redis id, so a plain append never doubles the+ // thread. Superseded `tool_call_update` snapshots are the one exception to append-only —+ // `appendToRunLog` merges them per toolCallId (see the `RunLog` doc for why).log: [- { entries: [] } as RunLog,+ emptyRunLog(),{- appendEntries: (state, { entries }) =>- entries.length === 0 ? state : { entries: [...state.entries, ...entries] },- reset: () => ({ entries: [] }),+ appendEntries: (state, { entries }) => appendToRunLog(state, entries),+ reset: () => emptyRunLog(),},],// True while a bootstrap is in flight before the thread has anything to show. Cleared once the