: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(tasks): prevent duplicate responses after refresh (#99375)
Georgiy Tarasov05c4b854191d
diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex ae6713529fbf..830e8285c010 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -314,12 +314,14 @@ export interface maxThreadLogicActions {} // posthogAiContextLogicbootstrapSandboxRun: (payload: {justCreatedRun?: boolean+ reconcileHistory?: booleanretainedMessage?: stringrunId: stringtaskId: stringtraceId?: string}) => {justCreatedRun?: boolean | undefined+ reconcileHistory?: boolean | undefinedretainedMessage?: string | undefinedrunId: stringtaskId: stringdiff --git a/products/posthog_ai/frontend/e2e/run-surface.spec.ts b/products/posthog_ai/frontend/e2e/run-surface.spec.tsindex 4409d63d2e17..7d2e94d21553 100644--- a/products/posthog_ai/frontend/e2e/run-surface.spec.ts+++ b/products/posthog_ai/frontend/e2e/run-surface.spec.ts@@ -23,9 +23,9 @@ interface AcpFrame {interface StreamMock {// 'body' delivers the frames then EOFs (a clean-EOF live drop); 'hang' never responds so the SSE open- // stalls short of `sseOpened` — used when a different signal (terminal status, exhausted history) should+ // stalls short of `sseOpened` — used when a different signal (terminal status) should// drive the surface state without the reconnect loop flapping.- mode: 'body' | 'hang'+ mode: 'body' | 'hang' | 'open'body?: string}@@ -132,8 +132,26 @@ async function routeTasksApi(page: Page, mock: TasksApiMock): Promise<void> {(route) => route.fulfill({ status: mock.logs.status, contentType: 'application/jsonl', body: mock.logs.body }))- if (mock.stream.mode === 'hang') {- // Leave the request pending forever; the bootstrap aborts it once the history retries exhaust.+ if (mock.stream.mode === 'open') {+ await page.addInitScript((streamPattern) => {+ const originalFetch = window.fetch.bind(window)+ window.fetch = async (input, init): Promise<Response> => {+ const url = input instanceof Request ? input.url : input.toString()+ if (!new RegExp(streamPattern).test(new URL(url, window.location.href).pathname)) {+ return originalFetch(input, init)+ }+ const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined)+ return new Response(+ new ReadableStream<Uint8Array>({+ start(controller): void {+ signal?.addEventListener('abort', () => controller.error(signal.reason), { once: true })+ },+ }),+ { headers: { 'Content-Type': 'text/event-stream' } }+ )+ }+ }, streamRe.source)+ } else if (mock.stream.mode === 'hang') {await page.route((url) => streamRe.test(url.pathname),() => new Promise<void>(() => {})@@ -630,8 +648,7 @@ test.describe('Task run surface', () => {await routeTasksApi(page, {runStatus: 'in_progress',logs: { status: 500, body: '' },- // Stall the SSE open so only the exhausted history drives the terminal state (no reconnect flapping).- stream: { mode: 'hang' },+ stream: { mode: 'open' },})await openRunDeepLink(page, workspace!.team_id)diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex a11a71013367..4bb88bd44b7a 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -4577,6 +4577,253 @@ describe('runStreamLogic', () => {;(tasksRunsStreamTokenRetrieve as jest.Mock).mockReset()})+ it.each([+ { name: 'token before history', historyFirst: false, proxy: true, remint: false },+ { name: 'history before token', historyFirst: true, proxy: true, remint: false },+ { name: 'Django fallback after history', historyFirst: true, proxy: false, remint: false },+ { name: 'token retry after history', historyFirst: true, proxy: true, remint: true },+ ])('starts a refreshed run from latest with $name', async ({ historyFirst, proxy, remint }) => {+ enableProxy()+ window.sessionStorage.setItem('posthog-ai:stream-resume:run-1', '1700-0')+ const target = { token: 'test-token', stream_base_url: proxy ? 'https://proxy.example' : null }+ let resolveToken!: (value: typeof target) => void+ let resolveLogs!: (value: StoredLogEntry[]) => void+ ;(tasksRunsStreamTokenRetrieve as jest.Mock)+ .mockImplementationOnce(() => new Promise((resolve) => (resolveToken = resolve)))+ .mockResolvedValue(target)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)+ const logsSpy = jest+ .spyOn(api.tasks.runs, 'getLogEntries')+ .mockReturnValue(new Promise((resolve) => (resolveLogs = resolve)))+ if (remint) {+ ;(api.tasks.runs.openStream as jest.Mock).mockRejectedValueOnce({ status: 401 })+ }+ const history = [+ {+ ...sessionUpdate({+ sessionUpdate: 'agent_message',+ content: { type: 'text', text: 'Checking the layout.' },+ }),+ event_id: 'boot-2',+ first_event_id: 'boot-1',+ },+ ]++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()+ expect(logsSpy).not.toHaveBeenCalled()+ if (historyFirst) {+ resolveLogs(history)+ } else {+ resolveToken(target)+ }+ await flushPromises()+ if (historyFirst) {+ resolveToken(target)+ } else {+ resolveLogs(history)+ }+ await flushPromises()++ for (const [, , options] of (api.tasks.runs.openStream as jest.Mock).mock.calls) {+ expect(options.lastEventId).toBeUndefined()+ expect(options.startLatest).toBe(true)+ }+ expect(MockStream.connections).toHaveLength(1)+ expect(+ logic.values.threadItems.filter((item) => item.type === 'assistant_message').map((item) => item.text)+ ).toEqual(['Checking the layout.'])++ await MockStream.latest().emitMessage(+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Next step.' } }),+ '1700-3'+ )+ jest.useFakeTimers()+ try {+ await MockStream.latest().emitClose()+ jest.advanceTimersByTime(2000)+ await flushPromises()+ expect(MockStream.connections).toHaveLength(2)+ expect(MockStream.latest().options.lastEventId).toEqual('1700-3')+ expect(+ logic.values.threadItems+ .filter((item) => item.type === 'assistant_message')+ .map((item) => item.text)+ ).toEqual(['Checking the layout.', 'Next step.'])+ } finally {+ jest.useRealTimers()+ }+ })++ it.each(['failed request', 'empty stream', 'fresh stream'])(+ 'recovers responses across a cursorless startup reconnect after a %s',+ async (drop) => {+ enableProxy()+ const target = { token: 'test-token', stream_base_url: 'https://proxy.example' }+ let resolveToken!: (value: typeof target) => void+ const nextToken = new Promise((resolve) => (resolveToken = resolve))+ ;(tasksRunsStreamTokenRetrieve as jest.Mock)+ .mockResolvedValueOnce(target)+ .mockReturnValueOnce(nextToken)+ .mockResolvedValue(target)+ if (drop !== 'fresh stream') {+ window.sessionStorage.setItem('posthog-ai:stream-resume:run-1', '1700-0')+ }+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)+ const savedReply = (text: string, eventId: string): StoredLogEntry => ({+ ...sessionUpdate({ sessionUpdate: 'agent_message', content: { type: 'text', text } }),+ event_id: eventId,+ })+ const originalHistory = [savedReply('Saved reply.', 'boot-1')]+ const recoveredHistory = [+ ...originalHistory,+ notification('_posthog/user_message', { content: 'Persisted follow-up.' }),+ savedReply('Reply during disconnect.', 'boot-2'),+ savedReply('Reply during recovery.', 'boot-3'),+ ]+ let recovering = false+ let resolveHistory!: (entries: StoredLogEntry[]) => void+ const nextHistory = new Promise<StoredLogEntry[]>((resolve) => (resolveHistory = resolve))+ const logsSpy = jest+ .spyOn(api.tasks.runs, 'getLogEntries')+ .mockImplementation(() => (recovering ? nextHistory : Promise.resolve(originalHistory)))+ if (drop === 'failed request') {+ ;(api.tasks.runs.openStream as jest.Mock).mockRejectedValueOnce({ status: 503 })+ }++ jest.useFakeTimers()+ try {+ logic.actions.bootstrapRun({+ taskId: 'task-1',+ runId: 'run-1',+ justCreatedRun: drop === 'fresh stream',+ })+ await flushPromises()+ logic.actions.pushHumanMessage('Persisted follow-up.')+ if (drop !== 'failed request') {+ await MockStream.latest().emitClose()+ }+ recovering = true+ const readsBeforeReconnect = logsSpy.mock.calls.length+ jest.advanceTimersByTime(2000)+ await flushPromises()+ expect(logsSpy).toHaveBeenCalledTimes(readsBeforeReconnect)+ resolveToken(target)+ await flushPromises()++ expect(MockStream.latest().options.lastEventId).toBeUndefined()+ expect(MockStream.latest().options.startLatest).toBe(true)+ await MockStream.latest().emitMessage(+ {+ ...sessionUpdate({+ sessionUpdate: 'agent_message_chunk',+ content: { type: 'text', text: 'Reply during recovery.' },+ }),+ event_id: 'boot-3',+ },+ '1700-3'+ )+ await MockStream.latest().emitMessage(savedReply('Live tail.', 'boot-4'), '1700-4')+ logic.actions.pushHumanMessage('Pending follow-up.')+ resolveHistory(recoveredHistory)+ await flushPromises()++ expect(+ logic.values.threadItems+ .filter((item) => item.type === 'assistant_message')+ .map((item) => item.text)+ ).toEqual(['Saved reply.', 'Reply during disconnect.', 'Reply during recovery.', 'Live tail.'])+ expect(+ logic.values.threadItems+ .filter((item) => item.type === 'human_message')+ .map((item) => item.text)+ ).toEqual(['Persisted follow-up.', 'Pending follow-up.'])+ expect(logic.values.cumulativeReconnectAttempt).toEqual(1)+ const readsAfterRecovery = logsSpy.mock.calls.length+ await MockStream.latest().emitClose()+ jest.advanceTimersByTime(2000)+ await flushPromises()+ expect(MockStream.latest().options.lastEventId).toEqual('1700-4')+ expect(logsSpy).toHaveBeenCalledTimes(readsAfterRecovery)+ } finally {+ jest.useRealTimers()+ }+ }+ )++ it('recovers the final response after a cursorless drop without consuming an older identical human turn', async () => {+ const runSpy = jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)+ const history = [+ notification('_posthog/user_message', { content: 'Repeat request.' }),+ notification('_posthog/turn_complete', {}),+ ]+ const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(history)+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()+ logic.actions.pushHumanMessage('Repeat request.')+ runSpy.mockResolvedValue({ status: 'completed' } as any)+ logsSpy.mockResolvedValue([+ ...history,+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'Final response.' } }),+ ])++ await MockStream.latest().emitClose()+ await flushPromises()++ expect(+ logic.values.threadItems.filter((item) => item.type === 'assistant_message').map((item) => item.text)+ ).toEqual(['Final response.'])+ expect(+ logic.values.threadItems.filter((item) => item.type === 'human_message').map((item) => item.text)+ ).toEqual(['Repeat request.', 'Repeat request.'])+ expect(logic.values.currentRunStatus).toEqual('completed')+ expect(logic.values.logBootstrapLoading).toBe(false)+ expect(MockStream.connections).toHaveLength(1)+ })++ it.each(['close', 'reset', 'run replacement'] as const)(+ 'discards pending recovery history after %s',+ async (teardown) => {+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)+ let resolveHistory!: (entries: StoredLogEntry[]) => void+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(+ new Promise((resolve) => (resolveHistory = resolve))+ )+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()+ const originalStream = MockStream.latest()+ await originalStream.emitMessage(+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'Buffered old response.' } }),+ '1700-1'+ )+ if (teardown === 'close') {+ logic.actions.closeSse()+ } else if (teardown === 'reset') {+ logic.actions.reset()+ } else {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-2' })+ }+ resolveHistory([+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'Stale response.' } }),+ ])+ await flushPromises()++ expect(logic.values.threadItems).toEqual([])+ expect(originalStream.closed).toBe(true)+ if (teardown === 'run replacement') {+ await MockStream.latest().emitMessage(+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'New run response.' } }),+ '1800-1'+ )+ expect(+ logic.values.threadItems+ .filter((item) => item.type === 'assistant_message')+ .map((item) => item.text)+ ).toEqual(['New run response.'])+ }+ }+ )+describe('resolveStreamTarget', () => {it('skips the token mint and streams from Django when the rollout is off', async () => {expect(await resolveStreamTarget('997', 'task-1', 'run-1', false)).toBeNull()diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex 3865aadba9f6..2df5cc64d182 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -1601,6 +1601,51 @@ export function foldLogToThread(return { threadItems: items, toolInvocations: invocations }}+function retainUnpersistedEntries(+ previous: StoredEntry[],+ history: StoredLogEntry[],+ isResumeRun: boolean+): StoredEntry[] {+ const transient = previous.filter(({ source }) => source !== 'replay')+ if (transient.length === 0) {+ return []+ }+ const survivors = new Set(+ dedupeBufferedAgainstHistory(+ transient.map(({ entry }) => entry),+ history+ )+ )+ const newHumanTexts = new Map<string, number>()+ const countHumans = (entries: StoredEntry[], increment: number): void => {+ for (const item of foldLogToThread(entries, { isResumeRun }).threadItems) {+ if (item.type === 'human_message' && item.text) {+ newHumanTexts.set(item.text, (newHumanTexts.get(item.text) ?? 0) + increment)+ }+ }+ }+ countHumans(+ history.map((entry) => ({ entry, source: 'replay' })),+ 1+ )+ countHumans(+ previous.filter(({ source }) => source === 'replay'),+ -1+ )+ return transient.filter(({ entry }) => {+ // Only newly persisted turns can replace local echoes; an older identical message is a different send.+ if (entry.notification.method === '_client/human_message') {+ const text = String(entry.notification.params?.content ?? '')+ const count = newHumanTexts.get(text) ?? 0+ if (count > 0) {+ newHumanTexts.set(text, count - 1)+ return false+ }+ }+ return survivors.has(entry)+ })+}+/*** Empty assistant messages, priming thoughts, and step-less progress rows stay in the log for folding.* Hide them from the rendered thread so message wrappers and virtualized consumers cannot reserve@@ -1718,12 +1763,14 @@ export interface runStreamLogicActions {}bootstrapRun: (payload: {justCreatedRun?: boolean+ reconcileHistory?: booleanretainedMessage?: stringrunId: stringtaskId: stringtraceId?: string}) => {justCreatedRun?: boolean | undefined+ reconcileHistory?: boolean | undefinedretainedMessage?: string | undefinedrunId: stringtaskId: string@@ -2022,6 +2069,7 @@ export const runStreamLogic = kea<runStreamLogicType>([justCreatedRun?: booleantraceId?: stringretainedMessage?: string+ reconcileHistory?: boolean}) => payload,openSseForRun: (payload: { taskId: string; runId: string; startLatest?: boolean; traceId?: string }) => payload,/**@@ -2213,7 +2261,7 @@ export const runStreamLogic = kea<runStreamLogicType>([sseReconnecting: (_, { attempt }) => attempt,// A successful (re)connection clears the counter; bootstrapping a run starts fresh.sseOpened: () => 0,- bootstrapRun: () => 0,+ bootstrapRun: (state, { reconcileHistory }) => (reconcileHistory ? state : 0),reset: () => 0,},],@@ -2224,7 +2272,7 @@ export const runStreamLogic = kea<runStreamLogicType>([0,{sseReconnecting: (state) => state + 1,- bootstrapRun: () => 0,+ bootstrapRun: (state, { reconcileHistory }) => (reconcileHistory ? state : 0),reset: () => 0,},],@@ -2283,7 +2331,7 @@ export const runStreamLogic = kea<runStreamLogicType>([bootstrapLoading: [false,{- bootstrapRun: () => true,+ bootstrapRun: (_, { reconcileHistory }) => !reconcileHistory,sseOpened: () => false,bootstrapReplayComplete: () => false,handleStreamError: () => false,@@ -2750,7 +2798,19 @@ export const runStreamLogic = kea<runStreamLogicType>([],}),listeners(({ values, actions, cache, props }) => ({- bootstrapRun: async ({ taskId, runId, justCreatedRun, retainedMessage }, breakpoint) => {+ bootstrapRun: async ({ taskId, runId, justCreatedRun, retainedMessage, reconcileHistory }, breakpoint) => {+ if (!reconcileHistory) {+ cache.streamBootstrap = { taskId, runId, retainedMessage }+ cache.bufferingLiveFrames = false+ cache.bufferedLiveFrames = undefined+ }+ const bootstrap = cache.streamBootstrap+ const disposables = cache.disposables+ const isCurrentBootstrap = (): boolean => cache.streamBootstrap === bootstrap && !disposables.isDisposed+ if (reconcileHistory) {+ cache.bufferingLiveFrames = true+ cache.bufferedLiveFrames ??= []+ }if (cache.activeRun && (cache.activeRun.runId !== runId || cache.activeRun.taskId !== taskId)) {actions.cancelPermissionDelivery()actions.permissionRunChanged()@@ -2808,11 +2868,15 @@ export const runStreamLogic = kea<runStreamLogicType>([// Persistent provisioning flag for disconnect telemetry: stays true across the async// gap between bootstrap and the first connection/run_started. Cleared on the first// `sseOpened`/`_posthog/run_started`.- cache.isBootstrapping = true+ if (!reconcileHistory) {+ cache.isBootstrapping = true+ }// Fresh run: clear the durable-stream end sentinel and the proxy re-mint budget so a// reopened conversation starts clean.- cache.streamEnded = false- cache.streamTokenRefreshes = 0+ if (!reconcileHistory) {+ cache.streamEnded = false+ cache.streamTokenRefreshes = 0+ }// Fresh-run fast path: nothing historical to assemble — stream from the top, with nothing// to buffer or drain.@@ -2828,10 +2892,21 @@ export const runStreamLogic = kea<runStreamLogicType>([try {run = await api.tasks.runs.get(taskId, runId)} catch (error) {+ if (!isCurrentBootstrap()) {+ return+ }+ if (reconcileHistory) {+ cache.bufferingLiveFrames = false+ cache.bufferedLiveFrames = undefined+ cache.disposables.dispose('event-source')+ }actions.handleStreamError(mapHttpStatusToStreamError((error as { status?: number })?.status))return}breakpoint()+ if (!isCurrentBootstrap()) {+ return+ }// Flag the run's resume-ness so the projection can drop the synthetic resume-context// prompt (§6) before any history frame folds.actions.markBootstrapResumeRun(isResumeRun(run))@@ -2845,14 +2920,22 @@ export const runStreamLogic = kea<runStreamLogicType>([// agent emits while the history loads are then captured by the live stream and buffered// (see `handleSseEvent`), not gapped between the snapshot read and the connect cutoff. The// buffered tail is reconciled against the history once the snapshot lands (the drain below).- if (!terminal) {+ if (!terminal && !reconcileHistory) {+ // History replaces the previous page's position, including retries before the first live event.+ cache.lastEventId = undefined+ clearStreamResumeId(runId)cache.bufferingLiveFrames = truecache.bufferedLiveFrames = []actions.openSseForRun({ taskId, runId, startLatest: true })+ return}// Retry the snapshot before giving up (§case 5) — a transient blip shouldn't kill the live SSE.const historyResult = await fetchLogEntriesWithRetry(taskId, runId, breakpoint)+ breakpoint()+ if (!isCurrentBootstrap()) {+ return+ }if (!Array.isArray(historyResult)) {// Retries exhausted; for an in-progress run the SSE is already open, so tear it down too —// a thread of live-only frames with no history is more confusing than a clean, retryable error.@@ -2866,7 +2949,6 @@ export const runStreamLogic = kea<runStreamLogicType>([return}const entries = historyResult- breakpoint()// The full resume-chain S3 snapshot — replayed as `replay`, so the projection renders// persisted human turns and side-effect telemetry stays suppressed for history.@@ -2900,9 +2982,20 @@ export const runStreamLogic = kea<runStreamLogicType>([actions.pushHumanMessage(retainedMessage)}} else {+ const retainedEntries = retainUnpersistedEntries(values.log.entries, history, isResumeRun(run))+ actions.replaceLog(emptyRunLog())history.forEach((entry) => actions.ingestAcpFrame(entry, 'replay'))+ actions.appendEntries(retainedEntries)}+ cache.streamBootstrap = { taskId, runId }++ // A terminal status can arrive while the snapshot loads; its buffered tail still belongs in the thread.+ const buffered = (cache.bufferedLiveFrames as StoredLogEntry[] | undefined) ?? []+ cache.bufferingLiveFrames = false+ cache.bufferedLiveFrames = undefined+ dedupeBufferedAgainstHistory(buffered, history).forEach((entry) => actions.ingestAcpFrame(entry, 'live'))+if (terminal) {if (retainedMessage) {// This bootstrap is the resume attach itself, and a terminal run opens no stream, so@@ -2920,13 +3013,6 @@ export const runStreamLogic = kea<runStreamLogicType>([return}- // Drain the seam: drop buffered-live frames the snapshot already accounts for (content- // multiset), then append the surviving tail as live. Stop buffering first so any frame- // arriving during the drain appends directly rather than landing in a buffer we've moved past.- const buffered = (cache.bufferedLiveFrames as StoredLogEntry[] | undefined) ?? []- cache.bufferingLiveFrames = false- cache.bufferedLiveFrames = undefined- dedupeBufferedAgainstHistory(buffered, history).forEach((entry) => actions.ingestAcpFrame(entry, 'live'))actions.bootstrapLogReady()},openSseForRun: ({ taskId, runId, startLatest }) => {@@ -2940,6 +3026,14 @@ export const runStreamLogic = kea<runStreamLogicType>([actions.handleStreamError({ errorTitle: 'No current project', retryable: false })return}+ if (+ cache.streamBootstrap &&+ (cache.streamBootstrap.taskId !== taskId || cache.streamBootstrap.runId !== runId)+ ) {+ cache.streamBootstrap = undefined+ cache.bufferingLiveFrames = false+ cache.bufferedLiveFrames = undefined+ }// Every open starts a fresh connection. The end sentinel and the proxy re-mint budget// belong to the connection that saw them, so a stale `streamEnded` must not leak into@@ -3054,6 +3148,9 @@ export const runStreamLogic = kea<runStreamLogicType>([// unknown frame types are ignored.}+ // Token lookup can outlast history loading, so capture the bootstrap cursor policy before awaiting it.+ const storedResumeId = cache.bufferingLiveFrames ? undefined : (readStreamResumeId(runId) ?? undefined)+// Open the stream as a fetch response and pump its body through the parser. A native// `EventSource` can't set request headers; a fetch can, so a reconnect resumes exactly// after `cache.lastEventId` via the Last-Event-ID header instead of re-broadcasting the@@ -3070,14 +3167,7 @@ export const runStreamLogic = kea<runStreamLogicType>([if (signal.aborted) {return}- // Resume cursor: prefer the in-memory id stamped by the reader; fall back to the- // persisted sessionStorage cursor only outside the bootstrap seam window- // (`bufferingLiveFrames`). The connect-first bootstrap deliberately streams- // `start=latest` and reconciles the S3 history seam, so a persisted cursor must never- // pre-empt it — only a live reconnect that lost its in-memory cursor honors it.- const lastEventId =- (cache.lastEventId as string | undefined) ??- (cache.bufferingLiveFrames ? undefined : (readStreamResumeId(runId) ?? undefined))+ const lastEventId = (cache.lastEventId as string | undefined) ?? storedResumeIdlet response: Responsetry {@@ -3123,6 +3213,17 @@ export const runStreamLogic = kea<runStreamLogicType>([}// Headers received and a body to read → the connection is open.actions.sseOpened()+ const bootstrap = cache.streamBootstrap as+ | { taskId: string; runId: string; retainedMessage?: string }+ | undefined+ if (+ bootstrap?.taskId === taskId &&+ bootstrap.runId === runId &&+ (cache.bufferingLiveFrames || (startLatest && !lastEventId))+ ) {+ // A cursorless open skips to the new head, so read history only after this connection succeeds.+ actions.bootstrapRun({ ...bootstrap, reconcileHistory: true })+ }const decoder = new TextDecoder()const parser = createParser({ onEvent: handleSseEvent })try {@@ -3215,6 +3316,9 @@ 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 })+ }actions.handleTerminalStatus({ status: result.status as RunStatus })return}@@ -3563,6 +3667,9 @@ export const runStreamLogic = kea<runStreamLogicType>([},closeSse: () => {actions.cancelPermissionDelivery()+ cache.streamBootstrap = undefined+ cache.bufferingLiveFrames = false+ cache.bufferedLiveFrames = undefinedcache.activeRun = undefinedcache.lastEventId = undefinedcache.disposables.dispose('reconnect-backoff')@@ -3572,6 +3679,7 @@ export const runStreamLogic = kea<runStreamLogicType>([},reset: () => {actions.cancelPermissionDelivery()+ cache.streamBootstrap = undefinedcache.optimisticResume = undefined// `log` clears via its own reducer on `reset`, so the projection empties with it. The// per-frame invocation tracker mirrors the log, so it must clear alongside it.