: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(onboarding): allow wizard sync state to use polling (#68248)
Fernando Gomes6a12e76a5967
diff --git a/bin/ensure-local-setup b/bin/ensure-local-setupindex b2ca4f3894f0..77a98b981fea 100755--- a/bin/ensure-local-setup+++ b/bin/ensure-local-setup@@ -22,19 +22,16 @@ from django.conf import settings # noqa: E402from django.core.management import call_command # noqa: E402from posthog.models import OAuthApplication # noqa: E402+from posthog.scopes import UNPRIVILEGED_SCOPES # noqa: E402-# What the wizard's agent step needs (mirrors @posthog/wizard's WIZARD_PROVISIONING_SCOPES). Local-dev-# convenience only — no need to track the published wizard forever.-WIZARD_SCOPES = [- "user:read",- "project:read",- "llm_gateway:read",- "dashboard:write",- "insight:write",- "query:read",- "notebook:write",- "wizard_session:write"-]+# The wizard requests @posthog/wizard's WIZARD_OAUTH_SCOPES plus per-program additions+# (PROGRAM_SCOPE_ADDITIONS), and any single scope outside the app's ceiling fails the whole+# /authorize with invalid_scope. Enumerating the union here would break every time a program+# adds a scope, so grant everything unprivileged plus the privileged/hidden scopes the wizard+# needs — same broad ceiling the hedgebox demo matrix sets on this app. Local-dev only.+WIZARD_SCOPES = sorted(+ UNPRIVILEGED_SCOPES | {"llm_gateway:read", "llm_gateway:write", "wizard_session:read", "wizard_session:write"}+)def ensure_wizard_oauth_app() -> None:@@ -47,6 +44,14 @@ def ensure_wizard_oauth_app() -> None:print(" not a local dev environment - skipping wizard OAuth app")return+ # DEBUG=True alone is not a reliable "this is a laptop" signal (misconfigured self-hosted+ # instances run with it), and this app is a public client with a committed client_id and a+ # broad scope ceiling - require a localhost SITE_URL too before seeding it.+ site_url = getattr(settings, "SITE_URL", "") or ""+ if "//localhost" not in site_url and "//127.0.0.1" not in site_url:+ print(f" SITE_URL ({site_url}) is not localhost - skipping wizard OAuth app")+ return+client_id = settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_IDif not client_id:print(" WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID not set - skipping wizard OAuth app")diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 55e326c0fb5f..4f866c392921 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -402,6 +402,7 @@ export const FEATURE_FLAGS = {ONBOARDING_WIZARD_CLOUD_RUN: 'onboarding-wizard-cloud-run', // owner: @fercgomes #team-growth multivariate=control,test — gates the "open a PR for me" cloud wizard option on the install stepONBOARDING_WIZARD_SIDEBAR: 'onboarding-wizard-sidebar', // owner: @fercgomes #team-growth multivariate=control,test — gates the installation status item in the sidebar footerONBOARDING_WIZARD_SYNC: 'onboarding-wizard-sync', // owner: @fercgomes #team-growth multivariate=control,test — gates the live wizard sync progress panel+ ONBOARDING_WIZARD_SYNC_MODE: 'onboarding-wizard-sync-mode', // owner: @fercgomes #team-growth multivariate=sse,polling — how the wizard sync panel pulls run updates (SSE stream vs REST polling); payload carries polling_interval_secsOWNER_ONLY_BILLING: 'owner-only-billing', // owner: @pawelcebula #team-billingPAGE_REPORTS_AVERAGE_PAGE_VIEW: 'page-reports-average-page-view', // owner: @jordanm-posthog #team-web-analyticsPAGE_REPORTS_RANKED_URL_SEARCH: 'page-reports-ranked-url-search', // owner: @jordanm-posthog #team-web-analyticsdiff --git a/frontend/src/lib/wizard-sync/pollLoop.ts b/frontend/src/lib/wizard-sync/pollLoop.tsnew file mode 100644index 000000000000..9681e3e31815--- /dev/null+++ b/frontend/src/lib/wizard-sync/pollLoop.ts@@ -0,0 +1,128 @@+import { ApiError } from 'lib/api-error'++// How a wizard sync stream pulls updates. `sse` holds a live EventSource; `polling` re-fetches a REST+// snapshot on an interval (GROW-118). Toggled by the `onboarding-wizard-sync-mode` flag; `sse` stays+// the default when the flag is off or unset.+export type WizardSyncMode = 'sse' | 'polling'++export function resolveWizardSyncMode(flagValue: unknown): WizardSyncMode {+ return flagValue === 'polling' ? 'polling' : 'sse'+}++export const DEFAULT_POLLING_INTERVAL_SECS = 3+const MIN_POLLING_INTERVAL_SECS = 1+// Also guards against `window.setTimeout` int32 overflow: a delay above 2^31-1 ms fires immediately,+// which would turn a fat-fingered payload into a tight polling loop across every flagged client.+export const MAX_POLLING_INTERVAL_SECS = 300++// Resolve the poll cadence from the flag payload's `polling_interval_secs`, falling back to the default+// and clamping on both ends so a stray payload can neither hammer the endpoint nor stall sync entirely.+export function resolvePollingIntervalMs(payload: unknown): number {+ const raw = (payload as { polling_interval_secs?: unknown } | null)?.polling_interval_secs+ const secs = typeof raw === 'number' && Number.isFinite(raw) ? raw : DEFAULT_POLLING_INTERVAL_SECS+ return Math.min(MAX_POLLING_INTERVAL_SECS, Math.max(MIN_POLLING_INTERVAL_SECS, secs)) * 1000+}++// Spread poll ticks ±20% around the base cadence so clients whose runs kicked off together (or whose+// tabs woke together) don't hit the endpoint in lockstep, avoiding a thundering herd on the API.+export const POLL_JITTER_RATIO = 0.2+export function jitteredIntervalMs(baseMs: number, random: () => number = Math.random): number {+ return Math.round(baseMs * (1 - POLL_JITTER_RATIO + random() * 2 * POLL_JITTER_RATIO))+}++// Backoff ceiling for consecutive failures/empties, and how many empty ticks ride the base cadence+// before slowing down (a run usually appears within a few ticks; a killswitched or idle endpoint+// should not be polled at full rate forever).+export const MAX_POLL_BACKOFF_MS = 60_000+export const EMPTY_POLLS_BEFORE_BACKOFF = 5++// 401/403 (access revoked), 404 (deleted), 410 (gone): retrying cannot succeed, stop the loop.+export function isPermanentPollError(error: unknown): boolean {+ return error instanceof ApiError && [401, 403, 404, 410].includes(error.status ?? 0)+}++export type PollTickOutcome = 'ok' | 'empty' | 'terminal'++export interface PollLoopOptions {+ /** Base cadence between ticks; jitter and backoff are applied on top. */+ intervalMs: number+ /** Fetch + dispatch one snapshot. Classify the result; throw on request failure. */+ tick: () => Promise<PollTickOutcome>+ /** Called for each failed tick. Return 'stop' to end the loop permanently. */+ onError: (error: unknown, consecutiveFailures: number) => 'retry' | 'stop'+ /** Checked before each tick; returning true ends the loop permanently. */+ shouldStop?: () => boolean+ /** Runs when the loop ends itself (terminal tick, error stop, shouldStop) — not on external cleanup. */+ onLoopEnd?: () => void+}++/**+ * Shared poll loop for the wizard sync transports (task-run and wizard-session polling modes).+ * Returns a disposable setup function for `cache.disposables.add`.+ *+ * Guarantees:+ * - Each tick schedules the next one only after its request settles, so a slow server can never+ * stack requests, and every gap gets fresh jitter.+ * - Consecutive failures back off exponentially (capped at MAX_POLL_BACKOFF_MS) and permanent+ * errors stop the loop, so an outage or a deleted resource is not hammered at full cadence.+ * - Consecutive empty ticks past EMPTY_POLLS_BEFORE_BACKOFF back off the same way, so an endpoint+ * with nothing to report (no session yet, killswitched) winds down instead of polling forever.+ */+export function createPollLoop(options: PollLoopOptions): () => () => void {+ return (): (() => void) => {+ let cancelled = false+ let timer: number | undefined+ let consecutiveFailures = 0+ let consecutiveEmpty = 0++ const nextDelayMs = (): number => {+ if (consecutiveFailures > 0) {+ return Math.min(options.intervalMs * 2 ** consecutiveFailures, MAX_POLL_BACKOFF_MS)+ }+ const emptyOverage = consecutiveEmpty - EMPTY_POLLS_BEFORE_BACKOFF+ if (emptyOverage >= 0) {+ return Math.min(options.intervalMs * 2 ** (emptyOverage + 1), MAX_POLL_BACKOFF_MS)+ }+ return options.intervalMs+ }++ const poll = async (): Promise<void> => {+ // Re-checked every tick, not just at connect: the disposables plugin re-runs setup on+ // tab-visibility resume, so connect-time guards alone would let a stale loop revive.+ if (options.shouldStop?.()) {+ options.onLoopEnd?.()+ return+ }+ try {+ const outcome = await options.tick()+ if (cancelled) {+ return+ }+ consecutiveFailures = 0+ consecutiveEmpty = outcome === 'empty' ? consecutiveEmpty + 1 : 0+ if (outcome === 'terminal') {+ options.onLoopEnd?.()+ return+ }+ } catch (error) {+ if (cancelled) {+ return+ }+ consecutiveFailures += 1+ if (options.onError(error, consecutiveFailures) === 'stop') {+ options.onLoopEnd?.()+ return+ }+ }+ // A tick's dispatches can synchronously dispose this loop; don't schedule an orphan.+ if (!cancelled) {+ timer = window.setTimeout(() => void poll(), jitteredIntervalMs(nextDelayMs()))+ }+ }+ void poll()+ return () => {+ cancelled = true+ window.clearTimeout(timer)+ }+ }+}diff --git a/frontend/src/lib/wizard-sync/wizardSyncDebugLogic.ts b/frontend/src/lib/wizard-sync/wizardSyncDebugLogic.tsnew file mode 100644index 000000000000..8574f49fada7--- /dev/null+++ b/frontend/src/lib/wizard-sync/wizardSyncDebugLogic.ts@@ -0,0 +1,124 @@+import { actions, kea, listeners, path, reducers } from 'kea'++import type { wizardSyncDebugLogicType } from './wizardSyncDebugLogicType'++export type SyncDebugKind = 'connect' | 'open' | 'poll' | 'event' | 'error' | 'complete' | 'disconnect'++export interface SyncDebugEntry {+ id: number+ at: number+ source: string+ kind: SyncDebugKind+ message: string+ /** For `poll`/`event` kinds: ms since the previous poll/event from the same source. */+ gapMs: number | null+}++export interface SyncDebugSourceInfo {+ source: string+ mode: 'sse' | 'polling' | null+ intervalMs: number | null+ /** Last poll settle / SSE event arrival. */+ lastAt: number | null+ lastGapMs: number | null+ /** Polls settled or SSE events received. */+ ticks: number+ lastKind: SyncDebugKind+ lastMessage: string+}++const MAX_ENTRIES = 200++let nextEntryId = 0+// Gap tracking lives here rather than in a reducer so `gapMs` can travel on the action payload and+// the reducers stay pure. Module-level is fine: this is a dev-only diagnostic, not app state.+const lastTickAtBySource = new Map<string, number>()++/**+ * Dev-only in-memory event log for the wizard sync transports (task-run SSE/polling, wizard-session+ * SSE/polling). Fed by `logSyncDebug` below and rendered by `WizardSyncDebugPanel`. Never mounted in+ * production — the helper no-ops there, so this logic holds no state outside development.+ */+export const wizardSyncDebugLogic = kea<wizardSyncDebugLogicType>([+ path(['lib', 'wizard-sync', 'wizardSyncDebugLogic']),+ actions({+ recordSyncEvent: (entry: SyncDebugEntry, mode?: 'sse' | 'polling', intervalMs?: number) => ({+ entry,+ mode,+ intervalMs,+ }),+ clearSyncDebugLog: true,+ }),+ reducers({+ entries: [+ [] as SyncDebugEntry[],+ {+ recordSyncEvent: (state, { entry }) => [entry, ...state].slice(0, MAX_ENTRIES),+ clearSyncDebugLog: () => [],+ },+ ],+ sources: [+ {} as Record<string, SyncDebugSourceInfo>,+ {+ recordSyncEvent: (state, { entry, mode, intervalMs }) => {+ const previous = state[entry.source]+ const isTick = entry.kind === 'poll' || entry.kind === 'event'+ return {+ ...state,+ [entry.source]: {+ source: entry.source,+ mode: mode ?? previous?.mode ?? null,+ intervalMs: intervalMs ?? previous?.intervalMs ?? null,+ lastAt: isTick ? entry.at : (previous?.lastAt ?? null),+ lastGapMs: isTick ? entry.gapMs : (previous?.lastGapMs ?? null),+ ticks: (previous?.ticks ?? 0) + (isTick ? 1 : 0),+ lastKind: entry.kind,+ lastMessage: entry.message,+ },+ }+ },+ clearSyncDebugLog: () => ({}),+ },+ ],+ }),+ listeners({+ // Reset the module-level gap tracker too, or the first tick after a clear reports a stale gap.+ clearSyncDebugLog: () => {+ lastTickAtBySource.clear()+ },+ }),+])++/**+ * Record a wizard-sync debug event. No-ops outside development and when the debug panel (the only+ * thing that mounts `wizardSyncDebugLogic`) isn't rendered, so instrumented production code paths+ * pay nothing.+ */+export function logSyncDebug(+ source: string,+ kind: SyncDebugKind,+ message: string,+ opts?: { mode?: 'sse' | 'polling'; intervalMs?: number }+): void {+ if (process.env.NODE_ENV !== 'development') {+ return+ }+ const mounted = wizardSyncDebugLogic.findMounted()+ if (!mounted) {+ return+ }+ const at = Date.now()+ let gapMs: number | null = null+ if (kind === 'poll' || kind === 'event') {+ const last = lastTickAtBySource.get(source)+ gapMs = last !== undefined ? at - last : null+ lastTickAtBySource.set(source, at)+ } else if (kind === 'connect') {+ lastTickAtBySource.delete(source)+ }+ mounted.actions.recordSyncEvent(+ { id: nextEntryId++, at, source, kind, message, gapMs },+ opts?.mode,+ opts?.intervalMs+ )+}diff --git a/frontend/src/scenes/AuthenticatedShell.tsx b/frontend/src/scenes/AuthenticatedShell.tsxindex 62f7a7eb10b4..b66b4344a155 100644--- a/frontend/src/scenes/AuthenticatedShell.tsx+++ b/frontend/src/scenes/AuthenticatedShell.tsx@@ -8,6 +8,7 @@ import { ToastCloseButton } from 'lib/lemon-ui/LemonToast/LemonToast'import { apiStatusLogic } from 'lib/logic/apiStatusLogic'import { eventIngestionRestrictionLogic } from 'lib/logic/eventIngestionRestrictionLogic'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { WizardSyncDebugPanel } from 'scenes/onboarding/self-driving/sdks/OnboardingInstallStep/WizardSync/WizardSyncDebugPanel'import { WizardSyncFab } from 'scenes/onboarding/self-driving/sdks/OnboardingInstallStep/WizardSync/WizardSyncFab'import { GlobalModals } from '~/layout/GlobalModals'@@ -41,6 +42,7 @@ export default function AuthenticatedShell({ children }: { children: React.React<ImpersonationNotice /><SelfReadOnlyNotice /><WizardSyncFab />+ <WizardSyncDebugPanel />{featureFlags[FEATURE_FLAGS.EXPERIMENTS_DW_AA_TEST] === 'test' && (<div data-attr="experiments-dw-aa-test-variant" className="hidden" />)}diff --git a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/WizardSync/WizardSyncDebugPanel.tsx b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/WizardSync/WizardSyncDebugPanel.tsxnew file mode 100644index 000000000000..94ac7643b3bc--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/WizardSync/WizardSyncDebugPanel.tsx@@ -0,0 +1,107 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { IconChevronDown, IconChevronRight } from '@posthog/icons'++import { dayjs } from 'lib/dayjs'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonTag } from 'lib/lemon-ui/LemonTag'+import { pluralize } from 'lib/utils/strings'+import { type SyncDebugKind, wizardSyncDebugLogic } from 'lib/wizard-sync/wizardSyncDebugLogic'++const KIND_COLORS: Record<SyncDebugKind, string> = {+ connect: 'text-muted',+ open: 'text-success',+ poll: 'text-default',+ event: 'text-default',+ error: 'text-danger',+ complete: 'text-success',+ disconnect: 'text-muted',+}++function formatTs(at: number): string {+ return dayjs(at).format('HH:mm:ss.SSS')+}++function formatGap(gapMs: number | null): string {+ return gapMs === null ? '' : ` (+${(gapMs / 1000).toFixed(2)}s)`+}++/**+ * Dev-only floating panel (bottom-left) surfacing what the wizard sync transports are doing: which+ * mode each source runs in (SSE vs polling), when polls/events land and the gap between them, and a+ * timestamped log. Renders nothing in production builds and stays hidden until a sync source emits.+ */+export function WizardSyncDebugPanel(): JSX.Element | null {+ if (process.env.NODE_ENV !== 'development') {+ return null+ }+ return <WizardSyncDebugPanelContent />+}++function WizardSyncDebugPanelContent(): JSX.Element | null {+ const { entries, sources } = useValues(wizardSyncDebugLogic)+ const { clearSyncDebugLog } = useActions(wizardSyncDebugLogic)+ const [collapsed, setCollapsed] = useState(false)++ const sourceList = Object.values(sources)+ if (sourceList.length === 0) {+ return null+ }++ return (+ <div className="fixed bottom-2 left-2 z-[9999] max-w-lg rounded border bg-surface-primary shadow-md text-xs">+ <div className="flex items-center gap-1 px-2 py-1 border-b">+ <LemonButton+ size="xsmall"+ icon={collapsed ? <IconChevronRight /> : <IconChevronDown />}+ onClick={() => setCollapsed(!collapsed)}+ tooltip={collapsed ? 'Expand' : 'Collapse'}+ aria-label={collapsed ? 'Expand wizard sync debug panel' : 'Collapse wizard sync debug panel'}+ />+ <span className="font-semibold">Wizard sync debug</span>+ <span className="text-muted">({pluralize(entries.length, 'event')})</span>+ <div className="flex-1" />+ <LemonButton size="xsmall" onClick={clearSyncDebugLog}>+ Clear+ </LemonButton>+ </div>+ {!collapsed && (+ <>+ <div className="px-2 py-1 space-y-1 border-b">+ {sourceList.map((info) => (+ <div key={info.source} className="flex items-center gap-2">+ <LemonTag type={info.mode === 'polling' ? 'warning' : 'success'} size="small">+ {info.mode ?? '?'}+ </LemonTag>+ <span className="font-mono truncate max-w-40" title={info.source}>+ {info.source}+ </span>+ {info.mode === 'polling' && info.intervalMs !== null && (+ <span className="text-muted">~{info.intervalMs / 1000}s ±20%</span>+ )}+ <span className="text-muted">+ {pluralize(info.ticks, info.mode === 'polling' ? 'poll' : 'event')}+ </span>+ {info.lastAt !== null && (+ <span className="text-muted">+ last {formatTs(info.lastAt)}+ {formatGap(info.lastGapMs)}+ </span>+ )}+ </div>+ ))}+ </div>+ <div className="max-h-48 overflow-y-auto overflow-x-auto px-2 py-1 font-mono whitespace-nowrap">+ {entries.map((entry) => (+ <div key={entry.id} className={KIND_COLORS[entry.kind]}>+ {formatTs(entry.at)} [{entry.kind}] {entry.source}: {entry.message}+ {formatGap(entry.gapMs)}+ </div>+ ))}+ </div>+ </>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/installationProgressLogic.ts b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/installationProgressLogic.tsindex 9c7d2d714053..4cb8b1b5e076 100644--- a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/installationProgressLogic.ts+++ b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/installationProgressLogic.ts@@ -1,4 +1,4 @@-import { afterMount, beforeUnmount, connect, kea, key, path, props, selectors } from 'kea'+import { afterMount, beforeUnmount, connect, kea, key, listeners, path, props, selectors } from 'kea'import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'import { wizardSessionStreamLogic } from 'products/wizard/frontend/wizardSessionStreamLogic'@@ -193,7 +193,11 @@ export const installationProgressLogic = kea<installationProgressLogicType>([],actions: [taskRunStreamLogic({ runId: props.runId ?? '', taskId: props.taskId ?? '' }),- ['connect as connectTaskRun', 'disconnect as disconnectTaskRun'],+ [+ 'connect as connectTaskRun',+ 'disconnect as disconnectTaskRun',+ 'streamCompleted as taskRunStreamCompleted',+ ],wizardSessionStreamLogic({ workflowId: WORKFLOW_ID }),['connect as connectSession', 'disconnect as disconnectSession'],],@@ -223,6 +227,16 @@ export const installationProgressLogic = kea<installationProgressLogicType>([: localProgress(latestSession, sessionConnectionStatus),],}),+ listeners(({ actions, props }) => ({+ // Once the cloud run is terminal there is nothing left for the session source to enrich, and+ // it has no terminal state of its own to stop on — without this, an undismissed finished run+ // keeps a session stream/poll alive app-wide until the user clicks "Dismiss this run".+ taskRunStreamCompleted: () => {+ if (props.mode === 'cloud') {+ actions.disconnectSession()+ }+ },+ })),afterMount(({ actions }) => {actions.connectTaskRun()actions.connectSession()diff --git a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.test.ts b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.test.tsindex 94078ea75bbd..1784633d8531 100644--- a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.test.ts+++ b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.test.ts@@ -1,8 +1,19 @@+import {+ DEFAULT_POLLING_INTERVAL_SECS,+ jitteredIntervalMs,+ MAX_POLLING_INTERVAL_SECS,+ POLL_JITTER_RATIO,+ resolvePollingIntervalMs,+} from 'lib/wizard-sync/pollLoop'++import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'+import {cloudRunCompletionReport,mergeProgressStep,parseTaskRunStreamMessage,TaskRunProgressStep,+ taskRunDetailToStreamState,taskRunPrUrl,TaskRunStreamState,} from './taskRunStreamLogic'@@ -152,6 +163,91 @@ describe('taskRunStreamLogic helpers', () => {})})+ describe('resolvePollingIntervalMs', () => {+ it.each([+ ['a valid payload interval', { polling_interval_secs: 10 }, 10_000],+ ['a sub-minimum interval (floored so it cannot hammer the endpoint)', { polling_interval_secs: 0 }, 1000],+ ['a negative interval', { polling_interval_secs: -5 }, 1000],+ ['a non-numeric interval', { polling_interval_secs: 'fast' }, DEFAULT_POLLING_INTERVAL_SECS * 1000],+ ['a missing payload', null, DEFAULT_POLLING_INTERVAL_SECS * 1000],+ ['a payload without the key', {}, DEFAULT_POLLING_INTERVAL_SECS * 1000],+ [+ 'an over-maximum interval (clamped so sync cannot silently stall)',+ { polling_interval_secs: 3600 },+ MAX_POLLING_INTERVAL_SECS * 1000,+ ],+ [+ 'a huge interval that would overflow the int32 setTimeout delay and fire immediately',+ { polling_interval_secs: 1_700_000_000 },+ MAX_POLLING_INTERVAL_SECS * 1000,+ ],+ ])('resolves %s', (_name, payload, expectedMs) => {+ expect(resolvePollingIntervalMs(payload)).toBe(expectedMs)+ })+ })++ describe('jitteredIntervalMs', () => {+ it.each([+ ['the lower jitter bound', 0, 3000 * (1 - POLL_JITTER_RATIO)],+ ['the base cadence at mid-roll', 0.5, 3000],+ ['the upper jitter bound', 1, 3000 * (1 + POLL_JITTER_RATIO)],+ ])('spreads ticks within ±20%% — %s', (_name, roll, expectedMs) => {+ expect(jitteredIntervalMs(3000, () => roll)).toBe(expectedMs)+ })+ })++ describe('taskRunDetailToStreamState', () => {+ it('projects a REST snapshot onto the SSE state shape, coercing missing fields to null', () => {+ const dto = {+ id: 'run-1',+ task: 'task-1',+ stage: undefined,+ branch: undefined,+ status: 'in_progress',+ environment: 'sandbox',+ error_message: null,+ output: undefined,+ state: {},+ artifacts: [],+ } as unknown as TaskRunDetailDTOApi+ expect(taskRunDetailToStreamState(dto)).toEqual({+ status: 'in_progress',+ stage: null,+ output: null,+ branch: null,+ error_message: null,+ updated_at: '',+ completed_at: null,+ })+ })++ it('carries the terminal fields the completion report depends on', () => {+ const dto = {+ id: 'run-1',+ task: 'task-1',+ stage: 'pr',+ branch: 'posthog-setup',+ status: 'completed',+ environment: 'sandbox',+ error_message: null,+ output: { pr_url: 'https://x/pull/1' },+ state: {},+ artifacts: [],+ updated_at: '2026-01-01T00:05:00Z',+ completed_at: '2026-01-01T00:04:30Z',+ } as unknown as TaskRunDetailDTOApi+ expect(taskRunDetailToStreamState(dto)).toEqual({+ status: 'completed',+ stage: 'pr',+ output: { pr_url: 'https://x/pull/1' },+ branch: 'posthog-setup',+ error_message: null,+ updated_at: '2026-01-01T00:05:00Z',+ completed_at: '2026-01-01T00:04:30Z',+ })+ })+ })+describe('taskRunPrUrl', () => {it('prefers the terminal output url over the pr progress step', () => {const state = runState({ output: { pr_url: 'https://x/pull/2' } })diff --git a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.ts b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.tsindex 21b2b2764ff1..fc95d07c4f48 100644--- a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.ts+++ b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.ts@@ -1,8 +1,19 @@import { actions, connect, kea, key, listeners, path, props, reducers } from 'kea'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic, getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'+import {+ createPollLoop,+ isPermanentPollError,+ resolvePollingIntervalMs,+ resolveWizardSyncMode,+ type WizardSyncMode,+} from 'lib/wizard-sync/pollLoop'+import { logSyncDebug } from 'lib/wizard-sync/wizardSyncDebugLogic'import { projectLogic } from 'scenes/projectLogic'-import { getTasksRunsStreamRetrieveUrl } from 'products/tasks/frontend/generated/api'+import { getTasksRunsStreamRetrieveUrl, tasksRunsRetrieve } from 'products/tasks/frontend/generated/api'+import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'import { onboardingEventUsageLogic } from '../../../onboardingEventUsageLogic'import { activeCloudRunLogic } from './activeCloudRunLogic'@@ -14,6 +25,20 @@ export type TaskRunConnectionStatus = 'idle' | 'connecting' | 'open' | 'closed'// seconds; minutes of silence means the pipeline isn't running at all.export const QUEUED_STALL_MS = 2 * 60 * 1000+// Project the REST run snapshot onto the same shape the SSE `task_run_state` events carry, so polling and+// streaming feed `taskRunStateUpdated` identically and the rest of the logic stays mode-agnostic.+export function taskRunDetailToStreamState(dto: TaskRunDetailDTOApi): TaskRunStreamState {+ return {+ status: dto.status,+ stage: dto.stage ?? null,+ output: (dto.output as { pr_url?: string | null } | null) ?? null,+ branch: dto.branch ?? null,+ error_message: dto.error_message ?? null,+ updated_at: dto.updated_at ?? '',+ completed_at: dto.completed_at ?? null,+ }+}+/*** Shapes of the SSE payloads the task-run stream pushes (see the tasks stream view). These are stream* messages, not REST serializers, so they're typed here rather than imported from the generated client.@@ -155,13 +180,26 @@ const reportedTerminalRuns = new Set<string>()* 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).+ *+ * 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+ * `taskRunStateUpdated` action. Polling carries run state only — `_posthog/progress` step+ * notifications are stream-borne, so the step timeline stays empty and surfaces degrade to the+ * coarse run status. The interval comes from the flag payload's `polling_interval_secs`.*/export const taskRunStreamLogic = kea<taskRunStreamLogicType>([props({} as TaskRunStreamLogicProps),key((props) => props.runId),path((key) => ['scenes', 'onboarding', 'taskRunStreamLogic', key]),connect(() => ({- values: [projectLogic, ['currentProjectId'], activeCloudRunLogic, ['activeCloudRun']],+ values: [+ projectLogic,+ ['currentProjectId'],+ activeCloudRunLogic,+ ['activeCloudRun'],+ featureFlagLogic,+ ['featureFlags'],+ ],actions: [onboardingEventUsageLogic, ['reportContextOnboardingCloudRunCompleted']],})),actions({@@ -171,6 +209,9 @@ export const taskRunStreamLogic = kea<taskRunStreamLogicType>([progressStepUpdated: (step: TaskRunProgressStep) => ({ step }),connectionOpened: true,connectionErrored: (error: string) => ({ error }),+ // Connect was requested but this run isn't the project's active cloud run — observable so+ // surfaces render idle instead of an eternal "connecting" spinner.+ connectionSkipped: true,streamCompleted: true,runStalled: true,}),@@ -194,6 +235,7 @@ export const taskRunStreamLogic = kea<taskRunStreamLogicType>([connect: () => 'connecting',connectionOpened: () => 'open',connectionErrored: () => 'error',+ connectionSkipped: () => 'idle',disconnect: () => 'closed',streamCompleted: () => 'closed',},@@ -263,48 +305,157 @@ export const taskRunStreamLogic = kea<taskRunStreamLogicType>([}const projectId = values.currentProjectIdif (projectId === null) {- actions.connectionErrored('No current project — cannot open task run stream.')+ actions.connectionErrored('No current project, cannot open task run stream.')return}+ // Defense in depth: only sync while this run is the project's active cloud run. If the+ // persisted handle is gone (dismissed, superseded) or belongs to another run, no wizard+ // run is happening for this key — never hold a background stream/poll open for it.+ if (values.activeCloudRun?.runId !== props.runId) {+ logSyncDebug(`run ${props.runId.slice(0, 8)}`, 'connect', 'skipped: not the active cloud run')+ actions.connectionSkipped()+ return+ }++ // Mode is re-sampled on every connect, and the setFeatureFlags listener below reconnects+ // when the resolved mode changes — so a flag flip (or flags arriving after a cold-cache+ // connect) swaps the transport live instead of waiting for a remount.+ const syncMode: WizardSyncMode = resolveWizardSyncMode(+ values.featureFlags[FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE]+ )+ cache.syncMode = syncMode+ const debugSource = `run ${props.runId.slice(0, 8)}`+ if (syncMode === 'polling') {+ const intervalMs = resolvePollingIntervalMs(+ getFeatureFlagPayload(FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE)+ )+ logSyncDebug(debugSource, 'connect', `polling every ~${intervalMs / 1000}s (±20% jitter)`, {+ mode: 'polling',+ intervalMs,+ })+ cache.disposables.add(+ createPollLoop({+ intervalMs,+ // Re-checked each tick: tab-visibility resume re-runs this setup, so a run+ // dismissed or superseded while hidden must not revive a stale loop.+ shouldStop: () => values.activeCloudRun?.runId !== props.runId,+ tick: async () => {+ const dto = await tasksRunsRetrieve(String(projectId), props.taskId, props.runId)+ logSyncDebug(+ debugSource,+ 'poll',+ `poll ok: ${dto.status}${dto.stage ? `/${dto.stage}` : ''}`,+ {+ mode: 'polling',+ intervalMs,+ }+ )+ // Only on first open / recovery from error — not every tick.+ if (values.connectionStatus !== 'open') {+ actions.connectionOpened()+ }+ actions.taskRunStateUpdated(taskRunDetailToStreamState(dto))+ if (isTerminalStatus(dto.status)) {+ logSyncDebug(debugSource, 'complete', `terminal status ${dto.status}, polling stopped`)+ actions.streamCompleted()+ return 'terminal'+ }+ return 'ok'+ },+ onError: (err) => {+ logSyncDebug(debugSource, 'error', `poll failed: ${String(err)}`)+ actions.connectionErrored(`Failed to poll task run: ${String(err)}`)+ return isPermanentPollError(err) ? 'stop' : 'retry'+ },+ // Dispose the key so a later tab-visibility resume doesn't restart a loop+ // that ended itself.+ onLoopEnd: () => cache.disposables.dispose('task-run-sync'),+ }),+ 'task-run-sync'+ )+ return+ }++ logSyncDebug(debugSource, 'connect', 'opening EventSource', { mode: 'sse' })cache.disposables.add((): (() => void) => {const url = getTasksRunsStreamRetrieveUrl(String(projectId), props.taskId, props.runId)const eventSource = new EventSource(url, { withCredentials: true })- eventSource.onopen = actions.connectionOpened+ eventSource.onopen = (): void => {+ // 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' })+ actions.connectionOpened()+ }eventSource.onmessage = (event: MessageEvent<string>): void => {try {const message = parseTaskRunStreamMessage(event.data)if (message?.kind === 'step') {+ logSyncDebug(+ debugSource,+ 'event',+ `step ${message.step.group}/${message.step.step} → ${message.step.status}`+ )actions.progressStepUpdated(message.step)} else if (message?.kind === 'state') {+ logSyncDebug(+ debugSource,+ 'event',+ `state → ${message.state.status}${message.state.stage ? `/${message.state.stage}` : ''}`+ )actions.taskRunStateUpdated(message.state)+ } else {+ logSyncDebug(debugSource, 'event', 'message ignored (keepalive/unknown type)')}} catch (err) {+ logSyncDebug(debugSource, 'error', `failed to parse SSE payload: ${String(err)}`)actions.connectionErrored(`Failed to parse SSE payload: ${String(err)}`)}}- // Completion sentinel — close so EventSource doesn't auto-reconnect to a finished run.+ // Completion sentinel. Dispose the whole disposable (which closes the EventSource)+ // rather than just closing: a registered-but-closed source would otherwise be+ // reopened by the disposables plugin on tab-visibility resume.eventSource.addEventListener('stream-end', () => {+ logSyncDebug(debugSource, 'complete', 'stream-end received')actions.streamCompleted()- eventSource.close()+ 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".if (eventSource.readyState === EventSource.CLOSED) {+ logSyncDebug(debugSource, 'error', 'SSE closed by server')actions.connectionErrored('EventSource connection closed by server — call connect() to retry')} else {+ logSyncDebug(debugSource, 'error', 'SSE transport error, reconnecting')actions.connectionErrored('EventSource transport error — reconnecting')}}return () => eventSource.close()- }, 'event-source')+ }, 'task-run-sync')},disconnect: () => {- cache.disposables.dispose('event-source')+ // 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('queued-stall')},+ // Flags can resolve after a cold-cache connect (posthog-js loads them async), and ops can flip+ // the mode mid-incident. Reconnect when the resolved mode differs from the running transport —+ // the keyed disposable makes the swap idempotent.+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {+ if (cache.syncMode === undefined || values.isComplete) {+ return+ }+ if (values.connectionStatus === 'idle' || values.connectionStatus === 'closed') {+ return+ }+ const mode = resolveWizardSyncMode(values.featureFlags[FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE])+ if (mode !== cache.syncMode) {+ actions.connect()+ }+ },})),])diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4118d17fed44..1162b22a3017 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4335,6 +4335,10 @@ importers:react:specifier: 18.3.1version: 18.3.1+ devDependencies:+ kea-test-utils:+ specifier: 'catalog:'+ version: 0.2.4([email protected]([email protected]))products/workflows:dependencies:diff --git a/products/wizard/frontend/wizardSessionStreamLogic.test.ts b/products/wizard/frontend/wizardSessionStreamLogic.test.tsnew file mode 100644index 000000000000..426863ad1d5f--- /dev/null+++ b/products/wizard/frontend/wizardSessionStreamLogic.test.ts@@ -0,0 +1,136 @@+import { expectLogic } from 'kea-test-utils'++import { ApiError } from 'lib/api-error'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { projectLogic } from 'scenes/projectLogic'++import { initKeaTests } from '~/test/init'++import { wizardSessionsLatestRetrieve } from './generated/api'+import type { WizardSessionDTOApi } from './generated/api.schemas'+import { wizardSessionStreamLogic } from './wizardSessionStreamLogic'++jest.mock('./generated/api', () => ({+ wizardSessionsLatestRetrieve: jest.fn(),+ getWizardSessionsStreamRetrieveUrl: jest.fn(() => '/mock-stream-url'),+}))++const mockLatestRetrieve = wizardSessionsLatestRetrieve as jest.Mock++function makeSession(overrides: Partial<WizardSessionDTOApi> = {}): WizardSessionDTOApi {+ return {+ session_id: 'sess-1',+ team_id: 997,+ workflow_id: 'posthog-integration',+ skill_id: 'install',+ started_at: '2026-01-01T00:00:00Z',+ run_phase: 'running',+ tasks: [],+ event_plan: null,+ error: null,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ is_stale: false,+ ...overrides,+ }+}++// Max jittered gap for the default 3s interval is 3.6s — advancing past it guarantees the next tick.+const PAST_MAX_JITTERED_INTERVAL_MS = 4000++describe('wizardSessionStreamLogic polling mode', () => {+ let logic: ReturnType<typeof wizardSessionStreamLogic.build>++ beforeEach(async () => {+ initKeaTests()+ mockLatestRetrieve.mockReset()+ logic = wizardSessionStreamLogic({ workflowId: 'posthog-integration' })+ logic.mount()+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE], {+ [FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE]: 'polling',+ })+ // 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()+ })++ it('polls the latest session and feeds it through sessionUpdated', async () => {+ const session = makeSession()+ mockLatestRetrieve.mockResolvedValue(session)++ logic.actions.connect()+ await expectLogic(logic)+ .toDispatchActions(['connectionOpened', 'sessionUpdated'])+ .toMatchValues({ latestSession: session, connectionStatus: 'open' })++ expect(mockLatestRetrieve).toHaveBeenCalledWith(expect.any(String), {+ workflow_id: 'posthog-integration',+ skill_id: undefined,+ })+ })++ it('keeps polling through a 204 (no session yet) without clobbering latestSession', async () => {+ // The generated client resolves an empty 204 body to null (getJSONOrNull), not undefined.+ mockLatestRetrieve.mockResolvedValue(null)++ logic.actions.connect()+ await expectLogic(logic)+ .toDispatchActions(['connectionOpened'])+ .toNotHaveDispatchedActions(['sessionUpdated'])+ .toMatchValues({ latestSession: null, connectionStatus: 'open' })++ jest.advanceTimersByTime(PAST_MAX_JITTERED_INTERVAL_MS)+ await Promise.resolve()+ expect(mockLatestRetrieve).toHaveBeenCalledTimes(2)+ })++ it('stops polling on disconnect', async () => {+ mockLatestRetrieve.mockResolvedValue(makeSession())++ logic.actions.connect()+ await expectLogic(logic).toDispatchActions(['sessionUpdated'])+ expect(mockLatestRetrieve).toHaveBeenCalledTimes(1)++ logic.actions.disconnect()+ jest.advanceTimersByTime(PAST_MAX_JITTERED_INTERVAL_MS)+ await Promise.resolve()+ expect(mockLatestRetrieve).toHaveBeenCalledTimes(1)+ })++ it('stops polling permanently on a 404', async () => {+ mockLatestRetrieve.mockRejectedValue(new ApiError('not found', 404))++ logic.actions.connect()+ await expectLogic(logic).toDispatchActions(['connectionErrored']).toMatchValues({ connectionStatus: 'error' })+ expect(mockLatestRetrieve).toHaveBeenCalledTimes(1)++ jest.advanceTimersByTime(10 * PAST_MAX_JITTERED_INTERVAL_MS)+ await Promise.resolve()+ expect(mockLatestRetrieve).toHaveBeenCalledTimes(1)+ })++ it('backs off after a transient error instead of retrying at full cadence', async () => {+ mockLatestRetrieve.mockRejectedValueOnce(new Error('network hiccup')).mockResolvedValue(makeSession())++ logic.actions.connect()+ await expectLogic(logic).toDispatchActions(['connectionErrored'])+ expect(mockLatestRetrieve).toHaveBeenCalledTimes(1)++ // One failure doubles the 3s base to 6s (±20% jitter → at least 4.8s): the base window+ // must NOT produce a retry...+ jest.advanceTimersByTime(PAST_MAX_JITTERED_INTERVAL_MS)+ await Promise.resolve()+ expect(mockLatestRetrieve).toHaveBeenCalledTimes(1)++ // ...but the backed-off window must.+ jest.advanceTimersByTime(PAST_MAX_JITTERED_INTERVAL_MS)+ await expectLogic(logic).toDispatchActions(['sessionUpdated'])+ expect(mockLatestRetrieve).toHaveBeenCalledTimes(2)+ })+})diff --git a/products/wizard/frontend/wizardSessionStreamLogic.ts b/products/wizard/frontend/wizardSessionStreamLogic.tsindex cddf530640f4..f0e6e74b1019 100644--- a/products/wizard/frontend/wizardSessionStreamLogic.ts+++ b/products/wizard/frontend/wizardSessionStreamLogic.ts@@ -1,8 +1,18 @@import { actions, connect, kea, key, listeners, path, props, reducers } from 'kea'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic, getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'+import {+ createPollLoop,+ isPermanentPollError,+ resolvePollingIntervalMs,+ resolveWizardSyncMode,+ type WizardSyncMode,+} from 'lib/wizard-sync/pollLoop'+import { logSyncDebug } from 'lib/wizard-sync/wizardSyncDebugLogic'import { projectLogic } from 'scenes/projectLogic'-import { getWizardSessionsStreamRetrieveUrl } from './generated/api'+import { getWizardSessionsStreamRetrieveUrl, wizardSessionsLatestRetrieve } from './generated/api'import type { WizardSessionDTOApi } from './generated/api.schemas'import type { wizardSessionStreamLogicType } from './wizardSessionStreamLogicType'@@ -26,6 +36,15 @@ export interface WizardSessionStreamLogicProps {* multiple subscriptions coexist in the app. Omitting skillId pattern-subscribes* to every skill under the workflow.*+ * When the `onboarding-wizard-sync-mode` flag resolves to `polling` (GROW-118), the+ * EventSource is replaced by a poll loop that re-fetches the latest session via+ * `wizard/sessions/latest/` and feeds it through the same `sessionUpdated` action.+ * The loop (shared with `taskRunStreamLogic`) backs off on consecutive errors, stops on+ * permanent ones (401/403/404), and backs off on consecutive empty responses — so an+ * endpoint with no session (not started yet, or killswitched to 204) winds down instead+ * of being polled at full cadence forever. Consumers stop it via `disconnect`;+ * `installationProgressLogic` does so once a cloud run reaches a terminal state.+ ** Usage:** // Listen to any skill under the posthog-integration workflow:@@ -43,7 +62,7 @@ export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([key((props) => `${props.workflowId}::${props.skillId ?? '*'}`),path((key) => ['products', 'wizard', 'wizardSessionStreamLogic', key]),connect(() => ({- values: [projectLogic, ['currentProjectId']],+ values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags']],})),actions({connect: true,@@ -85,6 +104,67 @@ export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([return}+ const debugSource = `session ${props.workflowId}::${props.skillId ?? '*'}`++ // Mode is re-sampled on every connect, and the setFeatureFlags listener below reconnects+ // when the resolved mode changes — so a flag flip (or flags arriving after a cold-cache+ // connect) swaps the transport live instead of waiting for a remount.+ const syncMode: WizardSyncMode = resolveWizardSyncMode(+ values.featureFlags[FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE]+ )+ cache.syncMode = syncMode++ if (syncMode === 'polling') {+ const intervalMs = resolvePollingIntervalMs(+ getFeatureFlagPayload(FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE)+ )+ logSyncDebug(debugSource, 'connect', `polling every ~${intervalMs / 1000}s (±20% jitter)`, {+ mode: 'polling',+ intervalMs,+ })+ cache.disposables.add(+ createPollLoop({+ intervalMs,+ tick: async () => {+ // 204 (no session yet, or killswitched) resolves to null — classify as+ // empty so the loop backs off instead of polling at full cadence forever.+ const session = await wizardSessionsLatestRetrieve(String(projectId), {+ workflow_id: props.workflowId,+ skill_id: props.skillId,+ })+ logSyncDebug(+ debugSource,+ 'poll',+ session+ ? `poll ok: ${session.run_phase} (${session.skill_id})`+ : 'poll ok: no session yet',+ { mode: 'polling', intervalMs }+ )+ // Only on first open / recovery from error — not every tick.+ if (values.connectionStatus !== 'open') {+ actions.connectionOpened()+ }+ if (!session) {+ return 'empty'+ }+ actions.sessionUpdated(session)+ return 'ok'+ },+ onError: (err) => {+ logSyncDebug(debugSource, 'error', `poll failed: ${String(err)}`)+ actions.connectionErrored(`Failed to poll wizard session: ${String(err)}`)+ return isPermanentPollError(err) ? 'stop' : 'retry'+ },+ // Dispose the key so a later tab-visibility resume doesn't restart a loop+ // that ended itself.+ onLoopEnd: () => cache.disposables.dispose('session-sync'),+ }),+ 'session-sync'+ )+ return+ }++ logSyncDebug(debugSource, 'connect', 'opening EventSource', { mode: 'sse' })cache.disposables.add((): (() => void) => {const url = getWizardSessionsStreamRetrieveUrl(String(projectId), {workflow_id: props.workflowId,@@ -92,12 +172,21 @@ export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([})const eventSource = new EventSource(url, { withCredentials: true })- eventSource.onopen = actions.connectionOpened+ eventSource.onopen = (): void => {+ // 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' })+ actions.connectionOpened()+ }eventSource.onmessage = (event: MessageEvent<string>): void => {try {const session = JSON.parse(event.data) as WizardSessionDTOApi+ logSyncDebug(debugSource, 'event', `session → ${session.run_phase} (${session.skill_id})`, {+ mode: 'sse',+ })actions.sessionUpdated(session)} catch (err) {+ logSyncDebug(debugSource, 'error', `failed to parse SSE payload: ${String(err)}`)actions.connectionErrored(`Failed to parse SSE payload: ${String(err)}`)}}@@ -108,17 +197,35 @@ export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([// 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')} else {+ logSyncDebug(debugSource, 'error', 'SSE transport error — reconnecting')actions.connectionErrored('EventSource transport error — reconnecting')}}return () => eventSource.close()- }, 'event-source')+ }, 'session-sync')},disconnect: () => {- cache.disposables.dispose('event-source')+ logSyncDebug(`session ${props.workflowId}::${props.skillId ?? '*'}`, 'disconnect', 'disconnected')+ cache.disposables.dispose('session-sync')+ },+ // Flags can resolve after a cold-cache connect (posthog-js loads them async), and ops can flip+ // the mode mid-incident. Reconnect when the resolved mode differs from the running transport —+ // the keyed disposable makes the swap idempotent.+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {+ if (cache.syncMode === undefined) {+ return+ }+ if (values.connectionStatus === 'idle' || values.connectionStatus === 'closed') {+ return+ }+ const mode = resolveWizardSyncMode(values.featureFlags[FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE])+ if (mode !== cache.syncMode) {+ actions.connect()+ }},})),])diff --git a/products/wizard/package.json b/products/wizard/package.jsonindex 771250fcc8a7..e489499abe8c 100644--- a/products/wizard/package.json+++ b/products/wizard/package.json@@ -7,6 +7,9 @@"dependencies": {"kea": "catalog:"},+ "devDependencies": {+ "kea-test-utils": "catalog:"+ },"peerDependencies": {"@types/react": "*","react": "*"