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.

feat(wizard): sync setup runs with onboarding (#126499)

Fernando Gomes3d1f2d047eaa
diff --git a/docs/internal/wizard-runs.md b/docs/internal/wizard-runs.md
index 34888b945a7e..579798b6e934 100644
--- a/docs/internal/wizard-runs.md
+++ b/docs/internal/wizard-runs.md
@@ -64,9 +64,37 @@ GET /api/projects/{project_id}/wizard/runs/{run_id}/stream/
Run responses include the creator ID and basic creator details for attribution in project-level run lists.
Use `GET /api/projects/{project_id}/wizard/runs/?status=created,running&limit=5` to fetch the newest active runs; `count` gives the total number of active runs in the project. The `status` filter also accepts any individual run status.
The optional `created_after` filter limits results and `count` to runs created after an ISO 8601 timestamp.
-On the Wizard page, the run details dialog shows live tasks for the newest active run in the project, or the newest recent run when none are active.
-It finds that run with a fixed launch cutoff on this filter, for active runs and the five newest runs of any status, and checks again every 30 seconds.
-It opens one event stream for an active run. Terminal runs do not open a stream.
+The browser loads project history once without a date or status cutoff.
+While the page is visible, it checks the newest page every five seconds and on tab return, merging discoveries without dropping older runs.
+Starting a cloud run from the Library adds the creation response to shared state immediately, without waiting for a poll.
+Onboarding shows only runs created by the signed-in user.
+Only runs watched by a visible consumer can open event streams, with at most one run stream per tab.
+Every 30 seconds, a bounded fallback refreshes one watched active run and its tasks, rotating through the watched runs.
+Hidden tabs pause polling and streams; terminal runs do not open streams.
+Opening run details or restoring an onboarding run loads its task snapshot and artifacts, including after completion.
+Active streamed updates reuse their task snapshots instead of downloading tasks and artifacts on each update.
+Only the selected onboarding run or open run details request hydration; discovery never retries previously opened runs.
+Failed hydration waits 30 seconds before an automatic retry, and the onboarding retry button bypasses that delay.
+Run details load only tasks into shared state and use the dialog's existing artifact request.
+
+### Onboarding state
+
+Entering onboarding records its start time in local storage, scoped to the project and user.
+The initial time uses the server's HTTP Date header to avoid browser clock skew, falling back to browser time when unavailable.
+Only `posthog-integration` runs created at or after that time can replace the installation instructions.
+The selected ID and creation timestamp are stored in `<project_id>.<user_id>.onboarding_wizard_run_id`.
+The start time is stored in `<project_id>.<user_id>.onboarding_wizard_started_at`.
+Returning to onboarding restores that run in any status; a newer eligible run supersedes it.
+Status updates to an older run do not make it a new installation.
+
+Users can continue onboarding while the setup agent runs.
+Failed runs show the reported error, and local success asks users to review their local changes.
+Failed and canceled runs keep the install command and manual setup available.
+Once a run starts, onboarding keeps its original installation content on the left and shows progress and results on the right.
+The columns stack when the installation container is narrow.
+Dedicated program steps, such as AI observability, do not use the base integration run to replace their instructions or enable Continue.
+Cloud success lists the artifacts and links to the first pull request for review.
+Onboarding does not link to the runs scene; pull-request links open in a new tab so onboarding stays open.
The PATCH request accepts a terminal `status`: `completed`, `failed`, or `cancelled`.
Failed runs can also include an `error_code`.
@@ -156,6 +184,8 @@ Do not add the CLI and service completion events together when counting runs.
The UI records library selections, create requests and failures, table searches, filters and pagination, detail dialog activity, run refreshes, copied run IDs, workspace opens, and artifact clicks.
It also records confirmed cancellation requests and outcomes.
+Onboarding records `wizard onboarding state artifact clicked` for artifact-list links and the review button, with `artifact_type`, `artifact_id`, `click_source`, and shared run properties.
+`click_source` is `artifact_list` or `review_button`; informational Git diffs are not clickable.
Polling does not create more view events. Clipboard failures do not count as command copies.
Use `wizard run create requested` and `wizard run create failed` to measure request failures, including limit responses.
Use `wizard_run_id` to join UI activity to run lifecycle and artifact events.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1e3f5c29f309..247923da4438 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8318,6 +8318,46 @@ snapshots:
hash: v1.k794b7964.c72c7e793f9f3725dc284ac6d8d8a8b39dc864a203eeb2383b23017c9f936612.B5aanH19C7nGRTh8ADjiMQk9BvBIs3dHvELe1DgzA5U
products-web-analytics-heatmaps-page-history-tile--selected-background--light:
hash: v1.k794b7964.b1509fdc1297f04f188ca9d5827ffba9e5c3da92d95359ee35aced109390caac.F7J-6dxSL2B9uVIkexLuxAdzaL4wllQUoIVkkmsu3xw
+ products-wizard-wizard-install-sync--artifact-load-failed--dark:
+ hash: v1.k794b7964.4544d714bd40d6a918e706a912b8a1403bb777b6093ca3033f9840cb2a459621.-foZ64EuvsqINQADzzRdvzo_oko8EZDPRtyOYF50es0
+ products-wizard-wizard-install-sync--artifact-load-failed--light:
+ hash: v1.k794b7964.83132457c1f68328509cbe295917e48a09011fb0a05728b3297be8457f2160d2.pr4EJ0cN4OCdhokfu4LLiyfRMBkel50-YAq-PUShmR0
+ products-wizard-wizard-install-sync--canceled--dark:
+ hash: v1.k794b7964.78e563eb1f323f75ca3d00c185cf2d0ea7dd855edad20fc3a73fda844ba2b85a.zBgfmvL6cpdTwBIJFx5IwsGi1FWY1yV9Sru6bcIkHNI
+ products-wizard-wizard-install-sync--canceled--light:
+ hash: v1.k794b7964.ad0a2662aa6eb34535ee209be7d8fa2a80fcd76f7312dcc4041712b025505500.KRHVXg_SwsqIeQDoqYjCsEAvDBd4BmMOpYjp0dEeRmM
+ products-wizard-wizard-install-sync--completed-locally--dark:
+ hash: v1.k794b7964.d5d947ff7d14131a6c3ee2bcd648618ce27dab08fc8e6c5b44647d050014a5dc.v6OaaTtpQtbuBG0fIMN-2jSn8ZxlOoy2mX4sGyQM3QM
+ products-wizard-wizard-install-sync--completed-locally--light:
+ hash: v1.k794b7964.1f05aff489b2ac839cbbe2eac2c650b8fccead65026fe3158bb07dc605024660.GHMqNK1BhAtspfF404igPRbBPDfSN49rBSWS3wHXtAI
+ products-wizard-wizard-install-sync--failed--dark:
+ hash: v1.k794b7964.2d604f52431dddcb0c4e1ea69911770233e4a601455aeb15de91b76de5874c28.EtzqZU-ihbKJpb5wtFVWwJZ6-uIxfUMEOLfzzUm93uQ
+ products-wizard-wizard-install-sync--failed--light:
+ hash: v1.k794b7964.751f4626bc63d529a4cf950ce129f07d573bb03474c39c8621ab4297c668459f.Df-GH_eLAwHDBJsdpWvvFunuoXNU-7c0OD3HcWB2MyI
+ products-wizard-wizard-install-sync--loading-artifacts--dark:
+ hash: v1.k794b7964.9c7f3e75edbe15b6951ff1335299a78aa6866d0f1b0cd2b49434efb86805119e.SICd6GezQ38ohLHaMtkoOxKgiYqLkN8K1-2wJ1yJCpU
+ products-wizard-wizard-install-sync--loading-artifacts--light:
+ hash: v1.k794b7964.fcc986507301751539abb1f6cdc93bf875569549c3dd1b89db1792dba85a80b6.r2NAiJfA4li00GYj13f-s2v4zkEfBN6fRnRo3cQuEnc
+ products-wizard-wizard-install-sync--many-tasks--dark:
+ hash: v1.k794b7964.1ad7129ba43ec317ad641e2aea7c86434c1c88c2da781fd7717be2459fa4eb78.zPQ8OyhzgTH5-2eNr8j6PuorV9A3iXJ-3wNOt7NQ9rY
+ products-wizard-wizard-install-sync--many-tasks--light:
+ hash: v1.k794b7964.32757af5f502956330c19fb97c11a879370accef51687fd3d34465ad67974a0c.oN5ENYWTB15SMfoOvh4Zz3VRicAHDAlHGXWfRfxkTdY
+ products-wizard-wizard-install-sync--running-with-tasks--dark:
+ hash: v1.k794b7964.bb895d336f44e2951b6824898ddef0b73514445fc3181c1c15c2e0bf49918d3a.jbKHf8wOXxxGlwn0YItYnaSUL9yJhAUJsUASfbv1duY
+ products-wizard-wizard-install-sync--running-with-tasks--light:
+ hash: v1.k794b7964.3e65e46e897219a902b9b0c06a034dafc3b5e3cac544edbe2d345e9570c78242.sY28AKjLxO1TLiti0tFn6Is7M8_jvObAyDhqXf0R9ek
+ products-wizard-wizard-install-sync--running-without-tasks--dark:
+ hash: v1.k794b7964.9f016ff641cf76094179d116e6089c9ea95188f4d0e4f231cd7d8543f3260a93.CcnkuOP_jtsYZqdTaCnaog-fU_Jb5QZb14vFVtM_y4s
+ products-wizard-wizard-install-sync--running-without-tasks--light:
+ hash: v1.k794b7964.cc3dd4c01ebd04d4825c653cd4186fe55e29d8e8de6a7dcec82fa3add034cf7d.iSEEl3kMvKG7am1v0gDrMC4yilON4YzgZPgCeLy5j2Y
+ products-wizard-wizard-install-sync--starting--dark:
+ hash: v1.k794b7964.00dede5b31a8c00f8e8b9aba3a11313840b9e87063affcd588e1188309b1647c.Y1sOD2m1G3h8UXEZE0ChyuHs63OHyg30pvi70DUy9Yk
+ products-wizard-wizard-install-sync--starting--light:
+ hash: v1.k794b7964.f30f870088e7235d19c24969b6e081f19517c5e5dce41ed5396801db806997cb.-bEld1xfDK1oHtbZ4TUcUHA9aXP9sbGkZc2Gm6uGcqU
+ products-wizard-wizard-install-sync--with-artifacts--dark:
+ hash: v1.k794b7964.2ceac48f83d9ee7b806e9a6939927af24bb82934411c39266a2c1d35e5368dcc.Ue6jr1P6Js-Y9H-qQ1jlI5Mlumopo64DP-f7vXuFyMM
+ products-wizard-wizard-install-sync--with-artifacts--light:
+ hash: v1.k794b7964.a3cd76407e3e5d7fee5db0ea4983b81e4f5feaf6c230a64eb087bcaddc80a496.BR4Jr5qmzfXO6SD_XofPDAvlKBMmdwPM9_vmp76bg40
products-wizard-wizard-run-diff-viewer--default--dark:
hash: v1.k794b7964.17c89495f75eed7f73f303b37e9871070e332d1f2b82ff0817f9d1ddd27828c0.bQzhC4f7HDdgFTn6hyiTj0toFWvU9TaivKJpUyOHcBI
products-wizard-wizard-run-diff-viewer--default--light:
@@ -16787,9 +16827,9 @@ snapshots:
scenes-other-integration-landing-page--slack-not-configured--light:
hash: v1.k794b7964.a12f1b2e9bcce6e07f5dc5b8e07821599e77d131e6431727dd04da5f6613ec1c.LZ2zwIHu0AhggyqW-hnQaE1EO6dAgmDI9Xlu2eWTYKM
scenes-other-onboarding--ai-observability-sdk-install--dark:
- hash: v1.k794b7964.99b591d1a81bf5348da5564b8380b3a0f5d2ee720d624fc198a0db099da8605b.Dss3uZ6TjFEIb8TX_b0lrLjmh87ZvqO96RU5LcfAld4
+ hash: v1.k794b7964.5b47373dd1b34bb418867351c6a7c875eafd5a89ff4900bf73d1bbd83bbc4028.rbB41ZhaYlZsUvDAXal7DLOe0wN6pAz3ausHtz8Yx_U
scenes-other-onboarding--ai-observability-sdk-install--light:
- hash: v1.k794b7964.32d9b7b59052431c97def2934189b7c082f55963f2eb90dfe604c29db584ea5b.jWPBTuIG-_5DDjN24_KA1xuwUJnsQnCVYbUMUo_7AzI
+ hash: v1.k794b7964.bfd2e57c7b2e1833c68991c08b74f072ba5c3953b1d7f96aa55f18003bf99880.yjYFLiaQSsqczymSDB3YEFUEDMF5aw3f_94ieLyD30A
scenes-other-onboarding--alerts--dark:
hash: v1.k794b7964.bb15a17dab8c6d94d7fce821c4eb5530e6c5e353a6f158134443b2e77e344b11.uRoH5DqZUWqQzdv8c5pM__vNu1MjSvicrhSdKKREUnw
scenes-other-onboarding--alerts--light:
@@ -16815,9 +16855,9 @@ snapshots:
scenes-other-onboarding--product-analytics-configuration--light:
hash: v1.k794b7964.ab7c6555aac1606b13277bb37e980da9feab594bf84907ed7f341d5567fa3d3c.Sn8H5UIg4w-xvGU41vmCnPdoNaWETZJ_38e9B62rEXw
scenes-other-onboarding--sdk-install--dark:
- hash: v1.k794b7964.3f953504a96f3d295e23721dbd39a6282ce5f719a7b7a50ca2f083c3c061660c.AaYe6HyJOq-J0IDdL_Iu3wJ5kHSSRkg5gIPzqRzB5uo
+ hash: v1.k794b7964.63bc10899dc8449316fff54d82a5eea91abcd01d930e63079fcbfe3a8379acb7.4a5Cj2bUAGVDy3fIEPPZgLdBlS9ruNnOFKD-zGxwIVw
scenes-other-onboarding--sdk-install--light:
- hash: v1.k794b7964.03f1893573652b0c32218385c83819272c30e7a87647ea479aa6c17100efa604.1KE0I10oG1Cfcl7IyLI6n9Wvw_0ipoS21uZhrEJRqvQ
+ hash: v1.k794b7964.53fc654e453b35a52b4a955604d814dba783396a18ad29ccc9f259afd16619d0.pWfwqqomEbXRxxb0wM6B2XJjdolwpP3L0Itma4ep20Y
scenes-other-onboarding--session-replay-configuration--dark:
hash: v1.k794b7964.53a16b04178eb3346c8589d3d51804548580372721faa6517b10bce388e9d45f.Zqg1N7ez03g_PNyRpSEqtbXOOGOqisAftmJAobkUO3c
scenes-other-onboarding--session-replay-configuration--light:
@@ -16847,9 +16887,9 @@ snapshots:
scenes-other-onboarding--workflows-custom-installation-instructions--light:
hash: v1.k794b7964.0edcc48dfab6e88670a09070350f73a96c21d160bf38ea8027f26492fae286fb.oUJvy8bgtNdYIhWFnn5-9uI7PlAkT21f6ExVDx6jANc
scenes-other-onboarding-install-step--control-arm--dark:
- hash: v1.k794b7964.3f953504a96f3d295e23721dbd39a6282ce5f719a7b7a50ca2f083c3c061660c.S12DDcG_kP6-5Y0hlBTZFDKUKAuzTBP9kPXFlqI0umE
+ hash: v1.k794b7964.63bc10899dc8449316fff54d82a5eea91abcd01d930e63079fcbfe3a8379acb7.nbdS-vOGNFf57M9Nu5wqwR3PC-MM_7eq7nSnDGM95XE
scenes-other-onboarding-install-step--control-arm--light:
- hash: v1.k794b7964.03f1893573652b0c32218385c83819272c30e7a87647ea479aa6c17100efa604.Ullr23ou7-8Q_0mO44avKU97VGRSbZGcK96bg8Hlwyk
+ hash: v1.k794b7964.53fc654e453b35a52b4a955604d814dba783396a18ad29ccc9f259afd16619d0.quiFo6I9hNybK-p39LleYzAQ_d5HIu1MtE7i5U8N1Bk
scenes-other-onboarding-install-step--simple-flow--dark:
hash: v1.k794b7964.82e295b93aca26c287b4207345daa25386169a22f859bcf6ffc826dc119fe753.gcs2PUEkwq8sVKLDiV89qsV53RH8PgsAaC1iPJ9WQ04
scenes-other-onboarding-install-step--simple-flow--light:
diff --git a/frontend/src/scenes/onboarding/Onboarding.tsx b/frontend/src/scenes/onboarding/Onboarding.tsx
index a9ce277e931a..8d0c44979673 100644
--- a/frontend/src/scenes/onboarding/Onboarding.tsx
+++ b/frontend/src/scenes/onboarding/Onboarding.tsx
@@ -1,11 +1,13 @@
import './Onboarding.scss'
import clsx from 'clsx'
-import { useValues } from 'kea'
+import { useMountedLogic, useValues } from 'kea'
import { Logo } from 'lib/brand'
import { SceneExport } from 'scenes/sceneTypes'
+import { onboardingWizardRunLogic } from 'products/wizard/frontend/views/onboarding/onboardingWizardRunLogic'
+
import { OnboardingFlowHost } from './OnboardingFlowHost'
import { onboardingLogic } from './onboardingLogic'
import { ProductSelectionShell } from './productSelection/ProductSelectionShell'
@@ -24,7 +26,10 @@ const CARD_CLASSES =
* flow skips product selection.
*/
export function Onboarding(): JSX.Element | null {
- const { productKey, flowVariant } = useValues(onboardingLogic)
+ const { productKey, flowVariant, currentTeam, user } = useValues(onboardingLogic)
+ useMountedLogic(
+ onboardingWizardRunLogic({ projectId: currentTeam ? String(currentTeam.id) : '', userId: user?.id ?? 0 })
+ )
return (
<div className="OnboardingDottedBg min-h-screen flex flex-col items-center justify-center p-4 sm:p-6">
diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.test.tsx b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.test.tsx
index 2ca238415d33..67c0f46dda4b 100644
--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.test.tsx
+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.test.tsx
@@ -1,11 +1,19 @@
+import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from 'lib/api.mock'
+import { installMockEventSource } from 'lib/wizard-sync/eventSource.mock'
+
import '@testing-library/jest-dom'
-import { cleanup, render, screen } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { Provider } from 'kea'
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import type { WizardRunApi } from 'products/wizard/frontend/generated/api.schemas'
+import { wizardRunSyncLogic } from 'products/wizard/frontend/logics/wizardRunSyncLogic'
+
import { VERIFY_AI_EVENTS } from '../../hooks/useInstallationComplete'
import { VariantProps } from '../types'
import { WizardInstallStep } from './index'
@@ -75,23 +83,44 @@ const AIO_PROPS: VariantProps = {
}
describe('WizardInstallStep with wizardOverrides', () => {
+ let restoreEventSource: () => void
beforeEach(() => {
+ localStorage.clear()
useMocks({
get: {
'/api/projects/:team_id/event_definitions': { results: [], count: 0 },
+ '/api/projects/:team_id/wizard/runs/': { results: [], count: 0, next: null },
+ '/api/projects/:team_id/wizard/runs/:run_id/tasks/': { tasks: [] },
+ '/api/projects/:team_id/wizard/runs/:run_id/artifacts/': { results: [], count: 0 },
},
post: {
'/api/environments/:team_id/query': { results: [] },
},
})
initKeaTests()
+ restoreEventSource = installMockEventSource()
})
afterEach(() => {
cleanup()
+ restoreEventSource()
+ localStorage.clear()
})
it('shows the ai-observability command and blocks Continue until installation completes', async () => {
+ const sync = wizardRunSyncLogic({ projectId: String(MOCK_DEFAULT_TEAM.id) })
+ sync.mount()
+ await expectLogic(sync).toFinishAllListeners()
+ sync.actions.runsLoaded([
+ {
+ id: 'base-installation',
+ team_id: MOCK_DEFAULT_TEAM.id,
+ created_by_id: MOCK_DEFAULT_USER.id,
+ program: { id: 'posthog-integration' },
+ status: 'completed',
+ created_at: new Date(Date.now() + 60_000).toISOString(),
+ } as WizardRunApi,
+ ])
render(
<Provider>
<WizardInstallStep {...AIO_PROPS} />
@@ -100,5 +129,180 @@ describe('WizardInstallStep with wizardOverrides', () => {
expect(await screen.findByText((t) => t.includes('ai-observability') && t.includes('npx'))).toBeInTheDocument()
expect(document.querySelector('[data-attr="mock-continue"]')).toHaveAttribute('aria-disabled', 'true')
+ expect(document.querySelector('[data-attr="wizard-install-sync"]')).toBeNull()
+ sync.unmount()
})
+
+ it.each([false, true])(
+ 'allows continuing during setup and keeps result actions in onboarding (compact=%s)',
+ async (compact) => {
+ render(
+ <Provider>
+ <WizardInstallStep
+ {...AIO_PROPS}
+ wizardOverrides={{ ...AIO_PROPS.wizardOverrides!, subcommand: '' }}
+ compact={compact}
+ />
+ </Provider>
+ )
+ const sync = wizardRunSyncLogic({ projectId: String(MOCK_DEFAULT_TEAM.id) })
+ await act(async () => {
+ await expectLogic(sync).toFinishAllListeners()
+ })
+ const createdAt = new Date(Date.now() + 60_000).toISOString()
+ const run: WizardRunApi = {
+ id: 'installation',
+ team_id: MOCK_DEFAULT_TEAM.id,
+ created_by_id: MOCK_DEFAULT_USER.id,
+ status: 'running',
+ stage: 'executing_wizard',
+ created_at: createdAt,
+ updated_at: createdAt,
+ environment: 'local',
+ workspace: { type: 'local_folder', project_name: 'example-project' },
+ program: {
+ id: 'posthog-integration',
+ name: 'PostHog integration',
+ description: '',
+ command: [],
+ wizard_version: '1.0.0',
+ tags: [],
+ required_programs: [],
+ supported_environments: ['local', 'cloud'],
+ },
+ created_by: null,
+ error_code: null,
+ error_message: null,
+ started_at: null,
+ finished_at: null,
+ deadline_at: null,
+ }
+ await act(async () => {
+ sync.actions.runsLoaded([run])
+ await expectLogic(sync).toFinishAllListeners()
+ })
+ expect(document.querySelector('[data-attr="mock-continue"]')).not.toHaveAttribute('aria-disabled')
+ expect(screen.getByText(/You can continue onboarding/)).toBeInTheDocument()
+ expect(screen.queryByText('View run')).not.toBeInTheDocument()
+ expect(screen.getByLabelText('Copy wizard command')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="sdk-continue"]')).toBeInTheDocument()
+
+ await act(async () => {
+ sync.actions.runsLoaded([
+ {
+ ...run,
+ status: 'failed',
+ error_code: 'PHW_DETECT_UNSUPPORTED_VERSION',
+ error_message: 'The project uses an unsupported framework version.',
+ },
+ ])
+ await expectLogic(sync).toFinishAllListeners()
+ })
+ expect(screen.getByText('The project uses an unsupported framework version.')).toBeInTheDocument()
+ expect(screen.getByText('Update the framework, then run the program again.')).toBeInTheDocument()
+ expect(screen.getByLabelText('Copy wizard command')).toBeInTheDocument()
+ fireEvent.click(document.querySelector('[data-attr="sdk-continue"]')!)
+ expect(screen.getByText('Manual SDK setup')).toBeInTheDocument()
+ fireEvent.click(screen.getByLabelText('close'))
+ expect(document.querySelector('[data-attr="mock-continue"]')).toHaveAttribute('aria-disabled', 'true')
+
+ await act(async () => {
+ sync.actions.runsLoaded([{ ...run, status: 'cancelled' }])
+ await expectLogic(sync).toFinishAllListeners()
+ })
+ expect(screen.getByLabelText('Copy wizard command')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="sdk-continue"]')).toBeInTheDocument()
+
+ await act(async () => {
+ sync.actions.runsLoaded([
+ {
+ ...run,
+ id: 'retry',
+ created_at: new Date(Date.now() + 120_000).toISOString(),
+ status: 'completed',
+ },
+ ])
+ await expectLogic(sync).toFinishAllListeners()
+ })
+ expect(screen.getByText(/Review the changes in your local project/)).toBeInTheDocument()
+ expect(screen.getByLabelText('Copy wizard command')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="mock-continue"]')).not.toHaveAttribute('aria-disabled')
+
+ const pullRequestUrl = 'https://github.com/example/project/pull/12'
+ useMocks({
+ get: {
+ '/api/projects/:team_id/wizard/runs/cloud-installation/artifacts/': {
+ count: 2,
+ results: [
+ {
+ id: 'diff',
+ team_id: MOCK_DEFAULT_TEAM.id,
+ run_id: 'cloud-installation',
+ artifact_type: 'git_diff',
+ size_bytes: 2048,
+ content_hash: 'example',
+ additions: 1,
+ removals: 0,
+ created_at: createdAt,
+ },
+ {
+ id: 'pr',
+ team_id: MOCK_DEFAULT_TEAM.id,
+ run_id: 'cloud-installation',
+ artifact_type: 'pull_request',
+ url: pullRequestUrl,
+ number: 12,
+ repository: 'example/project',
+ head_branch: 'setup',
+ base_branch: 'main',
+ created_at: createdAt,
+ },
+ ],
+ },
+ },
+ })
+ await act(async () => {
+ sync.actions.runsLoaded([
+ {
+ ...run,
+ id: 'cloud-installation',
+ created_at: new Date(Date.now() + 180_000).toISOString(),
+ environment: 'cloud',
+ workspace: { type: 'git_repository', repository: 'example/project' },
+ status: 'completed',
+ },
+ ])
+ await expectLogic(sync).toFinishAllListeners()
+ })
+ const reviewLink = screen.getByText('Review pull request').closest('a')
+ expect(reviewLink).toHaveAttribute('href', pullRequestUrl)
+ expect(reviewLink).toHaveAttribute('target', '_blank')
+ expect(screen.getByText('Git diff (2.0 KB)').closest('a')).toBeNull()
+ expect(document.querySelector('[data-attr="wizard-install-sync"] a[href*="/wizard/runs"]')).toBeNull()
+ fireEvent.click(document.querySelector('[data-attr="wizard-install-artifact"]')!)
+ fireEvent.click(reviewLink!)
+ for (const clickSource of ['artifact_list', 'review_button']) {
+ expect(posthog.capture).toHaveBeenCalledWith(
+ 'wizard onboarding state artifact clicked',
+ expect.objectContaining({
+ event_source: 'wizard_ui',
+ project_id: String(MOCK_DEFAULT_TEAM.id),
+ wizard_run_id: 'cloud-installation',
+ task_run_id: 'cloud-installation',
+ environment: 'cloud',
+ program_id: 'posthog-integration',
+ status: 'completed',
+ artifact_type: 'pull_request',
+ artifact_id: 'pr',
+ click_source: clickSource,
+ })
+ )
+ }
+ const artifactEvents = jest
+ .mocked(posthog.capture)
+ .mock.calls.filter(([event]) => event === 'wizard onboarding state artifact clicked')
+ expect(artifactEvents).toHaveLength(2)
+ expect(JSON.stringify(artifactEvents)).not.toContain(pullRequestUrl)
+ }
+ )
})
diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx
index 91b161178698..d29ba19af042 100644
--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx
+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx
@@ -2,8 +2,15 @@ import { useActions, useValues } from 'kea'
import { LemonButton, LemonModal, Link } from '@posthog/lemon-ui'
+import { teamLogic } from 'scenes/teamLogic'
+import { userLogic } from 'scenes/userLogic'
+
import { OnboardingStepKey, type SDK } from '~/types'
+import { wizardRunIsActive } from 'products/wizard/frontend/lib/wizardRunDisplay'
+import { onboardingWizardRunLogic } from 'products/wizard/frontend/views/onboarding/onboardingWizardRunLogic'
+import { WizardInstallSync } from 'products/wizard/frontend/views/onboarding/WizardInstallSync'
+
import { OnboardingStep } from '../../../OnboardingStep'
import { useWizardCommand } from '../../../shared/useWizardCommand'
import { WizardCommandBlock } from '../../../shared/wizard-command/WizardCommandBlock'
@@ -61,34 +68,53 @@ function OnboardingInstallOptions({
*/
export function WizardInstallStep(props: VariantProps): JSX.Element {
const { setManualModalOpen } = useActions(wizardInstallStepLogic)
+ const { currentTeam } = useValues(teamLogic)
+ const { user } = useValues(userLogic)
+ const projectId = !props.wizardOverrides?.subcommand && currentTeam?.id ? String(currentTeam.id) : null
+ const { run } = useValues(onboardingWizardRunLogic({ projectId: projectId ?? '', userId: user?.id ?? 0 }))
+ const canContinue = props.installationComplete || (!!run && (wizardRunIsActive(run) || run.status === 'completed'))
return (
<WizardInstallShell
- continueDisabledReason={props.installationComplete ? undefined : 'Installation is not complete'}
- showSkip={!props.installationComplete}
+ continueDisabledReason={canContinue ? undefined : 'Installation is not complete'}
+ showSkip={!canContinue}
props={props}
>
{props.compact ? (
- <WizardModeShell data-attr="wizard-install-compact">
- <p className="text-muted mb-0">
- {props.wizardOverrides?.intro ??
- 'Wizard is a setup agent. It detects your framework, installs the SDK, and adds your project token to your environment variables.'}
- </p>
- <OnboardingInstallOptions wizardOverrides={props.wizardOverrides} compact />
- <Link
- className="self-start text-sm"
- data-attr="sdk-continue"
- onClick={() => setManualModalOpen(true)}
- >
- Want to set up manually?
- </Link>
- </WizardModeShell>
+ <WizardInstallSync projectId={projectId}>
+ <WizardModeShell data-attr="wizard-install-compact">
+ <p className="text-muted mb-0">
+ {props.wizardOverrides?.intro ??
+ 'Wizard is a setup agent. It detects your framework, installs the SDK, and adds your project token to your environment variables.'}
+ </p>
+ <OnboardingInstallOptions wizardOverrides={props.wizardOverrides} compact />
+ <Link
+ className="self-start text-sm"
+ data-attr="sdk-continue"
+ onClick={() => setManualModalOpen(true)}
+ >
+ Want to set up manually?
+ </Link>
+ </WizardModeShell>
+ </WizardInstallSync>
) : (
- <>
- <WizardInstallIntro description={props.wizardOverrides?.intro} />
- <div className="max-w-xl mx-auto">
- <OnboardingInstallOptions wizardOverrides={props.wizardOverrides} />
- </div>
- </>
+ <WizardInstallSync projectId={projectId}>
+ <>
+ <WizardInstallIntro description={props.wizardOverrides?.intro} />
+ <div className="max-w-xl mx-auto">
+ <OnboardingInstallOptions wizardOverrides={props.wizardOverrides} />
+ </div>
+ <div className="flex justify-center">
+ <LemonButton
+ type="tertiary"
+ size="small"
+ data-attr="sdk-continue"
+ onClick={() => setManualModalOpen(true)}
+ >
+ Need to set up manually?
+ </LemonButton>
+ </div>
+ </>
+ </WizardInstallSync>
)}
</WizardInstallShell>
)
@@ -142,22 +168,7 @@ function WizardInstallShell({
>
{header}
{!installationComplete && <AdblockWarning adblockResult={adblockResult} />}
- <div className="mt-6 space-y-8">
- {children}
- {/* The compact layout puts this link in the Wizard column instead. */}
- {!props.compact && (
- <div className="flex justify-center">
- <LemonButton
- type="tertiary"
- size="small"
- data-attr="sdk-continue"
- onClick={() => setManualModalOpen(true)}
- >
- Need to set up manually?
- </LemonButton>
- </div>
- )}
- </div>
+ <div className="mt-6 space-y-8">{children}</div>
<LemonModal
isOpen={manualModalOpen}
diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardInstallStepLogic.ts b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardInstallStepLogic.ts
index b61eabf803a9..9e88a9d2eaf6 100644
--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardInstallStepLogic.ts
+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardInstallStepLogic.ts
@@ -1,4 +1,5 @@
-import { MakeLogicType, actions, kea, path, reducers } from 'kea'
+import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
+import posthog from 'posthog-js'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface wizardInstallStepLogicValues {
@@ -38,4 +39,11 @@ export const wizardInstallStepLogic = kea<wizardInstallStepLogicType>([
},
],
}),
+ listeners({
+ setManualModalOpen: ({ open }) => {
+ if (open) {
+ posthog.capture('wizard manual setup opened', { event_source: 'wizard_ui', location: 'onboarding' })
+ }
+ },
+ }),
])
diff --git a/frontend/src/scenes/onboarding/shared/wizard-command/WizardCommandBlock.tsx b/frontend/src/scenes/onboarding/shared/wizard-command/WizardCommandBlock.tsx
index 76c2ca576944..913134a0c2a1 100644
--- a/frontend/src/scenes/onboarding/shared/wizard-command/WizardCommandBlock.tsx
+++ b/frontend/src/scenes/onboarding/shared/wizard-command/WizardCommandBlock.tsx
@@ -1,3 +1,4 @@
+import posthog from 'posthog-js'
import { type ReactNode, useState } from 'react'
import { CommandBlock } from 'lib/components/CommandBlock/CommandBlock'
@@ -35,7 +36,13 @@ export function WizardCommandBlock({
size="md"
decoration="rainbow"
className="bg-bg-light border border-border hover:border-primary"
- onCopy={(key) => setCastKey(key)}
+ onCopy={(key) => {
+ setCastKey(key)
+ posthog.capture('wizard command copy requested', {
+ event_source: 'wizard_ui',
+ command: subcommand ?? 'default',
+ })
+ }}
// A subcommand pushes the displayed command past one line.
condensed={!!subcommand}
/>
diff --git a/products/wizard/frontend/components/run-tags/WizardRunStatusIcon.tsx b/products/wizard/frontend/components/run-tags/WizardRunStatusIcon.tsx
new file mode 100644
index 000000000000..35d28a4c8314
--- /dev/null
+++ b/products/wizard/frontend/components/run-tags/WizardRunStatusIcon.tsx
@@ -0,0 +1,17 @@
+import { IconCheckCircle, IconClock, IconXCircle } from '@posthog/icons'
+import { Spinner } from '@posthog/lemon-ui'
+
+import type { WizardRunApi } from '../../generated/api.schemas'
+
+export function WizardRunStatusIcon({ status }: { status: WizardRunApi['status'] }): JSX.Element {
+ if (status === 'completed') {
+ return <IconCheckCircle className="text-success" />
+ }
+ if (status === 'failed' || status === 'cancelled') {
+ return <IconXCircle className="text-danger" />
+ }
+ if (status === 'running') {
+ return <Spinner textColored />
+ }
+ return <IconClock className="text-muted" />
+}
diff --git a/products/wizard/frontend/lib/wizardApi.test.ts b/products/wizard/frontend/lib/wizardApi.test.ts
new file mode 100644
index 000000000000..c41ab433d892
--- /dev/null
+++ b/products/wizard/frontend/lib/wizardApi.test.ts
@@ -0,0 +1,35 @@
+import api from 'lib/api'
+
+import { SERVER_CLOCK_TIMEOUT_MS, loadWizardOnboardingStartTime } from './wizardApi'
+
+jest.mock('lib/api', () => ({ __esModule: true, default: { getResponse: jest.fn() } }))
+
+describe('Wizard onboarding server clock', () => {
+ afterEach(() => jest.useRealTimers())
+
+ it.each(['ahead', 'behind', 'missing', 'offline', 'stalled'])(
+ 'uses server time with an %s browser clock or falls back when unavailable',
+ async (clock) => {
+ jest.useFakeTimers()
+ const serverTime = '2026-09-23T10:00:00.000Z'
+ const browserTime = Date.parse(serverTime) + (clock === 'behind' ? -60_000 : 60_000)
+ jest.setSystemTime(browserTime)
+ jest.mocked(api.getResponse).mockImplementationOnce(async (_url, options) => {
+ if (clock === 'offline') {
+ throw new Error('offline')
+ }
+ if (clock === 'stalled') {
+ return await new Promise<Response>((_resolve, reject) =>
+ options?.signal?.addEventListener('abort', () => reject(new Error('aborted')))
+ )
+ }
+ return new Response(null, { headers: clock === 'missing' ? {} : { Date: serverTime } })
+ })
+ const startTime = loadWizardOnboardingStartTime('1')
+ await jest.advanceTimersByTimeAsync(SERVER_CLOCK_TIMEOUT_MS)
+ expect(await startTime).toBe(
+ clock === 'ahead' || clock === 'behind' ? serverTime : new Date(browserTime).toISOString()
+ )
+ }
+ )
+})
diff --git a/products/wizard/frontend/lib/wizardApi.ts b/products/wizard/frontend/lib/wizardApi.ts
index 4aa7092b44a0..6b7dd722d2be 100644
--- a/products/wizard/frontend/lib/wizardApi.ts
+++ b/products/wizard/frontend/lib/wizardApi.ts
@@ -1,8 +1,36 @@
import api from 'lib/api'
-import { getWizardRunsArtifactsContentRetrieveUrl, wizardRunsArtifactsList } from '../generated/api'
+import {
+ getWizardRunsArtifactsContentRetrieveUrl,
+ getWizardRunsListUrl,
+ wizardRunsArtifactsList,
+} from '../generated/api'
import type { WizardRunArtifactApi } from '../generated/api.schemas'
+// Onboarding waits for the server clock before it can select a run, so a stalled request must fall back.
+export const SERVER_CLOCK_TIMEOUT_MS = 5000
+
+export async function loadWizardOnboardingStartTime(projectId: string): Promise<string> {
+ const startedAt = Date.now()
+ const controller = new AbortController()
+ const timeout = setTimeout(() => controller.abort(), SERVER_CLOCK_TIMEOUT_MS)
+ try {
+ // nosemgrep: prefer-codegen-api -- The generated client returns only JSON, and onboarding also needs the server clock from the Date header.
+ const response = await api.getResponse(getWizardRunsListUrl(projectId, { limit: 1 }), {
+ signal: controller.signal,
+ })
+ const serverTime = Date.parse(response.headers.get('Date') ?? '')
+ if (Number.isFinite(serverTime)) {
+ return new Date(serverTime - (Date.now() - startedAt)).toISOString()
+ }
+ } catch {
+ // Keep manual installation available when discovery is offline.
+ } finally {
+ clearTimeout(timeout)
+ }
+ return new Date(startedAt).toISOString()
+}
+
export async function loadWizardRunArtifacts(projectId: string, runId: string): Promise<WizardRunArtifactApi[]> {
return (await wizardRunsArtifactsList(projectId, runId)).results
}
diff --git a/products/wizard/frontend/lib/wizardRunDisplay.test.ts b/products/wizard/frontend/lib/wizardRunDisplay.test.ts
index 2b6603976017..b2238e66fa0c 100644
--- a/products/wizard/frontend/lib/wizardRunDisplay.test.ts
+++ b/products/wizard/frontend/lib/wizardRunDisplay.test.ts
@@ -3,6 +3,7 @@ import {
WizardRunProgressStep,
wizardGithubRepositoryUrl,
wizardRunCanCancel,
+ selectWizardInstallRun,
wizardRunFailureStage,
wizardRunProgressStates,
wizardRunProgressStep,
@@ -109,6 +110,71 @@ describe('wizardRunProgressStates', () => {
})
})
+describe('selectWizardInstallRun', () => {
+ test('shows the newest run regardless of environment or status', () => {
+ const completedCloud = makeRun({
+ id: 'cloud-completed',
+ status: 'completed',
+ environment: 'cloud',
+ created_at: '2026-09-23T10:00:00Z',
+ })
+ const runningLocal = makeRun({
+ id: 'local-running',
+ status: 'running',
+ environment: 'local',
+ created_at: '2026-09-23T10:05:00Z',
+ })
+
+ expect(selectWizardInstallRun([completedCloud, runningLocal], '2026-09-23T09:00:00Z')).toBe(runningLocal)
+ expect(selectWizardInstallRun([runningLocal, completedCloud], '2026-09-23T09:00:00Z')).toBe(runningLocal)
+ })
+
+ test('returns the newest completed run when that is all there is', () => {
+ const run = makeRun({
+ id: 'local-completed',
+ status: 'completed',
+ environment: 'local',
+ created_at: '2026-09-23T10:00:00Z',
+ })
+
+ expect(selectWizardInstallRun([run], '2026-09-23T09:00:00Z')).toBe(run)
+ })
+
+ test('ignores runs created before the cutoff', () => {
+ const oldRun = makeRun({
+ id: 'old-run',
+ created_at: '2026-09-23T09:00:00Z',
+ })
+ const recentRun = makeRun({
+ id: 'recent-run',
+ created_at: '2026-09-23T10:00:00Z',
+ })
+
+ expect(selectWizardInstallRun([recentRun, oldRun], '2026-09-23T09:30:00Z')).toBe(recentRun)
+ expect(selectWizardInstallRun([oldRun], '2026-09-23T09:30:00Z')).toBeNull()
+ })
+
+ test('returns null when there are no runs', () => {
+ expect(selectWizardInstallRun([], '2026-09-23T09:00:00Z')).toBeNull()
+ })
+
+ test('ignores audit programs and compares creation time, not update time, against the saved run', () => {
+ const saved = makeRun({ id: 'saved', created_at: '2026-09-23T10:00:00Z' })
+ const older = makeRun({ id: 'older', created_at: '2026-09-23T09:30:00Z', updated_at: '2026-09-23T11:00:00Z' })
+ const audit = makeRun({
+ ...saved,
+ id: 'audit',
+ program: { ...saved.program, id: 'analytics-audit' },
+ created_at: '2026-09-23T12:00:00Z',
+ })
+ expect(selectWizardInstallRun([audit, older, saved], '2026-09-23T09:00:00Z', saved)).toBe(saved)
+ expect(selectWizardInstallRun([audit, older], '2026-09-23T09:00:00Z', saved)).toBeNull()
+
+ const newer = makeRun({ id: 'newer', created_at: '2026-09-23T10:30:00+00:00' })
+ expect(selectWizardInstallRun([saved, newer], '2026-09-23T09:00:00Z', saved)).toBe(newer)
+ })
+})
+
describe('wizardGithubRepositoryUrl', () => {
test('builds the GitHub URL for a repository', () => {
expect(wizardGithubRepositoryUrl('posthog/posthog')).toBe('https://github.com/posthog/posthog')
diff --git a/products/wizard/frontend/lib/wizardRunDisplay.ts b/products/wizard/frontend/lib/wizardRunDisplay.ts
index 2a521895a6ec..503bed00ad20 100644
--- a/products/wizard/frontend/lib/wizardRunDisplay.ts
+++ b/products/wizard/frontend/lib/wizardRunDisplay.ts
@@ -1,4 +1,7 @@
+import { elapsedSecondsFrom } from 'lib/utils/datetime'
+
import { WizardRunApi, WizardRunStageEnumApi } from '../generated/api.schemas'
+import type { WizardRunTaskApi } from '../generated/api.schemas'
import { wizardRunErrorDetails } from './wizardRunErrorCatalog'
export const MAX_RENDERED_WIZARD_DIFF_BYTES = 2 * 1024 * 1024
@@ -177,3 +180,45 @@ export function wizardRunCurrentState(run: WizardRunApi): string {
return run.status === 'running' ? 'Running the Wizard' : 'Starting the Wizard run'
}
}
+
+export function selectWizardInstallRun(
+ runs: WizardRunApi[],
+ onboardingStartedAt: string,
+ savedRun: Pick<WizardRunApi, 'id' | 'created_at'> | null = null
+): WizardRunApi | null {
+ const eligibleRuns = runs.filter(
+ (run) =>
+ run.program.id === 'posthog-integration' && Date.parse(run.created_at) >= Date.parse(onboardingStartedAt)
+ )
+ const newestRun = eligibleRuns.reduce<WizardRunApi | null>(
+ (newest, run) => (!newest || Date.parse(run.created_at) > Date.parse(newest.created_at) ? run : newest),
+ null
+ )
+
+ // Compare creation times so an older run's status update cannot replace the saved installation.
+ if (savedRun && (!newestRun || Date.parse(newestRun.created_at) <= Date.parse(savedRun.created_at))) {
+ return eligibleRuns.find((run) => run.id === savedRun.id) ?? null
+ }
+ return newestRun
+}
+
+export function wizardRunActivityLabel(run: WizardRunApi, tasks: readonly WizardRunTaskApi[]): string {
+ if (run.status === 'running' && wizardRunProgressStep(run) === WizardRunProgressStep.ExecutingWizard) {
+ return tasks.find((task) => task.status === 'running')?.name ?? wizardRunCurrentState(run)
+ }
+ return wizardRunCurrentState(run)
+}
+
+export function wizardRunElapsedSeconds(run: WizardRunApi, now: number): number {
+ const end = run.finished_at ? new Date(run.finished_at).getTime() : now
+ return elapsedSecondsFrom(run.started_at ?? run.created_at, end)
+}
+
+export function formatWizardRunElapsed(seconds: number): string {
+ const minutes = Math.floor(seconds / 60)
+ const remainder = seconds % 60
+ if (minutes >= 60) {
+ return `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, '0')}:${String(remainder).padStart(2, '0')}`
+ }
+ return `${String(minutes).padStart(2, '0')}:${String(remainder).padStart(2, '0')}`
+}
diff --git a/products/wizard/frontend/logics/wizardLibraryLogic.test.tsx b/products/wizard/frontend/logics/wizardLibraryLogic.test.tsx
index 32621110a965..66cca1389856 100644
--- a/products/wizard/frontend/logics/wizardLibraryLogic.test.tsx
+++ b/products/wizard/frontend/logics/wizardLibraryLogic.test.tsx
@@ -1,3 +1,6 @@
+import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+import { installMockEventSource } from 'lib/wizard-sync/eventSource.mock'
+
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { Provider } from 'kea'
import { expectLogic } from 'kea-test-utils'
@@ -16,6 +19,7 @@ import { wizardRegistryList, wizardRunsCreate } from '../generated/api'
import type { WizardProgramApi, WizardRunApi } from '../generated/api.schemas'
import { wizardLibraryLogic } from './wizardLibraryLogic'
import { wizardRunDetailsLogic } from './wizardRunDetailsLogic'
+import { wizardRunSyncLogic } from './wizardRunSyncLogic'
jest.mock('lib/utils/copyToClipboard', () => ({
copyToClipboard: jest.fn(),
@@ -25,6 +29,8 @@ jest.mock('../generated/api', () => ({
wizardRegistryList: jest.fn(),
wizardRunsCreate: jest.fn(),
wizardRunsList: jest.fn().mockResolvedValue({ count: 0, next: null, previous: null, results: [] }),
+ getWizardRunsStreamRetrieveUrl: (projectId: string, runId: string) =>
+ `/api/projects/${projectId}/wizard/runs/${runId}/stream/`,
}))
const mockWizardRegistryList = wizardRegistryList as jest.Mock
@@ -212,23 +218,35 @@ describe('wizardLibraryLogic', () => {
expect(mockWizardRunsCreate).not.toHaveBeenCalled()
})
- it('follows the new run after a successful start', async () => {
- const createdRun = makeRun()
+ it('follows the new run and updates shared run state immediately after a successful start', async () => {
+ const projectId = String(projectLogic.values.currentProjectId)
+ const createdRun = makeRun({ team_id: Number(projectId), created_by_id: MOCK_DEFAULT_USER.id })
mockWizardRunsCreate.mockResolvedValueOnce(createdRun)
+ const restoreEventSource = installMockEventSource()
+ const sync = wizardRunSyncLogic({ projectId })
+ sync.mount()
+ await expectLogic(sync).toFinishAllListeners()
const detailsLogic = wizardRunDetailsLogic()
detailsLogic.mount()
- logic.actions.openLibrary()
- logic.actions.selectProgram(program)
- logic.actions.setRepository('posthog/posthog')
-
- logic.actions.createRun()
- await expectLogic(logic).toFinishAllListeners()
-
- expect(detailsLogic.values.selectedRunSummary?.id).toBe('run-new')
- expect(posthog.capture).not.toHaveBeenCalledWith('wizard run create succeeded', expect.anything())
- expect(posthog.capture).not.toHaveBeenCalledWith('setup wizard finished', expect.anything())
- expect(JSON.stringify(jest.mocked(posthog.capture).mock.calls)).not.toContain('example/private-project')
- detailsLogic.unmount()
+ try {
+ logic.actions.openLibrary()
+ logic.actions.selectProgram(program)
+ logic.actions.setRepository('posthog/posthog')
+
+ logic.actions.createRun()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(detailsLogic.values.selectedRunSummary?.id).toBe('run-new')
+ expect(sync.values.userRuns).toEqual([createdRun])
+ expect(sync.values.activeUserRuns).toEqual([createdRun])
+ expect(posthog.capture).not.toHaveBeenCalledWith('wizard run create succeeded', expect.anything())
+ expect(posthog.capture).not.toHaveBeenCalledWith('setup wizard finished', expect.anything())
+ expect(JSON.stringify(jest.mocked(posthog.capture).mock.calls)).not.toContain('example/private-project')
+ } finally {
+ detailsLogic.unmount()
+ sync.unmount()
+ restoreEventSource()
+ }
})
it('selects the retried program after the registry reloads', async () => {
diff --git a/products/wizard/frontend/logics/wizardLibraryLogic.ts b/products/wizard/frontend/logics/wizardLibraryLogic.ts
index 067bb8bd5644..19321e2ad476 100644
--- a/products/wizard/frontend/logics/wizardLibraryLogic.ts
+++ b/products/wizard/frontend/logics/wizardLibraryLogic.ts
@@ -24,6 +24,7 @@ import { wizardEventProperties, wizardRunEventProperties } from '../lib/wizardAn
import { WIZARD_LOCAL_RUNS_VISIBLE, wizardCommand } from '../lib/wizardRunDisplay'
import { type WizardRunDetailSource, wizardRunDetailsLogic } from './wizardRunDetailsLogic'
import { wizardRunsLogic } from './wizardRunsLogic'
+import { wizardRunSyncLogic } from './wizardRunSyncLogic'
function requestError(error: unknown, fallback: string): string {
return error instanceof ApiError && error.detail ? error.detail : fallback
@@ -433,6 +434,9 @@ export const wizardLibraryLogic = kea<wizardLibraryLogicType>([
// Follow the new run in the drawer so the old failed run cannot reappear.
if (createRunRequest) {
+ wizardRunSyncLogic
+ .findMounted({ projectId: String(createRunRequest.team_id) })
+ ?.actions.runsLoaded([createRunRequest], true)
actions.selectRun(createRunRequest, 'wizard_library')
}
diff --git a/products/wizard/frontend/logics/wizardRunSyncLogic.test.ts b/products/wizard/frontend/logics/wizardRunSyncLogic.test.ts
index fc347c010d7e..3e8cc813f510 100644
--- a/products/wizard/frontend/logics/wizardRunSyncLogic.test.ts
+++ b/products/wizard/frontend/logics/wizardRunSyncLogic.test.ts
@@ -1,29 +1,52 @@
+import { MOCK_DEFAULT_USER } from 'lib/api.mock'
import { installMockEventSource, MockEventSource } from 'lib/wizard-sync/eventSource.mock'
import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
-import { wizardRunsList } from '../generated/api'
-import type { WizardRunApi } from '../generated/api.schemas'
+import { wizardRunsList, wizardRunsRetrieve, wizardRunsTasksRetrieve } from '../generated/api'
+import type {
+ WizardRunApi,
+ WizardRunArtifactApi,
+ WizardRunTaskApi,
+ WizardRunTaskListApi,
+} from '../generated/api.schemas'
+import { loadWizardRunArtifacts } from '../lib/wizardApi'
import { wizardRunSyncLogic } from './wizardRunSyncLogic'
jest.mock('../generated/api', () => ({
wizardRunsList: jest.fn(),
+ wizardRunsRetrieve: jest.fn(),
+ wizardRunsTasksRetrieve: jest.fn().mockResolvedValue({ tasks: [] }),
getWizardRunsStreamRetrieveUrl: (projectId: string, runId: string) =>
`/api/projects/${projectId}/wizard/runs/${runId}/stream/`,
}))
+jest.mock('../lib/wizardApi', () => ({
+ loadWizardRunArtifacts: jest.fn().mockResolvedValue([]),
+}))
+
const mockWizardRunsList = wizardRunsList as jest.Mock
function mockRunPages(activePage: { count: number; results: WizardRunApi[] }, recentRuns: WizardRunApi[] = []): void {
- mockWizardRunsList.mockImplementation((_projectId, { status }) =>
- Promise.resolve(status ? activePage : { count: recentRuns.length, results: recentRuns })
- )
+ const results = [
+ ...activePage.results,
+ ...recentRuns.filter((recent) => !activePage.results.some((active) => active.id === recent.id)),
+ ]
+ mockWizardRunsList.mockResolvedValue({ count: results.length, results })
}
function run(id: string): WizardRunApi {
- return { id, status: 'running', stage: 'executing_wizard' } as WizardRunApi
+ return {
+ id,
+ team_id: 1,
+ status: 'running',
+ stage: 'executing_wizard',
+ created_by_id: MOCK_DEFAULT_USER.id,
+ created_at: '2026-09-23T10:00:00Z',
+ updated_at: '2026-09-23T10:01:00Z',
+ } as WizardRunApi
}
describe('wizardRunSyncLogic', () => {
@@ -37,27 +60,24 @@ describe('wizardRunSyncLogic', () => {
mockRunPages({ count: 2, results: [run('newer')] })
logic = wizardRunSyncLogic({ projectId: '1' })
logic.mount()
+ logic.actions.watchRuns('test', ['newer'])
})
afterEach(() => {
logic.unmount()
restoreEventSource()
jest.restoreAllMocks()
+ jest.useRealTimers()
})
- it('streams only the newest active run and switches when it changes', async () => {
+ it('streams the active run and switches when it changes', async () => {
await expectLogic(logic).toFinishAllListeners()
expect(mockWizardRunsList).toHaveBeenCalledWith('1', {
- status: ['created', 'running'],
- created_after: '2026-09-28T00:00:00Z',
- limit: 5,
- })
- expect(mockWizardRunsList).toHaveBeenCalledWith('1', {
- created_after: '2026-09-28T00:00:00Z',
- limit: 5,
+ limit: 100,
+ offset: 0,
})
- expect(logic.values.run?.id).toBe('newer')
+ expect(logic.values.userRuns[0]?.id).toBe('newer')
expect(MockEventSource.instances).toHaveLength(1)
const firstStream = MockEventSource.last()
@@ -68,16 +88,41 @@ describe('wizardRunSyncLogic', () => {
tasks: [{ name: 'Install SDK', status: 'running' }],
})
)
- expect(logic.values.tasks).toEqual([{ name: 'Install SDK', status: 'running' }])
+ expect(logic.values.tasksByRunId.newer).toEqual([{ name: 'Install SDK', status: 'running' }])
mockRunPages({ count: 1, results: [run('older')] })
+ logic.actions.watchRuns('test', ['older'])
logic.actions.checkRuns()
await expectLogic(logic).toFinishAllListeners()
expect(firstStream.readyState).toBe(MockEventSource.CLOSED)
expect(MockEventSource.instances).toHaveLength(2)
expect(MockEventSource.last().url).toBe('/api/projects/1/wizard/runs/older/stream/')
- expect(logic.values.tasks).toEqual([])
+ expect(logic.values.tasksByRunId.older).toBeUndefined()
+ })
+
+ it('caps streams and polls the remaining watched runs without mixing their tasks', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ const older = run('older')
+ mockRunPages({ count: 2, results: [run('newer'), older] }, [run('newer'), older])
+ logic.actions.checkRuns()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.watchRuns('test', ['newer', 'older'])
+
+ expect(logic.values.activeUserRuns.map((activeRun) => activeRun.id)).toEqual(['newer', 'older'])
+ expect(MockEventSource.instances).toHaveLength(1)
+ jest.mocked(wizardRunsRetrieve).mockResolvedValueOnce(run('newer')).mockResolvedValueOnce(older)
+ jest.mocked(wizardRunsTasksRetrieve)
+ .mockResolvedValueOnce({ tasks: [] })
+ .mockResolvedValueOnce({ tasks: [{ name: 'Add events', status: 'running' } as WizardRunTaskApi] })
+ logic.actions.refreshWatchedRun()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.refreshWatchedRun()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.tasksByRunId.older).toEqual([{ name: 'Add events', status: 'running' }])
+ expect(logic.values.runs.find((r) => r.id === 'older')?.status).toBe('running')
+ expect(logic.values.tasksByRunId.newer).toEqual([])
})
it.each(['completed', 'failed', 'cancelled'] as const)(
@@ -90,42 +135,240 @@ describe('wizardRunSyncLogic', () => {
stream.emitMessage(JSON.stringify({ status, stage: null, tasks: [] }))
await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.run?.status).toBe(status)
+ expect(logic.values.userRuns[0]?.status).toBe(status)
expect(stream.readyState).toBe(MockEventSource.CLOSED)
logic.unmount()
logic = wizardRunSyncLogic({ projectId: '1' })
logic.mount()
+ logic.actions.watchRuns('test', ['next'])
await expectLogic(logic).toFinishAllListeners()
expect(mockWizardRunsList).toHaveBeenCalledWith('1', {
- created_after: '2026-09-28T00:00:00Z',
- limit: 5,
+ limit: 100,
+ offset: 0,
})
- expect(logic.values.run).toEqual(terminal)
+ expect(logic.values.userRuns).toEqual([terminal])
expect(MockEventSource.instances).toHaveLength(1)
mockRunPages({ count: 1, results: [run('next')] }, [terminal])
logic.actions.checkRuns()
await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.run?.id).toBe('next')
+ expect(logic.values.userRuns[0]?.id).toBe('next')
expect(MockEventSource.instances).toHaveLength(2)
}
)
- it('handles a run completing between the active and completed responses', async () => {
+ it('ignores runs created by other users', async () => {
await expectLogic(logic).toFinishAllListeners()
- mockRunPages({ count: 1, results: [run('newer')] }, [run('newer')])
+ const initialStream = MockEventSource.last()
+ const otherUserRun = { ...run('other-user'), created_by_id: MOCK_DEFAULT_USER.id + 1 }
+ mockRunPages({ count: 1, results: [otherUserRun] })
logic.actions.checkRuns()
await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.runs.map((run) => run.id)).toEqual(['newer'])
+ expect(logic.values.userRuns).toEqual([])
+ expect(logic.values.activeUserRuns).toEqual([])
+ expect(initialStream.readyState).toBe(MockEventSource.CLOSED)
+ })
+
+ it('keeps a completed run in the list', async () => {
+ await expectLogic(logic).toFinishAllListeners()
const completed = { ...run('newer'), status: 'completed' as const, stage: null }
- mockRunPages({ count: 1, results: [run('newer')] }, [completed])
+ mockRunPages({ count: 1, results: [completed] })
logic.actions.checkRuns()
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.runs).toEqual([completed])
- expect(logic.values.run?.status).toBe('completed')
+ expect(logic.values.userRuns[0]?.status).toBe('completed')
expect(MockEventSource.last().readyState).toBe(MockEventSource.CLOSED)
})
+
+ it('loads history once and bounds recurring requests to the recent page', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ logic.unmount()
+ jest.useFakeTimers()
+ logic = wizardRunSyncLogic({ projectId: '1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ mockWizardRunsList
+ .mockResolvedValueOnce({ results: [run('first')], next: '/next' })
+ .mockResolvedValueOnce({ results: [run('second')], next: null })
+ logic.actions.checkRuns()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockWizardRunsList).toHaveBeenLastCalledWith('1', { limit: 100, offset: 100 })
+ expect(logic.values.userRuns.map((run) => run.id)).toEqual(['first', 'second'])
+ const previousCalls = mockWizardRunsList.mock.calls.length
+ mockWizardRunsList.mockResolvedValue({ results: [run('first')], next: '/next' })
+ for (let poll = 0; poll < 6; poll++) {
+ jest.advanceTimersByTime(5_000)
+ await expectLogic(logic).toFinishAllListeners()
+ }
+ expect(mockWizardRunsList.mock.calls.length - previousCalls).toBe(6)
+ expect(mockWizardRunsList).toHaveBeenLastCalledWith('1', { limit: 100, offset: 0 })
+ expect(logic.values.userRuns.map((run) => run.id)).toEqual(['first', 'second'])
+ })
+
+ it.each(['poll', 'focus'])(
+ 'discovers local runs promptly on %s without dropping older history',
+ async (trigger) => {
+ await expectLogic(logic).toFinishAllListeners()
+ logic.unmount()
+ jest.useFakeTimers()
+ logic = wizardRunSyncLogic({ projectId: '1' })
+ logic.mount()
+ logic.actions.watchRuns('test', ['local-installation'])
+ await expectLogic(logic).toFinishAllListeners()
+ const history = { ...run('history'), status: 'completed' as const }
+ logic.actions.runsLoaded([run('newer'), history])
+ const localRun = { ...run('local-installation'), environment: 'local' as const }
+ mockWizardRunsList.mockResolvedValue({ results: [localRun], next: '/older-runs' })
+ const previousCalls = mockWizardRunsList.mock.calls.length
+
+ if (trigger === 'poll') {
+ jest.advanceTimersByTime(5_000)
+ } else {
+ window.dispatchEvent(new Event('focus'))
+ }
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockWizardRunsList.mock.calls.length - previousCalls).toBe(1)
+ expect(logic.values.userRuns.map((run) => run.id)).toEqual(['local-installation', 'newer', 'history'])
+ expect(MockEventSource.last().url).toBe('/api/projects/1/wizard/runs/local-installation/stream/')
+ }
+ )
+
+ it('keeps a new creation response when an older full-history poll finishes afterward', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ let resolvePoll!: (page: { results: WizardRunApi[]; next: null }) => void
+ mockWizardRunsList.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolvePoll = resolve
+ })
+ )
+ logic.actions.checkRuns()
+ const createdRun = run('created-in-library')
+ logic.actions.runsLoaded([createdRun], true)
+ expect(logic.values.userRuns.map((run) => run.id)).toContain(createdRun.id)
+
+ resolvePoll({ results: [run('newer')], next: null })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.userRuns.map((run) => run.id)).toEqual([createdRun.id, 'newer'])
+ })
+
+ it.each([
+ { createdById: MOCK_DEFAULT_USER.id, retry: 'manual' },
+ { createdById: MOCK_DEFAULT_USER.id + 1, retry: 'manual' },
+ { createdById: MOCK_DEFAULT_USER.id, retry: 'backoff' },
+ ])('restores terminal tasks for project member $createdById after $retry retry', async ({ createdById, retry }) => {
+ await expectLogic(logic).toFinishAllListeners()
+ const completed = { ...run('newer'), created_by_id: createdById, status: 'completed' as const }
+ logic.actions.runsLoaded([completed])
+ jest.mocked(wizardRunsTasksRetrieve).mockRejectedValueOnce(new Error('unavailable'))
+ logic.actions.loadRunData(completed)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.runDataErrors.newer).toBeTruthy()
+
+ const requests = jest.mocked(wizardRunsTasksRetrieve).mock.calls.length
+ logic.actions.watchRuns('test', [])
+ logic.actions.runsLoaded([completed])
+ logic.actions.loadRunData(completed)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(wizardRunsTasksRetrieve).toHaveBeenCalledTimes(requests)
+
+ const tasks: WizardRunTaskApi[] = [
+ {
+ name: 'Install SDK',
+ status: 'completed',
+ created_at: '2026-09-23T10:00:00Z',
+ started_at: null,
+ completed_at: null,
+ failed_at: null,
+ error_message: null,
+ },
+ ]
+ jest.mocked(wizardRunsTasksRetrieve).mockResolvedValueOnce({ tasks })
+ if (retry === 'backoff') {
+ jest.spyOn(Date, 'now').mockReturnValue(Date.now() + 30_000)
+ }
+ logic.actions.loadRunData(completed, { force: retry === 'manual' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.tasksByRunId.newer).toEqual(tasks)
+ expect(logic.values.runDataErrors.newer).toBeNull()
+ expect(logic.values.runDataLoading.newer).toBe(false)
+ expect(loadWizardRunArtifacts).toHaveBeenCalledWith('1', completed.id)
+ })
+
+ it('loads and streams a selected teammate run before discovery finishes', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ const teammateRun = { ...run('teammate'), created_by_id: MOCK_DEFAULT_USER.id + 1 }
+ const tasks = [{ name: 'Install SDK', status: 'running' } as WizardRunTaskApi]
+ jest.mocked(wizardRunsTasksRetrieve).mockResolvedValueOnce({ tasks })
+ const artifactReads = jest.mocked(loadWizardRunArtifacts).mock.calls.length
+ logic.actions.watchRuns('run-details', [teammateRun.id])
+ logic.actions.loadRunData(teammateRun, { tasksOnly: true })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.tasksByRunId.teammate).toEqual(tasks)
+ expect(loadWizardRunArtifacts).toHaveBeenCalledTimes(artifactReads)
+ expect(logic.values.userRuns.map((run) => run.id)).not.toContain(teammateRun.id)
+ const stream = MockEventSource.last()
+ expect(stream.url).toBe('/api/projects/1/wizard/runs/teammate/stream/')
+ stream.emitMessage(JSON.stringify({ status: 'running', tasks: [{ name: 'Install SDK', status: 'completed' }] }))
+ expect(logic.values.tasksByRunId.teammate[0].status).toBe('completed')
+ logic.actions.watchRuns('run-details', [])
+ expect(stream.readyState).toBe(MockEventSource.CLOSED)
+ })
+
+ it('keeps a newer streamed state when an older poll response arrives', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ MockEventSource.last().emitMessage(
+ JSON.stringify({
+ status: 'running',
+ stage: 'creating_artifacts',
+ updated_at: '2026-09-23T10:02:00Z',
+ tasks: [],
+ })
+ )
+ logic.actions.runsLoaded([run('newer')])
+ expect(logic.values.userRuns[0].stage).toBe('creating_artifacts')
+ })
+
+ it('does not let an in-flight active snapshot replace the terminal tasks or artifacts', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ let resolveSnapshot!: (snapshot: WizardRunTaskListApi) => void
+ jest.mocked(wizardRunsTasksRetrieve).mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveSnapshot = resolve
+ })
+ )
+ const artifact: WizardRunArtifactApi = {
+ id: 'completed-artifact',
+ artifact_type: 'pull_request',
+ team_id: 1,
+ run_id: 'newer',
+ url: 'https://github.com/example/project/pull/1',
+ number: 1,
+ repository: 'example/project',
+ head_branch: 'setup',
+ base_branch: 'main',
+ created_at: '2026-09-23T10:05:00Z',
+ }
+ jest.mocked(loadWizardRunArtifacts).mockResolvedValueOnce([]).mockResolvedValueOnce([artifact])
+ logic.actions.loadRunData(logic.values.userRuns[0])
+
+ await expectLogic(logic, () => {
+ MockEventSource.last().emitMessage(
+ JSON.stringify({
+ status: 'completed',
+ stage: null,
+ updated_at: '2026-09-23T10:05:00Z',
+ tasks: [],
+ })
+ )
+ logic.actions.loadRunData(logic.values.userRuns[0])
+ }).toDispatchActions(['runDataLoaded'])
+ expect(logic.values.artifactsByRunId.newer).toEqual([artifact])
+ resolveSnapshot({ tasks: [] })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.userRuns[0].status).toBe('completed')
+ expect(logic.values.artifactsByRunId.newer).toEqual([artifact])
+ })
})
diff --git a/products/wizard/frontend/logics/wizardRunSyncLogic.ts b/products/wizard/frontend/logics/wizardRunSyncLogic.ts
index 2a1c05b10f10..021dc6ac862b 100644
--- a/products/wizard/frontend/logics/wizardRunSyncLogic.ts
+++ b/products/wizard/frontend/logics/wizardRunSyncLogic.ts
@@ -1,15 +1,43 @@
-import { MakeLogicType, actions, events, kea, key, listeners, path, props, reducers } from 'kea'
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ connect,
+ events,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
-import { getWizardRunsStreamRetrieveUrl, wizardRunsList } from '../generated/api'
-import type { WizardRunApi, WizardRunTaskApi, WizardRunTaskListApi } from '../generated/api.schemas'
+import { userLogic } from 'scenes/userLogic'
+
+import type { UserType } from '~/types'
+
+import {
+ getWizardRunsStreamRetrieveUrl,
+ wizardRunsList,
+ wizardRunsRetrieve,
+ wizardRunsTasksRetrieve,
+} from '../generated/api'
+import type {
+ WizardRunApi,
+ WizardRunArtifactApi,
+ WizardRunTaskApi,
+ WizardRunTaskListApi,
+} from '../generated/api.schemas'
+import { loadWizardRunArtifacts } from '../lib/wizardApi'
import { wizardRunIsActive } from '../lib/wizardRunDisplay'
const RUN_POLL_MS = 30_000
+const RUN_DISCOVERY_POLL_MS = 5_000
-// Runs created before this are never synced, so older history does not open streams.
-const RUN_VISIBLE_AFTER = '2026-09-28T00:00:00Z'
-
-const RUN_LIST_LIMIT = 5
+const RUN_LIST_LIMIT = 100
+// Leave HTTP/1.1 connections available for requests and other app streams.
+const MAX_RUN_STREAMS = 1
type RunStreamState = Pick<
WizardRunApi,
@@ -17,23 +45,64 @@ type RunStreamState = Pick<
> &
WizardRunTaskListApi
+function streamRunPatch(state: RunStreamState): Partial<WizardRunApi> {
+ return {
+ status: state.status,
+ stage: state.stage,
+ error_code: state.error_code,
+ error_message: state.error_message,
+ updated_at: state.updated_at,
+ started_at: state.started_at,
+ finished_at: state.finished_at,
+ }
+}
+
export interface wizardRunSyncLogicProps {
projectId: string
}
+interface WizardRunDataOptions {
+ tasksOnly?: boolean
+ force?: boolean
+}
+
export interface wizardRunSyncLogicValues {
+ user: UserType | null
runs: WizardRunApi[]
- run: WizardRunApi | null
- tasks: readonly WizardRunTaskApi[]
+ userRuns: WizardRunApi[]
+ activeUserRuns: WizardRunApi[]
+ watchedRunIds: Record<string, string[]>
+ activeWatchedRuns: WizardRunApi[]
+ tasksByRunId: Record<string, readonly WizardRunTaskApi[]>
+ artifactsByRunId: Record<string, WizardRunArtifactApi[]>
+ runDataLoading: Record<string, boolean>
+ runDataErrors: Record<string, string | null>
}
export interface wizardRunSyncLogicActions {
- checkRuns: () => { value: true }
- runsLoaded: (runs: WizardRunApi[]) => { runs: WizardRunApi[] }
- clearTasks: () => { value: true }
- runUpdated: (state: RunStreamState) => { state: RunStreamState }
- showRun: (run: WizardRunApi | null) => { run: WizardRunApi | null }
- connectRun: () => { value: true }
+ checkRuns: (recentOnly?: boolean) => { recentOnly: boolean }
+ runsLoaded: (runs: WizardRunApi[], merge?: boolean) => { runs: WizardRunApi[]; merge: boolean }
+ runUpdated: (runId: string, state: RunStreamState) => { runId: string; state: RunStreamState }
+ loadRunData: (
+ run: WizardRunApi,
+ options?: WizardRunDataOptions
+ ) => { run: WizardRunApi; options: WizardRunDataOptions }
+ tasksLoaded: (
+ runId: string,
+ tasks: readonly WizardRunTaskApi[]
+ ) => { runId: string; tasks: readonly WizardRunTaskApi[] }
+ runDataLoaded: (
+ runId: string,
+ artifacts: WizardRunArtifactApi[]
+ ) => {
+ runId: string
+ artifacts: WizardRunArtifactApi[]
+ }
+ runDataStarted: (runId: string) => { runId: string }
+ runDataFailed: (runId: string) => { runId: string }
+ connectRuns: () => { value: true }
+ watchRuns: (source: string, runIds: string[]) => { source: string; runIds: string[] }
+ refreshWatchedRun: () => { value: true }
}
export type wizardRunSyncLogicType = MakeLogicType<
@@ -42,115 +111,281 @@ export type wizardRunSyncLogicType = MakeLogicType<
wizardRunSyncLogicProps
>
-export const wizardRunSyncLogic = kea<wizardRunSyncLogicType>([
- path(['products', 'wizard', 'wizardRunSyncLogic']),
+export const wizardRunSyncLogic: LogicWrapper<wizardRunSyncLogicType> = kea<wizardRunSyncLogicType>([
props({} as wizardRunSyncLogicProps),
key((logicProps) => logicProps.projectId),
+ path((key) => ['products', 'wizard', 'wizardRunSyncLogic', key]),
+ connect(() => ({ values: [userLogic, ['user']] })),
actions({
- checkRuns: true,
- runsLoaded: (runs: WizardRunApi[]) => ({ runs }),
- clearTasks: true,
- runUpdated: (state: RunStreamState) => ({ state }),
- showRun: (run: WizardRunApi | null) => ({ run }),
- connectRun: true,
+ checkRuns: (recentOnly = false) => ({ recentOnly }),
+ runsLoaded: (runs: WizardRunApi[], merge = false) => ({ runs, merge }),
+ runUpdated: (runId: string, state: RunStreamState) => ({ runId, state }),
+ loadRunData: (run: WizardRunApi, options: WizardRunDataOptions = {}) => ({ run, options }),
+ tasksLoaded: (runId: string, tasks: readonly WizardRunTaskApi[]) => ({ runId, tasks }),
+ runDataLoaded: (runId: string, artifacts: WizardRunArtifactApi[]) => ({ runId, artifacts }),
+ runDataStarted: (runId: string) => ({ runId }),
+ runDataFailed: (runId: string) => ({ runId }),
+ connectRuns: true,
+ watchRuns: (source: string, runIds: string[]) => ({ source, runIds }),
+ refreshWatchedRun: true,
}),
reducers({
- runs: [[] as WizardRunApi[], { runsLoaded: (_, { runs }) => runs }],
- run: [
- null as WizardRunApi | null,
+ watchedRunIds: [
+ {} as Record<string, string[]>,
+ { watchRuns: (state, { source, runIds }) => ({ ...state, [source]: runIds }) },
+ ],
+ runs: [
+ [] as WizardRunApi[],
+ {
+ runsLoaded: (current, { runs, merge }) => {
+ const currentRuns = new Map(current.map((run) => [run.id, run]))
+ const incomingIds = new Set(runs.map((run) => run.id))
+ const nextRuns = merge ? [...runs, ...current.filter((run) => !incomingIds.has(run.id))] : runs
+ return nextRuns.map((run) => {
+ const streamedRun = currentRuns.get(run.id)
+ return streamedRun &&
+ Date.parse(streamedRun.updated_at ?? streamedRun.created_at) >
+ Date.parse(run.updated_at ?? run.created_at)
+ ? streamedRun
+ : run
+ })
+ },
+ runUpdated: (current, { runId, state }) =>
+ current.map((run) => (run.id === runId ? { ...run, ...streamRunPatch(state) } : run)),
+ },
+ ],
+ tasksByRunId: [
+ {} as Record<string, readonly WizardRunTaskApi[]>,
+ {
+ runUpdated: (current, { runId, state }) => ({ ...current, [runId]: state.tasks }),
+ tasksLoaded: (current, { runId, tasks }) => ({ ...current, [runId]: tasks }),
+ },
+ ],
+ artifactsByRunId: [
+ {} as Record<string, WizardRunArtifactApi[]>,
+ {
+ runDataLoaded: (current, { runId, artifacts }) => ({ ...current, [runId]: artifacts }),
+ },
+ ],
+ runDataLoading: [
+ {} as Record<string, boolean>,
{
- runsLoaded: (current, { runs }) =>
- current ? (runs.find((run) => run.id === current.id) ?? current) : null,
- showRun: (_, { run }) => run,
- runUpdated: (current, { state }) => (current ? { ...current, ...state } : null),
+ runDataStarted: (state, { runId }) => ({ ...state, [runId]: true }),
+ runDataLoaded: (state, { runId }) => ({ ...state, [runId]: false }),
+ runDataFailed: (state, { runId }) => ({ ...state, [runId]: false }),
},
],
- tasks: [
- [] as readonly WizardRunTaskApi[],
+ runDataErrors: [
+ {} as Record<string, string | null>,
{
- clearTasks: () => [],
- showRun: () => [],
- runUpdated: (_, { state }) => state.tasks,
+ runDataStarted: (state, { runId }) => ({ ...state, [runId]: null }),
+ runDataFailed: (state, { runId }) => ({
+ ...state,
+ [runId]: "Couldn't load tasks and artifacts. Try again.",
+ }),
+ },
+ ],
+ }),
+ selectors({
+ userRuns: [
+ (s) => [s.runs, s.user],
+ (runs: WizardRunApi[], user: UserType | null): WizardRunApi[] =>
+ user ? runs.filter((run) => run.created_by_id === user.id) : [],
+ ],
+ activeUserRuns: [(s) => [s.userRuns], (runs: WizardRunApi[]): WizardRunApi[] => runs.filter(wizardRunIsActive)],
+ activeWatchedRuns: [
+ (s) => [s.runs, s.watchedRunIds],
+ (runs: WizardRunApi[], watched: Record<string, string[]>): WizardRunApi[] => {
+ const runsById = new Map(runs.map((run) => [run.id, run]))
+ return [...new Set(Object.values(watched).reverse().flat())]
+ .map((id) => runsById.get(id))
+ .filter((run): run is WizardRunApi => !!run && wizardRunIsActive(run))
},
],
}),
listeners(({ actions, cache, props: logicProps, values }) => ({
- checkRuns: async () => {
- if (cache.checking) {
+ checkRuns: async ({ recentOnly }) => {
+ if (cache.checking || !logicProps.projectId || !values.user) {
return
}
cache.checking = true
+ const disposables = cache.disposables
+ const knownRunIds = new Set(values.runs.map((run) => run.id))
try {
- const [activePage, recentPage] = await Promise.all([
- wizardRunsList(logicProps.projectId, {
- status: ['created', 'running'],
- created_after: RUN_VISIBLE_AFTER,
+ const runs: WizardRunApi[] = []
+ let offset = 0
+ while (true) {
+ const page = await wizardRunsList(logicProps.projectId, {
limit: RUN_LIST_LIMIT,
- }),
- wizardRunsList(logicProps.projectId, {
- created_after: RUN_VISIBLE_AFTER,
- limit: RUN_LIST_LIMIT,
- }),
- ])
- const activeRuns = activePage.results
- .map((run) => recentPage.results.find((recentRun) => recentRun.id === run.id) ?? run)
- .filter(wizardRunIsActive)
- actions.runsLoaded([
- ...activeRuns,
- ...recentPage.results.filter((run) => !activeRuns.some((activeRun) => activeRun.id === run.id)),
- ])
+ offset,
+ })
+ if (disposables.isDisposed) {
+ return
+ }
+ runs.push(...page.results)
+ if (recentOnly || !page.next) {
+ break
+ }
+ offset += RUN_LIST_LIMIT
+ }
+ // A Library creation response can arrive after this poll started but before its older snapshot.
+ const concurrentRuns = values.runs.filter((run) => !knownRunIds.has(run.id))
+ actions.runsLoaded(
+ [...new Map([...concurrentRuns, ...runs].map((run) => [run.id, run])).values()],
+ recentOnly
+ )
+ if (!recentOnly) {
+ cache.historyLoaded = true
+ }
} catch {
return
} finally {
cache.checking = false
}
},
- runsLoaded: () => {
- const nextRun = values.runs[0] ?? (values.run && !wizardRunIsActive(values.run) ? values.run : null)
- if (nextRun?.id !== values.run?.id) {
- actions.showRun(nextRun)
+ runsLoaded: () => actions.connectRuns(),
+ watchRuns: () => actions.connectRuns(),
+ [userLogic.actionTypes.loadUserSuccess]: () => {
+ actions.connectRuns()
+ actions.checkRuns(!!cache.historyLoaded)
+ },
+ runUpdated: ({ runId }) => {
+ actions.connectRuns()
+ const run = values.runs.find((run) => run.id === runId)
+ if (run && !wizardRunIsActive(run)) {
+ actions.checkRuns(true)
}
- actions.connectRun()
},
- connectRun: () => {
- const run = values.run
- if (!run || !wizardRunIsActive(run)) {
- cache.disposables.dispose('run-stream')
- cache.connectedRunId = undefined
+ loadRunData: async ({ run, options }) => {
+ if (run.team_id !== Number(logicProps.projectId)) {
return
}
- if (cache.connectedRunId === run.id) {
+ if (!values.runs.some((knownRun) => knownRun.id === run.id)) {
+ actions.runsLoaded([run], true)
+ }
+ const stateVersion = wizardRunIsActive(run) ? 'active' : `${run.status}:${run.updated_at}`
+ const version = options.tasksOnly ? `tasks:${stateVersion}` : stateVersion
+ if (cache.runDataVersions[run.id] === version || cache.runDataRequests[run.id]?.version === version) {
return
}
- cache.disposables.dispose('run-stream')
- cache.connectedRunId = run.id
- actions.clearTasks()
- cache.disposables.add(() => {
- const stream = new EventSource(getWizardRunsStreamRetrieveUrl(logicProps.projectId, run.id), {
- withCredentials: true,
- })
- stream.onmessage = (event: MessageEvent<string>): void => {
- try {
- const state = JSON.parse(event.data) as RunStreamState
- actions.runUpdated(state)
- if (!wizardRunIsActive({ ...run, ...state })) {
- actions.checkRuns()
+ const failure = cache.runDataFailures[run.id]
+ if (!options.force && failure?.version === version && failure.retryAfter > Date.now()) {
+ return
+ }
+ const request = { version }
+ cache.runDataRequests[run.id] = request
+ const disposables = cache.disposables
+ const isCurrentRequest = (): boolean => !disposables.isDisposed && cache.runDataRequests[run.id] === request
+ const previousTasks = values.tasksByRunId[run.id]
+ actions.runDataStarted(run.id)
+ try {
+ const [snapshot, artifacts] = await Promise.all([
+ wizardRunsTasksRetrieve(logicProps.projectId, run.id),
+ options.tasksOnly
+ ? Promise.resolve(values.artifactsByRunId[run.id] ?? [])
+ : loadWizardRunArtifacts(logicProps.projectId, run.id),
+ ])
+ if (!isCurrentRequest()) {
+ return
+ }
+ // A task snapshot requested before an SSE update must not overwrite that newer update.
+ if (values.tasksByRunId[run.id] === previousTasks) {
+ actions.tasksLoaded(run.id, snapshot.tasks)
+ }
+ cache.runDataVersions[run.id] = version
+ delete cache.runDataFailures[run.id]
+ actions.runDataLoaded(run.id, artifacts)
+ } catch {
+ if (isCurrentRequest()) {
+ cache.runDataFailures[run.id] = { version, retryAfter: Date.now() + RUN_POLL_MS }
+ actions.runDataFailed(run.id)
+ }
+ } finally {
+ if (cache.runDataRequests[run.id] === request) {
+ delete cache.runDataRequests[run.id]
+ }
+ }
+ },
+ refreshWatchedRun: async () => {
+ if (cache.refreshingWatchedRun || !values.activeWatchedRuns.length) {
+ return
+ }
+ const run = values.activeWatchedRuns[(cache.nextRunIndex ?? 0) % values.activeWatchedRuns.length]
+ cache.nextRunIndex = (cache.nextRunIndex ?? 0) + 1
+ cache.refreshingWatchedRun = true
+ const disposables = cache.disposables
+ const previousTasks = values.tasksByRunId[run.id]
+ try {
+ const [latest, snapshot] = await Promise.all([
+ wizardRunsRetrieve(logicProps.projectId, run.id),
+ wizardRunsTasksRetrieve(logicProps.projectId, run.id),
+ ])
+ if (disposables.isDisposed) {
+ return
+ }
+ actions.runsLoaded([latest], true)
+ if (values.tasksByRunId[run.id] === previousTasks) {
+ actions.tasksLoaded(run.id, snapshot.tasks)
+ }
+ } catch {
+ // Discovery and streams can still update the run while its fallback request fails.
+ } finally {
+ cache.refreshingWatchedRun = false
+ }
+ },
+ connectRuns: () => {
+ const streamedRuns = values.activeWatchedRuns.slice(0, MAX_RUN_STREAMS)
+ const activeRunIds = streamedRuns.map((run) => run.id)
+ const connectedRunIds: string[] = cache.connectedRunIds ?? []
+
+ for (const runId of connectedRunIds) {
+ if (!activeRunIds.includes(runId)) {
+ cache.disposables.dispose(`run-stream:${runId}`)
+ }
+ }
+ cache.connectedRunIds = activeRunIds
+
+ for (const run of streamedRuns) {
+ if (connectedRunIds.includes(run.id)) {
+ continue
+ }
+ cache.disposables.add(() => {
+ const stream = new EventSource(getWizardRunsStreamRetrieveUrl(logicProps.projectId, run.id), {
+ withCredentials: true,
+ })
+ stream.onmessage = (event: MessageEvent<string>): void => {
+ try {
+ const state = JSON.parse(event.data) as RunStreamState
+ actions.runUpdated(run.id, state)
+ } catch {
+ actions.checkRuns(true)
}
- } catch {
- actions.checkRuns()
}
- }
- return () => stream.close()
- }, 'run-stream')
+ return () => stream.close()
+ }, `run-stream:${run.id}`)
+ }
},
})),
events(({ actions, cache }) => ({
afterMount: () => {
+ cache.runDataVersions = {}
+ cache.runDataRequests = {}
+ cache.runDataFailures = {}
actions.checkRuns()
cache.disposables.add(() => {
- const timer = window.setInterval(() => actions.checkRuns(), RUN_POLL_MS)
+ const timer = window.setInterval(() => actions.refreshWatchedRun(), RUN_POLL_MS)
return () => window.clearInterval(timer)
}, 'active-run-poll')
+ cache.disposables.add(() => {
+ const discoverRuns = (): void => actions.checkRuns(true)
+ const timer = window.setInterval(discoverRuns, RUN_DISCOVERY_POLL_MS)
+ window.addEventListener('focus', discoverRuns)
+ discoverRuns()
+ return () => {
+ window.clearInterval(timer)
+ window.removeEventListener('focus', discoverRuns)
+ }
+ }, 'run-discovery-poll')
},
})),
])
diff --git a/products/wizard/frontend/views/onboarding/WizardInstallSync.tsx b/products/wizard/frontend/views/onboarding/WizardInstallSync.tsx
new file mode 100644
index 000000000000..7767c1ffd4c8
--- /dev/null
+++ b/products/wizard/frontend/views/onboarding/WizardInstallSync.tsx
@@ -0,0 +1,59 @@
+import { useActions, useValues } from 'kea'
+import { ReactNode, useState } from 'react'
+
+import { useInterval } from 'lib/hooks/useInterval'
+import { cn } from 'lib/utils/css-classes'
+import { userLogic } from 'scenes/userLogic'
+
+import { wizardRunIsActive } from '../../lib/wizardRunDisplay'
+import { wizardRunSyncLogic } from '../../logics/wizardRunSyncLogic'
+import { onboardingWizardRunLogic } from './onboardingWizardRunLogic'
+import { WizardInstallSyncView } from './WizardInstallSyncView'
+
+export function WizardInstallSync({
+ projectId,
+ children,
+}: {
+ projectId: string | null
+ children: ReactNode
+}): JSX.Element {
+ const { user } = useValues(userLogic)
+ const scopedProjectId = projectId ?? ''
+ const onboardingLogic = onboardingWizardRunLogic({ projectId: scopedProjectId, userId: user?.id ?? 0 })
+ const { run } = useValues(onboardingLogic)
+ const { clickArtifact } = useActions(onboardingLogic)
+ const syncLogic = wizardRunSyncLogic({ projectId: scopedProjectId })
+ const { tasksByRunId, artifactsByRunId, runDataErrors, runDataLoading } = useValues(syncLogic)
+ const { loadRunData } = useActions(syncLogic)
+ const [now, setNow] = useState(Date.now)
+ useInterval(() => setNow(Date.now()), run && wizardRunIsActive(run) ? 1000 : null)
+
+ return (
+ <div className="@container/wizard-install">
+ <div
+ className={cn(
+ 'grid grid-cols-1 items-start gap-6',
+ run && '@min-[44rem]/wizard-install:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]'
+ )}
+ >
+ <div className="min-w-0 space-y-8" data-attr="wizard-install-instructions">
+ {children}
+ </div>
+ {run && (
+ <div className="min-w-0">
+ <WizardInstallSyncView
+ run={run}
+ tasks={tasksByRunId[run.id] ?? []}
+ artifacts={artifactsByRunId[run.id] ?? []}
+ loading={runDataLoading[run.id] ?? true}
+ error={runDataErrors[run.id] ?? null}
+ onRetry={() => loadRunData(run, { force: true })}
+ onArtifactClick={clickArtifact}
+ now={now}
+ />
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/wizard/frontend/views/onboarding/WizardInstallSyncView.stories.tsx b/products/wizard/frontend/views/onboarding/WizardInstallSyncView.stories.tsx
new file mode 100644
index 000000000000..deb18bc3188d
--- /dev/null
+++ b/products/wizard/frontend/views/onboarding/WizardInstallSyncView.stories.tsx
@@ -0,0 +1,172 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import type { WizardRunApi, WizardRunArtifactApi, WizardRunTaskApi } from '../../generated/api.schemas'
+import { WizardInstallSyncView } from './WizardInstallSyncView'
+
+const NOW = new Date('2026-09-23T10:03:00Z').getTime()
+
+const run: WizardRunApi = {
+ id: '00000000-0000-4000-8000-000000000001',
+ team_id: 1,
+ created_by_id: 1,
+ created_by: null,
+ environment: 'local',
+ workspace: { type: 'local_folder', project_name: 'example-project' },
+ program: {
+ id: 'posthog-integration',
+ name: 'PostHog integration',
+ description: 'Set up PostHog',
+ wizard_version: '2.78.0',
+ command: [],
+ tags: [],
+ required_programs: [],
+ supported_environments: ['local'],
+ },
+ status: 'running',
+ stage: 'executing_wizard',
+ error_code: null,
+ error_message: null,
+ created_at: '2026-09-23T10:00:00Z',
+ updated_at: '2026-09-23T10:02:00Z',
+ started_at: '2026-09-23T10:00:30Z',
+ finished_at: null,
+ deadline_at: null,
+}
+
+const task = (name: string, status: WizardRunTaskApi['status']): WizardRunTaskApi => ({
+ name,
+ status,
+ created_at: '2026-09-23T10:00:00Z',
+ started_at: status === 'created' ? null : '2026-09-23T10:01:00Z',
+ completed_at: status === 'completed' ? '2026-09-23T10:02:00Z' : null,
+ failed_at: status === 'failed' ? '2026-09-23T10:02:00Z' : null,
+ error_message: null,
+})
+
+const artifacts: WizardRunArtifactApi[] = [
+ {
+ id: 'artifact-pr',
+ team_id: 1,
+ run_id: run.id,
+ artifact_type: 'pull_request',
+ url: 'https://github.com/example/project/pull/12',
+ number: 12,
+ repository: 'example/project',
+ head_branch: 'posthog/setup',
+ base_branch: 'main',
+ created_at: '2026-09-23T10:02:00Z',
+ },
+ {
+ id: 'artifact-diff',
+ team_id: 1,
+ run_id: run.id,
+ artifact_type: 'git_diff',
+ size_bytes: 2048,
+ content_hash: 'hash',
+ additions: 12,
+ removals: 3,
+ created_at: '2026-09-23T10:02:00Z',
+ },
+]
+
+const meta: Meta<typeof WizardInstallSyncView> = {
+ title: 'Products/Wizard/Wizard install sync',
+ component: WizardInstallSyncView,
+ parameters: { layout: 'centered', testOptions: { waitForLoadersToDisappear: false } },
+ decorators: [
+ (Story) => (
+ <div className="w-96">
+ <Story />
+ </div>
+ ),
+ ],
+ argTypes: {
+ run: { control: 'object' },
+ tasks: { control: 'object' },
+ artifacts: { control: 'object' },
+ now: { control: 'number' },
+ loading: { control: 'boolean' },
+ error: { control: 'text' },
+ },
+ args: {
+ run,
+ now: NOW,
+ tasks: [
+ task('Install the PostHog SDK', 'completed'),
+ task('Add your project token', 'running'),
+ task('Verify events', 'created'),
+ ],
+ },
+}
+
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const RunningWithTasks: Story = {}
+
+export const RunningWithoutTasks: Story = {
+ args: { tasks: [] },
+}
+
+export const WithArtifacts: Story = {
+ args: {
+ run: {
+ ...run,
+ environment: 'cloud',
+ workspace: { type: 'git_repository', repository: 'example/project' },
+ status: 'completed',
+ finished_at: '2026-09-23T10:03:00Z',
+ },
+ tasks: [],
+ artifacts: [artifacts[1], artifacts[0]],
+ },
+}
+
+export const CompletedLocally: Story = {
+ args: { run: { ...run, status: 'completed', finished_at: '2026-09-23T10:03:00Z' }, tasks: [] },
+}
+
+export const Canceled: Story = {
+ args: { run: { ...run, status: 'cancelled', finished_at: '2026-09-23T10:03:00Z' }, tasks: [] },
+}
+
+export const LoadingArtifacts: Story = {
+ args: { ...WithArtifacts.args, artifacts: [], loading: true },
+}
+
+export const ArtifactLoadFailed: Story = {
+ args: { ...WithArtifacts.args, artifacts: [], error: "Couldn't load tasks and artifacts. Try again." },
+}
+
+export const ManyTasks: Story = {
+ args: {
+ tasks: [
+ task('Detect your framework', 'completed'),
+ task('Install the PostHog SDK', 'completed'),
+ task('Add your project token', 'running'),
+ task('Verify events', 'created'),
+ task('Open a pull request', 'created'),
+ ],
+ },
+}
+
+export const Starting: Story = {
+ args: {
+ run: { ...run, status: 'created', stage: 'dispatching' },
+ tasks: [],
+ },
+}
+
+export const Failed: Story = {
+ args: {
+ run: {
+ ...run,
+ status: 'failed',
+ stage: 'executing_wizard',
+ error_code: 'execution_failed',
+ error_message: 'Could not install posthog-js: the package manager exited with code 1.',
+ finished_at: '2026-09-23T10:03:00Z',
+ },
+ tasks: [task('Install the PostHog SDK', 'completed'), task('Add your project token', 'failed')],
+ },
+}
diff --git a/products/wizard/frontend/views/onboarding/WizardInstallSyncView.tsx b/products/wizard/frontend/views/onboarding/WizardInstallSyncView.tsx
new file mode 100644
index 000000000000..bbcbb46d82a4
--- /dev/null
+++ b/products/wizard/frontend/views/onboarding/WizardInstallSyncView.tsx
@@ -0,0 +1,71 @@
+import { LemonButton, LemonCard } from '@posthog/lemon-ui'
+
+import { WizardRunStatusIcon } from '../../components/run-tags/WizardRunStatusIcon'
+import type { WizardRunApi, WizardRunArtifactApi, WizardRunTaskApi } from '../../generated/api.schemas'
+import {
+ formatWizardRunElapsed,
+ wizardRunActivityLabel,
+ wizardRunElapsedSeconds,
+ wizardRunIsActive,
+ wizardWorkspaceLabel,
+} from '../../lib/wizardRunDisplay'
+import { WizardInstallRunArtifacts } from './components/WizardInstallRunArtifacts'
+import { WizardInstallRunOutcome } from './components/WizardInstallRunOutcome'
+import { WizardInstallRunProgress } from './components/WizardInstallRunProgress'
+import type { WizardOnboardingArtifactClickSource } from './onboardingWizardRunLogic'
+
+export function WizardInstallSyncView({
+ run,
+ tasks,
+ artifacts = [],
+ now,
+ loading = false,
+ error = null,
+ onRetry,
+ onArtifactClick,
+}: {
+ run: WizardRunApi
+ tasks: readonly WizardRunTaskApi[]
+ artifacts?: readonly WizardRunArtifactApi[]
+ now: number
+ loading?: boolean
+ error?: string | null
+ onRetry?: () => void
+ onArtifactClick?: (artifact: WizardRunArtifactApi, source: WizardOnboardingArtifactClickSource) => void
+}): JSX.Element {
+ return (
+ <LemonCard className="p-3" hoverEffect={false} data-attr="wizard-install-sync">
+ <div className="flex items-center gap-2">
+ <WizardRunStatusIcon status={run.status} />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-sm font-semibold ph-no-capture">{run.program.name}</div>
+ <div className="truncate text-xs text-muted ph-no-capture">
+ {run.status === 'failed' ? 'Setup failed' : wizardRunActivityLabel(run, tasks)}
+ </div>
+ </div>
+ <span className="shrink-0 text-xs tabular-nums text-muted" translate="no">
+ {formatWizardRunElapsed(wizardRunElapsedSeconds(run, now))}
+ </span>
+ </div>
+
+ {wizardRunIsActive(run) && <WizardInstallRunProgress run={run} tasks={tasks} />}
+ <WizardInstallRunOutcome run={run} tasks={tasks} />
+ <WizardInstallRunArtifacts
+ run={run}
+ artifacts={artifacts}
+ loading={loading}
+ error={error}
+ onArtifactClick={onArtifactClick}
+ />
+ {error && (
+ <div className="mt-3 flex flex-wrap items-center gap-2 text-xs text-danger">
+ <span>{error}</span>
+ <LemonButton size="xsmall" onClick={onRetry} loading={loading} data-attr="wizard-install-retry">
+ Try again
+ </LemonButton>
+ </div>
+ )}
+ <div className="mt-3 truncate text-2xs text-muted ph-no-capture">{wizardWorkspaceLabel(run)}</div>
+ </LemonCard>
+ )
+}
diff --git a/products/wizard/frontend/views/onboarding/components/WizardInstallRunArtifacts.tsx b/products/wizard/frontend/views/onboarding/components/WizardInstallRunArtifacts.tsx
new file mode 100644
index 000000000000..3efed81679b0
--- /dev/null
+++ b/products/wizard/frontend/views/onboarding/components/WizardInstallRunArtifacts.tsx
@@ -0,0 +1,81 @@
+import { IconGitBranch, IconGithub } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+
+import type { WizardRunApi, WizardRunArtifactApi } from '../../../generated/api.schemas'
+import { formatArtifactSize } from '../../../lib/wizardRunDisplay'
+import type { WizardOnboardingArtifactClickSource } from '../onboardingWizardRunLogic'
+
+export function WizardInstallRunArtifacts({
+ run,
+ artifacts,
+ loading,
+ error,
+ onArtifactClick,
+}: {
+ run: WizardRunApi
+ artifacts: readonly WizardRunArtifactApi[]
+ loading: boolean
+ error: string | null
+ onArtifactClick?: (artifact: WizardRunArtifactApi, source: WizardOnboardingArtifactClickSource) => void
+}): JSX.Element | null {
+ if (run.environment !== 'cloud') {
+ return null
+ }
+ if (artifacts.length === 0) {
+ if (run.status !== 'completed' || error) {
+ return null
+ }
+ return (
+ <p className="mt-3 mb-0 text-xs text-muted">
+ {loading ? 'Loading artifacts…' : 'This run did not produce any artifacts.'}
+ </p>
+ )
+ }
+ const pullRequest = artifacts.find((artifact) => artifact.artifact_type === 'pull_request')
+ return (
+ <div className="mt-3 flex flex-wrap items-center gap-3 border-t border-primary pt-2 ph-no-capture">
+ <ul className="m-0 min-w-0 flex-1 list-none space-y-1 p-0">
+ {artifacts.map((artifact) => {
+ if (artifact.artifact_type === 'pull_request') {
+ return (
+ <li key={artifact.id}>
+ <LinkPrimitive
+ to={artifact.url}
+ target="_blank"
+ onClick={() => onArtifactClick?.(artifact, 'artifact_list')}
+ className="flex min-w-0 items-center gap-2 text-xs hover:underline"
+ data-attr="wizard-install-artifact"
+ >
+ <IconGithub />
+ <span className="truncate">{`Pull request #${artifact.number}`}</span>
+ </LinkPrimitive>
+ </li>
+ )
+ }
+ return (
+ <li key={artifact.id}>
+ <span className="flex min-w-0 items-center gap-2 text-xs text-muted">
+ <IconGitBranch />
+ <span className="truncate">{`Git diff (${formatArtifactSize(artifact.size_bytes)})`}</span>
+ </span>
+ </li>
+ )
+ })}
+ </ul>
+ {run.status === 'completed' && pullRequest && (
+ <LemonButton
+ type="primary"
+ size="xsmall"
+ to={pullRequest.url}
+ targetBlank
+ onClick={() => onArtifactClick?.(pullRequest, 'review_button')}
+ data-attr="wizard-install-review-pr"
+ >
+ Review pull request
+ </LemonButton>
+ )}
+ </div>
+ )
+}
diff --git a/products/wizard/frontend/views/onboarding/components/WizardInstallRunOutcome.tsx b/products/wizard/frontend/views/onboarding/components/WizardInstallRunOutcome.tsx
new file mode 100644
index 000000000000..f8de47e71c03
--- /dev/null
+++ b/products/wizard/frontend/views/onboarding/components/WizardInstallRunOutcome.tsx
@@ -0,0 +1,42 @@
+import type { WizardRunApi, WizardRunTaskApi } from '../../../generated/api.schemas'
+import { wizardRunIsActive } from '../../../lib/wizardRunDisplay'
+import { wizardRunErrorDetails } from '../../../lib/wizardRunErrorCatalog'
+
+export function WizardInstallRunOutcome({
+ run,
+ tasks,
+}: {
+ run: WizardRunApi
+ tasks: readonly WizardRunTaskApi[]
+}): JSX.Element {
+ if (wizardRunIsActive(run)) {
+ return <p className="mt-3 mb-0 text-xs text-muted">You can continue onboarding while the setup agent runs.</p>
+ }
+ if (run.status === 'failed') {
+ const details = wizardRunErrorDetails(run.error_code, null)
+ const failure =
+ run.error_message || tasks.find((task) => task.status === 'failed')?.error_message || details.description
+ return (
+ <div className="mt-3 text-xs">
+ <p className="mb-1 whitespace-pre-wrap break-words text-danger ph-no-capture">{failure}</p>
+ <p className="mb-0 text-muted">
+ {details.resolution ?? 'Review the error and run the setup agent again to retry.'}
+ </p>
+ </div>
+ )
+ }
+ if (run.status === 'cancelled') {
+ return (
+ <p className="mt-3 mb-0 text-xs text-muted">
+ This run was canceled. Run the setup agent again when you're ready.
+ </p>
+ )
+ }
+ return (
+ <p className="mt-3 mb-0 text-xs">
+ {run.environment === 'local'
+ ? 'PostHog setup is complete. Review the changes in your local project before committing them.'
+ : 'PostHog setup is complete. Review the changes before merging them.'}
+ </p>
+ )
+}
diff --git a/products/wizard/frontend/views/onboarding/components/WizardInstallRunProgress.tsx b/products/wizard/frontend/views/onboarding/components/WizardInstallRunProgress.tsx
new file mode 100644
index 000000000000..69f6699458cb
--- /dev/null
+++ b/products/wizard/frontend/views/onboarding/components/WizardInstallRunProgress.tsx
@@ -0,0 +1,70 @@
+import { IconCheckCircle, IconClock, IconXCircle } from '@posthog/icons'
+import { Spinner } from '@posthog/lemon-ui'
+
+import type { WizardRunApi, WizardRunTaskApi } from '../../../generated/api.schemas'
+import {
+ WIZARD_RUN_PROGRESS_STEPS,
+ WizardRunProgressStep,
+ wizardRunProgressStates,
+} from '../../../lib/wizardRunDisplay'
+import type { WizardRunProgressState } from '../../../lib/wizardRunDisplay'
+
+const STEP_LABELS: Record<WizardRunProgressStep, string> = {
+ [WizardRunProgressStep.Starting]: 'Starting',
+ [WizardRunProgressStep.PreparingWorkspace]: 'Preparing',
+ [WizardRunProgressStep.ExecutingWizard]: 'Running',
+ [WizardRunProgressStep.CreatingArtifacts]: 'Finishing',
+}
+
+const TASK_STATES: Record<WizardRunTaskApi['status'], WizardRunProgressState> = {
+ created: 'pending',
+ running: 'active',
+ completed: 'complete',
+ failed: 'failed',
+}
+
+function StepIcon({ state }: { state: WizardRunProgressState }): JSX.Element {
+ if (state === 'active') {
+ return <Spinner />
+ }
+ if (state === 'complete') {
+ return <IconCheckCircle className="text-success" />
+ }
+ return state === 'failed' ? <IconXCircle className="text-danger" /> : <IconClock className="text-muted" />
+}
+
+export function WizardInstallRunProgress({
+ run,
+ tasks,
+}: {
+ run: WizardRunApi
+ tasks: readonly WizardRunTaskApi[]
+}): JSX.Element {
+ const stepStates = wizardRunProgressStates(run)
+ const visibleTasks = tasks.slice(0, 3)
+ return (
+ <>
+ <div className="mt-3 flex flex-wrap gap-x-3 gap-y-1.5">
+ {WIZARD_RUN_PROGRESS_STEPS.map((step) => (
+ <span key={step} className="flex items-center gap-1 text-2xs text-muted">
+ <StepIcon state={stepStates[step]} />
+ <span>{STEP_LABELS[step]}</span>
+ </span>
+ ))}
+ </div>
+ {visibleTasks.length > 0 && (
+ <ul className="mt-3 mb-0 list-none space-y-1 p-0">
+ {visibleTasks.map((task) => (
+ <li key={task.name} className="flex items-center gap-2 text-xs">
+ <StepIcon state={TASK_STATES[task.status]} />
+ <span className="truncate ph-no-capture">{task.name}</span>
+ </li>
+ ))}
+ {tasks.length > visibleTasks.length && (
+ <li className="pl-6 text-2xs text-muted">{`+${tasks.length - visibleTasks.length} more tasks`}</li>
+ )}
+ </ul>
+ )}
+ </>
+ )
+}
diff --git a/products/wizard/frontend/views/onboarding/onboardingWizardRunLogic.test.ts b/products/wizard/frontend/views/onboarding/onboardingWizardRunLogic.test.ts
new file mode 100644
index 000000000000..12c398d8af25
--- /dev/null
+++ b/products/wizard/frontend/views/onboarding/onboardingWizardRunLogic.test.ts
@@ -0,0 +1,166 @@
+import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+import { installMockEventSource } from 'lib/wizard-sync/eventSource.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { wizardRunsList, wizardRunsTasksRetrieve } from '../../generated/api'
+import type { WizardRunApi } from '../../generated/api.schemas'
+import { loadWizardRunArtifacts } from '../../lib/wizardApi'
+import { wizardRunSyncLogic } from '../../logics/wizardRunSyncLogic'
+import { onboardingWizardRunLogic } from './onboardingWizardRunLogic'
+
+jest.mock('../../generated/api', () => ({
+ wizardRunsList: jest.fn().mockResolvedValue({ results: [], next: null }),
+ wizardRunsTasksRetrieve: jest.fn().mockResolvedValue({ tasks: [] }),
+ getWizardRunsStreamRetrieveUrl: () => '/stream',
+}))
+jest.mock('../../lib/wizardApi', () => ({
+ loadWizardRunArtifacts: jest.fn().mockResolvedValue([]),
+ loadWizardOnboardingStartTime: jest.fn().mockImplementation(async () => new Date().toISOString()),
+}))
+
+const props = { projectId: '1', userId: MOCK_DEFAULT_USER.id }
+const startedAt = '2026-09-23T10:00:00Z'
+const run: WizardRunApi = {
+ id: 'installation',
+ team_id: 1,
+ created_by_id: props.userId,
+ program: {
+ id: 'posthog-integration',
+ name: 'PostHog integration',
+ description: '',
+ command: [],
+ wizard_version: '1.0.0',
+ tags: [],
+ required_programs: [],
+ supported_environments: ['local', 'cloud'],
+ },
+ environment: 'local',
+ workspace: { type: 'local_folder', project_name: 'example-project' },
+ status: 'running',
+ created_at: '2026-09-23T10:01:00Z',
+ updated_at: '2026-09-23T10:01:00Z',
+ created_by: null,
+ stage: 'executing_wizard',
+ error_code: null,
+ error_message: null,
+ started_at: null,
+ finished_at: null,
+ deadline_at: null,
+}
+
+describe('onboardingWizardRunLogic', () => {
+ let logic: ReturnType<typeof onboardingWizardRunLogic.build>
+ let restoreEventSource: () => void
+
+ beforeEach(() => {
+ localStorage.clear()
+ initKeaTests()
+ restoreEventSource = installMockEventSource()
+ jest.mocked(wizardRunsList).mockResolvedValue({ count: 0, results: [], next: null })
+ localStorage.setItem(`1.${props.userId}.onboarding_wizard_started_at`, JSON.stringify(startedAt))
+ logic = onboardingWizardRunLogic(props)
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ restoreEventSource()
+ jest.restoreAllMocks()
+ localStorage.clear()
+ })
+
+ it('ignores history, audits, and other users, then saves the installation and supersedes it with a newer one', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ const sync = wizardRunSyncLogic({ projectId: '1' })
+ const history = { ...run, id: 'history', created_at: '2026-09-23T09:00:00Z' }
+ const audit = { ...run, id: 'audit', program: { ...run.program, id: 'analytics-audit' } }
+ const otherUser = { ...run, id: 'other-user', created_by_id: props.userId + 1 }
+ sync.actions.runsLoaded([history, audit, otherUser])
+ expect(logic.values.run).toBeNull()
+
+ sync.actions.runsLoaded([run, audit, history])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.savedRun).toEqual({ id: run.id, created_at: run.created_at })
+ expect(JSON.parse(localStorage.getItem(`1.${props.userId}.onboarding_wizard_run_id`)!)).toEqual(
+ logic.values.savedRun
+ )
+ const taskReads = jest.mocked(wizardRunsTasksRetrieve).mock.calls.length
+ const artifactReads = jest.mocked(loadWizardRunArtifacts).mock.calls.length
+ for (const updatedAt of ['2026-09-23T10:02:00Z', '2026-09-23T10:03:00Z']) {
+ sync.actions.runUpdated(run.id, {
+ status: 'running',
+ stage: 'executing_wizard',
+ error_code: null,
+ error_message: null,
+ updated_at: updatedAt,
+ started_at: null,
+ finished_at: null,
+ tasks: [],
+ })
+ }
+ await expectLogic(logic).toFinishAllListeners()
+ expect(wizardRunsTasksRetrieve).toHaveBeenCalledTimes(taskReads)
+ expect(loadWizardRunArtifacts).toHaveBeenCalledTimes(artifactReads)
+
+ const newer = { ...run, id: 'replacement', environment: 'cloud' as const, created_at: '2026-09-23T10:02:00Z' }
+ sync.actions.runsLoaded([run, newer, audit])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.run?.id).toBe(newer.id)
+ expect(logic.values.savedRun?.id).toBe(newer.id)
+ })
+
+ it.each(['completed', 'failed', 'cancelled'] as const)(
+ 'restores the saved %s installation after a fresh app mount',
+ async (status) => {
+ await expectLogic(logic).toFinishAllListeners()
+ const terminal = { ...run, status }
+ wizardRunSyncLogic({ projectId: '1' }).actions.runsLoaded([terminal])
+ await expectLogic(logic).toFinishAllListeners()
+ logic.unmount()
+
+ initKeaTests()
+ jest.mocked(wizardRunsList).mockResolvedValue({ count: 1, results: [terminal], next: null })
+ logic = onboardingWizardRunLogic(props)
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.onboardingStartedAt).toBe(startedAt)
+ expect(logic.values.run).toEqual(terminal)
+ expect(wizardRunsTasksRetrieve).toHaveBeenCalledWith('1', run.id)
+ }
+ )
+
+ it('does not restore another project or account selection', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ wizardRunSyncLogic({ projectId: '1' }).actions.runsLoaded([run])
+ await expectLogic(logic).toFinishAllListeners()
+ logic.unmount()
+ logic = onboardingWizardRunLogic({ projectId: '2', userId: props.userId + 1 })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.savedRun).toBeNull()
+ expect(logic.values.run).toBeNull()
+ })
+
+ it('persists the initial onboarding start before any run exists', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ logic.unmount()
+ localStorage.clear()
+ initKeaTests()
+ logic = onboardingWizardRunLogic(props)
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ const initialStart = logic.values.onboardingStartedAt
+ expect(Number.isFinite(Date.parse(initialStart!))).toBe(true)
+ expect(JSON.parse(localStorage.getItem(`1.${props.userId}.onboarding_wizard_started_at`)!)).toBe(initialStart)
+ logic.unmount()
+ initKeaTests()
+ logic = onboardingWizardRunLogic(props)
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.onboardingStartedAt).toBe(initialStart)
+ expect(logic.values.savedRun).toBeNull()
+ })
+})
diff --git a/products/wizard/frontend/views/onboarding/onboardingWizardRunLogic.ts b/products/wizard/frontend/views/onboarding/onboardingWizardRunLogic.ts
new file mode 100644
index 000000000000..f8b377697e5d
--- /dev/null
+++ b/products/wizard/frontend/views/onboarding/onboardingWizardRunLogic.ts
@@ -0,0 +1,155 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import posthog from 'posthog-js'
+
+import type { WizardRunApi, WizardRunArtifactApi } from '../../generated/api.schemas'
+import { wizardRunEventProperties } from '../../lib/wizardAnalytics'
+import { loadWizardOnboardingStartTime } from '../../lib/wizardApi'
+import { selectWizardInstallRun } from '../../lib/wizardRunDisplay'
+import { wizardRunSyncLogic } from '../../logics/wizardRunSyncLogic'
+
+interface OnboardingWizardRunProps {
+ projectId: string
+ userId: number
+}
+
+type SavedOnboardingWizardRun = Pick<WizardRunApi, 'id' | 'created_at'>
+export type WizardOnboardingArtifactClickSource = 'artifact_list' | 'review_button'
+
+export interface onboardingWizardRunLogicValues {
+ userRuns: WizardRunApi[]
+ onboardingStartedAt: string | null
+ savedRun: SavedOnboardingWizardRun | null
+ run: WizardRunApi | null
+}
+
+export interface onboardingWizardRunLogicActions {
+ initializeOnboarding: () => { value: true }
+ syncRun: () => { value: true }
+ startOnboarding: (timestamp: string) => { timestamp: string }
+ saveRun: (run: SavedOnboardingWizardRun) => { run: SavedOnboardingWizardRun }
+ loadRunData: (run: WizardRunApi) => { run: WizardRunApi }
+ watchRuns: (source: string, runIds: string[]) => { source: string; runIds: string[] }
+ clickArtifact: (
+ artifact: WizardRunArtifactApi,
+ clickSource: WizardOnboardingArtifactClickSource
+ ) => { artifact: WizardRunArtifactApi; clickSource: WizardOnboardingArtifactClickSource }
+}
+
+export type onboardingWizardRunLogicType = MakeLogicType<
+ onboardingWizardRunLogicValues,
+ onboardingWizardRunLogicActions,
+ OnboardingWizardRunProps
+>
+
+export const onboardingWizardRunLogic: LogicWrapper<onboardingWizardRunLogicType> = kea<onboardingWizardRunLogicType>([
+ props({} as OnboardingWizardRunProps),
+ key(({ projectId, userId }) => `${projectId}.${userId}`),
+ path((key) => ['products', 'wizard', 'onboardingWizardRunLogic', key]),
+ connect(({ projectId }: OnboardingWizardRunProps) => ({
+ values: [wizardRunSyncLogic({ projectId }), ['userRuns']],
+ actions: [wizardRunSyncLogic({ projectId }), ['loadRunData', 'watchRuns']],
+ })),
+ actions({
+ initializeOnboarding: true,
+ syncRun: true,
+ startOnboarding: (timestamp: string) => ({ timestamp }),
+ saveRun: (run: SavedOnboardingWizardRun) => ({ run }),
+ clickArtifact: (artifact: WizardRunArtifactApi, clickSource: WizardOnboardingArtifactClickSource) => ({
+ artifact,
+ clickSource,
+ }),
+ }),
+ reducers(({ props: { projectId, userId } }) => ({
+ onboardingStartedAt: [
+ null as string | null,
+ // The scope prevents one user's installation from being restored in another project or account.
+ { persist: true, storageKey: `${projectId}.${userId}.onboarding_wizard_started_at` },
+ {
+ startOnboarding: (state, { timestamp }) =>
+ Number.isFinite(Date.parse(state ?? '')) ? state : timestamp,
+ },
+ ],
+ savedRun: [
+ null as SavedOnboardingWizardRun | null,
+ { persist: true, storageKey: `${projectId}.${userId}.onboarding_wizard_run_id` },
+ { saveRun: (_, { run }) => run },
+ ],
+ })),
+ selectors(({ props }) => ({
+ run: [
+ (s) => [s.userRuns, s.onboardingStartedAt, s.savedRun],
+ (
+ runs: WizardRunApi[],
+ startedAt: string | null,
+ savedRun: SavedOnboardingWizardRun | null
+ ): WizardRunApi | null =>
+ startedAt && props.projectId && props.userId
+ ? selectWizardInstallRun(
+ runs.filter((run) => run.created_by_id === props.userId),
+ startedAt,
+ savedRun
+ )
+ : null,
+ ],
+ })),
+ listeners(({ actions, values, props: { projectId }, cache }) => ({
+ initializeOnboarding: async (_, breakpoint) => {
+ const timestamp = await loadWizardOnboardingStartTime(projectId)
+ await breakpoint()
+ actions.startOnboarding(timestamp)
+ actions.syncRun()
+ },
+ clickArtifact: ({ artifact, clickSource }) => {
+ if (values.run) {
+ posthog.capture('wizard onboarding state artifact clicked', {
+ ...wizardRunEventProperties(values.run),
+ artifact_type: artifact.artifact_type,
+ artifact_id: artifact.id,
+ click_source: clickSource,
+ })
+ }
+ },
+ [wizardRunSyncLogic({ projectId }).actionTypes.runsLoaded]: () => actions.syncRun(),
+ [wizardRunSyncLogic({ projectId }).actionTypes.runUpdated]: () => actions.syncRun(),
+ syncRun: () => {
+ const run = values.run
+ actions.watchRuns('onboarding', run ? [run.id] : [])
+ if (!run) {
+ return
+ }
+ if (run.id !== values.savedRun?.id) {
+ actions.saveRun({ id: run.id, created_at: run.created_at })
+ }
+ if (cache.shownState !== `${run.id}:${run.status}`) {
+ cache.shownState = `${run.id}:${run.status}`
+ posthog.capture('wizard onboarding run shown', wizardRunEventProperties(run))
+ }
+ actions.loadRunData(run)
+ },
+ })),
+ afterMount(({ actions, values, props, cache }) => {
+ if (!props.projectId || !props.userId) {
+ return
+ }
+ if (!values.onboardingStartedAt || !Number.isFinite(Date.parse(values.onboardingStartedAt))) {
+ actions.initializeOnboarding()
+ }
+ cache.disposables.add(() => {
+ actions.syncRun()
+ return () => actions.watchRuns('onboarding', [])
+ }, 'onboarding-run-watch')
+ }),
+])
diff --git a/products/wizard/frontend/views/run-details/WizardRunSceneSyncDetailsDialog.test.tsx b/products/wizard/frontend/views/run-details/WizardRunSceneSyncDetailsDialog.test.tsx
new file mode 100644
index 000000000000..6b97197ba50a
--- /dev/null
+++ b/products/wizard/frontend/views/run-details/WizardRunSceneSyncDetailsDialog.test.tsx
@@ -0,0 +1,88 @@
+import { installMockEventSource, MockEventSource } from 'lib/wizard-sync/eventSource.mock'
+
+import { act, cleanup, render } from '@testing-library/react'
+import { Provider } from 'kea'
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { wizardRunsRetrieve } from '../../generated/api'
+import type { WizardRunApi } from '../../generated/api.schemas'
+import { loadWizardRunArtifacts } from '../../lib/wizardApi'
+import { wizardRunDetailsLogic } from '../../logics/wizardRunDetailsLogic'
+import { wizardRunSyncLogic } from '../../logics/wizardRunSyncLogic'
+import { WizardRunSceneSyncDetailsDialog } from './WizardRunSceneSyncDetailsDialog'
+
+jest.mock('../../generated/api', () => ({
+ wizardRunsList: jest.fn().mockResolvedValue({ results: [], next: null }),
+ wizardRunsRetrieve: jest.fn(),
+ wizardRunsTasksRetrieve: jest.fn().mockResolvedValue({ tasks: [] }),
+ getWizardRunsStreamRetrieveUrl: (_: string, runId: string) => `/stream/${runId}`,
+}))
+jest.mock('../../lib/wizardApi', () => ({ loadWizardRunArtifacts: jest.fn().mockResolvedValue([]) }))
+jest.mock('./WizardRunDetailsDialog', () => ({ WizardRunDetailsDialog: () => null }))
+
+describe('WizardRunSceneSyncDetailsDialog', () => {
+ it('keeps its stream across detail refreshes and reuses the dialog artifact request', async () => {
+ initKeaTests()
+ const restoreEventSource = installMockEventSource()
+ const run: WizardRunApi = {
+ id: 'example-run',
+ team_id: 1,
+ created_by_id: 1,
+ created_by: null,
+ environment: 'cloud',
+ workspace: { type: 'git_repository', repository: 'example/project' },
+ program: {
+ id: 'posthog-integration',
+ name: 'PostHog integration',
+ description: 'Set up PostHog',
+ wizard_version: '2.6.0',
+ command: [],
+ tags: [],
+ required_programs: [],
+ supported_environments: ['local', 'cloud'],
+ },
+ status: 'running',
+ stage: 'executing_wizard',
+ error_code: null,
+ error_message: null,
+ created_at: '2026-09-23T10:00:00Z',
+ updated_at: '2026-09-23T10:01:00Z',
+ started_at: '2026-09-23T10:00:00Z',
+ finished_at: null,
+ deadline_at: null,
+ }
+ jest.mocked(wizardRunsRetrieve).mockResolvedValue(run)
+ const sync = wizardRunSyncLogic({ projectId: '1' })
+ const details = wizardRunDetailsLogic()
+ try {
+ render(
+ <Provider>
+ <WizardRunSceneSyncDetailsDialog projectId="1" onRunAgain={jest.fn()} />
+ </Provider>
+ )
+ await act(async () => {
+ details.actions.selectRun(run, 'wizard_datatable')
+ await expectLogic(details).toFinishAllListeners()
+ await expectLogic(sync).toFinishAllListeners()
+ })
+ const stream = MockEventSource.last()
+ expect(MockEventSource.instances).toHaveLength(1)
+
+ await act(async () => {
+ details.actions.loadRunDetailsSuccess({ ...run, updated_at: '2026-09-23T10:02:00Z' })
+ await expectLogic(sync).toFinishAllListeners()
+ })
+ expect(MockEventSource.instances).toHaveLength(1)
+ expect(stream.readyState).not.toBe(MockEventSource.CLOSED)
+ expect(loadWizardRunArtifacts).toHaveBeenCalledTimes(1)
+
+ act(() => details.actions.selectRun(null))
+ expect(stream.readyState).toBe(MockEventSource.CLOSED)
+ } finally {
+ cleanup()
+ restoreEventSource()
+ }
+ })
+})
diff --git a/products/wizard/frontend/views/run-details/WizardRunSceneSyncDetailsDialog.tsx b/products/wizard/frontend/views/run-details/WizardRunSceneSyncDetailsDialog.tsx
index a0d16a75b3d8..3da3929b4103 100644
--- a/products/wizard/frontend/views/run-details/WizardRunSceneSyncDetailsDialog.tsx
+++ b/products/wizard/frontend/views/run-details/WizardRunSceneSyncDetailsDialog.tsx
@@ -1,4 +1,5 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
import type { WizardRunApi } from '../../generated/api.schemas'
import { wizardRunDetailsLogic } from '../../logics/wizardRunDetailsLogic'
@@ -12,8 +13,24 @@ export function WizardRunSceneSyncDetailsDialog({
projectId: string
onRunAgain: (run: WizardRunApi) => void
}): JSX.Element {
- const { run, tasks } = useValues(wizardRunSyncLogic({ projectId }))
+ const { tasksByRunId } = useValues(wizardRunSyncLogic({ projectId }))
+ const { loadRunData, watchRuns } = useActions(wizardRunSyncLogic({ projectId }))
const { selectedRun } = useValues(wizardRunDetailsLogic)
+ const selectedRunId = selectedRun?.id
+ useEffect(() => {
+ watchRuns('run-details', selectedRunId ? [selectedRunId] : [])
+ return () => watchRuns('run-details', [])
+ }, [selectedRunId, watchRuns])
+ useEffect(() => {
+ if (selectedRun) {
+ loadRunData(selectedRun, { tasksOnly: true })
+ }
+ }, [selectedRun, loadRunData])
- return <WizardRunDetailsDialog tasks={selectedRun?.id === run?.id ? tasks : []} onRunAgain={onRunAgain} />
+ return (
+ <WizardRunDetailsDialog
+ tasks={selectedRun ? (tasksByRunId[selectedRun.id] ?? []) : []}
+ onRunAgain={onRunAgain}
+ />
+ )
}