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.

perf(posthog-ai): load task chat history latest turns first (#121113)

Shy Alter4bf62165bb64
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index bb122aae8c87..6f0bf745fbb2 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -483,6 +483,22 @@ export class ApiConfig {
/** A workflow's type: the surface that owns it, else what it does. */
export type HogFlowListType = 'messaging' | 'automation' | 'loop' | 'broadcast'
+function parseLogEntries(text: string): Record<string, any>[] {
+ const entries: Record<string, any>[] = []
+ for (const line of text.split('\n')) {
+ const trimmed = line.trim()
+ if (!trimmed) {
+ continue
+ }
+ try {
+ entries.push(JSON.parse(trimmed))
+ } catch {
+ // Skip unparseable lines — the stream is best-effort historical replay.
+ }
+ }
+ return entries
+}
+
export class ApiRequest {
private pathComponents: string[]
private queryString: string | undefined
@@ -5044,20 +5060,56 @@ const api = {
.taskRun(taskId, runId, options.projectId)
.withAction('logs')
.getResponse({ signal: options.signal })
- const text = await response.text()
- const entries: Record<string, any>[] = []
- for (const line of text.split('\n')) {
- const trimmed = line.trim()
- if (!trimmed) {
- continue
- }
- try {
- entries.push(JSON.parse(trimmed))
- } catch {
- // Skip unparseable lines — the stream is best-effort historical replay.
- }
+ return parseLogEntries(await response.text())
+ },
+ /**
+ * Fetch part of a run's resume-chain log. With `tailBytes`, the latest turns (at least `tailBytes`, from a
+ * cut where a user turn starts) that end before entry index `before`, or with `start`, every entry from
+ * that index on. The page starts with `preamble` earlier entries that still set run state; `offset` is
+ * the full-log index of the first entry after them, `count` is the full-log size, and `turnsBefore`
+ * counts the user turns before `offset`. Without `tailBytes`, or for a log the server does not page, the
+ * response is the full log and `indexed` is false.
+ */
+ async getLogPage(
+ taskId: Task['id'],
+ runId: TaskRun['id'],
+ options: {
+ signal?: AbortSignal
+ projectId?: TeamType['id']
+ tailBytes?: number
+ before?: number
+ start?: number
+ }
+ ): Promise<{
+ entries: Record<string, any>[]
+ offset: number
+ count: number
+ preamble: number
+ turnsBefore: number
+ origin: string
+ indexed: boolean
+ }> {
+ const response = await new ApiRequest()
+ .taskRun(taskId, runId, options.projectId)
+ .withAction('logs')
+ .withQueryString({
+ ...(options.tailBytes !== undefined ? { tail_bytes: options.tailBytes } : {}),
+ ...(options.before !== undefined ? { before: options.before } : {}),
+ ...(options.start !== undefined ? { start: options.start } : {}),
+ })
+ .getResponse({ signal: options.signal })
+ const entries = parseLogEntries(await response.text())
+ const indexed = response.headers.get('X-Log-Offset') !== null
+ const header = (name: string): number => Number(response.headers.get(name) ?? 0) || 0
+ return {
+ entries,
+ offset: header('X-Log-Offset'),
+ count: indexed ? header('X-Log-Count') : entries.length,
+ preamble: header('X-Log-Preamble'),
+ turnsBefore: header('X-Log-Turns-Before'),
+ origin: response.headers.get('X-Log-Origin') ?? '',
+ indexed,
}
- return entries
},
/**
* Open the live SSE stream for a run as a `fetch` response (the caller reads it with
diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.ts
index 13591b2dd996..869cadce4cdd 100644
--- a/frontend/src/scenes/max/maxThreadLogic.test.ts
+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts
@@ -1768,7 +1768,15 @@ describe('maxThreadLogic', () => {
it('replays logs/ then opens SSE for a non-terminal sandbox run, never reconnecting LangGraph', async () => {
logic.unmount()
jest.spyOn(api.conversations, 'get').mockResolvedValue(sandboxConversation(SANDBOX_RUN_ID))
- const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])
+ const logsSpy = jest.spyOn(api.tasks.runs, 'getLogPage').mockResolvedValue({
+ entries: [],
+ offset: 0,
+ count: 0,
+ preamble: 0,
+ turnsBefore: 0,
+ origin: '',
+ indexed: false,
+ })
const runSpy = jest
.spyOn(tasksApi, 'tasksRunsRetrieve')
.mockResolvedValue({ status: 'in_progress' } as TaskRunDetailDTOApi)
@@ -1786,10 +1794,11 @@ describe('maxThreadLogic', () => {
// bootstrapRun replayed logs/ and refetched the run, then opened SSE — and the LangGraph
// stream was never touched (coexistence).
- expect(logsSpy).toHaveBeenCalledWith(SANDBOX_TASK_ID, SANDBOX_RUN_ID, {
- signal: expect.any(AbortSignal),
- projectId: 997,
- })
+ expect(logsSpy).toHaveBeenCalledWith(
+ SANDBOX_TASK_ID,
+ SANDBOX_RUN_ID,
+ expect.objectContaining({ signal: expect.any(AbortSignal), projectId: 997 })
+ )
expect(runSpy).toHaveBeenCalledWith('997', SANDBOX_TASK_ID, SANDBOX_RUN_ID, {
signal: expect.any(AbortSignal),
})
@@ -1800,7 +1809,7 @@ describe('maxThreadLogic', () => {
logic.unmount()
const conversation = sandboxConversation(SANDBOX_RUN_ID, TaskRuntimeEnumApi.Pi)
jest.spyOn(api.conversations, 'get').mockResolvedValue(conversation)
- const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries')
+ const logsSpy = jest.spyOn(api.tasks.runs, 'getLogPage')
const streamSpy = mockStream()
logic = maxThreadLogic({
@@ -1818,7 +1827,7 @@ describe('maxThreadLogic', () => {
it('does not bootstrap a sandbox run without a latest_run', async () => {
logic.unmount()
jest.spyOn(api.conversations, 'get').mockResolvedValue(sandboxConversation(null))
- const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries')
+ const logsSpy = jest.spyOn(api.tasks.runs, 'getLogPage')
const streamSpy = mockStream()
logic = maxThreadLogic({
diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsx
index c8877bfdc918..49e802de6b01 100644
--- a/frontend/src/scenes/max/maxThreadLogic.tsx
+++ b/frontend/src/scenes/max/maxThreadLogic.tsx
@@ -317,6 +317,7 @@ export interface maxThreadLogicActions {
} // posthogAiContextLogic
bootstrapSandboxRun: (payload: {
justCreatedRun?: boolean
+ pagedHistory?: boolean
retainedMessage?: string
runId: string
taskId: string
@@ -324,6 +325,7 @@ export interface maxThreadLogicActions {
traceId?: string
}) => {
justCreatedRun?: boolean | undefined
+ pagedHistory?: boolean | undefined
retainedMessage?: string | undefined
runId: string
taskId: string
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 78b41a4bf036..865e82c32b55 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -3588,3 +3588,21 @@ export type LogsViewsListParams = {
*/
offset?: number
}
+
+export type TasksRunsLogsRetrieveParams = {
+ /**
+ * With tail_bytes, end the window before this entry index, so a client can page back through older turns: pass the X-Log-Offset of the oldest page it holds.
+ * @minimum 0
+ */
+ before?: number
+ /**
+ * With tail_bytes, return every entry from this index to the end, with no preamble, so a client that holds the entries before it can catch up after a disconnect: pass the X-Log-Count of its last read. When those entries are too large, the response holds the latest turns as tail_bytes alone returns them, and X-Log-Offset is greater than start.
+ * @minimum 0
+ */
+ start?: number
+ /**
+ * Return only the latest turns of the log: the shortest suffix that starts at a user turn and holds at least this many bytes. The X-Log-Offset and X-Log-Count headers give the index of the first tail entry and the size of the full log. The slice starts with X-Log-Preamble earlier entries that still set run state, such as the run start, usage, mode, commands and open permission requests. X-Log-Turns-Before counts the user turns before the slice, so a client numbers turns the way the full log does.
+ * @minimum 1
+ */
+ tail_bytes?: number
+}
diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.ts
index a8e5141bf27a..ad6de8ad0f1b 100644
--- a/products/logs/frontend/generated/api.ts
+++ b/products/logs/frontend/generated/api.ts
@@ -58,6 +58,7 @@ import type {
PatchedLogsSamplingRuleApi,
PatchedLogsViewApi,
PatchedTeamLogsConfigApi,
+ TasksRunsLogsRetrieveParams,
TeamLogsConfigApi,
_LogsAttributesResponseApi,
_LogsCountRangesRequestApi,
@@ -1310,21 +1311,39 @@ export const logsViewsDestroy = async (projectId: string, shortId: string, optio
})
}
-export const getTasksRunsLogsRetrieveUrl = (projectId: string, taskId: string, id: string) => {
- return `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/logs/`
+export const getTasksRunsLogsRetrieveUrl = (
+ projectId: string,
+ taskId: string,
+ id: string,
+ params?: TasksRunsLogsRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/logs/?${stringifiedParams}`
+ : `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/logs/`
}
/**
- * Fetch the logs for a task run as JSONL. If the run resumes from another (state.resume_from_run_id), each ancestor's log is concatenated first (oldest ancestor → ... → this run) so resume consumers see a single continuous history. A resumed Pi run includes the earlier runs of its task session the same way, each preceded by a pi_run_started entry that names its run. For a live presence-gated run, the request marks the stream as watched before it reads the log, so events after the snapshot reach the live stream.
+ * Fetch the logs for a task run as JSONL. If the run resumes from another (state.resume_from_run_id), each ancestor's log is concatenated first (oldest ancestor → ... → this run) so resume consumers see a single continuous history. A resumed Pi run includes the earlier runs of its task session the same way, each preceded by a pi_run_started entry that names its run. For a live presence-gated run, the request marks the stream as watched before it reads the log, so events after the snapshot reach the live stream. Pass tail_bytes to read only the latest turns first, add before to page back through older turns, or add start to read every entry after the ones a client holds. X-Log-Origin names the first run of the chain: indexes from responses with different origins do not match. A Pi run returns its full log without the X-Log headers.
* @summary Get task run logs
*/
export const tasksRunsLogsRetrieve = async (
projectId: string,
taskId: string,
id: string,
+ params?: TasksRunsLogsRetrieveParams,
options?: RequestInit
): Promise<void> => {
- return apiMutator<void>(getTasksRunsLogsRetrieveUrl(projectId, taskId, id), {
+ return apiMutator<void>(getTasksRunsLogsRetrieveUrl(projectId, taskId, id, params), {
...options,
method: 'GET',
})
diff --git a/products/posthog_ai/backend/turn_suggestions/transcript.py b/products/posthog_ai/backend/turn_suggestions/transcript.py
index 629ac42d0d11..9a5b5fd5e8ad 100644
--- a/products/posthog_ai/backend/turn_suggestions/transcript.py
+++ b/products/posthog_ai/backend/turn_suggestions/transcript.py
@@ -243,14 +243,22 @@ TURN_COMPLETE_METHOD = "_posthog/turn_complete"
RESUME_CONTEXT_PREFIX = "You are resuming a previous conversation."
-def _human_text(method: str | None, params: dict[str, Any]) -> tuple[str, bool] | None:
- """The user's text in a ``_posthog/user_message`` frame, paired with ``True``, or in a
- ``session/update`` user message, paired with ``False``. ``None`` for any other frame.
+@frozen
+class HumanText:
+ """The user's text in a frame, and whether the frame is the ``_posthog/user_message`` form."""
+
+ text: str
+ user_message: bool
+
+
+def human_text(method: str | None, params: dict[str, Any]) -> HumanText | None:
+ """The user's text in a ``_posthog/user_message`` frame or in a ``session/update`` user message.
+ ``None`` for any other frame.
These are the two forms the thread renders as a human message, so turn indexes match its trailers.
"""
if is_user_message_params(params, method):
- return strip_context_blocks(_text_from_content(params.get("content"))), True
+ return HumanText(text=strip_context_blocks(_text_from_content(params.get("content"))), user_message=True)
if method != "session/update":
return None
update = params.get("update")
@@ -262,7 +270,33 @@ def _human_text(method: str | None, params: dict[str, Any]) -> tuple[str, bool]
text = content.get("text") if isinstance(content, dict) else None
if not isinstance(text, str):
text = update.get("text")
- return strip_context_blocks(text if isinstance(text, str) else ""), False
+ return HumanText(text=strip_context_blocks(text if isinstance(text, str) else ""), user_message=False)
+
+
+def is_turn_text(text: str) -> bool:
+ """Whether a human text can open a turn. An empty text and the resume prompt never render."""
+ return bool(text) and not text.startswith(RESUME_CONTEXT_PREFIX)
+
+
+class HumanTurnCounter:
+ """Decides which human texts open a turn, the way the thread folds them.
+
+ A ``_posthog/user_message`` opens a turn and leaves a credit for its text. A later ``session/update`` user
+ message with the same text spends the credit and opens nothing, so a turn persisted in both wire forms
+ counts once.
+ """
+
+ def __init__(self) -> None:
+ self._credits: Counter[str] = Counter()
+
+ def opens_turn(self, text: str, is_user_message: bool) -> bool:
+ if is_user_message:
+ self._credits[text] += 1
+ return True
+ if self._credits[text] > 0:
+ self._credits[text] -= 1
+ return False
+ return True
def build_turn_transcript(entries: Iterable[dict[str, Any]]) -> TurnTranscript:
@@ -273,7 +307,7 @@ def build_turn_transcript(entries: Iterable[dict[str, Any]]) -> TurnTranscript:
counts once.
"""
human_messages: list[str] = []
- remembered_texts: Counter[str] = Counter()
+ turns = HumanTurnCounter()
earlier_turns: list[EarlierTurn] = []
# Assistant text by message id, in arrival order. Chunks append; a closing `agent_message`
# carries the whole text and replaces them, matching how the thread fold finalizes a bubble.
@@ -316,17 +350,10 @@ def build_turn_transcript(entries: Iterable[dict[str, Any]]) -> TurnTranscript:
assistant_messages[key] = assistant_messages.get(key, "") + text
for method, params in _notifications(entries):
- human = _human_text(method, params)
+ human = human_text(method, params)
if human is not None:
- text, is_user_message = human
- if not text or text.startswith(RESUME_CONTEXT_PREFIX):
- continue
- if is_user_message:
- remembered_texts[text] += 1
- elif remembered_texts[text] > 0:
- remembered_texts[text] -= 1
- continue
- start_turn(text)
+ if is_turn_text(human.text) and turns.opens_turn(human.text, human.user_message):
+ start_turn(human.text)
continue
if method == TURN_COMPLETE_METHOD:
latest_turn_complete = bool(human_messages)
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
index b330ae30afe5..38a5c962cc94 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
@@ -135,7 +135,12 @@ describe('RunSurface', () => {
expect(screen.getByTestId('thread')).toBeInTheDocument()
expect(screen.getByTestId('composer-child')).toBeInTheDocument()
- expect(bootstrapRun).toHaveBeenCalledWith({ taskId: 'task-1', runId: 'run-1', taskRuntime: runtime })
+ expect(bootstrapRun).toHaveBeenCalledWith({
+ taskId: 'task-1',
+ runId: 'run-1',
+ taskRuntime: runtime,
+ pagedHistory: true,
+ })
})
it('keeps a Pi task behind the unavailable banner until Pi web sessions are on', () => {
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
index d2caf5f0da88..8234860d8a5f 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
@@ -207,7 +207,7 @@ function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {
if (awaitingOptimisticAttach) {
// Attaching a freshly-created run to a seeded optimistic instance: skip the reset so the seed
// survives, and take the fresh-run fast path. The live SSE echo dedups the seeded message.
- bootstrapRun({ taskId, runId, justCreatedRun: true, taskRuntime })
+ bootstrapRun({ taskId, runId, justCreatedRun: true, taskRuntime, pagedHistory: true })
return
}
// Reset first so a reused instance (stable streamKey, changed run) replays/streams the new run
@@ -215,7 +215,7 @@ function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {
// `interaction` is in the deps so a status transition (live → terminal) re-bootstraps the right
// mode — the bound logic re-keys on it, so `bootstrapRun`/`reset` are fresh references anyway.
reset()
- bootstrapRun({ taskId, runId, taskRuntime })
+ bootstrapRun({ taskId, runId, taskRuntime, pagedHistory: true })
}, [
taskId,
runId,
diff --git a/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx b/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx
index 0a8decbe5cd4..2f2c53d0b997 100644
--- a/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx
+++ b/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx
@@ -28,6 +28,18 @@ describe('ThreadView connection state', () => {
beforeEach(() => {
initKeaTests()
+ jest.spyOn(api.tasks.runs, 'getLogPage').mockImplementation(async (taskId, runId, options) => {
+ const entries = await api.tasks.runs.getLogEntries(taskId, runId, options)
+ return {
+ entries,
+ offset: 0,
+ count: entries.length,
+ preamble: 0,
+ turnsBefore: 0,
+ origin: '',
+ indexed: false,
+ }
+ })
logic = runStreamLogic(props)
logic.mount()
// virtualized={false} so rows render in document flow under jsdom.
diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsx
index e99aedf65e69..bdd0d0d83f4a 100644
--- a/products/posthog_ai/frontend/components/ThreadView.tsx
+++ b/products/posthog_ai/frontend/components/ThreadView.tsx
@@ -148,7 +148,10 @@ export function ThreadView({
runConnectionState,
logBootstrapLoading,
pendingPermissionRequest,
+ olderHistoryState,
+ historyTurnBase,
} = useValues(runStreamLogic)
+ const { loadOlderHistory } = useActions(runStreamLogic)
const turnCancelled = currentRunStatus === 'cancelled'
// 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.
@@ -188,11 +191,11 @@ export function ThreadView({
const previousTrailers = useRef<Map<string, TurnTrailer> | null>(null)
const trailers = useMemo(() => {
const next = renderTurnTrailer
- ? reuseTurnTrailers(previousTrailers.current, computeTurnTrailers(threadItems))
+ ? reuseTurnTrailers(previousTrailers.current, computeTurnTrailers(threadItems, historyTurnBase))
: null
previousTrailers.current = next
return next
- }, [threadItems, renderTurnTrailer])
+ }, [threadItems, renderTurnTrailer, historyTurnBase])
const revealGroups = useMemo(() => mapRowsToRevealGroup(displayItems), [displayItems])
const previousRows = useRef<ThreadViewRow[]>([])
const rows = useMemo(() => {
@@ -326,6 +329,7 @@ export function ThreadView({
// 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.
itemsLoading={logBootstrapLoading}
+ onNearTop={olderHistoryState === 'idle' ? loadOlderHistory : undefined}
header={header}
footer={footer}
stickToBottom
diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
index 3e4f0a6c2338..1a75a14b69e0 100644
--- a/products/posthog_ai/frontend/components/VirtualizedThread.tsx
+++ b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
@@ -41,6 +41,8 @@ const NO_END_COMPENSATION = -1
*/
const AT_BOTTOM_EPSILON = 1
+/** How long a prepend keeps the reader's row in place while the rows put in front measure. */
+const PREPEND_HOLD_MS = 1_000
/** The core snaps its own scroll writes to within 1.5px of their target — below that is never the reader. */
const UNPIN_SLACK = 1.5
@@ -191,6 +193,12 @@ export interface VirtualizedThreadRootProps<T> {
* caller's job: while true the thread never takes its opening scroll.
*/
itemsLoading?: boolean
+ /**
+ * Called when the reader scrolls within a viewport of the top, so the caller can load older rows. Rows the
+ * caller then puts in front of `items` never move what the reader sees: the first visible row keeps its
+ * place on screen.
+ */
+ onNearTop?: () => void
maxWidthClassName?: string
className?: string
/**
@@ -224,6 +232,7 @@ function Root<T>({
anchorItemKey,
scrollRestorationKey,
itemsLoading = false,
+ onNearTop,
maxWidthClassName = 'max-w-180',
className,
listClassName,
@@ -278,8 +287,16 @@ function Root<T>({
const followingRef = useRef(following)
followingRef.current = following
// Read by the open-decision loop without re-arming it per commit.
- const itemsLengthRef = useRef(items.length)
- itemsLengthRef.current = items.length
+ const lastItemKeyRef = useRef<string | undefined>(undefined)
+ lastItemKeyRef.current = items.length > 0 ? getItemKey(items[items.length - 1], items.length - 1) : undefined
+ const onNearTopRef = useRef(onNearTop)
+ onNearTopRef.current = onNearTop
+ // The first row on screen and its offset from the viewport top, so rows put in front of `items` can keep it
+ // in place (see the prepend effect).
+ const topRowRef = useRef<{ key: string; offset: number; start: number } | null>(null)
+ // Set by the prepend effect for the commit that put rows above the reader, so the anchor effect in the
+ // same commit reads a new anchor from that history as history, not as a send.
+ const rowsLandedAboveRef = useRef(false)
// `undefined` means "thread not yet populated" — the anchor-change effect adopts the first real key.
const prevAnchorKeyRef = useRef<string | null | undefined>(undefined)
@@ -335,6 +352,9 @@ function Root<T>({
[items, getItemKey, hasHeader]
)
+ // Delayed loops read the resolver through this ref: the one a timer captured resolves keys against the items
+ // of the render that started it, and older rows loaded since would shift every index.
+ const findVirtualIndexForKeyRef = useRef<(key: string) => number>(() => -1)
const findVirtualIndexForKey = useCallback(
(key: string): number => {
// Scan from the end — the anchor (a recent human message) is near the tail in practice.
@@ -367,6 +387,21 @@ function Root<T>({
[items, hasHeader, estimateItemHeight, defaultRowHeight, gap]
)
+ findVirtualIndexForKeyRef.current = findVirtualIndexForKey
+ const holdTopRowRef = useRef<(itemsChanged: boolean) => void>(() => {})
+ // Rows put in front of the items, with the last row unchanged: older history loading above the reader.
+ const committedEdgeKeysRef = useRef<{ first: unknown; last: unknown } | null>(null)
+ const firstItemKey = items.length > 0 ? getItemKey(items[0], 0) : null
+ const lastItemKey = items.length > 0 ? getItemKey(items[items.length - 1], items.length - 1) : null
+ const committedEdgeKeys = committedEdgeKeysRef.current
+ const prepending =
+ committedEdgeKeys !== null &&
+ firstItemKey !== null &&
+ firstItemKey !== committedEdgeKeys.first &&
+ lastItemKey === committedEdgeKeys.last
+ useLayoutEffect(() => {
+ committedEdgeKeysRef.current = { first: firstItemKey, last: lastItemKey }
+ }, [firstItemKey, lastItemKey])
const virtualizer = useVirtualizer({
count: rowCount,
getScrollElement: () => scrollRef.current,
@@ -374,6 +409,7 @@ function Root<T>({
overscan: overscanCount,
getItemKey: getVirtualItemKey,
paddingEnd: endInset,
+ onChange: () => holdTopRowRef.current(false),
// The virtualizer writes container height + row offsets to the DOM itself, in the same tick as each
// measurement — no stale-offset overlap while rows measure, and React re-renders only on range change.
directDomUpdates: true,
@@ -400,7 +436,10 @@ function Root<T>({
// bottom, and that internal offset only re-syncs via async scroll events — so the
// opening anchor scroll lands, the next measurement batch compensates against the
// stale bottom offset, and the landing is yanked straight back down.
- anchorTo: itemsLoading || !pinnedRef.current ? ('start' as const) : ('end' as const),
+ // A prepend end-anchors too, unpinned: the core then keeps the row under the reader at its offset
+ // before it computes the rendered range, so the visible rows stay mounted (and keep their open
+ // state) instead of unmounting for a frame until the prepend effect below corrects the scroll.
+ anchorTo: itemsLoading || (!pinnedRef.current && !prepending) ? ('start' as const) : ('end' as const),
// The core's growth compensation (`resizeItem` re-applying a row's growth to the scroll
// offset whenever that offset is within this many px of the end) writes `scrollTop`
// synchronously, with no scroll-direction check and no knowledge of our pinned flag. At
@@ -496,6 +535,32 @@ function Root<T>({
[virtualizer]
)
+ // The first item row whose bottom is below the viewport top, from the measurement cache (which covers every
+ // row, rendered or not, so it stays right after a programmatic scroll the virtualizer has not seen yet).
+ const rememberTopRow = useCallback((): void => {
+ const el = scrollRef.current
+ if (!el) {
+ return
+ }
+ const top = el.scrollTop
+ const rows = virtualizer.measurementsCache
+ let low = 0
+ let high = rows.length - 1
+ let first = rows.length
+ while (low <= high) {
+ const middle = (low + high) >> 1
+ if (rows[middle].end > top) {
+ first = middle
+ high = middle - 1
+ } else {
+ low = middle + 1
+ }
+ }
+ // The header and footer never move relative to the items around them, so they cannot hold a place.
+ const row = rows.slice(first).find((item) => item.key !== HEADER_KEY && item.key !== FOOTER_KEY)
+ topRowRef.current = row ? { key: String(row.key), offset: row.start - top, start: row.start } : null
+ }, [virtualizer])
+
// Every scroll the component performs itself goes through here. The peak records where the *reader*
// has been, so a landing we caused — a replayed anchor jumping to a row mid-thread, the initial open,
// a follow write — has to reset it; otherwise the scroll event our own jump emits reads as the reader
@@ -504,14 +569,15 @@ function Root<T>({
const top = scrollRef.current?.scrollTop ?? 0
peakTopRef.current = top
recordScrollWrite(top)
- }, [recordScrollWrite])
+ rememberTopRow()
+ }, [recordScrollWrite, rememberTopRow])
// Hold an unpinned anchor landing steady while the thread's measurements settle (see the settle
// constants). Re-asserts via `scrollToIndex` so the corrective write re-computes the offset from the
// freshest measurements; stands down permanently the moment the reader scrolls or the thread pins
// (a pinned thread belongs to the follow effect).
const scheduleAnchorSettle = useCallback(
- (anchorIndex: number): void => {
+ (anchorKey: string): void => {
const startedAt = performance.now()
let remaining = ANCHOR_SETTLE_CHECKS
const tick = (): void => {
@@ -519,6 +585,11 @@ function Root<T>({
if (!el || lastUserScrollAtRef.current > startedAt || pinnedRef.current) {
return
}
+ // Resolved per tick: older rows put in front of the items move the anchor's index.
+ const anchorIndex = findVirtualIndexForKeyRef.current(anchorKey)
+ if (anchorIndex < 0) {
+ return
+ }
const target = virtualizer.getOffsetForIndex(anchorIndex, 'start')?.[0]
if (
target !== undefined &&
@@ -547,9 +618,11 @@ function Root<T>({
// still short — or the live stream appending before it ends, which makes the open a live-edge open —
// ⇒ a bottom open, pinned. Stops the moment the reader scrolls: their position, their call.
const scheduleOpenDecision = useCallback(
- (anchorIndex: number): void => {
+ (anchorKey: string): void => {
const startedAt = performance.now()
- const itemsAtOpen = itemsLengthRef.current
+ // The tail row, not the row count: older rows put in front change the count without the stream
+ // appending anything.
+ const tailAtOpen = lastItemKeyRef.current
let remaining = ANCHOR_SETTLE_CHECKS
const commitBottomOpen = (el: HTMLElement): void => {
el.scrollTop = el.scrollHeight
@@ -563,13 +636,14 @@ function Root<T>({
}
const viewport = el.clientHeight
const totalSize = virtualizer.getTotalSize()
- const anchorStart = virtualizer.measurementsCache[anchorIndex]?.start
+ const anchorIndex = findVirtualIndexForKeyRef.current(anchorKey)
+ const anchorStart = anchorIndex >= 0 ? virtualizer.measurementsCache[anchorIndex]?.start : undefined
const contentBelow = anchorStart !== undefined ? totalSize - anchorStart : 0
if (viewport > 0 && contentBelow >= viewport) {
return
}
remaining -= 1
- const verdictDue = itemsLengthRef.current !== itemsAtOpen || remaining === 0
+ const verdictDue = lastItemKeyRef.current !== tailAtOpen || remaining === 0
if (verdictDue && !hasUnseenScroll(el, lastSeenTopRef.current)) {
commitBottomOpen(el)
} else if (remaining > 0) {
@@ -581,6 +655,73 @@ function Root<T>({
[virtualizer, noteProgrammaticScroll, setPinned]
)
+ // Rows that land above the reader (a history page loading in front, or the fold placing an older row
+ // under the first message) must not move what the reader sees. When the items change and the first row that
+ // was on screen has moved, it goes back to the same offset from the viewport top before paint. The rows that
+ // landed render at estimated heights and measure a frame or two later, so measured-size changes keep
+ // correcting for a short hold; outside it, measurement belongs to the settle loops and the core.
+ const totalSize = virtualizer.getTotalSize()
+ const previousItemsRef = useRef(items)
+ const prependHoldRef = useRef({ from: 0, until: 0 })
+ // Also called from the virtualizer's measurement notifications: with direct DOM updates, a row that grows
+ // without changing the rendered range skips React, so the layout effect alone would miss it.
+ holdTopRowRef.current = (itemsChanged: boolean): void => {
+ const el = scrollRef.current
+ const topRow = topRowRef.current
+ // A thread following a live reply belongs to the follow effect; holding a row would pull it back up.
+ if (!virtualized || !el || !topRow || (pinnedRef.current && followingRef.current)) {
+ return
+ }
+ const hold = prependHoldRef.current
+ const holding = performance.now() < hold.until && lastUserScrollAtRef.current <= hold.from
+ if (!itemsChanged && !holding) {
+ return
+ }
+ const index = findVirtualIndexForKeyRef.current(topRow.key)
+ const start = index >= 0 ? virtualizer.measurementsCache[index]?.start : undefined
+ if (start === undefined || Math.abs(start - topRow.start) <= UNPIN_SLACK) {
+ return
+ }
+ // A reader's scroll whose event has not dispatched yet still moved the view: the correction keeps that
+ // movement, and the hold ends so a later measurement cannot reverse it.
+ const pending = hasUnseenScroll(el, lastSeenTopRef.current) ? el.scrollTop - lastSeenTopRef.current : 0
+ if (itemsChanged) {
+ rowsLandedAboveRef.current = true
+ }
+ if (pending !== 0) {
+ prependHoldRef.current = { from: 0, until: 0 }
+ } else if (itemsChanged) {
+ prependHoldRef.current = { from: performance.now(), until: performance.now() + PREPEND_HOLD_MS }
+ }
+ topRowRef.current = { ...topRow, start }
+ const target = start - topRow.offset + pending
+ if (Math.abs(el.scrollTop - target) > UNPIN_SLACK) {
+ el.scrollTop = target
+ noteProgrammaticScroll()
+ }
+ }
+ useLayoutEffect(() => {
+ const itemsChanged = previousItemsRef.current !== items
+ previousItemsRef.current = items
+ holdTopRowRef.current(itemsChanged)
+ }, [items, totalSize])
+
+ // A thread shorter than its viewport has no scroll to bring the reader near the top, so ask for older
+ // rows directly until it fills the viewport or the caller has none left. A reader who scrolled near the
+ // top and stays there sends no scroll event when older rows become available again (after a failed
+ // load waits and rearms), so that reader asks too.
+ useEffect(() => {
+ const el = scrollRef.current
+ if (!virtualized || !el || el.clientHeight === 0) {
+ return
+ }
+ const short = el.scrollHeight <= el.clientHeight + UNPIN_SLACK
+ const readerNearTop = lastUserScrollAtRef.current > 0 && el.scrollTop < el.clientHeight
+ if (short || readerNearTop) {
+ onNearTopRef.current?.()
+ }
+ }, [items, onNearTop, virtualized])
+
// Initial open (once): land before the browser paints, so a long thread never shows a top-frame
// flicker or a visible crawl. A thread that already has messages opens on its last meaningful turn —
// the anchor row (the last human message) at the top of the viewport, its response below — whether or
@@ -605,8 +746,9 @@ function Root<T>({
const savedIndex = savedReadItem.current ? findVirtualIndexForKey(savedReadItem.current) : -1
const anchorIndex =
savedIndex >= 0 ? savedIndex : anchorItemKey != null ? findVirtualIndexForKey(anchorItemKey) : -1
+ const landingKey = savedIndex >= 0 ? savedReadItem.current : anchorItemKey
const el = scrollRef.current
- if (anchorIndex >= 0) {
+ if (anchorIndex >= 0 && landingKey) {
// Provisional anchor landing — this commit only has estimates for the rows under the anchor,
// so whether the thread is really "top" or "bottom" shaped is decided by the decision loop
// once measurements land (see `scheduleOpenDecision`). The scroll itself is safe under
@@ -618,9 +760,9 @@ function Root<T>({
noteProgrammaticScroll()
setPinned(false)
bottomRepinBlockedUntilRef.current = performance.now() + BOTTOM_REPIN_BLOCK_MS
- scheduleAnchorSettle(anchorIndex)
+ scheduleAnchorSettle(landingKey)
if (savedIndex < 0) {
- scheduleOpenDecision(anchorIndex)
+ scheduleOpenDecision(landingKey)
}
return
}
@@ -667,6 +809,8 @@ function Root<T>({
// Gated on `itemsLoading` like the initial open — adopting mid-replay would pin the pre-history
// anchor value (typically null) and misread the full history's anchor as a fresh send.
useLayoutEffect(() => {
+ const rowsLandedAbove = rowsLandedAboveRef.current
+ rowsLandedAboveRef.current = false
if (!virtualized || itemsLoading || items.length === 0) {
return
}
@@ -685,6 +829,11 @@ function Root<T>({
if (anchorIndex < 0) {
return
}
+ if (rowsLandedAbove) {
+ // History that loaded above the reader brought this anchor; the prepend effect already holds the
+ // reader's row, so adopting the key is all there is to do.
+ return
+ }
const isFreshSend = prevKeys === null || !prevKeys.has(anchorItemKey)
if (!isFreshSend) {
virtualizer.scrollToIndex(anchorIndex, { align: 'start' })
@@ -692,7 +841,7 @@ function Root<T>({
// Same estimate-clamp settle as the initial open: the landing may touch the bottom
// transiently, and those touches must not read as the reader arriving there.
bottomRepinBlockedUntilRef.current = performance.now() + BOTTOM_REPIN_BLOCK_MS
- scheduleAnchorSettle(anchorIndex)
+ scheduleAnchorSettle(anchorItemKey)
return
}
// Sending is an explicit request to follow the answer, wherever the reader had scrolled to
@@ -781,6 +930,10 @@ function Root<T>({
const onScroll = (): void => {
const top = el.scrollTop
lastSeenTopRef.current = top
+ rememberTopRow()
+ if (top < el.clientHeight) {
+ onNearTopRef.current?.()
+ }
const maxTop = Math.max(0, el.scrollHeight - el.clientHeight)
// Content shrinking under the reader — a tool card's accordion collapsing the moment the tool
// completes, which on this surface is every finished tool — lowers the scroll range, and the
@@ -844,7 +997,7 @@ function Root<T>({
}
// Deliberately not keyed on the pinned state: re-subscribing mid-gesture would reset the peak
// baseline, which is the one thing that has to survive a gesture.
- }, [virtualized, stickToBottom, setPinned])
+ }, [virtualized, stickToBottom, setPinned, rememberTopRow])
// The turn's tail arrives after the turn is over — usage and cost come on their own stream frames and
// the footer swaps to them a commit or two later — so following has to outlast `turnActive` by a beat
diff --git a/products/posthog_ai/frontend/e2e/run-surface.spec.ts b/products/posthog_ai/frontend/e2e/run-surface.spec.ts
index 8b3de1eb8866..6961ab540341 100644
--- a/products/posthog_ai/frontend/e2e/run-surface.spec.ts
+++ b/products/posthog_ai/frontend/e2e/run-surface.spec.ts
@@ -111,7 +111,8 @@ async function routeTasksApi(page: Page, mock: TasksApiMock): Promise<void> {
const runsRe = new RegExp(`/tasks/${TASK_ID}/runs/$`)
const runRe = new RegExp(`/tasks/${TASK_ID}/runs/${RUN_ID}/$`)
const tokenRe = new RegExp(`/runs/${RUN_ID}/stream_token/$`)
- const logsRe = new RegExp(`/runs/${RUN_ID}/logs/$`)
+ // A paged read (`.../logs?tail_bytes=...`) has no trailing slash either, like the `stream` action below.
+ const logsRe = new RegExp(`/runs/${RUN_ID}/logs/?$`)
// The `stream` action URL has no trailing slash (`.../stream?start=latest`), unlike the other
// resource paths — match it with an optional slash so the route intercepts instead of falling through
// to the real backend (a fall-through 404s the fake run id and masks the clean-EOF drop under test).
diff --git a/products/posthog_ai/frontend/hooks/useFeedbackPrompt.ts b/products/posthog_ai/frontend/hooks/useFeedbackPrompt.ts
index fcd18f679ef6..c4cebc34c443 100644
--- a/products/posthog_ai/frontend/hooks/useFeedbackPrompt.ts
+++ b/products/posthog_ai/frontend/hooks/useFeedbackPrompt.ts
@@ -16,15 +16,17 @@ export interface UseFeedbackPromptResult {
* turn finishes, and treats a new message sent while the prompt is open as an implicit dismissal.
*/
export function useFeedbackPrompt(sessionId: string, streamKey: string): UseFeedbackPromptResult {
- const { threadItems, streamPhase } = useValues(runStreamLogic)
+ const { threadItems, streamPhase, historyTurnBase } = useValues(runStreamLogic)
const logic = feedbackPromptLogic({ sessionId, streamKey })
const { isPromptVisible, isDetailedFeedbackVisible, isThankYouVisible } = useValues(logic)
const { checkShouldShowPrompt, implicitDismissPrompt, implicitDismissDetailedFeedback } = useActions(logic)
const streamingActive = streamPhase !== 'idle'
+ // Counted over the full history, so an older page that loads is not a new send, and the trigger uses the same
+ // intervals as a submitted rating.
const humanMessageCount = useMemo(
- () => threadItems.filter((item) => item.type === 'human_message').length,
- [threadItems]
+ () => historyTurnBase + threadItems.filter((item) => item.type === 'human_message').length,
+ [threadItems, historyTurnBase]
)
const prevMessageCountRef = useRef(humanMessageCount)
const prevStreamingActiveRef = useRef(streamingActive)
diff --git a/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts b/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts
index 329c40ce42e1..02ca353c1a4b 100644
--- a/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts
+++ b/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts
@@ -39,13 +39,14 @@ function readStream(streamKey: string): StreamSnapshot {
return { traceId: null, turnIndex: null, humanMessageCount: 0, run: undefined }
}
const items = stream.values.threadItems
- const trailers = computeTurnTrailers(items)
+ const turnBase = stream.values.historyTurnBase
+ const trailers = computeTurnTrailers(items, turnBase)
const lastTurn = [...trailers.values()].find((trailer) => trailer.isLastTurn)
return {
// Same trailer as turnIndex, so the two can never describe different turns.
traceId: lastTurn?.traceId ?? null,
turnIndex: lastTurn?.turnIndex ?? null,
- humanMessageCount: items.filter((item) => item.type === 'human_message').length,
+ humanMessageCount: turnBase + items.filter((item) => item.type === 'human_message').length,
run: stream.cache.activeRun as RunRef | undefined,
}
}
diff --git a/products/posthog_ai/frontend/logics/runPrefetch.ts b/products/posthog_ai/frontend/logics/runPrefetch.ts
index 28936a2042e7..2523938ba141 100644
--- a/products/posthog_ai/frontend/logics/runPrefetch.ts
+++ b/products/posthog_ai/frontend/logics/runPrefetch.ts
@@ -35,6 +35,6 @@ export function prefetchRunStream(taskId: string, runId: string, taskRuntime: st
const logic = runStreamLogic({ streamKey: runId })
retainMountedLogic(PREFETCHED_RUN_STREAMS, runId, logic, MAX_PREFETCHED_RUN_STREAMS)
if (logic.values.bootstrappedRunId === null) {
- logic.actions.bootstrapRun({ taskId, runId, taskRuntime })
+ logic.actions.bootstrapRun({ taskId, runId, taskRuntime, pagedHistory: true })
}
}
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index ebc31c0bca47..c1200a131e88 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -1,3 +1,4 @@
+import { getContext } from 'kea'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
@@ -14,6 +15,7 @@ import {
} from 'products/tasks/frontend/generated/api'
import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'
+import logPageFixtures from '../../../tasks/backend/tests/fixtures/log_pages.json'
import { lookupToolRenderer, toolRegistry } from '../components/tool/toolRegistry'
import { extractQueryResult } from '../components/tool/widgets/extractors'
import { turnSuggestionsStateRetrieve } from '../generated/api'
@@ -34,6 +36,7 @@ import {
type FoldCheckpoint,
foldLogFromCheckpoint,
foldLogToThread,
+ type HistoryPage,
mapHttpStatusToStreamError,
MAX_CUMULATIVE_RECONNECT_ATTEMPTS,
MAX_HISTORY_FETCH_ATTEMPTS,
@@ -41,6 +44,7 @@ import {
mergeCoalescedRunLog,
mergeRunArtifacts,
parsePermissionRequestFrame,
+ readFullThread,
reconnectDelayMs,
reconcileRunLog,
resolveStreamTarget,
@@ -244,6 +248,18 @@ describe('runStreamLogic', () => {
.mockReset()
.mockResolvedValue({ status: 'in_progress' } as TaskRunDetailDTOApi)
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])
+ jest.spyOn(api.tasks.runs, 'getLogPage').mockImplementation(async (taskId, runId, options) => {
+ const entries = await api.tasks.runs.getLogEntries(taskId, runId, options)
+ return {
+ entries,
+ offset: 0,
+ count: entries.length,
+ preamble: 0,
+ turnsBefore: 0,
+ origin: '',
+ indexed: false,
+ }
+ })
jest.mocked(turnSuggestionsStateRetrieve).mockReset().mockResolvedValue({ muted: false, resolved_turns: [] })
projectLogic.mount()
projectLogic.actions.loadCurrentProjectSuccess({ id: 997 } as any)
@@ -1192,8 +1208,9 @@ describe('runStreamLogic', () => {
describe('pushHumanMessage', () => {
it('appends a timestamped human_message item ordered before subsequently ingested assistant frames', async () => {
+ logic.actions.pushHumanMessage('hello agent')
+ const placeholderId = logic.values.threadItems[0].id
await expectLogic(logic, () => {
- logic.actions.pushHumanMessage('hello agent')
// The agent takes the send up and echoes it, which is what places the message.
logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'hello agent' }))
logic.actions.ingestAcpFrame(
@@ -1204,7 +1221,7 @@ describe('runStreamLogic', () => {
expect(logic.values.threadItems).toHaveLength(2)
// The echo keeps the row the placeholder drew, rather than minting a second id.
expect(logic.values.threadItems[0]).toEqual({
- id: 'human-0',
+ id: placeholderId,
type: 'human_message',
text: 'hello agent',
complete: true,
@@ -1337,6 +1354,7 @@ describe('runStreamLogic', () => {
'session/update user_message',
sessionUpdate({ sessionUpdate: 'user_message', content: { text: wrapped } }),
],
+ ['page preamble', notification('_posthog/context_history', { messages: [wrapped] })],
])('records replayed context-block lines under the bootstrapped task (%s)', async (_form, frame) => {
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([frame] as any)
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
@@ -5234,6 +5252,317 @@ describe('runStreamLogic', () => {
})
})
+ describe('history pages', () => {
+ const page = (
+ entries: StoredLogEntry[],
+ offset: number,
+ count: number,
+ preamble = 0,
+ turnsBefore = 0,
+ origin = 'run-1'
+ ): HistoryPage => ({ entries, offset, count, preamble, turnsBefore, origin, indexed: true })
+ const turn = (text: string, eventId: string): StoredLogEntry => ({
+ ...sessionUpdate({ sessionUpdate: 'user_message_chunk', content: { type: 'text', text } }),
+ event_id: eventId,
+ })
+ const reply = (text: string, eventId: string): StoredLogEntry => ({
+ ...sessionUpdate({ sessionUpdate: 'agent_message', content: { type: 'text', text } }),
+ event_id: eventId,
+ })
+ const texts = (items: ThreadItem[]): string[] =>
+ items.flatMap((item) => ('text' in item && typeof item.text === 'string' ? [item.text] : []))
+ const isHuman = (item: ThreadItem): boolean => item.type === 'human_message'
+
+ it.each(logPageFixtures.cases)(
+ 'shows page by page what the full log shows: $name',
+ async ({ parts, pages }) => {
+ const log = parts.flat() as unknown as StoredLogEntry[]
+ const runId = String(
+ log.findLast((entry) => entry.notification.method === '_posthog/run_started')?.notification.params
+ ?.runId
+ )
+ const olderPages = new Map(pages.slice(1).map((older, index) => [pages[index].offset, older]))
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({
+ status: 'completed',
+ state: parts.length > 1 ? { resume_from_run_id: 'run-1' } : {},
+ } as unknown as TaskRunDetailDTOApi)
+ jest.spyOn(api.tasks.runs, 'getLogPage').mockImplementation(async (_taskId, _runId, options) => {
+ const golden =
+ options.tailBytes === undefined
+ ? undefined
+ : options.before === undefined
+ ? pages[0]
+ : olderPages.get(options.before)
+ return golden
+ ? {
+ entries: golden.entries,
+ offset: golden.offset,
+ count: golden.count,
+ preamble: golden.preamble,
+ turnsBefore: golden.turns_before,
+ origin: 'run-1',
+ indexed: true,
+ }
+ : {
+ entries: log,
+ offset: 0,
+ count: log.length,
+ preamble: 0,
+ turnsBefore: 0,
+ origin: '',
+ indexed: false,
+ }
+ })
+ const full = runStreamLogic({ streamKey: 'full-read' })
+ const paged = runStreamLogic({ streamKey: 'paged-read' })
+ full.mount()
+ paged.mount()
+ try {
+ full.actions.bootstrapRun({ taskId: 'task-1', runId })
+ paged.actions.bootstrapRun({ taskId: 'task-1', runId, pagedHistory: true })
+ await flushPromises()
+ const fullItems = full.values.threadItems
+ const fullTurns = new Map(fullItems.filter(isHuman).map((item, index) => [item.id, index]))
+ for (;;) {
+ const shown = paged.values.threadItems
+ expect(shown).toEqual(fullItems.slice(fullItems.length - shown.length))
+ expect(shown.filter(isHuman).map((_, index) => paged.values.historyTurnBase + index)).toEqual(
+ shown.filter(isHuman).map((item) => fullTurns.get(item.id))
+ )
+ expect([
+ paged.values.currentMode,
+ paged.values.contextUsage,
+ paged.values.pendingPermissionRequest,
+ ]).toEqual([
+ full.values.currentMode,
+ full.values.contextUsage,
+ full.values.pendingPermissionRequest,
+ ])
+ if (paged.values.olderHistoryState !== 'idle') {
+ break
+ }
+ const notebookThread = await readFullThread('paged-read')
+ expect(notebookThread?.threadItems).toEqual(fullItems)
+ paged.actions.loadOlderHistory()
+ await flushPromises()
+ }
+ expect([paged.values.olderHistoryState, paged.values.threadItems]).toEqual(['none', fullItems])
+ expect(readFullThread('paged-read')).toBeNull()
+ } finally {
+ full.unmount()
+ paged.unmount()
+ }
+ }
+ )
+
+ it('loads an older page in front of the thread without changing the rows, sends or mode it already shows', async () => {
+ const mode = (modeId: string, eventId: string): StoredLogEntry => ({
+ ...sessionUpdate({ sessionUpdate: 'current_mode_update', currentModeId: modeId }),
+ event_id: eventId,
+ })
+ jest.spyOn(api.tasks.runs, 'getLogPage').mockImplementation(async (_taskId, _runId, options) =>
+ options.before === undefined
+ ? page(
+ [
+ notification('_posthog/run_started', { runId: 'run-1' }),
+ mode('plan', 'b-3m'),
+ turn('latest question', 'b-3'),
+ reply('latest answer', 'b-4'),
+ ],
+ 3,
+ 5,
+ 1,
+ 1
+ )
+ : page([mode('default', 'b-0m'), turn('older question', 'b-1'), reply('older answer', 'b-2')], 0, 5)
+ )
+
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', pagedHistory: true })
+ await flushPromises()
+ await MockStream.latest().emitOpen()
+ await MockStream.latest().emitMessage(reply('stale backlog', 'b-1x'), 'log-0')
+ await MockStream.latest().emitMessage(reply('live answer', 'b-5'), 'b-5')
+ logic.actions.pushHumanMessage('older question')
+ const shown = logic.values.threadItems.map((item) => item.id)
+ expect([logic.values.olderHistoryState, logic.values.historyTurnBase]).toEqual(['idle', 1])
+
+ const dispatched: string[] = []
+ const store = getContext().store
+ const dispatch = store.dispatch
+ store.dispatch = ((action: { type: string }) => {
+ dispatched.push(action.type)
+ return dispatch(action)
+ }) as typeof store.dispatch
+ try {
+ logic.actions.loadOlderHistory()
+ await flushPromises()
+ } finally {
+ store.dispatch = dispatch
+ }
+
+ expect(dispatched).not.toContain(logic.actionTypes.setCurrentMode)
+ expect(texts(logic.values.threadItems)).toEqual([
+ 'older question',
+ 'older answer',
+ 'latest question',
+ 'latest answer',
+ 'live answer',
+ 'older question',
+ ])
+ expect(logic.values.threadItems.slice(-shown.length).map((item) => item.id)).toEqual(shown)
+ expect([logic.values.olderHistoryState, logic.values.historyTurnBase, logic.values.currentMode]).toEqual([
+ 'none',
+ 0,
+ 'plan',
+ ])
+ })
+
+ it('reads only the entries after the loaded log when the stream reconnects', async () => {
+ jest.useFakeTimers()
+ try {
+ const started = notification('_posthog/run_started', { runId: 'run-1' })
+ const reads: string[] = []
+ const pages: Record<string, HistoryPage> = {
+ latest: page([started, turn('b', 'e-3'), reply('b', 'e-4')], 3, 5, 1, 1),
+ 'before:3': page([started, turn('a', 'e-1'), reply('a', 'e-2')], 0, 5),
+ 'start:5': page(
+ [
+ reply('c', 'e-5'),
+ { ...notification('_posthog/user_message', { content: 'd' }), event_id: 'e-6' },
+ turn('d', 'e-7'),
+ ],
+ 5,
+ 8
+ ),
+ }
+ jest.spyOn(api.tasks.runs, 'getLogPage').mockImplementation(async (_taskId, _runId, options) => {
+ const key =
+ options.start !== undefined
+ ? `start:${options.start}`
+ : options.before !== undefined
+ ? `before:${options.before}`
+ : 'latest'
+ reads.push(key)
+ return pages[key]
+ })
+
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', pagedHistory: true })
+ await flushPromises()
+ await MockStream.latest().emitOpen()
+ logic.actions.loadOlderHistory()
+ await flushPromises()
+ await MockStream.latest().emitMessage(reply('c', 'e-5'), '105-0')
+ logic.actions.pushHumanMessage('d')
+ const sent = logic.values.threadItems.findLast(isHuman)?.id
+ await MockStream.latest().emitClose()
+ await jest.advanceTimersByTimeAsync(SSE_RECONNECT_BASE_DELAY_MS)
+ await MockStream.latest().emitMessage(reply('b', 'e-4'), '104-0')
+ await MockStream.latest().emitOpen()
+
+ expect(reads).toEqual(['latest', 'before:3', 'start:5'])
+ expect(texts(logic.values.threadItems)).toEqual(['a', 'a', 'b', 'b', 'c', 'd'])
+ expect(logic.values.threadItems.findLast(isHuman)?.id).toEqual(sent)
+ expect(logic.values.olderHistoryState).toEqual('none')
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('shows a live answer once when an older page also holds it', async () => {
+ jest.useFakeTimers()
+ try {
+ const started = notification('_posthog/run_started', { runId: 'run-1' })
+ jest.spyOn(api.tasks.runs, 'getLogPage').mockImplementation(async (_taskId, _runId, options) =>
+ options.before === undefined
+ ? page([started, turn('b', 'e-3'), reply('b', 'e-4')], 3, 5, 1, 1)
+ : page([started, turn('a', 'e-1'), reply('a', 'e-2')], 0, 5)
+ )
+ logic.actions.bootstrapRun({
+ taskId: 'task-1',
+ runId: 'run-1',
+ justCreatedRun: true,
+ pagedHistory: true,
+ })
+ await flushPromises()
+ await MockStream.latest().emitMessage(turn('a', 'e-1'), '101-0')
+ await MockStream.latest().emitMessage(reply('a', 'e-2'), '102-0')
+ await MockStream.latest().emitClose()
+ await jest.advanceTimersByTimeAsync(SSE_RECONNECT_BASE_DELAY_MS)
+ await MockStream.latest().emitOpen()
+ logic.actions.loadOlderHistory()
+ await jest.advanceTimersByTimeAsync(0)
+
+ expect(texts(logic.values.threadItems)).toEqual(['a', 'a', 'b', 'b'])
+ const ids = logic.values.threadItems.map((item) => item.id)
+ expect(new Set(ids).size).toEqual(ids.length)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('reads the latest turns again when the chain no longer starts at the same run', async () => {
+ jest.useFakeTimers()
+ try {
+ const started = notification('_posthog/run_started', { runId: 'run-1' })
+ const reads: string[] = []
+ jest.spyOn(api.tasks.runs, 'getLogPage').mockImplementation(async (_taskId, _runId, options) => {
+ reads.push(
+ options.start !== undefined
+ ? `start:${options.start}`
+ : options.before !== undefined
+ ? `before:${options.before}`
+ : 'latest'
+ )
+ return reads.length === 1
+ ? page([started, turn('b', 'e-3'), reply('b', 'e-4')], 3, 5, 1, 1)
+ : page([started, turn('b', 'e-3'), reply('b', 'e-4'), reply('c', 'e-5')], 2, 5, 1, 1, 'run-0')
+ })
+
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', pagedHistory: true })
+ await flushPromises()
+ await MockStream.latest().emitOpen()
+ await MockStream.latest().emitClose()
+ await jest.advanceTimersByTimeAsync(SSE_RECONNECT_BASE_DELAY_MS)
+ await MockStream.latest().emitOpen()
+
+ expect(reads).toEqual(['latest', 'before:3', 'start:5', 'latest'])
+ expect(texts(logic.values.threadItems)).toEqual(['b', 'b', 'c'])
+ expect(logic.values.olderHistoryState).toEqual('idle')
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('finishes an older page that loads while a finished run continues in a successor', async () => {
+ const started = notification('_posthog/run_started', { runId: 'run-1' })
+ let release: (older: HistoryPage) => void = () => {}
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed', state: {} } as TaskRunDetailDTOApi)
+ jest.spyOn(api.tasks.runs, 'getLogPage').mockImplementation((_taskId, _runId, options) =>
+ options.before === undefined
+ ? Promise.resolve(page([started, turn('b', 'e-3'), reply('b', 'e-4')], 3, 5, 1, 1))
+ : new Promise((resolve) => {
+ release = resolve
+ })
+ )
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', pagedHistory: true })
+ await flushPromises()
+ logic.actions.loadOlderHistory()
+ await flushPromises()
+
+ logic.actions.startOptimisticResume('continue')
+ logic.actions.attachOptimisticResume('task-1', {
+ id: 'run-2',
+ status: 'queued',
+ state: { resume_from_run_id: 'run-1' },
+ } as unknown as TaskRunDetailDTOApi)
+ release(page([started, turn('a', 'e-1'), reply('a', 'e-2')], 0, 5))
+ await flushPromises()
+
+ expect(logic.values.olderHistoryState).toEqual('none')
+ expect(texts(logic.values.threadItems)).toEqual(['a', 'a', 'b', 'b', 'continue'])
+ })
+ })
+
describe('_posthog/usage_update handling', () => {
it('folds the Codex split frames (used + cost, then breakdown) into contextUsage', async () => {
await expectLogic(logic, () => {
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index dcd2d1b6a741..a533466b05b6 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -20,6 +20,7 @@ import type { AgentConversationEvent } from '@posthog/agent-contracts/agent-conv
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { uuid } from 'lib/utils/dom'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { projectLogic } from 'scenes/projectLogic'
import { userLogic } from 'scenes/userLogic'
@@ -580,11 +581,121 @@ function isResumeRun(run: { state?: unknown }): boolean {
return isRecord(state) && typeof state.resume_from_run_id === 'string' && state.resume_from_run_id !== ''
}
-function normalizeHistory(entries: unknown[], runId: string, resumed: boolean): StoredLogEntry[] {
+/** Bytes of the latest turns a chat reads first; older turns load in pages of `HISTORY_PAGE_BYTES`. */
+const HISTORY_TAIL_BYTES = 1_000_000
+const HISTORY_PAGE_BYTES = 2_000_000
+/** Wait after the latest turns render before the next older page preloads, so it never competes with the open. */
+const OLDER_HISTORY_PRELOAD_DELAY_MS = 1_500
+/** Backoff after an older page fails to load, doubled per failure, and the failures before loading stops. */
+const OLDER_HISTORY_RETRY_DELAY_MS = 5_000
+const OLDER_HISTORY_MAX_FAILURES = 3
+
+export type OlderHistoryState = 'none' | 'idle' | 'loading'
+
+export interface HistoryPage {
+ entries: Record<string, any>[]
+ offset: number
+ count: number
+ preamble: number
+ turnsBefore: number
+ /** The first run of the chain the indexes count from; a chain keeps a limited number of runs. */
+ origin: string
+ /** False for a full log sent without paging headers: its entries carry no full-log index. */
+ indexed: boolean
+}
+
+/**
+ * Where the loaded log starts in the run's resume-chain log. `offset` is the full-log index of the first loaded entry
+ * after the preamble, and `turnsBefore` counts the user turns before it, so turns keep the numbers the full log gives
+ * them. The client log is always the preamble of `offset`, then every entry from `offset` on, then live entries.
+ */
+export interface HistoryCursor {
+ runId: string
+ origin: string
+ offset: number
+ turnsBefore: number
+}
+
+/** Stream backlog entries (`log-N` frames) by their full-log index. */
+const backlogIndexes = new WeakMap<StoredLogEntry, number>()
+
+/** Whether a stream backlog entry is already in the loaded log, or in an older page before it. */
+function isLoadedBacklog(entry: StoredLogEntry, loadedEnd: number | undefined): boolean {
+ const index = backlogIndexes.get(entry)
+ return index !== undefined && loadedEnd !== undefined && index < loadedEnd
+}
+
+/** The synthetic preamble entry that carries the context-block messages from before a page's cut. */
+const CONTEXT_HISTORY_METHOD = '_posthog/context_history'
+
+function contextHistoryLines(params: Record<string, unknown> | undefined): string[] {
+ const messages = params?.messages
+ return Array.isArray(messages)
+ ? messages.flatMap((message) => (typeof message === 'string' ? contextBlockLinesFromUserMessage(message) : []))
+ : []
+}
+
+/** Entries a page carried in its preamble: state from before the page, not entries at their own position. */
+const historyPreambles = new WeakSet<StoredLogEntry>()
+
+/**
+ * Put an older page in front of the log. The page's preamble replaces the preamble at the head of the log, so the log
+ * stays what a read from the page's cut returns. Nothing replays: the latest page already set the current state.
+ */
+function prependHistoryPage(log: RunLog, page: StoredLogEntry[]): RunLog {
+ // A stream that started without a history read keeps live entries the page can also hold; the saved copy
+ // at its own position wins.
+ const coverage = new RunEventCoverage(page)
+ return appendToRunLog(emptyRunLog(), [
+ ...page.map((entry): StoredEntry => ({ entry, source: 'replay' })),
+ ...log.entries.filter(
+ ({ entry, source }) =>
+ !historyPreambles.has(entry) && !(source === 'live' && !!entry.event_id && coverage.covers(entry))
+ ),
+ ])
+}
+
+/** The context-block lines of the user messages in an older page, which the send paths dedupe against. */
+function historyContextLines(entries: StoredLogEntry[]): string[] {
+ return entries.flatMap(({ notification }) => {
+ if (notification.method === CONTEXT_HISTORY_METHOD) {
+ return contextHistoryLines(notification.params)
+ }
+ if (notification.method === '_posthog/user_message') {
+ const content = notification.params?.content
+ if (Array.isArray(content) && content.length > 0 && content.every(isHiddenUserContent)) {
+ return []
+ }
+ return contextBlockLinesFromUserMessage(extractUserMessageText(content))
+ }
+ const update = notification.params?.update
+ if (
+ notification.method === 'session/update' &&
+ isSessionUpdateUserMessage(update) &&
+ update.sessionUpdate === 'user_message' &&
+ !isHiddenUserContent(update.content)
+ ) {
+ return contextBlockLinesFromUserMessage(String(update.content?.text ?? update.text ?? ''))
+ }
+ return []
+ })
+}
+
+/**
+ * `preamble` counts the leading entries that came in a page's preamble. `sourceRunId` names the run that owns the
+ * entries before the first run marker, for a read that continues a loaded log.
+ */
+function normalizeHistory(
+ entries: unknown[],
+ runId: string,
+ resumed: boolean,
+ preamble = 0,
+ sourceRunId?: string
+): StoredLogEntry[] {
// Match Desktop's run-marker scoping without changing the shared log payload or its deduplication keys.
// A resume chain without a marker has unknown ownership; a single-run history belongs to its requested run.
- let sourceRunId: string | undefined = resumed ? undefined : runId
- return entries.flatMap((raw) => {
+ let source: string | undefined = sourceRunId ?? (resumed ? undefined : runId)
+ return entries.flatMap((raw, index) => {
const entry = normalizeNotificationEntry(raw)
if (!entry) {
return []
@@ -597,9 +708,13 @@ function normalizeHistory(entries: unknown[], runId: string, resumed: boolean):
? params?.runId
: undefined
if (typeof marker === 'string') {
- sourceRunId = marker
+ source = marker
}
- return [{ ...entry, source_run_id: sourceRunId }]
+ const normalized = { ...entry, source_run_id: source }
+ if (index < preamble) {
+ historyPreambles.add(normalized)
+ }
+ return [normalized]
})
}
@@ -1399,6 +1514,49 @@ function retainedFramesWithoutOptimisticEchoes(retained: StoredEntry[]): StoredL
* is the one echo no persisted copy covers yet, matched by identity because the same words can
* arrive several times.
*/
+/**
+ * Row keys of optimistic sends, by the saved message that replaced them (`run:event_id`), so the row keeps the
+ * key it rendered with and the thread does not read the saved message as a new anchor.
+ */
+const sentHumanRowKeys = new Map<string, string>()
+
+function savedEntryKey(entry: StoredLogEntry): string | null {
+ return entry.event_id ? `${entry.source_run_id ?? ''}:${entry.event_id}` : null
+}
+
+/**
+ * The thread of the full conversation for a stream whose older history is not all loaded: the full log, with the
+ * stream's live and client entries after it. Null when the stream already holds its full history, so a caller
+ * that needs no read does not wait.
+ */
+export function readFullThread(
+ streamKey: string
+): Promise<{ threadItems: ThreadItem[]; toolInvocations: Map<string, ToolInvocation> }> | null {
+ const logic = runStreamLogic.findMounted({ streamKey })
+ const cursor = logic?.cache.historyCursor as HistoryCursor | undefined
+ const taskId = logic?.values.bootstrappedTaskId
+ const projectId = logic?.values.currentProjectId
+ if (!logic || !cursor || cursor.offset === 0 || !taskId || projectId == null) {
+ return null
+ }
+ return api.tasks.runs.getLogPage(taskId, cursor.runId, { projectId }).then((page) => {
+ const history = normalizeHistory(page.entries, cursor.runId, logic.values.isBootstrapResumeRun)
+ const tail = logic.values.log.entries.filter(({ source }) => source !== 'replay')
+ const folded = foldLogToThread(reconcileRunLog(history, tail, []).entries, {
+ isResumeRun: logic.values.isBootstrapResumeRun,
+ pendingMessage: logic.values.pendingRunMessage,
+ taskId,
+ })
+ const showDebugLogs = logic.values.showDebugLogs
+ return {
+ threadItems: folded.threadItems.filter(
+ (item) => (item.type !== 'debug' || showDebugLogs) && rendersThreadItemContent(item)
+ ),
+ toolInvocations: folded.toolInvocations,
+ }
+ })
+}
+
export function reconcileRunLog(
history: StoredLogEntry[],
retained: StoredEntry[],
@@ -1408,6 +1566,8 @@ export function reconcileRunLog(
let entries: StoredEntry[] = history.map((entry) => ({ entry, source: 'replay' }))
const coverage = new RunEventCoverage(history)
const savedHumanCounts = new Map<string, number>()
+ const savedHumanEntries = new Map<string, StoredLogEntry[]>()
+ const matchedSendIds = new Map<string, (string | undefined)[]>()
const rememberedHumanTexts = new Map<string, number>()
for (const entry of dedupeBufferedAgainstHistory(history, retainedFramesWithoutOptimisticEchoes(retained))) {
const text = persistedHumanText(entry)
@@ -1424,6 +1584,7 @@ export function reconcileRunLog(
}
}
savedHumanCounts.set(text, (savedHumanCounts.get(text) ?? 0) + 1)
+ savedHumanEntries.set(text, [...(savedHumanEntries.get(text) ?? []), entry])
}
for (const [tailIndex, tail] of [
retained,
@@ -1442,6 +1603,11 @@ export function reconcileRunLog(
const saved = savedHumanCounts.get(text) ?? 0
if (saved > 0) {
savedHumanCounts.set(text, saved - 1)
+ const clientId = entry.notification.params?.clientId
+ matchedSendIds.set(text, [
+ ...(matchedSendIds.get(text) ?? []),
+ typeof clientId === 'string' ? clientId : undefined,
+ ])
continue
}
}
@@ -1483,6 +1649,16 @@ export function reconcileRunLog(
}
}
}
+ // The sends that matched are the latest saved messages of their text, in order.
+ for (const [text, sendIds] of matchedSendIds) {
+ const saved = (savedHumanEntries.get(text) ?? []).slice(-sendIds.length)
+ sendIds.forEach((clientId, index) => {
+ const key = saved[index] ? savedEntryKey(saved[index]) : null
+ if (clientId && key && !sentHumanRowKeys.has(key)) {
+ sentHumanRowKeys.set(key, `client-${clientId}`)
+ }
+ })
+ }
return appendToRunLog(emptyRunLog(), entries)
}
@@ -1740,6 +1916,11 @@ export function foldLogFromCheckpoint(
let timestamp: number | undefined
let importedRun = resume?.importedRun ?? false
let entryRunId: string | undefined
+ // The agent's `event_id` of the entry being folded. Ids built from it stay the same when older history
+ // loads in front of the log, where the per-type counters behind the fallback ids would shift.
+ let entryKey: string | undefined
+ const seqId = (prefix: string, seq: number): string => (entryKey ? `${prefix}@${entryKey}` : `${prefix}-${seq}`)
+ const bubbleId = (id: string, seq: number): string => `${id}@${entryKey ?? seq}`
let pendingMessageSeen = resume?.pendingMessageSeen ?? false
let pendingInsertionIndex: number | undefined = resume?.pendingInsertionIndex
let bufferedAttachments: ThreadAttachment[] = resume ? [...resume.bufferedAttachments] : []
@@ -1759,7 +1940,7 @@ export function foldLogFromCheckpoint(
}
const carried = [...attachments, ...bufferedAttachments]
const item: ThreadItem = {
- id: placement.reuseId ?? `human-${humanCount++}`,
+ id: placement.reuseId ?? seqId('human', humanCount++),
type: 'human_message',
text,
complete: true,
@@ -1853,7 +2034,7 @@ export function foldLogFromCheckpoint(
openAssistantMessages++
}
items.push({
- id: `${id}@${bubbleSeq++}`,
+ id: bubbleId(id, bubbleSeq++),
type,
text: delta,
complete: false,
@@ -1892,7 +2073,7 @@ export function foldLogFromCheckpoint(
// arrives alone). Push a fresh bubble with a unique id — a bare fallback id would collide
// as a React key with every other no-`messageId` message in the thread.
items.push({
- id: `${id}@${bubbleSeq++}`,
+ id: bubbleId(id, bubbleSeq++),
type: 'assistant_message',
text,
complete: true,
@@ -2038,7 +2219,7 @@ export function foldLogFromCheckpoint(
items.splice(undeliveredIdx, 1)
}
items.push({
- id: `error-${errorSeq++}`,
+ id: seqId('error', errorSeq++),
type: 'error',
errorMessage: message,
variant,
@@ -2049,6 +2230,16 @@ export function foldLogFromCheckpoint(
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
+ const clientId = entry.notification.params?.clientId
+ // A saved message that replaces its streamed chunks keeps the first chunk's id, so its row keeps its key.
+ const savedKey = savedEntryKey(entry)
+ const eventKey = (savedKey && sentHumanRowKeys.get(savedKey)) || entry.first_event_id || entry.event_id
+ entryKey =
+ typeof eventKey === 'string' && eventKey
+ ? eventKey
+ : entry.notification.method === '_client/human_message' && typeof clientId === 'string'
+ ? `client-${clientId}`
+ : undefined
if (
options.pendingMessage &&
entryRunId === options.pendingMessage.runId &&
@@ -2074,7 +2265,7 @@ export function foldLogFromCheckpoint(
}
if (method === '_client/error') {
items.push({
- id: `error-${errorSeq++}`,
+ id: seqId('error', errorSeq++),
type: 'error',
errorMessage: String(params.message ?? ''),
variant: params.variant === 'crash' ? 'crash' : 'error',
@@ -2112,7 +2303,7 @@ export function foldLogFromCheckpoint(
})
}
items.push({
- id: `turn-${separatorSeq++}`,
+ id: seqId('turn', separatorSeq++),
type: 'turn_separator',
...(traceId && { traceId }),
...(timestamp !== undefined && { startedAt: timestamp }),
@@ -2142,7 +2333,7 @@ export function foldLogFromCheckpoint(
items[items.length - 1] = { ...last, undeliveredMessage: true }
} else {
items.push({
- id: `error-${errorSeq++}`,
+ id: seqId('error', errorSeq++),
type: 'error',
errorMessage: stringifyOptional(params.detail) ?? label ?? 'Message not delivered',
variant: 'undelivered',
@@ -2194,7 +2385,7 @@ export function foldLogFromCheckpoint(
(item) => !isPendingStatus(item, status === 'clearing_failed' ? 'clearing' : 'compacting')
)
items.push({
- id: `status-${statusSeq++}`,
+ id: seqId('status', statusSeq++),
type: 'status',
status,
isComplete: true,
@@ -2202,21 +2393,21 @@ export function foldLogFromCheckpoint(
})
} else if (status === 'extension_notice') {
items.push({
- id: `status-${statusSeq++}`,
+ id: seqId('status', statusSeq++),
type: 'status',
status,
isComplete: true,
message: stringifyOptional(params.message),
})
} else {
- items.push({ id: `status-${statusSeq++}`, type: 'status', status, isComplete })
+ items.push({ id: seqId('status', statusSeq++), type: 'status', status, isComplete })
}
continue
}
if (method === '_posthog/compact_boundary') {
items = items.filter((item) => !isPendingStatus(item, 'compacting'))
items.push({
- id: `compact-${compactSeq++}`,
+ id: seqId('compact', compactSeq++),
type: 'compact_boundary',
trigger: stringifyOptional(params.trigger),
preTokens: typeof params.preTokens === 'number' ? params.preTokens : undefined,
@@ -2228,12 +2419,12 @@ export function foldLogFromCheckpoint(
// The divider supersedes the spinner visually, but the completing `_posthog/status`
// frame is a separate notification that may not have landed yet.
items = items.filter((item) => !isPendingStatus(item, 'clearing'))
- items.push({ id: `cleared-${clearedSeq++}`, type: 'conversation_cleared' })
+ items.push({ id: seqId('cleared', clearedSeq++), type: 'conversation_cleared' })
continue
}
if (method === '_posthog/task_notification') {
items.push({
- id: `task-${taskSeq++}`,
+ id: seqId('task', taskSeq++),
type: 'task_notification',
status: stringifyOptional(params.status),
summary: stringifyOptional(params.summary),
@@ -2266,7 +2457,7 @@ export function foldLogFromCheckpoint(
const level = typeof params.level === 'string' ? params.level : 'info'
if (message) {
items.push({
- id: `console-${consoleSeq++}`,
+ id: seqId('console', consoleSeq++),
type: 'debug',
text: message,
debugLevel: level,
@@ -2422,11 +2613,14 @@ export interface runStreamLogicValues {
hasGitArtifacts: boolean
hasThreadItems: boolean
historyComplete: boolean
+ historyTurnBase: number
isBootstrapResumeRun: boolean
isThinking: boolean
latestTurnTraceId: string | null
log: RunLog
logBootstrapLoading: boolean
+ olderHistoryState: OlderHistoryState
+ pagedHistory: boolean
pendingPermissionRequest: PermissionRequestRecord | null
pendingRunMessage: PendingRunMessage | null
permissionResponseRequestIds: Set<string>
@@ -2506,6 +2700,8 @@ export interface runStreamLogicActions {
}
bootstrapRun: (payload: {
justCreatedRun?: boolean
+ /** Read the latest turns first and load older turns in pages, for a thread that can show them. */
+ pagedHistory?: boolean
retainedMessage?: string
runId: string
taskId: string
@@ -2513,6 +2709,7 @@ export interface runStreamLogicActions {
traceId?: string
}) => {
justCreatedRun?: boolean | undefined
+ pagedHistory?: boolean | undefined
retainedMessage?: string | undefined
runId: string
taskId: string
@@ -2573,6 +2770,9 @@ export interface runStreamLogicActions {
record: PermissionRequestRecord
replayedFromHistory: boolean
}
+ loadOlderHistory: () => {
+ value: true
+ }
loadTurnSuggestionLedger: (
taskId: string,
attempt?: number
@@ -2709,6 +2909,12 @@ export interface runStreamLogicActions {
setHistoryComplete: (complete: boolean) => {
complete: boolean
}
+ setHistoryTurnBase: (base: number) => {
+ base: number
+ }
+ setOlderHistoryState: (state: OlderHistoryState) => {
+ state: OlderHistoryState
+ }
setPendingRunMessage: (message: PendingRunMessage | null) => {
message: PendingRunMessage | null
}
@@ -2782,7 +2988,8 @@ export interface runStreamLogicMeta {
turnSuggestionOutcomesHere: Record<number, string>,
turnSuggestionAcceptedHere: number | null,
turnSuggestionsMuted: boolean,
- bootstrappedTaskId: string | null
+ bootstrappedTaskId: string | null,
+ historyTurnBase: number
) => TurnSuggestion | null
latestTurnTraceId: (threadItems: ThreadItem[]) => string | null
threadItems: (foldedThread: FoldedThread, showDebugLogs: boolean) => ThreadItem[]
@@ -2878,6 +3085,9 @@ export const runStreamLogic = kea<runStreamLogicType>([
resetRecoveryBudget: true,
recoveryRunChanged: true,
setHistoryComplete: (complete: boolean) => ({ complete }),
+ setOlderHistoryState: (state: OlderHistoryState) => ({ state }),
+ setHistoryTurnBase: (base: number) => ({ base }),
+ loadOlderHistory: true,
setStreamHasEnded: (ended: boolean) => ({ ended }),
recoveryProgress: (phase: RecoveryPhase, attempt: number, maxAttempts: number) => ({
phase,
@@ -2898,6 +3108,8 @@ export const runStreamLogic = kea<runStreamLogicType>([
traceId?: string
retainedMessage?: string
taskRuntime?: string | null
+ /** Read the latest turns first and load older turns in pages, for a thread that can show them. */
+ pagedHistory?: boolean
}) => payload,
openSseForRun: (payload: { taskId: string; runId: string; startLatest?: boolean; traceId?: string }) => payload,
/**
@@ -3076,6 +3288,27 @@ export const runStreamLogic = kea<runStreamLogicType>([
reset: () => false,
},
],
+ historyTurnBase: [
+ 0,
+ {
+ setHistoryTurnBase: (_, { base }) => base,
+ reset: () => 0,
+ },
+ ],
+ olderHistoryState: [
+ 'none' as OlderHistoryState,
+ {
+ setOlderHistoryState: (_, { state }) => state,
+ reset: () => 'none' as OlderHistoryState,
+ },
+ ],
+ pagedHistory: [
+ false,
+ {
+ bootstrapRun: (state, { pagedHistory }) => pagedHistory ?? state,
+ reset: () => false,
+ },
+ ],
streamHasEnded: [
false,
{
@@ -3570,6 +3803,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
s.turnSuggestionAcceptedHere,
s.turnSuggestionsMuted,
s.bootstrappedTaskId,
+ s.historyTurnBase,
],
(
foldedThread: FoldedThread,
@@ -3578,12 +3812,14 @@ export const runStreamLogic = kea<runStreamLogicType>([
outcomesHere: Record<number, string>,
acceptedHere: number | null,
muted: boolean,
- taskId: string | null
+ taskId: string | null,
+ historyTurnBase: number
): TurnSuggestion | null => {
const offer = foldedThread.turnSuggestions.latest
// The classifier runs after the answer, so an offer can land once the user already sent
// the next message; it belongs to the answer above it and closes when the thread moves on.
- const latestPromptIndex = threadItems.filter((item) => item.type === 'human_message').length - 1
+ const latestPromptIndex =
+ historyTurnBase + threadItems.filter((item) => item.type === 'human_message').length - 1
if (!offer || offer.turnIndex !== latestPromptIndex) {
return null
}
@@ -3911,13 +4147,30 @@ export const runStreamLogic = kea<runStreamLogicType>([
cache.recoveryStartedAt = undefined
}
}
+ /** The latest turns of a paged log, or every entry from `start` on; the full log when the log is not paged. */
+ const readHistory = (session: RunStreamRecovery, signal: AbortSignal, start?: number): Promise<HistoryPage> =>
+ api.tasks.runs.getLogPage(session.taskId, session.runId, {
+ signal,
+ projectId: session.projectId,
+ ...(values.pagedHistory ? { tailBytes: HISTORY_TAIL_BYTES, start } : {}),
+ })
+ const stopHistoryPaging = (): void => {
+ cache.disposables.dispose('older-history-request')
+ cache.disposables.dispose('older-history-retry')
+ cache.disposables.dispose('older-history-preload')
+ cache.olderHistoryRequest = undefined
+ cache.olderHistoryFailures = 0
+ }
+ const setHistoryCursor = (cursor: HistoryCursor | undefined): void => {
+ stopHistoryPaging()
+ cache.historyCursor = cursor
+ actions.setHistoryTurnBase(cursor?.turnsBefore ?? 0)
+ actions.setOlderHistoryState(cursor && cursor.offset > 0 ? 'idle' : 'none')
+ }
const startHistoryPrefetch = (session: RunStreamRecovery): void => {
dropHistoryPrefetch()
const controller = new AbortController()
- const entries = api.tasks.runs.getLogEntries(session.taskId, session.runId, {
- signal: controller.signal,
- projectId: session.projectId,
- })
+ const entries = readHistory(session, controller.signal)
entries.catch(() => {})
cache.disposables.add(() => () => controller.abort(), 'history-prefetch', { pauseOnPageHidden: false })
cache.historyPrefetch = {
@@ -3927,9 +4180,9 @@ export const runStreamLogic = kea<runStreamLogicType>([
entries,
}
}
- const takeHistoryPrefetch = (session: RunStreamRecovery): Promise<Record<string, any>[]> | undefined => {
+ const takeHistoryPrefetch = (session: RunStreamRecovery): Promise<HistoryPage> | undefined => {
const prefetch = cache.historyPrefetch as
- | { projectId: number; taskId: string; runId: string; entries: Promise<Record<string, any>[]> }
+ | { projectId: number; taskId: string; runId: string; entries: Promise<HistoryPage> }
| undefined
cache.historyPrefetch = undefined
if (
@@ -3945,74 +4198,22 @@ export const runStreamLogic = kea<runStreamLogicType>([
}
return prefetch.entries
}
- const reconcileHistory = async (session: RunStreamRecovery): Promise<void> => {
- const turnCompleteBeforeReconcile = values.turnComplete
- const recoveringLiveTurn = session.phase === 'history' || session.phase === 'stream'
- if (session.phase !== 'finalization') {
- session.phase = 'history'
- }
- let prefetched = takeHistoryPrefetch(session)
- const entries = await readWithRetry(session, () =>
- session.request(STREAM_HISTORY_TIMEOUT_MS, (signal) => {
- const pending = prefetched
- prefetched = undefined
- if (pending) {
- signal.addEventListener('abort', () => cache.disposables.dispose('history-prefetch'), {
- once: true,
- })
- return pending
- }
- return api.tasks.runs.getLogEntries(session.taskId, session.runId, {
- signal,
- projectId: session.projectId,
- })
- })
- )
- session.check()
- // Django log-N cursors index the same object entries, including non-notification records.
- entries.filter(isRecord).forEach((raw, index) => {
- const entry = normalizeNotificationEntry(raw)
- if (entry && !entry.event_id) {
- session.legacyBacklog.set(`log-${index}`, entry)
- }
- })
- const history = normalizeHistory(entries, session.runId, values.isBootstrapResumeRun)
- const echo = cache.retainedMessage
- ? values.log.entries.findLast(
- ({ entry }) =>
- entry.notification.method === '_client/human_message' &&
- entry.notification.params?.content === cache.retainedMessage
- )
- : undefined
- const echoPersisted =
- !!echo &&
- history.some(
- (entry) =>
- entry.source_run_id === session.runId && persistedHumanText(entry) === cache.retainedMessage
- )
- const retained = echoPersisted ? values.log.entries.filter((stored) => stored !== echo) : values.log.entries
- const log = reconcileRunLog(history, retained, session.buffer, echoPersisted ? undefined : echo)
- const bufferedEntries = new Set(session.buffer)
- const bufferedIds = new Set(session.buffer.flatMap((entry) => (entry.event_id ? [entry.event_id] : [])))
+ const replayRunLog = (log: RunLog, runId: string, isLiveFrame: (stored: StoredEntry) => boolean): void => {
// Rebuild state without publishing a partial transcript or repeating live reactions.
cache.rebuildingHistory = true
- cache.coalesceContextUsage = true
+ cache.coalesceReplay = true
cache.rebuildingLog = log
cache.trackedToolInvocations = undefined
try {
let reachedSuccessor = false
for (const stored of log.entries) {
- if (cache.retainedMessage && !reachedSuccessor && stored.entry.source_run_id === session.runId) {
+ if (cache.retainedMessage && !reachedSuccessor && stored.entry.source_run_id === runId) {
actions.prepareResumeRun()
reachedSuccessor = true
}
if (stored.entry.notification.method === '_client/human_message') {
actions.markTurnStarted()
- } else if (
- stored.source === 'live' &&
- (bufferedEntries.has(stored.entry) ||
- (stored.entry.event_id && bufferedIds.has(stored.entry.event_id)))
- ) {
+ } else if (isLiveFrame(stored)) {
actions.ingestAcpFrame(stored.entry, 'live')
} else if (stored.source !== 'client') {
ingestFrame(stored.entry, 'replay')
@@ -4023,7 +4224,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
}
} finally {
cache.rebuildingHistory = false
- cache.coalesceContextUsage = false
+ cache.coalesceReplay = false
cache.rebuildingLog = undefined
const replayContextUsage = cache.replayContextUsage as ContextUsage | undefined
cache.replayContextUsage = undefined
@@ -4031,9 +4232,116 @@ export const runStreamLogic = kea<runStreamLogicType>([
actions.setContextUsage(replayContextUsage)
}
}
+ }
+ const rememberLegacyBacklog = (session: RunStreamRecovery, entries: unknown[], offset: number): void => {
+ // Django log-N cursors index the same object entries, including non-notification records.
+ entries.filter(isRecord).forEach((raw, index) => {
+ const entry = normalizeNotificationEntry(raw)
+ if (entry && !entry.event_id) {
+ session.legacyBacklog.set(`log-${offset + index}`, entry)
+ }
+ })
+ }
+ const reconcileHistory = async (session: RunStreamRecovery): Promise<void> => {
+ const turnCompleteBeforeReconcile = values.turnComplete
+ const recoveringLiveTurn = session.phase === 'history' || session.phase === 'stream'
+ if (session.phase !== 'finalization') {
+ session.phase = 'history'
+ }
+ // A log this run already loaded needs only the entries after it, so the pages above the reader stay.
+ const cursor = cache.historyCursor as HistoryCursor | undefined
+ const loadedEnd =
+ values.pagedHistory && cursor?.runId === session.runId
+ ? (cache.historyEnd as number | undefined)
+ : undefined
+ let prefetched = loadedEnd === undefined ? takeHistoryPrefetch(session) : undefined
+ if (loadedEnd !== undefined) {
+ dropHistoryPrefetch()
+ }
+ const read = (start?: number): Promise<HistoryPage> =>
+ readWithRetry(session, () =>
+ session.request(STREAM_HISTORY_TIMEOUT_MS, (signal) => {
+ const pending = prefetched
+ prefetched = undefined
+ if (pending) {
+ signal.addEventListener('abort', () => cache.disposables.dispose('history-prefetch'), {
+ once: true,
+ })
+ return pending
+ }
+ return readHistory(session, signal, start)
+ })
+ )
+ let page = await read(loadedEnd)
+ session.check()
+ if (loadedEnd !== undefined && page.indexed && page.origin !== cursor?.origin) {
+ // The chain dropped its oldest run, so the loaded indexes no longer match: read the latest turns again.
+ page = await read()
+ session.check()
+ }
+ const continues =
+ loadedEnd !== undefined && page.indexed && page.origin === cursor?.origin && page.offset === loadedEnd
+ rememberLegacyBacklog(session, page.entries.slice(page.preamble), page.offset)
+ if (page.indexed) {
+ // A stream backlog replays the run log from its start; the read already holds everything before its end.
+ session.buffer = session.buffer.filter((entry) => !isLoadedBacklog(entry, page.count))
+ }
+ const kept = continues ? values.log.entries.filter(({ source }) => source === 'replay') : []
+ const history = normalizeHistory(
+ page.entries,
+ session.runId,
+ values.isBootstrapResumeRun,
+ page.preamble,
+ kept[kept.length - 1]?.entry.source_run_id
+ )
+ const echo = cache.retainedMessage
+ ? values.log.entries.findLast(
+ ({ entry }) =>
+ entry.notification.method === '_client/human_message' &&
+ entry.notification.params?.content === cache.retainedMessage
+ )
+ : undefined
+ const echoPersisted =
+ !!echo &&
+ history.some(
+ (entry) =>
+ entry.source_run_id === session.runId && persistedHumanText(entry) === cache.retainedMessage
+ )
+ // A paged log keeps its saved entries apart: only live and client entries meet the new read.
+ const tail = values.pagedHistory
+ ? values.log.entries.filter(({ source }) => source !== 'replay')
+ : values.log.entries
+ const retained = echoPersisted ? tail.filter((stored) => stored !== echo) : tail
+ // The kept entries take part, so a frame the stream sends again after the read is a duplicate of them too.
+ const saved = [...kept.map(({ entry }) => entry), ...history]
+ const log = reconcileRunLog(saved, retained, session.buffer, echoPersisted ? undefined : echo)
+ if (values.pagedHistory && page.indexed) {
+ cache.historyEnd = page.count
+ if (!continues) {
+ setHistoryCursor({
+ runId: session.runId,
+ origin: page.origin,
+ offset: page.offset,
+ turnsBefore: page.turnsBefore,
+ })
+ }
+ } else {
+ cache.historyEnd = undefined
+ setHistoryCursor(undefined)
+ }
+ const bufferedEntries = new Set(session.buffer)
+ const bufferedIds = new Set(session.buffer.flatMap((entry) => (entry.event_id ? [entry.event_id] : [])))
+ replayRunLog(
+ log,
+ session.runId,
+ (stored) =>
+ stored.source === 'live' &&
+ (bufferedEntries.has(stored.entry) ||
+ (!!stored.entry.event_id && bufferedIds.has(stored.entry.event_id)))
+ )
actions.replaceLog(log)
cache.eventCoverage = new RunEventCoverage([
- ...history,
+ ...saved,
...retained.map(({ entry }) => entry),
...session.buffer,
])
@@ -4050,7 +4358,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
recoveringLiveTurn &&
!turnCompleteBeforeReconcile &&
values.turnComplete &&
- !windowShowsToolCallInFlight(dedupeBufferedAgainstHistory(session.buffer, history))
+ !windowShowsToolCallInFlight(dedupeBufferedAgainstHistory(session.buffer, saved))
) {
actions.markTurnComplete()
}
@@ -4071,7 +4379,9 @@ export const runStreamLogic = kea<runStreamLogicType>([
task_id: session.taskId,
run_id: session.runId,
run_status: values.currentRunStatus,
- entry_count: entries.length,
+ entry_count: page.count || history.length,
+ loaded_entry_count: page.entries.length - page.preamble,
+ partial: page.indexed && page.offset > 0,
duration_ms: Math.round(performance.now() - cache.bootstrapStartedAt),
execution_type: 'sandbox',
})
@@ -4080,6 +4390,17 @@ export const runStreamLogic = kea<runStreamLogicType>([
if (session.phase !== 'finalization') {
recordRecovery(session)
}
+ const loaded = cache.historyCursor as HistoryCursor | undefined
+ if (!continues && loaded && loaded.offset > 0) {
+ cache.disposables.add(() => {
+ const timer = setTimeout(() => {
+ // Fired once: a tab that hides and shows again must not load another page on its own.
+ cache.disposables.dispose('older-history-preload')
+ actions.loadOlderHistory()
+ }, OLDER_HISTORY_PRELOAD_DELAY_MS)
+ return () => clearTimeout(timer)
+ }, 'older-history-preload')
+ }
}
const finalize = async (session: RunStreamRecovery): Promise<void> => {
@@ -4116,7 +4437,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
}
}
const foldContextUsage = (fold: (usage: ContextUsage | null) => ContextUsage): void => {
- if (cache.coalesceContextUsage) {
+ if (cache.coalesceReplay) {
cache.replayContextUsage = fold(
(cache.replayContextUsage as ContextUsage | undefined) ?? values.contextUsage
)
@@ -4301,6 +4622,13 @@ export const runStreamLogic = kea<runStreamLogicType>([
// sent-keys bookkeeping is lost (a reload, another tab, a teammate's session). An
// unattached optimistic stream has no task id and records nothing — its send path marks
// sent keys directly.
+ if (method === CONTEXT_HISTORY_METHOD) {
+ const lines = contextHistoryLines(notification.params)
+ if (values.bootstrappedTaskId && lines.length > 0) {
+ actions.markContextLinesSeen(values.bootstrappedTaskId, lines)
+ }
+ return
+ }
if (isPosthogNotification(notification, '_posthog/user_message')) {
const content = notification.params?.content
if (Array.isArray(content) && content.length > 0 && content.every(isHiddenUserContent)) {
@@ -4671,14 +4999,25 @@ export const runStreamLogic = kea<runStreamLogicType>([
...parsed,
source_run_id: parsed.source_run_id ?? (id?.startsWith('log-') ? backlogRunId : runId),
}
+ const backlogIndex = id?.startsWith('log-') ? Number(id.slice('log-'.length)) : NaN
+ if (Number.isSafeInteger(backlogIndex)) {
+ backlogIndexes.set(entry, backlogIndex)
+ }
+ // An entry the loaded log already holds is not ingested, but it still moves the resume cursor below.
+ const fresh = !isLoadedBacklog(entry, cache.historyEnd as number | undefined)
const savedBacklog = !entry.event_id && id ? session.legacyBacklog.get(id) : undefined
const matchesSavedBacklog =
savedBacklog &&
savedBacklog.timestamp === entry.timestamp &&
JSON.stringify(savedBacklog.notification) === JSON.stringify(entry.notification)
- if (session.buffering) {
+ if (fresh && session.buffering) {
session.buffer.push(entry)
- } else if (!matchesSavedBacklog && !(cache.eventCoverage as RunEventCoverage).covers(entry)) {
+ } else if (
+ fresh &&
+ !session.buffering &&
+ !matchesSavedBacklog &&
+ !(cache.eventCoverage as RunEventCoverage).covers(entry)
+ ) {
;(cache.eventCoverage as RunEventCoverage).add(entry)
if (entry.first_event_id) {
const log = mergeCoalescedRunLog(values.log, entry)
@@ -5220,6 +5559,9 @@ export const runStreamLogic = kea<runStreamLogicType>([
cache.disposables.dispose('event-source')
},
reset: () => {
+ stopHistoryPaging()
+ cache.historyCursor = undefined
+ cache.historyEnd = undefined
if (!props.replayOnly) {
liveRunStreams().delete(props.streamKey)
}
@@ -5303,6 +5645,11 @@ export const runStreamLogic = kea<runStreamLogicType>([
return
}
cache.optimisticResume = undefined
+ const cursor = cache.historyCursor as HistoryCursor | undefined
+ if (cursor) {
+ // The successor's chain holds this run's chain at the same indexes, so the loaded log stays valid.
+ cache.historyCursor = { ...cursor, runId: run.id }
+ }
actions.closeSse()
actions.prepareResumeRun()
actions.permissionRunChanged()
@@ -5337,6 +5684,8 @@ export const runStreamLogic = kea<runStreamLogicType>([
notification: {
method: '_client/human_message',
params: {
+ // Keeps the row's id when older history loads in front of it.
+ clientId: uuid(),
content,
...(stagedAttachments?.length ? { attachments: stagedAttachments } : {}),
},
@@ -5371,6 +5720,120 @@ export const runStreamLogic = kea<runStreamLogicType>([
])
},
ingestAcpFrame: ({ entry, source }) => ingestFrame(entry, source),
+ loadOlderHistory: async () => {
+ const cursor = cache.historyCursor as HistoryCursor | undefined
+ const projectId = values.currentProjectId
+ const taskId = values.bootstrappedTaskId
+ if (
+ !cursor ||
+ cursor.offset === 0 ||
+ values.olderHistoryState !== 'idle' ||
+ projectId === null ||
+ !taskId
+ ) {
+ return
+ }
+ cache.disposables.dispose('older-history-preload')
+ actions.setOlderHistoryState('loading')
+ // Paging owns its request, so a stream that reconnects, fails or moves to a successor run leaves it
+ // running. A new cursor, a reset or an unmount cancels it.
+ const request = {}
+ cache.olderHistoryRequest = request
+ const controller = new AbortController()
+ cache.disposables.add(
+ () => {
+ const timer = setTimeout(() => controller.abort(), STREAM_HISTORY_TIMEOUT_MS)
+ return () => {
+ clearTimeout(timer)
+ controller.abort()
+ }
+ },
+ 'older-history-request',
+ { pauseOnPageHidden: false }
+ )
+ const startedAt = performance.now()
+ const owned = (): HistoryCursor | undefined => {
+ const current = cache.historyCursor as HistoryCursor | undefined
+ return !cache.disposables.isDisposed &&
+ cache.olderHistoryRequest === request &&
+ current?.offset === cursor.offset
+ ? current
+ : undefined
+ }
+ const capture = (outcome: 'loaded' | 'failed', fields: Record<string, unknown>): void => {
+ posthog.capture('sandbox_run_older_history_loaded', {
+ conversation_id: props.conversationId,
+ task_id: taskId,
+ run_id: cursor.runId,
+ outcome,
+ duration_ms: Math.round(performance.now() - startedAt),
+ execution_type: 'sandbox',
+ ...fields,
+ })
+ }
+ try {
+ const page = await api.tasks.runs.getLogPage(taskId, cursor.runId, {
+ signal: controller.signal,
+ projectId,
+ tailBytes: HISTORY_PAGE_BYTES,
+ before: cursor.offset,
+ })
+ const current = owned()
+ if (!current) {
+ return
+ }
+ cache.olderHistoryRequest = undefined
+ cache.disposables.dispose('older-history-request')
+ // A page from a chain that dropped its oldest run counts from another run. The next history read
+ // finds the same change and reads the latest turns again, with a new cursor.
+ if (!page.indexed || page.origin !== current.origin || page.offset >= cursor.offset) {
+ actions.setOlderHistoryState('none')
+ return
+ }
+ const entries = normalizeHistory(
+ page.entries.slice(0, page.preamble + cursor.offset - page.offset),
+ current.runId,
+ values.isBootstrapResumeRun,
+ page.preamble
+ )
+ const lines = historyContextLines(entries)
+ if (lines.length > 0) {
+ actions.markContextLinesSeen(taskId, lines)
+ }
+ cache.historyCursor = { ...current, offset: page.offset, turnsBefore: page.turnsBefore }
+ cache.olderHistoryFailures = 0
+ actions.replaceLog(prependHistoryPage(values.log, entries))
+ actions.setHistoryTurnBase(page.turnsBefore)
+ actions.setOlderHistoryState(page.offset > 0 ? 'idle' : 'none')
+ capture('loaded', { entry_count: entries.length - page.preamble, remaining: page.offset > 0 })
+ } catch (error) {
+ if (!owned()) {
+ return
+ }
+ cache.olderHistoryRequest = undefined
+ cache.disposables.dispose('older-history-request')
+ const failures = ((cache.olderHistoryFailures as number | undefined) ?? 0) + 1
+ cache.olderHistoryFailures = failures
+ const status = (error as { status?: number } | null)?.status
+ capture('failed', { http_status: status, failures })
+ // A refused or missing log never loads, so it stops at once.
+ if (status === 403 || status === 404 || failures >= OLDER_HISTORY_MAX_FAILURES) {
+ actions.setOlderHistoryState('none')
+ return
+ }
+ // Every failure waits before the state rearms, so a short thread's automatic load cannot loop.
+ cache.disposables.add(() => {
+ const timer = setTimeout(
+ () => {
+ cache.disposables.dispose('older-history-retry')
+ actions.setOlderHistoryState('idle')
+ },
+ OLDER_HISTORY_RETRY_DELAY_MS * 2 ** (failures - 1)
+ )
+ return () => clearTimeout(timer)
+ }, 'older-history-retry')
+ }
+ },
}
}),
beforeUnmount(({ props }) => {
diff --git a/products/posthog_ai/frontend/logics/suggestionActionLogic.ts b/products/posthog_ai/frontend/logics/suggestionActionLogic.ts
index 37da1c67183e..f071d05aefb4 100644
--- a/products/posthog_ai/frontend/logics/suggestionActionLogic.ts
+++ b/products/posthog_ai/frontend/logics/suggestionActionLogic.ts
@@ -17,7 +17,7 @@ import { AcceptedSuggestion, acceptSuggestion } from '../utils/acceptSuggestion'
import { ConversationBlocks, collectConversationBlocks } from '../utils/conversationNotebook'
import { recordTurnSuggestionResolution } from '../utils/recordTurnSuggestionResolution'
import { captureTurnSuggestionEvent } from '../utils/turnSuggestionEvents'
-import { runStreamLogic } from './runStreamLogic'
+import { readFullThread, runStreamLogic } from './runStreamLogic'
import { slackDestinationLogic } from './slackDestinationLogic'
import { TurnSuggestionLogicProps, turnSuggestionLogic } from './turnSuggestionLogic'
@@ -164,7 +164,9 @@ export const suggestionActionLogic: LogicWrapper<suggestionActionLogicType> = ke
// so the outcome is recorded against the suggestion this accept started from.
let outcome: Awaited<ReturnType<typeof acceptSuggestion>>
try {
- outcome = await acceptSuggestion({
+ // The inputs are read before the full-history read: a message sent meanwhile clears the
+ // suggestion, and the title and the other fields derive from it.
+ const input = {
suggestion,
projectId: currentProjectId,
userId: values.user?.id,
@@ -176,6 +178,21 @@ export const suggestionActionLogic: LogicWrapper<suggestionActionLogicType> = ke
changePercent: values.changePercent,
notebookTitle: values.notebookTitle,
conversationBlocks: values.conversationBlocks,
+ }
+ // A chat that loaded only its latest turns reads the full conversation, so the notebook holds
+ // every turn. The loader keeps the button loading while it reads.
+ const fullRead = suggestion.kind === 'notebook' ? readFullThread(props.streamKey) : null
+ const fullThread = fullRead ? await fullRead : null
+ outcome = await acceptSuggestion({
+ ...input,
+ ...(fullThread
+ ? {
+ conversationBlocks: collectConversationBlocks(
+ fullThread.threadItems,
+ fullThread.toolInvocations
+ ),
+ }
+ : {}),
})
} catch (error) {
// posthog-js serializes an Error instance as an empty object.
diff --git a/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts b/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts
index 3c10cf219f57..f5f861775248 100644
--- a/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts
+++ b/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts
@@ -1,5 +1,11 @@
import type { ThreadItem, ToolInvocation } from '../types/streamTypes'
-import { activityWindow, groupConsecutiveTools, groupThreadActivity, groupToolRuns } from './groupThreadActivity'
+import {
+ activityWindow,
+ groupConsecutiveTools,
+ groupThreadActivity,
+ groupToolRuns,
+ reuseActivityGroups,
+} from './groupThreadActivity'
describe('thread activity grouping', () => {
const tool = (id: string, startedAt = 1000): ThreadItem => ({
@@ -95,6 +101,21 @@ describe('thread activity grouping', () => {
expect(groupToolRuns(items, calls, { ...options, settled: true }).at(-1)?.id).toBe('live-chart')
})
+ it('keeps a group id when earlier calls load in front of it', () => {
+ const latest = groupThreadActivity([tool('later'), tool('last', 1100)], new Set())
+ const loaded = reuseActivityGroups(
+ latest,
+ groupThreadActivity([tool('earlier', 900), tool('later'), tool('last', 1100)], new Set())
+ )
+
+ expect(loaded.map((item) => item.id)).toEqual(['activity-later'])
+ expect(loaded[0].type === 'activity_group' && loaded[0].items.map((row) => row.id)).toEqual([
+ 'earlier',
+ 'later',
+ 'last',
+ ])
+ })
+
it('does not invent a duration when part of the group has no recorded start', () => {
const result = groupThreadActivity(
[tool('timed'), { id: 'imported', type: 'tool_invocation', toolCallId: 'imported' }],
diff --git a/products/posthog_ai/frontend/utils/groupThreadActivity.ts b/products/posthog_ai/frontend/utils/groupThreadActivity.ts
index a57fe016ed22..f11287ecddc7 100644
--- a/products/posthog_ai/frontend/utils/groupThreadActivity.ts
+++ b/products/posthog_ai/frontend/utils/groupThreadActivity.ts
@@ -154,18 +154,34 @@ export function groupToolRuns(
export function reuseActivityGroups(previous: ThreadDisplayItem[], next: ThreadDisplayItem[]): ThreadDisplayItem[] {
const previousGroups = new Map<string, ThreadActivityGroup>()
+ const groupOfMember = new Map<string, string>()
for (const item of previous) {
if (item.type === 'activity_group') {
previousGroups.set(item.id, item)
+ item.items.forEach((row) => groupOfMember.set(row.id, item.id))
}
}
if (previousGroups.size === 0) {
return next
}
- return next.map((item) => {
- if (item.type !== 'activity_group') {
- return item
+ // A group's id comes from its first member, so earlier calls that load in front of it would rename it and
+ // remount it. A group that shares a member with a previous group keeps that group's id, unless a group in
+ // `next` already has that id, so a group that splits never gives two groups one key.
+ const reserved = new Set(
+ next.flatMap((item) => (item.type === 'activity_group' && previousGroups.has(item.id) ? [item.id] : []))
+ )
+ const claimed = new Set<string>()
+ return next.map((nextItem) => {
+ if (nextItem.type !== 'activity_group') {
+ return nextItem
}
+ const carried = previousGroups.has(nextItem.id)
+ ? undefined
+ : nextItem.items
+ .map((row) => groupOfMember.get(row.id))
+ .find((id) => id !== undefined && !claimed.has(id) && !reserved.has(id))
+ const item = carried ? { ...nextItem, id: carried } : nextItem
+ claimed.add(item.id)
const old = previousGroups.get(item.id)
return old &&
old.startedAt === item.startedAt &&
diff --git a/products/posthog_ai/frontend/utils/turnTrailers.test.ts b/products/posthog_ai/frontend/utils/turnTrailers.test.ts
index c57ff32099a5..519df2f13863 100644
--- a/products/posthog_ai/frontend/utils/turnTrailers.test.ts
+++ b/products/posthog_ai/frontend/utils/turnTrailers.test.ts
@@ -33,6 +33,19 @@ describe('turnTrailers', () => {
})
})
+ it('numbers turns after the user turns a partial history leaves out', () => {
+ const trailers = computeTurnTrailers(
+ [
+ item('human_message', 'h0', 'q'),
+ item('assistant_message', 'a0', 'answer'),
+ item('turn_separator', 'turn-0'),
+ ],
+ 7
+ )
+
+ expect(trailers.get('turn-0')?.turnIndex).toEqual(7)
+ })
+
it("does not leak a crashed turn's text into the next completed turn", () => {
// A crashed turn never emits its separator; the next human message starts a fresh turn.
const trailers = computeTurnTrailers([
diff --git a/products/posthog_ai/frontend/utils/turnTrailers.ts b/products/posthog_ai/frontend/utils/turnTrailers.ts
index 8f28e9373bb6..dfbf013f10f3 100644
--- a/products/posthog_ai/frontend/utils/turnTrailers.ts
+++ b/products/posthog_ai/frontend/utils/turnTrailers.ts
@@ -20,9 +20,10 @@ export interface TurnTrailer {
* the end of a completed turn, so a consumer can render per-turn UI (e.g. feedback actions) at
* the separator's position without the surface knowing what that UI is.
*/
-export function computeTurnTrailers(threadItems: ThreadItem[]): Map<string, TurnTrailer> {
+export function computeTurnTrailers(threadItems: ThreadItem[], turnBase = 0): Map<string, TurnTrailer> {
const trailers = new Map<string, TurnTrailer>()
- let turnIndex = -1
+ // A partial history starts after `turnBase` user turns.
+ let turnIndex = turnBase - 1
let textParts: string[] = []
let lastSeparatorId: string | null = null
for (const item of threadItems) {
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index e8714eb0b0f6..5c0bfecf14e5 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -110,6 +110,16 @@ from products.tasks.backend.feature_flags import (
from products.tasks.backend.github_repository_access import (
inaccessible_repositories_via_integration as _inaccessible_repositories_via_integration,
)
+from products.tasks.backend.logic.log_slice import (
+ LogPart,
+ LogPartSummary,
+ log_entries,
+ slice_log_parts_from,
+ slice_log_parts_tail,
+ summarize_log_part,
+ summary_from_json,
+ summary_to_json,
+)
from products.tasks.backend.logic.model_access import InvalidModelAccess, resolve_model_access
from products.tasks.backend.logic.services.gateway_model_pin import GATEWAY_PRODUCT_STATE_KEY, pinned_run_allows_model
from products.tasks.backend.logic.services.gateway_usage import refresh_task_run_cost
@@ -356,6 +366,7 @@ __all__ = [
"get_task_run_log_size",
"read_task_run_log_content",
"read_task_run_conversation_logs",
+ "read_task_run_conversation_log_slice",
"mark_task_run_stream_watched",
"read_task_run_logs",
"record_comment_activity",
@@ -5253,6 +5264,103 @@ def read_task_run_conversation_logs(run_id: str | UUID, task_id: str | UUID, tea
return "".join(parts)
+_LOG_PART_SUMMARY_CACHE_SECONDS = 24 * 60 * 60
+
+
+def _conversation_log_part_summary(log_url: str, entries: Callable[[], list[str]]) -> LogPartSummary:
+ """A run log's summary, cached under one key per log with the object size it was made from. A log only grows,
+ so its size identifies its content, and a new size replaces the old summary. The cache is an optimization: a
+ cache error counts as a miss, and the summary comes from the log itself."""
+ from django.core.cache import cache # noqa: PLC0415 — keep cache setup off the api import path
+
+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path
+
+ head = object_storage.head_object(log_url)
+ size = int(head.get("ContentLength", 0)) if head else 0
+ if not size:
+ return summarize_log_part(entries())
+ # The cache pickles values, so it holds only a JSON string: the object size, then the summary.
+ key = f"tasks:log-part-summary:v5:{hashlib.sha256(log_url.encode()).hexdigest()}"
+ try:
+ cached = cache.get(key)
+ except Exception:
+ logger.warning("task_log_part_summary_cache_read_failed", exc_info=True)
+ cached = None
+ if isinstance(cached, str) and cached.startswith(f"{size}:"):
+ summary_hit = summary_from_json(cached.removeprefix(f"{size}:"))
+ if summary_hit is not None:
+ return summary_hit
+ summary = summarize_log_part(entries())
+ try:
+ cache.set(key, f"{size}:{summary_to_json(summary)}", timeout=_LOG_PART_SUMMARY_CACHE_SECONDS)
+ except Exception:
+ logger.warning("task_log_part_summary_cache_write_failed", exc_info=True)
+ return summary
+
+
+def _conversation_log_parts(log_urls: list[str]) -> list[LogPart]:
+ """The run logs of a resume chain as slice parts. The summaries load in parallel, and a part's entries load
+ only when the slice needs them."""
+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path
+
+ def loader(log_url: str) -> Callable[[], list[str]]:
+ read: list[list[str]] = []
+
+ def entries() -> list[str]:
+ if not read:
+ read.append(log_entries(object_storage.read(log_url, missing_ok=True) or ""))
+ return read[0]
+
+ return entries
+
+ loaders = [loader(log_url) for log_url in log_urls]
+ pairs = list(zip(log_urls, loaders))
+ if len(pairs) == 1:
+ summaries = [_conversation_log_part_summary(*pairs[0])]
+ else:
+ summaries = list(_TASK_LOG_READ_EXECUTOR.map(lambda pair: _conversation_log_part_summary(*pair), pairs))
+ return [LogPart(summary=summary, entries=entries) for summary, entries in zip(summaries, loaders)]
+
+
+def read_task_run_conversation_log_slice(
+ run_id: str | UUID,
+ task_id: str | UUID,
+ team_id: int,
+ *,
+ tail_bytes: int,
+ before: int | None = None,
+ start: int | None = None,
+) -> contracts.TaskRunLogSliceDTO | None:
+ """Part of the conversation log, read from the run logs that overlap it.
+
+ With ``start``, every entry from that index to the end, or the latest turns when they are too many. Else the
+ latest turns that end before index ``before``, at least ``tail_bytes`` long. A Pi chain puts run markers
+ between its runs, so its indexes change when the chain grows: it returns the full log, not sliced.
+ """
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+ if run.task.runtime == Task.Runtime.PI:
+ content = read_task_run_conversation_logs(run_id, task_id, team_id)
+ if content is None:
+ return None
+ return contracts.TaskRunLogSliceDTO(content=content, offset=0, count=0, sliced=False)
+ chain = run.get_history_chain()
+ parts = _conversation_log_parts([ancestor.log_url for ancestor in chain])
+ if start is not None:
+ sliced = slice_log_parts_from(parts, start, tail_bytes)
+ else:
+ sliced = slice_log_parts_tail(parts, tail_bytes, before)
+ return contracts.TaskRunLogSliceDTO(
+ content=sliced.content,
+ offset=sliced.offset,
+ count=sliced.count,
+ preamble=sliced.preamble,
+ turns_before=sliced.turns_before,
+ origin=str(chain[0].id),
+ )
+
+
def get_task_run_log_urls(run_id: str | UUID, task_id: str | UUID, team_id: int) -> list[str] | None:
"""Log URLs across the run's resume chain (oldest ancestor first). ``None`` if the run isn't found."""
run = _get_visible_run(run_id, task_id, team_id)
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 1be7f0073390..c0836fc3c713 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -749,6 +749,27 @@ class TaskRunCreateResult:
error: TaskRunValidationError | None = None
+@dataclass(frozen=True)
+class TaskRunLogSliceDTO:
+ """Part of a run's conversation log.
+
+ ``content`` is JSONL. ``offset`` is the index in the full log of the first entry after the
+ ``preamble`` entries, ``count`` is the number of entries in the full log, and ``turns_before`` is the
+ number of user turns that start before ``offset``. ``origin`` is the id of the first run in the chain: the
+ chain keeps a limited number of runs, so indexes hold only while the origin stays the same. ``sliced`` is
+ false when the run's log cannot be read in parts, so ``content`` is the full log and the other fields carry
+ no index.
+ """
+
+ content: str
+ offset: int
+ count: int
+ preamble: int = 0
+ turns_before: int = 0
+ origin: str = ""
+ sliced: bool = True
+
+
@dataclass(frozen=True)
class TaskRunStreamInfoDTO:
"""The minimal run facts the SSE stream view needs without holding a model.
diff --git a/products/tasks/backend/logic/log_slice.py b/products/tasks/backend/logic/log_slice.py
new file mode 100644
index 000000000000..8682f146a787
--- /dev/null
+++ b/products/tasks/backend/logic/log_slice.py
@@ -0,0 +1,541 @@
+import json
+import bisect
+import hashlib
+from collections import defaultdict
+from collections.abc import Callable, Iterator, Sequence
+
+from posthog.dataclasses import frozen
+
+from products.posthog_ai.backend.turn_suggestions.transcript import HumanTurnCounter, human_text, is_turn_text
+
+TAIL_TURN_SLACK_FACTOR = 4
+START_READ_MAX_BYTES = 8 * 1024 * 1024
+
+STATE_METHODS = frozenset({"_posthog/run_started", "_posthog/sdk_session", "session/new"})
+STATE_SESSION_UPDATES = frozenset({"current_mode_update", "available_commands_update"})
+USAGE_METHOD = "_posthog/usage_update"
+USAGE_SESSION_UPDATE = "usage_update"
+PERMISSION_REQUEST = "_posthog/permission_request"
+PERMISSION_RESOLVED = "_posthog/permission_resolved"
+TURN_COMPLETE = "_posthog/turn_complete"
+USER_MESSAGE_METHOD = "_posthog/user_message"
+PROMPT_METHOD = "session/prompt"
+USER_SESSION_UPDATES = frozenset({"user_message_chunk", "user_message"})
+TOOL_SESSION_UPDATES = frozenset({"tool_call", "tool_call_update"})
+CONTEXT_HISTORY_METHOD = "_posthog/context_history"
+CONTEXT_BLOCK_PREFIX = "<posthog_"
+CONTEXT_HISTORY_MAX_BYTES = 256 * 1024
+STATE_MARKERS = (
+ *STATE_METHODS,
+ *STATE_SESSION_UPDATES,
+ USAGE_SESSION_UPDATE,
+ PERMISSION_REQUEST,
+ PERMISSION_RESOLVED,
+ TURN_COMPLETE,
+ "user_message",
+)
+
+
+@frozen
+class LogSlice:
+ content: str
+ offset: int
+ count: int
+ preamble: int = 0
+ turns_before: int = 0
+
+
+@frozen
+class HumanEntry:
+ """A human message in a log part as the turn rule reads it: its index in the part, a digest of its text, and
+ whether it is the ``_posthog/user_message`` form."""
+
+ index: int
+ text_key: str
+ user_message: bool
+
+
+@frozen
+class LogPartSummary:
+ """What one log part contributes to a slice, so a slice never reads a part that lies before it.
+
+ ``state`` maps each state key to the last entry in the part that set it, as its index in the part and its
+ line; ``requests`` holds the part's permission requests the same way, with their ids; ``resolved`` holds
+ the request ids the part resolves. ``last_turn_complete`` is the index of its last turn completion, which
+ closes every request before it. ``human`` lists the human messages that the turn rule reads, ``context``
+ holds the texts of the user messages that carry context blocks, once each, and ``size`` is the byte size of
+ the part's entries.
+ """
+
+ count: int
+ state: dict[str, tuple[int, str]]
+ requests: list[tuple[int, str, str]]
+ resolved: frozenset[str]
+ last_turn_complete: int | None = None
+ human: tuple[HumanEntry, ...] = ()
+ context: tuple[str, ...] = ()
+ size: int = 0
+
+
+@frozen
+class LogPart:
+ """One storage object of a resume-chain log: its summary, and its entries, which load on first use."""
+
+ summary: LogPartSummary
+ entries: Callable[[], list[str]]
+
+
+def log_entries(content: str) -> list[str]:
+ return [line for line in content.split("\n") if line.strip().startswith("{")]
+
+
+def log_part(entries: list[str]) -> LogPart:
+ return LogPart(summary=summarize_log_part(entries), entries=lambda: entries)
+
+
+def _entry(line: str) -> dict:
+ try:
+ entry = json.loads(line)
+ except ValueError:
+ return {}
+ return entry if isinstance(entry, dict) else {}
+
+
+def _notification(line: str) -> dict:
+ notification = _entry(line).get("notification")
+ return notification if isinstance(notification, dict) else {}
+
+
+def _method(notification: dict) -> str | None:
+ method = notification.get("method")
+ return method if isinstance(method, str) else None
+
+
+def _session_update(notification: dict) -> dict:
+ params = notification.get("params")
+ update = params.get("update") if isinstance(params, dict) else None
+ return update if isinstance(update, dict) else {}
+
+
+def _session_update_type(notification: dict) -> str | None:
+ session_update = _session_update(notification).get("sessionUpdate")
+ return session_update if isinstance(session_update, str) else None
+
+
+def _is_user_entry(line: str) -> bool:
+ """Any entry of a user message, in either wire form, including a hidden prompt and an attached file."""
+ if "user_message" not in line:
+ return False
+ notification = _notification(line)
+ method = _method(notification)
+ if method == USER_MESSAGE_METHOD:
+ return True
+ return method == "session/update" and _session_update_type(notification) in USER_SESSION_UPDATES
+
+
+def _is_prompt(line: str) -> bool:
+ return PROMPT_METHOD in line and _method(_notification(line)) == PROMPT_METHOD
+
+
+def _human_entry(index: int, line: str) -> HumanEntry | None:
+ if "user_message" not in line:
+ return None
+ notification = _notification(line)
+ params = notification.get("params")
+ human = human_text(_method(notification), params if isinstance(params, dict) else {})
+ if human is None or not is_turn_text(human.text):
+ return None
+ return HumanEntry(
+ index=index, text_key=hashlib.sha256(human.text.encode()).hexdigest(), user_message=human.user_message
+ )
+
+
+@frozen
+class EchoSpan:
+ """A ``_posthog/user_message`` at ``first`` and the later ``session/update`` form of it at ``last``. A cut in
+ ``(first, last]`` separates the two."""
+
+ first: int
+ last: int
+
+
+@frozen
+class ToolFrame:
+ """A tool call frame: ``tool_call`` or ``tool_call_update``, its call id, and the call id of its parent."""
+
+ kind: str
+ call_id: str
+ parent: str | None
+
+
+def _tool_frame(line: str) -> ToolFrame | None:
+ if '"tool_call' not in line:
+ return None
+ notification = _notification(line)
+ if _method(notification) != "session/update":
+ return None
+ update = _session_update(notification)
+ kind = update.get("sessionUpdate")
+ call_id = update.get("toolCallId")
+ if kind not in TOOL_SESSION_UPDATES or not isinstance(call_id, str) or not call_id:
+ return None
+ meta = update.get("_meta")
+ claude_code = meta.get("claudeCode") if isinstance(meta, dict) else None
+ parent = claude_code.get("parentToolCallId") if isinstance(claude_code, dict) else None
+ return ToolFrame(kind=str(kind), call_id=call_id, parent=parent if isinstance(parent, str) and parent else None)
+
+
+def _context_text(notification: dict) -> str | None:
+ """The text of a user message that starts with context blocks. The client reads the block lines from it to
+ dedupe the context it sends, so a page that starts after the message still knows that context."""
+ method = _method(notification)
+ params = notification.get("params")
+ if not isinstance(params, dict):
+ return None
+ text: object = None
+ if method == USER_MESSAGE_METHOD:
+ content = params.get("content")
+ if isinstance(content, list):
+ text = "".join(
+ block["text"]
+ for block in content
+ if isinstance(block, dict) and block.get("type") == "text" and isinstance(block.get("text"), str)
+ )
+ else:
+ text = content
+ elif method == "session/update" and _session_update_type(notification) == "user_message":
+ update = _session_update(notification)
+ content = update.get("content")
+ text = content.get("text") if isinstance(content, dict) else update.get("text")
+ return text if isinstance(text, str) and text.startswith(CONTEXT_BLOCK_PREFIX) else None
+
+
+def _request_id(notification: dict) -> str | None:
+ params = notification.get("params")
+ request_id = params.get("requestId") if isinstance(params, dict) else None
+ return request_id if isinstance(request_id, str) else None
+
+
+def _state_keys(notification: dict) -> list[str]:
+ """The state keys an entry sets. Usage folds field by field, so each usage field is its own key."""
+ method = _method(notification)
+ if method in STATE_METHODS:
+ return [str(method)]
+ if method == USAGE_METHOD:
+ params = notification.get("params")
+ return [f"usage:{field}" for field in params] if isinstance(params, dict) else []
+ update_type = _session_update_type(notification)
+ if method == "session/update" and update_type in STATE_SESSION_UPDATES:
+ return [f"session/update:{update_type}"]
+ if method == "session/update" and update_type == USAGE_SESSION_UPDATE:
+ return [f"session-usage:{field}" for field in _session_update(notification) if field != "sessionUpdate"]
+ return []
+
+
+def summarize_log_part(entries: Sequence[str]) -> LogPartSummary:
+ state: dict[str, tuple[int, str]] = {}
+ requests: list[tuple[int, str, str]] = []
+ resolved: set[str] = set()
+ last_turn_complete: int | None = None
+ human: list[HumanEntry] = []
+ context: dict[str, None] = {}
+ for index, line in enumerate(entries):
+ if not any(marker in line for marker in STATE_MARKERS):
+ continue
+ if (human_entry := _human_entry(index, line)) is not None:
+ human.append(human_entry)
+ notification = _notification(line)
+ if CONTEXT_BLOCK_PREFIX in line and (text := _context_text(notification)) is not None:
+ context[text] = None
+ method = _method(notification)
+ if method == PERMISSION_REQUEST and (request_id := _request_id(notification)) is not None:
+ requests.append((index, request_id, line))
+ elif method == PERMISSION_RESOLVED and (request_id := _request_id(notification)) is not None:
+ resolved.add(request_id)
+ elif method == TURN_COMPLETE:
+ last_turn_complete = index
+ for key in _state_keys(notification):
+ state[key] = (index, line)
+ return LogPartSummary(
+ count=len(entries),
+ state=state,
+ requests=requests,
+ resolved=frozenset(resolved),
+ last_turn_complete=last_turn_complete,
+ human=tuple(human),
+ context=tuple(context),
+ size=sum(len(line) + 1 for line in entries),
+ )
+
+
+def summary_to_json(summary: LogPartSummary) -> str:
+ return json.dumps(
+ {
+ "count": summary.count,
+ "state": {key: [index, line] for key, (index, line) in summary.state.items()},
+ "requests": [list(request) for request in summary.requests],
+ "resolved": sorted(summary.resolved),
+ "last_turn_complete": summary.last_turn_complete,
+ "human": [[entry.index, entry.text_key, entry.user_message] for entry in summary.human],
+ "context": list(summary.context),
+ "size": summary.size,
+ }
+ )
+
+
+def summary_from_json(text: object) -> LogPartSummary | None:
+ """The summary that ``summary_to_json`` wrote, or ``None`` when the value has another shape."""
+ if not isinstance(text, str):
+ return None
+ try:
+ data = json.loads(text)
+ return LogPartSummary(
+ count=int(data["count"]),
+ state={str(key): (int(index), str(line)) for key, (index, line) in data["state"].items()},
+ requests=[(int(index), str(request_id), str(line)) for index, request_id, line in data["requests"]],
+ resolved=frozenset(str(request_id) for request_id in data["resolved"]),
+ last_turn_complete=None if data["last_turn_complete"] is None else int(data["last_turn_complete"]),
+ human=tuple(
+ HumanEntry(index=int(index), text_key=str(text_key), user_message=bool(user_message))
+ for index, text_key, user_message in data["human"]
+ ),
+ context=tuple(str(message) for message in data["context"]),
+ size=int(data["size"]),
+ )
+ except (ValueError, TypeError, KeyError, AttributeError):
+ return None
+
+
+class _Chain:
+ """The parts of a resume-chain log, read by full-log index. A part's entries load only when a read needs them."""
+
+ def __init__(self, parts: Sequence[LogPart]) -> None:
+ self._parts = parts
+ self._loaded: dict[int, list[str]] = {}
+ self.starts: list[int] = []
+ total = 0
+ for part in parts:
+ self.starts.append(total)
+ total += part.summary.count
+ self.count = total
+ self._human = [
+ (self.starts[part_index] + entry.index, entry)
+ for part_index, part in enumerate(parts)
+ for entry in part.summary.human
+ ]
+ self._echo_spans = self._unsafe_echo_spans()
+ self._echo_firsts = [span.first for span in self._echo_spans]
+
+ def _entries(self, part_index: int) -> list[str]:
+ if part_index not in self._loaded:
+ self._loaded[part_index] = self._parts[part_index].entries()
+ return self._loaded[part_index]
+
+ def lines_backward(self, end: int) -> Iterator[tuple[int, str]]:
+ for part_index in range(len(self._parts) - 1, -1, -1):
+ start = self.starts[part_index]
+ if start >= end:
+ continue
+ entries = self._entries(part_index)
+ last = min(self._parts[part_index].summary.count, len(entries), end - start)
+ for local in range(last - 1, -1, -1):
+ yield start + local, entries[local]
+
+ def lines(self, begin: int, end: int) -> list[str]:
+ lines: list[str] = []
+ for part_index, part in enumerate(self._parts):
+ start = self.starts[part_index]
+ stop = start + part.summary.count
+ if stop <= begin or start >= end:
+ continue
+ lines += self._entries(part_index)[max(begin - start, 0) : min(end, stop) - start]
+ return lines
+
+ def size_after_part_of(self, index: int) -> int:
+ """The byte size of the parts that start after the part that holds ``index``."""
+ return sum(part.summary.size for part_index, part in enumerate(self._parts) if self.starts[part_index] > index)
+
+ def turns_before(self, cut: int) -> int:
+ counter = HumanTurnCounter()
+ return sum(
+ 1 for index, entry in self._human if index < cut and counter.opens_turn(entry.text_key, entry.user_message)
+ )
+
+ def _unsafe_echo_spans(self) -> list[EchoSpan]:
+ """The spans where a cut separates a ``_posthog/user_message`` from the later ``session/update`` form that
+ ``HumanTurnCounter`` pairs with it, merged and sorted. Each later form spends the newest credit of its
+ text, which keeps the same counts the counter keeps."""
+ credits: defaultdict[str, list[int]] = defaultdict(list)
+ spans: list[tuple[int, int]] = []
+ for index, entry in self._human:
+ if entry.user_message:
+ credits[entry.text_key].append(index)
+ elif credits[entry.text_key]:
+ # The newest credit: an older message whose echo never came leaves a credit the counter never spends.
+ spans.append((credits[entry.text_key].pop(), index))
+ merged: list[EchoSpan] = []
+ for first, last in sorted(spans):
+ if merged and first < merged[-1].last:
+ merged[-1] = EchoSpan(first=merged[-1].first, last=max(merged[-1].last, last))
+ else:
+ merged.append(EchoSpan(first=first, last=last))
+ return merged
+
+ def echo_safe(self, cut: int) -> bool:
+ """Whether the turn rule reads every human message from ``cut`` on the same way with or without the
+ messages before it. A ``_posthog/user_message`` before the cut whose echo comes after the cut fails."""
+ position = bisect.bisect_left(self._echo_firsts, cut) - 1
+ return position < 0 or not (self._echo_spans[position].first < cut <= self._echo_spans[position].last)
+
+ def preamble(self, cut: int) -> list[str]:
+ """The entries before ``cut`` that still set run state there: the latest entry for each state key (run
+ start, SDK session, starting mode, mode, commands, each usage field) and the permission requests that
+ nobody resolved. A synthetic ``_posthog/context_history`` entry carries the context-block messages before
+ the cut, newest kept within ``CONTEXT_HISTORY_MAX_BYTES``."""
+ summaries = [part.summary for part in self._parts]
+ resolved = frozenset().union(*(summary.resolved for summary in summaries))
+ # A turn completion closes every request before it, resolved or not.
+ closed_before = max(
+ (
+ self.starts[part_index] + summary.last_turn_complete
+ for part_index, summary in enumerate(summaries)
+ if summary.last_turn_complete is not None
+ ),
+ default=-1,
+ )
+ latest: dict[str, tuple[int, str]] = {}
+ requests: list[tuple[int, str]] = []
+ context: dict[str, None] = {}
+ for part_index, summary in enumerate(summaries):
+ start = self.starts[part_index]
+ if start >= cut:
+ break
+ if start + summary.count > cut:
+ summary = summarize_log_part(self._entries(part_index)[: cut - start])
+ for key, (index, line) in summary.state.items():
+ latest[key] = (start + index, line)
+ requests += [
+ (start + index, line)
+ for index, request_id, line in summary.requests
+ if request_id not in resolved and start + index > closed_before
+ ]
+ for message in summary.context:
+ context.pop(message, None)
+ context[message] = None
+ lines = [line for _, line in sorted({*latest.values(), *requests})]
+ messages: list[str] = []
+ size = 0
+ for message in reversed(context):
+ size += len(message)
+ if size > CONTEXT_HISTORY_MAX_BYTES:
+ break
+ messages.insert(0, message)
+ if messages:
+ history = {"method": CONTEXT_HISTORY_METHOD, "params": {"messages": messages}}
+ lines.insert(0, json.dumps({"type": "notification", "notification": history}))
+ return lines
+
+
+def _find_cut(chain: _Chain, end: int, tail_bytes: int) -> int:
+ """The latest safe cut that leaves at least ``tail_bytes`` before ``end``, or 0 when the log has none.
+
+ A cut starts a user turn: the first user entry of a run of user entries and prompts, so both wire forms of
+ one message stay on one side. A turn that grows past ``TAIL_TURN_SLACK_FACTOR`` times the budget can be
+ cut before a top-level tool call instead. A cut is safe when every tool frame after it has its call, and
+ its parent's call, after it too, and when the turn rule reads the messages after it the same way.
+ """
+ cap = tail_bytes * TAIL_TURN_SLACK_FACTOR
+ size = 0
+ started: set[str] = set()
+ missing: set[str] = set()
+ turn_start: int | None = None
+ tool_cut: int | None = None
+
+ def safe(index: int) -> bool:
+ return not missing and chain.echo_safe(index)
+
+ for index, line in chain.lines_backward(end):
+ if _is_user_entry(line):
+ turn_start = index
+ elif turn_start is not None and not _is_prompt(line):
+ if size >= tail_bytes and safe(turn_start):
+ return turn_start
+ turn_start = None
+ size += len(line) + 1
+ if (frame := _tool_frame(line)) is not None:
+ if frame.kind == "tool_call":
+ started.add(frame.call_id)
+ missing.discard(frame.call_id)
+ elif frame.call_id not in started:
+ missing.add(frame.call_id)
+ if frame.parent is not None and frame.parent not in started:
+ missing.add(frame.parent)
+ top_level_call = frame.kind == "tool_call" and frame.parent is None
+ if top_level_call and tool_cut is None and size >= tail_bytes and safe(index):
+ tool_cut = index
+ if size > cap and tool_cut is not None:
+ return tool_cut
+ return 0
+
+
+def _join(entries: Sequence[str]) -> str:
+ return "".join(f"{entry}\n" for entry in entries)
+
+
+def _tail(chain: _Chain, tail_bytes: int, before: int | None) -> LogSlice:
+ end = chain.count if before is None else min(max(before, 0), chain.count)
+ cut = _find_cut(chain, end, tail_bytes)
+ preamble = chain.preamble(cut) if cut else []
+ return LogSlice(
+ content=_join([*preamble, *chain.lines(cut, end)]),
+ offset=cut,
+ count=chain.count,
+ preamble=len(preamble),
+ turns_before=chain.turns_before(cut),
+ )
+
+
+def slice_log_parts_tail(parts: Sequence[LogPart], tail_bytes: int, before: int | None = None) -> LogSlice:
+ """The latest entries of a multi-part JSONL log, from the latest safe cut (see ``_find_cut``).
+
+ ``before`` ends the window at that entry index, so a client can page back through older turns. ``offset``
+ is the index of the first returned entry in the full log, the same index that ``log-N`` stream cursors use.
+ The slice starts with ``preamble`` entries from before the cut that still set run state there. Only the
+ parts that overlap the window are read; the parts before it contribute through their summaries.
+ """
+ return _tail(_Chain(parts), tail_bytes, before)
+
+
+def slice_log_parts_from(
+ parts: Sequence[LogPart], start: int, tail_bytes: int, max_bytes: int = START_READ_MAX_BYTES
+) -> LogSlice:
+ """Every entry from index ``start`` to the end, with no preamble, for a client that holds the entries
+ before ``start``. When they are more than ``max_bytes``, the latest entries as ``slice_log_parts_tail``
+ returns them, so the client starts again from them."""
+ chain = _Chain(parts)
+ start = min(max(start, 0), chain.count)
+ if chain.size_after_part_of(start) <= max_bytes:
+ lines = chain.lines(start, chain.count)
+ if sum(len(line) + 1 for line in lines) <= max_bytes:
+ return LogSlice(
+ content=_join(lines), offset=start, count=chain.count, turns_before=chain.turns_before(start)
+ )
+ tail = _tail(chain, tail_bytes, None)
+ if tail.offset > start:
+ return tail
+ return LogSlice(
+ content=_join(chain.lines(start, chain.count)),
+ offset=start,
+ count=chain.count,
+ turns_before=chain.turns_before(start),
+ )
+
+
+def slice_log_tail(content: str, tail_bytes: int, before: int | None = None) -> LogSlice:
+ """``slice_log_parts_tail`` over a log held in one string."""
+ return slice_log_parts_tail([log_part(log_entries(content))], tail_bytes, before)
+
+
+def slice_log_from(content: str, start: int, tail_bytes: int, max_bytes: int = START_READ_MAX_BYTES) -> LogSlice:
+ """``slice_log_parts_from`` over a log held in one string."""
+ return slice_log_parts_from([log_part(log_entries(content))], start, tail_bytes, max_bytes)
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 8f40204bd2ea..ef1597fc864a 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -3448,6 +3448,48 @@ class ConnectionTokenResponseSerializer(serializers.Serializer):
token = serializers.CharField(help_text="JWT token for authenticating with the sandbox")
+class TaskRunLogsQuerySerializer(serializers.Serializer):
+ """Query parameters for reading part of a task run log"""
+
+ tail_bytes = serializers.IntegerField(
+ required=False,
+ min_value=1,
+ help_text=(
+ "Return only the latest turns of the log: the shortest suffix that starts at a user turn and holds at "
+ "least this many bytes. The X-Log-Offset and X-Log-Count headers give the index of the first tail entry "
+ "and the size of the full log. The slice starts with X-Log-Preamble earlier entries that still set run "
+ "state, such as the run start, usage, mode, commands and open permission requests. X-Log-Turns-Before "
+ "counts the user turns before the slice, so a client numbers turns the way the full log does."
+ ),
+ )
+ before = serializers.IntegerField(
+ required=False,
+ min_value=0,
+ help_text=(
+ "With tail_bytes, end the window before this entry index, so a client can page back through older "
+ "turns: pass the X-Log-Offset of the oldest page it holds."
+ ),
+ )
+ start = serializers.IntegerField(
+ required=False,
+ min_value=0,
+ help_text=(
+ "With tail_bytes, return every entry from this index to the end, with no preamble, so a client that "
+ "holds the entries before it can catch up after a disconnect: pass the X-Log-Count of its last read. "
+ "When those entries are too large, the response holds the latest turns as tail_bytes alone returns "
+ "them, and X-Log-Offset is greater than start."
+ ),
+ )
+
+ def validate(self, attrs: dict) -> dict:
+ for field in ("before", "start"):
+ if field in attrs and "tail_bytes" not in attrs:
+ raise serializers.ValidationError(f"Use {field} together with tail_bytes.")
+ if "before" in attrs and "start" in attrs:
+ raise serializers.ValidationError("Use before or start, not both.")
+ return attrs
+
+
class StreamReadTokenQuerySerializer(serializers.Serializer):
"""Query parameters for requesting a task run stream read token"""
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 39e743cda992..51a8828b52ae 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -202,6 +202,7 @@ from products.tasks.backend.presentation.serializers import (
TaskRunLivingArtifactOpenResponseSerializer,
TaskRunLivingArtifactResponseSerializer,
TaskRunLivingArtifactsResponseSerializer,
+ TaskRunLogsQuerySerializer,
TaskRunPeerMessageRequestSerializer,
TaskRunPeerMessageResponseSerializer,
TaskRunPeersResponseSerializer,
@@ -3545,7 +3546,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
raise NotFound()
return Response(TaskRunPeerMessageResponseSerializer(result).data)
- @extend_schema(
+ @validated_request(
+ query_serializer=TaskRunLogsQuerySerializer,
extensions={"x-product": "logs"},
responses={
200: OpenApiResponse(description="Log content in JSONL format"),
@@ -3560,21 +3562,50 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"includes the earlier runs of its task session the same way, each "
"preceded by a pi_run_started entry that names its run. For a live "
"presence-gated run, the request marks the stream as watched before "
- "it reads the log, so events after the snapshot reach the live stream."
+ "it reads the log, so events after the snapshot reach the live stream. Pass tail_bytes to read only "
+ "the latest turns first, add before to page back through older turns, or add start to read every "
+ "entry after the ones a client holds. X-Log-Origin names the first run of the chain: indexes from responses "
+ "with different origins do not match. A Pi run returns its full log without the X-Log headers."
),
)
@action(detail=True, methods=["get"], url_path="logs", required_scopes=["task:read"])
def logs(self, request, pk=None, **kwargs):
task_id = self._ensure_task_accessible()
+ query = request.validated_query_data
timer = ServerTimingsGathered()
with timer("mark_watched"):
tasks_facade.mark_task_run_stream_watched(pk, task_id, self.team_id)
- with timer("s3_read"):
- log_content = tasks_facade.read_task_run_conversation_logs(pk, task_id, self.team_id)
- if log_content is None:
- raise NotFound()
+ if "tail_bytes" not in query:
+ with timer("s3_read"):
+ log_content = tasks_facade.read_task_run_conversation_logs(pk, task_id, self.team_id)
+ if log_content is None:
+ raise NotFound()
+ response = HttpResponse(log_content, content_type="application/jsonl")
+ else:
+ with timer("s3_read"):
+ log_slice = tasks_facade.read_task_run_conversation_log_slice(
+ pk,
+ task_id,
+ self.team_id,
+ tail_bytes=query["tail_bytes"],
+ before=query.get("before"),
+ start=query.get("start"),
+ )
+ if log_slice is None:
+ raise NotFound()
+ response = HttpResponse(log_slice.content, content_type="application/jsonl")
+ if log_slice.sliced:
+ response["X-Log-Offset"] = str(log_slice.offset)
+ response["X-Log-Count"] = str(log_slice.count)
+ response["X-Log-Preamble"] = str(log_slice.preamble)
+ response["X-Log-Turns-Before"] = str(log_slice.turns_before)
+ response["X-Log-Origin"] = log_slice.origin
+ # A cross-origin frontend (standalone OAuth mode) can read only exposed headers, and a page whose
+ # headers it cannot read looks like the whole log.
+ response["Access-Control-Expose-Headers"] = (
+ "X-Log-Offset, X-Log-Count, X-Log-Preamble, X-Log-Turns-Before, X-Log-Origin"
+ )
- response = HttpResponse(log_content, content_type="application/jsonl")
response["Cache-Control"] = "no-cache"
response["Server-Timing"] = timer.to_header_string()
return response
diff --git a/products/tasks/backend/tests/fixtures/log_pages.json b/products/tasks/backend/tests/fixtures/log_pages.json
new file mode 100644
index 000000000000..0396519799dd
--- /dev/null
+++ b/products/tasks/backend/tests/fixtures/log_pages.json
@@ -0,0 +1,4367 @@
+{
+ "cases": [
+ {
+ "name": "one_run",
+ "tail_bytes": 1500,
+ "parts": [
+ [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b1-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b1-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "default"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:03Z",
+ "event_id": "b1-3",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "available_commands_update",
+ "availableCommands": [
+ {
+ "name": "clear",
+ "description": "Clear the chat"
+ }
+ ]
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:04Z",
+ "event_id": "b1-4",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Which pages get the most views?"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:05Z",
+ "event_id": "b1-5",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Which pages get the most views?"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:06Z",
+ "event_id": "b1-6",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Which pages get the most views?"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:07Z",
+ "event_id": "b1-7",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "t1",
+ "title": "query pageviews",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "query pageviews"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:08Z",
+ "event_id": "b1-8",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "t1",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:09Z",
+ "event_id": "b1-9",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "The pricing page gets the most views."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:10Z",
+ "event_id": "b1-10",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 900
+ },
+ "cost": 0.009
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:11Z",
+ "event_id": "b1-11",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 10000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:12Z",
+ "event_id": "b1-12",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:13Z",
+ "event_id": "b1-13",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Compare this week with last week"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:14Z",
+ "event_id": "b1-14",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Compare this week with last week"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:15Z",
+ "event_id": "b1-15",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Compare this week with last week"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:16Z",
+ "event_id": "b1-16",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "a1",
+ "title": "this week",
+ "status": "in_progress"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:17Z",
+ "event_id": "b1-17",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "b1",
+ "title": "last week",
+ "status": "in_progress"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:18Z",
+ "event_id": "b1-18",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "a1",
+ "status": "completed",
+ "rawOutput": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:19Z",
+ "event_id": "b1-19",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "b1",
+ "status": "completed",
+ "rawOutput": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:20Z",
+ "event_id": "b1-20",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "Views grew by a tenth."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:21Z",
+ "event_id": "b1-21",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "current_mode_update",
+ "currentModeId": "plan"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:22Z",
+ "event_id": "b1-22",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 2100
+ },
+ "cost": 0.021
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:23Z",
+ "event_id": "b1-23",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 22000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:24Z",
+ "event_id": "b1-24",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:25Z",
+ "event_id": "b1-25",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Summarize the signup funnel"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:26Z",
+ "event_id": "b1-26",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Summarize the signup funnel"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:27Z",
+ "event_id": "b1-27",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Summarize the signup funnel"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:28Z",
+ "event_id": "b1-28",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "task-1",
+ "title": "Task",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "Task"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:29Z",
+ "event_id": "b1-29",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "child-1",
+ "title": "funnel steps",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "funnel steps"
+ },
+ "_meta": {
+ "claudeCode": {
+ "parentToolCallId": "task-1"
+ }
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:30Z",
+ "event_id": "b1-30",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "child-1",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr",
+ "_meta": {
+ "claudeCode": {
+ "parentToolCallId": "task-1"
+ }
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:31Z",
+ "event_id": "b1-31",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "child-2",
+ "title": "drop-off",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "drop-off"
+ },
+ "_meta": {
+ "claudeCode": {
+ "parentToolCallId": "task-1"
+ }
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:32Z",
+ "event_id": "b1-32",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "child-2",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr",
+ "_meta": {
+ "claudeCode": {
+ "parentToolCallId": "task-1"
+ }
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:33Z",
+ "event_id": "b1-33",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "task-1",
+ "status": "completed",
+ "rawOutput": "done"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:34Z",
+ "event_id": "b1-34",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "Most people leave at the second step."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:35Z",
+ "event_id": "b1-35",
+ "notification": {
+ "method": "_posthog/permission_request",
+ "params": {
+ "requestId": "p1",
+ "toolCall": {
+ "toolCallId": "w1",
+ "toolName": "dashboard-create"
+ },
+ "options": [
+ {
+ "optionId": "allow_once",
+ "name": "Allow",
+ "kind": "allow_once"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:36Z",
+ "event_id": "b1-36",
+ "notification": {
+ "method": "_posthog/permission_resolved",
+ "params": {
+ "requestId": "p1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:37Z",
+ "event_id": "b1-37",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 3600
+ },
+ "cost": 0.036
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:38Z",
+ "event_id": "b1-38",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 37000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:39Z",
+ "event_id": "b1-39",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:40Z",
+ "event_id": "b1-40",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Show me retention"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:41Z",
+ "event_id": "b1-41",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Show me retention"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:42Z",
+ "event_id": "b1-42",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Show me retention"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:43Z",
+ "event_id": "b1-43",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "r1",
+ "title": "query retention",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "query retention"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:44Z",
+ "event_id": "b1-44",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Also add a chart"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:45Z",
+ "event_id": "b1-45",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "r1",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:46Z",
+ "event_id": "b1-46",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "Retention is flat."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:47Z",
+ "event_id": "b1-47",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 4600
+ },
+ "cost": 0.046
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:48Z",
+ "event_id": "b1-48",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 47000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:49Z",
+ "event_id": "b1-49",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:50Z",
+ "event_id": "b1-50",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Also add a chart"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:51Z",
+ "event_id": "b1-51",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Also add a chart"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:52Z",
+ "event_id": "b1-52",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "c1",
+ "title": "create chart",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "create chart"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:53Z",
+ "event_id": "b1-53",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "c1",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:54Z",
+ "event_id": "b1-54",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "I added the chart."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:55Z",
+ "event_id": "b1-55",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 5400
+ },
+ "cost": 0.054
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:56Z",
+ "event_id": "b1-56",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 55000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:57Z",
+ "event_id": "b1-57",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:58Z",
+ "event_id": "b1-58",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "One more thing"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:59Z",
+ "event_id": "b1-59",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "and export it"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:00Z",
+ "event_id": "b1-60",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "e1",
+ "title": "export",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "export"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:01Z",
+ "event_id": "b1-61",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "e1",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:02Z",
+ "event_id": "b1-62",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "Exported."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:03Z",
+ "event_id": "b1-63",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "current_mode_update",
+ "currentModeId": "default"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:04Z",
+ "event_id": "b1-64",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 6300
+ },
+ "cost": 0.063
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:05Z",
+ "event_id": "b1-65",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 64000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:06Z",
+ "event_id": "b1-66",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:07Z",
+ "event_id": "b1-67",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Delete the old dashboard"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:08Z",
+ "event_id": "b1-68",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Delete the old dashboard"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:09Z",
+ "event_id": "b1-69",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Delete the old dashboard"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:10Z",
+ "event_id": "b1-70",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "d1",
+ "title": "dashboard-delete",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "dashboard-delete"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:11Z",
+ "event_id": "b1-71",
+ "notification": {
+ "method": "_posthog/permission_request",
+ "params": {
+ "requestId": "p2",
+ "toolCall": {
+ "toolCallId": "d1",
+ "toolName": "dashboard-delete"
+ },
+ "options": [
+ {
+ "optionId": "allow_once",
+ "name": "Allow",
+ "kind": "allow_once"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ ],
+ "pages": [
+ {
+ "offset": 57,
+ "count": 71,
+ "preamble": 6,
+ "turns_before": 5,
+ "entries": [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b1-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b1-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "default"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:03Z",
+ "event_id": "b1-3",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "available_commands_update",
+ "availableCommands": [
+ {
+ "name": "clear",
+ "description": "Clear the chat"
+ }
+ ]
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:21Z",
+ "event_id": "b1-21",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "current_mode_update",
+ "currentModeId": "plan"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:55Z",
+ "event_id": "b1-55",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 5400
+ },
+ "cost": 0.054
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:56Z",
+ "event_id": "b1-56",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 55000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:58Z",
+ "event_id": "b1-58",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "One more thing"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:59Z",
+ "event_id": "b1-59",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "and export it"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:00Z",
+ "event_id": "b1-60",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "e1",
+ "title": "export",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "export"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:01Z",
+ "event_id": "b1-61",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "e1",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:02Z",
+ "event_id": "b1-62",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "Exported."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:03Z",
+ "event_id": "b1-63",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "current_mode_update",
+ "currentModeId": "default"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:04Z",
+ "event_id": "b1-64",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 6300
+ },
+ "cost": 0.063
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:05Z",
+ "event_id": "b1-65",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 64000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:06Z",
+ "event_id": "b1-66",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:07Z",
+ "event_id": "b1-67",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Delete the old dashboard"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:08Z",
+ "event_id": "b1-68",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Delete the old dashboard"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:09Z",
+ "event_id": "b1-69",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Delete the old dashboard"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:10Z",
+ "event_id": "b1-70",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "d1",
+ "title": "dashboard-delete",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "dashboard-delete"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:01:11Z",
+ "event_id": "b1-71",
+ "notification": {
+ "method": "_posthog/permission_request",
+ "params": {
+ "requestId": "p2",
+ "toolCall": {
+ "toolCallId": "d1",
+ "toolName": "dashboard-delete"
+ },
+ "options": [
+ {
+ "optionId": "allow_once",
+ "name": "Allow",
+ "kind": "allow_once"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ {
+ "offset": 39,
+ "count": 71,
+ "preamble": 6,
+ "turns_before": 3,
+ "entries": [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b1-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b1-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "default"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:03Z",
+ "event_id": "b1-3",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "available_commands_update",
+ "availableCommands": [
+ {
+ "name": "clear",
+ "description": "Clear the chat"
+ }
+ ]
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:21Z",
+ "event_id": "b1-21",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "current_mode_update",
+ "currentModeId": "plan"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:37Z",
+ "event_id": "b1-37",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 3600
+ },
+ "cost": 0.036
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:38Z",
+ "event_id": "b1-38",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 37000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:40Z",
+ "event_id": "b1-40",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Show me retention"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:41Z",
+ "event_id": "b1-41",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Show me retention"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:42Z",
+ "event_id": "b1-42",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Show me retention"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:43Z",
+ "event_id": "b1-43",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "r1",
+ "title": "query retention",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "query retention"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:44Z",
+ "event_id": "b1-44",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Also add a chart"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:45Z",
+ "event_id": "b1-45",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "r1",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:46Z",
+ "event_id": "b1-46",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "Retention is flat."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:47Z",
+ "event_id": "b1-47",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 4600
+ },
+ "cost": 0.046
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:48Z",
+ "event_id": "b1-48",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 47000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:49Z",
+ "event_id": "b1-49",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:50Z",
+ "event_id": "b1-50",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Also add a chart"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:51Z",
+ "event_id": "b1-51",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Also add a chart"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:52Z",
+ "event_id": "b1-52",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "c1",
+ "title": "create chart",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "create chart"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:53Z",
+ "event_id": "b1-53",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "c1",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:54Z",
+ "event_id": "b1-54",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "I added the chart."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:55Z",
+ "event_id": "b1-55",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 5400
+ },
+ "cost": 0.054
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:56Z",
+ "event_id": "b1-56",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 55000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:57Z",
+ "event_id": "b1-57",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ }
+ ]
+ },
+ {
+ "offset": 24,
+ "count": 71,
+ "preamble": 6,
+ "turns_before": 2,
+ "entries": [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b1-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b1-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "default"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:03Z",
+ "event_id": "b1-3",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "available_commands_update",
+ "availableCommands": [
+ {
+ "name": "clear",
+ "description": "Clear the chat"
+ }
+ ]
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:21Z",
+ "event_id": "b1-21",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "current_mode_update",
+ "currentModeId": "plan"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:22Z",
+ "event_id": "b1-22",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 2100
+ },
+ "cost": 0.021
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:23Z",
+ "event_id": "b1-23",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 22000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:25Z",
+ "event_id": "b1-25",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Summarize the signup funnel"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:26Z",
+ "event_id": "b1-26",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Summarize the signup funnel"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:27Z",
+ "event_id": "b1-27",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Summarize the signup funnel"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:28Z",
+ "event_id": "b1-28",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "task-1",
+ "title": "Task",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "Task"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:29Z",
+ "event_id": "b1-29",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "child-1",
+ "title": "funnel steps",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "funnel steps"
+ },
+ "_meta": {
+ "claudeCode": {
+ "parentToolCallId": "task-1"
+ }
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:30Z",
+ "event_id": "b1-30",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "child-1",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr",
+ "_meta": {
+ "claudeCode": {
+ "parentToolCallId": "task-1"
+ }
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:31Z",
+ "event_id": "b1-31",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "child-2",
+ "title": "drop-off",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "drop-off"
+ },
+ "_meta": {
+ "claudeCode": {
+ "parentToolCallId": "task-1"
+ }
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:32Z",
+ "event_id": "b1-32",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "child-2",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr",
+ "_meta": {
+ "claudeCode": {
+ "parentToolCallId": "task-1"
+ }
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:33Z",
+ "event_id": "b1-33",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "task-1",
+ "status": "completed",
+ "rawOutput": "done"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:34Z",
+ "event_id": "b1-34",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "Most people leave at the second step."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:35Z",
+ "event_id": "b1-35",
+ "notification": {
+ "method": "_posthog/permission_request",
+ "params": {
+ "requestId": "p1",
+ "toolCall": {
+ "toolCallId": "w1",
+ "toolName": "dashboard-create"
+ },
+ "options": [
+ {
+ "optionId": "allow_once",
+ "name": "Allow",
+ "kind": "allow_once"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:36Z",
+ "event_id": "b1-36",
+ "notification": {
+ "method": "_posthog/permission_resolved",
+ "params": {
+ "requestId": "p1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:37Z",
+ "event_id": "b1-37",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 3600
+ },
+ "cost": 0.036
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:38Z",
+ "event_id": "b1-38",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 37000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:39Z",
+ "event_id": "b1-39",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ }
+ ]
+ },
+ {
+ "offset": 12,
+ "count": 71,
+ "preamble": 5,
+ "turns_before": 1,
+ "entries": [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b1-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b1-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "default"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:03Z",
+ "event_id": "b1-3",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "available_commands_update",
+ "availableCommands": [
+ {
+ "name": "clear",
+ "description": "Clear the chat"
+ }
+ ]
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:10Z",
+ "event_id": "b1-10",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 900
+ },
+ "cost": 0.009
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:11Z",
+ "event_id": "b1-11",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 10000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:13Z",
+ "event_id": "b1-13",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Compare this week with last week"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:14Z",
+ "event_id": "b1-14",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Compare this week with last week"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:15Z",
+ "event_id": "b1-15",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Compare this week with last week"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:16Z",
+ "event_id": "b1-16",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "a1",
+ "title": "this week",
+ "status": "in_progress"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:17Z",
+ "event_id": "b1-17",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "b1",
+ "title": "last week",
+ "status": "in_progress"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:18Z",
+ "event_id": "b1-18",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "a1",
+ "status": "completed",
+ "rawOutput": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:19Z",
+ "event_id": "b1-19",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "b1",
+ "status": "completed",
+ "rawOutput": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:20Z",
+ "event_id": "b1-20",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "Views grew by a tenth."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:21Z",
+ "event_id": "b1-21",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "current_mode_update",
+ "currentModeId": "plan"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:22Z",
+ "event_id": "b1-22",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 2100
+ },
+ "cost": 0.021
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:23Z",
+ "event_id": "b1-23",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 22000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:24Z",
+ "event_id": "b1-24",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ }
+ ]
+ },
+ {
+ "offset": 3,
+ "count": 71,
+ "preamble": 3,
+ "turns_before": 0,
+ "entries": [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b1-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b1-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "default"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:03Z",
+ "event_id": "b1-3",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "available_commands_update",
+ "availableCommands": [
+ {
+ "name": "clear",
+ "description": "Clear the chat"
+ }
+ ]
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:04Z",
+ "event_id": "b1-4",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Which pages get the most views?"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:05Z",
+ "event_id": "b1-5",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Which pages get the most views?"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:06Z",
+ "event_id": "b1-6",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Which pages get the most views?"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:07Z",
+ "event_id": "b1-7",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "t1",
+ "title": "query pageviews",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "query pageviews"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:08Z",
+ "event_id": "b1-8",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "t1",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:09Z",
+ "event_id": "b1-9",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "The pricing page gets the most views."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:10Z",
+ "event_id": "b1-10",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 900
+ },
+ "cost": 0.009
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:11Z",
+ "event_id": "b1-11",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 10000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:12Z",
+ "event_id": "b1-12",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ }
+ ]
+ },
+ {
+ "offset": 0,
+ "count": 71,
+ "preamble": 0,
+ "turns_before": 0,
+ "entries": [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b1-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b1-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "default"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:03Z",
+ "event_id": "b1-3",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "available_commands_update",
+ "availableCommands": [
+ {
+ "name": "clear",
+ "description": "Clear the chat"
+ }
+ ]
+ }
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "resume_chain",
+ "tail_bytes": 1200,
+ "parts": [
+ [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b1-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b1-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "default"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:03Z",
+ "event_id": "b1-3",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "How many signups this month?"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:04Z",
+ "event_id": "b1-4",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "How many signups this month?"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:05Z",
+ "event_id": "b1-5",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "How many signups this month?"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:06Z",
+ "event_id": "b1-6",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "s1",
+ "title": "query signups",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "query signups"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:07Z",
+ "event_id": "b1-7",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "s1",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:08Z",
+ "event_id": "b1-8",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "There were 120 signups."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:09Z",
+ "event_id": "b1-9",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 800
+ },
+ "cost": 0.008
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:10Z",
+ "event_id": "b1-10",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 9000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:11Z",
+ "event_id": "b1-11",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:12Z",
+ "event_id": "b1-12",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "And last month?"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:13Z",
+ "event_id": "b1-13",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "And last month?"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:14Z",
+ "event_id": "b1-14",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "And last month?"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:15Z",
+ "event_id": "b1-15",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "s2",
+ "title": "query signups",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "query signups"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:16Z",
+ "event_id": "b1-16",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "s2",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:17Z",
+ "event_id": "b1-17",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "There were 90 signups."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:18Z",
+ "event_id": "b1-18",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 1700
+ },
+ "cost": 0.017
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:19Z",
+ "event_id": "b1-19",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 18000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:20Z",
+ "event_id": "b1-20",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ }
+ ],
+ [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b2-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-2"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b2-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "bypassPermissions"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:03Z",
+ "event_id": "b2-3",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "You are resuming a previous conversation."
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:04Z",
+ "event_id": "b2-4",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "You are resuming a previous conversation. Here is what happened."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:05Z",
+ "event_id": "b2-5",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Break it down by country"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:06Z",
+ "event_id": "b2-6",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Break it down by country"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:07Z",
+ "event_id": "b2-7",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Break it down by country"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:08Z",
+ "event_id": "b2-8",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "s3",
+ "title": "query countries",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "query countries"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:09Z",
+ "event_id": "b2-9",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "s3",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:10Z",
+ "event_id": "b2-10",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "Most signups come from the US."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:11Z",
+ "event_id": "b2-11",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 1000
+ },
+ "cost": 0.01
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:12Z",
+ "event_id": "b2-12",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 11000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:13Z",
+ "event_id": "b2-13",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:14Z",
+ "event_id": "b2-14",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "How many signups this month?"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:15Z",
+ "event_id": "b2-15",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "How many signups this month?"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:16Z",
+ "event_id": "b2-16",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "How many signups this month?"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:17Z",
+ "event_id": "b2-17",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "s4",
+ "title": "query signups",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "query signups"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:18Z",
+ "event_id": "b2-18",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "s4",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:19Z",
+ "event_id": "b2-19",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "Still 120."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:20Z",
+ "event_id": "b2-20",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 1900
+ },
+ "cost": 0.019
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:21Z",
+ "event_id": "b2-21",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 20000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:22Z",
+ "event_id": "b2-22",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:23Z",
+ "event_id": "b2-23",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Thanks"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:24Z",
+ "event_id": "b2-24",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Thanks"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:25Z",
+ "event_id": "b2-25",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Thanks"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:26Z",
+ "event_id": "b2-26",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "You are welcome."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:27Z",
+ "event_id": "b2-27",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 2600
+ },
+ "cost": 0.026
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:28Z",
+ "event_id": "b2-28",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 27000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:29Z",
+ "event_id": "b2-29",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ }
+ ]
+ ],
+ "pages": [
+ {
+ "offset": 42,
+ "count": 49,
+ "preamble": 4,
+ "turns_before": 4,
+ "entries": [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b2-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-2"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b2-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "bypassPermissions"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:20Z",
+ "event_id": "b2-20",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 1900
+ },
+ "cost": 0.019
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:21Z",
+ "event_id": "b2-21",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 20000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:23Z",
+ "event_id": "b2-23",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Thanks"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:24Z",
+ "event_id": "b2-24",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Thanks"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:25Z",
+ "event_id": "b2-25",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Thanks"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:26Z",
+ "event_id": "b2-26",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "You are welcome."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:27Z",
+ "event_id": "b2-27",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 2600
+ },
+ "cost": 0.026
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:28Z",
+ "event_id": "b2-28",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 27000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:29Z",
+ "event_id": "b2-29",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ }
+ ]
+ },
+ {
+ "offset": 33,
+ "count": 49,
+ "preamble": 4,
+ "turns_before": 3,
+ "entries": [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b2-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-2"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b2-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "bypassPermissions"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:11Z",
+ "event_id": "b2-11",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 1000
+ },
+ "cost": 0.01
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:12Z",
+ "event_id": "b2-12",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 11000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:14Z",
+ "event_id": "b2-14",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "How many signups this month?"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:15Z",
+ "event_id": "b2-15",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "How many signups this month?"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:16Z",
+ "event_id": "b2-16",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "How many signups this month?"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:17Z",
+ "event_id": "b2-17",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "s4",
+ "title": "query signups",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "query signups"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:18Z",
+ "event_id": "b2-18",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "s4",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:19Z",
+ "event_id": "b2-19",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "Still 120."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:20Z",
+ "event_id": "b2-20",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 1900
+ },
+ "cost": 0.019
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:21Z",
+ "event_id": "b2-21",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 20000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:22Z",
+ "event_id": "b2-22",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ }
+ ]
+ },
+ {
+ "offset": 23,
+ "count": 49,
+ "preamble": 4,
+ "turns_before": 2,
+ "entries": [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:18Z",
+ "event_id": "b1-18",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 1700
+ },
+ "cost": 0.017
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:19Z",
+ "event_id": "b1-19",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 18000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b2-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-2"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b2-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "bypassPermissions"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:04Z",
+ "event_id": "b2-4",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "You are resuming a previous conversation. Here is what happened."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:05Z",
+ "event_id": "b2-5",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "Break it down by country"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:06Z",
+ "event_id": "b2-6",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "Break it down by country"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:07Z",
+ "event_id": "b2-7",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "Break it down by country"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:08Z",
+ "event_id": "b2-8",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "s3",
+ "title": "query countries",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "query countries"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:09Z",
+ "event_id": "b2-9",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "s3",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:10Z",
+ "event_id": "b2-10",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "Most signups come from the US."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:11Z",
+ "event_id": "b2-11",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 1000
+ },
+ "cost": 0.01
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:12Z",
+ "event_id": "b2-12",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 11000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:13Z",
+ "event_id": "b2-13",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ }
+ ]
+ },
+ {
+ "offset": 11,
+ "count": 49,
+ "preamble": 4,
+ "turns_before": 1,
+ "entries": [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b1-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b1-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "default"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:09Z",
+ "event_id": "b1-9",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 800
+ },
+ "cost": 0.008
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:10Z",
+ "event_id": "b1-10",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 9000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:12Z",
+ "event_id": "b1-12",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "And last month?"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:13Z",
+ "event_id": "b1-13",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "And last month?"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:14Z",
+ "event_id": "b1-14",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "And last month?"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:15Z",
+ "event_id": "b1-15",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "s2",
+ "title": "query signups",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "query signups"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:16Z",
+ "event_id": "b1-16",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "s2",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:17Z",
+ "event_id": "b1-17",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "There were 90 signups."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:18Z",
+ "event_id": "b1-18",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 1700
+ },
+ "cost": 0.017
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:19Z",
+ "event_id": "b1-19",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 18000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:20Z",
+ "event_id": "b1-20",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b2-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-2"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b2-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "bypassPermissions"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:03Z",
+ "event_id": "b2-3",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "You are resuming a previous conversation."
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ {
+ "offset": 2,
+ "count": 49,
+ "preamble": 2,
+ "turns_before": 0,
+ "entries": [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b1-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b1-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "default"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:03Z",
+ "event_id": "b1-3",
+ "notification": {
+ "method": "_posthog/user_message",
+ "params": {
+ "content": "How many signups this month?"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:04Z",
+ "event_id": "b1-4",
+ "notification": {
+ "method": "session/prompt",
+ "params": {
+ "prompt": [
+ {
+ "type": "text",
+ "text": "How many signups this month?"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:05Z",
+ "event_id": "b1-5",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "How many signups this month?"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:06Z",
+ "event_id": "b1-6",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "s1",
+ "title": "query signups",
+ "status": "in_progress",
+ "rawInput": {
+ "command": "query signups"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:07Z",
+ "event_id": "b1-7",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "s1",
+ "status": "completed",
+ "rawOutput": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:08Z",
+ "event_id": "b1-8",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "agent_message",
+ "content": {
+ "type": "text",
+ "text": "There were 120 signups."
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:09Z",
+ "event_id": "b1-9",
+ "notification": {
+ "method": "_posthog/usage_update",
+ "params": {
+ "used": {
+ "inputTokens": 800
+ },
+ "cost": 0.008
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:10Z",
+ "event_id": "b1-10",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "usage_update",
+ "used": 9000,
+ "size": 200000
+ }
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:11Z",
+ "event_id": "b1-11",
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {}
+ }
+ }
+ ]
+ },
+ {
+ "offset": 0,
+ "count": 49,
+ "preamble": 0,
+ "turns_before": 0,
+ "entries": [
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "event_id": "b1-1",
+ "notification": {
+ "method": "_posthog/run_started",
+ "params": {
+ "runId": "run-1"
+ }
+ }
+ },
+ {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02Z",
+ "event_id": "b1-2",
+ "notification": {
+ "method": "session/new",
+ "params": {
+ "_meta": {
+ "permissionMode": "default"
+ }
+ }
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index f0820963887c..0ce605ee5ca0 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -11198,6 +11198,54 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.content.decode("utf-8").splitlines(), expected_lines)
+ @parameterized.expand(
+ [
+ ("latest_turn_across_the_chain", "?tail_bytes=1", status.HTTP_200_OK, ("2", "3", "1"), ["latest"]),
+ ("older_page_before_an_offset", "?tail_bytes=1&before=2", status.HTTP_200_OK, ("0", "3", "0"), ["older"]),
+ ("before_needs_tail_bytes", "?before=2", status.HTTP_400_BAD_REQUEST, None, None),
+ ("entries_after_a_start_index", "?tail_bytes=1&start=2", status.HTTP_200_OK, ("2", "3", "0"), ["latest"]),
+ ("start_needs_tail_bytes", "?start=2", status.HTTP_400_BAD_REQUEST, None, None),
+ ]
+ )
+ @patch("posthog.storage.object_storage.read")
+ def test_logs_endpoint_pages_through_the_resume_chain(
+ self,
+ _name: str,
+ query: str,
+ expected_status: int,
+ expected_headers: tuple[str, str, str] | None,
+ expected_turns: list[str] | None,
+ mock_read,
+ ):
+ task = self.create_task()
+ ancestor = TaskRun.objects.create(task=task, team=self.team)
+ target = TaskRun.objects.create(task=task, team=self.team, state={"resume_from_run_id": str(ancestor.id)})
+
+ def user_turn(text: str) -> str:
+ update = {"sessionUpdate": "user_message_chunk", "content": {"type": "text", "text": text}}
+ return json.dumps({"notification": {"method": "session/update", "params": {"update": update}}})
+
+ run_started = json.dumps({"notification": {"method": "_posthog/run_started", "params": {"runId": "r"}}})
+ logs = {ancestor.log_url: f"{user_turn('older')}\n{run_started}\n", target.log_url: f"{user_turn('latest')}\n"}
+ mock_read.side_effect = lambda path, missing_ok=False: logs.get(path)
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{target.id}/logs/{query}")
+
+ self.assertEqual(response.status_code, expected_status)
+ if expected_headers is not None:
+ self.assertEqual(
+ (response["X-Log-Offset"], response["X-Log-Count"], response["X-Log-Preamble"]), expected_headers
+ )
+ self.assertEqual(response["X-Log-Origin"], str(ancestor.id))
+ self.assertIn("X-Log-Origin", response["Access-Control-Expose-Headers"])
+ lines = [json.loads(line) for line in response.content.decode("utf-8").splitlines()]
+ turns = [
+ line["notification"]["params"]["update"]["content"]["text"]
+ for line in lines
+ if line["notification"]["method"] == "session/update"
+ ]
+ self.assertEqual(turns, expected_turns)
+
@parameterized.expand(
[
("live_gated_run_is_marked", TaskRun.Status.IN_PROGRESS, True, True),
diff --git a/products/tasks/backend/tests/test_log_slice.py b/products/tasks/backend/tests/test_log_slice.py
new file mode 100644
index 000000000000..8c9a9d842624
--- /dev/null
+++ b/products/tasks/backend/tests/test_log_slice.py
@@ -0,0 +1,313 @@
+import os
+import json
+from pathlib import Path
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.tasks.backend.logic.log_slice import (
+ LogPart,
+ log_entries,
+ log_part,
+ slice_log_from,
+ slice_log_parts_tail,
+ slice_log_tail,
+ summarize_log_part,
+ summary_from_json,
+ summary_to_json,
+)
+
+# The client tests replay these pages, so they run against what this slicer returns.
+LOG_PAGE_FIXTURES = Path(__file__).parent / "fixtures" / "log_pages.json"
+
+
+def _line(method: str, params: dict | None = None) -> str:
+ return json.dumps({"type": "notification", "notification": {"method": method, "params": params or {}}})
+
+
+def _update(session_update: str, **fields: object) -> str:
+ return _line("session/update", {"update": {"sessionUpdate": session_update, **fields}})
+
+
+def _user(text: str) -> str:
+ return _update("user_message_chunk", content={"type": "text", "text": text})
+
+
+def _tool(call_id: str, output_bytes: int) -> list[str]:
+ return [
+ _update("tool_call", toolCallId=call_id, title="Bash"),
+ _update("tool_call_update", toolCallId=call_id, status="completed", rawOutput="x" * output_bytes),
+ ]
+
+
+def _log(lines: list[str]) -> str:
+ return "".join(f"{line}\n" for line in lines)
+
+
+def _turn(text: str, tools: int, output_bytes: int) -> list[str]:
+ lines = [_user(text)]
+ for index in range(tools):
+ lines += _tool(f"{text}-{index}", output_bytes)
+ return [*lines, _update("agent_message", content={"type": "text", "text": f"{text} done"})]
+
+
+class TestSliceLogTail(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("latest_turn_that_meets_the_budget", 1000, None, 10, "second"),
+ ("whole_log_when_the_budget_covers_it", 10**9, None, 0, "first"),
+ ("window_ends_before_the_given_index", 1000, 10, 0, "first"),
+ ]
+ )
+ def test_cuts_at_a_user_turn(
+ self, _name: str, tail_bytes: int, before: int | None, offset: int, first_text: str
+ ) -> None:
+ lines = [*_turn("first", 4, 100), *_turn("second", 4, 100)]
+
+ sliced = slice_log_tail(_log(lines), tail_bytes, before)
+
+ self.assertEqual((sliced.offset, sliced.count, sliced.turns_before), (offset, len(lines), 1 if offset else 0))
+ entries = [json.loads(line) for line in sliced.content.splitlines()][sliced.preamble :]
+ self.assertEqual(entries[0]["notification"]["params"]["update"]["content"]["text"], first_text)
+ self.assertEqual(len(entries), (before if before is not None else len(lines)) - offset)
+
+ @parameterized.expand(
+ [
+ ("acp_whole_message", _update("user_message", content={"type": "text", "text": "second"})),
+ ("posthog_notification", _line("_posthog/user_message", {"content": "second"})),
+ ]
+ )
+ def test_recognizes_every_user_turn_format(self, _name: str, user_line: str) -> None:
+ second = [user_line, *_turn("second", 4, 100)[1:]]
+ lines = [*_turn("first", 4, 100), *second]
+
+ sliced = slice_log_tail(_log(lines), 1000)
+
+ self.assertEqual(sliced.content.splitlines()[sliced.preamble], user_line)
+
+ @parameterized.expand(
+ [
+ (
+ "nested_subagent_calls",
+ [
+ _update("tool_call", toolCallId="parent", title="Task"),
+ *[
+ _update(
+ kind,
+ toolCallId=f"child-{index}",
+ title="Bash",
+ rawOutput="x" * 1000,
+ _meta={"claudeCode": {"parentToolCallId": "parent"}},
+ )
+ for index in range(12)
+ for kind in ("tool_call", "tool_call_update")
+ ],
+ ],
+ ),
+ (
+ "parallel_calls",
+ [
+ _update(kind, toolCallId=f"{name}-{index}", title="Bash", rawOutput="x" * 1000)
+ for index in range(12)
+ for kind, name in (
+ ("tool_call", "a"),
+ ("tool_call", "b"),
+ ("tool_call_update", "a"),
+ ("tool_call_update", "b"),
+ )
+ ],
+ ),
+ ]
+ )
+ def test_cut_leaves_no_tool_frame_without_its_call(self, _name: str, tool_lines: list[str]) -> None:
+ lines = [_user("only"), *tool_lines]
+
+ sliced = slice_log_tail(_log(lines), 2000)
+
+ window = [json.loads(line)["notification"]["params"]["update"] for line in sliced.content.splitlines()]
+ called = {update["toolCallId"] for update in window if update["sessionUpdate"] == "tool_call"}
+ referenced = {update["toolCallId"] for update in window} | {
+ update["_meta"]["claudeCode"]["parentToolCallId"] for update in window if "_meta" in update
+ }
+ self.assertGreater(sliced.offset, 0)
+ self.assertEqual(referenced - called, set())
+
+ @parameterized.expand(
+ [
+ ("echo_after_its_prompt", []),
+ ("echo_a_turn_later", [_update("agent_message", content={"type": "text", "text": "first done"})]),
+ ]
+ )
+ def test_cut_keeps_both_forms_of_a_message_on_one_side(self, _name: str, between: list[str]) -> None:
+ queued = [_line("_posthog/user_message", {"content": "second"}), *between, _line("session/prompt")]
+ # An older send of the same text whose echo never came must not hold the cut back to it.
+ unanswered = [_line("_posthog/user_message", {"content": "second"}), *_turn("old", 4, 100)[1:]]
+ lines = [*unanswered, *_turn("first", 4, 100), *queued, _user("second"), *_turn("second", 4, 100)[1:]]
+
+ sliced = slice_log_tail(_log(lines), 1000)
+
+ window = sliced.content.splitlines()[sliced.preamble :]
+ self.assertEqual(sliced.offset, len(lines) - len(window))
+ self.assertIn(queued[0], window)
+ self.assertIn(_user("second"), window)
+ self.assertGreater(sliced.offset, len(unanswered))
+
+ def test_summary_cache_value_round_trips_as_json(self) -> None:
+ context = "<posthog_untrusted_context>\n- insight abc\n</posthog_untrusted_context>\nwhy"
+ lines = [
+ _line("_posthog/run_started", {"runId": "r"}),
+ _line("_posthog/permission_request", {"requestId": "open"}),
+ _line("_posthog/permission_resolved", {"requestId": "done"}),
+ _line("_posthog/user_message", {"content": context}),
+ *_turn("first", 2, 10),
+ ]
+ summary = summarize_log_part(lines)
+
+ self.assertEqual(summary_from_json(summary_to_json(summary)), summary)
+ self.assertIsNone(summary_from_json('{"count": "x"}'))
+
+ def test_counts_turns_before_the_cut_the_way_the_thread_does(self) -> None:
+ hidden = _update("user_message_chunk", content={"type": "text", "text": "x", "_meta": {"ui": {"hidden": True}}})
+ lines = [
+ _line("_posthog/user_message", {"content": "echoed"}),
+ _line("session/prompt"),
+ _user("echoed"),
+ _update("agent_message", content={"type": "text", "text": "a"}),
+ hidden,
+ _update("agent_message", content={"type": "text", "text": "b"}),
+ _user("one"),
+ _user("two"),
+ _update("agent_message", content={"type": "text", "text": "c"}),
+ *_turn("latest", 0, 0),
+ ]
+
+ sliced = slice_log_tail(_log(lines), 1)
+
+ self.assertEqual((sliced.offset, sliced.turns_before), (9, 3))
+
+ def test_reads_a_log_with_a_method_that_is_not_a_string(self) -> None:
+ malformed = json.dumps({"type": "notification", "notification": {"method": ["_posthog/usage_update"]}})
+ lines = [*_turn("first", 4, 100), malformed, *_turn("second", 4, 100)]
+
+ sliced = slice_log_tail(_log(lines), 1000)
+
+ self.assertEqual(sliced.offset, 11)
+
+ @parameterized.expand(
+ [
+ ("every_entry_from_the_start", 10, 10**9, 10**9, 10, 0),
+ ("latest_turns_when_too_large", 2, 1000, 500, 10, 0),
+ ("from_the_start_when_the_latest_turns_begin_earlier", 18, 10**9, 10, 18, 0),
+ ]
+ )
+ def test_reads_from_a_start_index(
+ self, _name: str, start: int, tail_bytes: int, max_bytes: int, offset: int, preamble: int
+ ) -> None:
+ lines = [*_turn("first", 4, 100), *_turn("second", 4, 100)]
+
+ sliced = slice_log_from(_log(lines), start, tail_bytes, max_bytes)
+
+ self.assertEqual((sliced.offset, sliced.preamble, sliced.count), (offset, preamble, len(lines)))
+ self.assertEqual(sliced.content.splitlines()[sliced.preamble :], lines[offset:])
+
+ def test_cuts_a_turn_past_the_cap_before_a_tool_call(self) -> None:
+ lines = _turn("only", 40, 1000)
+
+ sliced = slice_log_tail(_log(lines), 2000)
+
+ first = json.loads(sliced.content.splitlines()[sliced.preamble])
+ self.assertGreater(sliced.offset, 0)
+ self.assertEqual(first["notification"]["params"]["update"]["sessionUpdate"], "tool_call")
+ self.assertLess(len(sliced.content), 2000 * 5)
+
+ def test_preamble_keeps_the_state_that_still_holds_at_the_cut(self) -> None:
+ head = [
+ _line("_posthog/run_started", {"runId": "old"}),
+ _line("session/new", {"_meta": {"permissionMode": "bypassPermissions"}}),
+ _line("_posthog/run_started", {"runId": "current"}),
+ _line("_posthog/usage_update", {"used": {"inputTokens": 5}, "cost": 0.1}),
+ _line("_posthog/usage_update", {"breakdown": {"tools": 3}}),
+ _line("_posthog/permission_request", {"requestId": "open"}),
+ _line("_posthog/permission_request", {"requestId": "answered"}),
+ _line("_posthog/permission_resolved", {"requestId": "answered"}),
+ ]
+ closed = [_line("_posthog/permission_request", {"requestId": "closed"}), _line("_posthog/turn_complete")]
+ context = "<posthog_untrusted_context>\n- insight abc\n</posthog_untrusted_context>\nwhy"
+ with_context = [_line("_posthog/user_message", {"content": context})]
+ lines = [*closed, *head, *with_context, *_turn("first", 4, 100), *_turn("second", 4, 100)]
+
+ sliced = slice_log_tail(_log(lines), 1000)
+
+ preamble = [json.loads(line)["notification"] for line in sliced.content.splitlines()[: sliced.preamble]]
+ self.assertEqual(preamble[0], {"method": "_posthog/context_history", "params": {"messages": [context]}})
+ self.assertEqual(
+ [(item["method"], item["params"].get("runId") or item["params"].get("requestId")) for item in preamble[1:]],
+ [
+ ("session/new", None),
+ ("_posthog/run_started", "current"),
+ ("_posthog/usage_update", None),
+ ("_posthog/usage_update", None),
+ ("_posthog/permission_request", "open"),
+ ],
+ )
+
+ def test_reads_only_the_runs_the_window_overlaps(self) -> None:
+ runs = [
+ [_line("_posthog/run_started", {"runId": "older"}), *_turn("older", 4, 100)],
+ [_line("_posthog/run_started", {"runId": "newer"}), *_turn("first", 4, 100), *_turn("second", 4, 100)],
+ ]
+ reads: list[int] = []
+
+ def part(index: int) -> LogPart:
+ entries = log_entries("".join(f"{line}\n" for line in runs[index]))
+
+ def read() -> list[str]:
+ reads.append(index)
+ return entries
+
+ return LogPart(summary=summarize_log_part(entries), entries=read)
+
+ sliced = slice_log_parts_tail([part(0), part(1)], 1000)
+
+ self.assertEqual(reads, [1])
+ self.assertEqual((sliced.offset, sliced.count), (len(runs[0]) + 11, len(runs[0]) + len(runs[1])))
+ preamble = [
+ json.loads(line)["notification"]["params"] for line in sliced.content.splitlines()[: sliced.preamble]
+ ]
+ self.assertEqual(preamble, [{"runId": "newer"}])
+
+
+def _pages(case: dict) -> list[dict]:
+ parts = [log_part([json.dumps(entry) for entry in part]) for part in case["parts"]]
+ pages: list[dict] = []
+ before: int | None = None
+ while before != 0:
+ sliced = slice_log_parts_tail(parts, case["tail_bytes"], before)
+ pages.append(
+ {
+ "offset": sliced.offset,
+ "count": sliced.count,
+ "preamble": sliced.preamble,
+ "turns_before": sliced.turns_before,
+ "entries": [json.loads(line) for line in sliced.content.splitlines()],
+ }
+ )
+ before = sliced.offset
+ return pages
+
+
+class TestLogPageFixtures(SimpleTestCase):
+ def test_fixture_pages_are_what_the_slicer_returns(self) -> None:
+ fixture = json.loads(LOG_PAGE_FIXTURES.read_text())
+ pages = {case["name"]: _pages(case) for case in fixture["cases"]}
+ if os.environ.get("UPDATE_LOG_PAGE_FIXTURES"):
+ for case in fixture["cases"]:
+ case["pages"] = pages[case["name"]]
+ LOG_PAGE_FIXTURES.write_text(json.dumps(fixture, indent=1) + "\n")
+
+ self.assertEqual(
+ {case["name"]: case.get("pages") for case in fixture["cases"]},
+ pages,
+ "Run this test with UPDATE_LOG_PAGE_FIXTURES=1 to write the pages again.",
+ )
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 73403f56343b..47280786dd57 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -135508,6 +135508,24 @@ export namespace Schemas {
version?: number;
};
+ export type TasksRunsLogsRetrieveParams = {
+ /**
+ * With tail_bytes, end the window before this entry index, so a client can page back through older turns: pass the X-Log-Offset of the oldest page it holds.
+ * @minimum 0
+ */
+ before?: number;
+ /**
+ * With tail_bytes, return every entry from this index to the end, with no preamble, so a client that holds the entries before it can catch up after a disconnect: pass the X-Log-Count of its last read. When those entries are too large, the response holds the latest turns as tail_bytes alone returns them, and X-Log-Offset is greater than start.
+ * @minimum 0
+ */
+ start?: number;
+ /**
+ * Return only the latest turns of the log: the shortest suffix that starts at a user turn and holds at least this many bytes. The X-Log-Offset and X-Log-Count headers give the index of the first tail entry and the size of the full log. The slice starts with X-Log-Preamble earlier entries that still set run state, such as the run start, usage, mode, commands and open permission requests. X-Log-Turns-Before counts the user turns before the slice, so a client numbers turns the way the full log does.
+ * @minimum 1
+ */
+ tail_bytes?: number;
+ };
+
export type TasksRunsSessionLogsRetrieveParams = {
/**
* Only return events after this ISO8601 timestamp