:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(phai): route sandbox agent logs through the agent-proxy (#65726)
Georgiy Tarasovefc01eec1468
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 15e40d2a3b1e..d138a9cfa487 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -5358,13 +5358,38 @@ const api = {async openStream(taskId: Task['id'],runId: TaskRun['id'],- options: { signal: AbortSignal; lastEventId?: string; startLatest?: boolean }+ options: {+ signal: AbortSignal+ lastEventId?: string+ startLatest?: boolean+ /**+ * When set, read the stream from the standalone agent-proxy instead of the Django+ * endpoint. `baseUrl` is the proxy origin the server resolved via `stream_token`,+ * and the run-scoped `token` is sent as a Bearer header. Absent ⇒ the same-origin+ * Django stream (session auth) — the pre-proxy behavior.+ */+ proxyTarget?: { baseUrl: string; token: string }+ }): Promise<Response> {const headers: Record<string, string> = {}- let request = new ApiRequest().taskRun(taskId, runId).withAction('stream')if (options.lastEventId) {headers['Last-Event-ID'] = options.lastEventId- } else if (options.startLatest) {+ }+ if (options.proxyTarget) {+ // Absolute proxy URL with a run-scoped Bearer token — `ApiRequest` only builds+ // Django-relative paths, so assemble the proxy URL directly. `start=latest` applies+ // only on a first connect (no resume cursor); the Last-Event-ID header, when+ // present, takes precedence and an exact resume ignores `start`.+ const base = options.proxyTarget.baseUrl.replace(/\/+$/, '')+ const url =+ !options.lastEventId && options.startLatest+ ? `${base}/v1/runs/${runId}/stream?start=latest`+ : `${base}/v1/runs/${runId}/stream`+ headers['Authorization'] = `Bearer ${options.proxyTarget.token}`+ return api.getResponse(url, { signal: options.signal, headers })+ }+ let request = new ApiRequest().taskRun(taskId, runId).withAction('stream')+ if (!options.lastEventId && options.startLatest) {request = request.withQueryString({ start: 'latest' })}return request.getResponse({ signal: options.signal, headers })diff --git a/products/posthog_ai/frontend/sandbox/sandboxStreamLogic.test.ts b/products/posthog_ai/frontend/sandbox/sandboxStreamLogic.test.tsindex 764f8f409445..2b1766256dec 100644--- a/products/posthog_ai/frontend/sandbox/sandboxStreamLogic.test.ts+++ b/products/posthog_ai/frontend/sandbox/sandboxStreamLogic.test.ts@@ -2,12 +2,14 @@ import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { projectLogic } from 'scenes/projectLogic'import { initKeaTests } from '~/test/init'-import { tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'+import { tasksRunsCommandCreate, tasksRunsStreamTokenRetrieve } from 'products/tasks/frontend/generated/api'import {extractRunArtifacts,@@ -18,6 +20,7 @@ import {mergeRunArtifacts,parsePermissionRequestFrame,reconnectDelayMs,+ resolveSandboxStreamTarget,sandboxStreamLogic,SSE_HEALTHY_CONNECTION_MS,SSE_RECONNECT_BASE_DELAY_MS,@@ -27,6 +30,7 @@ import type { PermissionRequestFrame, StoredLogEntry } from './types/sandboxWirejest.mock('products/tasks/frontend/generated/api', () => ({tasksRunsCommandCreate: jest.fn(),+ tasksRunsStreamTokenRetrieve: jest.fn(),}))function notification(method: string, params: Record<string, unknown>): StoredLogEntry {@@ -56,13 +60,20 @@ type ReaderResult = { done: false; value: Uint8Array } | { done: true; value: un* SSE-encoded frames; each `emit*` resolves the logic's pending `reader.read()` and drains the* microtask queue so the dispatched actions have settled before the test asserts.*/+interface MockStreamOptions {+ signal: AbortSignal+ lastEventId?: string+ startLatest?: boolean+ proxyTarget?: { baseUrl: string; token: string }+}+class MockStreamConnection {- readonly options: { signal: AbortSignal; lastEventId?: string; startLatest?: boolean }+ readonly options: MockStreamOptionsprivate pendingRead: ((r: ReaderResult) => void) | null = nullprivate queued: ReaderResult[] = []private encoder = new TextEncoder()- constructor(options: { signal: AbortSignal; lastEventId?: string; startLatest?: boolean }) {+ constructor(options: MockStreamOptions) {this.options = options// Teardown (dispose 'event-source') aborts the signal — unblock any pending read so the// logic's loop sees `done`/`aborted` and exits without scheduling a reconnect.@@ -131,6 +142,17 @@ class MockStreamConnection {await flushPromises()}+ /** Emit the durable `event: stream-end` end-of-run sentinel, then close the body. */+ async emitStreamEnd(): Promise<void> {+ this.deliver({+ done: false,+ value: this.encodeFrame({ data: JSON.stringify({ status: 'complete' }), event: 'stream-end' }),+ })+ await flushPromises()+ this.deliver({ done: true, value: undefined })+ await flushPromises()+ }+/** Server cleanly closes the stream body → the logic treats it as a drop. */async emitClose(): Promise<void> {this.deliver({ done: true, value: undefined })@@ -164,6 +186,9 @@ describe('sandboxStreamLogic', () => {beforeEach(() => {initKeaTests()+ // The logic mirrors the live resume cursor to sessionStorage — clear it so a cursor written+ // by one test can't seed another test's reconnect.+ window.sessionStorage.clear()MockStream.reset()MockStream.install()projectLogic.mount()@@ -2662,6 +2687,9 @@ describe('sandboxStreamLogic', () => {it('auto-approves a non-destructive PostHog exec without showing a card', async () => {const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ // Resolving the proxy stream target mints a token before `openStream`, so the connection+ // registers a microtask later — flush before grabbing it.+ await flushPromises()const source = MockStream.latest()await source.emitMessage({@@ -2687,6 +2715,7 @@ describe('sandboxStreamLogic', () => {it('auto-approves a built-in tool without showing a card', async () => {logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()const source = MockStream.latest()await source.emitMessage({@@ -2886,6 +2915,102 @@ describe('sandboxStreamLogic', () => {expect(logic.values.pendingPermissionRequest).toBeNull()})})++ describe('agent-proxy stream routing', () => {+ const enableProxy = (): void =>+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY], {+ [FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY]: true,+ })++ beforeEach(() => {+ ;(tasksRunsStreamTokenRetrieve as jest.Mock).mockReset()+ })++ describe('resolveSandboxStreamTarget', () => {+ it('skips the token mint and streams from Django when the rollout is off', async () => {+ expect(await resolveSandboxStreamTarget('997', 'task-1', 'run-1', false)).toBeNull()+ expect(tasksRunsStreamTokenRetrieve).not.toHaveBeenCalled()+ })++ it('routes to the proxy when the server resolves a base URL', async () => {+ ;(tasksRunsStreamTokenRetrieve as jest.Mock).mockResolvedValue({+ token: 'tok-1',+ stream_base_url: 'https://proxy.example/',+ })+ expect(await resolveSandboxStreamTarget('997', 'task-1', 'run-1', true)).toEqual({+ baseUrl: 'https://proxy.example/',+ token: 'tok-1',+ })+ })++ it('falls back to Django when the server resolves no base URL', async () => {+ ;(tasksRunsStreamTokenRetrieve as jest.Mock).mockResolvedValue({+ token: 'tok-1',+ stream_base_url: null,+ })+ expect(await resolveSandboxStreamTarget('997', 'task-1', 'run-1', true)).toBeNull()+ })++ it('falls back to Django when minting the token throws', async () => {+ ;(tasksRunsStreamTokenRetrieve as jest.Mock).mockRejectedValue(new Error('forbidden'))+ expect(await resolveSandboxStreamTarget('997', 'task-1', 'run-1', true)).toBeNull()+ })+ })++ it('passes the resolved proxy target to openStream when the rollout is on', async () => {+ enableProxy()+ ;(tasksRunsStreamTokenRetrieve as jest.Mock).mockResolvedValue({+ token: 'tok-1',+ stream_base_url: 'https://proxy.example',+ })++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledWith('997', 'task-1', 'run-1')+ expect(MockStream.latest().options.proxyTarget).toEqual({+ baseUrl: 'https://proxy.example',+ token: 'tok-1',+ })+ })++ it('re-mints the read token and retries once on a 401 from the proxy leg', async () => {+ enableProxy()+ ;(tasksRunsStreamTokenRetrieve as jest.Mock).mockResolvedValue({+ token: 'tok-1',+ stream_base_url: 'https://proxy.example',+ })+ // The first open fails with an expired-token 401; the retry must mint a fresh token+ // rather than surface an auth error.+ ;(api.tasks.runs.openStream as jest.Mock).mockRejectedValueOnce({ status: 401 })++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ expect((tasksRunsStreamTokenRetrieve as jest.Mock).mock.calls.length).toBeGreaterThanOrEqual(2)+ expect(logic.values.sseStatus).toEqual('open')+ })++ 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)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()+ const source = MockStream.latest()+ // A live frame seeds the persisted resume cursor.+ await source.emitMessage(notification('_posthog/run_started', {}), '1700-5')+ expect(window.sessionStorage.getItem('posthog-ai:stream-resume:run-1')).toEqual('1700-5')++ const connectionsBefore = MockStream.connections.length+ await source.emitStreamEnd()++ // The sentinel finalizes via a status refetch — no reconnect, and the cursor is dropped so+ // a reload can't try to resume a finished run.+ expect(logic.values.currentRunStatus).toEqual('completed')+ expect(MockStream.connections.length).toEqual(connectionsBefore)+ expect(window.sessionStorage.getItem('posthog-ai:stream-resume:run-1')).toBeNull()+ })+ })})// Drain queued microtasks (chained `await`s in async listeners) without relying on timers, so itdiff --git a/products/posthog_ai/frontend/sandbox/sandboxStreamLogic.ts b/products/posthog_ai/frontend/sandbox/sandboxStreamLogic.tsindex 585dc798b5a7..7f2a3d0b02e8 100644--- a/products/posthog_ai/frontend/sandbox/sandboxStreamLogic.ts+++ b/products/posthog_ai/frontend/sandbox/sandboxStreamLogic.ts@@ -3,10 +3,13 @@ import { actions, connect, kea, key, listeners, path, props, reducers, selectorsimport posthog from 'posthog-js'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { projectLogic } from 'scenes/projectLogic'-import { tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'+import { tasksRunsCommandCreate, tasksRunsStreamTokenRetrieve } from 'products/tasks/frontend/generated/api'import type { TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'import { parseSandboxQuestions } from './sandboxQuestionUtils'@@ -82,6 +85,76 @@ export const SANDBOX_INITIAL_PERMISSION_MODE: TaskRunBootstrapCreateRequestIniti/** The crash-error string the in-sandbox agent server writes on a fatal exception. */const AGENT_CRASH_PREFIX = 'Agent server crashed'+/**+ * In-band durable end-of-run sentinel emitted by both the Django stream view and the agent-proxy+ * (`event: stream-end`, `data: {"status":"complete"}`). Distinct from the rotation `end` event (a+ * 15-min connection recycle that means "reconnect"): the sentinel means the run is finished, so the+ * client stops reconnecting and drops its resume cursor instead of resuming.+ */+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.+ */+function sandboxStreamResumeKey(runId: string): string {+ return `posthog-ai:stream-resume:${runId}`+}+function readSandboxStreamResumeId(runId: string): string | null {+ try {+ return window.sessionStorage.getItem(sandboxStreamResumeKey(runId))+ } catch {+ return null+ }+}+function writeSandboxStreamResumeId(runId: string, eventId: string): void {+ try {+ window.sessionStorage.setItem(sandboxStreamResumeKey(runId), eventId)+ } catch {+ // sessionStorage may be unavailable (private mode / quota) — resume from in-memory state only.+ }+}+function clearSandboxStreamResumeId(runId: string): void {+ try {+ window.sessionStorage.removeItem(sandboxStreamResumeKey(runId))+ } catch {+ // ignore+ }+}++/** Resolved live-stream destination: the agent-proxy origin plus the run-scoped read token. */+export interface SandboxStreamProxyTarget {+ baseUrl: string+ token: string+}++/**+ * Resolve the proxy target for a run, or null to stream from Django. Purely additive: with the+ * rollout flag off we skip the token mint entirely (pre-proxy behavior); with it on but the server+ * resolves no base URL — or the mint throws — we fall back to Django so streaming never breaks.+ */+export async function resolveSandboxStreamTarget(+ projectId: string,+ taskId: string,+ runId: string,+ viaProxy: boolean+): Promise<SandboxStreamProxyTarget | null> {+ if (!viaProxy) {+ return null+ }+ try {+ const { token, stream_base_url } = await tasksRunsStreamTokenRetrieve(projectId, taskId, runId)+ if (!stream_base_url) {+ return null+ }+ return { baseUrl: stream_base_url, token }+ } catch {+ return null+ }+}+const TERMINAL_RUN_STATUSES: ReadonlySet<string> = new Set(['completed', 'failed', 'cancelled'])export function isTerminalRunStatus(status: string | null | undefined): boolean {@@ -963,7 +1036,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([key((props) => (props.replayOnly ? `replay:${props.streamKey}` : props.streamKey)),path((key) => ['products', 'posthog_ai', 'sandbox', 'sandboxStreamLogic', key]),connect(() => ({- values: [projectLogic, ['currentProjectId']],+ values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags'], preflightLogic, ['preflight']],})),actions({/**@@ -984,6 +1057,12 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([sseReconnecting: (attempt: number) => ({ attempt }),/** Internal: an SSE drop initiates the refetch + backoff loop. */sseDropped: true,+ /**+ * Internal: the in-band `stream-end` sentinel landed — the run's event stream is finished.+ * Tears the connection down without reconnecting and finalizes the run status (a safety net+ * for a stream that ended without a preceding terminal `task_run_state` frame).+ */+ streamEnded: true,/*** Frame ingestion — appends one frame to the log and runs its one-shot side effects* (telemetry, permission routing, value folds). Called by the live SSE listener@@ -1378,6 +1457,17 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([(s) => [s.runArtifacts],(runArtifacts): boolean => !!runArtifacts.prUrl || !!runArtifacts.branch,],+ /**+ * Gates routing the live stream through the standalone agent-proxy (the durable-streaming+ * rollout). Local dev disables the analytics SDK, so DEBUG instances opt in unconditionally —+ * the server still owns the final proxy-vs-Django decision via `stream_token` (no base URL+ * ⇒ Django), so opting in here is safe even where the proxy isn't deployed.+ */+ streamViaProxyEnabled: [+ (s) => [s.featureFlags, s.preflight],+ (featureFlags, preflight): boolean =>+ !!featureFlags[FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY] || !!preflight?.is_debug,+ ],}),listeners(({ values, actions, cache, props }) => ({bootstrapRun: async ({ taskId, runId, justCreatedRun }, breakpoint) => {@@ -1433,6 +1523,10 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// gap between bootstrap and the first connection/run_started. Cleared on the first// `sseOpened`/`_posthog/run_started`.cache.isBootstrapping = true+ // Fresh run: clear the durable-stream end sentinel and the proxy re-mint budget so a+ // reopened conversation starts clean.+ cache.streamEnded = false+ cache.streamTokenRefreshes = 0// Fresh-run fast path: nothing historical to assemble — stream from the top, with nothing// to buffer or drain.@@ -1532,8 +1626,21 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([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.+ // 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+ writeSandboxStreamResumeId(runId, id)+ }+ 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+ clearSandboxStreamResumeId(runId)+ actions.streamEnded()+ return}if (event === 'error') {// Named error envelope — surface verbatim. Real backend frames carry only `error`,@@ -1604,12 +1711,32 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// 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 resolveSandboxStreamTarget(String(projectId), taskId, runId, true)+ : null+ if (signal.aborted) {+ return+ }+ // Resume cursor: prefer the in-memory id stamped by the reader; fall back to the+ // persisted sessionStorage cursor only outside the bootstrap seam window+ // (`bufferingLiveFrames`). The connect-first bootstrap deliberately streams+ // `start=latest` and reconciles the S3 history seam, so a persisted cursor must never+ // pre-empt it — only a live reconnect that lost its in-memory cursor honors it.+ const lastEventId =+ (cache.lastEventId as string | undefined) ??+ (cache.bufferingLiveFrames ? undefined : (readSandboxStreamResumeId(runId) ?? undefined))+let response: Responsetry {response = await api.tasks.runs.openStream(taskId, runId, {signal,- lastEventId: cache.lastEventId as string | undefined,+ lastEventId,startLatest,+ ...(proxyTarget ? { proxyTarget } : {}),})} catch (error) {if (signal.aborted) {@@ -1620,6 +1747,19 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// 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_SSE_RECONNECT_ATTEMPTS+ ) {+ cache.streamTokenRefreshes = ((cache.streamTokenRefreshes as number | undefined) ?? 0) + 1+ return streamRun(signal)+ }const mapped = status !== undefined ? mapHttpStatusToStreamError(status) : undefinedif (mapped && !mapped.retryable) {actions.handleStreamError(mapped)@@ -1651,14 +1791,15 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([}}} catch {- if (!signal.aborted) {+ if (!signal.aborted && !cache.streamEnded) {actions.sseDropped()}return}- // Clean EOF: the server closed the stream. A terminal frame would already have torn- // us down (dispose → abort); otherwise this is a drop, so refetch status and decide.- if (!signal.aborted) {+ // 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()}}@@ -1687,6 +1828,9 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// 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@@ -1760,6 +1904,34 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([{ 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 SandboxRunStatus })+ }+ },routePermissionRequest: ({ record, replayedFromHistory }) => {// Replayed history is a read-only restore — never auto-approve (the run may be terminal).if (!replayedFromHistory && defaultPermissionDecision(record) === 'auto_allow') {@@ -1880,6 +2052,13 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([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) {+ clearSandboxStreamResumeId(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.@@ -1948,6 +2127,8 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([cache.bufferingLiveFrames = falsecache.bufferedLiveFrames = undefinedcache.sseConnectedAtMs = undefined+ cache.streamEnded = false+ cache.streamTokenRefreshes = 0// Drop the resume cursor so the next bootstrap opens fresh (start=latest) instead of// resuming a prior run's stream.cache.lastEventId = undefined