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(onboarding): reconnect wizard sync SSE streams after fatal closes (#74034)

Fernando Gomes0e3331db2c60
diff --git a/frontend/src/lib/wizard-sync/eventSource.mock.ts b/frontend/src/lib/wizard-sync/eventSource.mock.ts
new file mode 100644
index 000000000000..37c65567e691
--- /dev/null
+++ b/frontend/src/lib/wizard-sync/eventSource.mock.ts
@@ -0,0 +1,100 @@
+/**
+ * A driveable EventSource stand-in for tests. jsdom ships no EventSource at all, and the wizard sync
+ * transports need one a test can step frame by frame: open, data frames, named events (`stream-end`,
+ * the server's `error` payload) and browser transport failures, which differ only by readyState.
+ *
+ * Handlers registered both ways are invoked, since the transports use `onmessage`/`onerror`
+ * assignment for data and `addEventListener` for named events.
+ */
+export class MockEventSource {
+ static readonly CONNECTING = 0
+ static readonly OPEN = 1
+ static readonly CLOSED = 2
+
+ /** Every source opened since the last `reset()`, in order — the count is how many connects happened. */
+ static instances: MockEventSource[] = []
+
+ readyState: number = MockEventSource.CONNECTING
+ onopen: ((event: Event) => void) | null = null
+ onmessage: ((event: MessageEvent) => void) | null = null
+ onerror: ((event: Event) => void) | null = null
+
+ private listeners = new Map<string, ((event: Event) => void)[]>()
+
+ constructor(readonly url: string) {
+ MockEventSource.instances.push(this)
+ }
+
+ static reset(): void {
+ MockEventSource.instances = []
+ }
+
+ static last(): MockEventSource {
+ const source = MockEventSource.instances[MockEventSource.instances.length - 1]
+ if (!source) {
+ throw new Error('No EventSource was opened')
+ }
+ return source
+ }
+
+ addEventListener(name: string, handler: (event: Event) => void): void {
+ this.listeners.set(name, [...(this.listeners.get(name) ?? []), handler])
+ }
+
+ removeEventListener(name: string, handler: (event: Event) => void): void {
+ this.listeners.set(
+ name,
+ (this.listeners.get(name) ?? []).filter((h) => h !== handler)
+ )
+ }
+
+ close(): void {
+ this.readyState = MockEventSource.CLOSED
+ }
+
+ emitOpen(): void {
+ this.readyState = MockEventSource.OPEN
+ const event = new Event('open')
+ this.onopen?.(event)
+ this.dispatch('open', event)
+ }
+
+ /** An unnamed data frame, the shape both transports read run/session state from. */
+ emitMessage(data: string): void {
+ const event = new MessageEvent('message', { data })
+ this.onmessage?.(event)
+ this.dispatch('message', event)
+ }
+
+ /** A named event. With `data` it is a MessageEvent, which is what tells a server-sent
+ * `error` apart from a transport failure. */
+ emitNamed(name: string, data?: string): void {
+ const event = data === undefined ? new Event(name) : new MessageEvent(name, { data })
+ if (name === 'error') {
+ this.onerror?.(event)
+ }
+ this.dispatch(name, event)
+ }
+
+ /** A browser transport failure. CLOSED means the browser gave up and will not retry on its own. */
+ emitTransportError(readyState: number = MockEventSource.CLOSED): void {
+ this.readyState = readyState
+ this.emitNamed('error')
+ }
+
+ private dispatch(name: string, event: Event): void {
+ for (const handler of this.listeners.get(name) ?? []) {
+ handler(event)
+ }
+ }
+}
+
+/** Swap the global in for a test. Returns the restore function. */
+export function installMockEventSource(): () => void {
+ const original = (global as any).EventSource
+ MockEventSource.reset()
+ ;(global as any).EventSource = MockEventSource
+ return () => {
+ ;(global as any).EventSource = original
+ }
+}
diff --git a/frontend/src/lib/wizard-sync/pollLoop.ts b/frontend/src/lib/wizard-sync/pollLoop.ts
index 9681e3e31815..5dd9fd25e387 100644
--- a/frontend/src/lib/wizard-sync/pollLoop.ts
+++ b/frontend/src/lib/wizard-sync/pollLoop.ts
@@ -41,6 +41,22 @@ export function isPermanentPollError(error: unknown): boolean {
return error instanceof ApiError && [401, 403, 404, 410].includes(error.status ?? 0)
}
+// A native EventSource only auto-reconnects after a cleanly dropped connection. Any non-200 response
+// on a (re)connect leaves it CLOSED for good, and posthog/api/streaming.py requires SSE consumers to
+// schedule their own reconnect from onerror. Consecutive attempts back off exponentially from the
+// base to the cap, with the same jitter as poll ticks so clients dropped together (a deploy, an
+// admission-control rejection wave) do not reconnect in lockstep.
+export const SSE_RECONNECT_BASE_MS = 2_000
+export const SSE_RECONNECT_MAX_MS = 30_000
+
+// Delay before reconnect attempt `attempt` (1-based count of consecutive failures since the last
+// successful open). Non-positive attempts are treated as the first.
+export function sseReconnectDelayMs(attempt: number, random: () => number = Math.random): number {
+ const exponent = Math.max(0, attempt - 1)
+ const baseMs = Math.min(SSE_RECONNECT_BASE_MS * 2 ** exponent, SSE_RECONNECT_MAX_MS)
+ return jitteredIntervalMs(baseMs, random)
+}
+
export type PollTickOutcome = 'ok' | 'empty' | 'terminal'
export interface PollLoopOptions {
diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.test.ts
index 1784633d8531..08e513c1d3df 100644
--- a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.test.ts
+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.test.ts
@@ -1,13 +1,26 @@
+import { MOCK_TEAM_ID } from 'lib/api.mock'
+import { installMockEventSource, MockEventSource } from 'lib/wizard-sync/eventSource.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
import {
DEFAULT_POLLING_INTERVAL_SECS,
jitteredIntervalMs,
MAX_POLLING_INTERVAL_SECS,
POLL_JITTER_RATIO,
resolvePollingIntervalMs,
+ SSE_RECONNECT_BASE_MS,
+ SSE_RECONNECT_MAX_MS,
+ sseReconnectDelayMs,
} from 'lib/wizard-sync/pollLoop'
+import { projectLogic } from 'scenes/projectLogic'
+
+import { initKeaTests } from '~/test/init'
+import { tasksActiveWizardRunRetrieve } from 'products/tasks/frontend/generated/api'
import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'
+import { activeCloudRunLogic } from './activeCloudRunLogic'
import {
cloudRunCompletionReport,
mergeProgressStep,
@@ -15,9 +28,19 @@ import {
TaskRunProgressStep,
taskRunDetailToStreamState,
taskRunPrUrl,
+ taskRunStreamLogic,
TaskRunStreamState,
} from './taskRunStreamLogic'
+jest.mock('products/tasks/frontend/generated/api', () => ({
+ getTasksRunsStreamRetrieveUrl: jest.fn(() => '/mock-run-stream'),
+ tasksRunsRetrieve: jest.fn(),
+ tasksActiveWizardRunRetrieve: jest.fn(),
+ tasksRunsCancelCreate: jest.fn(),
+}))
+
+const mockActiveWizardRun = tasksActiveWizardRunRetrieve as jest.Mock
+
function step(overrides: Partial<TaskRunProgressStep> = {}): TaskRunProgressStep {
return {
step: 'clone',
@@ -186,6 +209,25 @@ describe('taskRunStreamLogic helpers', () => {
})
})
+ describe('sseReconnectDelayMs', () => {
+ // A CLOSED EventSource never retries natively, so these delays are the only thing standing
+ // between a dropped stream and a permanently dead run card.
+ it.each([
+ ['the first attempt starts at the base', 1, SSE_RECONNECT_BASE_MS],
+ ['a zero attempt is treated as the first', 0, SSE_RECONNECT_BASE_MS],
+ ['consecutive attempts back off exponentially', 3, SSE_RECONNECT_BASE_MS * 4],
+ ['the backoff caps at the ceiling', 10, SSE_RECONNECT_MAX_MS],
+ ])('%s', (_name, attempt, expectedMs) => {
+ // Mid-roll jitter resolves to the un-jittered delay.
+ expect(sseReconnectDelayMs(attempt, () => 0.5)).toBe(expectedMs)
+ })
+
+ it('jitters the delay so dropped clients do not reconnect in lockstep', () => {
+ expect(sseReconnectDelayMs(1, () => 0)).toBe(SSE_RECONNECT_BASE_MS * (1 - POLL_JITTER_RATIO))
+ expect(sseReconnectDelayMs(1, () => 1)).toBe(SSE_RECONNECT_BASE_MS * (1 + POLL_JITTER_RATIO))
+ })
+ })
+
describe('jitteredIntervalMs', () => {
it.each([
['the lower jitter bound', 0, 3000 * (1 - POLL_JITTER_RATIO)],
@@ -347,3 +389,109 @@ describe('taskRunStreamLogic helpers', () => {
})
})
})
+
+// The first backoff step is 2s ±20%, so this window always contains the retry and never the second
+// step's (4s -20% = 3.2s).
+const PAST_FIRST_RECONNECT_MS = 2600
+const RUN_STARTED_AT = '2026-01-01T00:00:00Z'
+
+describe('taskRunStreamLogic transport', () => {
+ let logic: ReturnType<typeof taskRunStreamLogic.build>
+ let restoreEventSource: () => void
+ let mounted = false
+
+ beforeEach(async () => {
+ // The run handle is persisted to localStorage, so a leftover from another test would decide
+ // whether this run is the active one.
+ window.localStorage.clear()
+ initKeaTests()
+ // Reconciliation must confirm the run under test, or it would clear the handle mid-test and
+ // the stream would refuse to connect.
+ mockActiveWizardRun.mockResolvedValue({
+ task_id: 'task-1',
+ run_id: 'run-1',
+ status: 'in_progress',
+ started_at: RUN_STARTED_AT,
+ })
+ restoreEventSource = installMockEventSource()
+ logic = taskRunStreamLogic({ taskId: 'task-1', runId: 'run-1' })
+ logic.mount()
+ mounted = true
+ activeCloudRunLogic.actions.setActiveCloudRun('task-1', 'run-1', RUN_STARTED_AT, MOCK_TEAM_ID)
+ await expectLogic(projectLogic).toMatchValues({ currentProjectId: MOCK_TEAM_ID })
+ jest.useFakeTimers()
+ })
+
+ afterEach(() => {
+ if (mounted) {
+ logic.unmount()
+ mounted = false
+ }
+ jest.useRealTimers()
+ restoreEventSource()
+ })
+
+ it('reconnects after a fatal close, which the browser never retries on its own', async () => {
+ logic.actions.connect()
+ MockEventSource.last().emitOpen()
+ await expectLogic(logic).toDispatchActions(['connectionOpened'])
+
+ MockEventSource.last().emitTransportError(MockEventSource.CLOSED)
+ await expectLogic(logic).toDispatchActions(['connectionErrored'])
+ expect(MockEventSource.instances).toHaveLength(1)
+
+ jest.advanceTimersByTime(PAST_FIRST_RECONNECT_MS)
+ await expectLogic(logic).toDispatchActions(['connect'])
+ expect(MockEventSource.instances).toHaveLength(2)
+ })
+
+ it('backs off between consecutive fatal closes', async () => {
+ logic.actions.connect()
+ MockEventSource.last().emitTransportError(MockEventSource.CLOSED)
+ await expectLogic(logic).toDispatchActions(['connectionErrored'])
+ jest.advanceTimersByTime(PAST_FIRST_RECONNECT_MS)
+ expect(MockEventSource.instances).toHaveLength(2)
+
+ // No successful open in between, so the second attempt waits out the doubled window.
+ MockEventSource.last().emitTransportError(MockEventSource.CLOSED)
+ await expectLogic(logic).toDispatchActions(['connectionErrored'])
+ jest.advanceTimersByTime(PAST_FIRST_RECONNECT_MS)
+ expect(MockEventSource.instances).toHaveLength(2)
+
+ jest.advanceTimersByTime(SSE_RECONNECT_MAX_MS)
+ expect(MockEventSource.instances).toHaveLength(3)
+ })
+
+ it('leaves a transient drop to the browser, which retries it natively', async () => {
+ logic.actions.connect()
+ MockEventSource.last().emitOpen()
+ await expectLogic(logic).toDispatchActions(['connectionOpened'])
+
+ MockEventSource.last().emitTransportError(MockEventSource.CONNECTING)
+ await expectLogic(logic).toDispatchActions(['connectionErrored'])
+
+ jest.advanceTimersByTime(SSE_RECONNECT_MAX_MS)
+ expect(MockEventSource.instances).toHaveLength(1)
+ })
+
+ it('cancels a pending reconnect on disconnect', async () => {
+ logic.actions.connect()
+ MockEventSource.last().emitTransportError(MockEventSource.CLOSED)
+ await expectLogic(logic).toDispatchActions(['connectionErrored'])
+
+ logic.actions.disconnect()
+ jest.advanceTimersByTime(SSE_RECONNECT_MAX_MS)
+ expect(MockEventSource.instances).toHaveLength(1)
+ })
+
+ it('cancels a pending reconnect on unmount', async () => {
+ logic.actions.connect()
+ MockEventSource.last().emitTransportError(MockEventSource.CLOSED)
+ await expectLogic(logic).toDispatchActions(['connectionErrored'])
+
+ logic.unmount()
+ mounted = false
+ jest.advanceTimersByTime(SSE_RECONNECT_MAX_MS)
+ expect(MockEventSource.instances).toHaveLength(1)
+ })
+})
diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts
index c5b26b132e1d..57d5a5a43098 100644
--- a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts
+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts
@@ -1,5 +1,6 @@
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
+import { sseReconnectDelayMs } from 'lib/wizard-sync/pollLoop'
import { logSyncDebug } from 'lib/wizard-sync/wizardSyncDebugLogic'
import { projectLogic } from 'scenes/projectLogic'
@@ -249,7 +250,9 @@ export type taskRunStreamLogicType = MakeLogicType<
*
* Data events (`task_run_state`, `_posthog/progress` notifications) arrive unnamed via `onmessage`;
* `stream-end` closes the stream; rotation (`end`) and transient drops are handled by EventSource's
- * native reconnect (it replays the `Last-Event-ID` cursor the server stamps on every event).
+ * native reconnect (it replays the `Last-Event-ID` cursor the server stamps on every event). Fatal
+ * closes (readyState CLOSED, e.g. any non-200 on a (re)connect) never retry natively, so the logic
+ * schedules its own backed-off reconnect, per the posthog/api/streaming.py consumer contract.
*
* When the `onboarding-wizard-sync-mode` flag resolves to `polling` (GROW-118), the EventSource is
* replaced by an interval that re-fetches the run's REST snapshot and feeds it through the same
@@ -380,6 +383,9 @@ export const taskRunStreamLogic = kea<taskRunStreamLogicType>([
}, 'queued-stall')
},
connect: () => {
+ // A connect (manual or scheduled) supersedes any pending reconnect timer, so the two can
+ // never race a second stream open.
+ cache.disposables.dispose('task-run-reconnect')
// No run to stream — the Installation layer connects this source even in local mode (where
// there's no TaskRun), so stay idle rather than opening a stream to a non-existent run.
if (!props.runId) {
@@ -416,6 +422,7 @@ export const taskRunStreamLogic = kea<taskRunStreamLogicType>([
// Mode rides along here too: the connect event can predate the debug panel's
// mount (and get dropped), but open/events always land after it.
logSyncDebug(debugSource, 'open', 'SSE connection open', { mode: 'sse' })
+ cache.sseReconnectAttempt = 0
actions.connectionOpened()
}
eventSource.onmessage = (event: MessageEvent<string>): void => {
@@ -452,14 +459,31 @@ export const taskRunStreamLogic = kea<taskRunStreamLogicType>([
cache.disposables.dispose('task-run-sync')
})
eventSource.onerror = (): void => {
- // CLOSED → browser gave up (won't auto-reconnect); anything else → it's already
- // retrying (rides the Last-Event-ID cursor), so just surface "reconnecting".
+ // CLOSED → browser gave up (any non-200 on a (re)connect lands here and it will
+ // never retry on its own), so schedule our own reconnect with backoff; anything
+ // else → it's already retrying (rides the Last-Event-ID cursor), so just surface
+ // "reconnecting".
if (eventSource.readyState === EventSource.CLOSED) {
- logSyncDebug(debugSource, 'error', 'SSE closed by server')
- actions.connectionErrored('EventSource connection closed by server — call connect() to retry')
+ const attempt = ((cache.sseReconnectAttempt as number | undefined) ?? 0) + 1
+ cache.sseReconnectAttempt = attempt
+ const delayMs = sseReconnectDelayMs(attempt)
+ logSyncDebug(
+ debugSource,
+ 'error',
+ `SSE closed, reconnecting in ~${Math.round(delayMs / 1000)}s`
+ )
+ actions.connectionErrored(
+ `EventSource connection closed, reconnecting in ~${Math.round(delayMs / 1000)}s`
+ )
+ // The timer rides disposables so an unmount tears it down, and a hidden tab
+ // pauses it instead of reconnecting in the background.
+ cache.disposables.add(() => {
+ const timer = window.setTimeout(() => actions.connect(), delayMs)
+ return () => window.clearTimeout(timer)
+ }, 'task-run-reconnect')
} else {
logSyncDebug(debugSource, 'error', 'SSE transport error, reconnecting')
- actions.connectionErrored('EventSource transport error — reconnecting')
+ actions.connectionErrored('EventSource transport error, reconnecting')
}
}
@@ -470,6 +494,7 @@ export const taskRunStreamLogic = kea<taskRunStreamLogicType>([
// Tolerant of an empty/absent runId: local mode builds this logic with runId ''.
logSyncDebug(`run ${String(props.runId ?? '').slice(0, 8)}`, 'disconnect', 'disconnected')
cache.disposables.dispose('task-run-sync')
+ cache.disposables.dispose('task-run-reconnect')
cache.disposables.dispose('queued-stall')
},
})),
diff --git a/products/wizard/frontend/wizardSessionStreamLogic.test.ts b/products/wizard/frontend/wizardSessionStreamLogic.test.ts
index 317d0f058f0a..93e5e47ad011 100644
--- a/products/wizard/frontend/wizardSessionStreamLogic.test.ts
+++ b/products/wizard/frontend/wizardSessionStreamLogic.test.ts
@@ -1,8 +1,12 @@
+import { installMockEventSource, MockEventSource } from 'lib/wizard-sync/eventSource.mock'
+
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { ApiError } from 'lib/api-error'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { SSE_RECONNECT_MAX_MS } from 'lib/wizard-sync/pollLoop'
import { projectLogic } from 'scenes/projectLogic'
import { initKeaTests } from '~/test/init'
@@ -138,3 +142,64 @@ describe('wizardSessionStreamLogic polling mode', () => {
expect(mockLatestRetrieve).toHaveBeenCalledTimes(2)
})
})
+
+// The first backoff step is 2s ±20%, so this window always contains the retry.
+const PAST_FIRST_RECONNECT_MS = 2600
+
+describe('wizardSessionStreamLogic SSE mode', () => {
+ let logic: ReturnType<typeof wizardSessionStreamLogic.build>
+ let restoreEventSource: () => void
+ let capture: jest.SpyInstance
+
+ beforeEach(async () => {
+ // Resolved feature flags are persisted, so the polling suite above would otherwise decide
+ // this suite's transport too.
+ window.localStorage.clear()
+ initKeaTests()
+ mockLatestRetrieve.mockReset()
+ restoreEventSource = installMockEventSource()
+ capture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as never)
+ logic = wizardSessionStreamLogic({ workflowId: 'posthog-integration' })
+ logic.mount()
+ // connect() no-ops into an error without a project — wait for the test bootstrap to provide one.
+ await expectLogic(projectLogic).toMatchValues({ currentProjectId: expect.any(Number) })
+ jest.useFakeTimers()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ jest.useRealTimers()
+ restoreEventSource()
+ capture.mockRestore()
+ })
+
+ const transportErrors = (): unknown[] =>
+ capture.mock.calls.filter(([event]) => event === 'wizard sync transport error')
+
+ it('reconnects after a fatal close and reports the transport error once per connect cycle', async () => {
+ logic.actions.connect()
+ MockEventSource.last().emitOpen()
+ await expectLogic(logic).toDispatchActions(['connectionOpened'])
+
+ MockEventSource.last().emitTransportError(MockEventSource.CLOSED)
+ await expectLogic(logic).toDispatchActions(['connectionErrored'])
+ jest.advanceTimersByTime(PAST_FIRST_RECONNECT_MS)
+ expect(MockEventSource.instances).toHaveLength(2)
+
+ // A stream that stays fatally closed retries for as long as the tab is open. One capture per
+ // backoff step would be one every 30s per tab, enough to drown the transport comparison.
+ MockEventSource.last().emitTransportError(MockEventSource.CLOSED)
+ await expectLogic(logic).toDispatchActions(['connectionErrored'])
+ expect(transportErrors()).toHaveLength(1)
+ })
+
+ it('cancels a pending reconnect on disconnect', async () => {
+ logic.actions.connect()
+ MockEventSource.last().emitTransportError(MockEventSource.CLOSED)
+ await expectLogic(logic).toDispatchActions(['connectionErrored'])
+
+ logic.actions.disconnect()
+ jest.advanceTimersByTime(SSE_RECONNECT_MAX_MS)
+ expect(MockEventSource.instances).toHaveLength(1)
+ })
+})
diff --git a/products/wizard/frontend/wizardSessionStreamLogic.ts b/products/wizard/frontend/wizardSessionStreamLogic.ts
index 847d3a380c67..f34e42e2b4d9 100644
--- a/products/wizard/frontend/wizardSessionStreamLogic.ts
+++ b/products/wizard/frontend/wizardSessionStreamLogic.ts
@@ -8,6 +8,7 @@ import {
isPermanentPollError,
resolvePollingIntervalMs,
resolveWizardSyncMode,
+ sseReconnectDelayMs,
type WizardSyncMode,
} from 'lib/wizard-sync/pollLoop'
import { logSyncDebug } from 'lib/wizard-sync/wizardSyncDebugLogic'
@@ -139,6 +140,15 @@ export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([
}),
listeners(({ values, actions, props, cache }) => ({
connect: () => {
+ // A connect (manual or scheduled) supersedes any pending reconnect timer, so the two can
+ // never race a second transport open.
+ cache.disposables.dispose('session-reconnect')
+ // A scheduled retry continues the connect cycle that failed rather than starting a new
+ // one, so it must leave the telemetry guards below alone. Resetting them here would emit
+ // one transport-error capture per backoff step for as long as the stream stays closed,
+ // which is once every 30s per tab and enough to swamp the SSE-vs-polling comparison.
+ const resumingCycle = cache.reconnectScheduled === true
+ cache.reconnectScheduled = false
const projectId = values.currentProjectId
if (projectId === null) {
actions.connectionErrored('No current project — cannot open wizard session stream.')
@@ -148,9 +158,11 @@ export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([
// Per-connect-cycle transport telemetry: one "ready" (first session delivered) and at
// most one "error" per cycle, so SSE and polling performance stay comparable without
// an event per delivery or per EventSource retry.
- cache.connectStartedAt = Date.now()
- cache.transportReadyReported = false
- cache.transportErrorReported = false
+ if (!resumingCycle) {
+ cache.connectStartedAt = Date.now()
+ cache.transportReadyReported = false
+ cache.transportErrorReported = false
+ }
const debugSource = `session ${props.workflowId}::${props.skillId ?? '*'}`
@@ -228,6 +240,7 @@ export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([
// Mode rides along here too: the connect event can predate the debug panel's
// mount (and get dropped), but open/events always land after it.
logSyncDebug(debugSource, 'open', 'SSE connection open', { mode: 'sse' })
+ cache.sseReconnectAttempt = 0
actions.connectionOpened()
}
eventSource.onmessage = (event: MessageEvent<string>): void => {
@@ -244,16 +257,36 @@ export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([
}
eventSource.onerror = (): void => {
// EventSource readyState distinguishes terminal close vs transient retry:
- // CLOSED (2) → browser gave up; will NOT auto-reconnect.
- // Consumers must call connect() again.
+ // CLOSED (2) → browser gave up (any non-200 on a (re)connect lands here)
+ // and will NOT auto-reconnect, so schedule our own reconnect
+ // with backoff.
// CONNECTING (0) → browser is already retrying; ride it out, surface
// the state so the UI can show "reconnecting".
if (eventSource.readyState === EventSource.CLOSED) {
- logSyncDebug(debugSource, 'error', 'SSE closed by server')
- actions.connectionErrored('EventSource connection closed by server — call connect() to retry')
+ const attempt = ((cache.sseReconnectAttempt as number | undefined) ?? 0) + 1
+ cache.sseReconnectAttempt = attempt
+ const delayMs = sseReconnectDelayMs(attempt)
+ logSyncDebug(
+ debugSource,
+ 'error',
+ `SSE closed, reconnecting in ~${Math.round(delayMs / 1000)}s`
+ )
+ actions.connectionErrored(
+ `EventSource connection closed, reconnecting in ~${Math.round(delayMs / 1000)}s`
+ )
+ // The timer rides disposables so an unmount tears it down, and a hidden tab
+ // pauses it instead of reconnecting in the background. connect() re-samples
+ // the sync-mode flag, so a mid-outage flip to polling takes effect here too.
+ cache.disposables.add(() => {
+ const timer = window.setTimeout(() => {
+ cache.reconnectScheduled = true
+ actions.connect()
+ }, delayMs)
+ return () => window.clearTimeout(timer)
+ }, 'session-reconnect')
} else {
- logSyncDebug(debugSource, 'error', 'SSE transport error — reconnecting')
- actions.connectionErrored('EventSource transport error — reconnecting')
+ logSyncDebug(debugSource, 'error', 'SSE transport error, reconnecting')
+ actions.connectionErrored('EventSource transport error, reconnecting')
}
}
@@ -263,6 +296,9 @@ export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([
disconnect: () => {
logSyncDebug(`session ${props.workflowId}::${props.skillId ?? '*'}`, 'disconnect', 'disconnected')
cache.disposables.dispose('session-sync')
+ cache.disposables.dispose('session-reconnect')
+ // The next connect is a new cycle, not a continuation of the one that was torn down.
+ cache.reconnectScheduled = false
},
sessionUpdated: () => {
if (cache.transportReadyReported || cache.connectStartedAt === undefined) {