Skip to content

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

fix(ai): recover agent streams after network failures (#99348)

Georgiy Tarasovadde90cdddea
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index 534c69d545cf..82e4d2c2152e 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -42,6 +42,44 @@ The chat history filters for PostHog AI, Slack, and Desktop show tasks created b
These requests wait until the current user's ID is available, including filter changes, searches, and refreshes.
When the user loads, the pending request uses the active filter and search term.
+### Stream recovery
+
+The shared agent thread reconnects automatically after temporary network failures.
+It keeps displayed output while it restores saved history, including output saved during the interruption.
+A connection failure does not mark the run as failed: only the run's authoritative status can do that.
+
+Recovery opens the stream before reading history and buffers incoming frames until reconciliation finishes.
+Shared `event_id` and `first_event_id` values reconcile live events with saved, coalesced messages.
+Coalesced text replaces only text events in its range, preserving interleaved task notifications.
+Saved user messages replace their optimistic copies, and a retained follow-up keeps its turn active when saved history lags.
+Older logs without these IDs use the existing content multiset comparison, which cannot identify every overlap.
+Late Django backlog frames also match their saved log position and payload, without suppressing repeated live output.
+Output that was never persisted or mirrored cannot be reconstructed.
+The resume cursor advances only with retained output; a cursor in session storage does not prove that history is complete.
+Django backlog cursors retain their source run ID so reconnecting after a run marker does not duplicate output.
+
+Stream recovery allows 10 attempts with a 2-second exponential backoff capped at 30 seconds, plus a cumulative cap of 30 reconnects per recovery session.
+Status probes after a drop participate in that budget, including failed probes.
+Bootstrap status, final status, and history reads each allow three attempts.
+Proxy authentication permits five token remints before requiring manual recovery.
+Metadata, token, and handshake requests time out after 30 seconds; history reads and streams without data or keepalives time out after 60 seconds.
+Network failures, timeouts, HTTP 408, 429, 5xx, and retryable stream error frames retry automatically.
+After token refresh handling, HTTP 401, 403, and 406 require Retry; HTTP 404 and other permanent errors stop automatic recovery.
+
+When attempts run out, the thread shows Retry beside the connection error.
+Recovery stays paused until Retry, including when the browser comes online or the tab becomes visible.
+Retry resets the budgets and reads the same run's status and history without submitting messages, commands, or another run.
+Read-only viewers refresh run metadata and saved history without opening a live stream.
+Once a stream ends, Retry can refresh status and history but cannot reopen the stream.
+The thinking indicator stops at stream end, and a history error stays visible even if the final run status is known.
+
+`sandbox_stream_disconnected` records final recovery failures, with `recovery_phase`, `run_status`, `http_status`, and attempt counts.
+`sandbox_stream_recovered` records successful recovery after history reconciliation, with the phase, run status, attempt counts, and elapsed time.
+Neither event includes transcript contents or proxy tokens.
+
+After deployment, verify recovery with `tasks-stream-via-proxy` both enabled and disabled: interrupt a live stream, let the agent persist output, and confirm the restored transcript contains it once.
+Also exhaust retries and verify that Retry works for both an active run and an ended run with an unreadable history snapshot.
+
```text
Your product code
│
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6e275a23fe27..8bb7fb55eb3e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6573,9 +6573,13 @@ snapshots:
products-posthog-ai-runalertactivity--agent-error--light:
hash: v1.k794b7964.80f6609069820af2a251601dd7115b8d364ec1d891a37b74209a8d22fba81c5d._2bu60yDLcOZ8SA2_Ycwp5k_sVXZduKpQ4HyTN8Frf8
products-posthog-ai-runalertactivity--connection-lost--dark:
- hash: v1.k794b7964.5b77068e6d403c438c0cabbece087db1a40901f7fa2942cc43d258e7eff9cb90.TpYqYzxt1UUWI4bry-_PtA1pi6I3hvnSSo4Zc_atnFY
+ hash: v1.k794b7964.a0e07e2ea9a7c7b57d292fa721e44d4bdcc2b8bb9345bfccd95ff0163ba82a73.hqxuwCOJD-LjNycbNIKHUsXHFSn2ot1svqTjB580iCU
products-posthog-ai-runalertactivity--connection-lost--light:
- hash: v1.k794b7964.27f84f7d7e83edba111e619a09998ef53ec204085b762cf0ead3f54eec7601c8.jv5IdH_VAMerURE_to4RCI0yn9OoZar4f-5n7Citvxs
+ hash: v1.k794b7964.98f16d2506ca1274f40960546dad5c4459d8dd9f115a570c87c57dffbfd9630e.jOR1Q25QfQszWtjqdXXppcBPIMnteSaQqIIP8jWm6Ec
+ products-posthog-ai-runalertactivity--connection-lost-narrow--dark:
+ hash: v1.k794b7964.021e665c3e19af3c7170cd271bc45f58cea737f02f840c6927b581d80e15ddad.YLcaLPVzDOReaNKQjH-zAhhua9srhgo9R9QTwR6kbsc
+ products-posthog-ai-runalertactivity--connection-lost-narrow--light:
+ hash: v1.k794b7964.8555bf34acfd36c149b40599f32ca9aba1e2e746b94e43abea582710b3c2dd3f.a8iigoMwFpLemT0mLL8QoBjdFHkg_IZ1uvvSireyP9U
products-posthog-ai-startup-chat--queued-sidebar--dark:
hash: v1.k794b7964.b00472829dd4a536ce873322691bcbf252f3079eb37d0614c7fa9baf9e0b3272.DObEcDsp_ZwITHJgw5jyv6_t4h1oDp1U2jI0wTthlWU
products-posthog-ai-startup-chat--queued-sidebar--light:
diff --git a/frontend/src/lib/api.test.ts b/frontend/src/lib/api.test.ts
index f844e6b4ebb8..b9239b45d6e2 100644
--- a/frontend/src/lib/api.test.ts
+++ b/frontend/src/lib/api.test.ts
@@ -62,6 +62,38 @@ describe('API helper', () => {
})
})
+ describe('agent stream recovery requests', () => {
+ it.each(['history', 'django', 'proxy'] as const)(
+ 'keeps the captured project and cancellation on the %s path',
+ async (path) => {
+ const controller = new AbortController()
+ ApiConfig.setCurrentTeamId(999)
+ if (path === 'history') {
+ await api.tasks.runs.getLogEntries('task-1', 'run-1', { projectId: 123, signal: controller.signal })
+ } else {
+ await api.tasks.runs.openStream('task-1', 'run-1', {
+ projectId: 123,
+ signal: controller.signal,
+ lastEventId: '100-0',
+ ...(path === 'proxy'
+ ? { proxyTarget: { baseUrl: 'https://example.com', token: 'fake-stream-token' } }
+ : {}),
+ })
+ }
+ const streamHeaders = expect.objectContaining({ 'Last-Event-ID': '100-0' })
+ expect(fakeFetch).toHaveBeenCalledWith(
+ path === 'proxy'
+ ? 'https://example.com/v1/runs/run-1/stream?resync=1'
+ : `/api/projects/123/tasks/task-1/runs/run-1/${path === 'history' ? 'logs' : 'stream'}/`,
+ expect.objectContaining({
+ signal: controller.signal,
+ ...(path !== 'history' ? { headers: streamHeaders } : {}),
+ })
+ )
+ }
+ )
+ })
+
describe('dashboard tile streaming', () => {
it.each([
{ status: 401, body: { detail: 'Authentication expired.' }, expectedCode: null },
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index a37a9cf70e40..b8dae0dc31ba 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -5148,8 +5148,15 @@ const api = {
* across the entire resume chain). Used to bootstrap the sandbox stream before
* opening SSE.
*/
- async getLogEntries(taskId: Task['id'], runId: TaskRun['id']): Promise<Record<string, any>[]> {
- const response = await new ApiRequest().taskRun(taskId, runId).withAction('logs').getResponse()
+ async getLogEntries(
+ taskId: Task['id'],
+ runId: TaskRun['id'],
+ options: { signal?: AbortSignal; projectId?: TeamType['id'] } = {}
+ ): Promise<Record<string, any>[]> {
+ const response = await new ApiRequest()
+ .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')) {
@@ -5179,6 +5186,7 @@ const api = {
runId: TaskRun['id'],
options: {
signal: AbortSignal
+ projectId?: TeamType['id']
lastEventId?: string
startLatest?: boolean
/**
@@ -5208,7 +5216,7 @@ const api = {
headers['Authorization'] = `Bearer ${options.proxyTarget.token}`
return api.getResponse(url, { signal: options.signal, headers })
}
- let request = new ApiRequest().taskRun(taskId, runId).withAction('stream')
+ let request = new ApiRequest().taskRun(taskId, runId, options.projectId).withAction('stream')
if (!options.lastEventId && options.startLatest) {
request = request.withQueryString({ start: 'latest' })
}
diff --git a/frontend/src/lib/components/ObjectTags/ObjectTags.removal.test.tsx b/frontend/src/lib/components/ObjectTags/ObjectTags.removal.test.tsx
index 1b83183332aa..8cec77543f9f 100644
--- a/frontend/src/lib/components/ObjectTags/ObjectTags.removal.test.tsx
+++ b/frontend/src/lib/components/ObjectTags/ObjectTags.removal.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen } from '@testing-library/react'
+import { render, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
@@ -6,19 +6,19 @@ import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
describe('ObjectTags', () => {
it('removes a tag via the x without collapsing edit mode', async () => {
const onChange = jest.fn()
- render(
+ const { container } = render(
<ObjectTags tags={['alpha', 'beta']} onChange={onChange} saving={false} tagsAvailable={['alpha', 'beta']} />
)
- await userEvent.click(screen.getByText('Edit tags'))
+ await userEvent.click(within(container).getByText('Edit tags'))
- const closeButtons = document.querySelectorAll('.LemonSnack__close button')
+ const closeButtons = container.querySelectorAll('.LemonSnack__close button')
expect(closeButtons).toHaveLength(2)
await userEvent.click(closeButtons[0] as HTMLElement)
// The click must actually remove the tag (not just close editing before it lands)
expect(onChange).toHaveBeenCalledWith(['beta'])
- expect(document.querySelector('input[type="text"]')).not.toBeNull()
+ expect(container.querySelector('input[type="text"]')).not.toBeNull()
})
})
diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.ts
index b6741b0561ce..ced3f40b9ba3 100644
--- a/frontend/src/scenes/max/maxThreadLogic.test.ts
+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts
@@ -41,7 +41,8 @@ import {
} from '~/types'
import { attachedContextLogic, runStreamLogic } from 'products/posthog_ai/frontend/api/logics'
-import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
+import * as tasksApi from 'products/tasks/frontend/generated/api'
+import { TaskRunDetailDTOApi, TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
import { EnhancedToolCall, MESSAGE_TOO_LONG, TOOL_DEFINITIONS } from './max-constants'
import { maxContextLogic } from './maxContextLogic'
@@ -1766,7 +1767,9 @@ describe('maxThreadLogic', () => {
logic.unmount()
jest.spyOn(api.conversations, 'get').mockResolvedValue(sandboxConversation(SANDBOX_RUN_ID))
const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])
- const runSpy = jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ const runSpy = jest
+ .spyOn(tasksApi, 'tasksRunsRetrieve')
+ .mockResolvedValue({ status: 'in_progress' } as TaskRunDetailDTOApi)
const streamSpy = mockStream()
logic = maxThreadLogic({
@@ -1781,8 +1784,13 @@ 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)
- expect(runSpy).toHaveBeenCalledWith(SANDBOX_TASK_ID, SANDBOX_RUN_ID)
+ expect(logsSpy).toHaveBeenCalledWith(SANDBOX_TASK_ID, SANDBOX_RUN_ID, {
+ signal: expect.any(AbortSignal),
+ projectId: 997,
+ })
+ expect(runSpy).toHaveBeenCalledWith('997', SANDBOX_TASK_ID, SANDBOX_RUN_ID, {
+ signal: expect.any(AbortSignal),
+ })
expect(streamSpy).not.toHaveBeenCalled()
})
diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsx
index bfc3da21ed40..ca17f73d8f95 100644
--- a/frontend/src/scenes/max/maxThreadLogic.tsx
+++ b/frontend/src/scenes/max/maxThreadLogic.tsx
@@ -315,14 +315,12 @@ export interface maxThreadLogicActions {
} // posthogAiContextLogic
bootstrapSandboxRun: (payload: {
justCreatedRun?: boolean
- reconcileHistory?: boolean
retainedMessage?: string
runId: string
taskId: string
traceId?: string
}) => {
justCreatedRun?: boolean | undefined
- reconcileHistory?: boolean | undefined
retainedMessage?: string | undefined
runId: string
taskId: string
diff --git a/products/posthog_ai/frontend/components/RunAlertActivity.stories.tsx b/products/posthog_ai/frontend/components/RunAlertActivity.stories.tsx
index a43a4e5c00fc..b2b08cf1dff1 100644
--- a/products/posthog_ai/frontend/components/RunAlertActivity.stories.tsx
+++ b/products/posthog_ai/frontend/components/RunAlertActivity.stories.tsx
@@ -19,9 +19,23 @@ export default meta
type Story = StoryObj<typeof RunAlertActivity>
-/** Terminal state after reconnect attempts are exhausted — title only, no detail to surface. */
export const ConnectionLost: Story = {
- args: { kind: 'connection_failed' },
+ args: {
+ kind: 'connection_failed',
+ retryable: true,
+ onRetry: () => {},
+ message: 'Connection lost. Retry to restore the conversation.',
+ },
+}
+
+export const ConnectionLostNarrow: Story = {
+ ...ConnectionLost,
+ parameters: { viewport: { defaultViewport: 'small' } },
+ render: (args) => (
+ <div className="w-130 max-w-full p-4">
+ <RunAlertActivity {...args} />
+ </div>
+ ),
}
/** Genuine agent failure — the detail message rides the always-visible region, not the collapsed body. */
diff --git a/products/posthog_ai/frontend/components/RunAlertActivity.test.tsx b/products/posthog_ai/frontend/components/RunAlertActivity.test.tsx
index d30eb8c0ac6c..3a13b2ad3cb2 100644
--- a/products/posthog_ai/frontend/components/RunAlertActivity.test.tsx
+++ b/products/posthog_ai/frontend/components/RunAlertActivity.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { cleanup, render, screen } from '@testing-library/react'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { RunAlertActivity } from './RunAlertActivity'
@@ -10,7 +10,7 @@ describe('RunAlertActivity', () => {
it('shows the reconnect attempt counter while reconnecting', () => {
render(<RunAlertActivity kind="reconnecting" attempt={2} maxAttempts={10} />)
- expect(screen.getByText('Reconnecting to agent')).toBeInTheDocument()
+ expect(screen.getByText('Restoring conversation')).toBeInTheDocument()
expect(screen.getByText('Attempt 2 of 10')).toBeInTheDocument()
})
@@ -32,4 +32,14 @@ describe('RunAlertActivity', () => {
expect(screen.getByText('Your last message was not delivered.')).toBeInTheDocument()
})
+ it.each([true, false])('only offers Retry for a retryable connection failure: %s', (retryable) => {
+ const onRetry = jest.fn()
+ render(<RunAlertActivity kind="connection_failed" retryable={retryable} onRetry={onRetry} />)
+ const retry = screen.queryByText('Retry')
+ expect(retry !== null).toBe(retryable)
+ if (retry) {
+ fireEvent.click(retry)
+ }
+ expect(onRetry).toHaveBeenCalledTimes(Number(retryable))
+ })
})
diff --git a/products/posthog_ai/frontend/components/RunAlertActivity.tsx b/products/posthog_ai/frontend/components/RunAlertActivity.tsx
index e8c20b0b9fad..ba5198edd379 100644
--- a/products/posthog_ai/frontend/components/RunAlertActivity.tsx
+++ b/products/posthog_ai/frontend/components/RunAlertActivity.tsx
@@ -10,6 +10,7 @@ import { Activity } from './ActivityPrimitives'
interface RunAlertActivityProps extends RunConnectionState {
/** Stable id for the markdown message. Defaults per kind. */
id?: string
+ onRetry?: () => void
/** A follow-up message failed to reach the agent because of this error. */
undeliveredMessage?: boolean
/** Text for the "Copy details" action: run and task ids, trace id, and the reason. */
@@ -17,7 +18,7 @@ interface RunAlertActivityProps extends RunConnectionState {
}
const TITLES: Record<RunAlertKind, string> = {
- reconnecting: 'Reconnecting to agent',
+ reconnecting: 'Restoring conversation',
connection_failed: 'Connection lost',
agent_error: 'Run stopped',
agent_error_continued: 'Agent error',
@@ -40,13 +41,15 @@ export function RunAlertActivity({
attempt,
maxAttempts,
message,
+ retryable,
+ onRetry,
undeliveredMessage,
copyDetails,
}: RunAlertActivityProps): JSX.Element {
const activityId = id ?? `run-alert-${kind}`
if (kind === 'reconnecting') {
- const subtitle = attempt && maxAttempts ? `Attempt ${attempt} of ${maxAttempts}` : 'Attempting to reconnect…'
+ const subtitle = attempt && maxAttempts ? `Attempt ${attempt} of ${maxAttempts}` : 'Loading…'
return (
<Activity
id={activityId}
@@ -80,12 +83,19 @@ export function RunAlertActivity({
/>
)}
</div>
- <div className="pl-6 flex flex-col gap-1 text-secondary">
+ <div className="pl-6 flex flex-col gap-1 text-secondary break-words min-w-0">
{message ? <MarkdownMessage content={message} id={`${activityId}-message`} /> : null}
{undeliveredMessage && kind !== 'message_undelivered' ? (
<div>Your last message was not delivered.</div>
) : null}
</div>
+ {kind === 'connection_failed' && retryable && onRetry && (
+ <div className="pl-6 flex flex-wrap items-center gap-2">
+ <LemonButton type="secondary" size="small" onClick={onRetry} data-attr="agent-stream-retry">
+ Retry
+ </LemonButton>
+ </div>
+ )}
</div>
)
}
diff --git a/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx b/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx
index afcc0f2bf590..0a8decbe5cd4 100644
--- a/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx
+++ b/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx
@@ -3,12 +3,20 @@ import '@testing-library/jest-dom'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { BindLogic, Provider } from 'kea'
+import api from 'lib/api'
+import { projectLogic } from 'scenes/projectLogic'
+
import { initKeaTests } from '~/test/init'
+import { tasksRunsRetrieve } from 'products/tasks/frontend/generated/api'
+import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'
+
import { runStreamLogic } from '../logics/runStreamLogic'
import type { StoredLogEntry } from '../types/wireTypes'
import { ThreadView } from './ThreadView'
+jest.mock('products/tasks/frontend/generated/api', () => ({ tasksRunsRetrieve: jest.fn() }))
+
// runStreamLogic.test.ts's frame builder isn't exported — copy the one-liner rather than import it.
function notification(method: string, params: Record<string, unknown>): StoredLogEntry {
return { type: 'notification', notification: { method, params } }
@@ -35,6 +43,7 @@ describe('ThreadView connection state', () => {
afterEach(() => {
cleanup()
logic?.unmount()
+ jest.restoreAllMocks()
})
// Reconnecting projects runConnectionState → footer RunAlertActivity, and its showConnectionStatus gate
@@ -43,7 +52,7 @@ describe('ThreadView connection state', () => {
logic.actions.sseReconnecting(2)
await waitFor(() => {
- expect(screen.getByText('Reconnecting to agent')).toBeInTheDocument()
+ expect(screen.getByText('Restoring conversation')).toBeInTheDocument()
})
// maxAttempts flows from the selector (MAX_SSE_RECONNECT_ATTEMPTS = 10), not a hand-passed prop.
expect(screen.getByText('Attempt 2 of 10')).toBeInTheDocument()
@@ -60,7 +69,37 @@ describe('ThreadView connection state', () => {
})
})
- // A folded _posthog/error frame renders inline as an error card; the run is still live here, so it keeps the softer title.
+ it('retries a failed history read from the footer and guards repeated clicks', async () => {
+ projectLogic.mount()
+ projectLogic.actions.loadCurrentProjectSuccess({ id: 997 } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as TaskRunDetailDTOApi)
+ const history = jest.spyOn(api.tasks.runs, 'getLogEntries').mockRejectedValueOnce({ status: 403 })
+ act(() => logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' }))
+ const retry = await screen.findByText('Retry')
+ let finishHistory!: (entries: StoredLogEntry[]) => void
+ history.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finishHistory = resolve
+ })
+ )
+ act(() => {
+ fireEvent.click(retry)
+ fireEvent.click(retry)
+ })
+ await waitFor(() => expect(history).toHaveBeenCalledTimes(2))
+ expect(screen.queryByText('Retry')).toBeNull()
+ await act(async () =>
+ finishHistory([
+ notification('session/update', {
+ update: { sessionUpdate: 'agent_message', content: { text: 'Recovered output' } },
+ }),
+ ])
+ )
+ await waitFor(() => expect(screen.getByText('Recovered output')).toBeVisible())
+ expect(screen.queryByText('Connection lost')).toBeNull()
+ })
+
it('renders an inline agent-error card for a _posthog/error frame', async () => {
logic.actions.ingestAcpFrame(notification('_posthog/error', { message: 'boom' }), 'replay')
@@ -72,7 +111,7 @@ describe('ThreadView connection state', () => {
// A fresh, healthy mount must paint no connection banner.
it('shows no connection banner on a fresh mount', () => {
- expect(screen.queryByText('Reconnecting to agent')).toBeNull()
+ expect(screen.queryByText('Restoring conversation')).toBeNull()
expect(screen.queryByText('Connection lost')).toBeNull()
})
diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsx
index 77807d917d1f..a2c0846c57a6 100644
--- a/products/posthog_ai/frontend/components/ThreadView.tsx
+++ b/products/posthog_ai/frontend/components/ThreadView.tsx
@@ -1,4 +1,4 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { type ReactNode, memo, useCallback, useEffect, useMemo, useState } from 'react'
import { inStorybookTestRunner } from 'lib/utils/dom'
@@ -319,11 +319,14 @@ const ThreadFooter = memo(function ThreadFooter({
// `runConnectionState` is self-subscribed here (like `currentProgress`) so the frequently-updating
// reconnect attempt counter stays isolated to this leaf and never destabilizes `ThreadView`'s footer.
const { currentProgress, runConnectionState } = useValues(runStreamLogic)
+ const { retryConnection } = useActions(runStreamLogic)
// `gap-1.5` matches the thread's inter-row gap (`VirtualizedThread`'s `gap` default) so stacked footer
// items keep the same vertical rhythm as the thread.
return (
<div className="flex flex-col gap-1.5">
- {showConnectionStatus && runConnectionState && <RunAlertActivity {...runConnectionState} />}
+ {showConnectionStatus && runConnectionState && (
+ <RunAlertActivity {...runConnectionState} onRetry={retryConnection} />
+ )}
{showThinking && (
<ThinkingIndicator
progress={thinkingPhase === 'provisioning' ? null : currentProgress}
diff --git a/products/posthog_ai/frontend/e2e/run-surface.spec.ts b/products/posthog_ai/frontend/e2e/run-surface.spec.ts
index 7d2e94d21553..10fceb4b81f7 100644
--- a/products/posthog_ai/frontend/e2e/run-surface.spec.ts
+++ b/products/posthog_ai/frontend/e2e/run-surface.spec.ts
@@ -304,6 +304,25 @@ test.describe('Task run surface', () => {
}
)
await composer.fill(draft)
+ await page.addInitScript((runId) => {
+ const originalFetch = window.fetch.bind(window)
+ window.fetch = async (input, init): Promise<Response> => {
+ const response = await originalFetch(input, init)
+ const url = input instanceof Request ? input.url : input.toString()
+ if (!new RegExp(`/runs/${runId}/stream/?$`).test(new URL(url, window.location.href).pathname)) {
+ return response
+ }
+ const body = new TextEncoder().encode(await response.text())
+ return new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller): void {
+ controller.enqueue(body)
+ },
+ }),
+ { status: response.status, headers: response.headers }
+ )
+ }
+ }, RUN_ID)
await page.reload()
await expect(composer).toHaveValue(restoredDraft, { timeout: 40000 })
await expect(page.getByTestId('task-draft-restored')).toHaveText('Draft restored. Review it before sending.')
@@ -623,8 +642,8 @@ test.describe('Task run surface', () => {
await expect(composer).toHaveValue('Keep this newer draft.')
})
- test('live stream drop shows the reconnecting banner', async ({ page }) => {
- // Regression: a clean-EOF drop on an in-progress run must surface the reconnecting banner (the backoff
+ test('live stream drop shows the restoring conversation banner', async ({ page }) => {
+ // Regression: a clean-EOF drop on an in-progress run must surface the recovery banner (the backoff
// loop) rather than silently stalling or reading as ordinary thinking.
await routeTasksApi(page, {
runStatus: 'in_progress',
@@ -639,7 +658,7 @@ test.describe('Task run surface', () => {
// Assert only the first reconnecting window — `reconnectAttempt` resets to 0 on each reopen so the banner
// cycles; a single visibility check on the title keeps it deterministic.
- await expect(page.getByText('Reconnecting to agent')).toBeVisible({ timeout: 20000 })
+ await expect(page.getByText('Restoring conversation')).toBeVisible({ timeout: 20000 })
})
test('exhausted run history shows connection lost', async ({ page }) => {
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index d7a989fa1c92..289cfb904031 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -9,7 +9,11 @@ import { projectLogic } from 'scenes/projectLogic'
import { initKeaTests } from '~/test/init'
-import { tasksRunsCommandCreate, tasksRunsStreamTokenRetrieve } from 'products/tasks/frontend/generated/api'
+import {
+ tasksRunsCommandCreate,
+ tasksRunsRetrieve,
+ tasksRunsStreamTokenRetrieve,
+} from 'products/tasks/frontend/generated/api'
import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'
import { lookupToolRenderer, toolRegistry } from '../components/tool/toolRegistry'
@@ -29,9 +33,11 @@ import {
MAX_CUMULATIVE_RECONNECT_ATTEMPTS,
MAX_HISTORY_FETCH_ATTEMPTS,
MAX_SSE_RECONNECT_ATTEMPTS,
+ mergeCoalescedRunLog,
mergeRunArtifacts,
parsePermissionRequestFrame,
reconnectDelayMs,
+ reconcileRunLog,
resolveStreamTarget,
runStreamLogic,
SSE_HEALTHY_CONNECTION_MS,
@@ -41,6 +47,7 @@ import {
import { toolStreamEventsLogic } from './toolStreamEventsLogic'
jest.mock('products/tasks/frontend/generated/api', () => ({
+ tasksRunsRetrieve: jest.fn(),
tasksRunsCommandCreate: jest.fn(),
tasksRunsStreamTokenRetrieve: jest.fn(),
}))
@@ -68,6 +75,16 @@ function legacyNotification(method: string, params: Record<string, unknown>): Re
return { notification: { method, params } }
}
+function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void; reject: (error: unknown) => void } {
+ let resolve!: (value: T) => void
+ let reject!: (error: unknown) => void
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res
+ reject = rej
+ })
+ return { promise, resolve, reject }
+}
+
type ReaderResult = { done: false; value: Uint8Array } | { done: true; value: undefined }
/**
@@ -216,6 +233,10 @@ describe('runStreamLogic', () => {
window.sessionStorage.clear()
MockStream.reset()
MockStream.install()
+ jest.mocked(tasksRunsRetrieve)
+ .mockReset()
+ .mockResolvedValue({ status: 'in_progress' } as TaskRunDetailDTOApi)
+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])
projectLogic.mount()
projectLogic.actions.loadCurrentProjectSuccess({ id: 997 } as any)
;(tasksRunsCommandCreate as jest.Mock)
@@ -1133,7 +1154,7 @@ describe('runStreamLogic', () => {
],
])('records replayed context-block lines under the bootstrapped task (%s)', async (_form, frame) => {
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([frame] as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
await expectLogic(logic, () => {
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
@@ -1164,7 +1185,7 @@ describe('runStreamLogic', () => {
notification('_posthog/turn_complete', { sessionId: 's1', stopReason: 'end_turn', traceId: TRACE }),
]
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
await expectLogic(logic, () => {
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
@@ -1228,7 +1249,7 @@ describe('runStreamLogic', () => {
sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Let me check.' } }),
]
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
await expectLogic(logic, () => {
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
@@ -1255,7 +1276,7 @@ describe('runStreamLogic', () => {
}),
]
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
await expectLogic(logic, () => {
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
@@ -1281,7 +1302,7 @@ describe('runStreamLogic', () => {
])('strips a leading %s wrapper from a replayed human message', async (_name, wrapped) => {
const frames: StoredLogEntry[] = [notification('_posthog/user_message', { content: wrapped })]
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
await expectLogic(logic, () => {
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
@@ -1299,7 +1320,7 @@ describe('runStreamLogic', () => {
const wrapped = `${trustedBlock}\n${untrustedBlock}\n\nWhy did signups drop?`
const frames: StoredLogEntry[] = [notification('_posthog/user_message', { content: wrapped })]
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
await expectLogic(logic, () => {
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
@@ -1337,7 +1358,7 @@ describe('runStreamLogic', () => {
const content = 'Compare weekly activity.'
runStreamLogic({ ...logic.props, replayOnly: readOnly })
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({
id: 'run-1',
task: 'task-1',
stage: null,
@@ -1409,7 +1430,7 @@ describe('runStreamLogic', () => {
sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Several.' } }),
]
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
await expectLogic(logic, () => {
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
@@ -1470,7 +1491,7 @@ describe('runStreamLogic', () => {
sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Here you go.' } }),
]
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({
status: 'completed',
state: { resume_from_run_id: 'ancestor-run' },
} as any)
@@ -1516,7 +1537,7 @@ describe('runStreamLogic', () => {
sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Continuing.' } }),
]
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({
status: 'completed',
state: { resume_from_run_id: 'ancestor-run' },
} as any)
@@ -1546,7 +1567,7 @@ describe('runStreamLogic', () => {
}),
]
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
await expectLogic(logic, () => {
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
@@ -1838,7 +1859,7 @@ describe('runStreamLogic', () => {
}),
]
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({
status: 'completed',
state: { resume_from_run_id: 'run-0' },
} as any)
@@ -1862,7 +1883,7 @@ describe('runStreamLogic', () => {
}),
]
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
await expectLogic(logic, () => {
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
@@ -1928,7 +1949,7 @@ describe('runStreamLogic', () => {
describe('bootstrap log loading state', () => {
it('keeps log bootstrap loading after SSE opens until history is ready', async () => {
let resolveRun: (run: { status: string }) => void = () => {}
- jest.spyOn(api.tasks.runs, 'get').mockReturnValue(
+ jest.mocked(tasksRunsRetrieve).mockReturnValue(
new Promise((resolve) => {
resolveRun = resolve
}) as Promise<any>
@@ -1954,7 +1975,7 @@ describe('runStreamLogic', () => {
})
it('clears the bootstrap spinner for a terminal run whose history renders no rows', async () => {
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'failed', state: {} } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'failed', state: {} } as any)
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])
await expectLogic(logic, () => {
@@ -2198,7 +2219,7 @@ describe('runStreamLogic', () => {
]
: []),
]
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue(run)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue(run)
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(history)
logic.actions.handleTerminalStatus({ status: 'completed', replayedFromHistory: true })
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
@@ -2214,7 +2235,7 @@ describe('runStreamLogic', () => {
// composer, and a live run publishes no further state frame until it terminates.
expect(logic.values.currentRunStatus).toBe('queued')
expect(logic.values.turnComplete).toBe(false)
- expect(MockStream.latest().options.startLatest).toBe(true)
+ expect(MockStream.latest().options.startLatest).toBe(false)
await MockStream.latest().emitOpen()
await MockStream.latest().emitMessage(notification('_posthog/user_message', { content: 'continue' }))
expect(logic.values.threadItems.filter((item) => item.text === 'continue')).toHaveLength(2)
@@ -2242,7 +2263,7 @@ describe('runStreamLogic', () => {
updated_at: '2026-01-01T00:00:00Z',
completed_at: '2026-01-01T00:00:01Z',
} satisfies TaskRunDetailDTOApi
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue(run)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue(run)
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([
notification('_posthog/run_started', { runId: 'run-1' }),
notification('_posthog/user_message', { content: 'continue' }),
@@ -2356,7 +2377,7 @@ describe('runStreamLogic', () => {
it('captures branch / base / pr from the bootstrap run fetch', async () => {
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([] as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({
status: 'completed',
branch: 'feat/posthog-ai-sandboxes',
state: { pr_base_branch: 'master' },
@@ -2394,7 +2415,7 @@ describe('runStreamLogic', () => {
it('stays empty and self-hideable for a run with no git context', async () => {
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([] as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
await expectLogic(logic, () => {
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
@@ -2418,9 +2439,739 @@ describe('runStreamLogic', () => {
})
})
+ describe('history reconciliation', () => {
+ const chunk = (text: string, event_id?: string, first_event_id?: string): StoredLogEntry => ({
+ ...sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text } }),
+ event_id,
+ first_event_id,
+ })
+ it.each([
+ {
+ name: 'saved coalesced range',
+ history: [chunk('abc', 'boot-3', 'boot-1')],
+ retained: [chunk('a', 'boot-1')],
+ buffered: [chunk('b', 'boot-2'), chunk('c', 'boot-3'), chunk('d', 'boot-4')],
+ expected: 'abcd',
+ },
+ {
+ name: 'lagging snapshot',
+ history: [chunk('a', 'boot-1')],
+ retained: [chunk('abc', 'boot-3', 'boot-1')],
+ buffered: [chunk('c', 'boot-3'), chunk('d', 'boot-4')],
+ expected: 'abcd',
+ },
+ {
+ name: 'identical messages with distinct IDs',
+ history: [chunk('same', 'boot-1')],
+ retained: [chunk('same', 'boot-1'), chunk('same', 'boot-2')],
+ buffered: [chunk('same', 'boot-2'), chunk('same', 'boot-3')],
+ expected: 'samesamesame',
+ },
+ {
+ name: 'legacy history with identified live frames',
+ history: [chunk('same')],
+ retained: [],
+ buffered: [chunk('same', 'boot-1'), chunk('same', 'boot-2')],
+ expected: 'samesame',
+ },
+ {
+ name: 'identified history with legacy live frames',
+ history: [chunk('same', 'boot-1')],
+ retained: [],
+ buffered: [chunk('same'), chunk('same')],
+ expected: 'samesame',
+ },
+ {
+ name: 'legacy multiset overlap',
+ history: [chunk('same')],
+ retained: [chunk('same'), chunk('same')],
+ buffered: [chunk('same'), chunk('same'), chunk('same')],
+ expected: 'samesamesame',
+ },
+ ])('preserves output across $name', ({ history, retained, buffered, expected }) => {
+ const log = reconcileRunLog(
+ history,
+ retained.map((entry) => ({ entry, source: 'live' })),
+ buffered
+ )
+ expect(
+ foldLogToThread(log.entries, { isResumeRun: false }).threadItems.find(
+ (item) => item.type === 'assistant_message'
+ )?.text
+ ).toBe(expected)
+ })
+
+ it.each([true, false])('retains the newest tool fields when saved state is newer: %s', (savedNewer) => {
+ const tool = sessionUpdate({
+ sessionUpdate: 'tool_call',
+ toolCallId: 'tool-1',
+ toolName: 'read',
+ status: 'in_progress',
+ })
+ const old = {
+ ...sessionUpdate({
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 'tool-1',
+ rawInput: { path: 'example.txt' },
+ rawOutput: 'partial',
+ status: 'in_progress',
+ }),
+ event_id: 'boot-2',
+ }
+ const latest = {
+ ...sessionUpdate({
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 'tool-1',
+ rawOutput: 'complete',
+ status: 'completed',
+ }),
+ event_id: 'boot-3',
+ }
+ const log = reconcileRunLog(
+ [tool, savedNewer ? latest : old],
+ [tool, savedNewer ? old : latest].map((entry) => ({ entry, source: 'live' })),
+ []
+ )
+ const invocation = foldLogToThread(log.entries, { isResumeRun: false }).toolInvocations.get('tool-1')
+ expect(invocation).toMatchObject({
+ status: 'completed',
+ output: 'complete',
+ input: { path: 'example.txt' },
+ })
+ expect(log.entries).toHaveLength(2)
+ })
+
+ it('keeps a newer buffered legacy tool update over a saved partial result', () => {
+ const tool = sessionUpdate({
+ sessionUpdate: 'tool_call',
+ toolCallId: 'tool-1',
+ toolName: 'read',
+ status: 'in_progress',
+ })
+ const old = sessionUpdate({
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 'tool-1',
+ rawOutput: 'partial',
+ status: 'in_progress',
+ })
+ const latest = sessionUpdate({
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 'tool-1',
+ rawOutput: 'complete',
+ status: 'completed',
+ })
+ const log = reconcileRunLog([tool, old], [], [latest])
+ expect(foldLogToThread(log.entries, { isResumeRun: false }).toolInvocations.get('tool-1')).toMatchObject({
+ status: 'completed',
+ output: 'complete',
+ })
+ })
+
+ it.each(['posthog', 'chunk', 'message', 'both'])(
+ 'preserves optimistic messages while replacing their saved %s echoes',
+ (format) => {
+ const persisted = notification('_posthog/user_message', { content: 'First message' })
+ const wire = sessionUpdate({
+ sessionUpdate: format === 'message' ? 'user_message' : 'user_message_chunk',
+ content: { type: 'text', text: 'First message' },
+ })
+ const saved = [
+ ...(format === 'posthog' ? [persisted] : format === 'both' ? [persisted, wire] : [wire]),
+ notification('_posthog/turn_complete', {}),
+ ]
+ const optimistic = ['First message', 'First message', 'Still sending'].map((content) => ({
+ entry: notification('_client/human_message', { content }),
+ source: 'client' as const,
+ }))
+ const log = reconcileRunLog(saved, optimistic, [])
+ expect(
+ foldLogToThread(log.entries, { isResumeRun: false })
+ .threadItems.filter((item) => item.type === 'human_message')
+ .map((item) => item.text)
+ ).toEqual(['First message', 'First message', 'Still sending'])
+ }
+ )
+
+ it.each(['history', 'retained', 'buffered'])(
+ 'preserves neutral notifications inside a coalesced range from %s',
+ (source) => {
+ const notice = {
+ ...notification('_posthog/task_notification', { taskId: 'background-1', summary: 'Work finished' }),
+ event_id: 'boot-2',
+ source_run_id: 'run-1',
+ }
+ const merged = { ...chunk('abc', 'boot-3', 'boot-1'), source_run_id: 'run-1' }
+ const log = reconcileRunLog(
+ source === 'history' ? [merged] : [],
+ (source === 'retained' ? [notice, merged] : [notice]).map((entry) => ({ entry, source: 'live' })),
+ source === 'buffered' ? [merged] : []
+ )
+ expect(log.entries.map(({ entry }) => entry)).toEqual(expect.arrayContaining([notice, merged]))
+ expect(log.entries).toHaveLength(2)
+ }
+ )
+
+ it.each([false, true])(
+ 'recovers a completed optimistic turn and preserves a new follow-up: %s',
+ async (followUp) => {
+ jest.useFakeTimers()
+ try {
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', justCreatedRun: true })
+ await flushPromises()
+ const started = { ...notification('_posthog/run_started', {}), event_id: 'boot-1' }
+ const echo = {
+ ...sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'Repeat request' },
+ }),
+ event_id: 'boot-2',
+ }
+ const completed = { ...notification('_posthog/turn_complete', {}), event_id: 'boot-3' }
+ await MockStream.latest().emitMessage(started, '100-0')
+ logic.actions.pushHumanMessage('Repeat request')
+ await MockStream.latest().emitMessage(echo, '101-0')
+ await MockStream.latest().emitMessage(completed, '102-0')
+ if (followUp) {
+ logic.actions.pushHumanMessage('Repeat request')
+ }
+ jest.mocked(api.tasks.runs.getLogEntries).mockResolvedValue([started, echo, completed])
+ await MockStream.latest().emitClose()
+ await jest.advanceTimersByTimeAsync(SSE_RECONNECT_BASE_DELAY_MS)
+ expect(
+ logic.values.threadItems
+ .filter((item) => item.type === 'human_message')
+ .map((item) => item.text)
+ ).toEqual(followUp ? ['Repeat request', 'Repeat request'] : ['Repeat request'])
+ expect(logic.values.turnComplete).toBe(!followUp)
+ expect(logic.values.isThinking).toBe(followUp)
+ } finally {
+ jest.useRealTimers()
+ }
+ }
+ )
+
+ it('retains resumed backlog ownership when reconnecting after the run marker', async () => {
+ jest.useFakeTimers()
+ try {
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({
+ id: 'run-2',
+ task: 'task-1',
+ stage: null,
+ branch: null,
+ status: 'in_progress',
+ environment: TaskRunEnvironment.CLOUD,
+ error_message: null,
+ output: null,
+ task_summary: null,
+ artifacts: [],
+ state: { resume_from_run_id: 'run-1' },
+ })
+ const firstRun = notification('_posthog/run_started', { runId: 'run-1' })
+ const secondRun = notification('_posthog/run_started', { runId: 'run-2' })
+ const firstChunk = chunk('a', 'boot-1')
+ const secondChunk = chunk('b', 'boot-2')
+ jest.mocked(api.tasks.runs.getLogEntries).mockResolvedValue([firstRun, secondRun, firstChunk])
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-2' })
+ await flushPromises()
+ await MockStream.latest().emitMessage(secondRun, 'log-1')
+ await MockStream.latest().emitMessage(firstChunk, 'log-2')
+ jest.mocked(api.tasks.runs.getLogEntries).mockResolvedValue([
+ firstRun,
+ secondRun,
+ firstChunk,
+ secondChunk,
+ ])
+ await MockStream.latest().emitClose()
+ await jest.advanceTimersByTimeAsync(SSE_RECONNECT_BASE_DELAY_MS)
+ expect(MockStream.latest().options.lastEventId).toBe('log-2')
+ await MockStream.latest().emitMessage(secondChunk, 'log-3')
+ expect(logic.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toBe('ab')
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('reconciles coalesced backlog frames that arrive after the history request', async () => {
+ jest.mocked(api.tasks.runs.getLogEntries).mockResolvedValue([chunk('a', 'boot-1')])
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
+ const notice = {
+ ...notification('_posthog/task_notification', { taskId: 'background-1', summary: 'Work finished' }),
+ event_id: 'boot-2',
+ }
+ await MockStream.latest().emitMessage(notice, 'log-0')
+ await MockStream.latest().emitMessage(chunk('abc', 'boot-4', 'boot-1'), 'log-1')
+ await MockStream.latest().emitMessage(chunk('a', 'boot-1'), '100-0')
+ await MockStream.latest().emitMessage(chunk('b', 'boot-3'), '101-0')
+ await MockStream.latest().emitMessage(chunk('c', 'boot-4'), '102-0')
+ expect(logic.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toBe('abc')
+ expect(
+ logic.values.log.entries.some(({ entry }) => entry.notification.method === '_posthog/task_notification')
+ ).toBe(true)
+ })
+
+ it('merges a coalesced frame into a long transcript without losing unrelated entries', () => {
+ const entries = Array.from({ length: 2000 }, (_, index) => ({
+ entry: chunk(`Message ${index}`, `boot-${index * 2 + 2}`, `boot-${index * 2 + 1}`),
+ source: 'replay' as const,
+ }))
+ const incoming = chunk('Expanded first message', 'boot-2', 'boot-1')
+ const log = mergeCoalescedRunLog({ entries, toolUpdateIndex: {} }, incoming)
+ expect(log.entries).toEqual([{ entry: incoming, source: 'live' }, ...entries.slice(1)])
+ const recovered = reconcileRunLog(
+ entries.slice(0, 1000).map(({ entry }) => entry),
+ entries,
+ []
+ )
+ expect(recovered.entries.map(({ entry }) => entry)).toEqual(entries.map(({ entry }) => entry))
+ })
+
+ it.each([false, true])(
+ 'deduplicates late legacy backlog while preserving repeated live output: history first %s',
+ async (historyFirst) => {
+ const history = deferred<unknown[]>()
+ jest.mocked(api.tasks.runs.getLogEntries).mockReturnValue(
+ history.promise as Promise<Record<string, unknown>[]>
+ )
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
+ const saved = chunk('Saved output.')
+ if (!historyFirst) {
+ await MockStream.latest().emitMessage(saved, 'log-1')
+ }
+ history.resolve([null, [], { metadata: 'example' }, saved])
+ await flushPromises()
+ if (historyFirst) {
+ await MockStream.latest().emitMessage(saved, 'log-1')
+ }
+ expect(logic.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toBe(
+ 'Saved output.'
+ )
+ await MockStream.latest().emitMessage(saved, '200-0')
+ expect(logic.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toBe(
+ 'Saved output.Saved output.'
+ )
+ await MockStream.latest().emitMessage(saved, 'log-2')
+ expect(logic.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toBe(
+ 'Saved output.Saved output.Saved output.'
+ )
+ }
+ )
+
+ it('rebuilds history without repeating tool or turn reactions and resolved approvals', async () => {
+ jest.useFakeTimers()
+ const capture = jest.spyOn(posthog, 'capture')
+ const toolEvent = jest.fn()
+ const turnEvent = jest.fn()
+ toolStreamEventsLogic.actions.registerToolListener('history-side-effects', {
+ tools: '*',
+ onEvent: toolEvent,
+ onTurnComplete: turnEvent,
+ includeReplay: true,
+ })
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', justCreatedRun: true })
+ await flushPromises()
+ const frames = [
+ {
+ ...sessionUpdate({
+ sessionUpdate: 'tool_call',
+ toolCallId: 'tool-1',
+ toolName: 'read',
+ status: 'in_progress',
+ }),
+ event_id: 'boot-1',
+ },
+ {
+ ...sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'tool-1', status: 'completed' }),
+ event_id: 'boot-2',
+ },
+ { ...notification('_posthog/turn_complete', {}), event_id: 'boot-3' },
+ ]
+ for (const [index, frame] of frames.entries()) {
+ await MockStream.latest().emitMessage(frame, `${index + 1}-0`)
+ }
+ logic.actions.markPermissionRequestResolved('resolved-approval')
+ const before = {
+ tools: toolEvent.mock.calls.length,
+ turns: turnEvent.mock.calls.length,
+ completed: capture.mock.calls.filter(([event]) => event === 'tool_call_completed').length,
+ }
+ jest.mocked(api.tasks.runs.getLogEntries).mockResolvedValue(frames)
+ await MockStream.latest().emitClose()
+ await jest.advanceTimersByTimeAsync(2000)
+ expect(toolEvent).toHaveBeenCalledTimes(before.tools)
+ expect(turnEvent).toHaveBeenCalledTimes(before.turns)
+ expect(capture.mock.calls.filter(([event]) => event === 'tool_call_completed')).toHaveLength(
+ before.completed
+ )
+ expect(logic.values.resolvedPermissionRequestIds.has('resolved-approval')).toBe(true)
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ jest.useRealTimers()
+ })
+ })
+
+ describe('network recovery ownership', () => {
+ beforeEach(() => jest.useFakeTimers())
+ afterEach(() => jest.useRealTimers())
+
+ it.each([new TypeError('Network unavailable'), { status: 0 }, { status: 503 }])(
+ 'recovers a drop even when its status probe fails with %s, then restores saved output',
+ async (error) => {
+ const capture = jest.spyOn(posthog, 'capture')
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', justCreatedRun: true })
+ await flushPromises()
+ const first = {
+ ...sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'First. ' } }),
+ event_id: 'boot-1',
+ }
+ const saved = {
+ ...sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'Saved offline. ' } }),
+ event_id: 'boot-2',
+ }
+ await MockStream.latest().emitMessage(first, '100-0')
+ jest.mocked(tasksRunsRetrieve).mockRejectedValueOnce(error)
+ jest.mocked(api.tasks.runs.getLogEntries).mockResolvedValue([first, saved])
+ await MockStream.latest().emitClose()
+ expect(logic.values.sseStatus).toBe('reconnecting')
+ expect(logic.values.currentRunStatus).toBe('queued')
+ await jest.advanceTimersByTimeAsync(2000)
+ expect(MockStream.latest().options.lastEventId).toBe('100-0')
+ await MockStream.latest().emitMessage(saved, '101-0')
+ expect(logic.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toBe(
+ 'First. Saved offline. '
+ )
+ expect(logic.values.historyComplete).toBe(true)
+ expect(logic.values.sseStatus).toBe('open')
+ expect(capture.mock.calls.filter(([event]) => event === 'sandbox_stream_recovered')).toHaveLength(1)
+ expect(capture.mock.calls.filter(([event]) => event === 'sandbox_stream_disconnected')).toHaveLength(0)
+ }
+ )
+
+ it.each(['metadata', 'history'] as const)(
+ 'pauses after %s exhaustion until one guarded Retry',
+ async (phase) => {
+ const request =
+ phase === 'metadata' ? jest.mocked(tasksRunsRetrieve) : jest.mocked(api.tasks.runs.getLogEntries)
+ request.mockRejectedValue({ status: 503 })
+ logic.actions.pushHumanMessage('Keep this message')
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
+ await jest.advanceTimersByTimeAsync(2000)
+ await jest.advanceTimersByTimeAsync(4000)
+ expect(request).toHaveBeenCalledTimes(3)
+ expect(logic.values.historyComplete).toBe(false)
+ expect(logic.values.threadItems.some((item) => item.text === 'Keep this message')).toBe(true)
+ expect(logic.values.runConnectionState).toMatchObject({ kind: 'connection_failed', retryable: true })
+ window.dispatchEvent(new Event('online'))
+ document.dispatchEvent(new Event('visibilitychange'))
+ await jest.advanceTimersByTimeAsync(120000)
+ expect(request).toHaveBeenCalledTimes(3)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as TaskRunDetailDTOApi)
+ jest.mocked(api.tasks.runs.getLogEntries).mockResolvedValue([])
+ const attempts = jest.mocked(tasksRunsRetrieve).mock.calls.length
+ logic.actions.retryConnection()
+ logic.actions.retryConnection()
+ expect(logic.values.runConnectionState?.kind).not.toBe('connection_failed')
+ await flushPromises()
+ expect(tasksRunsRetrieve).toHaveBeenCalledTimes(attempts + 1)
+ expect(logic.values.sseStatus).toBe('open')
+ expect(logic.values.historyComplete).toBe(true)
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each([401, 403, 406, 404, 400])('does not automatically retry HTTP %s', async (status) => {
+ jest.mocked(tasksRunsRetrieve).mockRejectedValue({ status })
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
+ await jest.advanceTimersByTimeAsync(120000)
+ expect(tasksRunsRetrieve).toHaveBeenCalledTimes(1)
+ expect(logic.values.runConnectionState).toMatchObject({
+ kind: 'connection_failed',
+ retryable: [401, 403, 406].includes(status),
+ })
+ expect(logic.values.currentRunStatus).not.toBe('failed')
+ })
+
+ it.each(
+ ['close', 'reset', 'unmount', 'project', 'run', 'terminal'].flatMap((change) =>
+ [false, true].map((reject) => ({ change, reject }))
+ )
+ )('ignores delayed metadata after $change (reject=$reject)', async ({ change, reject }) => {
+ const metadata = deferred<TaskRunDetailDTOApi>()
+ jest.mocked(tasksRunsRetrieve).mockReturnValueOnce(metadata.promise)
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ const signal = jest.mocked(tasksRunsRetrieve).mock.calls[0][3]?.signal
+ if (change === 'close') {
+ logic.actions.closeSse()
+ }
+ if (change === 'reset') {
+ logic.actions.reset()
+ }
+ if (change === 'unmount') {
+ logic.unmount()
+ logic.mount()
+ }
+ if (change === 'project') {
+ projectLogic.actions.loadCurrentProjectSuccess({ id: 998 } as any)
+ }
+ if (change === 'run') {
+ logic.actions.bootstrapRun({ taskId: 'task-2', runId: 'run-2', justCreatedRun: true })
+ }
+ if (change === 'terminal') {
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as TaskRunDetailDTOApi)
+ logic.actions.streamEnded()
+ }
+ await flushPromises()
+ const opened = MockStream.connections.length
+ if (reject) {
+ metadata.reject({ status: 404 })
+ } else {
+ metadata.resolve({ status: 'failed', branch: 'stale-branch' } as TaskRunDetailDTOApi)
+ }
+ await flushPromises()
+ expect(MockStream.connections).toHaveLength(opened)
+ expect(logic.values.runArtifacts.branch).not.toBe('stale-branch')
+ expect(logic.values.currentRunStatus).not.toBe('failed')
+ expect(logic.values.bootstrapError).toBeNull()
+ expect(signal?.aborted).toBe(true)
+ })
+
+ it.each(['close', 'unmount', 'project', 'run', 'terminal'])(
+ 'ignores delayed history failures after %s',
+ async (change) => {
+ const history = deferred<Record<string, any>[]>()
+ jest.mocked(api.tasks.runs.getLogEntries).mockReturnValueOnce(history.promise)
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
+ const signal = jest.mocked(api.tasks.runs.getLogEntries).mock.calls[0][2]?.signal
+ if (change === 'close') {
+ logic.actions.closeSse()
+ }
+ if (change === 'unmount') {
+ logic.unmount()
+ logic.mount()
+ }
+ if (change === 'project') {
+ projectLogic.actions.loadCurrentProjectSuccess({ id: 998 } as any)
+ }
+ if (change === 'run') {
+ logic.actions.bootstrapRun({ taskId: 'task-2', runId: 'run-2', justCreatedRun: true })
+ }
+ if (change === 'terminal') {
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as TaskRunDetailDTOApi)
+ logic.actions.streamEnded()
+ }
+ await flushPromises()
+ const opened = MockStream.connections.length
+ history.reject({ status: 404 })
+ await flushPromises()
+ expect(MockStream.connections).toHaveLength(opened)
+ expect(logic.values.bootstrapError).toBeNull()
+ expect(signal?.aborted).toBe(true)
+ }
+ )
+
+ it('ignores a handshake that resolves after close without starting a reader', async () => {
+ const response = deferred<Response>()
+ jest.mocked(api.tasks.runs.openStream).mockReturnValueOnce(response.promise)
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', justCreatedRun: true })
+ await flushPromises()
+ logic.actions.closeSse()
+ const getReader = jest.fn()
+ response.resolve({ body: { getReader } } as unknown as Response)
+ await flushPromises()
+ expect(getReader).not.toHaveBeenCalled()
+ expect(logic.values.sseStatus).toBe('closed')
+ })
+
+ it('rolls back a discarded buffer cursor and rejects its late history response', async () => {
+ const history = deferred<Record<string, any>[]>()
+ jest.mocked(api.tasks.runs.getLogEntries).mockReturnValueOnce(history.promise)
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
+ const entry = {
+ ...sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'Recovered' } }),
+ event_id: 'boot-1',
+ }
+ await MockStream.latest().emitMessage(entry, '200-0')
+ expect(window.sessionStorage.getItem('posthog-ai:stream-resume:run-1')).toBeNull()
+ await MockStream.latest().emitClose()
+ await jest.advanceTimersByTimeAsync(2000)
+ expect(MockStream.latest().options.lastEventId).toBeUndefined()
+ expect(MockStream.latest().options.startLatest).toBe(false)
+ await MockStream.latest().emitMessage(entry, '200-0')
+ history.resolve([
+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'Stale history' } }),
+ ])
+ await flushPromises()
+ expect(logic.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toBe('Recovered')
+ expect(window.sessionStorage.getItem('posthog-ai:stream-resume:run-1')).toBe('200-0')
+ })
+
+ it('keeps buffered output when the stream drops before history arrives', async () => {
+ const firstHistory = deferred<Record<string, unknown>[]>()
+ jest.mocked(api.tasks.runs.getLogEntries).mockReturnValueOnce(firstHistory.promise)
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
+
+ await MockStream.latest().emitMessage(
+ {
+ ...sessionUpdate({
+ sessionUpdate: 'agent_message',
+ messageId: 'reply',
+ content: { text: 'Recovered' },
+ }),
+ event_id: 'reply-1',
+ },
+ '200-0'
+ )
+ await MockStream.latest().emitClose()
+ await jest.advanceTimersByTimeAsync(2000)
+ await flushPromises()
+
+ expect(logic.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toBe('Recovered')
+ firstHistory.resolve([])
+ await flushPromises()
+ expect(logic.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toBe('Recovered')
+ })
+
+ it.each(['status', 'history'] as const)(
+ 'retries terminal %s without reopening an ended stream',
+ async (failure) => {
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', justCreatedRun: true })
+ await flushPromises()
+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}))
+ if (failure === 'status') {
+ jest.mocked(tasksRunsRetrieve).mockRejectedValue({ status: 503 })
+ } else {
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'failed' } as TaskRunDetailDTOApi)
+ jest.mocked(api.tasks.runs.getLogEntries).mockRejectedValue({ status: 503 })
+ }
+ await MockStream.latest().emitStreamEnd()
+ expect(logic.values.isThinking).toBe(false)
+ await jest.advanceTimersByTimeAsync(2000)
+ await jest.advanceTimersByTimeAsync(4000)
+ expect(logic.values.runConnectionState).toMatchObject({ kind: 'connection_failed', retryable: true })
+ expect(logic.values.currentRunStatus).toBe(failure === 'status' ? 'queued' : 'failed')
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'failed' } as TaskRunDetailDTOApi)
+ jest.mocked(api.tasks.runs.getLogEntries).mockResolvedValue([
+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'Final saved output' } }),
+ ])
+ logic.actions.retryConnection()
+ logic.actions.retryConnection()
+ await flushPromises()
+ expect(logic.values.runConnectionState).toBeNull()
+ expect(logic.values.threadItems.some((item) => item.text === 'Final saved output')).toBe(true)
+ expect(MockStream.connections).toHaveLength(1)
+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ expect(MockStream.connections).toHaveLength(1)
+ }
+ )
+
+ it.each(['metadata', 'history'])(
+ 'retries a read-only %s failure without opening SSE or sending commands',
+ async (failure) => {
+ const viewer = runStreamLogic({ streamKey: 'read-only-retry', replayOnly: true })
+ const unmount = viewer.mount()
+ try {
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({
+ id: 'run-1',
+ task: 'task-1',
+ stage: null,
+ branch: null,
+ status: 'in_progress',
+ environment: TaskRunEnvironment.CLOUD,
+ error_message: null,
+ output: null,
+ task_summary: null,
+ artifacts: [],
+ state: { resume_from_run_id: 'run-0' },
+ })
+ jest.mocked(api.tasks.runs.getLogEntries).mockResolvedValue([
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { text: 'You are resuming a previous conversation. Example context' },
+ }),
+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'Recovered output' } }),
+ ])
+ if (failure === 'metadata') {
+ jest.mocked(tasksRunsRetrieve).mockRejectedValueOnce({ status: 403 })
+ } else {
+ jest.mocked(api.tasks.runs.getLogEntries).mockRejectedValueOnce({ status: 403 })
+ }
+ viewer.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
+ expect(viewer.values.runConnectionState?.retryable).toBe(true)
+ viewer.actions.retryConnection()
+ await flushPromises()
+ expect(viewer.values.currentRunStatus).toBe('in_progress')
+ expect(viewer.values.isBootstrapResumeRun).toBe(true)
+ expect(viewer.values.threadItems.map((item) => item.text)).toEqual(['Recovered output'])
+ expect(viewer.values.historyComplete).toBe(true)
+ expect(viewer.values.isThinking).toBe(false)
+ expect(MockStream.connections).toHaveLength(0)
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ } finally {
+ unmount()
+ }
+ }
+ )
+
+ it('aborts retryable SSE error readers so EOF schedules only one recovery', async () => {
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', justCreatedRun: true })
+ await flushPromises()
+ const stream = MockStream.latest()
+ await stream.emitErrorFrame({ retryable: true, errorTitle: 'Try again' })
+ await stream.emitClose()
+ expect(stream.closed).toBe(true)
+ expect(logic.values.cumulativeReconnectAttempt).toBe(1)
+ await jest.advanceTimersByTimeAsync(2000)
+ expect(MockStream.connections).toHaveLength(2)
+ expect(logic.values.sseStatus).toBe('open')
+ })
+
+ it.each(['metadata', 'handshake', 'history'] as const)('bounds stalled %s requests', async (phase) => {
+ const stalled = new Promise<never>(() => {})
+ if (phase === 'metadata') {
+ jest.mocked(tasksRunsRetrieve).mockReturnValue(stalled)
+ }
+ if (phase === 'handshake') {
+ jest.mocked(api.tasks.runs.openStream).mockReturnValue(stalled)
+ }
+ if (phase === 'history') {
+ jest.mocked(api.tasks.runs.getLogEntries).mockReturnValue(stalled)
+ }
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
+ await jest.advanceTimersByTimeAsync(phase === 'history' ? 60000 : 30000)
+ expect(logic.values.sseStatus).toBe('reconnecting')
+ expect(logic.values.currentRunStatus).not.toBe('failed')
+ if (phase === 'metadata') {
+ await jest.advanceTimersByTimeAsync(2000 + 30000 + 4000 + 30000)
+ }
+ expect(logic.values.runConnectionState?.kind).toBe(
+ phase === 'metadata' ? 'connection_failed' : 'reconnecting'
+ )
+ })
+
+ it('recovers a stalled stream and treats keepalives as activity', async () => {
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', justCreatedRun: true })
+ await flushPromises()
+ await jest.advanceTimersByTimeAsync(59000)
+ await MockStream.latest().emitMessage({ type: 'keepalive' })
+ await jest.advanceTimersByTimeAsync(59000)
+ expect(MockStream.connections).toHaveLength(1)
+ await jest.advanceTimersByTimeAsync(1000)
+ expect(logic.values.sseStatus).toBe('reconnecting')
+ await jest.advanceTimersByTimeAsync(2000)
+ expect(MockStream.connections).toHaveLength(2)
+ })
+ })
+
describe('reconnect / backoff', () => {
it('refetches and surfaces terminal status on a drop, without reopening', async () => {
- const getSpy = jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ const getSpy = jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
await MockStream.latest().emitOpen()
@@ -2429,14 +3180,14 @@ describe('runStreamLogic', () => {
logic.actions.sseDropped()
await flushPromises()
- expect(getSpy).toHaveBeenCalledWith('task-1', 'run-1')
+ expect(getSpy).toHaveBeenCalledWith('997', 'task-1', 'run-1', { signal: expect.any(AbortSignal) })
expect(logic.values.currentRunStatus).toEqual('completed')
// No new connection was opened (terminal → no reconnect).
expect(MockStream.connections.length).toEqual(beforeDrop)
})
it('backs off and reopens on a drop while the run is non-terminal', async () => {
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
await MockStream.latest().emitOpen()
@@ -2449,17 +3200,16 @@ describe('runStreamLogic', () => {
expect(logic.values.sseStatus).toEqual('reconnecting')
expect(logic.values.reconnectAttempt).toEqual(1)
- jest.advanceTimersByTime(2000)
+ await jest.advanceTimersByTimeAsync(2000)
expect(MockStream.connections.length).toEqual(beforeDrop + 1)
- // No frame carried an id before the drop, so there's nothing to resume from — the reopen
- // requests start=latest (only new frames) rather than re-broadcasting the whole stream.
- expect(MockStream.latest().options.startLatest).toEqual(true)
+ // Without a committed cursor, replay from the beginning so the reconnect cannot skip output.
+ expect(MockStream.latest().options.startLatest).toEqual(false)
expect(MockStream.latest().options.lastEventId).toBeUndefined()
jest.useRealTimers()
})
it('resumes from the last-seen event id via the Last-Event-ID header on reconnect', async () => {
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
// A live frame stamps its Redis stream id as the resume cursor.
@@ -2468,7 +3218,7 @@ describe('runStreamLogic', () => {
jest.useFakeTimers()
logic.actions.sseDropped()
await flushPromises()
- jest.advanceTimersByTime(2000)
+ await jest.advanceTimersByTimeAsync(2000)
// The reconnect resumes exactly after the last-seen frame — header set, no start=latest.
expect(MockStream.latest().options.lastEventId).toEqual('1700-0')
@@ -2477,7 +3227,7 @@ describe('runStreamLogic', () => {
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)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
await flushPromises()
@@ -2489,7 +3239,7 @@ describe('runStreamLogic', () => {
jest.useFakeTimers()
await MockStream.latest().emitClose()
await flushPromises()
- jest.advanceTimersByTime(2000)
+ await jest.advanceTimersByTimeAsync(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.
@@ -2504,7 +3254,7 @@ describe('runStreamLogic', () => {
jest.useFakeTimers()
await MockStream.latest().emitClose()
await flushPromises()
- jest.advanceTimersByTime(2000)
+ await jest.advanceTimersByTimeAsync(2000)
expect(MockStream.latest().options.lastEventId).toBeUndefined()
expect(MockStream.latest().options.startLatest).toEqual(false)
jest.useRealTimers()
@@ -2516,14 +3266,14 @@ describe('runStreamLogic', () => {
jest.useFakeTimers()
await MockStream.latest().emitClose()
await flushPromises()
- jest.advanceTimersByTime(2000)
+ await jest.advanceTimersByTimeAsync(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)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
await MockStream.latest().emitOpen()
@@ -2534,7 +3284,7 @@ describe('runStreamLogic', () => {
jest.useFakeTimers()
await MockStream.latest().emitClose()
await flushPromises()
- jest.advanceTimersByTime(2000)
+ await jest.advanceTimersByTimeAsync(2000)
expect(MockStream.latest().options.lastEventId).toBeUndefined()
expect(MockStream.latest().options.startLatest).toEqual(false)
jest.useRealTimers()
@@ -2544,7 +3294,7 @@ describe('runStreamLogic', () => {
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)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
await MockStream.latest().emitOpen()
@@ -2565,7 +3315,7 @@ describe('runStreamLogic', () => {
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)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
await MockStream.latest().emitOpen()
@@ -2584,7 +3334,7 @@ describe('runStreamLogic', () => {
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)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
await MockStream.latest().emitOpen()
@@ -2594,7 +3344,7 @@ describe('runStreamLogic', () => {
jest.useFakeTimers()
await MockStream.latest().emitClose()
await flushPromises()
- jest.advanceTimersByTime(2000)
+ await jest.advanceTimersByTimeAsync(2000)
jest.useRealTimers()
await MockStream.latest().emitOpen()
@@ -2603,7 +3353,7 @@ describe('runStreamLogic', () => {
await MockStream.latest().emitMessage(turnComplete, '1800-0')
expect(logic.values.turnComplete).toEqual(false)
- resolveLogs([turnComplete])
+ resolveLogs([notification('_posthog/run_started', {}), turnComplete])
await flushPromises()
expect(logic.values.turnComplete).toEqual(true)
@@ -2616,7 +3366,7 @@ describe('runStreamLogic', () => {
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)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
await MockStream.latest().emitOpen()
@@ -2626,7 +3376,7 @@ describe('runStreamLogic', () => {
jest.useFakeTimers()
await MockStream.latest().emitClose()
await flushPromises()
- jest.advanceTimersByTime(2000)
+ await jest.advanceTimersByTimeAsync(2000)
jest.useRealTimers()
await MockStream.latest().emitOpen()
@@ -2635,34 +3385,35 @@ describe('runStreamLogic', () => {
'1800-0'
)
- resolveLogs([turnComplete])
+ resolveLogs([notification('_posthog/run_started', {}), 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 () => {
+ it('restores history even when the final 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 })
+ jest.mocked(tasksRunsRetrieve).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()
+ jest.useFakeTimers()
+ await MockStream.latest().emitStreamEnd()
+ await jest.advanceTimersByTimeAsync(10_000)
await flushPromises()
+ jest.useRealTimers()
- expect(getLogEntriesSpy).not.toHaveBeenCalled()
- expect(logic.values.currentRunStatus).toEqual('completed')
+ expect(getLogEntriesSpy).toHaveBeenCalledTimes(1)
+ expect(MockStream.connections).toHaveLength(1)
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)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
await MockStream.latest().emitOpen()
@@ -2691,7 +3442,7 @@ describe('runStreamLogic', () => {
it('abandons the drop loop when the stream is closed mid-refetch', async () => {
let resolveGet: (value: unknown) => void = () => {}
- jest.spyOn(api.tasks.runs, 'get').mockReturnValue(new Promise((resolve) => (resolveGet = resolve)) as any)
+ jest.mocked(tasksRunsRetrieve).mockReturnValue(new Promise((resolve) => (resolveGet = resolve)) as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
logic.actions.sseDropped()
@@ -2701,11 +3452,11 @@ describe('runStreamLogic', () => {
await flushPromises()
expect(logic.values.sseStatus).toEqual('closed')
- expect(logic.values.reconnectAttempt).toEqual(0)
+ expect(logic.values.reconnectAttempt).toEqual(1)
})
it('surfaces a retryable error after exhausting the attempt cap', async () => {
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
// Drive the attempt counter to the cap without an intervening successful open.
@@ -2718,7 +3469,7 @@ describe('runStreamLogic', () => {
})
it('maps a refetch failure through the HTTP-status table', async () => {
- jest.spyOn(api.tasks.runs, 'get').mockRejectedValue({ status: 404 })
+ jest.mocked(tasksRunsRetrieve).mockRejectedValue({ status: 404 })
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
logic.actions.sseDropped()
@@ -2733,7 +3484,7 @@ describe('runStreamLogic', () => {
// run's sentinel flag and resume cursor must not carry into it: the flag gates the drop
// handler, and the cursor addresses a different Redis stream.
it("opens a successor run on fresh connection state, not the finished run's", async () => {
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '100-0')
await MockStream.latest().emitStreamEnd()
@@ -2748,13 +3499,13 @@ describe('runStreamLogic', () => {
await MockStream.latest().emitClose()
await flushPromises()
expect(logic.values.sseStatus).toEqual('reconnecting')
- jest.advanceTimersByTime(2000)
+ await jest.advanceTimersByTimeAsync(2000)
expect(MockStream.connections.length).toEqual(opened + 1)
jest.useRealTimers()
})
it('leaves a dead stream closed when a follow-up starts a turn', async () => {
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '100-0')
await MockStream.latest().emitStreamEnd()
@@ -2807,7 +3558,7 @@ describe('runStreamLogic', () => {
notification('_posthog/run_started', {}) as any,
sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'history' } }) as any,
])
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
await flushPromises()
@@ -2815,14 +3566,14 @@ describe('runStreamLogic', () => {
expect(logic.values.runStarted).toEqual(true)
const assistantItem = logic.values.threadItems.find((item) => item.type === 'assistant_message')
expect(assistantItem?.text).toEqual('history')
- // No live frame carried an id, so the connect opens from latest (no resume cursor).
- expect(MockStream.latest().options.startLatest).toEqual(true)
+ // Without a committed cursor, the stream must replay output that history may not contain yet.
+ expect(MockStream.latest().options.startLatest).toEqual(false)
expect(MockStream.latest().options.lastEventId).toBeUndefined()
})
it('replays logs/ and stays read-only for a terminal run', async () => {
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
await flushPromises()
@@ -2833,7 +3584,7 @@ describe('runStreamLogic', () => {
it('fetches history exactly once for a terminal run (no terminal reconcile pass)', async () => {
const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
await flushPromises()
@@ -2848,14 +3599,14 @@ describe('runStreamLogic', () => {
jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(
new Promise((resolve) => (resolveLogs = resolve)) as any
)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
await flushPromises()
// The SSE is open before the (still-pending) history fetch resolves.
expect(MockStream.connections.length).toEqual(1)
- expect(MockStream.latest().options.startLatest).toEqual(true)
+ expect(MockStream.latest().options.startLatest).toEqual(false)
// A live frame arriving now is buffered, not yet rendered.
await MockStream.latest().emitOpen()
@@ -2888,7 +3639,7 @@ describe('runStreamLogic', () => {
jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(
new Promise((resolve) => (resolveLogs = resolve)) as any
)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({
status: 'in_progress',
state: resumed ? { resume_from_run_id: 'ancestor-run' } : {},
} as any)
@@ -2925,7 +3676,7 @@ describe('runStreamLogic', () => {
jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(
new Promise((resolve) => (resolveLogs = resolve)) as any
)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
await flushPromises()
@@ -3035,7 +3786,7 @@ describe('runStreamLogic', () => {
jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(
new Promise((resolve) => (resolveLogs = resolve)) as any
)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({
status: 'in_progress',
state: ancestor ? { resume_from_run_id: 'ancestor-run' } : {},
} as any)
@@ -3080,7 +3831,7 @@ describe('runStreamLogic', () => {
notification('_posthog/run_started', {}) as any,
sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'done' } }) as any,
])
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
const viewer = mountViewer('run-ro-terminal')
viewer.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
@@ -3100,7 +3851,7 @@ describe('runStreamLogic', () => {
notification('_posthog/run_started', {}) as any,
sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'partial' } }) as any,
])
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
const viewer = mountViewer('run-ro-inprogress')
viewer.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-2' })
@@ -3119,7 +3870,7 @@ describe('runStreamLogic', () => {
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([
sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'once' } }) as any,
])
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
const viewer = mountViewer('run-ro-idempotent')
viewer.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-3' })
@@ -3134,7 +3885,7 @@ describe('runStreamLogic', () => {
})
it('retries the snapshot then surfaces the connection-failed banner (not an inline error), no SSE', async () => {
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
const getLogEntriesSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockRejectedValue({ status: 500 })
jest.useFakeTimers()
@@ -3163,7 +3914,7 @@ describe('runStreamLogic', () => {
content: { text: 'replayed' },
}) as any,
])
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
const live = runStreamLogic({ streamKey: 'run-shared' })
live.mount()
@@ -3910,7 +4661,7 @@ describe('runStreamLogic', () => {
}) as any,
sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'completed' }) as any,
])
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
await flushPromises()
@@ -3983,7 +4734,7 @@ describe('runStreamLogic', () => {
describe('stream-disconnect telemetry', () => {
it('captures sandbox_stream_disconnected and surfaces the banner without spamming error items', async () => {
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', traceId: 'trace-1' })
@@ -4019,6 +4770,7 @@ describe('runStreamLogic', () => {
logic.actions.sseReconnecting(3)
expect(logic.values.runConnectionState).toEqual({
kind: 'reconnecting',
+ retryable: false,
attempt: 3,
maxAttempts: MAX_SSE_RECONNECT_ATTEMPTS,
})
@@ -4026,7 +4778,7 @@ describe('runStreamLogic', () => {
it('retries the snapshot before teardown and reports was_bootstrapping=true on exhaustion', async () => {
const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
const getLogEntriesSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockRejectedValue({ status: 500 })
jest.useFakeTimers()
@@ -4080,7 +4832,7 @@ describe('runStreamLogic', () => {
describe('reconnect refinements', () => {
it('forgives a healthy connection drop — no reconnectAttempt increment but still schedules a reopen', async () => {
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
const source = MockStream.latest()
@@ -4100,13 +4852,13 @@ describe('runStreamLogic', () => {
expect(logic.values.cumulativeReconnectAttempt).toEqual(1)
expect(logic.values.sseStatus).toEqual('reconnecting')
- jest.advanceTimersByTime(SSE_RECONNECT_BASE_DELAY_MS)
+ await jest.advanceTimersByTimeAsync(SSE_RECONNECT_BASE_DELAY_MS)
expect(MockStream.connections.length).toEqual(beforeDrop + 1)
jest.useRealTimers()
})
it('fails on the cumulative cap even when the per-drop counter keeps resetting', async () => {
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
await MockStream.latest().emitOpen()
@@ -4424,7 +5176,7 @@ describe('runStreamLogic', () => {
})
it('populates pendingPermissionRequest off a permission_request SSE frame', async () => {
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
@@ -4765,7 +5517,7 @@ describe('runStreamLogic', () => {
options: permissionFrame.options,
}),
])
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({
status: 'in_progress',
state: resumed ? { resume_from_run_id: 'ancestor-run' } : {},
} as any)
@@ -4790,7 +5542,7 @@ describe('runStreamLogic', () => {
}) as any,
notification('_posthog/permission_resolved', { requestId: 'req-1', optionId: 'allow_once' }) as any,
])
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
await flushPromises()
@@ -4836,7 +5588,7 @@ describe('runStreamLogic', () => {
{ 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 }) => {
+ ])('replays a refreshed run without a stored cursor 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 }
@@ -4845,7 +5597,7 @@ describe('runStreamLogic', () => {
;(tasksRunsStreamTokenRetrieve as jest.Mock)
.mockImplementationOnce(() => new Promise((resolve) => (resolveToken = resolve)))
.mockResolvedValue(target)
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
const logsSpy = jest
.spyOn(api.tasks.runs, 'getLogEntries')
.mockReturnValue(new Promise((resolve) => (resolveLogs = resolve)))
@@ -4881,7 +5633,7 @@ describe('runStreamLogic', () => {
for (const [, , options] of (api.tasks.runs.openStream as jest.Mock).mock.calls) {
expect(options.lastEventId).toBeUndefined()
- expect(options.startLatest).toBe(true)
+ expect(options.startLatest).toBe(false)
}
expect(MockStream.connections).toHaveLength(1)
expect(
@@ -4895,7 +5647,7 @@ describe('runStreamLogic', () => {
jest.useFakeTimers()
try {
await MockStream.latest().emitClose()
- jest.advanceTimersByTime(2000)
+ await jest.advanceTimersByTimeAsync(2000)
await flushPromises()
expect(MockStream.connections).toHaveLength(2)
expect(MockStream.latest().options.lastEventId).toEqual('1700-3')
@@ -4923,7 +5675,7 @@ describe('runStreamLogic', () => {
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)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
const savedReply = (text: string, eventId: string): StoredLogEntry => ({
...sessionUpdate({ sessionUpdate: 'agent_message', content: { type: 'text', text } }),
event_id: eventId,
@@ -4959,14 +5711,14 @@ describe('runStreamLogic', () => {
}
recovering = true
const readsBeforeReconnect = logsSpy.mock.calls.length
- jest.advanceTimersByTime(2000)
+ await jest.advanceTimersByTimeAsync(2000)
await flushPromises()
expect(logsSpy).toHaveBeenCalledTimes(readsBeforeReconnect)
resolveToken(target)
await flushPromises()
expect(MockStream.latest().options.lastEventId).toBeUndefined()
- expect(MockStream.latest().options.startLatest).toBe(true)
+ expect(MockStream.latest().options.startLatest).toBe(false)
await MockStream.latest().emitMessage(
{
...sessionUpdate({
@@ -4994,11 +5746,13 @@ describe('runStreamLogic', () => {
).toEqual(['Persisted follow-up.', 'Pending follow-up.'])
expect(logic.values.cumulativeReconnectAttempt).toEqual(1)
const readsAfterRecovery = logsSpy.mock.calls.length
+ const recoveredThread = logic.values.threadItems
await MockStream.latest().emitClose()
- jest.advanceTimersByTime(2000)
+ await jest.advanceTimersByTimeAsync(2000)
await flushPromises()
expect(MockStream.latest().options.lastEventId).toEqual('1700-4')
- expect(logsSpy).toHaveBeenCalledTimes(readsAfterRecovery)
+ expect(logsSpy).toHaveBeenCalledTimes(readsAfterRecovery + 1)
+ expect(logic.values.threadItems).toEqual(recoveredThread)
} finally {
jest.useRealTimers()
}
@@ -5006,7 +5760,7 @@ describe('runStreamLogic', () => {
)
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 runSpy = jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
const history = [
notification('_posthog/user_message', { content: 'Repeat request.' }),
notification('_posthog/turn_complete', {}),
@@ -5038,11 +5792,11 @@ describe('runStreamLogic', () => {
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)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
let resolveHistory!: (entries: StoredLogEntry[]) => void
- jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(
- new Promise((resolve) => (resolveHistory = resolve))
- )
+ jest.spyOn(api.tasks.runs, 'getLogEntries')
+ .mockReturnValueOnce(new Promise((resolve) => (resolveHistory = resolve)))
+ .mockResolvedValue([])
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
await flushPromises()
const originalStream = MockStream.latest()
@@ -5093,9 +5847,13 @@ describe('runStreamLogic', () => {
baseUrl: 'https://proxy.example/',
token: 'tok-1',
})
- expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledWith('997', 'task-1', 'run-1', {
- resync: true,
- })
+ expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledWith(
+ '997',
+ 'task-1',
+ 'run-1',
+ { resync: true },
+ { signal: undefined }
+ )
})
it('falls back to Django when the server resolves no base URL', async () => {
@@ -5122,7 +5880,13 @@ describe('runStreamLogic', () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
await flushPromises()
- expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledWith('997', 'task-1', 'run-1', { resync: true })
+ expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledWith(
+ '997',
+ 'task-1',
+ 'run-1',
+ { resync: true },
+ { signal: expect.any(AbortSignal) }
+ )
expect(MockStream.latest().options.proxyTarget).toEqual({
baseUrl: 'https://proxy.example',
token: 'tok-1',
@@ -5157,8 +5921,30 @@ describe('runStreamLogic', () => {
expect(logic.values.sseStatus).toEqual('open')
})
+ it('pauses after five proxy-token remints until manual Retry', async () => {
+ jest.useFakeTimers()
+ enableProxy()
+ jest.mocked(tasksRunsStreamTokenRetrieve).mockResolvedValue({
+ token: 'fake-token',
+ stream_base_url: 'https://example.com',
+ })
+ jest.mocked(api.tasks.runs.openStream).mockRejectedValue({ status: 401 })
+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await jest.advanceTimersByTimeAsync(0)
+ expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledTimes(6)
+ expect(logic.values.runConnectionState).toMatchObject({ kind: 'connection_failed', retryable: true })
+ await jest.advanceTimersByTimeAsync(120000)
+ expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledTimes(6)
+ MockStream.install()
+ logic.actions.retryConnection()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(logic.values.sseStatus).toBe('open')
+ expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledTimes(7)
+ jest.useRealTimers()
+ })
+
it('finalizes on the stream-end sentinel without reconnecting, and clears the resume cursor', async () => {
- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
await flushPromises()
@@ -5182,7 +5968,7 @@ describe('runStreamLogic', () => {
// Drain queued microtasks (chained `await`s in async listeners) without relying on timers, so it
// works under both real and fake timers.
async function flushPromises(): Promise<void> {
- for (let i = 0; i < 10; i++) {
+ for (let i = 0; i < 40; i++) {
await Promise.resolve()
}
}
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index 54e9ca6eb583..a8706c2ab9ac 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -1,17 +1,5 @@
import { type EventSourceMessage, createParser } from 'eventsource-parser'
-import {
- MakeLogicType,
- type BreakPointFunction,
- actions,
- connect,
- kea,
- key,
- listeners,
- path,
- props,
- reducers,
- selectors,
-} from 'kea'
+import { MakeLogicType, getContext, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import posthog from 'posthog-js'
import api from 'lib/api'
@@ -22,7 +10,11 @@ import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { projectLogic } from 'scenes/projectLogic'
import { userLogic } from 'scenes/userLogic'
-import { tasksRunsCommandCreate, tasksRunsStreamTokenRetrieve } from 'products/tasks/frontend/generated/api'
+import {
+ tasksRunsCommandCreate,
+ tasksRunsRetrieve,
+ tasksRunsStreamTokenRetrieve,
+} from 'products/tasks/frontend/generated/api'
import type {
TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi,
TaskRunDetailDTOApi,
@@ -82,6 +74,14 @@ import { attachedContextLogic } from './attachedContextLogic'
import { debugLogsLogic } from './debugLogsLogic'
import { registerHmrStreamAbort } from './devHmrStreamAbort'
import { foregroundStreamLogic } from './foregroundStreamLogic'
+import {
+ RunStreamRecovery,
+ type RecoveryPhase,
+ isTransientStreamError,
+ STREAM_REQUEST_TIMEOUT_MS,
+ STREAM_HISTORY_TIMEOUT_MS,
+ STREAM_IDLE_TIMEOUT_MS,
+} from './runStreamRecovery'
import { hasReplayListener, toolStreamEventsLogic } from './toolStreamEventsLogic'
import type { ToolStreamSubscription } from './toolStreamEventsLogic'
@@ -184,21 +184,12 @@ const AGENT_GENERATING_SESSION_UPDATES: ReadonlySet<string> = new Set([
const STREAM_END_EVENT = 'stream-end'
/**
- * Per-run resume cursor persisted to sessionStorage. The sandbox's primary reload-resume is the S3
- * history replay (see `bootstrapRun`); this cursor is the secondary hint the live reconnect path
- * falls back to when the in-memory cursor is gone (a keyed-logic remount). Keyed by run id so two
- * runs never collide. Cleared when the run's stream completes or reaches a terminal status.
+ * Mirror the committed cursor for diagnostics. Recovery only uses the in-memory cursor attached to
+ * the retained transcript; session storage cannot prove that a remounted viewer has that output.
*/
function streamResumeKey(runId: string): string {
return `posthog-ai:stream-resume:${runId}`
}
-function readStreamResumeId(runId: string): string | null {
- try {
- return window.sessionStorage.getItem(streamResumeKey(runId))
- } catch {
- return null
- }
-}
function writeStreamResumeId(runId: string, eventId: string): void {
try {
window.sessionStorage.setItem(streamResumeKey(runId), eventId)
@@ -229,20 +220,28 @@ export async function resolveStreamTarget(
projectId: string,
taskId: string,
runId: string,
- viaProxy: boolean
+ viaProxy: boolean,
+ signal?: AbortSignal
): Promise<StreamProxyTarget | null> {
if (!viaProxy) {
return null
}
try {
- const { token, stream_base_url } = await tasksRunsStreamTokenRetrieve(projectId, taskId, runId, {
- resync: true,
- })
+ const { token, stream_base_url } = await tasksRunsStreamTokenRetrieve(
+ projectId,
+ taskId,
+ runId,
+ { resync: true },
+ { signal }
+ )
if (!stream_base_url) {
return null
}
return { baseUrl: stream_base_url, token }
- } catch {
+ } catch (error) {
+ if (signal?.aborted) {
+ throw error
+ }
return null
}
}
@@ -285,7 +284,15 @@ export function mapHttpStatusToStreamError(status: number | undefined): StreamEr
case 406:
return streamError('Cloud stream unavailable', true, status)
default:
- return streamError('Cloud stream failed', true, status)
+ return streamError(
+ 'Cloud stream failed',
+ status === undefined ||
+ status === 0 ||
+ status === 408 ||
+ status === 429 ||
+ (status >= 500 && status < 600),
+ status
+ )
}
}
@@ -346,7 +353,7 @@ function contextBlockLinesFromUserMessage(text: string): string[] {
* string; the live wire may instead carry ACP content blocks (`[{ type: 'text', text }]`). Returns
* the concatenated text, or '' when there's nothing renderable.
*/
-function extractUserMessageText(content: string | unknown[] | undefined): string {
+function extractUserMessageText(content: unknown): string {
if (typeof content === 'string') {
return content
}
@@ -513,44 +520,6 @@ export function foldUsageAggregate(existing: ContextUsage | null, update: Sessio
return next
}
-/**
- * Fetch the run's `logs/` snapshot, retrying transient failures with capped backoff (§case 5). Returns the
- * raw entries on success, or `{ historyError }` once the attempts are exhausted — a sentinel object, not a
- * throw, so the caller's teardown branch is driven by an ordinary check and a kea `breakpoint(ms)` delay
- * (which throws to cancel a superseded bootstrap) propagates through untouched.
- */
-async function fetchLogEntriesWithRetry(
- taskId: string,
- runId: string,
- breakpoint: BreakPointFunction
-): Promise<unknown[] | { historyError: unknown }> {
- for (let attempt = 1; ; attempt++) {
- try {
- return await api.tasks.runs.getLogEntries(taskId, runId)
- } catch (error) {
- if (attempt >= MAX_HISTORY_FETCH_ATTEMPTS) {
- return { historyError: error }
- }
- }
- // Outside the try so a supersession cancel (breakpoint throw) is never mistaken for a fetch failure.
- await breakpoint(reconnectDelayMs(attempt))
- }
-}
-
-/** Refetch the run's status (plus any git artifacts it now exposes); on failure return the mapped error envelope. */
-async function fetchRunStatus(
- taskId: string,
- runId: string
-): Promise<{ status: string | null; artifacts: Partial<RunArtifacts> } | { error: StreamErrorEnvelope }> {
- try {
- const run: { status?: string; state?: unknown; output?: unknown; branch?: string | null } =
- await api.tasks.runs.get(taskId, runId)
- return { status: run.status ?? null, artifacts: extractRunArtifacts(run) }
- } catch (error) {
- return { error: mapHttpStatusToStreamError((error as { status?: number })?.status) }
- }
-}
-
/**
* The id of the parent Task tool call when this frame belongs to a subagent's inner work
* (`_meta.claudeCode.parentToolCallId`), else undefined. Inner calls are rolled into their parent
@@ -951,6 +920,30 @@ function isResumeContextPrompt(text: string): boolean {
return text.startsWith(RESUME_CONTEXT_PREFIX)
}
+function isAgentMessageEntry(entry: StoredLogEntry): boolean {
+ const update = entry.notification.params?.update
+ return (
+ entry.notification.method === 'session/update' &&
+ isRecord(update) &&
+ (update.sessionUpdate === 'agent_message_chunk' || update.sessionUpdate === 'agent_message')
+ )
+}
+
+function persistedHumanText(entry: StoredLogEntry): string | null {
+ if (entry.notification.method === '_posthog/user_message') {
+ return unwrapUserMessageContent(extractUserMessageText(entry.notification.params?.content))
+ }
+ const update = entry.notification.params?.update
+ if (
+ entry.notification.method === 'session/update' &&
+ isSessionUpdateUserMessage(update) &&
+ !isHiddenUserContent(update.content)
+ ) {
+ return unwrapUserMessageContent(String(update.content?.text ?? update.text ?? ''))
+ }
+ return null
+}
+
function parseAgentEventId(eventId: string): { boot: string; sequence: number } | null {
const match = /^(.+)-(\d+)$/.exec(eventId)
if (!match) {
@@ -985,7 +978,7 @@ function dedupeBufferedAgainstHistory(buffered: StoredLogEntry[], history: Store
continue
}
eventIds.set(JSON.stringify([entry.source_run_id, entry.event_id]), index)
- if (typeof entry.first_event_id !== 'string' || !entry.first_event_id) {
+ if (!isAgentMessageEntry(entry) || typeof entry.first_event_id !== 'string' || !entry.first_event_id) {
continue
}
eventIds.set(JSON.stringify([entry.source_run_id, entry.first_event_id]), index)
@@ -1004,7 +997,7 @@ function dedupeBufferedAgainstHistory(buffered: StoredLogEntry[], history: Store
let coveredIndex = hasEventId(entry)
? eventIds.get(JSON.stringify([entry.source_run_id, entry.event_id]))
: undefined
- if (coveredIndex === undefined && hasEventId(entry)) {
+ if (coveredIndex === undefined && hasEventId(entry) && isAgentMessageEntry(entry)) {
const parsed = parseAgentEventId(entry.event_id)
if (parsed) {
coveredIndex = eventRanges
@@ -1039,6 +1032,242 @@ function dedupeBufferedAgainstHistory(buffered: StoredLogEntry[], history: Store
return survivors
}
+function eventPosition(entry: StoredLogEntry, first = false): { boot: string; sequence: number } | null {
+ const id = first ? (entry.first_event_id ?? entry.event_id) : entry.event_id
+ return id ? parseAgentEventId(id) : null
+}
+
+function coversEntry(cover: StoredLogEntry, entry: StoredLogEntry): boolean {
+ if (
+ !cover.event_id ||
+ !entry.event_id ||
+ cover.source_run_id !== entry.source_run_id ||
+ !isAgentMessageEntry(cover) ||
+ !isAgentMessageEntry(entry)
+ ) {
+ return false
+ }
+ const first = eventPosition(cover, true)
+ const last = eventPosition(cover)
+ const entryFirst = eventPosition(entry, true)
+ const entryLast = eventPosition(entry)
+ return first && last && entryFirst && entryLast
+ ? first.boot === last.boot &&
+ first.boot === entryFirst.boot &&
+ first.boot === entryLast.boot &&
+ first.sequence <= entryFirst.sequence &&
+ last.sequence >= entryLast.sequence
+ : cover.event_id === entry.event_id
+}
+
+class RunEventCoverage {
+ private readonly ids = new Set<string>()
+ private readonly ranges = new Map<string, { first: number; last: number }[]>()
+
+ constructor(entries: StoredLogEntry[]) {
+ entries.forEach((entry) => this.add(entry))
+ }
+
+ add(entry: StoredLogEntry): void {
+ if (!entry.event_id) {
+ return
+ }
+ this.ids.add(JSON.stringify([entry.source_run_id, entry.event_id]))
+ // Neutral notifications can occur inside a coalesced text range without being superseded.
+ if (!isAgentMessageEntry(entry)) {
+ return
+ }
+ const first = eventPosition(entry, true)
+ const last = eventPosition(entry)
+ if (first && last && first.boot === last.boot && first.sequence <= last.sequence) {
+ const key = JSON.stringify([entry.source_run_id, first.boot])
+ const ranges = this.ranges.get(key) ?? []
+ const range = { first: first.sequence, last: last.sequence }
+ let index = ranges.length
+ while (index > 0 && ranges[index - 1].first > range.first) {
+ index--
+ }
+ if (index > 0 && ranges[index - 1].last + 1 >= range.first) {
+ index--
+ range.first = ranges[index].first
+ }
+ while (index < ranges.length && ranges[index].first <= range.last + 1) {
+ range.last = Math.max(range.last, ranges[index].last)
+ ranges.splice(index, 1)
+ }
+ ranges.splice(index, 0, range)
+ this.ranges.set(key, ranges)
+ }
+ }
+
+ private overlappingRange(entry: StoredLogEntry): { first: number; last: number } | undefined {
+ if (!isAgentMessageEntry(entry)) {
+ return
+ }
+ const first = eventPosition(entry, true)
+ const last = eventPosition(entry)
+ if (!first || !last || first.boot !== last.boot) {
+ return
+ }
+ const ranges = this.ranges.get(JSON.stringify([entry.source_run_id, first.boot])) ?? []
+ let low = 0
+ let high = ranges.length
+ while (low < high) {
+ const middle = (low + high) >>> 1
+ if (ranges[middle].last < first.sequence) {
+ low = middle + 1
+ } else {
+ high = middle
+ }
+ }
+ const range = ranges[low]
+ return range && range.first <= last.sequence ? range : undefined
+ }
+
+ overlaps(entry: StoredLogEntry): boolean {
+ return this.overlappingRange(entry) !== undefined
+ }
+
+ covers(entry: StoredLogEntry): boolean {
+ if (!entry.event_id) {
+ return false
+ }
+ if (!entry.first_event_id && this.ids.has(JSON.stringify([entry.source_run_id, entry.event_id]))) {
+ return true
+ }
+ const range = this.overlappingRange(entry)
+ const first = eventPosition(entry, true)
+ const last = eventPosition(entry)
+ return !!(range && first && last && range.first <= first.sequence && range.last >= last.sequence)
+ }
+}
+
+function compareEntryPosition(left: StoredLogEntry, right: StoredLogEntry): number {
+ const a = eventPosition(left)
+ const b = eventPosition(right)
+ if (a && b && a.boot === b.boot) {
+ return a.sequence - b.sequence
+ }
+ return left.timestamp && right.timestamp ? Date.parse(left.timestamp) - Date.parse(right.timestamp) : 0
+}
+
+export function mergeCoalescedRunLog(log: RunLog, entry: StoredLogEntry): RunLog {
+ const entries = log.entries.filter((stored) => !coversEntry(entry, stored.entry))
+ const nextIndex = entries.findIndex((stored) => compareEntryPosition(entry, stored.entry) < 0)
+ entries.splice(nextIndex < 0 ? entries.length : nextIndex, 0, { entry, source: 'live' })
+ return appendToRunLog(emptyRunLog(), entries)
+}
+
+function retainedFramesWithoutOptimisticEchoes(retained: StoredEntry[]): StoredLogEntry[] {
+ const optimisticCounts = new Map<string, number>()
+ return retained.flatMap(({ entry, source }) => {
+ if (entry.notification.method === '_posthog/turn_complete') {
+ optimisticCounts.clear()
+ }
+ if (source === 'client') {
+ if (entry.notification.method === '_client/human_message') {
+ const text = String(entry.notification.params?.content ?? '')
+ optimisticCounts.set(text, (optimisticCounts.get(text) ?? 0) + 1)
+ }
+ return []
+ }
+ const text = source === 'live' ? persistedHumanText(entry) : null
+ const optimistic = text ? (optimisticCounts.get(text) ?? 0) : 0
+ if (text && optimistic > 0) {
+ optimisticCounts.set(text, optimistic - 1)
+ return []
+ }
+ return [entry]
+ })
+}
+
+export function reconcileRunLog(
+ history: StoredLogEntry[],
+ retained: StoredEntry[],
+ buffered: StoredLogEntry[],
+ optimisticRunId?: string
+): RunLog {
+ let entries: StoredEntry[] = history.map((entry) => ({ entry, source: 'replay' }))
+ const coverage = new RunEventCoverage(history)
+ const savedHumanCounts = new Map<string, number>()
+ const rememberedHumanTexts = new Map<string, number>()
+ for (const entry of dedupeBufferedAgainstHistory(history, retainedFramesWithoutOptimisticEchoes(retained))) {
+ const text = persistedHumanText(entry)
+ if (!text || (optimisticRunId && entry.source_run_id !== optimisticRunId)) {
+ continue
+ }
+ if (entry.notification.method === '_posthog/user_message') {
+ rememberedHumanTexts.set(text, (rememberedHumanTexts.get(text) ?? 0) + 1)
+ } else {
+ const remembered = rememberedHumanTexts.get(text) ?? 0
+ if (remembered > 0) {
+ rememberedHumanTexts.set(text, remembered - 1)
+ continue
+ }
+ }
+ savedHumanCounts.set(text, (savedHumanCounts.get(text) ?? 0) + 1)
+ }
+ for (const [tailIndex, tail] of [
+ retained,
+ buffered.map((entry): StoredEntry => ({ entry, source: 'live' })),
+ ].entries()) {
+ const survivors = dedupeBufferedAgainstHistory(
+ tail.filter(({ source }) => source !== 'client').map(({ entry }) => entry),
+ entries.map(({ entry }) => entry)
+ )
+ const survivorCounts = new Map<StoredLogEntry, number>()
+ survivors.forEach((entry) => survivorCounts.set(entry, (survivorCounts.get(entry) ?? 0) + 1))
+ for (const stored of tail) {
+ const { entry } = stored
+ if (entry.notification.method === '_client/human_message') {
+ const text = String(entry.notification.params?.content ?? '')
+ const saved = savedHumanCounts.get(text) ?? 0
+ if (saved > 0) {
+ savedHumanCounts.set(text, saved - 1)
+ continue
+ }
+ }
+ if (stored.source !== 'client') {
+ const survivorCount = survivorCounts.get(entry) ?? 0
+ if (survivorCount === 0) {
+ continue
+ }
+ survivorCounts.set(entry, survivorCount - 1)
+ if (entry.event_id) {
+ if (coverage.covers(entry)) {
+ continue
+ }
+ // A retained coalesced message can be newer than the saved snapshot.
+ if (entry.first_event_id && coverage.overlaps(entry)) {
+ entries = entries.filter((existing) => !coversEntry(entry, existing.entry))
+ }
+ coverage.add(entry)
+ }
+ }
+ const toolKey = toolCallUpdateKey(stored)
+ const newerToolIndex =
+ toolKey === null ? -1 : entries.findIndex((other) => toolCallUpdateKey(other) === toolKey)
+ const toolOrder = newerToolIndex >= 0 ? compareEntryPosition(entry, entries[newerToolIndex].entry) : 1
+ if (newerToolIndex >= 0 && (toolOrder < 0 || (toolOrder === 0 && tailIndex === 0))) {
+ entries[newerToolIndex] = mergeToolCallUpdateEntries(stored, entries[newerToolIndex])
+ continue
+ }
+ const nextIndex =
+ entry.event_id &&
+ entries.length > 0 &&
+ compareEntryPosition(entry, entries[entries.length - 1].entry) < 0
+ ? entries.findIndex((other) => compareEntryPosition(entry, other.entry) < 0)
+ : -1
+ if (nextIndex >= 0) {
+ entries.splice(nextIndex, 0, stored)
+ } else {
+ entries.push(stored)
+ }
+ }
+ }
+ return appendToRunLog(emptyRunLog(), entries)
+}
+
/**
* The invocation a `tool_call` frame creates, replacing any prior invocation for the id. Shared by
* the `foldLogToThread` projection and the per-frame tracker in `ingestAcpFrame`, so tool-stream
@@ -1628,51 +1857,6 @@ 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
@@ -1717,7 +1901,7 @@ export interface runStreamLogicValues {
foldedThread: FoldedThread
hasGitArtifacts: boolean
hasThreadItems: boolean
- historyRecoveryFailed: boolean
+ historyComplete: boolean
isBootstrapResumeRun: boolean
isThinking: boolean
latestTurnTraceId: string | null
@@ -1727,6 +1911,11 @@ export interface runStreamLogicValues {
pendingRunMessage: PendingRunMessage | null
permissionResponseRequestIds: Set<string>
reconnectAttempt: number
+ recoveryState: {
+ attempt: number
+ maxAttempts: number
+ phase: RecoveryPhase
+ } | null
resolvedPermissionRequestIds: Set<string>
respondingToPermission: boolean
runArtifacts: RunArtifacts
@@ -1737,6 +1926,7 @@ export interface runStreamLogicValues {
seenPermissionRequestIds: Set<string>
showThinkingIndicator: boolean
sseStatus: RunSseStatus
+ streamHasEnded: boolean
streamPhase: 'idle' | 'provisioning' | 'thinking'
streamViaProxyEnabled: boolean
threadItems: ThreadItem[]
@@ -1791,14 +1981,12 @@ export interface runStreamLogicActions {
}
bootstrapRun: (payload: {
justCreatedRun?: boolean
- reconcileHistory?: boolean
retainedMessage?: string
runId: string
taskId: string
traceId?: string
}) => {
justCreatedRun?: boolean | undefined
- reconcileHistory?: boolean | undefined
retainedMessage?: string | undefined
runId: string
taskId: string
@@ -1861,9 +2049,6 @@ export interface runStreamLogicActions {
markBootstrapResumeRun: (value: boolean) => {
value: boolean
}
- markHistoryRecoveryFailed: () => {
- value: true
- }
markPermissionRequestResolved: (requestId: string) => {
requestId: string
}
@@ -1910,12 +2095,27 @@ export interface runStreamLogicActions {
pushHumanMessage: (content: string) => {
content: string
}
+ recoveryProgress: (
+ phase: RecoveryPhase,
+ attempt: number,
+ maxAttempts: number
+ ) => {
+ attempt: number
+ maxAttempts: number
+ phase: RecoveryPhase
+ }
+ recoveryRunChanged: () => {
+ value: true
+ }
replaceLog: (log: RunLog) => {
log: RunLog
}
reset: () => {
value: true
}
+ resetRecoveryBudget: () => {
+ value: true
+ }
respondToPermission: (payload: {
answers?: Record<string, string>
customInput?: string
@@ -1927,6 +2127,9 @@ export interface runStreamLogicActions {
optionId: string
requestId: string
}
+ retryConnection: () => {
+ value: true
+ }
rollbackOptimisticResume: () => {
value: true
}
@@ -1952,6 +2155,9 @@ export interface runStreamLogicActions {
setCurrentStage: (stage: string | null) => {
stage: string | null
}
+ setHistoryComplete: (complete: boolean) => {
+ complete: boolean
+ }
setPendingRunMessage: (message: PendingRunMessage | null) => {
message: PendingRunMessage | null
}
@@ -1961,6 +2167,9 @@ export interface runStreamLogicActions {
setSdkSession: (session: SdkSession) => {
session: SdkSession
}
+ setStreamHasEnded: (ended: boolean) => {
+ ended: boolean
+ }
sseConnecting: () => {
value: true
}
@@ -2007,7 +2216,8 @@ export interface runStreamLogicMeta {
turnComplete: boolean,
currentRunStatus: RunStatus | null,
sseStatus: RunSseStatus,
- arg: boolean | undefined
+ arg: boolean | undefined,
+ streamHasEnded: boolean
) => boolean
streamPhase: (
runStarted: boolean,
@@ -2028,9 +2238,11 @@ export interface runStreamLogicMeta {
sseStatus: RunSseStatus,
reconnectAttempt: number,
bootstrapError: StreamErrorEnvelope | null,
- currentRunStatus: RunStatus | null,
- historyRecoveryFailed: boolean,
- arg: boolean | undefined
+ recoveryState: {
+ attempt: number
+ maxAttempts: number
+ phase: RecoveryPhase
+ } | null
) => RunConnectionState | null
}
}
@@ -2088,6 +2300,16 @@ export const runStreamLogic = kea<runStreamLogicType>([
],
})),
actions({
+ retryConnection: true,
+ resetRecoveryBudget: true,
+ recoveryRunChanged: true,
+ setHistoryComplete: (complete: boolean) => ({ complete }),
+ setStreamHasEnded: (ended: boolean) => ({ ended }),
+ recoveryProgress: (phase: RecoveryPhase, attempt: number, maxAttempts: number) => ({
+ phase,
+ attempt,
+ maxAttempts,
+ }),
/**
* Bootstrap an existing run on conversation open. Terminal run: replay the `logs/` history
* and stay read-only (no SSE). In-progress run: connect the SSE *first* (buffering live
@@ -2101,7 +2323,6 @@ export const runStreamLogic = kea<runStreamLogicType>([
justCreatedRun?: boolean
traceId?: string
retainedMessage?: string
- reconcileHistory?: boolean
}) => payload,
openSseForRun: (payload: { taskId: string; runId: string; startLatest?: boolean; traceId?: string }) => payload,
/**
@@ -2136,7 +2357,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
* (`source: 'live'`), the products/tasks `logs/` replay (`source: 'replay'`), and the
* bootstrap drain (the deduped live tail). Telemetry is suppressed for replay; the
* permission/run-started/tool-completion guards keep the side effects fired-once without a
- * per-frame key. The resume cursor (`cache.lastEventId`) is stamped by the SSE reader, not here.
+ * per-frame key. The recovery session commits resume cursors only after retaining their frames.
*/
ingestAcpFrame: (entry: StoredLogEntry, source: FrameSource = 'live') => ({ entry, source }),
/** Append frames to the ordered log (the single source of truth). */
@@ -2221,7 +2442,6 @@ export const runStreamLogic = kea<runStreamLogicType>([
/** Records the agent's `/clear` capability, read off each `_posthog/run_started` frame. */
setConversationClearSupported: (supported: boolean) => ({ supported }),
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
@@ -2258,6 +2478,36 @@ export const runStreamLogic = kea<runStreamLogicType>([
reset: true,
}),
reducers({
+ historyComplete: [
+ false,
+ {
+ setHistoryComplete: (_, { complete }) => complete,
+ reset: () => false,
+ },
+ ],
+ streamHasEnded: [
+ false,
+ {
+ setStreamHasEnded: (_, { ended }) => ended,
+ streamEnded: () => true,
+ recoveryRunChanged: () => false,
+ reset: () => false,
+ },
+ ],
+ recoveryState: [
+ null as { phase: RecoveryPhase; attempt: number; maxAttempts: number } | null,
+ {
+ recoveryProgress: (_, state) => state,
+ sseReconnecting: (_, { attempt }) => ({
+ phase: 'stream' as RecoveryPhase,
+ attempt,
+ maxAttempts: MAX_SSE_RECONNECT_ATTEMPTS,
+ }),
+ bootstrapReplayComplete: () => null,
+ bootstrapLogReady: () => null,
+ reset: () => null,
+ },
+ ],
// True while the conversations/open POST is in flight, before any SSE state exists. Folds into
// `streamPhase` as provisioning so the thread shows the optimistic "spinning up" indicator
// immediately on send. Cleared once a real stream lifecycle takes over (or ends/errors).
@@ -2278,6 +2528,9 @@ export const runStreamLogic = kea<runStreamLogicType>([
'idle' as RunSseStatus,
{
sseConnecting: () => 'connecting',
+ bootstrapRun: () => 'connecting',
+ recoveryProgress: () => 'reconnecting',
+ bootstrapReplayComplete: () => 'closed',
sseOpened: () => 'open',
sseReconnecting: () => 'reconnecting',
closeSse: () => 'closed',
@@ -2292,9 +2545,10 @@ export const runStreamLogic = kea<runStreamLogicType>([
0,
{
sseReconnecting: (_, { attempt }) => attempt,
- // A successful (re)connection clears the counter; bootstrapping a run starts fresh.
+ // Successful connections reset the consecutive budget; the cumulative cap still applies.
sseOpened: () => 0,
- bootstrapRun: (state, { reconcileHistory }) => (reconcileHistory ? state : 0),
+ bootstrapRun: () => 0,
+ resetRecoveryBudget: () => 0,
reset: () => 0,
},
],
@@ -2305,7 +2559,8 @@ export const runStreamLogic = kea<runStreamLogicType>([
0,
{
sseReconnecting: (state) => state + 1,
- bootstrapRun: (state, { reconcileHistory }) => (reconcileHistory ? state : 0),
+ bootstrapRun: () => 0,
+ resetRecoveryBudget: () => 0,
reset: () => 0,
},
],
@@ -2322,7 +2577,8 @@ export const runStreamLogic = kea<runStreamLogicType>([
{
// A reconnect reopens the same in-flight run — keep its known status rather than
// flickering back to queued; only a fresh open (no/terminal status) resets.
- openSseForRun: (state) => (state && !isTerminalRunStatus(state) ? state : 'queued'),
+ openSseForRun: (state) => state ?? 'queued',
+ recoveryRunChanged: () => null,
handleTerminalStatus: (_, { status }) => status,
// The boundary drops the status of the run being left behind, which is always a terminal
// one. The successor's own seed can already be here — `openSseForRun` runs before the
@@ -2364,7 +2620,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
bootstrapLoading: [
false,
{
- bootstrapRun: (_, { reconcileHistory }) => !reconcileHistory,
+ bootstrapRun: () => true,
sseOpened: () => false,
bootstrapReplayComplete: () => false,
handleStreamError: () => false,
@@ -2420,22 +2676,13 @@ export const runStreamLogic = kea<runStreamLogicType>([
null as StreamErrorEnvelope | null,
{
bootstrapRun: () => null,
+ recoveryProgress: () => null,
bootstrapLogReady: () => null,
bootstrapReplayComplete: () => null,
handleStreamError: (_, envelope) => envelope,
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: [
@@ -2681,20 +2928,21 @@ export const runStreamLogic = kea<runStreamLogicType>([
*/
isThinking: [
// `replayOnly` always resolves (default in `props`); `!` drops the optional-prop `undefined`.
- (s, p) => [s.runStarted, s.turnComplete, s.currentRunStatus, s.sseStatus, p.replayOnly!],
+ (s, p) => [s.runStarted, s.turnComplete, s.currentRunStatus, s.sseStatus, p.replayOnly!, s.streamHasEnded],
(
runStarted: boolean,
turnComplete: boolean,
currentRunStatus: RunStatus | null,
sseStatus: RunSseStatus,
- replayOnly: boolean | undefined
+ replayOnly: boolean | undefined,
+ streamHasEnded: boolean
): boolean => {
// A read-only snapshot is never "thinking" — it's a static replay, so the indicator
// must never spin (an in-progress run replayed read-only has no live turn to await).
if (replayOnly) {
return false
}
- if (sseStatus === 'error' || isTerminalRunStatus(currentRunStatus)) {
+ if (streamHasEnded || sseStatus === 'error' || isTerminalRunStatus(currentRunStatus)) {
return false
}
const runInFlight = runStarted || currentRunStatus === 'queued' || currentRunStatus === 'in_progress'
@@ -2809,1408 +3057,1450 @@ 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 — except when a resync
- * failed to re-read the history, which leaves a hole no inline item reports.
+ * failure/crash is an inline `error` item. History failures remain visible after termination.
*/
runConnectionState: [
- (s, p) => [
- s.sseStatus,
- s.reconnectAttempt,
- s.bootstrapError,
- s.currentRunStatus,
- s.historyRecoveryFailed,
- p.replayOnly!,
- ],
+ (s) => [s.sseStatus, s.reconnectAttempt, s.bootstrapError, s.recoveryState],
(
sseStatus: RunSseStatus,
reconnectAttempt: number,
bootstrapError: StreamErrorEnvelope | null,
- currentRunStatus: RunStatus | null,
- historyRecoveryFailed: boolean,
- replayOnly: boolean | undefined
+ recoveryState: { phase: RecoveryPhase; attempt: number; maxAttempts: number } | null
): RunConnectionState | null => {
- if (isTerminalRunStatus(currentRunStatus) && !historyRecoveryFailed) {
- return null
+ if (sseStatus === 'error') {
+ const detail = bootstrapError
+ ? [bootstrapError.errorTitle, bootstrapError.errorMessage].filter(Boolean).join('. ')
+ : undefined
+ return {
+ kind: 'connection_failed',
+ message: detail || undefined,
+ retryable: bootstrapError?.retryable ?? false,
+ }
}
- if (!replayOnly && sseStatus === 'reconnecting') {
+ if (sseStatus === 'reconnecting') {
return {
kind: 'reconnecting',
- attempt: reconnectAttempt,
- maxAttempts: MAX_SSE_RECONNECT_ATTEMPTS,
+ attempt: recoveryState?.attempt ?? reconnectAttempt,
+ maxAttempts: recoveryState?.maxAttempts ?? MAX_SSE_RECONNECT_ATTEMPTS,
+ retryable: false,
}
}
- if (sseStatus === 'error') {
- const detail = bootstrapError
- ? [bootstrapError.errorTitle, bootstrapError.errorMessage].filter(Boolean).join(' — ')
- : undefined
- return { kind: 'connection_failed', message: detail || undefined }
- }
return null
},
],
}),
- listeners(({ values, actions, cache, props }) => ({
- 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
- const turnCompleteBeforeReconcile = reconcileHistory ? values.turnComplete : false
- if (reconcileHistory) {
- cache.bufferingLiveFrames = true
- cache.bufferedLiveFrames ??= []
- }
- if (cache.activeRun && (cache.activeRun.runId !== runId || cache.activeRun.taskId !== taskId)) {
- actions.cancelPermissionDelivery()
- actions.permissionRunChanged()
- cache.activeRun = undefined
- }
+ listeners(({ values, actions, cache, props }) => {
+ const sessionNow = (): RunStreamRecovery | undefined => cache.recoverySession
+ const endedKey = (projectId: number, taskId: string, runId: string): string => `${projectId}:${taskId}:${runId}`
+ const hasEnded = (session: RunStreamRecovery): boolean =>
+ cache.endedRuns?.has(endedKey(session.projectId, session.taskId, session.runId)) === true
+ const beginSession = (taskId: string, runId: string): RunStreamRecovery | undefined => {
const projectId = values.currentProjectId
if (projectId === null) {
- if (reconcileHistory) {
- actions.markHistoryRecoveryFailed()
- }
actions.handleStreamError({ errorTitle: 'No current project', retryable: false })
return
}
-
- // Read-only viewer: replay the `logs/` snapshot once and never open SSE, regardless of run
- // status. `breakpoint()` cancels a superseded in-flight bootstrap (a remount / StrictMode
- // double-invoke), and the log-empty guard before folding keeps a re-bootstrap of a shared
- // keyed instance (a second mounted viewer of the same run) from doubling the thread.
- if (props.replayOnly) {
- let replayRun: { status?: string; state?: unknown; output?: unknown; branch?: string | null }
- try {
- replayRun = await api.tasks.runs.get(taskId, runId)
- } catch (error) {
- actions.handleStreamError(mapHttpStatusToStreamError((error as { status?: number })?.status))
- return
- }
- breakpoint()
- actions.markBootstrapResumeRun(isResumeRun(replayRun))
- actions.mergeRunArtifacts(extractRunArtifacts(replayRun))
- actions.setPendingRunMessage(readPendingRunMessage(replayRun.state, runId))
-
- const replayResult = await fetchLogEntriesWithRetry(taskId, runId, breakpoint)
- if (!Array.isArray(replayResult)) {
- actions.handleStreamError(
- mapHttpStatusToStreamError((replayResult.historyError as { status?: number })?.status)
- )
- return
- }
- const replayEntries = replayResult
- breakpoint()
- if (values.log.entries.length === 0) {
- normalizeHistory(replayEntries, runId, isResumeRun(replayRun)).forEach((entry) =>
- actions.ingestAcpFrame(entry, 'replay')
- )
- }
-
- if (isTerminalRunStatus(replayRun.status ?? null)) {
- // Record the terminal status read-only — no SSE to close, no termination telemetry.
- actions.handleTerminalStatus({
- status: replayRun.status as RunStatus,
- replayedFromHistory: true,
- })
+ const previous = sessionNow()
+ const sameRun = previous?.projectId === projectId && previous.taskId === taskId && previous.runId === runId
+ cache.disposables.dispose('event-source')
+ const context = getContext()
+ const session = new RunStreamRecovery(
+ projectId,
+ taskId,
+ runId,
+ (cache.recoveryGeneration = (cache.recoveryGeneration ?? 0) + 1),
+ cache.disposables,
+ () =>
+ getContext() === context &&
+ cache.recoverySession === session &&
+ values.currentProjectId === projectId
+ )
+ if (sameRun) {
+ session.committedCursor = previous.committedCursor
+ session.committedBacklogRunId = previous.committedBacklogRunId
+ if (previous.buffering) {
+ session.buffer = [...previous.buffer]
+ session.buffering = true
}
- actions.bootstrapReplayComplete()
- return
- }
-
- // 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`.
- 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.
- if (!reconcileHistory) {
- cache.streamEnded = false
- cache.streamTokenRefreshes = 0
+ } else {
+ actions.cancelPermissionDelivery()
+ actions.permissionRunChanged()
+ cache.eventCoverage = undefined
+ actions.recoveryRunChanged()
+ actions.handleTerminalStatus({ status: 'queued' })
}
-
- // Fresh-run fast path: nothing historical to assemble — stream from the top, with nothing
- // to buffer or drain.
- if (justCreatedRun) {
- actions.openSseForRun({ taskId, runId, startLatest: false })
- actions.bootstrapLogReady()
+ cache.recoverySession = session
+ cache.pausedError = undefined
+ cache.activeRun = session
+ cache.permissionRunId = runId
+ cache.streamTokenRefreshes = 0
+ actions.setStreamHasEnded(hasEnded(session))
+ return session
+ }
+ const failRecovery = (session: RunStreamRecovery, error: unknown): void => {
+ if (!session.owns() || session.paused) {
return
}
-
- // Existing run: read the status first to branch terminal (read-only history) vs.
- // in-progress (connect-first, then reconcile the seam).
- let run: { status?: string; state?: unknown; output?: unknown; branch?: string | null }
- 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.markHistoryRecoveryFailed()
- }
- actions.handleStreamError(mapHttpStatusToStreamError((error as { status?: number })?.status))
- return
+ const envelope =
+ isRecord(error) && typeof error.errorTitle === 'string'
+ ? (error as unknown as StreamErrorEnvelope)
+ : mapHttpStatusToStreamError((error as { status?: number })?.status)
+ session.paused = true
+ cache.pausedError = envelope
+ session.buffer = []
+ session.receivedCursor = session.committedCursor
+ session.receivedBacklogRunId = session.committedBacklogRunId
+ if (session.phase !== 'finalization') {
+ actions.setHistoryComplete(false)
}
- breakpoint()
- if (!isCurrentBootstrap()) {
- return
+ cache.disposables.dispose('event-source')
+ actions.handleStreamError(envelope)
+ session.controller.abort()
+ }
+ const readWithRetry = async <T>(session: RunStreamRecovery, read: () => Promise<T>): Promise<T> => {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ const result = await read()
+ session.check()
+ return result
+ } catch (error) {
+ session.check()
+ if (
+ attempt >= MAX_HISTORY_FETCH_ATTEMPTS ||
+ !isTransientStreamError(error as StreamErrorEnvelope)
+ ) {
+ throw error
+ }
+ cache.recoveryStartedAt ??= Date.now()
+ actions.recoveryProgress(session.phase, attempt, MAX_HISTORY_FETCH_ATTEMPTS)
+ await session.wait(reconnectDelayMs(attempt))
+ }
}
- // Flag the run's resume-ness so the projection can drop the synthetic resume-context
- // prompt (§6) before any history frame folds.
+ }
+ const readRun = (session: RunStreamRecovery): Promise<TaskRunDetailDTOApi> =>
+ session.request(STREAM_REQUEST_TIMEOUT_MS, (signal) =>
+ tasksRunsRetrieve(String(session.projectId), session.taskId, session.runId, { signal })
+ )
+ const applyRun = (session: RunStreamRecovery, run: TaskRunDetailDTOApi): void => {
+ session.check()
actions.markBootstrapResumeRun(isResumeRun(run))
- actions.setPendingRunMessage(readPendingRunMessage(run.state, runId))
- // Surface any git artifacts the run already carries (working/base branch, an opened PR)
- // so the pre-turn header and post-turn PR card render immediately on reopen.
actions.mergeRunArtifacts(extractRunArtifacts(run))
- const terminal = isTerminalRunStatus(run.status ?? null)
-
- // Connect the live SSE *before* reading the S3 snapshot for an in-progress run. Frames the
- // 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 && !reconcileHistory) {
- // History replaces the previous page's position, including retries before the first live event.
- cache.lastEventId = undefined
- clearStreamResumeId(runId)
- cache.bufferingLiveFrames = true
- cache.bufferedLiveFrames = []
- actions.openSseForRun({ taskId, runId, startLatest: true })
- return
+ actions.setPendingRunMessage(readPendingRunMessage(run.state, session.runId))
+ if (!isTerminalRunStatus(run.status) && !hasEnded(session)) {
+ actions.handleTerminalStatus({ status: run.status as RunStatus })
}
-
- // 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
+ }
+ const recordRecovery = (session: RunStreamRecovery): void => {
+ if (cache.recoveryStartedAt !== undefined) {
+ posthog.capture('sandbox_stream_recovered', {
+ conversation_id: props.conversationId,
+ trace_id: values.traceId,
+ task_id: session.taskId,
+ run_id: session.runId,
+ recovery_phase: session.phase,
+ run_status: values.currentRunStatus,
+ reconnect_attempts: values.reconnectAttempt,
+ cumulative_reconnect_attempts: values.cumulativeReconnectAttempt,
+ duration_ms: Date.now() - cache.recoveryStartedAt,
+ execution_type: 'sandbox',
+ })
+ cache.recoveryStartedAt = undefined
}
- 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.
- cache.bufferingLiveFrames = false
- cache.bufferedLiveFrames = undefined
- cache.disposables.dispose('reconnect-backoff')
- cache.disposables.dispose('event-source')
- if (reconcileHistory) {
- actions.markHistoryRecoveryFailed()
+ }
+ 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'
+ }
+ const entries = await readWithRetry(session, () =>
+ session.request(STREAM_HISTORY_TIMEOUT_MS, (signal) =>
+ 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)
}
- actions.handleStreamError(
- mapHttpStatusToStreamError((historyResult.historyError as { status?: number })?.status)
+ })
+ const history = normalizeHistory(entries, session.runId, values.isBootstrapResumeRun)
+ let retained = values.log.entries
+ if (
+ cache.retainedMessage &&
+ history.some(
+ (entry) =>
+ entry.source_run_id === session.runId && persistedHumanText(entry) === cache.retainedMessage
)
- return
+ ) {
+ const optimisticIndex = retained.findLastIndex(
+ ({ entry }) =>
+ entry.notification.method === '_client/human_message' &&
+ entry.notification.params?.content === cache.retainedMessage
+ )
+ retained = retained.filter((_, index) => index !== optimisticIndex)
}
- const entries = historyResult
-
- // The full resume-chain S3 snapshot — replayed as `replay`, so the projection renders
- // persisted human turns and side-effect telemetry stays suppressed for history.
- const history = normalizeHistory(entries, runId, isResumeRun(run))
- if (retainedMessage) {
- // Replace the partial snapshot synchronously; ancestor lifecycle frames must not make
- // a successor that is still provisioning appear started or finished.
- actions.replaceLog(emptyRunLog())
+ const log = reconcileRunLog(history, retained, session.buffer, session.runId)
+ const bufferedEntries = new Set(session.buffer)
+ const bufferedIds = new Set(session.buffer.flatMap((entry) => (entry.event_id ? [entry.event_id] : [])))
+ // Rebuild state without publishing a partial transcript or repeating live reactions.
+ cache.rebuildingHistory = true
+ cache.trackedToolInvocations = undefined
+ try {
let reachedSuccessor = false
- history.forEach((entry) => {
- if (!reachedSuccessor && entry.source_run_id === runId) {
- actions.appendResumeBoundary()
+ for (const stored of log.entries) {
+ if (cache.retainedMessage && !reachedSuccessor && stored.entry.source_run_id === session.runId) {
actions.prepareResumeRun()
- actions.permissionRunChanged()
reachedSuccessor = true
}
- actions.ingestAcpFrame(entry, 'replay')
- })
- if (!reachedSuccessor) {
- actions.appendResumeBoundary()
- actions.prepareResumeRun()
- actions.permissionRunChanged()
+ if (stored.entry.notification.method === '_client/human_message') {
+ actions.markTurnStarted()
+ } else if (stored.source !== 'client') {
+ actions.ingestAcpFrame(
+ stored.entry,
+ stored.source === 'live' &&
+ (bufferedEntries.has(stored.entry) ||
+ (stored.entry.event_id && bufferedIds.has(stored.entry.event_id)))
+ ? 'live'
+ : 'replay'
+ )
+ }
}
- const successorItems = foldLogToThread(
- history
- .filter((entry) => entry.source_run_id === runId)
- .map((entry) => ({ entry, source: 'replay' })),
- { isResumeRun: true }
- ).threadItems
- if (!successorItems.some((item) => item.type === 'human_message' && item.text === retainedMessage)) {
- actions.pushHumanMessage(retainedMessage)
+ if (cache.retainedMessage && !reachedSuccessor) {
+ actions.prepareResumeRun()
}
- } else {
- const retainedEntries = retainUnpersistedEntries(values.log.entries, history, isResumeRun(run))
- actions.replaceLog(emptyRunLog())
- history.forEach((entry) => actions.ingestAcpFrame(entry, 'replay'))
- actions.appendEntries(retainedEntries)
+ } finally {
+ cache.rebuildingHistory = false
}
-
- 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
- const survivors = dedupeBufferedAgainstHistory(buffered, history)
- survivors.forEach((entry) => actions.ingestAcpFrame(entry, 'live'))
-
+ actions.replaceLog(log)
+ cache.eventCoverage = new RunEventCoverage([
+ ...history,
+ ...retained.map(({ entry }) => entry),
+ ...session.buffer,
+ ])
+ if (
+ cache.retainedMessage &&
+ !foldLogToThread(log.entries, { isResumeRun: true }).threadItems.some(
+ (item) => item.type === 'human_message' && item.text === cache.retainedMessage
+ )
+ ) {
+ actions.pushHumanMessage(cache.retainedMessage)
+ }
+ cache.retainedMessage = undefined
if (
- reconcileHistory &&
+ recoveringLiveTurn &&
!turnCompleteBeforeReconcile &&
values.turnComplete &&
- !windowShowsToolCallInFlight(survivors)
+ !windowShowsToolCallInFlight(dedupeBufferedAgainstHistory(session.buffer, history))
) {
actions.markTurnComplete()
}
-
- if (terminal) {
- if (retainedMessage) {
- // This bootstrap is the resume attach itself, and a terminal run opens no stream, so
- // the provisioning window is over. A replayed terminal status alone must not clear the
- // flag — an ancestor's bootstrap can resolve terminal while the successor still opens.
- actions.setRunOpening(false)
- }
- // Read-only history — surface the terminal status, do not open SSE. Flag the replay
- // so the listener records the status without re-emitting termination telemetry.
- actions.handleTerminalStatus({ status: run.status as RunStatus, replayedFromHistory: true })
- // `bootstrapReplayComplete`, not `bootstrapLogReady`: with no SSE to open, `sseOpened`
- // never clears the bootstrap spinner, so a terminal run whose history folds to no
- // renderable rows would sit on the skeleton for the instance's lifetime.
- actions.bootstrapReplayComplete()
- return
- }
-
- actions.bootstrapLogReady()
- },
- 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) {
- return
+ session.buffer = []
+ session.buffering = false
+ if (session.receivedCursor) {
+ session.committedCursor = session.receivedCursor
+ session.committedBacklogRunId = session.receivedBacklogRunId
}
- const projectId = values.currentProjectId
- if (projectId === null) {
- actions.handleStreamError({ errorTitle: 'No current project', retryable: false })
- return
+ if (session.committedCursor && !hasEnded(session)) {
+ writeStreamResumeId(session.runId, session.committedCursor)
}
- if (
- cache.streamBootstrap &&
- (cache.streamBootstrap.taskId !== taskId || cache.streamBootstrap.runId !== runId)
- ) {
- cache.streamBootstrap = undefined
- cache.bufferingLiveFrames = false
- cache.bufferedLiveFrames = undefined
+ actions.setHistoryComplete(true)
+ actions.bootstrapLogReady()
+ if (session.phase !== 'finalization') {
+ recordRecovery(session)
}
+ }
- // 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
- // this one — it suppresses the drop handler, which leaves a dropped stream dead with no
- // reconnect and no terminal refetch (the thread then waits on a turn nothing delivers).
- // A stream that really is finished re-delivers the sentinel on this connection.
- cache.streamEnded = false
- cache.streamTokenRefreshes = 0
- const previousRun = cache.activeRun as { taskId: string; runId: string } | undefined
- if (cache.permissionRunId && cache.permissionRunId !== runId) {
- actions.cancelPermissionDelivery()
- actions.permissionRunChanged()
+ const finalize = async (session: RunStreamRecovery): Promise<void> => {
+ session.phase = 'finalization'
+ actions.setHistoryComplete(false)
+ actions.recoveryProgress('finalization', 0, MAX_HISTORY_FETCH_ATTEMPTS)
+ // Status and history have independent budgets; a failed status read must not hide saved output.
+ const results = await Promise.allSettled([
+ isTerminalRunStatus(values.currentRunStatus)
+ ? Promise.resolve()
+ : readWithRetry(session, async () => {
+ const run = await readRun(session)
+ applyRun(session, run)
+ if (!isTerminalRunStatus(run.status)) {
+ throw {
+ errorTitle: "Couldn't confirm the run's final status",
+ errorMessage: 'Retry to check again',
+ retryable: true,
+ }
+ }
+ actions.handleTerminalStatus({ status: run.status as RunStatus })
+ }),
+ reconcileHistory(session),
+ ])
+ if (!session.owns()) {
+ return
}
- cache.permissionRunId = runId
- if (previousRun && (previousRun.runId !== runId || previousRun.taskId !== taskId)) {
- actions.cancelPermissionDelivery()
- actions.permissionRunChanged()
- // 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
+ const failed = results.find((result) => result.status === 'rejected')
+ if (failed?.status === 'rejected') {
+ failRecovery(session, failed.reason)
+ } else {
+ recordRecovery(session)
+ actions.bootstrapReplayComplete()
}
- // Track the active run so the reconnect loop can refetch it on a drop.
- cache.activeRun = { taskId, runId }
- const startLatest = cache.resyncPending ? false : requestedStartLatest
-
- actions.sseConnecting()
- cache.disposables.dispose('reconnect-backoff')
-
- // Route one parsed SSE event. `eventsource-parser` unifies the old `onmessage` (default
- // data channel — `event` undefined) and `addEventListener('error')` (named `error`
- // envelope) split into one callback keyed off the `event` field.
- const handleSseEvent = ({ id, event, data }: EventSourceMessage): void => {
- if (id) {
- // The Redis stream id. Stamped (even for a buffered frame) so a reconnect resumes
- // exactly after it via the Last-Event-ID header — an exclusive resume, so the
- // 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 = false
- writeStreamResumeId(runId, id)
+ }
+ return {
+ [projectLogic.actionTypes.loadCurrentProjectSuccess]: () => {
+ const session = sessionNow()
+ if (session && session.projectId !== values.currentProjectId) {
+ actions.reset()
}
- if (event === STREAM_END_EVENT) {
- // Durable end-of-run sentinel — the run's event stream is finished, so stop here
- // rather than treating the imminent connection close as a drop to reconnect. Drop
- // the persisted cursor (a completed run must never be resumed) and finalize via
- // the listener. `streamEnded` (read by the reader loop) suppresses the clean-EOF
- // drop that follows.
- cache.streamEnded = true
- clearStreamResumeId(runId)
- actions.streamEnded()
+ },
+ bootstrapRun: async ({ taskId, runId, justCreatedRun, retainedMessage }) => {
+ const previous = sessionNow()
+ if (
+ previous?.paused &&
+ previous.projectId === values.currentProjectId &&
+ previous.taskId === taskId &&
+ previous.runId === runId
+ ) {
+ actions.handleStreamError(cache.pausedError)
return
}
- if (event === 'error') {
- // Named error envelope — surface verbatim. Real backend frames carry only `error`,
- // so the title/retryable fall back to the generic stream-failure defaults.
- try {
- const envelope: SseErrorFrameData = JSON.parse(data)
- actions.handleStreamError({
- errorTitle: envelope.errorTitle ?? 'Cloud stream failed',
- errorMessage: envelope.errorMessage,
- retryable: envelope.retryable ?? true,
- })
- } catch {
- actions.handleStreamError({ errorTitle: 'Cloud stream failed', retryable: true })
- }
+ const session = beginSession(taskId, runId)
+ if (!session) {
return
}
- if (event === 'end') {
- let control: unknown
- try {
- control = JSON.parse(data)
- } catch {
+ cache.retainedMessage = retainedMessage
+ cache.isBootstrapping = true
+ actions.setHistoryComplete(false)
+ try {
+ if (hasEnded(session)) {
+ await finalize(session)
+ return
+ }
+ if (justCreatedRun && !props.replayOnly) {
+ cache.skipInitialHistory = true
+ session.buffering = false
+ actions.setHistoryComplete(true)
+ actions.bootstrapLogReady()
+ actions.openSseForRun({ taskId, runId, startLatest: false })
return
}
- if (isRecord(control) && control.type === 'resync') {
- cache.lastEventId = undefined
- clearStreamResumeId(runId)
- cache.resyncPending = true
+ const run = await readWithRetry(session, () => readRun(session))
+ applyRun(session, run)
+ if (isTerminalRunStatus(run.status) || props.replayOnly) {
+ if (isTerminalRunStatus(run.status)) {
+ actions.handleTerminalStatus({ status: run.status as RunStatus, replayedFromHistory: true })
+ }
+ await reconcileHistory(session)
+ session.check()
+ actions.setRunOpening(false)
+ actions.bootstrapReplayComplete()
+ } else {
+ actions.openSseForRun({ taskId, runId, startLatest: false })
}
+ } catch (error) {
+ failRecovery(session, error)
+ }
+ },
+ retryConnection: () => {
+ const previous = sessionNow()
+ if (
+ !previous?.paused ||
+ !values.bootstrapError?.retryable ||
+ values.currentProjectId !== previous.projectId
+ ) {
return
}
- // keepalive (and any other named, non-data event) carries nothing to fold.
- if (event && event !== 'message') {
+ previous.paused = false
+ actions.resetRecoveryBudget()
+ cache.recoveryStartedAt = Date.now()
+ actions.bootstrapRun({ taskId: previous.taskId, runId: previous.runId })
+ },
+ openSseForRun: ({ taskId, runId }) => {
+ if (props.replayOnly) {
return
}
- let parsed: unknown
- try {
- parsed = JSON.parse(data)
- } catch {
+ const previous = sessionNow()
+ if (
+ (previous?.paused &&
+ previous.runId === runId &&
+ previous.taskId === taskId &&
+ previous.projectId === values.currentProjectId) ||
+ (previous && hasEnded(previous) && previous.runId === runId && previous.taskId === taskId)
+ ) {
return
}
- if (isNotificationFrame(parsed)) {
- const entry = { ...parsed, source_run_id: runId }
- // During the bootstrap window the SSE is connected before the S3 snapshot lands,
- // so buffer live notification frames instead of appending them; the drain
- // reconciles them against the snapshot once it loads (see `bootstrapRun`). Steady
- // state (and every send/reconnect open, which never buffers) appends directly.
- if (cache.bufferingLiveFrames) {
- ;(cache.bufferedLiveFrames as StoredLogEntry[]).push(entry)
+ const skipHistory = cache.skipInitialHistory === true || !previous
+ cache.skipInitialHistory = false
+ const session = beginSession(taskId, runId)
+ if (!session || hasEnded(session)) {
+ return
+ }
+ session.phase = 'stream'
+ cache.eventCoverage ??= new RunEventCoverage(values.log.entries.map(({ entry }) => entry))
+ session.buffering = !skipHistory
+ actions.sseConnecting()
+ const controller = new AbortController()
+ let backlogRunId = session.committedBacklogRunId ?? (values.isBootstrapResumeRun ? undefined : runId)
+ const ownsStream = (): boolean => session.owns() && !controller.signal.aborted && !hasEnded(session)
+ const drop = (error?: StreamErrorEnvelope): void => {
+ if (!ownsStream()) {
+ return
+ }
+ if (error && !isTransientStreamError(error)) {
+ failRecovery(session, error)
} else {
- actions.ingestAcpFrame(entry, 'live')
+ actions.sseDropped()
}
- } else if (isPermissionRequestFrame(parsed)) {
- // requestId-keyed dedup: this top-level envelope isn't a notification, so a
- // reconnect's resume could re-deliver it verbatim.
- const record = parsePermissionRequestFrame(parsed, runId)
- if (
- record &&
- !values.seenPermissionRequestIds.has(record.requestId) &&
- !values.resolvedPermissionRequestIds.has(record.requestId)
- ) {
- actions.routePermissionRequest(record)
+ }
+ const handleSseEvent = ({ id, event, data }: EventSourceMessage): void => {
+ if (!ownsStream()) {
+ return
}
- } else if (isTaskRunStateFrame(parsed)) {
- // `stage` is dropped by handleTerminalStatus's status-only path; track it
- // separately for a future richer status surface. Generally unset for PHAI.
- if (parsed.stage !== undefined) {
- actions.setCurrentStage(parsed.stage ?? null)
+ if (event === STREAM_END_EVENT) {
+ actions.streamEnded()
+ return
}
- // The frame carries the working `branch` and an `output.pr_url` once the run opens
- // a PR — fold them in so the post-turn PR card appears the moment it lands.
- actions.mergeRunArtifacts(extractRunArtifacts(parsed))
- actions.handleTerminalStatus({
- status: parsed.status as RunStatus,
- errorMessage: parsed.error_message ?? null,
- })
- }
- // 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
- // whole stream. A clean EOF or read error (not an abort) is a drop → run the recovery
- // loop; an aborted signal (teardown) is silent.
- const streamRun = async (signal: AbortSignal): Promise<void> => {
- // Resolve the destination fresh on every (re)connect: with the rollout flag on this
- // mints a short-lived proxy read token (so a reconnect after a long stream always
- // carries a valid one); with it off, or on the fallback, it's a no-op and we hit
- // Django. A failed mint falls back to Django — streaming never breaks on the proxy.
- const proxyTarget = values.streamViaProxyEnabled
- ? await resolveStreamTarget(String(projectId), taskId, runId, true)
- : null
- if (signal.aborted) {
- return
- }
- const lastEventId = (cache.lastEventId as string | undefined) ?? storedResumeId
-
- let response: Response
- try {
- response = await api.tasks.runs.openStream(taskId, runId, {
- signal,
- lastEventId,
- startLatest,
- ...(proxyTarget ? { proxyTarget } : {}),
- })
- } catch (error) {
- if (signal.aborted) {
+ if (event === 'error') {
+ try {
+ const envelope: SseErrorFrameData = JSON.parse(data)
+ drop({
+ errorTitle: envelope.errorTitle ?? 'Cloud stream failed',
+ errorMessage: envelope.errorMessage,
+ retryable: envelope.retryable ?? true,
+ })
+ } catch {
+ drop({ errorTitle: 'Cloud stream failed', retryable: true })
+ }
return
}
- // A fetch (unlike a native EventSource) exposes the HTTP status. Surface a
- // permanently-failed open (e.g. 404 — the backing run is gone) as a terminal
- // stream error instead of looping the reconnect logic forever; treat a transient
- // status or a network-level reject as a drop and let the recovery loop retry.
- const status = (error as { status?: number })?.status
- // A 401 on the proxy leg means the short-lived read token expired between mint and
- // handshake — re-mint and retry once (free, off the reconnect budget) rather than
- // surfacing an auth error. Bounded so a genuinely revoked user can't loop; on
- // exhaustion it falls through to the normal drop handling (whose Django fallback
- // surfaces a real 401 as a retryable error).
- if (status === 401 && proxyTarget && (cache.streamTokenRefreshes ?? 0) < MAX_STREAM_TOKEN_REMINTS) {
- cache.streamTokenRefreshes = ((cache.streamTokenRefreshes as number | undefined) ?? 0) + 1
- return streamRun(signal)
+ if (event === 'end') {
+ let control: unknown
+ try {
+ control = JSON.parse(data)
+ } catch {
+ return
+ }
+ if (isRecord(control) && control.type === 'resync') {
+ session.committedCursor = undefined
+ session.receivedCursor = undefined
+ session.committedBacklogRunId = undefined
+ session.receivedBacklogRunId = undefined
+ clearStreamResumeId(runId)
+ }
+ return
}
- const mapped = status !== undefined ? mapHttpStatusToStreamError(status) : undefined
- if (mapped && !mapped.retryable) {
- actions.handleStreamError(mapped)
- } else {
- actions.sseDropped()
+ if (event && event !== 'message') {
+ return
+ }
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(data)
+ } catch {
+ return
+ }
+ if (isNotificationFrame(parsed)) {
+ const marker =
+ parsed.notification.method === '_posthog/run_started'
+ ? parsed.notification.params?.runId
+ : parsed.notification.method === '_posthog/sdk_session'
+ ? parsed.notification.params?.taskRunId
+ : undefined
+ if (id?.startsWith('log-') && typeof marker === 'string') {
+ backlogRunId = marker
+ }
+ const entry = {
+ ...parsed,
+ source_run_id: parsed.source_run_id ?? (id?.startsWith('log-') ? backlogRunId : runId),
+ }
+ 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) {
+ session.buffer.push(entry)
+ } else if (!matchesSavedBacklog && !(cache.eventCoverage as RunEventCoverage).covers(entry)) {
+ ;(cache.eventCoverage as RunEventCoverage).add(entry)
+ if (entry.first_event_id) {
+ const log = mergeCoalescedRunLog(values.log, entry)
+ cache.rebuildingHistory = true
+ try {
+ actions.ingestAcpFrame(entry, 'live')
+ } finally {
+ cache.rebuildingHistory = false
+ }
+ actions.replaceLog(log)
+ } else {
+ actions.ingestAcpFrame(entry, 'live')
+ }
+ }
+ } else if (isPermissionRequestFrame(parsed)) {
+ if (session.buffering) {
+ session.buffer.push({
+ type: 'notification',
+ source_run_id: runId,
+ notification: {
+ method: '_posthog/permission_request',
+ params: parsed as unknown as Record<string, unknown>,
+ },
+ })
+ return
+ }
+ const record = parsePermissionRequestFrame(parsed, runId)
+ if (
+ record &&
+ !values.seenPermissionRequestIds.has(record.requestId) &&
+ !values.resolvedPermissionRequestIds.has(record.requestId)
+ ) {
+ actions.routePermissionRequest(record)
+ }
+ } else if (isTaskRunStateFrame(parsed)) {
+ if (parsed.stage !== undefined) {
+ actions.setCurrentStage(parsed.stage ?? null)
+ }
+ actions.mergeRunArtifacts(extractRunArtifacts(parsed))
+ actions.handleTerminalStatus({
+ status: parsed.status as RunStatus,
+ errorMessage: parsed.error_message ?? null,
+ })
+ }
+ if (id && ownsStream()) {
+ session.receivedCursor = id
+ session.receivedBacklogRunId = backlogRunId
+ if (!session.buffering) {
+ session.committedCursor = id
+ session.committedBacklogRunId = backlogRunId
+ writeStreamResumeId(runId, id)
+ }
+ }
+ }
+ const streamRun = async (): Promise<void> => {
+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
+ try {
+ let response: Response
+ for (;;) {
+ const proxyTarget = values.streamViaProxyEnabled
+ ? await session.request(
+ STREAM_REQUEST_TIMEOUT_MS,
+ (signal) =>
+ resolveStreamTarget(String(session.projectId), taskId, runId, true, signal),
+ controller.signal
+ )
+ : null
+ if (!ownsStream()) {
+ return
+ }
+ try {
+ response = await session.request(
+ STREAM_REQUEST_TIMEOUT_MS,
+ () =>
+ api.tasks.runs.openStream(taskId, runId, {
+ projectId: session.projectId,
+ signal: controller.signal,
+ lastEventId: session.committedCursor,
+ startLatest: false,
+ ...(proxyTarget ? { proxyTarget } : {}),
+ }),
+ controller.signal
+ )
+ break
+ } catch (error) {
+ if (!ownsStream()) {
+ return
+ }
+ const status = (error as { status?: number })?.status
+ if (
+ status === 401 &&
+ proxyTarget &&
+ (cache.streamTokenRefreshes ?? 0) < MAX_STREAM_TOKEN_REMINTS
+ ) {
+ cache.streamTokenRefreshes = (cache.streamTokenRefreshes ?? 0) + 1
+ continue
+ }
+ throw error
+ }
+ }
+ if (!ownsStream()) {
+ return
+ }
+ reader = response.body?.getReader()
+ if (!reader) {
+ drop()
+ return
+ }
+ const streamReader = reader
+ cache.disposables.add(
+ () => () => {
+ void streamReader.cancel?.().catch(() => {})
+ },
+ 'stream-reader',
+ { pauseOnPageHidden: false }
+ )
+ actions.sseOpened()
+ if (session.buffering) {
+ void reconcileHistory(session)
+ .then(() => {
+ if (ownsStream()) {
+ actions.sseOpened()
+ }
+ })
+ .catch((error) => failRecovery(session, error))
+ }
+ const decoder = new TextDecoder()
+ const parser = createParser({ onEvent: handleSseEvent })
+ while (ownsStream()) {
+ const { done, value } = await session.request(
+ STREAM_IDLE_TIMEOUT_MS,
+ () => streamReader.read(),
+ controller.signal
+ )
+ if (!ownsStream()) {
+ return
+ }
+ if (value) {
+ parser.feed(decoder.decode(value, { stream: true }))
+ }
+ if (done) {
+ drop()
+ return
+ }
+ }
+ } catch (error) {
+ if (ownsStream()) {
+ drop(mapHttpStatusToStreamError((error as { status?: number })?.status))
+ }
}
- return
}
- if (signal.aborted) {
+ cache.disposables.add(
+ () => {
+ const entry: LiveStreamEntry = {
+ controller,
+ reopen: () => {
+ if (session.owns() && !session.paused) {
+ actions.openSseForRun({ taskId, runId })
+ }
+ },
+ }
+ liveStreamControllers.add(entry)
+ void streamRun()
+ return () => {
+ liveStreamControllers.delete(entry)
+ controller.abort()
+ cache.disposables.dispose('stream-reader')
+ }
+ },
+ 'event-source',
+ { pauseOnPageHidden: false }
+ )
+ },
+ sseOpened: () => {
+ cache.sseConnectedAtMs = Date.now()
+ cache.streamTokenRefreshes = 0
+ },
+ sseDropped: async () => {
+ const previous = sessionNow()
+ if (!previous?.owns() || previous.paused || hasEnded(previous)) {
return
}
- const reader = response.body?.getReader()
- if (!reader) {
- actions.sseDropped()
+ const connectedAtMs = cache.sseConnectedAtMs as number | undefined
+ const wasHealthy =
+ connectedAtMs !== undefined && Date.now() - connectedAtMs >= SSE_HEALTHY_CONNECTION_MS
+ const attempt = wasHealthy ? values.reconnectAttempt : values.reconnectAttempt + 1
+ const session = beginSession(previous.taskId, previous.runId)
+ if (!session) {
return
}
- // 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 (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))
+ session.phase = 'stream'
+ cache.sseConnectedAtMs = undefined
+ cache.recoveryStartedAt ??= Date.now()
+ actions.setHistoryComplete(false)
+ if (
+ attempt > MAX_SSE_RECONNECT_ATTEMPTS ||
+ values.cumulativeReconnectAttempt >= MAX_CUMULATIVE_RECONNECT_ATTEMPTS
) {
- // A cursorless open skips to the new head, so read history only after this connection succeeds.
- actions.bootstrapRun({ ...bootstrap, reconcileHistory: true })
+ failRecovery(session, {
+ errorTitle: 'Cloud stream failed',
+ errorMessage: 'Retry to restore the conversation.',
+ retryable: true,
+ })
+ return
}
- const decoder = new TextDecoder()
- const parser = createParser({ onEvent: handleSseEvent })
+ actions.sseReconnecting(attempt)
try {
- for (;;) {
- const { done, value } = await reader.read()
- if (value) {
- parser.feed(decoder.decode(value, { stream: true }))
+ try {
+ const run = await readRun(session)
+ applyRun(session, run)
+ if (isTerminalRunStatus(run.status)) {
+ actions.handleTerminalStatus({ status: run.status as RunStatus })
+ return
}
- if (done) {
- break
+ } catch (error) {
+ session.check()
+ if (!isTransientStreamError(error as StreamErrorEnvelope)) {
+ throw error
}
}
- } catch {
- if (!signal.aborted && !cache.streamEnded) {
- actions.sseDropped()
- }
+ await session.wait(reconnectDelayMs(Math.max(attempt, 1)))
+ session.check()
+ actions.openSseForRun({ taskId: session.taskId, runId: session.runId })
+ } catch (error) {
+ failRecovery(session, error)
+ }
+ },
+ streamEnded: () => {
+ const previous = sessionNow()
+ if (!previous?.owns() || previous.phase === 'finalization') {
return
}
- // Clean EOF: the server closed the stream. A terminal frame or the `stream-end`
- // sentinel would already have torn us down (dispose → abort / `streamEnded`);
- // otherwise this is a drop, so refetch status and decide.
- if (!signal.aborted && !cache.streamEnded) {
- actions.sseDropped()
+ ;(cache.endedRuns ??= new Set<string>()).add(
+ endedKey(previous.projectId, previous.taskId, previous.runId)
+ )
+ const session = beginSession(previous.taskId, previous.runId)
+ if (!session) {
+ return
}
- }
-
- // Replace any prior connection. A hot reload can orphan the previous build's reader (its
- // `cache`, and thus this disposable, is discarded before teardown runs) — the keyed
- // log store makes duplicate ingestion idempotent, and the module-level
- // `liveStreamControllers` HMR hook aborts the orphan's connection itself.
- cache.disposables.dispose('event-source')
- // pauseOnPageHidden: false — a live stream must survive tab hides; re-running setup on
- // show would reopen the stream and re-fold thread state.
- cache.disposables.add(
- (): (() => void) => {
- const controller = new AbortController()
- // `startLatest: true` mirrors the reconnect path below: the resume actually happens
- // off `cache.lastEventId` via Last-Event-ID, so this only matters if no frame has
- // arrived yet.
- const entry: LiveStreamEntry = {
- controller,
- reopen: () => actions.openSseForRun({ taskId, runId, startLatest: true }),
+ session.buffer = previous.buffer
+ session.receivedCursor = previous.receivedCursor
+ clearStreamResumeId(session.runId)
+ void finalize(session)
+ },
+ routePermissionRequest: ({ record, replayedFromHistory }) => {
+ if (
+ props.replayOnly ||
+ !record.sourceRunId ||
+ record.sourceRunId !== cache.activeRun?.runId ||
+ isTerminalRunStatus(values.currentRunStatus)
+ ) {
+ return
+ }
+ // Replayed history is a read-only restore — never auto-approve (the run may be terminal).
+ // Full-auto covers the task's selected project. Questions, plan approvals, and calls into
+ // connected projects still surface because the task did not authorize them.
+ const fullAuto =
+ isFullAutoMode(values.currentMode) &&
+ !record.questions?.length &&
+ !isPlanPermissionRequest(record) &&
+ !isConnectedProjectTool(record)
+ const decision = fullAuto ? 'auto_allow' : defaultPermissionDecision(record)
+ if (!replayedFromHistory && decision === 'auto_allow') {
+ const optionId = findAllowOptionId(record)
+ if (optionId) {
+ actions.autoApprovePermissionRequest(record, optionId)
+ return
}
- liveStreamControllers.add(entry)
- void streamRun(controller.signal)
- return () => {
- liveStreamControllers.delete(entry)
+ }
+ actions.ingestPermissionRequest(record, replayedFromHistory)
+ },
+ autoApprovePermissionRequest: async ({ record, optionId }) => {
+ // Pin it seen up front so a reconnect replay can't re-process the same request mid-POST.
+ actions.markPermissionRequestSeen(record.requestId)
+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
+ const resolvedToolCall = resolveToolCall(record.rawToolCall)
+ posthog.capture('permission_auto_approved', {
+ conversation_id: props.conversationId,
+ trace_id: values.traceId,
+ request_id: record.requestId,
+ tool_call_name: resolvedToolCall.resolvedKey,
+ tool_call_id: record.toolCallId,
+ run_id: activeRun?.runId,
+ task_id: activeRun?.taskId,
+ execution_type: 'sandbox',
+ })
+ if (!activeRun || values.currentProjectId == null) {
+ // No active run to command yet — fall back to the manual card so the user can respond.
+ actions.ingestPermissionRequest(record)
+ return
+ }
+ actions.deliverPermission(record, optionId, undefined, undefined, true)
+ },
+ ingestPermissionRequest: ({ record, replayedFromHistory }) => {
+ if (replayedFromHistory) {
+ return
+ }
+ // conversation_id / trace_id are correlated by the caller (the SSE bypasses Django);
+ // emit what this logic knows.
+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
+ const resolvedToolCall = resolveToolCall(record.rawToolCall)
+ posthog.capture('permission_requested', {
+ conversation_id: props.conversationId,
+ trace_id: values.traceId,
+ request_id: record.requestId,
+ tool_call_name: resolvedToolCall.resolvedKey,
+ tool_call_id: record.toolCallId,
+ run_id: activeRun?.runId,
+ task_id: activeRun?.taskId,
+ execution_type: 'sandbox',
+ })
+ },
+ respondToPermission: ({ requestId, optionId, customInput, answers }) => {
+ const record = values.pendingPermissionRequest
+ if (record?.requestId === requestId) {
+ actions.deliverPermission(record, optionId, customInput, answers)
+ }
+ },
+ deliverPermission: async ({ record, optionId, customInput, answers, automatic }) => {
+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
+ const projectId = values.currentProjectId
+ if (
+ !activeRun ||
+ projectId == null ||
+ record.sourceRunId !== activeRun.runId ||
+ isTerminalRunStatus(values.currentRunStatus) ||
+ props.replayOnly
+ ) {
+ actions.permissionResponseFailed(record.requestId)
+ return
+ }
+ const deliveries = (cache.permissionDeliveries ??= new Map<string, AbortController>()) as Map<
+ string,
+ AbortController
+ >
+ const key = `permission-delivery:${activeRun.runId}:${record.requestId}`
+ if (deliveries.has(key)) {
+ return
+ }
+ if (values.resolvedPermissionRequestIds.has(record.requestId)) {
+ actions.permissionResponseFailed(record.requestId)
+ return
+ }
+ const controller = new AbortController()
+ const disposables = cache.disposables
+ deliveries.set(key, controller)
+ disposables.add(
+ () => () => {
controller.abort()
+ deliveries.delete(key)
+ },
+ key,
+ { pauseOnPageHidden: false }
+ )
+ const params = {
+ requestId: record.requestId,
+ optionId,
+ customInput,
+ answers: answers ? { ...answers } : undefined,
+ }
+ try {
+ await deliverPermissionResponse(
+ (signal) =>
+ tasksRunsCommandCreate(
+ String(projectId),
+ activeRun.taskId,
+ activeRun.runId,
+ {
+ jsonrpc: '2.0',
+ method: 'permission_response',
+ params,
+ },
+ { signal }
+ ),
+ controller.signal
+ )
+ if (!controller.signal.aborted && !disposables.isDisposed) {
+ actions.markPermissionRequestResolved(record.requestId)
}
- },
- 'event-source',
- { pauseOnPageHidden: false }
- )
- },
- sseOpened: () => {
- // Stamp the connection time for the healthy-connection rule in sseDropped. The
- // provisioning flag (`isBootstrapping`, read by the disconnect telemetry) is NOT cleared
- // here: connect-first opens the SSE before the history snapshot loads, so the bootstrap
- // window (connect → snapshot → drain → first `run_started`) outlives the first connect.
- // It clears when the agent actually starts (`_posthog/run_started`) or on reset.
- cache.sseConnectedAtMs = Date.now()
- // A successful handshake means the proxy token worked — reset the re-mint budget so a
- // later expiry on this long-lived connection re-mints from a clean slate.
- cache.streamTokenRefreshes = 0
- },
- sseDropped: async (_, breakpoint) => {
- const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
- if (!activeRun) {
- return
- }
- // Abort the in-flight reader so its clean-EOF/error handler can't also schedule a
- // reconnect while this loop owns recovery.
- cache.disposables.dispose('event-source')
-
- // First refetch the run to detect terminal state.
- const result = await fetchRunStatus(activeRun.taskId, activeRun.runId)
- breakpoint()
- // The stream was closed or replaced while the refetch was in flight — drop this loop.
- if (cache.activeRun !== activeRun) {
- return
- }
- if ('error' in result) {
- actions.handleStreamError(result.error)
- return
- }
-
- // A reconnect refetch can be the first place a freshly-opened PR (or branch) shows up —
- // fold it in even if the run has since terminated.
- actions.mergeRunArtifacts(result.artifacts)
-
- // Terminal → final terminal-status action + close.
- if (isTerminalRunStatus(result.status)) {
- 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,
+ } catch (error) {
+ if (controller.signal.aborted || disposables.isDisposed) {
+ return
+ }
+ posthog.captureException(error)
+ // The run ended before the approval arrived, so every further attempt gets the same
+ // rejection. Drop the card instead of asking for a retry that cannot succeed.
+ if (isPermissionTargetEnded(error)) {
+ actions.clearPermissionRequest()
+ lemonToast.error(
+ "This run has ended, so the approval wasn't sent. Send a new message to continue."
+ )
+ return
+ }
+ if (automatic) {
+ actions.ingestPermissionRequest(record)
+ }
+ actions.permissionResponseFailed(record.requestId)
+ lemonToast.error('Failed to send approval. Please try again.')
+ } finally {
+ disposables.dispose(key)
+ }
+ },
+ cancelPermissionDelivery: () => {
+ const deliveries = cache.permissionDeliveries as Map<string, AbortController> | undefined
+ for (const key of deliveries?.keys() ?? []) {
+ cache.disposables.dispose(key)
+ }
+ },
+ markPermissionRequestResolved: ({ requestId }) => {
+ cache.disposables.dispose(`permission-delivery:${cache.activeRun?.runId}:${requestId}`)
+ },
+ clearPermissionRequest: () => {
+ actions.cancelPermissionDelivery()
+ },
+ cancelRun: async ({ run }) => {
+ // Cancel a run through the generic tasks relay — the same command PostHog Desktop issues. The
+ // SSE then receives a terminal task_run_state; cancellation telemetry is emitted server-side
+ // by the relay. `run` defaults to the streamed run; a warm Run (not streamed) is passed in.
+ // Fire-and-forget: a failure leaves the run alive for a retry.
+ const target = run ?? (cache.activeRun as { taskId: string; runId: string } | undefined)
+ if (!target || values.currentProjectId == null) {
+ return
+ }
+ // An approval waiting on agent startup outlives this command — the terminal frame that stops
+ // it is a round trip away, so the agent can still accept work the user just canceled. Drop
+ // the delivery here. A warm Run is not the streamed run, so its deliveries are not ours.
+ if (target.runId === (cache.activeRun as { runId: string } | undefined)?.runId) {
+ actions.cancelPermissionDelivery()
+ }
+ try {
+ await tasksRunsCommandCreate(String(values.currentProjectId), target.taskId, target.runId, {
+ jsonrpc: '2.0',
+ method: 'cancel',
})
+ } catch (error) {
+ posthog.captureException(error)
+ }
+ },
+ handleTerminalStatus: ({ status, errorMessage, replayedFromHistory }) => {
+ // The wire emits task_run_state for non-terminal transitions too (e.g. queued →
+ // in_progress) — only an actually-terminal run has no more frames to stream.
+ if (!isTerminalRunStatus(status)) {
+ return
+ }
+ actions.cancelPermissionDelivery()
+ const session = sessionNow()
+ if (session) {
+ ;(cache.endedRuns ??= new Set<string>()).add(
+ endedKey(session.projectId, session.taskId, session.runId)
+ )
+ actions.setStreamHasEnded(true)
+ clearStreamResumeId(session.runId)
+ if (session.phase !== 'finalization' && !replayedFromHistory) {
+ actions.streamEnded()
+ }
}
- actions.handleTerminalStatus({ status: result.status as RunStatus })
- return
- }
- // Cumulative cap — bounds runaway clean-EOF reopen loops that keep resetting the per-drop
- // counter. The about-to-be-scheduled reconnect is the (cumulative + 1)th.
- if (values.cumulativeReconnectAttempt + 1 > MAX_CUMULATIVE_RECONNECT_ATTEMPTS) {
- actions.handleStreamError({ errorTitle: 'Cloud stream failed', retryable: true })
- return
- }
+ // A run that already terminated in a prior session is surfaced read-only on reopen —
+ // the reducers still record the terminal status, but re-emitting telemetry on every
+ // page load would inflate termination counts.
+ if (replayedFromHistory) {
+ return
+ }
- // Healthy-connection rule — a connection that stayed open ≥60s before dropping is not a
- // flaky transport, so its drop is forgiven: schedule a reconnect but don't grow the
- // per-drop budget. The cumulative counter still increments (via sseReconnecting) to
- // bound pathological reopen loops.
- const connectedAtMs = cache.sseConnectedAtMs as number | undefined
- const wasHealthy = connectedAtMs !== undefined && Date.now() - connectedAtMs >= SSE_HEALTHY_CONNECTION_MS
+ // Run-lifecycle signal for apply-back consumers: publish once per run when a live run
+ // reaches a terminal status. `handleTerminalStatus` can fire more than once for the same
+ // run (a task_run_state frame, then a post-drop refetch), so guard on the run id — a
+ // reconnect double-transition must not re-fire the reaction. Replay is already excluded
+ // by the early return above.
+ const lifecycleRun = cache.activeRun as { taskId: string; runId: string } | undefined
+ const emittedRunIds = (cache.emittedTerminalRunIds ??= new Set<string>()) as Set<string>
+ if (lifecycleRun && emittedRunIds.has(lifecycleRun.runId)) {
+ return
+ }
+ if (lifecycleRun) {
+ emittedRunIds.add(lifecycleRun.runId)
+ actions.emitRunLifecycleEvent({ streamKey: props.streamKey, status: status as RunTerminalStatus })
+ }
- // Non-terminal → capped exponential backoff; attempts exhausted surface a retryable error.
- const attempt = wasHealthy ? values.reconnectAttempt : values.reconnectAttempt + 1
- if (attempt > MAX_SSE_RECONNECT_ATTEMPTS) {
- actions.handleStreamError({ errorTitle: 'Cloud stream failed', retryable: true })
- return
- }
- // Backoff off the per-drop budget; a forgiven healthy drop (attempt 0) reconnects fast.
- const delayMs = reconnectDelayMs(Math.max(attempt, 1))
- actions.sseReconnecting(attempt)
- // pauseOnPageHidden: false — the SSE connection survives tab hides, so a drop in a
- // hidden tab must also reconnect there; a paused timer would stall until refocus.
- cache.disposables.add(
- (): (() => void) => {
- const timer = window.setTimeout(() => {
- // Resume from `cache.lastEventId` via the Last-Event-ID header (set inside
- // openSseForRun) — the backend replays exactly the frames after it, filling
- // the gap with no re-broadcast. `startLatest: true` only matters if no frame
- // was ever seen (dropped before the first one): then resume from the head
- // rather than re-streaming from `0`.
- actions.openSseForRun({ taskId: activeRun.taskId, runId: activeRun.runId, startLatest: true })
- }, delayMs)
- return () => clearTimeout(timer)
- },
- 'reconnect-backoff',
- { pauseOnPageHidden: false }
- )
- },
- streamEnded: async (_, breakpoint) => {
- // The durable `stream-end` sentinel landed: tear down without reconnecting.
- cache.disposables.dispose('reconnect-backoff')
- cache.disposables.dispose('event-source')
- const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
- // The terminal `task_run_state` frame ahead of the sentinel usually already finalized the
- // run (and fired its telemetry); short-circuit so we don't refetch or double-count. Only
- // when the stream ended without one do we refetch to resolve the authoritative status.
- if (!activeRun || isTerminalRunStatus(values.currentRunStatus)) {
- return
- }
- const result = await fetchRunStatus(activeRun.taskId, activeRun.runId)
- breakpoint()
- // The stream was closed or replaced while the refetch was in flight — drop this loop.
- if (cache.activeRun !== activeRun) {
- return
- }
- if ('error' in result) {
- // Stream said done but the status is unreadable — leave the thread as-is and never
- // reconnect; the durable stream is authoritatively finished.
- return
- }
- // A reconnect/end refetch can be the first place a freshly-opened PR (or branch) shows up.
- actions.mergeRunArtifacts(result.artifacts)
- if (isTerminalRunStatus(result.status)) {
- actions.handleTerminalStatus({ status: result.status as RunStatus })
- }
- },
- routePermissionRequest: ({ record, replayedFromHistory }) => {
- if (
- props.replayOnly ||
- !record.sourceRunId ||
- record.sourceRunId !== cache.activeRun?.runId ||
- isTerminalRunStatus(values.currentRunStatus)
- ) {
- return
- }
- // Replayed history is a read-only restore — never auto-approve (the run may be terminal).
- // Full-auto covers the task's selected project. Questions, plan approvals, and calls into
- // connected projects still surface because the task did not authorize them.
- const fullAuto =
- isFullAutoMode(values.currentMode) &&
- !record.questions?.length &&
- !isPlanPermissionRequest(record) &&
- !isConnectedProjectTool(record)
- const decision = fullAuto ? 'auto_allow' : defaultPermissionDecision(record)
- if (!replayedFromHistory && decision === 'auto_allow') {
- const optionId = findAllowOptionId(record)
- if (optionId) {
- actions.autoApprovePermissionRequest(record, optionId)
+ // Crash/failure affordance: a failed run carrying an error_message otherwise just blanks
+ // the thinking indicator. Push a visible error item so the user sees why it stopped. The
+ // in-sandbox agent server writes "Agent server crashed: …" on a fatal exception — render
+ // that as a friendlier, retry-oriented `crash` variant; other failures show the raw line.
+ if (status === 'failed' && errorMessage) {
+ actions.pushErrorItem(errorMessage, errorMessage.startsWith(AGENT_CRASH_PREFIX) ? 'crash' : 'error')
+ }
+
+ // TASK_RUN_TERMINATED telemetry. `duration_ms` is measured from the current turn's start
+ // (run start for the first turn, the latest human message for a follow-up); absent if the
+ // run terminated before either was seen.
+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
+ const startedAt = cache.turnStartedAtMs as number | undefined
+ posthog.capture('task_run_terminated', {
+ conversation_id: props.conversationId,
+ trace_id: values.traceId,
+ run_id: activeRun?.runId,
+ task_id: activeRun?.taskId,
+ status,
+ error_message: errorMessage ?? undefined,
+ execution_type: 'sandbox',
+ duration_ms: startedAt !== undefined ? Date.now() - startedAt : undefined,
+ })
+ },
+ handleStreamError: ({ errorTitle, retryable }) => {
+ const session = sessionNow()
+ if (session && cache.disconnectedGeneration === session.generation) {
return
}
- }
- actions.ingestPermissionRequest(record, replayedFromHistory)
- },
- autoApprovePermissionRequest: async ({ record, optionId }) => {
- // Pin it seen up front so a reconnect replay can't re-process the same request mid-POST.
- actions.markPermissionRequestSeen(record.requestId)
- const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
- const resolvedToolCall = resolveToolCall(record.rawToolCall)
- posthog.capture('permission_auto_approved', {
- conversation_id: props.conversationId,
- trace_id: values.traceId,
- request_id: record.requestId,
- tool_call_name: resolvedToolCall.resolvedKey,
- tool_call_id: record.toolCallId,
- run_id: activeRun?.runId,
- task_id: activeRun?.taskId,
- execution_type: 'sandbox',
- })
- if (!activeRun || values.currentProjectId == null) {
- // No active run to command yet — fall back to the manual card so the user can respond.
- actions.ingestPermissionRequest(record)
- return
- }
- actions.deliverPermission(record, optionId, undefined, undefined, true)
- },
- ingestPermissionRequest: ({ record, replayedFromHistory }) => {
- if (replayedFromHistory) {
- return
- }
- // conversation_id / trace_id are correlated by the caller (the SSE bypasses Django);
- // emit what this logic knows.
- const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
- const resolvedToolCall = resolveToolCall(record.rawToolCall)
- posthog.capture('permission_requested', {
- conversation_id: props.conversationId,
- trace_id: values.traceId,
- request_id: record.requestId,
- tool_call_name: resolvedToolCall.resolvedKey,
- tool_call_id: record.toolCallId,
- run_id: activeRun?.runId,
- task_id: activeRun?.taskId,
- execution_type: 'sandbox',
- })
- },
- respondToPermission: ({ requestId, optionId, customInput, answers }) => {
- const record = values.pendingPermissionRequest
- if (record?.requestId === requestId) {
- actions.deliverPermission(record, optionId, customInput, answers)
- }
- },
- deliverPermission: async ({ record, optionId, customInput, answers, automatic }) => {
- const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
- const projectId = values.currentProjectId
- if (
- !activeRun ||
- projectId == null ||
- record.sourceRunId !== activeRun.runId ||
- isTerminalRunStatus(values.currentRunStatus) ||
- props.replayOnly
- ) {
- actions.permissionResponseFailed(record.requestId)
- return
- }
- const deliveries = (cache.permissionDeliveries ??= new Map<string, AbortController>()) as Map<
- string,
- AbortController
- >
- const key = `permission-delivery:${activeRun.runId}:${record.requestId}`
- if (deliveries.has(key)) {
- return
- }
- if (values.resolvedPermissionRequestIds.has(record.requestId)) {
- actions.permissionResponseFailed(record.requestId)
- return
- }
- const controller = new AbortController()
- const disposables = cache.disposables
- deliveries.set(key, controller)
- disposables.add(
- () => () => {
- controller.abort()
- deliveries.delete(key)
- },
- key,
- { pauseOnPageHidden: false }
- )
- const params = {
- requestId: record.requestId,
- optionId,
- customInput,
- answers: answers ? { ...answers } : undefined,
- }
- try {
- await deliverPermissionResponse(
- (signal) =>
- tasksRunsCommandCreate(
- String(projectId),
- activeRun.taskId,
- activeRun.runId,
- {
- jsonrpc: '2.0',
- method: 'permission_response',
- params,
+ cache.disconnectedGeneration = session?.generation
+ // A stream/connection failure no longer appends an inline error item (which stacked up as
+ // spam on a flapping stream). It sets `sseStatus='error'` + the error envelope via the reducers,
+ // which the `runConnectionState` selector projects into the single footer `RunAlertActivity`
+ // card. Here we only capture the disconnect telemetry that mirrors the cloud client's
+ // CLOUD_STREAM_DISCONNECTED (the relay can't see a client-side reconnect-budget exhaustion).
+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
+ posthog.capture('sandbox_stream_disconnected', {
+ conversation_id: props.conversationId,
+ trace_id: values.traceId,
+ run_id: activeRun?.runId,
+ task_id: activeRun?.taskId,
+ error_title: errorTitle,
+ retryable,
+ reconnect_attempts: values.reconnectAttempt,
+ stream_error_attempts: 0,
+ cumulative_reconnect_attempts: values.cumulativeReconnectAttempt,
+ was_bootstrapping: cache.isBootstrapping === true,
+ execution_type: 'sandbox',
+ recovery_phase: sessionNow()?.phase,
+ run_status: values.currentRunStatus,
+ http_status: values.bootstrapError?.status,
+ })
+ },
+ closeSse: () => {
+ cache.disposables.dispose('stream-session')
+ if (sessionNow()) {
+ sessionNow()!.paused = false
+ }
+ actions.cancelPermissionDelivery()
+ cache.activeRun = undefined
+ // Aborts the in-flight fetch reader (its signal); the reader loop sees `aborted` and
+ // exits without scheduling a reconnect.
+ cache.disposables.dispose('event-source')
+ },
+ reset: () => {
+ cache.disposables.dispose('stream-session')
+ cache.recoverySession = undefined
+ cache.eventCoverage = undefined
+ cache.retainedMessage = undefined
+ cache.recoveryStartedAt = undefined
+ actions.cancelPermissionDelivery()
+ cache.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.
+ cache.trackedToolInvocations = undefined
+ cache.permissionRunId = undefined
+ cache.activeRun = undefined
+ cache.turnStartedAtMs = undefined
+ cache.isBootstrapping = false
+ cache.sseConnectedAtMs = undefined
+ cache.streamTokenRefreshes = 0
+ cache.disposables.dispose('event-source')
+ },
+ startOptimisticRun: ({ message }) => {
+ actions.setRunOpening(true)
+ if (message) {
+ actions.pushHumanMessage(message)
+ }
+ },
+ appendResumeBoundary: () => {
+ // A killed run can end without a turn_complete frame. Close that turn before inserting
+ // the successor's message, or the projection moves it ahead of the previous answer.
+ if (!values.turnComplete && values.log.entries.length > 0) {
+ actions.appendEntries([
+ {
+ entry: {
+ type: 'notification',
+ notification: { method: '_posthog/turn_complete', params: {} },
},
- { signal }
- ),
- controller.signal
- )
- if (!controller.signal.aborted && !disposables.isDisposed) {
- actions.markPermissionRequestResolved(record.requestId)
+ source: 'client',
+ },
+ ])
}
- } catch (error) {
- if (controller.signal.aborted || disposables.isDisposed) {
+ },
+ startOptimisticResume: ({ message }) => {
+ const historyComplete = values.historyComplete
+ const turnComplete = values.turnComplete
+ const previousEntryCount = values.log.entries.length
+ actions.appendResumeBoundary()
+ actions.setRunOpening(true)
+ actions.pushHumanMessage(message)
+ cache.optimisticResume = {
+ entries: values.log.entries.slice(previousEntryCount),
+ message,
+ historyComplete,
+ turnComplete,
+ } satisfies OptimisticResume
+ },
+ rollbackOptimisticResume: () => {
+ const resume = cache.optimisticResume as OptimisticResume | undefined
+ if (!resume) {
return
}
- posthog.captureException(error)
- // The run ended before the approval arrived, so every further attempt gets the same
- // rejection. Drop the card instead of asking for a retry that cannot succeed.
- if (isPermissionTargetEnded(error)) {
- actions.clearPermissionRequest()
- lemonToast.error("This run has ended, so the approval wasn't sent. Send a new message to continue.")
- return
+ cache.optimisticResume = undefined
+ actions.replaceLog(
+ appendToRunLog(
+ emptyRunLog(),
+ values.log.entries.filter((entry) => !resume.entries.includes(entry))
+ )
+ )
+ if (resume.turnComplete) {
+ actions.markTurnComplete()
}
- if (automatic) {
- actions.ingestPermissionRequest(record)
+ },
+ attachOptimisticResume: ({ taskId, run }) => {
+ const resume = cache.optimisticResume as OptimisticResume | undefined
+ if (!resume) {
+ return
}
- actions.permissionResponseFailed(record.requestId)
- lemonToast.error('Failed to send approval. Please try again.')
- } finally {
- disposables.dispose(key)
- }
- },
- cancelPermissionDelivery: () => {
- const deliveries = cache.permissionDeliveries as Map<string, AbortController> | undefined
- for (const key of deliveries?.keys() ?? []) {
- cache.disposables.dispose(key)
- }
- },
- markPermissionRequestResolved: ({ requestId }) => {
- cache.disposables.dispose(`permission-delivery:${cache.activeRun?.runId}:${requestId}`)
- },
- clearPermissionRequest: () => {
- actions.cancelPermissionDelivery()
- },
- cancelRun: async ({ run }) => {
- // Cancel a run through the generic tasks relay — the same command PostHog Desktop issues. The
- // SSE then receives a terminal task_run_state; cancellation telemetry is emitted server-side
- // by the relay. `run` defaults to the streamed run; a warm Run (not streamed) is passed in.
- // Fire-and-forget: a failure leaves the run alive for a retry.
- const target = run ?? (cache.activeRun as { taskId: string; runId: string } | undefined)
- if (!target || values.currentProjectId == null) {
- return
- }
- // An approval waiting on agent startup outlives this command — the terminal frame that stops
- // it is a round trip away, so the agent can still accept work the user just canceled. Drop
- // the delivery here. A warm Run is not the streamed run, so its deliveries are not ours.
- if (target.runId === (cache.activeRun as { runId: string } | undefined)?.runId) {
- actions.cancelPermissionDelivery()
- }
- try {
- await tasksRunsCommandCreate(String(values.currentProjectId), target.taskId, target.runId, {
- jsonrpc: '2.0',
- method: 'cancel',
+ cache.optimisticResume = undefined
+ actions.closeSse()
+ actions.prepareResumeRun()
+ actions.permissionRunChanged()
+ cache.trackedToolInvocations = undefined
+ actions.markBootstrapResumeRun(true)
+ actions.mergeRunArtifacts(extractRunArtifacts(run))
+ actions.bootstrapRun({
+ taskId,
+ runId: run.id,
+ justCreatedRun: resume.historyComplete,
+ ...(!resume.historyComplete ? { retainedMessage: resume.message } : {}),
})
- } catch (error) {
- posthog.captureException(error)
- }
- },
- handleTerminalStatus: ({ status, errorMessage, replayedFromHistory }) => {
- // The wire emits task_run_state for non-terminal transitions too (e.g. queued →
- // in_progress) — only an actually-terminal run has no more frames to stream.
- if (!isTerminalRunStatus(status)) {
- return
- }
- actions.cancelPermissionDelivery()
- cache.disposables.dispose('reconnect-backoff')
- cache.disposables.dispose('event-source')
-
- // The run is done — drop its persisted resume cursor so a later reopen can't try to
- // resume a finished stream (the S3 history replay is the reopen path).
- const terminalRun = cache.activeRun as { taskId: string; runId: string } | undefined
- if (terminalRun) {
- clearStreamResumeId(terminalRun.runId)
- }
-
- // A run that already terminated in a prior session is surfaced read-only on reopen —
- // the reducers still record the terminal status, but re-emitting telemetry on every
- // page load would inflate termination counts.
- if (replayedFromHistory) {
- return
- }
-
- // Run-lifecycle signal for apply-back consumers: publish once per run when a live run
- // reaches a terminal status. `handleTerminalStatus` can fire more than once for the same
- // run (a task_run_state frame, then a post-drop refetch), so guard on the run id — a
- // reconnect double-transition must not re-fire the reaction. Replay is already excluded
- // by the early return above.
- const lifecycleRun = cache.activeRun as { taskId: string; runId: string } | undefined
- const emittedRunIds = (cache.emittedTerminalRunIds ??= new Set<string>()) as Set<string>
- if (lifecycleRun && !emittedRunIds.has(lifecycleRun.runId)) {
- emittedRunIds.add(lifecycleRun.runId)
- actions.emitRunLifecycleEvent({ streamKey: props.streamKey, status: status as RunTerminalStatus })
- }
-
- // Crash/failure affordance: a failed run carrying an error_message otherwise just blanks
- // the thinking indicator. Push a visible error item so the user sees why it stopped. The
- // in-sandbox agent server writes "Agent server crashed: …" on a fatal exception — render
- // that as a friendlier, retry-oriented `crash` variant; other failures show the raw line.
- if (status === 'failed' && errorMessage) {
- actions.pushErrorItem(errorMessage, errorMessage.startsWith(AGENT_CRASH_PREFIX) ? 'crash' : 'error')
- }
-
- // TASK_RUN_TERMINATED telemetry. `duration_ms` is measured from the current turn's start
- // (run start for the first turn, the latest human message for a follow-up); absent if the
- // run terminated before either was seen.
- const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
- const startedAt = cache.turnStartedAtMs as number | undefined
- posthog.capture('task_run_terminated', {
- conversation_id: props.conversationId,
- trace_id: values.traceId,
- run_id: activeRun?.runId,
- task_id: activeRun?.taskId,
- status,
- error_message: errorMessage ?? undefined,
- execution_type: 'sandbox',
- duration_ms: startedAt !== undefined ? Date.now() - startedAt : undefined,
- })
- },
- handleStreamError: ({ errorTitle, retryable }) => {
- // A stream/connection failure no longer appends an inline error item (which stacked up as
- // spam on a flapping stream). It sets `sseStatus='error'` + the error envelope via the reducers,
- // which the `runConnectionState` selector projects into the single footer `RunAlertActivity`
- // card. Here we only capture the disconnect telemetry that mirrors the cloud client's
- // CLOUD_STREAM_DISCONNECTED (the relay can't see a client-side reconnect-budget exhaustion).
- const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
- posthog.capture('sandbox_stream_disconnected', {
- conversation_id: props.conversationId,
- trace_id: values.traceId,
- run_id: activeRun?.runId,
- task_id: activeRun?.taskId,
- error_title: errorTitle,
- retryable,
- reconnect_attempts: values.reconnectAttempt,
- stream_error_attempts: 0,
- cumulative_reconnect_attempts: values.cumulativeReconnectAttempt,
- was_bootstrapping: cache.isBootstrapping === true,
- execution_type: 'sandbox',
- })
- },
- closeSse: () => {
- actions.cancelPermissionDelivery()
- cache.streamBootstrap = undefined
- cache.bufferingLiveFrames = false
- cache.bufferedLiveFrames = undefined
- cache.activeRun = undefined
- cache.lastEventId = undefined
- cache.resyncPending = false
- cache.disposables.dispose('reconnect-backoff')
- // Aborts the in-flight fetch reader (its signal); the reader loop sees `aborted` and
- // exits without scheduling a reconnect.
- cache.disposables.dispose('event-source')
- },
- reset: () => {
- actions.cancelPermissionDelivery()
- cache.streamBootstrap = undefined
- cache.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.
- cache.trackedToolInvocations = undefined
- cache.permissionRunId = undefined
- cache.activeRun = undefined
- cache.turnStartedAtMs = undefined
- cache.isBootstrapping = false
- cache.bufferingLiveFrames = false
- cache.bufferedLiveFrames = undefined
- cache.resyncPending = false
- cache.sseConnectedAtMs = undefined
- cache.streamEnded = false
- cache.streamTokenRefreshes = 0
- cache.emittedTerminalRunIds = undefined
- // Drop the resume cursor so the next bootstrap opens fresh (start=latest) instead of
- // resuming a prior run's stream.
- cache.lastEventId = undefined
- cache.disposables.dispose('reconnect-backoff')
- cache.disposables.dispose('event-source')
- },
- startOptimisticRun: ({ message }) => {
- actions.setRunOpening(true)
- if (message) {
- actions.pushHumanMessage(message)
- }
- },
- appendResumeBoundary: () => {
- // A killed run can end without a turn_complete frame. Close that turn before inserting
- // the successor's message, or the projection moves it ahead of the previous answer.
- if (!values.turnComplete && values.log.entries.length > 0) {
+ },
+ pushHumanMessage: ({ content }) => {
+ // The echo is always a live turn (replayed human turns render straight from the log), so
+ // stamp the turn start for per-turn duration metrics and append it as a `client`-sourced
+ // log entry the projection renders in order.
+ cache.turnStartedAtMs = Date.now()
+ // A send does NOT revive a dead stream, and reviving one is harder than it looks:
+ // `sseStatus: 'error'` covers a failed history bootstrap as well as an exhausted
+ // reconnect budget, and the bootstrap case has already dropped buffered frames whose
+ // ids advanced the resume cursor, so reopening from it silently skips them; a reopen
+ // also inherits the spent reconnect budgets, so the next drop gives up at once. A
+ // stream the durable sentinel closed cannot be revived at all — its Redis stream holds
+ // a completion entry the server stops at and refuses to write past.
actions.appendEntries([
{
- entry: { type: 'notification', notification: { method: '_posthog/turn_complete', params: {} } },
+ entry: {
+ type: 'notification',
+ notification: { method: '_client/human_message', params: { content } },
+ },
source: 'client',
},
])
- }
- },
- startOptimisticResume: ({ message }) => {
- const historyComplete = !values.logBootstrapLoading && !values.bootstrapError
- const turnComplete = values.turnComplete
- const previousEntryCount = values.log.entries.length
- actions.appendResumeBoundary()
- actions.setRunOpening(true)
- actions.pushHumanMessage(message)
- cache.optimisticResume = {
- entries: values.log.entries.slice(previousEntryCount),
- message,
- historyComplete,
- turnComplete,
- } satisfies OptimisticResume
- },
- rollbackOptimisticResume: () => {
- const resume = cache.optimisticResume as OptimisticResume | undefined
- if (!resume) {
- return
- }
- cache.optimisticResume = undefined
- actions.replaceLog(
- appendToRunLog(
- emptyRunLog(),
- values.log.entries.filter((entry) => !resume.entries.includes(entry))
- )
- )
- if (resume.turnComplete) {
- actions.markTurnComplete()
- }
- },
- attachOptimisticResume: ({ taskId, run }) => {
- const resume = cache.optimisticResume as OptimisticResume | undefined
- if (!resume) {
- return
- }
- cache.optimisticResume = undefined
- actions.closeSse()
- actions.prepareResumeRun()
- actions.permissionRunChanged()
- cache.trackedToolInvocations = undefined
- actions.markBootstrapResumeRun(true)
- actions.mergeRunArtifacts(extractRunArtifacts(run))
- actions.bootstrapRun({
- taskId,
- runId: run.id,
- justCreatedRun: resume.historyComplete,
- ...(!resume.historyComplete ? { retainedMessage: resume.message } : {}),
- })
- },
- pushHumanMessage: ({ content }) => {
- // The echo is always a live turn (replayed human turns render straight from the log), so
- // stamp the turn start for per-turn duration metrics and append it as a `client`-sourced
- // log entry the projection renders in order.
- cache.turnStartedAtMs = Date.now()
- // A send does NOT revive a dead stream, and reviving one is harder than it looks:
- // `sseStatus: 'error'` covers a failed history bootstrap as well as an exhausted
- // reconnect budget, and the bootstrap case has already dropped buffered frames whose
- // ids advanced the resume cursor, so reopening from it silently skips them; a reopen
- // also inherits the spent reconnect budgets, so the next drop gives up at once. A
- // stream the durable sentinel closed cannot be revived at all — its Redis stream holds
- // a completion entry the server stops at and refuses to write past.
- actions.appendEntries([
- {
- entry: {
- type: 'notification',
- notification: { method: '_client/human_message', params: { content } },
- },
- source: 'client',
- },
- ])
- },
- pushConversationCleared: () => {
- actions.appendEntries([
- {
- entry: {
- type: 'notification',
- notification: { method: '_posthog/conversation_cleared', params: {} },
+ },
+ pushConversationCleared: () => {
+ actions.appendEntries([
+ {
+ entry: {
+ type: 'notification',
+ notification: { method: '_posthog/conversation_cleared', params: {} },
+ },
+ source: 'client',
},
- source: 'client',
- },
- ])
- },
- pushErrorItem: ({ errorMessage, variant }) => {
- // Client-side errors (terminal failure, stream disconnect) aren't wire frames — append
- // them as `client`-sourced log entries so the projection renders them in thread order.
- actions.appendEntries([
- {
- entry: {
- type: 'notification',
- notification: { method: '_client/error', params: { message: errorMessage, variant } },
+ ])
+ },
+ pushErrorItem: ({ errorMessage, variant }) => {
+ // Client-side errors (terminal failure, stream disconnect) aren't wire frames — append
+ // them as `client`-sourced log entries so the projection renders them in thread order.
+ actions.appendEntries([
+ {
+ entry: {
+ type: 'notification',
+ notification: { method: '_client/error', params: { message: errorMessage, variant } },
+ },
+ source: 'client',
},
- source: 'client',
- },
- ])
- },
- ingestAcpFrame: ({ entry, source }) => {
- const notification = entry?.notification
- if (!notification) {
- return
- }
- const method = notification.method
- const isReplay = source === 'replay'
+ ])
+ },
+ ingestAcpFrame: ({ entry, source }) => {
+ const notification = entry?.notification
+ if (!notification) {
+ return
+ }
+ const method = notification.method
+ const isReplay = source === 'replay'
+
+ // Tool-stream events go out for every live frame; on replay only when a subscriber opted in
+ // (so history replay doesn't pay per-frame resolution for nobody).
+ const emitToolStream =
+ !isReplay || (!cache.rebuildingHistory && hasReplayListener(values.toolListeners))
+
+ // Per-frame tool-invocation tracker: the same fold the projection applies, maintained
+ // O(1) per tool frame so the telemetry and tool-stream emits below never read the
+ // `toolInvocations` projection (each such read re-folds the entire log, which turns a
+ // long tool-heavy history replay quadratic). Maintained for every source so a live update
+ // whose `tool_call` arrived during replay still sees the right prior status.
+ // `preToolStatus` is the status BEFORE this frame folds in; it gates the
+ // once-per-transition `tool_call_completed` telemetry and the tool-stream phase.
+ const trackedInvocations: Map<string, ToolInvocation> = (cache.trackedToolInvocations ??= new Map())
+ let preToolStatus: ToolInvocationStatus | undefined
+ if (method === 'session/update') {
+ const u = notification.params?.update
+ if (isRecord(u) && u.sessionUpdate === 'tool_call') {
+ const invocation = invocationFromToolCall(u)
+ if (invocation) {
+ trackedInvocations.set(invocation.toolCallId, invocation)
+ }
+ } else if (isRecord(u) && u.sessionUpdate === 'tool_call_update') {
+ const existing = trackedInvocations.get(String(u.toolCallId ?? ''))
+ preToolStatus = existing?.status
+ const invocation = invocationFromToolCallUpdate(existing, u, notification)
+ if (invocation) {
+ trackedInvocations.set(invocation.toolCallId, invocation)
+ }
+ }
+ }
- // Tool-stream events go out for every live frame; on replay only when a subscriber opted in
- // (so history replay doesn't pay per-frame resolution for nobody).
- const emitToolStream = !isReplay || hasReplayListener(values.toolListeners)
+ // Append to the ordered log — the single source of truth. The bootstrap seam was already
+ // deduped (see `bootstrapRun`) and steady-state live frames resume exclusively, so the
+ // side effects below run exactly once per frame without a per-frame key; the
+ // run-started/permission/tool-completion guards enforce fire-once on their own.
+ if (!cache.rebuildingHistory) {
+ actions.appendEntries([{ entry, source }])
+ }
- // Per-frame tool-invocation tracker: the same fold the projection applies, maintained
- // O(1) per tool frame so the telemetry and tool-stream emits below never read the
- // `toolInvocations` projection (each such read re-folds the entire log, which turns a
- // long tool-heavy history replay quadratic). Maintained for every source so a live update
- // whose `tool_call` arrived during replay still sees the right prior status.
- // `preToolStatus` is the status BEFORE this frame folds in; it gates the
- // once-per-transition `tool_call_completed` telemetry and the tool-stream phase.
- const trackedInvocations: Map<string, ToolInvocation> = (cache.trackedToolInvocations ??= new Map())
- let preToolStatus: ToolInvocationStatus | undefined
- if (method === 'session/update') {
- const u = notification.params?.update
- if (isRecord(u) && u.sessionUpdate === 'tool_call') {
- const invocation = invocationFromToolCall(u)
- if (invocation) {
- trackedInvocations.set(invocation.toolCallId, invocation)
+ // Custom `_posthog/*` notification namespace emitted by the agent-server. Thread items
+ // (errors, status, compaction, task notifications, progress, human turns) are derived by
+ // the projection straight from the log — handled here only for their value-fold side
+ // effects (telemetry, usage/resources/mode folds, permission routing).
+ if (method === '_posthog/run_started') {
+ // TASK_RUN_STARTED telemetry — emit once per run on the first `_posthog/run_started`
+ // frame. Suppressed while replaying history (the run started in a prior session);
+ // `markRunStarted` still runs so started/thinking state stays correct.
+ if (!values.runStarted && !isReplay) {
+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
+ cache.turnStartedAtMs = Date.now()
+ posthog.capture('task_run_started', {
+ conversation_id: props.conversationId,
+ trace_id: values.traceId,
+ run_id: activeRun?.runId,
+ task_id: activeRun?.taskId,
+ execution_type: 'sandbox',
+ // The run-started frame carries no warmth signal and pre-warming isn't wired
+ // yet, so every run is a cold start. A later pre-warm hook flips this.
+ cold_start: true,
+ })
}
- } else if (isRecord(u) && u.sessionUpdate === 'tool_call_update') {
- const existing = trackedInvocations.get(String(u.toolCallId ?? ''))
- preToolStatus = existing?.status
- const invocation = invocationFromToolCallUpdate(existing, u, notification)
- if (invocation) {
- trackedInvocations.set(invocation.toolCallId, invocation)
+ actions.setConversationClearSupported(
+ (notification.params as { conversationClear?: unknown } | undefined)?.conversationClear === true
+ )
+ cache.isBootstrapping = false
+ actions.markRunStarted()
+ return
+ }
+ if (method === '_posthog/turn_complete') {
+ if (!isReplay) {
+ actions.emitTurnCompleteEvent({ streamKey: props.streamKey })
}
+ actions.markTurnComplete(isReplay)
+ return
}
- }
-
- // Append to the ordered log — the single source of truth. The bootstrap seam was already
- // deduped (see `bootstrapRun`) and steady-state live frames resume exclusively, so the
- // side effects below run exactly once per frame without a per-frame key; the
- // run-started/permission/tool-completion guards enforce fire-once on their own.
- actions.appendEntries([{ entry, source }])
-
- // Custom `_posthog/*` notification namespace emitted by the agent-server. Thread items
- // (errors, status, compaction, task notifications, progress, human turns) are derived by
- // the projection straight from the log — handled here only for their value-fold side
- // effects (telemetry, usage/resources/mode folds, permission routing).
- if (method === '_posthog/run_started') {
- // TASK_RUN_STARTED telemetry — emit once per run on the first `_posthog/run_started`
- // frame. Suppressed while replaying history (the run started in a prior session);
- // `markRunStarted` still runs so started/thinking state stays correct.
- if (!values.runStarted && !isReplay) {
- const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined
- cache.turnStartedAtMs = Date.now()
- posthog.capture('task_run_started', {
- conversation_id: props.conversationId,
- trace_id: values.traceId,
- run_id: activeRun?.runId,
- task_id: activeRun?.taskId,
- execution_type: 'sandbox',
- // The run-started frame carries no warmth signal and pre-warming isn't wired
- // yet, so every run is a cold start. A later pre-warm hook flips this.
- cold_start: true,
- })
+ if (method === '_posthog/progress') {
+ const progress = (notification.params ?? {}) as PosthogProgressParams
+ const status = normalizeProgressStatus(progress.status)
+ // A finished step is a milestone (the thread's progress card keeps it), not the current
+ // activity — clear it so the thinking line falls back to the rotating message instead of
+ // sticking on e.g. "Started agent" for the rest of the turn.
+ if (status === 'completed' || status === 'failed') {
+ actions.setCurrentProgress(null)
+ } else {
+ actions.setCurrentProgress(
+ stringifyOptional(progress.label) ?? stringifyOptional(progress.detail) ?? ''
+ )
+ }
+ return
}
- actions.setConversationClearSupported(
- (notification.params as { conversationClear?: unknown } | undefined)?.conversationClear === true
- )
- cache.isBootstrapping = false
- actions.markRunStarted()
- return
- }
- if (method === '_posthog/turn_complete') {
- if (!isReplay) {
- actions.emitTurnCompleteEvent({ streamKey: props.streamKey })
+ // The agent-server persists the permission lifecycle to the run log — pending approvals
+ // are re-derived on bootstrap (a reload mid-approval would otherwise lose the card while
+ // the agent stays blocked), and a resolution observed here clears the local card.
+ if (isPosthogNotification(notification, '_posthog/permission_request')) {
+ const record = parsePermissionRequestFrame(notification.params ?? {}, entry.source_run_id)
+ if (
+ record &&
+ !values.seenPermissionRequestIds.has(record.requestId) &&
+ !values.resolvedPermissionRequestIds.has(record.requestId)
+ ) {
+ actions.routePermissionRequest(record, isReplay)
+ }
+ return
}
- actions.markTurnComplete(isReplay)
- return
- }
- if (method === '_posthog/progress') {
- const progress = (notification.params ?? {}) as PosthogProgressParams
- const status = normalizeProgressStatus(progress.status)
- // A finished step is a milestone (the thread's progress card keeps it), not the current
- // activity — clear it so the thinking line falls back to the rotating message instead of
- // sticking on e.g. "Started agent" for the rest of the turn.
- if (status === 'completed' || status === 'failed') {
- actions.setCurrentProgress(null)
- } else {
- actions.setCurrentProgress(
- stringifyOptional(progress.label) ?? stringifyOptional(progress.detail) ?? ''
- )
+ if (isPosthogNotification(notification, '_posthog/permission_resolved')) {
+ const requestId = notification.params?.requestId
+ if (
+ typeof requestId === 'string' &&
+ requestId &&
+ entry.source_run_id === cache.activeRun?.runId &&
+ entry.source_run_id
+ ) {
+ actions.markPermissionRequestResolved(requestId)
+ }
+ return
}
- return
- }
- // The agent-server persists the permission lifecycle to the run log — pending approvals
- // are re-derived on bootstrap (a reload mid-approval would otherwise lose the card while
- // the agent stays blocked), and a resolution observed here clears the local card.
- if (isPosthogNotification(notification, '_posthog/permission_request')) {
- const record = parsePermissionRequestFrame(notification.params ?? {}, entry.source_run_id)
- if (
- record &&
- !values.seenPermissionRequestIds.has(record.requestId) &&
- !values.resolvedPermissionRequestIds.has(record.requestId)
- ) {
- actions.routePermissionRequest(record, isReplay)
+ // Token usage + cost + context-window breakdown. The numeric used/size aggregate that
+ // drives the percentage ring arrives separately on a session/update (handled below).
+ if (isPosthogNotification(notification, '_posthog/usage_update')) {
+ actions.setContextUsage(foldUsageNotification(values.contextUsage, notification.params ?? {}))
+ return
}
- return
- }
- if (isPosthogNotification(notification, '_posthog/permission_resolved')) {
- const requestId = notification.params?.requestId
- if (
- typeof requestId === 'string' &&
- requestId &&
- entry.source_run_id === cache.activeRun?.runId &&
- entry.source_run_id
- ) {
- actions.markPermissionRequestResolved(requestId)
+ // Diagnostic only — no UI; kept for resume telemetry / crash-affordance work.
+ if (isPosthogNotification(notification, '_posthog/sdk_session')) {
+ const params = notification.params
+ actions.setSdkSession({ sessionId: params?.sessionId, adapter: params?.adapter })
+ return
}
- return
- }
- // Token usage + cost + context-window breakdown. The numeric used/size aggregate that
- // drives the percentage ring arrives separately on a session/update (handled below).
- if (isPosthogNotification(notification, '_posthog/usage_update')) {
- actions.setContextUsage(foldUsageNotification(values.contextUsage, notification.params ?? {}))
- return
- }
- // Diagnostic only — no UI; kept for resume telemetry / crash-affordance work.
- if (isPosthogNotification(notification, '_posthog/sdk_session')) {
- const params = notification.params
- actions.setSdkSession({ sessionId: params?.sessionId, adapter: params?.adapter })
- return
- }
- // History-derived context dedupe: a persisted or echoed user message still carries the
- // context blocks its send was wrapped with; record their rendered lines under the
- // bootstrapped task (the `logs/` replay spans the task's full resume chain), so
- // `pendingContextItems` prunes items the chain already carries even after the in-memory
- // 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 (isPosthogNotification(notification, '_posthog/user_message')) {
- const content = notification.params?.content
- if (Array.isArray(content) && content.length > 0 && content.every(isHiddenUserContent)) {
+ // History-derived context dedupe: a persisted or echoed user message still carries the
+ // context blocks its send was wrapped with; record their rendered lines under the
+ // bootstrapped task (the `logs/` replay spans the task's full resume chain), so
+ // `pendingContextItems` prunes items the chain already carries even after the in-memory
+ // 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 (isPosthogNotification(notification, '_posthog/user_message')) {
+ const content = notification.params?.content
+ if (Array.isArray(content) && content.length > 0 && content.every(isHiddenUserContent)) {
+ return
+ }
+ actions.markTurnStarted()
+ if (values.bootstrappedTaskId) {
+ const lines = contextBlockLinesFromUserMessage(
+ extractUserMessageText(notification.params?.content)
+ )
+ if (lines.length > 0) {
+ actions.markContextLinesSeen(values.bootstrappedTaskId, lines)
+ }
+ }
+ return
+ }
+ if (method?.startsWith('_posthog/')) {
+ // _posthog/error, _posthog/status, _posthog/compact_boundary, _posthog/task_notification
+ // → rendered by the projection. _posthog/console, _posthog/sandbox_output,
+ // other internal events → no UI. No side effect either way.
return
}
- actions.markTurnStarted()
- if (values.bootstrappedTaskId) {
- const lines = contextBlockLinesFromUserMessage(extractUserMessageText(notification.params?.content))
- if (lines.length > 0) {
- actions.markContextLinesSeen(values.bootstrappedTaskId, lines)
+ // The session/new request carries the run's starting permission mode in its meta. Seed the
+ // mode fold from it so mode-aware permission routing (full-auto answering in
+ // `bypassPermissions`) works before any `current_mode_update` arrives — the adapter only
+ // emits those on changes.
+ if (method === 'session/new') {
+ const meta = (notification.params as { _meta?: { permissionMode?: unknown } } | undefined)?._meta
+ if (typeof meta?.permissionMode === 'string' && meta.permissionMode) {
+ actions.setCurrentMode(meta.permissionMode)
}
+ return
}
- return
- }
- if (method?.startsWith('_posthog/')) {
- // _posthog/error, _posthog/status, _posthog/compact_boundary, _posthog/task_notification
- // → rendered by the projection. _posthog/console, _posthog/sandbox_output,
- // other internal events → no UI. No side effect either way.
- return
- }
- // The session/new request carries the run's starting permission mode in its meta. Seed the
- // mode fold from it so mode-aware permission routing (full-auto answering in
- // `bypassPermissions`) works before any `current_mode_update` arrives — the adapter only
- // emits those on changes.
- if (method === 'session/new') {
- const meta = (notification.params as { _meta?: { permissionMode?: unknown } } | undefined)?._meta
- if (typeof meta?.permissionMode === 'string' && meta.permissionMode) {
- actions.setCurrentMode(meta.permissionMode)
+ // session/prompt never renders and the resume-context filter is handled in the projection.
+ if (method === 'session/prompt') {
+ return
}
- return
- }
- // session/prompt never renders and the resume-context filter is handled in the projection.
- if (method === 'session/prompt') {
- return
- }
- if (!isSessionUpdateNotification(notification)) {
- return
- }
- const update = notification.params?.update
- // The numeric used/size usage aggregate is session/update-framed — fold it into the ring.
- if (isSessionUpdateUsage(update)) {
- actions.setContextUsage(foldUsageAggregate(values.contextUsage, update))
- return
- }
- // Wire user turns render only on replay (the projection branches on source). Their one side
- // effect is the same context-line recording as `_posthog/user_message` above — resume
- // chains persist a turn in both wire forms, and the seen-lines reducer dedupes the overlap.
- // Chunked frames are skipped: a partial text could truncate a block mid-line.
- if (isSessionUpdateUserMessage(update)) {
- if (isHiddenUserContent(update.content)) {
+ if (!isSessionUpdateNotification(notification)) {
return
}
- actions.markTurnStarted()
- if (values.bootstrappedTaskId && update.sessionUpdate === 'user_message') {
- const lines = contextBlockLinesFromUserMessage(String(update.content?.text ?? update.text ?? ''))
- if (lines.length > 0) {
- actions.markContextLinesSeen(values.bootstrappedTaskId, lines)
- }
+ const update = notification.params?.update
+ // The numeric used/size usage aggregate is session/update-framed — fold it into the ring.
+ if (isSessionUpdateUsage(update)) {
+ actions.setContextUsage(foldUsageAggregate(values.contextUsage, update))
+ return
}
- return
- }
- if (!isKnownSessionUpdate(update)) {
- return
- }
- // The agent producing output is the only marker of a new turn this client can rely on when the
- // turn was started from outside its own composer. Such a follow-up is queued on the run, which
- // emits no second `run_started`, and neither wire form of the user turn fills the gap: the live
- // stream never carries one, and the persisted one is written when the message is received, so a
- // message sent mid-turn is replayed *before* the previous turn's `turn_complete`. Guarded on
- // `turnComplete` so this costs one dispatch per turn rather than one per streamed chunk.
- if (values.turnComplete && AGENT_GENERATING_SESSION_UPDATES.has(update.sessionUpdate)) {
- actions.markTurnStarted()
- }
- if (update.sessionUpdate === 'current_mode_update') {
- actions.setCurrentMode(String(update.currentModeId ?? update.mode ?? ''))
- return
- }
- if (update.sessionUpdate === 'tool_call') {
- // A fresh tool call — the tracker folded it in above, so resolve its name off the
- // merged invocation and publish a `started` event on the bus.
- if (emitToolStream) {
- const toolCallId = String(update.toolCallId ?? '')
- const invocation = toolCallId ? trackedInvocations.get(toolCallId) : undefined
- if (invocation) {
- actions.emitToolEvent({
- streamKey: props.streamKey,
- toolCallId,
- toolName: resolveToolCall(invocation).resolvedKey,
- rawToolName: invocation.rawToolName,
- phase: 'started',
- invocation,
- source,
- })
+ // Wire user turns render only on replay (the projection branches on source). Their one side
+ // effect is the same context-line recording as `_posthog/user_message` above — resume
+ // chains persist a turn in both wire forms, and the seen-lines reducer dedupes the overlap.
+ // Chunked frames are skipped: a partial text could truncate a block mid-line.
+ if (isSessionUpdateUserMessage(update)) {
+ if (isHiddenUserContent(update.content)) {
+ return
+ }
+ actions.markTurnStarted()
+ if (values.bootstrappedTaskId && update.sessionUpdate === 'user_message') {
+ const lines = contextBlockLinesFromUserMessage(
+ String(update.content?.text ?? update.text ?? '')
+ )
+ if (lines.length > 0) {
+ actions.markContextLinesSeen(values.bootstrappedTaskId, lines)
+ }
}
+ return
}
- return
- }
- if (update.sessionUpdate === 'tool_call_update') {
- // TOOL_CALL_COMPLETED telemetry — emit once when a tool call first transitions to a
- // terminal status. `preToolStatus` (read before the upsert) gates the once-only fire;
- // the resolved key comes from the tracked merged invocation. Suppressed on replay,
- // and skipped when the creating `tool_call` was lost (no pre-status).
- const toolCallId = String(update.toolCallId ?? '')
- if (!toolCallId) {
+ if (!isKnownSessionUpdate(update)) {
return
}
- const status = mapAcpStatus(update.status ?? preToolStatus)
- if (
- !isReplay &&
- preToolStatus !== undefined &&
- preToolStatus !== 'completed' &&
- preToolStatus !== 'failed' &&
- (status === 'completed' || status === 'failed')
- ) {
- const invocation = trackedInvocations.get(toolCallId)
- const startedAt = cache.turnStartedAtMs as number | undefined
- posthog.capture('tool_call_completed', {
- conversation_id: props.conversationId,
- trace_id: values.traceId,
- tool_call_id: toolCallId,
- tool_qualified_name: invocation ? resolveToolCall(invocation).resolvedKey : undefined,
- status,
- duration_ms: startedAt !== undefined ? Date.now() - startedAt : undefined,
- execution_type: 'sandbox',
- })
+ // The agent producing output is the only marker of a new turn this client can rely on when the
+ // turn was started from outside its own composer. Such a follow-up is queued on the run, which
+ // emits no second `run_started`, and neither wire form of the user turn fills the gap: the live
+ // stream never carries one, and the persisted one is written when the message is received, so a
+ // message sent mid-turn is replayed *before* the previous turn's `turn_complete`. Guarded on
+ // `turnComplete` so this costs one dispatch per turn rather than one per streamed chunk.
+ if (values.turnComplete && AGENT_GENERATING_SESSION_UPDATES.has(update.sessionUpdate)) {
+ actions.markTurnStarted()
+ }
+ if (update.sessionUpdate === 'current_mode_update') {
+ actions.setCurrentMode(String(update.currentModeId ?? update.mode ?? ''))
+ return
+ }
+ if (update.sessionUpdate === 'tool_call') {
+ // A fresh tool call — the tracker folded it in above, so resolve its name off the
+ // merged invocation and publish a `started` event on the bus.
+ if (emitToolStream) {
+ const toolCallId = String(update.toolCallId ?? '')
+ const invocation = toolCallId ? trackedInvocations.get(toolCallId) : undefined
+ if (invocation) {
+ actions.emitToolEvent({
+ streamKey: props.streamKey,
+ toolCallId,
+ toolName: resolveToolCall(invocation).resolvedKey,
+ rawToolName: invocation.rawToolName,
+ phase: 'started',
+ invocation,
+ source,
+ })
+ }
+ }
+ return
}
- // Tool-stream event: phase from the pre-fold status → new status transition. A crossing
- // into a terminal status is `completed`/`failed`; any other update is `updated`.
- if (emitToolStream) {
- const invocation = trackedInvocations.get(toolCallId)
- if (invocation) {
- const wasTerminal = preToolStatus === 'completed' || preToolStatus === 'failed'
- const phase: ToolStreamPhase =
- !wasTerminal && status === 'completed'
- ? 'completed'
- : !wasTerminal && status === 'failed'
- ? 'failed'
- : 'updated'
- actions.emitToolEvent({
- streamKey: props.streamKey,
- toolCallId,
- toolName: resolveToolCall(invocation).resolvedKey,
- rawToolName: invocation.rawToolName,
- phase,
- invocation,
- source,
+ if (update.sessionUpdate === 'tool_call_update') {
+ // TOOL_CALL_COMPLETED telemetry — emit once when a tool call first transitions to a
+ // terminal status. `preToolStatus` (read before the upsert) gates the once-only fire;
+ // the resolved key comes from the tracked merged invocation. Suppressed on replay,
+ // and skipped when the creating `tool_call` was lost (no pre-status).
+ const toolCallId = String(update.toolCallId ?? '')
+ if (!toolCallId) {
+ return
+ }
+ const status = mapAcpStatus(update.status ?? preToolStatus)
+ if (
+ !isReplay &&
+ preToolStatus !== undefined &&
+ preToolStatus !== 'completed' &&
+ preToolStatus !== 'failed' &&
+ (status === 'completed' || status === 'failed')
+ ) {
+ const invocation = trackedInvocations.get(toolCallId)
+ const startedAt = cache.turnStartedAtMs as number | undefined
+ posthog.capture('tool_call_completed', {
+ conversation_id: props.conversationId,
+ trace_id: values.traceId,
+ tool_call_id: toolCallId,
+ tool_qualified_name: invocation ? resolveToolCall(invocation).resolvedKey : undefined,
+ status,
+ duration_ms: startedAt !== undefined ? Date.now() - startedAt : undefined,
+ execution_type: 'sandbox',
})
}
+ // Tool-stream event: phase from the pre-fold status → new status transition. A crossing
+ // into a terminal status is `completed`/`failed`; any other update is `updated`.
+ if (emitToolStream) {
+ const invocation = trackedInvocations.get(toolCallId)
+ if (invocation) {
+ const wasTerminal = preToolStatus === 'completed' || preToolStatus === 'failed'
+ const phase: ToolStreamPhase =
+ !wasTerminal && status === 'completed'
+ ? 'completed'
+ : !wasTerminal && status === 'failed'
+ ? 'failed'
+ : 'updated'
+ actions.emitToolEvent({
+ streamKey: props.streamKey,
+ toolCallId,
+ toolName: resolveToolCall(invocation).resolvedKey,
+ rawToolName: invocation.rawToolName,
+ phase,
+ invocation,
+ source,
+ })
+ }
+ }
+ return
}
- return
- }
- // agent_message_chunk / agent_message / agent_thought_chunk → projection only.
- },
- })),
+ // agent_message_chunk / agent_message / agent_thought_chunk → projection only.
+ },
+ }
+ }),
])
diff --git a/products/posthog_ai/frontend/logics/runStreamRecovery.ts b/products/posthog_ai/frontend/logics/runStreamRecovery.ts
new file mode 100644
index 000000000000..d12e998a7515
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/runStreamRecovery.ts
@@ -0,0 +1,130 @@
+import type { DisposablesManager } from 'kea-disposables'
+
+import type { StoredLogEntry } from '../types/wireTypes'
+
+export type RecoveryPhase = 'bootstrap' | 'stream' | 'history' | 'finalization'
+
+export const STREAM_REQUEST_TIMEOUT_MS = 30_000
+export const STREAM_HISTORY_TIMEOUT_MS = 60_000
+export const STREAM_IDLE_TIMEOUT_MS = 60_000
+
+export function isTransientStreamError(error: { status?: number; retryable?: boolean }): boolean {
+ return (
+ error.retryable !== false &&
+ (error.status === undefined ||
+ error.status === 0 ||
+ error.status === 408 ||
+ error.status === 429 ||
+ (error.status >= 500 && error.status < 600))
+ )
+}
+
+export class RunStreamRecovery {
+ readonly controller = new AbortController()
+ phase: RecoveryPhase = 'bootstrap'
+ paused = false
+ buffering = true
+ buffer: StoredLogEntry[] = []
+ readonly legacyBacklog = new Map<string, StoredLogEntry>()
+ receivedCursor?: string
+ committedCursor?: string
+ receivedBacklogRunId?: string
+ committedBacklogRunId?: string
+ private resourceId = 0
+
+ constructor(
+ readonly projectId: number,
+ readonly taskId: string,
+ readonly runId: string,
+ readonly generation: number,
+ private readonly disposables: DisposablesManager,
+ private readonly isCurrent: () => boolean
+ ) {
+ disposables.add(() => () => this.controller.abort(), 'stream-session', { pauseOnPageHidden: false })
+ }
+
+ owns(): boolean {
+ return !this.controller.signal.aborted && !this.disposables.isDisposed && this.isCurrent()
+ }
+
+ check(): void {
+ if (!this.owns()) {
+ throw new DOMException('Recovery canceled', 'AbortError')
+ }
+ }
+
+ async request<T>(
+ timeoutMs: number,
+ request: (signal: AbortSignal) => Promise<T>,
+ parent: AbortSignal = this.controller.signal
+ ): Promise<T> {
+ this.check()
+ const key = `stream-request-${this.generation}-${this.resourceId++}`
+ const controller = new AbortController()
+ let settled = false
+ try {
+ const result = await new Promise<T>((resolve, reject) => {
+ const cancel = (): void => {
+ controller.abort()
+ reject(new DOMException('Recovery canceled', 'AbortError'))
+ }
+ this.disposables.add(
+ () => {
+ const timer = setTimeout(() => {
+ reject(new DOMException('Agent request timed out', 'TimeoutError'))
+ controller.abort()
+ }, timeoutMs)
+ parent.addEventListener('abort', cancel, { once: true })
+ this.controller.signal.addEventListener('abort', cancel, { once: true })
+ if (parent.aborted) {
+ cancel()
+ } else {
+ request(controller.signal).then(resolve, reject)
+ }
+ return () => {
+ clearTimeout(timer)
+ parent.removeEventListener('abort', cancel)
+ this.controller.signal.removeEventListener('abort', cancel)
+ if (!settled) {
+ cancel()
+ }
+ }
+ },
+ key,
+ { pauseOnPageHidden: false }
+ )
+ })
+ this.check()
+ return result
+ } finally {
+ settled = true
+ this.disposables.dispose(key)
+ }
+ }
+
+ async wait(delayMs: number): Promise<void> {
+ this.check()
+ const key = `stream-delay-${this.generation}-${this.resourceId++}`
+ try {
+ await new Promise<void>((resolve, reject) => {
+ const cancel = (): void => reject(new DOMException('Recovery canceled', 'AbortError'))
+ this.disposables.add(
+ () => {
+ const timer = setTimeout(resolve, delayMs)
+ this.controller.signal.addEventListener('abort', cancel, { once: true })
+ return () => {
+ clearTimeout(timer)
+ this.controller.signal.removeEventListener('abort', cancel)
+ cancel()
+ }
+ },
+ key,
+ { pauseOnPageHidden: false }
+ )
+ })
+ this.check()
+ } finally {
+ this.disposables.dispose(key)
+ }
+ }
+}
diff --git a/products/posthog_ai/frontend/types/streamTypes.ts b/products/posthog_ai/frontend/types/streamTypes.ts
index eee3ce2c3eb4..089051b6f49c 100644
--- a/products/posthog_ai/frontend/types/streamTypes.ts
+++ b/products/posthog_ai/frontend/types/streamTypes.ts
@@ -39,6 +39,7 @@ export type RunAlertKind =
*/
export interface RunConnectionState {
kind: RunAlertKind
+ retryable?: boolean
/** `reconnecting`: current 1-based reconnect attempt. */
attempt?: number
/** `reconnecting`: max attempts before the connection is given up. */