:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(posthog-ai): rebuild the thread on a trimmed stream cursor (#101107)
Alessandro Pogliaghic6eb18d58329
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 0c4f6eeea682..5ee0f7bf13f7 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -5365,10 +5365,11 @@ const api = {// only on a first connect (no resume cursor); the Last-Event-ID header, when// present, takes precedence and an exact resume ignores `start`.const base = options.proxyTarget.baseUrl.replace(/\/+$/, '')- const url =- !options.lastEventId && options.startLatest- ? `${base}/v1/runs/${runId}/stream?start=latest`- : `${base}/v1/runs/${runId}/stream`+ const params = new URLSearchParams({ resync: '1' })+ if (!options.lastEventId && options.startLatest) {+ params.set('start', 'latest')+ }+ const url = `${base}/v1/runs/${runId}/stream?${params.toString()}`headers['Authorization'] = `Bearer ${options.proxyTarget.token}`return api.getResponse(url, { signal: options.signal, headers })}diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex 830e8285c010..a5a249c43b4a 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -1684,7 +1684,11 @@ export const maxThreadLogic = kea<maxThreadLogicType>([}}return {- [sandboxStreamActionTypes.markTurnComplete]: completeSandboxTurn,+ [sandboxStreamActionTypes.markTurnComplete]: ({ isReplay }: { isReplay?: boolean }) => {+ if (!isReplay) {+ completeSandboxTurn()+ }+ },// handleTerminalStatus fires for every task_run_state frame, including the initial// non-terminal queued/in_progress ones — only tear down on an actually terminal// status, mirroring runStreamLogic's own guard.diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex b41a73403154..704d672f6cce 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -41,7 +41,7 @@ jest.mock('./runStreamLogic', () => {pushConversationCleared: true,respondToPermission: (payload: unknown) => ({ payload }),cancelRun: (run?: unknown) => ({ run }),- markTurnComplete: true,+ markTurnComplete: (isReplay: boolean = false) => ({ isReplay }),setCurrentMode: (mode: string) => ({ mode }),handleTerminalStatus: (status: { status: string }) => status,setStubStatus: (status: string | null) => ({ status }),@@ -610,6 +610,21 @@ describe('runInteractionLogic', () => {expect(logic.values.queuedMessages).toEqual([])})+ it('keeps a staged follow-up queued when history replays an older turn completion', async () => {+ setThinking(true)+ logic.actions.setComposerFormValues({ draft: 'follow up' })+ logic.actions.submitComposerForm()+ expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'follow up' }])++ setThinking(false)+ await expectLogic(logic, () => {+ stream.actions.markTurnComplete(true)+ }).toFinishAllListeners()++ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()+ expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'follow up' }])+ })+it.each(['approval first', 'turn first'])('holds ordinary delivery until both gates clear: %s', async (order) => {const record = { requestId: 'approval-1', sourceRunId: RUN_ID } as PermissionRequestRecordstream.actions.ingestPermissionRequest(record)diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex c0eab1b3dad2..91f1f92a5512 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -251,8 +251,8 @@ export interface runInteractionLogicActions {markPermissionRequestResolved: (requestId: string) => {requestId: string} // runStreamLogic- markTurnComplete: () => {- value: true+ markTurnComplete: (isReplay?: boolean | undefined) => {+ isReplay: boolean} // runStreamLogicpermissionResponseFailed: (requestId: string) => {requestId: string@@ -1313,8 +1313,10 @@ export const runInteractionLogic = kea<runInteractionLogicType>([},// The agent finished a turn — drain any staged follow-ups.- markTurnComplete: () => {- actions.flushQueue()+ markTurnComplete: ({ isReplay }) => {+ if (!isReplay) {+ actions.flushQueue()+ }},// The new model may not support the current effort — clamp the override so it never holds andiff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex c3b696ff4400..37b35a81ecf2 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -158,6 +158,12 @@ class MockStreamConnection {await flushPromises()}+ /** Emit a named `event: end` control frame (a rotation or a resync) without closing the body. */+ async emitEndFrame(payload: Record<string, unknown>): Promise<void> {+ this.deliver({ done: false, value: this.encodeFrame({ data: JSON.stringify(payload), event: 'end' }) })+ await flushPromises()+ }+/** Emit the durable `event: stream-end` end-of-run sentinel, then close the body. */async emitStreamEnd(): Promise<void> {this.deliver({@@ -2431,6 +2437,212 @@ describe('runStreamLogic', () => {jest.useRealTimers()})+ it('rebuilds from history and replays the stream window when the server reports the cursor trimmed', async () => {+ const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()+ await MockStream.latest().emitOpen()+ expect(logsSpy).toHaveBeenCalledTimes(1)+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')+ await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })++ jest.useFakeTimers()+ await MockStream.latest().emitClose()+ await flushPromises()+ jest.advanceTimersByTime(2000)++ // The reopen reads the whole surviving window (no cursor, no start=latest) so the seam dedupe+ // can fill in the in-progress turn, and history is re-read once the connection is up.+ expect(MockStream.latest().options.lastEventId).toBeUndefined()+ expect(MockStream.latest().options.startLatest).toEqual(false)+ expect(window.sessionStorage.getItem('posthog-ai:stream-resume:run-1')).toBeNull()+ jest.useRealTimers()+ await MockStream.latest().emitOpen()+ expect(logsSpy).toHaveBeenCalledTimes(2)++ // A drop before any replayed frame arrives must not fall back to start=latest.+ jest.useFakeTimers()+ await MockStream.latest().emitClose()+ await flushPromises()+ jest.advanceTimersByTime(2000)+ expect(MockStream.latest().options.lastEventId).toBeUndefined()+ expect(MockStream.latest().options.startLatest).toEqual(false)+ jest.useRealTimers()+ await MockStream.latest().emitOpen()+ expect(logsSpy).toHaveBeenCalledTimes(3)+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1800-0')++ // Once a replayed frame establishes a cursor, a drop resumes from it as usual.+ jest.useFakeTimers()+ await MockStream.latest().emitClose()+ await flushPromises()+ jest.advanceTimersByTime(2000)+ expect(MockStream.latest().options.lastEventId).toEqual('1800-0')+ jest.useRealTimers()+ })++ it('re-reads history after a resync on a run whose stream was opened directly', async () => {+ const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })+ await MockStream.latest().emitOpen()+ expect(logsSpy).not.toHaveBeenCalled()+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')+ await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })++ jest.useFakeTimers()+ await MockStream.latest().emitClose()+ await flushPromises()+ jest.advanceTimersByTime(2000)+ expect(MockStream.latest().options.lastEventId).toBeUndefined()+ expect(MockStream.latest().options.startLatest).toEqual(false)+ jest.useRealTimers()+ await MockStream.latest().emitOpen()+ expect(logsSpy).toHaveBeenCalledTimes(1)+ })++ it('replays the surviving window when a send reopens the run while a resync is pending', async () => {+ const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })+ await MockStream.latest().emitOpen()+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')+ await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })+ await MockStream.latest().emitClose()+ await flushPromises()++ // A follow-up send reopens the same run and would otherwise skip to the tail.+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: true })+ await flushPromises()++ expect(MockStream.latest().options.lastEventId).toBeUndefined()+ expect(MockStream.latest().options.startLatest).toEqual(false)+ await MockStream.latest().emitOpen()+ expect(logsSpy).toHaveBeenCalledTimes(1)+ })++ it('re-reads history when a directly opened run finishes during a resync', async () => {+ const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })+ await MockStream.latest().emitOpen()+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')+ await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })+ await MockStream.latest().emitClose()+ await flushPromises()++ expect(logsSpy).toHaveBeenCalledTimes(1)+ expect(logic.values.currentRunStatus).toEqual('completed')+ })++ it('releases the live turn when the resync recovers its completion from history', async () => {+ const turnComplete = notification('_posthog/turn_complete', { stopReason: 'end_turn' })+ let resolveLogs: (entries: StoredLogEntry[]) => void = () => {}+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(+ new Promise<StoredLogEntry[]>((resolve) => (resolveLogs = resolve)) as any+ )+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })+ await MockStream.latest().emitOpen()+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')+ await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })++ jest.useFakeTimers()+ await MockStream.latest().emitClose()+ await flushPromises()+ jest.advanceTimersByTime(2000)+ jest.useRealTimers()+ await MockStream.latest().emitOpen()++ // The turn ended during the outage: the replayed window carries the completion the client+ // never saw live, and the history read that is still in flight carries it too.+ await MockStream.latest().emitMessage(turnComplete, '1800-0')+ expect(logic.values.turnComplete).toEqual(false)++ resolveLogs([turnComplete])+ await flushPromises()++ expect(logic.values.turnComplete).toEqual(true)+ await expectLogic(logic).toDispatchActions([logic.actionCreators.markTurnComplete(false)])+ })++ it('keeps the turn open when the replayed completion belongs to an older turn', async () => {+ const turnComplete = notification('_posthog/turn_complete', { stopReason: 'end_turn' })+ let resolveLogs: (entries: StoredLogEntry[]) => void = () => {}+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(+ new Promise<StoredLogEntry[]>((resolve) => (resolveLogs = resolve)) as any+ )+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })+ await MockStream.latest().emitOpen()+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')+ await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })++ jest.useFakeTimers()+ await MockStream.latest().emitClose()+ await flushPromises()+ jest.advanceTimersByTime(2000)+ jest.useRealTimers()+ await MockStream.latest().emitOpen()++ await MockStream.latest().emitMessage(+ sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'call-1', status: 'in_progress' }),+ '1800-0'+ )++ resolveLogs([turnComplete])+ await flushPromises()++ expect(logic.values.turnComplete).toEqual(true)+ await expectLogic(logic).toNotHaveDispatchedActions([logic.actionCreators.markTurnComplete(false)])+ })++ it('surfaces a failed history re-read when the run lookup fails on a terminal resync', async () => {+ const getLogEntriesSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])+ jest.spyOn(api.tasks.runs, 'get')+ .mockResolvedValueOnce({ status: 'completed' } as any)+ .mockRejectedValue({ status: 500 })++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })+ await MockStream.latest().emitOpen()+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')+ await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })+ await MockStream.latest().emitClose()+ await flushPromises()++ expect(getLogEntriesSpy).not.toHaveBeenCalled()+ expect(logic.values.currentRunStatus).toEqual('completed')+ expect(logic.values.runConnectionState?.kind).toEqual('connection_failed')+ })++ it('surfaces a failed history re-read once the resynced run is terminal', async () => {+ const getLogEntriesSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockRejectedValue({ status: 500 })+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })+ await MockStream.latest().emitOpen()+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')+ await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })++ jest.useFakeTimers()+ await MockStream.latest().emitClose()+ // Advance past the inter-attempt backoff so every retry runs.+ await jest.advanceTimersByTimeAsync(10_000)+ await flushPromises()+ jest.useRealTimers()++ expect(getLogEntriesSpy).toHaveBeenCalledTimes(MAX_HISTORY_FETCH_ATTEMPTS)+ expect(logic.values.currentRunStatus).toEqual('completed')+ expect(logic.values.runConnectionState?.kind).toEqual('connection_failed')+ })+it('preserves a known in-flight status when the reconnect reopens the stream', async () => {logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })logic.actions.handleTerminalStatus({ status: 'in_progress' })@@ -4843,6 +5055,7 @@ describe('runStreamLogic', () => {baseUrl: 'https://proxy.example/',token: 'tok-1',})+ expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledWith('997', 'task-1', 'run-1')})it('falls back to Django when the server resolves no base URL', async () => {diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex 2df5cc64d182..be2913deea52 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -817,6 +817,16 @@ export function emptyRunLog(): RunLog {return { entries: [], toolUpdateIndex: {} }}+function windowShowsToolCallInFlight(entries: StoredLogEntry[]): boolean {+ return entries.some((entry) => {+ if (entry.notification.method !== 'session/update') {+ return false+ }+ const update = entry.notification.params?.update+ return isRecord(update) && update.sessionUpdate === 'tool_call_update'+ })+}+/** The non-empty toolCallId of a `tool_call_update` frame, or null for every other frame. */function toolCallUpdateKey(stored: StoredEntry): string | null {const notification = stored.entry.notification@@ -1690,6 +1700,7 @@ export interface runStreamLogicValues {foldedThread: FoldedThreadhasGitArtifacts: booleanhasThreadItems: boolean+ historyRecoveryFailed: booleanisBootstrapResumeRun: booleanisThinking: booleanlatestTurnTraceId: string | null@@ -1833,6 +1844,9 @@ export interface runStreamLogicActions {markBootstrapResumeRun: (value: boolean) => {value: boolean}+ markHistoryRecoveryFailed: () => {+ value: true+ }markPermissionRequestResolved: (requestId: string) => {requestId: string}@@ -1842,8 +1856,8 @@ export interface runStreamLogicActions {markRunStarted: () => {value: true}- markTurnComplete: () => {- value: true+ markTurnComplete: (isReplay?: boolean) => {+ isReplay: boolean}markTurnStarted: () => {value: true@@ -1998,6 +2012,7 @@ export interface runStreamLogicMeta {reconnectAttempt: number,bootstrapError: StreamErrorEnvelope | null,currentRunStatus: RunStatus | null,+ historyRecoveryFailed: boolean,arg: boolean | undefined) => RunConnectionState | null}@@ -2188,7 +2203,8 @@ export const runStreamLogic = kea<runStreamLogicType>([markRunStarted: true,/** Records the agent's `/clear` capability, read off each `_posthog/run_started` frame. */setConversationClearSupported: (supported: boolean) => ({ supported }),- markTurnComplete: true,+ markTurnComplete: (isReplay: boolean = false) => ({ isReplay }),+ markHistoryRecoveryFailed: true,/*** Reopens the turn for a follow-up that started outside this composer, such as one sent from Slack* or from another tab. Dispatched from a user turn seen on the wire, and from the agent's first@@ -2393,6 +2409,16 @@ export const runStreamLogic = kea<runStreamLogicType>([reset: () => null,},],+ historyRecoveryFailed: [+ false,+ {+ markHistoryRecoveryFailed: () => true,+ bootstrapRun: () => false,+ bootstrapLogReady: () => false,+ bootstrapReplayComplete: () => false,+ reset: () => false,+ },+ ],// Whether the bootstrapped run is a resume run — drives the §6 resume-prompt filter in the// projection. Set from `run.state.resume_from_run_id` when bootstrap fetches the run.isBootstrapResumeRun: [@@ -2766,18 +2792,27 @@ export const runStreamLogic = kea<runStreamLogicType>([* healthy. `reconnecting` drives the attempt-counter card during the backoff loop; `connection_failed`* is its terminal state (retries/cumulative exhausted, a non-retryable open, or a bootstrap-fetch* failure — including read-only replay, which surfaces via `sseStatus='error'`). A terminal run's own- * failure/crash is an inline `error` item, not a banner, so it's excluded here.+ * failure/crash is an inline `error` item, not a banner, so it's excluded here — except when a resync+ * failed to re-read the history, which leaves a hole no inline item reports.*/runConnectionState: [- (s, p) => [s.sseStatus, s.reconnectAttempt, s.bootstrapError, s.currentRunStatus, p.replayOnly!],+ (s, p) => [+ s.sseStatus,+ s.reconnectAttempt,+ s.bootstrapError,+ s.currentRunStatus,+ s.historyRecoveryFailed,+ p.replayOnly!,+ ],(sseStatus: RunSseStatus,reconnectAttempt: number,bootstrapError: StreamErrorEnvelope | null,currentRunStatus: RunStatus | null,+ historyRecoveryFailed: boolean,replayOnly: boolean | undefined): RunConnectionState | null => {- if (isTerminalRunStatus(currentRunStatus)) {+ if (isTerminalRunStatus(currentRunStatus) && !historyRecoveryFailed) {return null}if (!replayOnly && sseStatus === 'reconnecting') {@@ -2807,6 +2842,7 @@ export const runStreamLogic = kea<runStreamLogicType>([const bootstrap = cache.streamBootstrapconst disposables = cache.disposablesconst isCurrentBootstrap = (): boolean => cache.streamBootstrap === bootstrap && !disposables.isDisposed+ const turnCompleteBeforeReconcile = reconcileHistory ? values.turnComplete : falseif (reconcileHistory) {cache.bufferingLiveFrames = truecache.bufferedLiveFrames ??= []@@ -2818,6 +2854,9 @@ export const runStreamLogic = kea<runStreamLogicType>([}const projectId = values.currentProjectIdif (projectId === null) {+ if (reconcileHistory) {+ actions.markHistoryRecoveryFailed()+ }actions.handleStreamError({ errorTitle: 'No current project', retryable: false })return}@@ -2899,6 +2938,7 @@ export const runStreamLogic = kea<runStreamLogicType>([cache.bufferingLiveFrames = falsecache.bufferedLiveFrames = undefinedcache.disposables.dispose('event-source')+ actions.markHistoryRecoveryFailed()}actions.handleStreamError(mapHttpStatusToStreamError((error as { status?: number })?.status))return@@ -2943,6 +2983,9 @@ export const runStreamLogic = kea<runStreamLogicType>([cache.bufferedLiveFrames = undefinedcache.disposables.dispose('reconnect-backoff')cache.disposables.dispose('event-source')+ if (reconcileHistory) {+ actions.markHistoryRecoveryFailed()+ }actions.handleStreamError(mapHttpStatusToStreamError((historyResult.historyError as { status?: number })?.status))@@ -2994,7 +3037,17 @@ export const runStreamLogic = kea<runStreamLogicType>([const buffered = (cache.bufferedLiveFrames as StoredLogEntry[] | undefined) ?? []cache.bufferingLiveFrames = falsecache.bufferedLiveFrames = undefined- dedupeBufferedAgainstHistory(buffered, history).forEach((entry) => actions.ingestAcpFrame(entry, 'live'))+ const survivors = dedupeBufferedAgainstHistory(buffered, history)+ survivors.forEach((entry) => actions.ingestAcpFrame(entry, 'live'))++ if (+ reconcileHistory &&+ !turnCompleteBeforeReconcile &&+ values.turnComplete &&+ !windowShowsToolCallInFlight(survivors)+ ) {+ actions.markTurnComplete()+ }if (terminal) {if (retainedMessage) {@@ -3015,7 +3068,7 @@ export const runStreamLogic = kea<runStreamLogicType>([actions.bootstrapLogReady()},- openSseForRun: ({ taskId, runId, startLatest }) => {+ openSseForRun: ({ taskId, runId, startLatest: requestedStartLatest }) => {// A read-only instance must never stream — guard here too, so even a stray or connected// dispatch can't open SSE into a read-only thread.if (props.replayOnly) {@@ -3054,9 +3107,11 @@ export const runStreamLogic = kea<runStreamLogicType>([// The cursor is a Redis id from the previous run's stream — it addresses nothing in// this one, so resuming from it can skip this run's opening frames.cache.lastEventId = undefined+ cache.resyncPending = false}// Track the active run so the reconnect loop can refetch it on a drop.cache.activeRun = { taskId, runId }+ const startLatest = cache.resyncPending ? false : requestedStartLatestactions.sseConnecting()cache.disposables.dispose('reconnect-backoff')@@ -3071,6 +3126,7 @@ export const runStreamLogic = kea<runStreamLogicType>([// steady-state stream never re-delivers a frame we've already appended. Mirrored to// sessionStorage so a live reconnect that lost the in-memory cursor can recover it.cache.lastEventId = id+ cache.resyncPending = falsewriteStreamResumeId(runId, id)}if (event === STREAM_END_EVENT) {@@ -3099,6 +3155,20 @@ export const runStreamLogic = kea<runStreamLogicType>([}return}+ if (event === 'end') {+ let control: unknown+ try {+ control = JSON.parse(data)+ } catch {+ return+ }+ if (isRecord(control) && control.type === 'resync') {+ cache.lastEventId = undefined+ clearStreamResumeId(runId)+ cache.resyncPending = true+ }+ return+ }// keepalive (and any other named, non-data event) carries nothing to fold.if (event && event !== 'message') {return@@ -3216,7 +3286,14 @@ export const runStreamLogic = kea<runStreamLogicType>([const bootstrap = cache.streamBootstrap as| { taskId: string; runId: string; retainedMessage?: string }| undefined- if (+ if (cache.resyncPending) {+ actions.bootstrapRun({+ taskId,+ runId,+ retainedMessage: bootstrap?.runId === runId ? bootstrap.retainedMessage : undefined,+ reconcileHistory: true,+ })+ } else if (bootstrap?.taskId === taskId &&bootstrap.runId === runId &&(cache.bufferingLiveFrames || (startLatest && !lastEventId))@@ -3316,8 +3393,18 @@ export const runStreamLogic = kea<runStreamLogicType>([// Terminal → final terminal-status action + close.if (isTerminalRunStatus(result.status)) {- if (!cache.lastEventId && cache.streamBootstrap) {- actions.bootstrapRun({ ...cache.streamBootstrap, reconcileHistory: true })+ const bootstrap = cache.streamBootstrap as+ | { taskId: string; runId: string; retainedMessage?: string }+ | undefined+ if (!cache.lastEventId && (bootstrap || cache.resyncPending)) {+ actions.bootstrapRun({+ taskId: bootstrap?.taskId ?? activeRun.taskId,+ runId: bootstrap?.runId ?? activeRun.runId,+ ...(bootstrap?.retainedMessage !== undefined+ ? { retainedMessage: bootstrap.retainedMessage }+ : {}),+ reconcileHistory: true,+ })}actions.handleTerminalStatus({ status: result.status as RunStatus })return@@ -3672,6 +3759,7 @@ export const runStreamLogic = kea<runStreamLogicType>([cache.bufferedLiveFrames = undefinedcache.activeRun = undefinedcache.lastEventId = undefined+ cache.resyncPending = falsecache.disposables.dispose('reconnect-backoff')// Aborts the in-flight fetch reader (its signal); the reader loop sees `aborted` and// exits without scheduling a reconnect.@@ -3690,6 +3778,7 @@ export const runStreamLogic = kea<runStreamLogicType>([cache.isBootstrapping = falsecache.bufferingLiveFrames = falsecache.bufferedLiveFrames = undefined+ cache.resyncPending = falsecache.sseConnectedAtMs = undefinedcache.streamEnded = falsecache.streamTokenRefreshes = 0@@ -3890,7 +3979,7 @@ export const runStreamLogic = kea<runStreamLogicType>([if (!isReplay) {actions.emitTurnCompleteEvent({ streamKey: props.streamKey })}- actions.markTurnComplete()+ actions.markTurnComplete(isReplay)return}if (method === '_posthog/progress') {