:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(wizard): remove wizard sync widgets and session frontend (#123627)
Fernando Gomes397c1e506c09
diff --git a/docs/internal/wizard-runs.md b/docs/internal/wizard-runs.mdindex a7c73781b0b7..34888b945a7e 100644--- a/docs/internal/wizard-runs.md+++ b/docs/internal/wizard-runs.md@@ -64,13 +64,9 @@ 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.-The app-wide sync widget uses a fixed launch cutoff with this filter for active runs and the five newest runs of any status. It shows runs from anyone in the current project, not only runs created by the viewer.-It opens one event stream for the displayed active run. Terminal runs do not open a stream.-It shows the newest active run by default, or the newest recent run when none are active.-The selector lists up to five active and five recent runs by workspace and status, with the selected run marked and the total active count shown separately.-The Wizard page lists any others. A manual selection stays in place while that run remains in either list, including when it completes.-Its card shows the current task, run stages, elapsed time, environment, and workspace. "Close" hides the current run until the page reloads, while "Don't show this run again" hides that run in this browser. New runs still show the widget, and run details remain on the Wizard page. Recent terminal runs remain available after reloading unless dismissed.-The `wizard-run-sync` feature flag uses the `wizard-session` and `wizard-run` variants to select the sync widget in the authenticated shell.+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 PATCH request accepts a terminal `status`: `completed`, `failed`, or `cancelled`.Failed runs can also include an `error_code`.@@ -158,7 +154,7 @@ Its `status` values remain `success`, `error`, and `cancelled`.The service finish event describes the full cloud lifecycle, including failures before CLI startup and failures during repository publication.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, FAB activity, run refreshes, copied run IDs, workspace opens, and artifact clicks.+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.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.@@ -277,6 +273,10 @@ POST /api/projects/{project_id}/wizard/sessions/```Wizard sessions remain independent from Wizard runs in V0.-They continue to synchronize the setup agent's legacy workflow and skill state without a run ID.+The setup agent can still write them, but the PostHog app no longer reads them.-The existing `/api/wizard/cloud_run` onboarding flow remains Tasks-backed until its TaskRun progress and pull-request UI have a replacement based on Wizard runs and Run Artifacts.+The existing `/api/wizard/cloud_run` onboarding flow remains Tasks-backed.+The app no longer starts these runs or shows their progress.+The insights sample-data placeholder still finds the newest onboarding task through the tasks API, so it can show that setup is running or link the setup pull request.+It refreshes every 10 seconds while setup runs or its pull request remains unmerged, and pauses in hidden tabs.+Transient API failures retain the last status for retry; switching projects clears it.diff --git a/frontend/bin/layer-baseline.txt b/frontend/bin/layer-baseline.txtindex 8993c30b6b1a..a7e3d0353c63 100644--- a/frontend/bin/layer-baseline.txt+++ b/frontend/bin/layer-baseline.txt@@ -455,8 +455,6 @@ frontend/src/queries/nodes/WebVitals/WebVitals.tsx -> frontend/src/scenes/web-anfrontend/src/queries/nodes/WebVitals/WebVitalsContent.tsx -> frontend/src/scenes/web-analytics/webAnalyticsLogic.tsxfrontend/src/queries/nodes/WebVitals/WebVitalsPathBreakdown.tsx -> frontend/src/scenes/web-analytics/webAnalyticsLogic.tsxfrontend/src/queries/query.ts -> frontend/src/exporter/exporterViewLogic.ts-frontend/src/scenes/AuthenticatedShell.tsx -> frontend/src/scenes/onboarding/shared/wizard-sync/WizardHandoffDialog.tsx-frontend/src/scenes/AuthenticatedShell.tsx -> frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncDebugPanel.tsxfrontend/src/scenes/AuthenticatedShell.tsx -> products/webmcp/frontend/logics/webmcpLogic.tsfrontend/src/scenes/appScenes.ts -> frontend/src/scenes/project-homepage/importProjectHomepage.tsfrontend/src/scenes/bootApp.ts -> frontend/src/scenes/notebooks/AddToNotebook/registerNotebookLinkDrag.tsdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 7c4397667053..e32736d9573d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1781,13 +1781,13 @@ snapshots:components-integrations-slack--slack-full-page-connect--light:hash: v1.k794b7964.43f9ed59c7ada1816c3868080fbed403f9d77b62366cdc4537779e3541e9326b.wItDTj0Z5U5FlAltTgn5YnNgC444wkCDR8yhBDf5KIocomponents-integrations-slack--slack-full-page-connected-all-scopes--dark:- hash: v1.k794b7964.5f07a7ca81ea242d0f1324a2e2ea6b5687057f1d2f88231f8c7ac0d3f959aa7b.PHPt53fppsCs3u7f48A50CiP6VAqRrxwr6uL2lhxCM4+ hash: v1.k794b7964.3b130834b7417de7dfb5f4d0568a926937ace8723bb4cb77a3671412e05966a7.cMHWcgKFnOQfumiOCpbQqMiiqmv4CZA2NApzb3GyPx0components-integrations-slack--slack-full-page-connected-all-scopes--light:- hash: v1.k794b7964.9acd9bfe35e19620c3b30279f484e40a019d6894f63ef92adc97b2bbdd4b188c.ChJjan_VyyddbM8VvsA5RIDOgr1BHLpidjzSE9O1qfo+ hash: v1.k794b7964.77dd222ec563b9aa7810afb4c82888705daa532b1367adc460e7879f72fa61ff.5KNfkH24O9MSKY7T2-_AiV69o-C_L9pY_CMHH1j7uU8components-integrations-slack--slack-full-page-connected-missing-scopes--dark:- hash: v1.k794b7964.57080295e3db711682eef4f811c2fabbf0351dd38a797086b3897cd109ec65ce.Zu-d4K9TvGeKyWNJ81HLY9kT6wkFkCpQq3KUd5Exvyc+ hash: v1.k794b7964.595f1f4786a388c9241b3cbbc782e3d0a2b436c2bef84ebaea50f425c557c298.kxskaDryzAHuppv6Kv8NNI_5jiLyJT_duBhZEoXcoEwcomponents-integrations-slack--slack-full-page-connected-missing-scopes--light:- hash: v1.k794b7964.55d53fef0a8690fd054e3a2f2b439790923928607c3e96ce8e84ceb8bfecb361.g2PwsLL0Ski-DPKuNdhEA5Km3UChJVQWPFr0sQG9z1U+ hash: v1.k794b7964.dcab274cc879933e82bdfd6c650520b0e0f3f4785b8db4183b76379569294803.fHps8LIi_ogsc_59TKPlYImP49araKsVOKoeM3hlJdQcomponents-integrations-slack--slack-integration--dark:hash: v1.k794b7964.1bcb0a5391d8290b0bdc18f53b3a3363dad6c03cfce5ffb28bdc4d8b26185f5d._h-SOFA2XkHyVKX9pGcZQItPw6XVxVXbouougXrIqkocomponents-integrations-slack--slack-integration--light:@@ -8326,22 +8326,6 @@ snapshots:hash: v1.k794b7964.f5f068b9fcb09a322383e37d0e2bd1128ff6adeed932826d62161a1902e9fa91.QO2io3ZYVVvjY9thRJKCoY2e0yBnpSWzHiHDefLz3Dcproducts-wizard-wizard-run-diff-viewer--narrow--light:hash: v1.k794b7964.2ea84850b2a15dfe74254e4439305686f9718b0627f1bc8ca05a0fd428fcebba.qvBX7qTpArw7bMv-azF7FL1HSBhsl9BhNblAoqlGpi8- products-wizard-wizard-run-sync-card--completed--dark:- hash: v1.k794b7964.b389514fabb5dec603e6ac02cfe893d90ee793ced7fa06fdee051ab218ed9e6f.ifpv5W-1BCjmRB-laDihXTly_4UxYYZfwk0_xRMcVoo- products-wizard-wizard-run-sync-card--completed--light:- hash: v1.k794b7964.0d171f1dd84ed010d842617f35781f5d1b31f4222c48631e6854b76a56106ad3.3MBXO6B3RlDeEPOSAIHl4RB3UffoZOLrBdN50j8GCH4- products-wizard-wizard-run-sync-card--local-running--dark:- hash: v1.k794b7964.070388138ab8bc5e20c611f5b42036c39901c3317beee7ba8f6aed70af62676f.sk2IJooQi8BK7jzJ2f_fBf7oRzT84m5IITvhwWu_09c- products-wizard-wizard-run-sync-card--local-running--light:- hash: v1.k794b7964.a38acaf7ddbfa37a3eaade8958875c54749471c262ddb52f0eade0d1d4b198ed.CbsNAL-B-ud5AUggvwVq5ub2-kDqUp8TWuRRxm1rO08- products-wizard-wizard-run-sync-card--multiple-runs--dark:- hash: v1.k794b7964.e789ca3d622fa2b08aee57c2baadd6bb0a52300e488a8f930de58cdab26cea69.DGYEtSMfDUbr2sATZhkHRT2_QvZGDJFNgDapxqrzThE- products-wizard-wizard-run-sync-card--multiple-runs--light:- hash: v1.k794b7964.69189adcaad12ad70369068150d954cd8c11f9d56c6c1bfb0bedee839a69b2dc.TkYYU8OORDZougolY7DYEZYahFzy4aEQCqeLS9DFsY8- products-wizard-wizard-run-sync-card--running--dark:- hash: v1.k794b7964.b59d3e3b569184f8fdd9029c1c2067b053e8e135173c37218bfe4c626079b7e3.v2d325yM8eofSv8GOhTRsOEFjAoT2k8AHsyUXsGxaHs- products-wizard-wizard-run-sync-card--running--light:- hash: v1.k794b7964.df30028d9399928f4b1c8d2ad87fadb9ce6597419600e07b57b35d34ac9ade93.zpJJ3MjyG1rhJm9eAq8JTYdRRteI3ptNuZor2nr8hOAproducts-workflows-customerioimportmodal--all-steps-completed--dark:hash: v1.k794b7964.4433daf4a6f3ad289f37cbc466609a947b254f8b3a027357d05e00a725c57fa9.06a8j_j5NyzCTMMcfO3UH1b6ZIvt9oDgSBHpTJ6JOFkproducts-workflows-customerioimportmodal--all-steps-completed--light:@@ -12570,10 +12554,6 @@ snapshots:hash: v1.k794b7964.20a12c4fb2c623d2f393d883f0a6f2313fe02e628dacae11f07d8bf261d485d7.2_h_OhXXlUh-PRzAfR73B2CC9-lWJEvC8CazFui-OUEscenes-app-inbox-scene--inbox--light:hash: v1.k794b7964.ac90d148508d247d2ae17c5487ff013c4e40b00eab688237641402bbb4b1f7b6.x4pedqoEQOX7MVMR9n3LRXRXqJFCQXTOjVVhH3d0CYk- scenes-app-inbox-scene--installing-self-driving--dark:- hash: v1.k794b7964.14709655eca7051b8b75552501e606315317ca917bc308c113f184b2e04c73b5.6_dNVe1Wmq2kk-lsqTng3JBbqIG9BWkd9-CcABUDvIY- scenes-app-inbox-scene--installing-self-driving--light:- hash: v1.k794b7964.210aa02f090b14972638f537dc9963f1c3084ab0da4aee6081eff9c2095d6820.px0spHyEFZPWte0oVgw5xWNoDP9oTF_JnV0dURw9SpIscenes-app-inbox-scene--report-with-many-evidence-items--dark:hash: v1.k794b7964.87b4023d1181af0c9f5d86706035c57b717b85fe9cefaa264eccbc7d63937c2a.Fc7NrUn6tbhkkGPOhgnqH55HuLQgVJfyEQjfMR_hWSkscenes-app-inbox-scene--report-with-many-evidence-items--light:@@ -16810,10 +16790,6 @@ snapshots:hash: v1.k794b7964.99b591d1a81bf5348da5564b8380b3a0f5d2ee720d624fc198a0db099da8605b.Dss3uZ6TjFEIb8TX_b0lrLjmh87ZvqO96RU5LcfAld4scenes-other-onboarding--ai-observability-sdk-install--light:hash: v1.k794b7964.32d9b7b59052431c97def2934189b7c082f55963f2eb90dfe604c29db584ea5b.jWPBTuIG-_5DDjN24_KA1xuwUJnsQnCVYbUMUo_7AzI- scenes-other-onboarding--ai-observability-sdk-install-with-cloud-run-flag--dark:- hash: v1.k794b7964.99b591d1a81bf5348da5564b8380b3a0f5d2ee720d624fc198a0db099da8605b.wX4MHhE7fbYCXaOlsmTg5XXuPiRX_vby-IJTJkzT70g- scenes-other-onboarding--ai-observability-sdk-install-with-cloud-run-flag--light:- hash: v1.k794b7964.32d9b7b59052431c97def2934189b7c082f55963f2eb90dfe604c29db584ea5b.l6brHKy8JSO8-nkw-zvd9_wlhxxvAzp4AOSxLNDnnkoscenes-other-onboarding--alerts--dark:hash: v1.k794b7964.bb15a17dab8c6d94d7fce821c4eb5530e6c5e353a6f158134443b2e77e344b11.uRoH5DqZUWqQzdv8c5pM__vNu1MjSvicrhSdKKREUnwscenes-other-onboarding--alerts--light:@@ -16870,186 +16846,18 @@ snapshots:hash: v1.k794b7964.a355f36bf002a119233c8592bebd8c34a0d3aad8050a01a81d2593f1e32ca904.wr-z1hhmoZg1XERZ_bK76Xjx--dCEmDeb87X8neB598scenes-other-onboarding--workflows-custom-installation-instructions--light:hash: v1.k794b7964.0edcc48dfab6e88670a09070350f73a96c21d160bf38ea8027f26492fae286fb.oUJvy8bgtNdYIhWFnn5-9uI7PlAkT21f6ExVDx6jANc- scenes-other-onboarding-install-step--cloud-run-in-progress--dark:- hash: v1.k794b7964.ad4fcfa9cc9df360e913fcda6c88237211750e26c604be536444594031a508f6.WIDlaN8ByKeWnqddw6vjZiSEB7EC48tw6dQs9Bqxaxc- scenes-other-onboarding-install-step--cloud-run-in-progress--light:- hash: v1.k794b7964.704c60485fa45afb873967e81cc163e00b9677ddf65387390bfba267fcf32baf.POic8YLlFQHnGLJxe9Lfd92NFXKK9-NhJ19lENha1T0scenes-other-onboarding-install-step--control-arm--dark:hash: v1.k794b7964.3f953504a96f3d295e23721dbd39a6282ce5f719a7b7a50ca2f083c3c061660c.S12DDcG_kP6-5Y0hlBTZFDKUKAuzTBP9kPXFlqI0umEscenes-other-onboarding-install-step--control-arm--light:hash: v1.k794b7964.03f1893573652b0c32218385c83819272c30e7a87647ea479aa6c17100efa604.Ullr23ou7-8Q_0mO44avKU97VGRSbZGcK96bg8Hlwyk- scenes-other-onboarding-install-step--simple-flow-cloud-arm--dark:- hash: v1.k794b7964.df9b92d8c888b475bd93f5ace1352d25fa664bd9ed03c857b021eb890a37333a.FzEQJH0X0v-bL-GrgcgXSOWOQ8yTofhtNvyr7f_87Bo- scenes-other-onboarding-install-step--simple-flow-cloud-arm--light:- hash: v1.k794b7964.db6e985814b37a2e586c9fa49eb3d3bb389d54473d068389512c1aab3e4caea5.VNhgsuAfDompEhCACYLMHjUva4JI7Br1V3_bdZuDHhM- scenes-other-onboarding-install-step--simple-flow-cloud-run-in-progress--dark:- hash: v1.k794b7964.365c4897a5ca3f25a79820327beb8aff012b08437d44eb4cd1e4de5c44e32371.BgFgX38cWgmPVLemqWUizW8WftkfjwhrDS3PrAIo5ZQ- scenes-other-onboarding-install-step--simple-flow-cloud-run-in-progress--light:- hash: v1.k794b7964.c67745495d59c63a1dd66de572842eae2ea5adcf2f841cf1bddabd5390c44b7d.9GgxjXMFJ25HXlIuFQ4nN1waOlvtFD0O1bBjMDze4gc- scenes-other-onboarding-install-step--test-arm--dark:- hash: v1.k794b7964.02e757ddb1ee8fd40b5b20f4ffa67c2c01adef3aa14454056ef9bff28c73565c.9MnHMgx2YubgCwkEhohWJUbiMaOfaxOKCsHsCGqA9Mk- scenes-other-onboarding-install-step--test-arm--light:- hash: v1.k794b7964.949de7407890712b6d3d2fd9ded05dded417bf9b56cab651746e4df685d179c9.uRQ5qMOFesy07o3rzNVchTwmhmqEhiGnZTzDyvx4Q4k+ scenes-other-onboarding-install-step--simple-flow--dark:+ hash: v1.k794b7964.82e295b93aca26c287b4207345daa25386169a22f859bcf6ffc826dc119fe753.gcs2PUEkwq8sVKLDiV89qsV53RH8PgsAaC1iPJ9WQ04+ scenes-other-onboarding-install-step--simple-flow--light:+ hash: v1.k794b7964.125b132e09d3238ca209e88a17aad57778c93ba453d6b8c1a55bad2cf9a37c81.xneZrlfKJkSgGBZkZpeo7_i45_aJE9A0mFWZ1cwiqpUscenes-other-onboarding-product-selection--base--dark:hash: v1.k794b7964.b60ec49c9c54425935da72dee08b9af582389d080594a5ab04047940ea3d2ca0.BUp2Cv79bdb2-k0twgulEJlDBQ_Ipk0dL-SoQ-3MiD4scenes-other-onboarding-product-selection--base--light:hash: v1.k794b7964.e5c1b8b7d8fee3b4c6a4cc3703ee0e1b2f7b00a89209abe8f6ce3a24e4fa8c39.AGzFde75eRPi_uCkV3I1rh8AYJsOfU_7GVRrQ-hYiZ4- scenes-other-onboarding-shared-installation-progress--all-states--dark:- hash: v1.k794b7964.f27ec49d9f5135f7c07e378091bebea93949d910823f9f9d498f162baa1e5536.j1ZpoUvgIKsVhfaOTJ5j5M9ycLq6FAL3o1w-7te1Rqw- scenes-other-onboarding-shared-installation-progress--all-states--light:- hash: v1.k794b7964.eabb93282dcad2997538e4794784640cf1ffceba4da5bb74dd4cf322ca483971.LrAr55BBERISTpjnTdeRppsc-iJa05lP7_dXIscZRxM- scenes-other-onboarding-shared-installation-progress--completed--dark:- hash: v1.k794b7964.a5c39954664721c5f485671e2144a599f4bee52af9d43d3eba9d5469d10b34fb.RwKIupLIPaIjkqA-87qce-fCE6iJ9J4FlanTULVNY24- scenes-other-onboarding-shared-installation-progress--completed--light:- hash: v1.k794b7964.bcf5d2def507944709285c026e238335307c02ad344b7216536be2b9e29b344f.PO-TsJat5OfrttiFuq4wkZMAOx3I5QROXVLzBPvGg18- scenes-other-onboarding-shared-installation-progress--completed-local-handoff--dark:- hash: v1.k794b7964.54ae5f41796064680fe877e8abafbde8ea98cee8546285b5a02331e33fac858f.Kh-7hjN_VcotxJxZa4ApD0z8izu71VI8KI8bEbD7Vf0- scenes-other-onboarding-shared-installation-progress--completed-local-handoff--light:- hash: v1.k794b7964.fc63a53dee20d549c4ea64c895f15c83c26eef9c2dbf2ada40deeb9277d57d26.cpt2CC2sMf6gWij9n7HjydPHfcL7hkyD10fRCCYKkDM- scenes-other-onboarding-shared-installation-progress--completed-merged--dark:- hash: v1.k794b7964.e41a47c6d198618b61635ee98c7424dcd8893284a69cf72c2cd18bbcbf1bce4c.Q8Ahyvmp_7fhazPC-B3XSNQd9igBc1zLpI5tzQYOMqc- scenes-other-onboarding-shared-installation-progress--completed-merged--light:- hash: v1.k794b7964.ef1b2c0a826afa7076da12b56c7bd333632b2e4bb0328a7c58daa8d62312f837.AWVXxeb0paS-ddXiaEy5oF6j6KvJ8ATAdTaO0S7Qx0g- scenes-other-onboarding-shared-installation-progress--connecting--dark:- hash: v1.k794b7964.c979fc93fe8ea9d6a8d7ecfc667cba31879bfcafce56b1f09ae143d43e77efce.cHHBvXk9MnAaTdks6cwqJLv_--qKj8AwUXIv6FZRV3U- scenes-other-onboarding-shared-installation-progress--connecting--light:- hash: v1.k794b7964.de2fd7cd21b7ee81c5b164e9a32da2778f866868edcbc6a4857b8d7b689be980.KikveOWdAWy-4S1PbWC4YJf08W6t-_jnps05QAoDSkQ- scenes-other-onboarding-shared-installation-progress--connecting-local--dark:- hash: v1.k794b7964.883bd63d429ca952e3fada4ffb8d6079068ecb39cfa9a36ade3f1f10c09ea293.Jp3lHkTTExFAPCEN83NenmIXpRikBD6O99Cs6QpdyNw- scenes-other-onboarding-shared-installation-progress--connecting-local--light:- hash: v1.k794b7964.de4738c6722563365787947eae922187fa65758070fc5d0c875931bedd1bc3ea.BgoC-hE3JTwBmDrHiLITbiYcfNPEdnAUmiImKSgWNYI- scenes-other-onboarding-shared-installation-progress--failed-clone--dark:- hash: v1.k794b7964.70ffe6826a0c102c60c4aae8cda14b9a8d63898542334bf258d0b1f3dc85cce3.KbYx6q0WrGLiQh8AnwTRAMIa5yyHXzSghEVJFjdthh4- scenes-other-onboarding-shared-installation-progress--failed-clone--light:- hash: v1.k794b7964.94c4fc6b8198ed716157034597c767e3ae39885871562e988a079e3270efc731.1sYwXTZigpehFl_vV0bOKZtVtv4pRtUNLrIPw37a5U8- scenes-other-onboarding-shared-installation-progress--failed-no-detail--dark:- hash: v1.k794b7964.58610476a191d7d7ed2c8594ffffbd14d485ae8ff3b3cb52650034c879982ee8.alL7O2YP-vp0_l-YCMpnXOaX-FfhEV9eO6vHSH3izBQ- scenes-other-onboarding-shared-installation-progress--failed-no-detail--light:- hash: v1.k794b7964.5991f74c2c2c03dfc42df0586a3a5526c2c1c3077dbb4cce75ba192be46316c7.Gs16jzYhNytlMnlz_X-_bKYcDFBDNdYgliVKiONjP1Q- scenes-other-onboarding-shared-installation-progress--failed-provisioning--dark:- hash: v1.k794b7964.7fcafd04ed6c719a8ad01cebc7abcc7265a3f677a2398e6ee19004eac26d1eff.kASMuoxhwilbDbtUhEblU0HnMTCXcWhk0aGBx34zYYk- scenes-other-onboarding-shared-installation-progress--failed-provisioning--light:- hash: v1.k794b7964.ae9111e8e758485d7791e5d85cd44d5cd5ffb2d5ec8948b1a9bb360455bc6674.O0Mx_17KqsoiMCWOgBgvn9w30i-uCzJpz05Jk9K3Isc- scenes-other-onboarding-shared-installation-progress--failed-usage-limit--dark:- hash: v1.k794b7964.60aae9b667df8cbdb74bf7419d201ece1ecede99bfb47de5ab86ca92cf29a3ca.vJvgDkUSC7s5hJ5wiiC1F7WgLlRUqmshkqDn5bOB0e8- scenes-other-onboarding-shared-installation-progress--failed-usage-limit--light:- hash: v1.k794b7964.50c4be57a0b7f54e4f9576afc3c8640b7fe50d81fb5ac53491a7627514c98759.2_g9z9UW7cdf77LuleEVHVIKOKW9qDlojT8K9IRbrLk- scenes-other-onboarding-shared-installation-progress--failed-wizard--dark:- hash: v1.k794b7964.3a1cef199fe6ff0b83ed59eb7c203067ceb40d28992890194f4b65eb54037063.G8lqwGkC_dmlyq1MoxtZlaWREPKsfAmXjlt1i3opb-w- scenes-other-onboarding-shared-installation-progress--failed-wizard--light:- hash: v1.k794b7964.0fb344f11f3320139a596e39e0e980e9ecda58bab2cc7447c3e2876bf98ee9f7.bJH5sO50ROg-bcX5kue9erVDrEy4jni186glKF8rt-4- scenes-other-onboarding-shared-installation-progress--floating-dismissible--dark:- hash: v1.k794b7964.a21998e89bf8467ab55efee9b035db51afb042ebe36551e9a47273ddf2e67609.AODFzzcBWc0nJzj1J_lobuSKcS21_mFsYR-ITbTH21Y- scenes-other-onboarding-shared-installation-progress--floating-dismissible--light:- hash: v1.k794b7964.4355159959fbe751c547f2900ca7113b7da45a0319fc712998780ffda13ae155.qNAp9aF20iIG8GW2eU-heTT4kKRwhJEvcoiZzeojdJg- scenes-other-onboarding-shared-installation-progress--lost-contact--dark:- hash: v1.k794b7964.dae9f74c48a511842537f9ec2ccf1e76b6909b6dbc318665a24091ef369ee1b0.A475B62vNvHQlT0-mfSGoaJIzoOGVUzqCnNB-DT7vvY- scenes-other-onboarding-shared-installation-progress--lost-contact--light:- hash: v1.k794b7964.cf38a26713c8ed464a7de37e7edfb1c9774673f4e310cec29a1db98cb96419e0.CFI0ueTLg5KlXQvzl2TaKR_CpKonqflTgzi513HRD_w- scenes-other-onboarding-shared-installation-progress--playground--dark:- hash: v1.k794b7964.73dd3b1ca302d1d915814fb1c93516188ee3a6c010a9deedc21aba892b0c4eaa.TED9G6l7yoWOiiXzoG27nGeTlcy4E02tWrI0-iEqOBM- scenes-other-onboarding-shared-installation-progress--playground--light:- hash: v1.k794b7964.136fe9ea63b8e3301642e87d677f6e9d46f1796683a666a3ab18ee23fbbf5539.4sb2JpWGGJR3UBjBelT0C_Y2JvuppqCQCzwvFT5RptI- scenes-other-onboarding-shared-installation-progress--pull-request-merged--dark:- hash: v1.k794b7964.638b946e49e098d04583d90f6053b75d9597545a5b5a6312eb9d8b49ce06cc5a.K30fdLzVMN7H433eGeF5ISIPzVLjOJEE7Br824UVNwM- scenes-other-onboarding-shared-installation-progress--pull-request-merged--light:- hash: v1.k794b7964.814693ea93fbe19868432c9a60ad3b5d59d0c88ec63b6c240dac5db2cb238099.QtWxBAEYXexElR040I3uVGt4k_szR5SODeH12s3ZyCM- scenes-other-onboarding-shared-installation-progress--pull-request-ready--dark:- hash: v1.k794b7964.c0dd7977c4b4e125098401eb4643e2896f600b116c04bf0ff56f09de25579835.x7qV5sJxPaxI27L4YuzDnvP5qLdsHcFQtGRM1cQE23c- scenes-other-onboarding-shared-installation-progress--pull-request-ready--light:- hash: v1.k794b7964.458e8704b135fff8915a132d5b7f53ab5c9afb7656c9bf9e4f76b56e12de8741.2KxhAyq-ILY_fcnXJLF9UCFJTVOXjMG71pclz8wapDI- scenes-other-onboarding-shared-installation-progress--running-provisioning--dark:- hash: v1.k794b7964.e58710cd2f0ff91e2bd88191284a11f60187e134263860dffd3df13cca06f21b.59LsqQjRRlzraOnea_lmuyDVCNXp9a0GP7x7vszqzKI- scenes-other-onboarding-shared-installation-progress--running-provisioning--light:- hash: v1.k794b7964.7395683f7e441f8329644b9081d672afa6bd863d844cb654312b052316697314.R92_90heZOueGfKYPpzrFspW32OFs4aV2J98R5sjiYw- scenes-other-onboarding-shared-installation-progress--running-wizard--dark:- hash: v1.k794b7964.79adfbd6331ef6d2d893fa8dbfd8ef3f7669cd44c78b105abc94a95ec176f21c.7PqVKbq6z8ASe9S4ILXbDZMFzXT5KMKYnIf9-Fu0Ld4- scenes-other-onboarding-shared-installation-progress--running-wizard--light:- hash: v1.k794b7964.c6ad24b9d785ebe203a5bd7f52d8ce95c22627709eb99f43a8035c27805a6a4d.65BK591qtOlIdohy6c4QY_b0-4qLXTGPiilnI8BuMp8- scenes-other-onboarding-shared-wizard-cloud-run--connected--dark:- hash: v1.k794b7964.1ce5366ddf7653d94db593d6cad5f279dded5f538ef74ef2dd030995cd4e88c8.kr68p-keSbcj193CXgPaLnTbsPks4qA1GWl6LjGab48- scenes-other-onboarding-shared-wizard-cloud-run--connected--light:- hash: v1.k794b7964.7ebfa7872852aacf3e3ae1fb35ad66970df87660446283c0318e6b59eb69e940.Ey8rwc9TnU1jVe_qEHx9cRJ4D4eC1_5lggbCT5VJ0d4- scenes-other-onboarding-shared-wizard-cloud-run--not-connected--dark:- hash: v1.k794b7964.acdef11c6b1058dacf532d05fd67636244f201a1c52f7c902de5e7249fc45075.LMxfSHX_C1FXJXo3DZdahPSeBIvUoJ2Tu0BtNoP5VT4- scenes-other-onboarding-shared-wizard-cloud-run--not-connected--light:- hash: v1.k794b7964.046d88670afad91c9214519ccb751537a46d8f90170c5465cd6956720245efc5.N8CSJNxVehmP96bOtythkT4H3KHWuSV4kBVC-bXcJ7s- scenes-other-onboarding-shared-wizard-cloud-run--playground--dark:- hash: v1.k794b7964.ac153cecf12df4984b50f911c82a953d0e9ec3b77d3ec7aae64980c21ec0e84c.maA8DUvFiPq_6Kln4Q9WZAl6VNkWB62Wwx8G_GDfOzw- scenes-other-onboarding-shared-wizard-cloud-run--playground--light:- hash: v1.k794b7964.89b12fe7e6f467daa70d1e8e2b0775c620137ebf940fd1dd1cdb8fc6e6d6d51f.L4uxBbKm6JjeA_3zz9amB89ihed2ZNAaUXpLmyLNX7I- scenes-other-onboarding-shared-wizard-cloud-run--pull-request-queued--dark:- hash: v1.k794b7964.c2039ff14cc4b1bdf6222d7f10fd5da815cb0b31472c468f6688aa0037692bed.YHla-5uZOW2jdpA5p5GKOIKBlt-kLBp4-hz2pvqHEDg- scenes-other-onboarding-shared-wizard-cloud-run--pull-request-queued--light:- hash: v1.k794b7964.50e1266f1e861c917bb687103cc9d91e1d5f50838bc4a5777876eef5b7a26cab.xjGijhzQBDZPiWD6RrPXspib-56zWH6CmaWT5_gz_yA- scenes-other-onboarding-shared-wizard-cloud-run--repo-picker-open--dark:- hash: v1.k794b7964.86fa9c4496b5d280b84b90c0302a90fe624103308f8950fe74fe20fb82007366.sHbVDI4ZO7poJbeaA1bkMpEoMiMJcPqysKIJw8Bi6aw- scenes-other-onboarding-shared-wizard-cloud-run--repo-picker-open--light:- hash: v1.k794b7964.f62c285e332b519ece409508fe0e0fce4e84a2eb9c0d85fc60c0c768160459d6.Gcsq5CXVb9m8E8V9aJBbZ1FMc3RzBrxfT7Ks5qrMSI0- scenes-other-onboarding-shared-wizard-cloud-run--repo-selected--dark:- hash: v1.k794b7964.ac153cecf12df4984b50f911c82a953d0e9ec3b77d3ec7aae64980c21ec0e84c.7S1T_r89HZTVdEnJ5u5ng8O0ieDiyMg2QfudRL9hJQs- scenes-other-onboarding-shared-wizard-cloud-run--repo-selected--light:- hash: v1.k794b7964.89b12fe7e6f467daa70d1e8e2b0775c620137ebf940fd1dd1cdb8fc6e6d6d51f.OvuTsg8C0z8E4iE9S6aMFub_i2dmpQP4kaC02XM8bM8- scenes-other-onboarding-shared-wizard-cloud-run--run-it-yourself--dark:- hash: v1.k794b7964.5a35f0677ffb11febcba8084a0ccb558ecff39d861a8cd8c6501671f47a1fac2.Of5i_K-cfe3g96_a6dHtRI0PeaDjaJ0rdWZMi6O4aG0- scenes-other-onboarding-shared-wizard-cloud-run--run-it-yourself--light:- hash: v1.k794b7964.acc28e25e011b28ef72f89cc2e2494c5b20d4df504f501b3841777f33caecc2f.yvS9TBOTcaphHhW5g2EW9hNjWcKf7TidUb2f2Tp2ROk- scenes-other-onboarding-shared-wizard-handoff-dialog--opened--dark:- hash: v1.k794b7964.810fb1774d7f9ebf7b63cab5e3b5a45606bb9f498c3aff4ee6ee4d45bbb33123.jD9rqBcIaYTHx4mQTQs73wzG3zM_WtCv8UutSWtnny0- scenes-other-onboarding-shared-wizard-handoff-dialog--opened--light:- hash: v1.k794b7964.4d516d425a6ca045ff7bcc0645341bd4c2e4ed0d1a4a5be97c8ae6ed27ea4839.L7gQvpwmqU9bjiJVp5-SCjjQsl8zwTkNhKAzGc4TidM- scenes-other-onboarding-shared-wizard-sync-card--all-states--dark:- hash: v1.k794b7964.4de365c2b65ca7d49ff0f39a2a040b2e08ba2e5d8f7cb7ca9fde78b966fc038b.RAPRNUnyG1v_M-N5gkvUBP7EQpdV3HlqmTYmRAbxzRo- scenes-other-onboarding-shared-wizard-sync-card--all-states--light:- hash: v1.k794b7964.920b94b7310ba6ca3c115f434164d806fd25300237347e583ec8c46d9cc01b1d.MBbUyGnBshoWMOTUiPa01Ngs6G8SPFQFBZjy2iDl27o- scenes-other-onboarding-shared-wizard-sync-card--cloud-keeping-ci-green--dark:- hash: v1.k794b7964.fba9c3af456f60a00dec760305609433d1d8ffb609f1573352f71cb29f1fa6b2.2tmy7T0O1t2rw1SYTOXCMCePVPleYZWjuUnc4EU5a7Q- scenes-other-onboarding-shared-wizard-sync-card--cloud-keeping-ci-green--light:- hash: v1.k794b7964.5f4e8d2dc89a2d72257ff2f0d8f31037586de10147d2afb4258b51393dd2422e.UalM3WZh4Z42LDzofIc770L1bL-I3--5yYoPyHkE_rw- scenes-other-onboarding-shared-wizard-sync-card--cloud-wizard-running--dark:- hash: v1.k794b7964.c69534afe39d0311b0ed3247beb145b94381706a25f2e6c7b5d3415c87564375.0VCSVCtYrJPx_h_nck6OJYWoF1WYaitbX1wtcql9JUA- scenes-other-onboarding-shared-wizard-sync-card--cloud-wizard-running--light:- hash: v1.k794b7964.0cfae6b396d23d4bf84998b078b2bc21d231cff6ca91c6ad72287015ffbc3612.Nqks6pgFbq51kBcq0GujrhNTSnl__D3lqAVAdBvfSaQ- scenes-other-onboarding-shared-wizard-sync-card--completed--dark:- hash: v1.k794b7964.cbe10b004d48825cb5d32c97202005cfd962aa87bce2b10012be22db03d25d22.HqoMOp0OoJZqLjwfHXRn13XRvwdOFObzdPKfijwaWLY- scenes-other-onboarding-shared-wizard-sync-card--completed--light:- hash: v1.k794b7964.466de6282ec983ff5917df90ea8d0e65106e91957af246554375d8ea140b22f5.Nn7X9ZeY0nRHXoYWbI7DphrUf5qfvB-31Pr8bn-a9LQ- scenes-other-onboarding-shared-wizard-sync-card--completed-local--dark:- hash: v1.k794b7964.5be2ade3340eb7d67a5996891d3c3d2575f94b9abd4a462f1276ee3466cf4425.E2i7G97orrTue7-H34-0pofN2nuykAjrbge_a_79EHo- scenes-other-onboarding-shared-wizard-sync-card--completed-local--light:- hash: v1.k794b7964.c33efb6554e27c18637f34cb1282973d7919a237fe5ee632ccc8bda15e1210d1.NM3GIOLmjmkD8NfAV0ud6NHgstOSbmiteNlBicx8SEo- scenes-other-onboarding-shared-wizard-sync-card--connecting--dark:- hash: v1.k794b7964.61398434096848c5eb49dc43a6649548981357049ad0e237bee837e83da9eaf7.wPw2Z4LDdDur-vsryi8JhcHJ-LFpgwc1rVX6rmn1Ng0- scenes-other-onboarding-shared-wizard-sync-card--connecting--light:- hash: v1.k794b7964.00de83bd008d8ea2c3020e7c09d2acde3da28546225c780c6df558ce588403bf.GI2el38jH7WJgGOjVlTOEppP2tfVFQIlutUsIDe9S58- scenes-other-onboarding-shared-wizard-sync-card--failed--dark:- hash: v1.k794b7964.0699d0268f15fd6d9502d0642c901b5d233088e66dae63e4529bf8dfad525932.hZeKlAlNg4bCEKbgqL48EJtg3Os2FKEmfFx0aQho69g- scenes-other-onboarding-shared-wizard-sync-card--failed--light:- hash: v1.k794b7964.50b5fa9355ae6176715bf17f02954d776dbcf74ed53ba5cb084f7272aa6334f0.0Gs7PPLNlQ8aUC47bK5rAgtYKWhs8ZTzxUl-Xpqobvo- scenes-other-onboarding-shared-wizard-sync-card--local-running--dark:- hash: v1.k794b7964.8ebd0fb0b9db1f2cc68bcb63d890a44003403e27688a938e5cb04fbffb3b5d5e.aKxLz7jngQZcJL6b0nrArk3V-pDEoGNoPsYUiGbIYy4- scenes-other-onboarding-shared-wizard-sync-card--local-running--light:- hash: v1.k794b7964.644de0941a464befbdd1c1173307918762ec7bf580d08b6bb73e0170da71ab57.roPN1jIIWT47y5Xh3Gluqd744nCUVhJkfniX1oq__3M- scenes-other-onboarding-shared-wizard-sync-card--local-running-started-by-teammate--dark:- hash: v1.k794b7964.9238cd8306270044b6be400d8b253942a6ebc7639dac27e091afe3afb5900291.1tQS7yVR_gZ7fmjjzoegrw7GXmePG9-QafLgOaddLfo- scenes-other-onboarding-shared-wizard-sync-card--local-running-started-by-teammate--light:- hash: v1.k794b7964.311090aa83634a64027ca60d44a1ac93ecb22124f9144032439c364e0e513105.jEWKZmu_Lw9ugOlP0970x-jQom-SKcWM7N__q-UTgT8- scenes-other-onboarding-shared-wizard-sync-card--local-waiting-for-input--dark:- hash: v1.k794b7964.882a0f73b32a910ae1582ef69720f025078bc35867e04d6a03e4931999999ae1.udwLNxP_oZh1qhyS1Ce07RtoSfNpckSBGlOxC41rVp0- scenes-other-onboarding-shared-wizard-sync-card--local-waiting-for-input--light:- hash: v1.k794b7964.9369015b4d74aebf27366e91a570c6d59f1cf2424f3b4c8de7bab1bf2a6cee16.Xu1mzkKb3bbUjVa7FC-lADj0seNneKJtEBvNaPcZwvI- scenes-other-onboarding-shared-wizard-sync-card--local-waiting-for-sensitive-input--dark:- hash: v1.k794b7964.f074463c40fd8b34d0ca55c651b409fb35668ecc69fefb4e631208b3f5db1bde.zioGxlu5eKa64EXl2wzmAT4K-EC_0eK5uoUMxZIu98Y- scenes-other-onboarding-shared-wizard-sync-card--local-waiting-for-sensitive-input--light:- hash: v1.k794b7964.57524d53d6835dd9472c87a6aca291266fb8e8971d95ba311842386f94347fc8.sMjUBzJVzLkCThwa5LT8ntVK63w5tJ0lYltmn2pD70E- scenes-other-onboarding-shared-wizard-sync-card--playground--dark:- hash: v1.k794b7964.c69534afe39d0311b0ed3247beb145b94381706a25f2e6c7b5d3415c87564375.ViSw0_amXLmDYynCEuR_kgnY5Ncm4ULveglgIJoTIaU- scenes-other-onboarding-shared-wizard-sync-card--playground--light:- hash: v1.k794b7964.0cfae6b396d23d4bf84998b078b2bc21d231cff6ca91c6ad72287015ffbc3612.G64MtMVMRObRn64tStKU_8edvGJThXVEEXPHQhxtMOY- scenes-other-onboarding-shared-wizard-sync-card--stalled--dark:- hash: v1.k794b7964.5d437bffa8c9834cf88a783f58dbab3f625c27839ac872f0c2db7fd4b08f4ed8.sOK517AeohAmtL0coLOcSFfAB90HUEtQGr2HwmZLoi8- scenes-other-onboarding-shared-wizard-sync-card--stalled--light:- hash: v1.k794b7964.b52a107e85cd22687e6bc1dcf23a4067f185915e7aaa4518b39ef1bbfefe87ac.TU0cv3huC_bueumE3zh9JXnBoRGtM6FKvdbtqCcUL4cscenes-other-onboarding-welcome--default--dark:hash: v1.k794b7964.b2aafd7f923a67f40aa8e6be9fa012079073b1c8143e848b3e9d166c0036b334.FQvjQktw1Z0LAVV97BAiSLrHTRMq341uL9h5e_v61wMscenes-other-onboarding-welcome--default--light:@@ -17315,17 +17123,13 @@ snapshots:scenes-other-welcome-dialog--no-inviter--light:hash: v1.k794b7964.f766cbd27b7bc11b50ce42602ca2fcab11fa005e795aad0d66e6f67e627570d2.M3CFGWAqq3ebMX5h9Rlb9cCCOBUfhrdc86fQexL6-MAscenes-other-welcome-dialog--provisioned--dark:- hash: v1.k794b7964.f2c3d2da5c26ff0d4e4883583589df344c65b8d6b58ae37ef5c4792c02b5d026.G7Cluv7BykKb0ZB6ox1bq_ETjWtz13E0kNhkGxqV-ao+ hash: v1.k794b7964.4624c39797f30be4664c956382e53f065207d2a5c3c10dc923ef5d670a6c4cbd.wgrcJwwsFI0sB4jHPZb_jmpnhkoLO3TFXN5zkw3tPHoscenes-other-welcome-dialog--provisioned--light:- hash: v1.k794b7964.7bc96d4f26a15090c0e0822f013065ffbf00a22f0edda8572b12c01a531fe6dc.x21M2rAOPxoCSK84EZ-zyIs4Mvpl_BEBXhi33H3UJzw+ hash: v1.k794b7964.fa2f4c4df2000b0aac6b2d030e35e09b87ccff491a31f6526b0510c497694c57.0RINcqkztk_dHUnIPDZmxsYcQaJuuv3XJPCtwFi8Yq8scenes-other-welcome-flagshipproductscard--default--dark:hash: v1.k794b7964.0f57eeaac62cc6fa6fcd833c9d2bc8fd0d30d8ab5e9819b685b4b2bb7052cdca.oPfu3XSL2xF96rf2RAWtGdSkWwDPbnjxiTntYx82B6cscenes-other-welcome-flagshipproductscard--default--light:hash: v1.k794b7964.92dc089f0f436d72aa337eb15d43083cfc4e44b7c85a8df27ac340bbcda264c2.poVRks4WEPaI3pO_Mp-lgOpRLiL0mSYjHacHqVchIXo- scenes-other-welcome-installprogresscard--default--dark:- hash: v1.k794b7964.b321aa0af8cd6635d3746c0f22e768f1ef0ed4a56210e219babebd1c38896890.2f7pqD-CII2Cb_5O9oo_SAA4A-hzd2n42nThxggLws8- scenes-other-welcome-installprogresscard--default--light:- hash: v1.k794b7964.18bf702600c4ca6149a0b4b3e9481b2b1f8d55b54165c4a5768bcf3c7b989db2.xPgy_DM70OW8Q1dMWhXPeOYMPVHC5YuNKwdvBjFEcYQscenes-session-recordings-networkview--default--dark:hash: v1.k794b7964.e03dd8a06b90190b999e4dc6e568b018b13e36c6e0b690d14a8e692e6c153ea8.TnB0l_7lTb-n7V9wf8FQPRBP-IL-l7JZJcNPgG8uBvkscenes-session-recordings-networkview--default--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 04ea97354614..814914b9e386 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -445,8 +445,6 @@ export const FEATURE_FLAGS = {NOTEBOOK_SANDBOX_FREE_COMPUTE: 'notebook-sandbox-free-compute', // owner: #team-data-tools, shows the notebook sandbox rate crossed out at $0.00 / hNOTEBOOK_SHARING: 'notebook-sharing', // owner: @reecejones #team-platform-featuresONBOARDING_SIMPLE_FLOW: 'onboarding-simple-flow', // owner: @rafaeelaudibert #team-growth multivariate=control,test, test sends new users through a short install, MCP and card flow, then to the welcome page- ONBOARDING_WIZARD_CLOUD_RUN: 'onboarding-wizard-cloud-run', // owner: @fercgomes #team-growth multivariate=control,test — gates the "open a PR for me" cloud wizard option on the install step- ONBOARDING_WIZARD_SYNC_MODE: 'onboarding-wizard-sync-mode', // owner: @fercgomes #team-growth multivariate=sse,polling — how the wizard sync panel pulls run updates (SSE stream vs REST polling); payload carries polling_interval_secsORGANIZATION_BILLING_API: 'organization-billing-api', // owner: #team-billing, reads the usage and spend pages from the organization billing API; the same flag gates those routesOWNER_ONLY_BILLING: 'owner-only-billing', // owner: @pawelcebula #team-billingPAGE_REPORTS_AVERAGE_PAGE_VIEW: 'page-reports-average-page-view', // owner: @jordanm-posthog #team-web-analytics@@ -615,7 +613,6 @@ export const FEATURE_FLAGS = {WEB_ANALYTICS_TILE_HEADER_V2: 'web-analytics-tile-header-v2', // owner: @jordanm-posthog #team-web-analytics multivariate=control,testWEB_ANALYTICS_TILE_SKELETONS: 'web-analytics-tile-skeletons', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_TILE_TOGGLES: 'web-analytics-tile-toggles', // owner: @lricoy #team-web-analytics- WIZARD_RUN_SYNC: 'wizard-run-sync', // owner: #team-growth multivariate=wizard-session,wizard-run — selects the Wizard sync widgetWIZARD_UI_ENABLED: 'wizard-ui-enabled', // owner: @fercgomes #team-growth — gates the /wizard/runs interfaceWORKFLOW_ADD_TO_STATIC_COHORT_ACTION: 'workflow-add-to-static-cohort-action', // owner: #team-workflowsWORKFLOW_CLASSIFY_ACTION: 'workflow-classify-action', // owner: #team-workflowsdiff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex 25919d45c841..61fa4408b6b9 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -10,7 +10,6 @@ import { retryImport } from 'lib/utils/retryImport'import { BillingUsageInteractionProps } from 'scenes/billing/types'import type { ExperimentWizardStepNavigation } from 'scenes/experiments/ExperimentWizard/experimentWizardLogic'import { SharedMetric } from 'scenes/experiments/SharedMetrics/sharedMetricLogic'-import type { InstallationErrorKind } from 'scenes/onboarding/shared/wizard-sync/installationProgressLogic'import { ProductTourEvent } from 'scenes/product-tours/constants'import { SURVEY_CREATED_SOURCE } from 'scenes/surveys/constants'import { userLogic } from 'scenes/userLogic'@@ -1182,12 +1181,10 @@ export interface eventUsageLogicActions {reportIntegrationConnectClicked: (integration: string,kind: string,- surface: IntegrationConnectSurface,- selfDriving?: boolean+ surface: IntegrationConnectSurface) => {integration: stringkind: string- selfDriving: boolean | undefinedsurface: IntegrationConnectSurface}reportIntegrationConnectRejected: (@@ -1465,34 +1462,6 @@ export interface eventUsageLogicActions {enabled: boolean}}- reportWizardSyncSessionDetected: (props: {- runPhase: string- skillId: string- taskCount: number- workflowId: string- }) => {- runPhase: string- skillId: string- taskCount: number- workflowId: string- }- reportWizardSyncSessionFinished: (props: {- completedTaskCount: number- elapsedSeconds: number- errorKind: InstallationErrorKind | null- outcome: string- skillId: string- taskCount: number- workflowId: string- }) => {- completedTaskCount: number- elapsedSeconds: number- errorKind: 'usage_limit' | null- outcome: string- skillId: string- taskCount: number- workflowId: string- }}export type eventUsageLogicType = MakeLogicType<eventUsageLogicValues, eventUsageLogicActions>@@ -1511,16 +1480,10 @@ export const eventUsageLogic = kea<eventUsageLogicType>([// timingreportTimeToSeeData: (payload: TimeToSeeDataPayload) => ({ payload }),reportGroupTypeDetailDashboardCreated: () => ({}),- reportIntegrationConnectClicked: (- integration: string,- kind: string,- surface: IntegrationConnectSurface,- selfDriving?: boolean- ) => ({+ reportIntegrationConnectClicked: (integration: string, kind: string, surface: IntegrationConnectSurface) => ({integration,kind,surface,- selfDriving,}),reportIntegrationLinkExistingOffered: (kind: string,@@ -1774,23 +1737,6 @@ export const eventUsageLogic = kea<eventUsageLogicType>([sdkKey,surface,}),- // Setup wizard sync (CLI ↔ app) funnel. Fired from the Installation layer- // (installationProgressLogic); guards for "once per session" live in that logic.- reportWizardSyncSessionDetected: (props: {- workflowId: string- skillId: string- runPhase: string- taskCount: number- }) => props,- reportWizardSyncSessionFinished: (props: {- workflowId: string- skillId: string- outcome: string- errorKind: InstallationErrorKind | null- taskCount: number- completedTaskCount: number- elapsedSeconds: number- }) => props,reportAccountOwnerClicked: ({ name, email }: { name: string; email: string }) => ({ name, email }),// revenue analyticsreportRevenueAnalyticsSettingsViewed: () => ({}),@@ -1912,15 +1858,11 @@ export const eventUsageLogic = kea<eventUsageLogicType>([reportAxisUnitsChanged: (properties) => {posthog.capture('axis units changed', properties)},- reportIntegrationConnectClicked: ({ integration, kind, surface, selfDriving }) => {+ reportIntegrationConnectClicked: ({ integration, kind, surface }) => {posthog.capture('integration_connect_clicked', {integration,integration_kind: kind,surface,- // Only set where the surface can actually tell. The OAuth landing page serves both- // self-driving runs and everyone else, so it resolves this; surfaces that are- // self-driving by construction leave it unset rather than assert a constant.- self_driving: selfDriving,})},// The banner offering an existing installation is where an unfamiliar account name is read,@@ -2449,33 +2391,6 @@ export const eventUsageLogic = kea<eventUsageLogicType>([surface,})},- reportWizardSyncSessionDetected: ({ workflowId, skillId, runPhase, taskCount }) => {- posthog.capture('setup wizard sync session detected', {- workflow_id: workflowId,- skill_id: skillId,- run_phase: runPhase,- task_count: taskCount,- })- },- reportWizardSyncSessionFinished: ({- workflowId,- skillId,- outcome,- errorKind,- taskCount,- completedTaskCount,- elapsedSeconds,- }) => {- posthog.capture('setup wizard sync session finished', {- workflow_id: workflowId,- skill_id: skillId,- outcome,- error_kind: errorKind,- task_count: taskCount,- completed_task_count: completedTaskCount,- elapsed_seconds: elapsedSeconds,- })- },// command barreportCommandBarStatusChanged: ({ status }) => {posthog.capture('command bar status changed', { status })diff --git a/frontend/src/lib/wizard-sync/pollLoop.ts b/frontend/src/lib/wizard-sync/pollLoop.tsindex 5dd9fd25e387..9ce615fc7b26 100644--- a/frontend/src/lib/wizard-sync/pollLoop.ts+++ b/frontend/src/lib/wizard-sync/pollLoop.ts@@ -1,28 +1,5 @@import { ApiError } from 'lib/api-error'-// How a wizard sync stream pulls updates. `sse` holds a live EventSource; `polling` re-fetches a REST-// snapshot on an interval (GROW-118). Toggled by the `onboarding-wizard-sync-mode` flag; `sse` stays-// the default when the flag is off or unset.-export type WizardSyncMode = 'sse' | 'polling'--export function resolveWizardSyncMode(flagValue: unknown): WizardSyncMode {- return flagValue === 'polling' ? 'polling' : 'sse'-}--export const DEFAULT_POLLING_INTERVAL_SECS = 3-const MIN_POLLING_INTERVAL_SECS = 1-// Also guards against `window.setTimeout` int32 overflow: a delay above 2^31-1 ms fires immediately,-// which would turn a fat-fingered payload into a tight polling loop across every flagged client.-export const MAX_POLLING_INTERVAL_SECS = 300--// Resolve the poll cadence from the flag payload's `polling_interval_secs`, falling back to the default-// and clamping on both ends so a stray payload can neither hammer the endpoint nor stall sync entirely.-export function resolvePollingIntervalMs(payload: unknown): number {- const raw = (payload as { polling_interval_secs?: unknown } | null)?.polling_interval_secs- const secs = typeof raw === 'number' && Number.isFinite(raw) ? raw : DEFAULT_POLLING_INTERVAL_SECS- return Math.min(MAX_POLLING_INTERVAL_SECS, Math.max(MIN_POLLING_INTERVAL_SECS, secs)) * 1000-}-// Spread poll ticks ±20% around the base cadence so clients whose runs kicked off together (or whose// tabs woke together) don't hit the endpoint in lockstep, avoiding a thundering herd on the API.export const POLL_JITTER_RATIO = 0.2@@ -41,22 +18,6 @@ export function isPermanentPollError(error: unknown): boolean {return error instanceof ApiError && [401, 403, 404, 410].includes(error.status ?? 0)}-// A native EventSource only auto-reconnects after a cleanly dropped connection. Any non-200 response-// on a (re)connect leaves it CLOSED for good, and posthog/api/streaming.py requires SSE consumers to-// schedule their own reconnect from onerror. Consecutive attempts back off exponentially from the-// base to the cap, with the same jitter as poll ticks so clients dropped together (a deploy, an-// admission-control rejection wave) do not reconnect in lockstep.-export const SSE_RECONNECT_BASE_MS = 2_000-export const SSE_RECONNECT_MAX_MS = 30_000--// Delay before reconnect attempt `attempt` (1-based count of consecutive failures since the last-// successful open). Non-positive attempts are treated as the first.-export function sseReconnectDelayMs(attempt: number, random: () => number = Math.random): number {- const exponent = Math.max(0, attempt - 1)- const baseMs = Math.min(SSE_RECONNECT_BASE_MS * 2 ** exponent, SSE_RECONNECT_MAX_MS)- return jitteredIntervalMs(baseMs, random)-}-export type PollTickOutcome = 'ok' | 'empty' | 'terminal'export interface PollLoopOptions {diff --git a/frontend/src/lib/wizard-sync/wizardSyncDebugLogic.ts b/frontend/src/lib/wizard-sync/wizardSyncDebugLogic.tsdeleted file mode 100644index 237e1659bf8a..000000000000--- a/frontend/src/lib/wizard-sync/wizardSyncDebugLogic.ts+++ /dev/null@@ -1,146 +0,0 @@-import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'--export type SyncDebugKind = 'connect' | 'open' | 'poll' | 'event' | 'error' | 'complete' | 'disconnect'--export interface SyncDebugEntry {- id: number- at: number- source: string- kind: SyncDebugKind- message: string- /** For `poll`/`event` kinds: ms since the previous poll/event from the same source. */- gapMs: number | null-}--export interface SyncDebugSourceInfo {- source: string- mode: 'sse' | 'polling' | null- intervalMs: number | null- /** Last poll settle / SSE event arrival. */- lastAt: number | null- lastGapMs: number | null- /** Polls settled or SSE events received. */- ticks: number- lastKind: SyncDebugKind- lastMessage: string-}--const MAX_ENTRIES = 200--let nextEntryId = 0-// Gap tracking lives here rather than in a reducer so `gapMs` can travel on the action payload and-// the reducers stay pure. Module-level is fine: this is a dev-only diagnostic, not app state.-const lastTickAtBySource = new Map<string, number>()--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardSyncDebugLogicValues {- entries: SyncDebugEntry[]- sources: Record<string, SyncDebugSourceInfo>-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardSyncDebugLogicActions {- clearSyncDebugLog: () => {- value: true- }- recordSyncEvent: (- entry: SyncDebugEntry,- mode?: 'polling' | 'sse',- intervalMs?: number- ) => {- entry: SyncDebugEntry- intervalMs: number | undefined- mode: 'polling' | 'sse' | undefined- }-}--export type wizardSyncDebugLogicType = MakeLogicType<wizardSyncDebugLogicValues, wizardSyncDebugLogicActions>--/**- * Dev-only in-memory event log for the wizard sync transports (task-run SSE/polling, wizard-session- * SSE/polling). Fed by `logSyncDebug` below and rendered by `WizardSyncDebugPanel`. Never mounted in- * production — the helper no-ops there, so this logic holds no state outside development.- */-export const wizardSyncDebugLogic = kea<wizardSyncDebugLogicType>([- path(['lib', 'wizard-sync', 'wizardSyncDebugLogic']),- actions({- recordSyncEvent: (entry: SyncDebugEntry, mode?: 'sse' | 'polling', intervalMs?: number) => ({- entry,- mode,- intervalMs,- }),- clearSyncDebugLog: true,- }),- reducers({- entries: [- [] as SyncDebugEntry[],- {- recordSyncEvent: (state, { entry }) => [entry, ...state].slice(0, MAX_ENTRIES),- clearSyncDebugLog: () => [],- },- ],- sources: [- {} as Record<string, SyncDebugSourceInfo>,- {- recordSyncEvent: (state, { entry, mode, intervalMs }) => {- const previous = state[entry.source]- const isTick = entry.kind === 'poll' || entry.kind === 'event'- return {- ...state,- [entry.source]: {- source: entry.source,- mode: mode ?? previous?.mode ?? null,- intervalMs: intervalMs ?? previous?.intervalMs ?? null,- lastAt: isTick ? entry.at : (previous?.lastAt ?? null),- lastGapMs: isTick ? entry.gapMs : (previous?.lastGapMs ?? null),- ticks: (previous?.ticks ?? 0) + (isTick ? 1 : 0),- lastKind: entry.kind,- lastMessage: entry.message,- },- }- },- clearSyncDebugLog: () => ({}),- },- ],- }),- listeners({- // Reset the module-level gap tracker too, or the first tick after a clear reports a stale gap.- clearSyncDebugLog: () => {- lastTickAtBySource.clear()- },- }),-])--/**- * Record a wizard-sync debug event. No-ops outside development and when the debug panel (the only- * thing that mounts `wizardSyncDebugLogic`) isn't rendered, so instrumented production code paths- * pay nothing.- */-export function logSyncDebug(- source: string,- kind: SyncDebugKind,- message: string,- opts?: { mode?: 'sse' | 'polling'; intervalMs?: number }-): void {- if (process.env.NODE_ENV !== 'development') {- return- }- const mounted = wizardSyncDebugLogic.findMounted()- if (!mounted) {- return- }- const at = Date.now()- let gapMs: number | null = null- if (kind === 'poll' || kind === 'event') {- const last = lastTickAtBySource.get(source)- gapMs = last !== undefined ? at - last : null- lastTickAtBySource.set(source, at)- } else if (kind === 'connect') {- lastTickAtBySource.delete(source)- }- mounted.actions.recordSyncEvent(- { id: nextEntryId++, at, source, kind, message, gapMs },- opts?.mode,- opts?.intervalMs- )-}diff --git a/frontend/src/scenes/AuthenticatedShell.tsx b/frontend/src/scenes/AuthenticatedShell.tsxindex c06f73798746..ac926fcebcd5 100644--- a/frontend/src/scenes/AuthenticatedShell.tsx+++ b/frontend/src/scenes/AuthenticatedShell.tsx@@ -15,8 +15,6 @@ import { runWhenIdle } from 'lib/utils/async'import { isEmbeddedPageFrame } from 'lib/utils/embeddedPageFrame'import { lazyWithRetry } from 'lib/utils/retryImport'import { ChunkLoadErrorBoundary } from 'scenes/ChunkLoadErrorBoundary'-import { WizardHandoffDialog } from 'scenes/onboarding/shared/wizard-sync/WizardHandoffDialog'-import { WizardSyncDebugPanel } from 'scenes/onboarding/shared/wizard-sync/WizardSyncDebugPanel'import { userLogic } from 'scenes/userLogic'import { ErrorBoundary } from '~/layout/ErrorBoundary'@@ -50,18 +48,6 @@ const InternalFeedbackWidget = lazyWithRetry(() =>default: InternalFeedbackWidget,})))-// Deciding whether a run is active takes API polls, so the shell cannot gate these cheaply.-// Lazy loading keeps their logic and generated API clients off the first paint instead.-const WizardSyncFab = lazyWithRetry(() =>- import('scenes/onboarding/shared/wizard-sync/WizardSyncFab').then(({ WizardSyncFab }) => ({- default: WizardSyncFab,- }))-)-const WizardRunSyncFab = lazyWithRetry(() =>- import('products/wizard/frontend/runs/WizardRunSyncFab').then(({ WizardRunSyncFab }) => ({- default: WizardRunSyncFab,- }))-)export default function AuthenticatedShell({ children }: { children: React.ReactNode }): JSX.Element {useMountedLogic(apiStatusLogic)@@ -86,7 +72,7 @@ export default function AuthenticatedShell({ children }: { children: React.React)const showInternalFeedback =!!featureFlags[FEATURE_FLAGS.INTERNAL_FEEDBACK_WIDGET] && !!user?.email?.toLowerCase().endsWith('@posthog.com')- const runSyncEnabled = featureFlags[FEATURE_FLAGS.WIZARD_RUN_SYNC] === 'wizard-run'+const toasts = (<ToastContainerautoClose={6000}@@ -133,15 +119,6 @@ export default function AuthenticatedShell({ children }: { children: React.React</ErrorBoundary>)}<ImpersonationNoticeSlot />- <ErrorBoundary>- <ChunkLoadErrorBoundary>- <Suspense fallback={null}>{runSyncEnabled ? <WizardRunSyncFab /> : <WizardSyncFab />}</Suspense>- </ChunkLoadErrorBoundary>- </ErrorBoundary>- {/* Separate from the FAB: the FAB stands down while an inline panel shows the run,- but the doc dialog must be able to open from any surface. */}- <WizardHandoffDialog />- <WizardSyncDebugPanel />{showInternalFeedback && (<ErrorBoundary><Suspense fallback={null}>diff --git a/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx b/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsxindex fb5eb5f47535..3f62e9b797cc 100644--- a/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx+++ b/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx@@ -171,18 +171,10 @@ export function SampleDataState({title={<div className="max-w-72 space-y-1.5 p-0.5"><div className="font-semibold">Setup wizard is running</div>- {setupStatus.mode === 'cloud' ? (- <p className="m-0">- The AI setup wizard is installing PostHog in the cloud, on a copy of your- codebase. Once it's done, it will open a pull request for you to review and- merge.- </p>- ) : (- <p className="m-0">- The AI setup wizard is installing PostHog in your codebase from your terminal.- You'll see real data here soon after it's done.- </p>- )}+ <p className="m-0">+ The AI setup wizard is installing PostHog in the cloud, on a copy of your codebase.+ Once it's done, it will open a pull request for you to review and merge.+ </p></div>}placement="bottom"diff --git a/frontend/src/scenes/insights/EmptyStates/SampleDataTag.tsx b/frontend/src/scenes/insights/EmptyStates/SampleDataTag.tsxindex 5b56a2b7b386..2ac207db8e4a 100644--- a/frontend/src/scenes/insights/EmptyStates/SampleDataTag.tsx+++ b/frontend/src/scenes/insights/EmptyStates/SampleDataTag.tsx@@ -15,18 +15,12 @@ export function SampleDataTag(): JSX.Element {This project hasn't received any events yet - you'll see your real data here as soon as events startcoming in.</p>- {setupStatus?.kind === 'installing' &&- (setupStatus.mode === 'cloud' ? (- <p className="m-0">- The setup wizard is installing PostHog in your codebase. Once it's done, it will open a pull- request for you to merge.- </p>- ) : (- <p className="m-0">- The setup wizard is installing PostHog in your codebase. You'll see real data here soon after- it's done.- </p>- ))}+ {setupStatus?.kind === 'installing' && (+ <p className="m-0">+ The setup wizard is installing PostHog in your codebase. Once it's done, it will open a pull request+ for you to merge.+ </p>+ )}{setupStatus?.kind === 'pull_request' &&(setupStatus.pullRequest.merged ? (<p className="m-0">diff --git a/frontend/src/scenes/integrations/IntegrationFullPage.tsx b/frontend/src/scenes/integrations/IntegrationFullPage.tsxindex 5ada44019aca..bf37f6886cbe 100644--- a/frontend/src/scenes/integrations/IntegrationFullPage.tsx+++ b/frontend/src/scenes/integrations/IntegrationFullPage.tsx@@ -9,7 +9,6 @@ import { TeamMembershipLevel } from 'lib/constants'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { describeOAuthCallbackError, INTEGRATION_ERROR_PARAM } from 'lib/integrations/oauthCallbackErrors'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'-import { useSelfDrivingRunState } from 'scenes/onboarding/shared/wizard-sync/hooks'import { urls } from 'scenes/urls'import { IntegrationType } from '~/types'@@ -93,10 +92,6 @@ function ConnectView({SettingsSection: SettingsSectionComponent}): JSX.Element {const { reportIntegrationConnectClicked } = useActions(eventUsageLogic)- // This page serves both the self-driving wizard, which parks a run here for the GitHub round- // trip, and everyone arriving under their own steam. Both leave the same click behind, so- // recording which it was is the only way to attribute a connect to a wizard run.- const { inFlight: selfDrivingRunInFlight } = useSelfDrivingRunState()// Connecting an integration requires project membership (enforced again in the backend);// editing or removing one still requires admin. Users with no project access fall back to// the request-access flow below.@@ -106,12 +101,7 @@ function ConnectView({})const onConnectClick = (): void => {- reportIntegrationConnectClicked(- definition.slug,- definition.kind,- 'integration_landing_page',- selfDrivingRunInFlight- )+ reportIntegrationConnectClicked(definition.slug, definition.kind, 'integration_landing_page')}return (@@ -203,11 +193,12 @@ function ConnectedView({}/**- * Where the user goes after connecting. A wizard run owns the flow it started — the browser is only- * here to click through the provider's consent screen — so send them back to their terminal rather- * than into the app. Routing them anywhere is wrong for every path the wizard can produce: a- * provisioned account lands in an onboarding it never started, an unonboarded existing account gets- * bounced there by the onboarding gate, and an onboarded one is pulled away from the run mid-flight.+ * Where the user goes after connecting. This page is reached by clicking through a provider's+ * consent screen, which is mostly something a setup agent run sent the user off to do. That run owns+ * the flow it started, so the page points back to the terminal rather than into the app: routing a+ * run's user anywhere is wrong for every path the agent can produce. The link below still gets anyone+ * who arrived some other way where they wanted to go. An integration with its own web setup, such as+ * the Slack app, sends the user on to that setup instead.*/function ConnectedNextStep({definition,@@ -216,26 +207,8 @@ function ConnectedNextStep({definition: IntegrationDefinitionintegrations: IntegrationType[]}): JSX.Element {- const { inFlight, resolved } = useSelfDrivingRunState()const setupUrl = definition.useSetupUrl?.(integrations) ?? null- // Until the detector answers, assume the run: this page is reached by clicking through a- // provider's consent screen, which is overwhelmingly something a run sent the user off to do,- // and offering the app as the primary action is the one outcome that is wrong on every wizard- // path. The link below still gets anyone who arrived some other way where they wanted to go.- if (inFlight || !resolved) {- return (- <div className="flex flex-col items-center gap-2">- <p className="text-secondary text-center m-0">- Head back to your terminal. The setup agent picks up from here.- </p>- <LemonButton type="tertiary" size="small" to={urls.projectHomepage()}>- Go to PostHog- </LemonButton>- </div>- )- }-if (setupUrl) {return (<LemonButton type="primary" to={setupUrl} data-attr="integration-continue-setup">@@ -245,8 +218,13 @@ function ConnectedNextStep({}return (- <LemonButton type="primary" to={urls.projectHomepage()}>- Go to PostHog- </LemonButton>+ <div className="flex flex-col items-center gap-2">+ <p className="text-secondary text-center m-0">+ If the setup agent sent you here, head back to your terminal. It picks up from there.+ </p>+ <LemonButton type="tertiary" size="small" to={urls.projectHomepage()}>+ Go to PostHog+ </LemonButton>+ </div>)}diff --git a/frontend/src/scenes/onboarding/Onboarding.stories.tsx b/frontend/src/scenes/onboarding/Onboarding.stories.tsxindex 785289cd5786..cdb202e1a75f 100644--- a/frontend/src/scenes/onboarding/Onboarding.stories.tsx+++ b/frontend/src/scenes/onboarding/Onboarding.stories.tsx@@ -150,30 +150,6 @@ export const AIObservabilitySDKInstall: Story = {},}-// The cloud-run experiment arm enabled: a dedicated wizard program must keep its own command-// and never offer the cloud arm. (The active-run takeover scenario is pinned by-// WizardInstallStep.test.tsx — staging a run here would write the persisted handle to-// localStorage, which stories share, contaminating every story rendered after this one.)-export const AIObservabilitySDKInstallWithCloudRunFlag: Story = {- render: () => {- useMountedLogic(onboardingLogic)- const { setProduct } = useActions(onboardingLogic)-- useDelayedOnMountEffect(() => {- setProduct(availableOnboardingProducts[ProductKey.AI_OBSERVABILITY])- router.actions.push(- urls.onboarding({ productKey: ProductKey.AI_OBSERVABILITY, stepKey: OnboardingStepKey.INSTALL })- )- })-- return <App />- },- parameters: {- featureFlags: { [FEATURE_FLAGS.ONBOARDING_WIZARD_CLOUD_RUN]: 'test' },- testOptions: { waitForSelector: '[data-attr="sdk-continue"]' },- },-}-// ==========================================// Product Configuration Steps// ==========================================diff --git a/frontend/src/scenes/onboarding/onboardingEventUsageLogic.ts b/frontend/src/scenes/onboarding/onboardingEventUsageLogic.tsdeleted file mode 100644index 8c9d0964c221..000000000000--- a/frontend/src/scenes/onboarding/onboardingEventUsageLogic.ts+++ /dev/null@@ -1,246 +0,0 @@-import { MakeLogicType, actions, connect, kea, listeners, path } from 'kea'-import posthog from 'posthog-js'--import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'--export type CloudRunExperimentArm = 'control' | 'test'--export function resolveCloudRunExperimentArm(featureFlags: FeatureFlagsSet): CloudRunExperimentArm | null {- const value = featureFlags[FEATURE_FLAGS.ONBOARDING_WIZARD_CLOUD_RUN]- return value === 'test' || value === 'control' ? value : null-}--function wizardSyncEventProps(featureFlags: FeatureFlagsSet): {- version: 2- flow_variant: 'legacy'- cloud_run_experiment_arm: CloudRunExperimentArm | null-} {- return {- version: 2,- // pinned: event property value. Insights filter on `flow_variant`, so it keeps the value- // the flow sent while it was one of two experiment arms.- flow_variant: 'legacy',- cloud_run_experiment_arm: resolveCloudRunExperimentArm(featureFlags),- }-}--const reportedHandoffShownRuns = new Set<string>()--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface onboardingEventUsageLogicValues {- featureFlags: FeatureFlagsSet // featureFlagLogic-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface onboardingEventUsageLogicActions {- reportOnboardingCloudRunCompleted: (props: {- durationSeconds: number | null- prOpened: boolean- prUrl: string | null- runId: string- status: 'cancelled' | 'completed' | 'failed'- taskId: string- }) => {- durationSeconds: number | null- prOpened: boolean- prUrl: string | null- runId: string- status: 'cancelled' | 'completed' | 'failed'- taskId: string- }- reportOnboardingCloudRunQueued: (props: { repository: string; runId: string; taskId: string }) => {- repository: string- runId: string- taskId: string- }- reportOnboardingInstallModeSelected: (mode: 'cloud' | 'local' | 'manual') => {- mode: 'cloud' | 'local' | 'manual'- }- reportWizardSyncExpanded: (props: { mode: 'cloud' | 'local'; phase: string; runKey: string }) => {- mode: 'cloud' | 'local'- phase: string- runKey: string- }- reportWizardSyncHandoffDocOpened: (props: {- mode: 'cloud' | 'local'- runKey: string- trigger: 'auto' | 'button'- }) => {- mode: 'cloud' | 'local'- runKey: string- trigger: 'auto' | 'button'- }- reportWizardSyncHandoffShown: (props: {- mode: 'cloud' | 'local'- prOpened: boolean- runKey: string- surface: 'fab' | 'inline'- }) => {- mode: 'cloud' | 'local'- prOpened: boolean- runKey: string- surface: 'fab' | 'inline'- }- reportWizardSyncMinimized: (props: { mode: 'cloud' | 'local'; phase: string; runKey: string }) => {- mode: 'cloud' | 'local'- phase: string- runKey: string- }- reportWizardSyncRestored: (props: { mode: 'cloud' | 'local'; phase: string; runKey: string }) => {- mode: 'cloud' | 'local'- phase: string- runKey: string- }- reportWizardSyncRunDismissed: (props: {- elapsedSeconds: number- mode: 'cloud' | 'local'- phase: string- runKey: string- }) => {- elapsedSeconds: number- mode: 'cloud' | 'local'- phase: string- runKey: string- }- reportWizardSyncUsageLimitAgentOpened: (props: { agent: string; mode: 'cloud' | 'local'; runKey: string }) => {- agent: string- mode: 'cloud' | 'local'- runKey: string- }-}--export type onboardingEventUsageLogicType = MakeLogicType<- onboardingEventUsageLogicValues,- onboardingEventUsageLogicActions->--export const onboardingEventUsageLogic = kea<onboardingEventUsageLogicType>([- path(['scenes', 'onboarding', 'onboardingEventUsageLogic']),- connect(() => ({- values: [featureFlagLogic, ['featureFlags']],- })),- actions({- reportOnboardingInstallModeSelected: (mode: 'cloud' | 'local' | 'manual') => ({ mode }),- reportOnboardingCloudRunQueued: (props: { taskId: string; runId: string; repository: string }) => props,- reportOnboardingCloudRunCompleted: (props: {- taskId: string- runId: string- status: 'completed' | 'failed' | 'cancelled'- durationSeconds: number | null- prOpened: boolean- prUrl: string | null- }) => props,- reportWizardSyncExpanded: (props: { runKey: string; mode: 'cloud' | 'local'; phase: string }) => props,- reportWizardSyncMinimized: (props: { runKey: string; mode: 'cloud' | 'local'; phase: string }) => props,- reportWizardSyncRestored: (props: { runKey: string; mode: 'cloud' | 'local'; phase: string }) => props,- reportWizardSyncRunDismissed: (props: {- runKey: string- mode: 'cloud' | 'local'- phase: string- elapsedSeconds: number- }) => props,- reportWizardSyncHandoffShown: (props: {- runKey: string- mode: 'cloud' | 'local'- surface: 'inline' | 'fab'- prOpened: boolean- }) => props,- reportWizardSyncHandoffDocOpened: (props: {- runKey: string- mode: 'cloud' | 'local'- trigger: 'auto' | 'button'- }) => props,- reportWizardSyncUsageLimitAgentOpened: (props: { runKey: string; mode: 'cloud' | 'local'; agent: string }) =>- props,- }),- listeners(({ values }) => ({- reportOnboardingInstallModeSelected: ({ mode }) => {- posthog.capture('onboarding install mode selected', {- mode,- ...wizardSyncEventProps(values.featureFlags),- })- },- reportOnboardingCloudRunQueued: ({ taskId, runId }) => {- posthog.capture('onboarding cloud run queued', {- task_id: taskId,- run_id: runId,- ...wizardSyncEventProps(values.featureFlags),- })- },- reportOnboardingCloudRunCompleted: ({ taskId, runId, status, durationSeconds, prOpened }) => {- posthog.capture('onboarding cloud run completed', {- task_id: taskId,- run_id: runId,- status,- duration_seconds: durationSeconds,- pr_opened: prOpened,- ...wizardSyncEventProps(values.featureFlags),- })- },- reportWizardSyncExpanded: ({ runKey, mode, phase }) => {- posthog.capture('wizard sync expanded', {- run_key: runKey,- mode,- phase,- ...wizardSyncEventProps(values.featureFlags),- })- },- reportWizardSyncMinimized: ({ runKey, mode, phase }) => {- posthog.capture('wizard sync minimized', {- run_key: runKey,- mode,- phase,- ...wizardSyncEventProps(values.featureFlags),- })- },- reportWizardSyncRestored: ({ runKey, mode, phase }) => {- posthog.capture('wizard sync restored', {- run_key: runKey,- mode,- phase,- ...wizardSyncEventProps(values.featureFlags),- })- },- reportWizardSyncRunDismissed: ({ runKey, mode, phase, elapsedSeconds }) => {- posthog.capture('wizard sync run dismissed', {- run_key: runKey,- mode,- phase,- elapsed_seconds: elapsedSeconds,- ...wizardSyncEventProps(values.featureFlags),- })- },- reportWizardSyncHandoffShown: ({ runKey, mode, surface, prOpened }) => {- if (reportedHandoffShownRuns.has(runKey)) {- return- }- reportedHandoffShownRuns.add(runKey)- posthog.capture('wizard sync handoff shown', {- run_key: runKey,- mode,- surface,- pr_opened: prOpened,- ...wizardSyncEventProps(values.featureFlags),- })- },- // Opens are NOT deduped: reopening the doc through the button is real engagement, and the- // auto trigger fires at most once per run by construction (wizardSyncUiLogic's seen keys).- reportWizardSyncHandoffDocOpened: ({ runKey, mode, trigger }) => {- posthog.capture('wizard sync handoff doc opened', {- run_key: runKey,- mode,- trigger,- ...wizardSyncEventProps(values.featureFlags),- })- },- reportWizardSyncUsageLimitAgentOpened: ({ runKey, mode, agent }) => {- posthog.capture('wizard sync usage limit agent opened', {- run_key: runKey,- mode,- agent,- ...wizardSyncEventProps(values.featureFlags),- })- },- })),-])diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.stories.tsx b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.stories.tsxindex 8c51326281ce..17dce27f3bf1 100644--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.stories.tsx+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.stories.tsx@@ -1,7 +1,4 @@-import { MOCK_TEAM_ID } from 'lib/api.mock'-import { Meta, StoryObj } from '@storybook/react'-import { waitFor } from '@testing-library/dom'import { useActions, useMountedLogic } from 'kea'import { router } from 'kea-router'@@ -15,72 +12,11 @@ import { mswDecorator } from '~/mocks/browser'import { billingJson } from '~/mocks/fixtures/_billing'import preflightJson from '~/mocks/fixtures/_preflight.json'import { ProductKey } from '~/queries/schema/schema-general'-import { IntegrationType, OnboardingStepKey } from '~/types'+import { OnboardingStepKey } from '~/types'import { onboardingLogic } from '../../../onboardingLogic'-import { activeCloudRunLogic } from '../../../shared/wizard-sync/activeCloudRunLogic'--/**- * The onboarding install step under each arm of the cloud-wizard AB test (GROW-117), plus the- * pinned progress state once a cloud run is underway. The cloud run block's own states live in the- * Wizard Cloud Run stories.- */--const githubIntegration: IntegrationType = {- id: 1,- kind: 'github',- display_name: 'acme-co',- icon_url: '/static/services/github.png',- config: { account: { name: 'acme-co', type: 'Organization' }, repository_selection: 'all' },- created_at: '2024-01-01T00:00:00Z',-}--const githubReposResponse = {- repositories: [- {- id: 1,- name: 'web',- full_name: 'acme-co/web',- private: false,- default_branch: 'main',- language: 'TypeScript',- pushed_at: '2023-05-24T10:00:00Z',- archived: false,- can_push: true,- },- ],- has_more: false,-}--// One SSE frame. The task-run stream speaks `data:`-only messages (default event type), so the-// EventSource `onmessage` handler picks them up.-const sseEvent = (data: object): string => `data: ${JSON.stringify(data)}\n\n`-const sseStep = (group: string, step: string, status: string, label: string, detail: string | null = null): string =>- sseEvent({- type: 'notification',- notification: { method: '_posthog/progress', params: { group, step, status, label, detail } },- })-// A mid-run pipeline snapshot, replayed to the InstallationProgressView the moment it connects. The-// trailing `stream-end` sentinel makes the logic close the EventSource, so the rendered state is-// stable for the snapshot (no reconnect churn).-const TASK_RUN_STREAM_BODY = [- sseEvent({- type: 'task_run_state',- status: 'in_progress',- stage: 'work',- output: null,- branch: null,- error_message: null,- updated_at: '2023-05-25T00:00:00Z',- completed_at: null,- }),- sseStep('setup', 'sandbox', 'completed', 'Set up sandbox'),- sseStep('setup', 'clone', 'completed', 'Cloned repository'),- sseStep('setup', 'wizard', 'in_progress', 'Running setup wizard', 'Detecting Next.js'),- sseStep('deliver', 'pr', 'pending', 'Opening pull request'),- 'event: stream-end\ndata: {}\n\n',-].join('')+/** The onboarding install step: the full layout and the simple flow's compact layout. */const meta: Meta = {title: 'Scenes-Other/Onboarding/Install Step',@@ -88,9 +24,6 @@ const meta: Meta = {layout: 'fullscreen',viewMode: 'story',mockDate: '2023-05-25',- // The cloud tab and the pinned run render spinners by design (repo loading, in-progress- // steps) — skip the test runner's default "wait for loaders to hide" check.- testOptions: { waitForLoadersToDisappear: false },},decorators: [mswDecorator({@@ -99,16 +32,6 @@ const meta: Meta = {'/stats': {},'/events': {},'/api/billing/': { ...billingJson },- '/api/projects/:team_id/integrations': { results: [githubIntegration] },- '/api/environments/:team_id/integrations/:id/github_repos': githubReposResponse,- '/api/projects/:project_id/tasks/:task_id/runs/:run_id/stream': () =>- new Response(TASK_RUN_STREAM_BODY, {- status: 200,- headers: { 'Content-Type': 'text/event-stream' },- }),- // No wizard session enriching the run in these stories; a 404 closes the EventSource- // without retries (the pipeline above is the only progress source).- '/api/projects/:project_id/wizard/sessions/stream': () => [404],},patch: {'/api/environments/:team_id/add_product_intent/': {},@@ -120,31 +43,20 @@ export default metatype Story = StoryObj-/** Lands on the install step for product analytics, optionally staging extra state first. */+/** Lands on the install step for product analytics. */function installStepStory({featureFlags = {},- drive,- waitForSelector,- play,simple = false,}: {featureFlags?: Record<string, string | boolean>- drive?: () => void- waitForSelector: string- play?: () => Promise<void>simple?: boolean}): Story {return {render: () => {useMountedLogic(onboardingLogic)- useMountedLogic(activeCloudRunLogic)const { setProduct } = useActions(onboardingLogic)useDelayedOnMountEffect(() => {- // activeCloudRun is persisted (survives a refresh mid-run) — clear any handle left- // over from an earlier story in the same browser session before driving this one.- activeCloudRunLogic.actions.clearActiveCloudRun()- drive?.()if (simple) {router.actions.push(urls.simpleOnboarding(), {step: `${OnboardingStepKey.INSTALL}:${ProductKey.PRODUCT_ANALYTICS}`,@@ -159,71 +71,15 @@ function installStepStory({return <App />},- parameters: { featureFlags, testOptions: { waitForSelector } },- play,+ parameters: { featureFlags, testOptions: { waitForSelector: '[data-attr="wizard-command-block"]' } },}}-/**- * Control arm: no cloud option — the intro, the CLI command block, and the framework badges. The flag- * is deliberately UNSET rather than 'control': storybook's useFeatureFlag treats any truthy value as- * flag-on (the variant match is ignored there), and the control arm renders the flag-off branch anyway.- */-export const ControlArm: Story = installStepStory({- waitForSelector: '[data-attr="wizard-command-block"]',-})--/** Test arm: the cloud/local toggle with the "open a PR" block up front (GitHub connected). */-export const TestArm: Story = installStepStory({- featureFlags: { [FEATURE_FLAGS.ONBOARDING_WIZARD_CLOUD_RUN]: 'test' },- waitForSelector: '[data-attr="wizard-cloud-run-open-pr"]',-})--const startCloudRun = (): void =>- activeCloudRunLogic.actions.setActiveCloudRun('task-1', 'run-1', new Date().toISOString(), MOCK_TEAM_ID)--// The panel mounts in the 'connecting' phase; hold the snapshot until the mocked stream's pipeline-// steps have rendered so it captures the mid-run timeline, not the placeholder.-const waitForPipelineTimeline = async (): Promise<void> => {- await waitFor(- () => {- const timeline = document.querySelector('[data-attr="installation-progress"]')- if (!timeline?.textContent?.includes('Running setup wizard')) {- throw new Error('pipeline timeline not ready')- }- },- { timeout: 8000, interval: 200 }- )-}--/**- * A cloud run underway: the step pins to the run's live pipeline (fed by the mocked task-run- * stream), the local tab is blocked, and Continue is unblocked.- */-export const CloudRunInProgress: Story = installStepStory({- featureFlags: { [FEATURE_FLAGS.ONBOARDING_WIZARD_CLOUD_RUN]: 'test' },- drive: startCloudRun,- waitForSelector: '[data-attr="installation-progress"]',- play: waitForPipelineTimeline,-})--const SIMPLE_FLOW_CLOUD_FLAGS = {- [FEATURE_FLAGS.ONBOARDING_SIMPLE_FLOW]: 'test',- [FEATURE_FLAGS.ONBOARDING_WIZARD_CLOUD_RUN]: 'test',-}--/** The simple flow's compact install step on the cloud arm, with GitHub connected. */-export const SimpleFlowCloudArm: Story = installStepStory({- simple: true,- featureFlags: SIMPLE_FLOW_CLOUD_FLAGS,- waitForSelector: '[data-attr="wizard-cloud-run-open-pr"]',-})+/** The intro, the CLI command block, and the framework badges. */+export const ControlArm: Story = installStepStory({})-/** A cloud run underway in the simple flow: the compact step pins to the run's live pipeline. */-export const SimpleFlowCloudRunInProgress: Story = installStepStory({+/** The simple flow's compact install step. */+export const SimpleFlow: Story = installStepStory({simple: true,- featureFlags: SIMPLE_FLOW_CLOUD_FLAGS,- drive: startCloudRun,- waitForSelector: '[data-attr="installation-progress"]',- play: waitForPipelineTimeline,+ featureFlags: { [FEATURE_FLAGS.ONBOARDING_SIMPLE_FLOW]: 'test' },})diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.test.tsx b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.test.tsxindex 43433200ef9d..2ca238415d33 100644--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.test.tsx+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.test.tsx@@ -3,9 +3,6 @@ import '@testing-library/jest-dom'import { cleanup, render, screen } from '@testing-library/react'import { Provider } from 'kea'-import { activeCloudRunLogic } from 'scenes/onboarding/shared/wizard-sync/activeCloudRunLogic'-import { projectLogic } from 'scenes/projectLogic'-import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -13,12 +10,6 @@ import { VERIFY_AI_EVENTS } from '../../hooks/useInstallationComplete'import { VariantProps } from '../types'import { WizardInstallStep } from './index'-// The run block's internals (session stream) are irrelevant here — the assertion is which-// branch renders, so a marker stub keeps jsdom out of SSE territory.-jest.mock('scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock', () => ({- WizardCloudRunBlock: () => <div data-attr="mock-cloud-run-block" />,-}))-// OnboardingStep pulls in half the app (support side panel, project tree). The stub keeps the// contract that matters: the Continue button is driven by continueDisabledReason, which is// computed by the real WizardInstallStep code under test.@@ -51,12 +42,9 @@ jest.mock('../../RealtimeCheckIndicator', () => ({AdblockWarning: () => null,}))-// Manual-setup surfaces (behind a modal that stays closed) and the sync progress view — not under test.+// Manual-setup surfaces (behind a modal that stays closed) are not under test.jest.mock('../SDKGrid', () => ({ SDKGrid: () => null }))jest.mock('../SDKInstructionsModal', () => ({ SDKInstructionsModal: () => null }))-jest.mock('scenes/onboarding/shared/wizard-sync/InstallationProgressView', () => ({- InstallationProgressView: () => null,-}))const AIO_PROPS: VariantProps = {sdkGridProps: {@@ -87,35 +75,23 @@ const AIO_PROPS: VariantProps = {}describe('WizardInstallStep with wizardOverrides', () => {- let projectId: number-beforeEach(() => {useMocks({get: {'/api/projects/:team_id/event_definitions': { results: [], count: 0 },- '/api/projects/:project_id/tasks/active_wizard_run/': {- task_id: 'task-from-earlier-step',- run_id: 'run-from-earlier-step',- status: 'running',- started_at: '2026-08-06T00:00:00Z',- },},post: {'/api/environments/:team_id/query': { results: [] },},})initKeaTests()- projectLogic.mount()- projectId = projectLogic.values.currentProjectId as number- activeCloudRunLogic.mount()})afterEach(() => {- activeCloudRunLogic.actions.clearActiveCloudRun()cleanup()})- it('without an active cloud run: shows the ai-observability command and blocks Continue', async () => {+ it('shows the ai-observability command and blocks Continue until installation completes', async () => {render(<Provider><WizardInstallStep {...AIO_PROPS} />@@ -123,30 +99,6 @@ describe('WizardInstallStep with wizardOverrides', () => {)expect(await screen.findByText((t) => t.includes('ai-observability') && t.includes('npx'))).toBeInTheDocument()- expect(document.querySelector('[data-attr="mock-cloud-run-block"]')).toBeNull()-- expect(document.querySelector('[data-attr="mock-continue"]')).toHaveAttribute('aria-disabled', 'true')- })-- it('ignores a cloud run queued on an earlier install step: command stays, Continue stays blocked', async () => {- // The base-program run the user queued on the posthog-js install step of the same flow. It- // must not replace the dedicated ai-observability command or satisfy the continue gate.- activeCloudRunLogic.actions.setActiveCloudRun(- 'task-from-earlier-step',- 'run-from-earlier-step',- '2026-08-06T00:00:00Z',- projectId- )-- render(- <Provider>- <WizardInstallStep {...AIO_PROPS} />- </Provider>- )-- expect(await screen.findByText((t) => t.includes('ai-observability') && t.includes('npx'))).toBeInTheDocument()- expect(document.querySelector('[data-attr="mock-cloud-run-block"]')).toBeNull()-expect(document.querySelector('[data-attr="mock-continue"]')).toHaveAttribute('aria-disabled', 'true')})})diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/index.tsxindex 7fbe83e43fc0..91b161178698 100644--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx@@ -4,15 +4,11 @@ import { LemonButton, LemonModal, Link } from '@posthog/lemon-ui'import { OnboardingStepKey, type SDK } from '~/types'-import { onboardingEventUsageLogic } from '../../../onboardingEventUsageLogic'import { OnboardingStep } from '../../../OnboardingStep'-import { activeCloudRunLogic } from '../../../shared/wizard-sync/activeCloudRunLogic'-import { useLocalWizardRunActive } from '../../../shared/wizard-sync/hooks'-import { InstallationProgressView } from '../../../shared/wizard-sync/InstallationProgressView'-import { WizardCommandBlock } from '../../../shared/wizard-sync/WizardCommandBlock'-import { WizardFrameworkIcons } from '../../../shared/wizard-sync/WizardFrameworkIcons'-import { WizardInstallOptions } from '../../../shared/wizard-sync/WizardInstallOptions'-import { WizardFrameworkBadges, WizardModeShell } from '../../../shared/wizard-sync/WizardModeShell'+import { useWizardCommand } from '../../../shared/useWizardCommand'+import { WizardCommandBlock } from '../../../shared/wizard-command/WizardCommandBlock'+import { WizardFrameworkIcons } from '../../../shared/wizard-command/WizardFrameworkIcons'+import { WizardFrameworkBadges, WizardModeShell } from '../../../shared/wizard-command/WizardModeShell'import { AdblockWarning, RealtimeCheckIndicator } from '../../RealtimeCheckIndicator'import { SDKGrid } from '../SDKGrid'import { SDKInstructionsModal } from '../SDKInstructionsModal'@@ -20,9 +16,7 @@ import { VariantProps, WizardOverrides } from '../types'import { wizardInstallStepLogic } from '../wizardInstallStepLogic'import { WizardInstallIntro } from './WizardInstallIntro'-// The shared cloud/local switcher wrapped with onboarding's own command block and instrumentation.-// An active cloud run renders inside it (WizardCloudRunBlock pins to the run's progress), so the-// failed-run "Run it yourself" fallback keeps working — the mode state must not unmount mid-recovery.+// Onboarding's command block with the framework badges. Self-hosted gets no Wizard, so no badges either.function OnboardingInstallOptions({wizardOverrides,compact = false,@@ -30,33 +24,29 @@ function OnboardingInstallOptions({wizardOverrides?: WizardOverridescompact?: boolean}): JSX.Element {- const { reportOnboardingInstallModeSelected } = useActions(onboardingEventUsageLogic)+ const { isCloudOrDev } = useWizardCommand()return (- <WizardInstallOptions- onModeSelected={reportOnboardingInstallModeSelected}- // The cloud runner only executes the base integration program, not dedicated subcommands,- // so a dedicated-program step neither offers a run nor lets one queued elsewhere take over.- offerCloudRun={!wizardOverrides}- ignoreActiveCloudRun={!!wizardOverrides}- hog={compact ? null : undefined}- badges={- wizardOverrides?.supports ? (- <WizardFrameworkBadges items={wizardOverrides.supports} />- ) : compact ? (- <WizardFrameworkIcons />- ) : undefined- }- localBlock={- <WizardCommandBlock- subcommand={wizardOverrides?.subcommand}- description={- wizardOverrides?.description ??- (compact ? 'Run this in your project folder. No API key needed.' : undefined)- }- hog={compact ? null : undefined}- />- }- />+ <div className="flex flex-col gap-4">+ {isCloudOrDev && (+ <div className="pb-2">+ {wizardOverrides?.supports ? (+ <WizardFrameworkBadges items={wizardOverrides.supports} />+ ) : compact ? (+ <WizardFrameworkIcons />+ ) : (+ <WizardFrameworkBadges />+ )}+ </div>+ )}+ <WizardCommandBlock+ subcommand={wizardOverrides?.subcommand}+ description={+ wizardOverrides?.description ??+ (compact ? 'Run this in your project folder. No API key needed.' : undefined)+ }+ hog={compact ? null : undefined}+ />+ </div>)}@@ -68,47 +58,22 @@ function OnboardingInstallOptions({* picking an SDK in the manual modal closes it and opens the instructions* modal; closing the instructions modal reopens manual setup. The shared modal* in the parent OnboardingInstallStep is skipped here.- *- * A live local wizard run takes over the step, and an in-flight run (cloud or local) unblocks- * Continue without waiting for installation events.*/export function WizardInstallStep(props: VariantProps): JSX.Element {- const isLocalRunActive = useLocalWizardRunActive()const { setManualModalOpen } = useActions(wizardInstallStepLogic)- // Deliberately not gated on the cloud-run flag: a persisted handle is proof the user started a- // run while on the test arm, and a mid-experiment flag change must not strand an in-flight run.- // A dedicated-program step ignores it, because the run only executes the base program.- const { activeCloudRun: persistedCloudRun } = useValues(activeCloudRunLogic)- const activeCloudRun = props.wizardOverrides ? null : persistedCloudRun- // Once the wizard is in flight (cloud or local), trust it — installation events aren't required- // to unblock Continue.- const continueDisabledReason =- isLocalRunActive || activeCloudRun || props.installationComplete ? undefined : 'Installation is not complete'- // A cloud run wins over the local run view: the cloud wizard posts to the same session stream, so- // rendering both would show the same run twice. The cloud run's progress renders inside- // OnboardingInstallOptions (WizardCloudRunBlock pins to it).- const runView = activeCloudRun ? (- <OnboardingInstallOptions wizardOverrides={props.wizardOverrides} compact={props.compact} />- ) : isLocalRunActive ? (- <InstallationProgressView mode="local" />- ) : nullreturn (<WizardInstallShell- continueDisabledReason={continueDisabledReason}- showSkip={!props.installationComplete && !isLocalRunActive && !activeCloudRun}+ continueDisabledReason={props.installationComplete ? undefined : 'Installation is not complete'}+ showSkip={!props.installationComplete}props={props}>{props.compact ? (<WizardModeShell data-attr="wizard-install-compact">- {runView ?? (- <>- <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 />- </>- )}+ <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 /><LinkclassName="self-start text-sm"data-attr="sdk-continue"@@ -117,8 +82,6 @@ export function WizardInstallStep(props: VariantProps): JSX.Element {Want to set up manually?</Link></WizardModeShell>- ) : runView ? (- <div className="max-w-xl mx-auto">{runView}</div>) : (<><WizardInstallIntro description={props.wizardOverrides?.intro} />diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/types.ts b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/types.tsindex 9c42b173f336..35672669c46a 100644--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/types.ts+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/types.ts@@ -1,4 +1,4 @@-import type { WizardBadgeItem } from 'scenes/onboarding/shared/wizard-sync/WizardModeShell'+import type { WizardBadgeItem } from 'scenes/onboarding/shared/wizard-command/WizardModeShell'import { type SDK, SDKInstructionsMap, SDKTag } from '~/types'diff --git a/frontend/src/scenes/onboarding/sdks/skillBadge.tsx b/frontend/src/scenes/onboarding/sdks/skillBadge.tsxindex b6566ac5310b..0122830c58da 100644--- a/frontend/src/scenes/onboarding/sdks/skillBadge.tsx+++ b/frontend/src/scenes/onboarding/sdks/skillBadge.tsx@@ -106,7 +106,7 @@ export function getSkillDisplayName(skillId: string): string {/*** Inline logo + display name for a wizard skill_id. Use anywhere a wizard- * session needs to be visually identified (progress panel, FAB, logs, etc.).+ * session needs to be visually identified (progress panel, logs, etc.).** Unknown skills fall back to a generic code icon plus a tidied display name.*/diff --git a/frontend/src/scenes/onboarding/shared/setupWizardStatusLogic.test.ts b/frontend/src/scenes/onboarding/shared/setupWizardStatusLogic.test.tsnew file mode 100644index 000000000000..a07d6a4270b9--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/setupWizardStatusLogic.test.ts@@ -0,0 +1,116 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { ApiError } from 'lib/api-error'+import { preflightLogic } from 'lib/logic/preflightLogic'+import { teamLogic } from 'scenes/teamLogic'++import { initKeaTests } from '~/test/init'++import { tasksList } from 'products/tasks/frontend/generated/api'++import { setupWizardStatusLogic } from './setupWizardStatusLogic'++jest.mock('products/tasks/frontend/generated/api', () => ({+ tasksList: jest.fn(),+ tasksRunsList: jest.fn(),+}))++describe('setupWizardStatusLogic', () => {+ beforeEach(async () => {+ initKeaTests()+ await expectLogic(preflightLogic).toFinishAllListeners()+ jest.useFakeTimers()+ })++ afterEach(() => {+ jest.useRealTimers()+ jest.resetAllMocks()+ })++ it.each(['completed', 'failed'] as const)('refreshes an installing run until it is %s', async (status) => {+ const mockTasksList = tasksList as jest.Mock+ const task = {+ id: 'example-task',+ created_at: '2026-09-23T10:00:00Z',+ latest_run: { id: 'example-run', status: 'in_progress', output: null },+ }+ mockTasksList.mockResolvedValueOnce({ results: [task] })+ const logic = setupWizardStatusLogic()+ logic.mount()+ try {+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.setupStatus).toEqual({ kind: 'installing' })++ mockTasksList.mockRejectedValueOnce(new Error('temporarily unavailable'))+ jest.advanceTimersByTime(10_000)+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.setupStatus).toEqual({ kind: 'installing' })++ const output = status === 'completed' ? { pr_url: 'https://github.com/example/project/pull/12' } : null+ mockTasksList.mockResolvedValue({+ results: [{ ...task, latest_run: { ...task.latest_run, status, output } }],+ })+ jest.advanceTimersByTime(10_000)+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.setupStatus).toEqual(+ output ? { kind: 'pull_request', pullRequest: { url: output.pr_url, merged: false } } : null+ )++ if (output) {+ mockTasksList.mockResolvedValue({+ results: [{ ...task, latest_run: { status, output: { ...output, pr_merged: true } } }],+ })+ jest.advanceTimersByTime(10_000)+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.setupStatus).toEqual({+ kind: 'pull_request',+ pullRequest: { url: output.pr_url, merged: true },+ })+ }+ const requests = mockTasksList.mock.calls.length+ jest.advanceTimersByTime(20_000)+ await expectLogic(logic).toFinishAllListeners()+ expect(mockTasksList).toHaveBeenCalledTimes(requests)++ mockTasksList.mockRejectedValueOnce(new Error('temporarily unavailable'))+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, id: MOCK_DEFAULT_TEAM.id + 1 })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.setupStatus).toBeNull()+ } finally {+ logic.unmount()+ }+ })++ it.each([401, 403, 404])('stops polling an installing run after a %s', async (status) => {+ const mockTasksList = tasksList as jest.Mock+ mockTasksList.mockResolvedValueOnce({+ results: [+ {+ id: 'example-task',+ created_at: '2026-09-23T10:00:00Z',+ latest_run: { id: 'example-run', status: 'in_progress', output: null },+ },+ ],+ })+ const logic = setupWizardStatusLogic()+ logic.mount()+ try {+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.setupStatus).toEqual({ kind: 'installing' })++ mockTasksList.mockRejectedValue(new ApiError(undefined, status))+ jest.advanceTimersByTime(10_000)+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.setupStatus).toBeNull()++ const requests = mockTasksList.mock.calls.length+ jest.advanceTimersByTime(30_000)+ await expectLogic(logic).toFinishAllListeners()+ expect(mockTasksList).toHaveBeenCalledTimes(requests)+ } finally {+ logic.unmount()+ }+ })+})diff --git a/frontend/src/scenes/onboarding/shared/setupWizardStatusLogic.ts b/frontend/src/scenes/onboarding/shared/setupWizardStatusLogic.tsindex 72cede8230f7..315247c991dd 100644--- a/frontend/src/scenes/onboarding/shared/setupWizardStatusLogic.ts+++ b/frontend/src/scenes/onboarding/shared/setupWizardStatusLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, actions, afterMount, connect, getContext, kea, path, reducers, selectors } from 'kea'+import { MakeLogicType, afterMount, connect, kea, path, selectors } from 'kea'import { loaders } from 'kea-loaders'import { subscriptions } from 'kea-subscriptions'@@ -9,15 +9,6 @@ import { isSharedView } from '~/exporter/exporterViewLogic'import { tasksList, tasksRunsList } from 'products/tasks/frontend/generated/api'import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'-import { activeCloudRunLogic } from './wizard-sync/activeCloudRunLogic'-import type { CloudRunHandle } from './wizard-sync/activeCloudRunLogic'-import {- InstallationMode,- InstallationProgress,- installationProgressLogic,-} from './wizard-sync/installationProgressLogic'-import { wizardActiveSessionDetectorLogic } from './wizard-sync/wizardActiveSessionDetectorLogic'-export interface SetupPullRequest {url: stringmerged: boolean@@ -27,21 +18,13 @@ export interface SetupPullRequest {export type SetupWizardStatus =/** The wizard opened a pull request - surface it so the user merges it. */| { kind: 'pull_request'; pullRequest: SetupPullRequest }- /** The wizard is still working on the integration - cloud runs end in a PR, local ones don't. */- | { kind: 'installing'; mode: InstallationMode }--export interface SetupRunHandle {- taskId: string- runId: string-}--export interface DiscoveredSetupRun {- status: SetupWizardStatus- /** Null when the tasks API response carried no run id, so there is nothing to stream. */- handle: SetupRunHandle | null-}+ /** The wizard is still working on the integration and ends with a pull request. */+ | { kind: 'installing' }const RUNNING_STATUSES = ['not_started', 'queued', 'in_progress']+const STATUS_POLL_INTERVAL_MS = 10_000+// Lost access or a deleted resource does not recover on retry, unlike a network or server error.+const PERMANENT_ERROR_STATUSES = [401, 403, 404]const byCreatedAtDesc = (a: { created_at?: string | null }, b: { created_at?: string | null }): number =>(b.created_at ?? '').localeCompare(a.created_at ?? '')@@ -69,41 +52,17 @@ export function isRunRunning(run: Partial<LatestRunDetail> | null): boolean {return typeof run?.status === 'string' && RUNNING_STATUSES.includes(run.status)}-/**- * Collapse the live installation progress into the coarse setup status. The stream does not know- * whether a PR got merged, so `merged` only ever turns true via the REST snapshot.- */-export function statusFromProgress(progress: InstallationProgress | null): SetupWizardStatus | null {- if (!progress?.isCurrent) {- return null- }- if (progress.prUrl) {- return { kind: 'pull_request', pullRequest: { url: progress.prUrl, merged: false } }- }- if (progress.phase === 'connecting' || progress.phase === 'running') {- return { kind: 'installing', mode: 'cloud' }- }- return null-}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface setupWizardStatusLogicValues {- activeCloudRun: CloudRunHandle | null // activeCloudRunLogiccurrentTeamId: number | null // teamLogic- hasActiveSession: boolean // wizardActiveSessionDetectorLogic- discoveredRun: DiscoveredSetupRun | null+ discoveredRun: SetupWizardStatus | nulldiscoveredRunLoading: boolean- liveProgress: InstallationProgress | null- liveRunHandle: SetupRunHandle | nullsetupStatus: SetupWizardStatus | nullsetupStatusLoading: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface setupWizardStatusLogicActions {- liveProgressUpdated: (progress: InstallationProgress | null) => {- progress: InstallationProgress | null- }loadDiscoveredRun: () => anyloadDiscoveredRunFailure: (error: string,@@ -113,10 +72,10 @@ export interface setupWizardStatusLogicActions {errorObject?: any}loadDiscoveredRunSuccess: (- discoveredRun: DiscoveredSetupRun | null,+ discoveredRun: SetupWizardStatus | null,payload?: any) => {- discoveredRun: DiscoveredSetupRun | null+ discoveredRun: SetupWizardStatus | nullpayload?: any}}@@ -124,15 +83,7 @@ export interface setupWizardStatusLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface setupWizardStatusLogicMeta {__keaTypeGenInternalSelectorTypes: {- liveRunHandle: (- activeCloudRun: CloudRunHandle | null,- discoveredRun: DiscoveredSetupRun | null- ) => SetupRunHandle | null- setupStatus: (- liveProgress: InstallationProgress | null,- discoveredRun: DiscoveredSetupRun | null,- hasActiveSession: boolean- ) => SetupWizardStatus | null+ setupStatus: (discoveredRun: SetupWizardStatus | null) => SetupWizardStatus | nullsetupStatusLoading: (discoveredRunLoading: boolean) => boolean}}@@ -145,42 +96,23 @@ export type setupWizardStatusLogicType = MakeLogicType<>/**- * App-wide status of the onboarding wizard's setup task run (the cloud run that installs PostHog- * in the user's codebase and opens a pull request).- *- * Two complementary sources, merged in `setupStatus`:- * - REST discovery (`loadDiscoveredRun`): finds the newest onboarding task via the tasks API, so- * runs kicked off elsewhere (another browser, before a refresh) are found too. Also the only- * source that knows whether the PR got merged.- * - Live streaming: when a run handle is known (the persisted `activeCloudRunLogic` handle, or a- * still-running discovered run), `installationProgressLogic` is mounted for it and its- * normalized progress is mirrored here, so the status updates in real time.- * - Local runs: the CLI wizard creates no task run, so `wizardActiveSessionDetectorLogic`'s cheap- * session poll fills in "installing" when neither cloud source knows of a run.+ * Status of the onboarding wizard's setup task run (the cloud run that installs PostHog in the+ * user's codebase and opens a pull request). It finds the newest onboarding task through the tasks+ * API, so runs started elsewhere (another browser, a server-side drop flow) are found too, and it is+ * the only source that knows whether the PR got merged.*- * Mounting this logic starts the REST discovery and, while a run is live, an SSE stream. Mount it- * from surfaces that actually need setup state rather than app-wide (INC-886).+ * Mount it from surfaces that actually need setup state rather than app-wide (INC-886).*/export const setupWizardStatusLogic = kea<setupWizardStatusLogicType>([path(['scenes', 'onboarding', 'shared', 'setupWizardStatusLogic']),connect(() => ({- values: [- teamLogic,- ['currentTeamId'],- activeCloudRunLogic,- ['activeCloudRun'],- wizardActiveSessionDetectorLogic,- ['hasActiveSession'],- ],+ values: [teamLogic, ['currentTeamId']],})),- actions({- liveProgressUpdated: (progress: InstallationProgress | null) => ({ progress }),- }),loaders(({ values }) => ({discoveredRun: [- null as DiscoveredSetupRun | null,+ null as SetupWizardStatus | null,{- loadDiscoveredRun: async (): Promise<DiscoveredSetupRun | null> => {+ loadDiscoveredRun: async (): Promise<SetupWizardStatus | null> => {// The onboarding wizard is meaningless to a logged-out viewer, and the tasks API// it hits is team-scoped, so it 403s in a shared/exported view. Skip it entirely.if (isSharedView()) {@@ -198,10 +130,7 @@ export const setupWizardStatusLogic = kea<setupWizardStatusLogicType>([const run = asLatestRunDetail(task.latest_run)const pullRequest = pullRequestFromRunOutput(run?.output)if (pullRequest) {- return {- status: { kind: 'pull_request', pullRequest },- handle: run?.id ? { taskId: task.id, runId: run.id } : null,- }+ return { kind: 'pull_request', pullRequest }}}// Fallback for when `latest_run` really is a bare run id: check the newest task's runs@@ -212,150 +141,71 @@ export const setupWizardStatusLogic = kea<setupWizardStatusLogicType>([for (const run of runsNewestFirst) {const pullRequest = pullRequestFromRunOutput(run.output)if (pullRequest) {- return {- status: { kind: 'pull_request', pullRequest },- handle: { taskId: newestTask.id, runId: run.id },- }+ return { kind: 'pull_request', pullRequest }}}- const runningRun = runsNewestFirst.find((run) => isRunRunning(run))- if (runningRun) {- return {- status: { kind: 'installing', mode: 'cloud' },- handle: { taskId: newestTask.id, runId: runningRun.id },- }+ if (runsNewestFirst.some((run) => isRunRunning(run))) {+ return { kind: 'installing' }}}// No PR anywhere: the wizard may still be working on itfor (const task of newestFirst) {const run = asLatestRunDetail(task.latest_run)if (isRunRunning(run)) {- return {- status: { kind: 'installing', mode: 'cloud' },- handle: run?.id ? { taskId: task.id, runId: run.id } : null,- }+ return { kind: 'installing' }}}return null- } catch {- // Consumers work without wizard context: a tasks API failure is non-fatal- return null+ } catch (error) {+ // A null status stops the poll, so permanent errors clear it. Transient+ // errors keep the last status so the poll continues.+ const status = (error as { status?: unknown } | null)?.status+ if (typeof status === 'number' && PERMANENT_ERROR_STATUSES.includes(status)) {+ return null+ }+ return values.discoveredRun}},},],})),- reducers({- liveProgress: [- null as InstallationProgress | null,- {- liveProgressUpdated: (_, { progress }) => progress,- },- ],- }),selectors({- liveRunHandle: [- (s) => [s.activeCloudRun, s.discoveredRun],- (- activeCloudRun: null | import('./wizard-sync/activeCloudRunLogic').CloudRunHandle,- discoveredRun: DiscoveredSetupRun | null- ): SetupRunHandle | null => {- if (activeCloudRun) {- return { taskId: activeCloudRun.taskId, runId: activeCloudRun.runId }- }- // Only stream discovered runs that are still going; finished runs are fully described by REST- return discoveredRun?.status.kind === 'installing' ? discoveredRun.handle : null- },- ],setupStatus: [- (s) => [s.liveProgress, s.discoveredRun, s.hasActiveSession],- (- liveProgress: InstallationProgress | null,- discoveredRun: DiscoveredSetupRun | null,- hasActiveSession: boolean- ): SetupWizardStatus | null => {- const live = statusFromProgress(liveProgress)- const discovered = discoveredRun?.status ?? null- if (live?.kind === 'pull_request') {- // Only REST knows whether the PR got merged, so prefer its record of the same PR- if (discovered?.kind === 'pull_request' && discovered.pullRequest.url === live.pullRequest.url) {- return discovered- }- return live- }- if (live) {- return live- }- // The live layer watched the run reach a terminal state without a PR: a stale REST- // "installing" snapshot must not keep claiming the wizard is still at work- if (- liveProgress?.isCurrent &&- (liveProgress.phase === 'error' || liveProgress.phase === 'completed') &&- discovered?.kind === 'installing'- ) {- return null- }- if (discovered) {- return discovered- }- // No cloud run anywhere, but the CLI wizard has an active local session- return hasActiveSession ? { kind: 'installing', mode: 'local' } : null- },+ (s) => [s.discoveredRun],+ (discoveredRun: SetupWizardStatus | null): SetupWizardStatus | null => discoveredRun,],setupStatusLoading: [(s) => [s.discoveredRunLoading],(discoveredRunLoading: boolean): boolean => discoveredRunLoading,],}),- subscriptions(({ actions, cache }) => ({+ subscriptions(({ actions }) => ({// The afterMount load no-ops when the logic mounts before the team is known; (re)load once// the team id arrives or changes. kea-subscriptions' initial mount call (prev undefined) is// skipped since afterMount already covers it.currentTeamId: (teamId: number | null, prevTeamId: number | null | undefined) => {- if (teamId !== null && prevTeamId !== undefined && teamId !== prevTeamId) {- actions.loadDiscoveredRun()- }- },- // installationProgressLogic is keyed by a run id we only know at runtime, so it can't be- // connected statically. Mount it imperatively for the current handle and mirror its- // progress selector through a store subscription; disposables tear it all down on unmount.- liveRunHandle: (handle: SetupRunHandle | null) => {- const runKey = handle ? `${handle.taskId}:${handle.runId}` : null- if (runKey === cache.liveRunKey) {- return- }- cache.liveRunKey = runKey- cache.disposables.dispose('live-progress')- if (!handle) {- actions.liveProgressUpdated(null)- return- }- cache.disposables.add(() => {- const progressLogic = installationProgressLogic.build({- mode: 'cloud',- runId: handle.runId,- taskId: handle.taskId,- })- const unmount = progressLogic.mount()- const { store } = getContext()- let lastPushed: InstallationProgress | null = null- const push = (): void => {- const progress = progressLogic.selectors.installationProgress(store.getState(), progressLogic.props)- if (progress !== lastPushed) {- lastPushed = progress- actions.liveProgressUpdated(progress)- }+ if (prevTeamId !== undefined && teamId !== prevTeamId) {+ actions.loadDiscoveredRunSuccess(null)+ if (teamId !== null) {+ actions.loadDiscoveredRun()}- push()- const unsubscribe = store.subscribe(push)- return () => {- unsubscribe()- unmount()- }- }, 'live-progress')+ }},})),- afterMount(({ actions }) => {+ afterMount(({ actions, cache, values }) => {actions.loadDiscoveredRun()+ cache.disposables.add(() => {+ const timer = window.setInterval(() => {+ const status = values.setupStatus+ if (+ !values.discoveredRunLoading &&+ status &&+ (status.kind === 'installing' || !status.pullRequest.merged)+ ) {+ actions.loadDiscoveredRun()+ }+ }, STATUS_POLL_INTERVAL_MS)+ return () => window.clearInterval(timer)+ }, 'setup-status-poll')}),])diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCommandBlock.tsx b/frontend/src/scenes/onboarding/shared/wizard-command/WizardCommandBlock.tsxsimilarity index 100%rename from frontend/src/scenes/onboarding/shared/wizard-sync/WizardCommandBlock.tsxrename to frontend/src/scenes/onboarding/shared/wizard-command/WizardCommandBlock.tsxdiff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardFrameworkIcons.tsx b/frontend/src/scenes/onboarding/shared/wizard-command/WizardFrameworkIcons.tsxsimilarity index 100%rename from frontend/src/scenes/onboarding/shared/wizard-sync/WizardFrameworkIcons.tsxrename to frontend/src/scenes/onboarding/shared/wizard-command/WizardFrameworkIcons.tsxdiff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardModeShell.scss b/frontend/src/scenes/onboarding/shared/wizard-command/WizardModeShell.scsssimilarity index 100%rename from frontend/src/scenes/onboarding/shared/wizard-sync/WizardModeShell.scssrename to frontend/src/scenes/onboarding/shared/wizard-command/WizardModeShell.scssdiff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardModeShell.tsx b/frontend/src/scenes/onboarding/shared/wizard-command/WizardModeShell.tsxsimilarity index 100%rename from frontend/src/scenes/onboarding/shared/wizard-sync/WizardModeShell.tsxrename to frontend/src/scenes/onboarding/shared/wizard-command/WizardModeShell.tsxdiff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressContent.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressContent.tsxdeleted file mode 100644index 5dc78a706ba7..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressContent.tsx+++ /dev/null@@ -1,288 +0,0 @@-import { type ReactNode } from 'react'--import * as wizardPng from '@posthog/brand/hoggies/png/wizard-1'-import { IconDocument, IconPullRequest, IconRocket, IconSearch, IconTerminal, IconX } from '@posthog/icons'-import { LemonBanner, LemonButton, Spinner } from '@posthog/lemon-ui'--import { pngHoggie } from 'lib/brand/hoggies'-import { AgentPromptButton } from 'lib/components/AgentPromptButton'-import { cn } from 'lib/utils/css-classes'--import { CheckList } from '../components/CheckList'-import { prNameLabel } from './helpers'-import { useMergeCelebration } from './hooks'-import { SELF_DRIVING_UPCOMING_STEPS, syncCopy, UPCOMING_STEPS } from './installationProgressCopy'-import { InstallationMode, InstallationProgress } from './installationProgressLogic'-import { StepIcon } from './StepIcon'-import { Timeline } from './Timeline'-import { resolveWorkflowId, SELF_DRIVING_WORKFLOW_ID } from './workflows'--const HedgehogWizard = pngHoggie(wizardPng)--/**- * Presentational renderer for an `InstallationProgress`: a text header, a connected step timeline, and- * the terminal payoff (PR link) or failure detail. No logic or streams, so every state, including the- * error variants, is storyable in isolation. The container `InstallationProgressView` feeds it live- * progress from the Installation layer.- */-export function InstallationProgressContent({- workflowId,- continueHint,- docsUrl = 'https://posthog.com/docs/getting-started/install',- progress,- mode,- onViewReport,- onDismiss,- onRetryLocally,- onAgentPromptRun,-}: {- progress: InstallationProgress- /** Tailors the connecting state (copy + upcoming-step preview) to where the run happens. */- mode?: InstallationMode- /** Wizard program being watched — picks the copy, since the programs do different work. */- workflowId?: string- /** Shown while the run is in flight, to say it keeps going if the user navigates away. */- continueHint?: ReactNode- docsUrl?: string- /** Opens the run's handoff doc (the setup report) — the completed state's payoff. Only rendered- * when the progress actually carries a doc. */- onViewReport?: () => void- onDismiss?: () => void- /** When set, a failed run offers a "Run it yourself" button (switches the install step to the local- * command). Omitted where no local fallback exists (e.g. the floating FAB), which shows only docs. */- onRetryLocally?: () => void- onAgentPromptRun?: (agentKey: string) => void-}): JSX.Element {- const { phase, steps, error, prUrl, prMerged } = progress- const usageLimited = error?.kind === 'usage_limit'-- // The PR is opened mid-run: while the run keeps going (keeping CI green), surface it as ready rather- // than an indefinite "setting up". Terminal phases keep their own headline.- const prReady = !!prUrl && phase !== 'completed' && phase !== 'error'-- // Celebrate a merge the user performs while watching, exactly once per mount.- const { CelebrationComponent } = useMergeCelebration(prMerged)-- const selfDriving = resolveWorkflowId(workflowId) === SELF_DRIVING_WORKFLOW_ID- const { headline, subtitle } = syncCopy({ progress, mode, selfDriving, prReady })-- // Before the stream delivers steps there is nothing moving on screen — carry the "alive" signal in- // the header, and preview the pipeline so the wait reads as "about to do X", not a mystery.- const waitingForSteps = steps.length === 0 && (phase === 'connecting' || phase === 'running') && !prReady- // Preview the plan for the whole gap before the first real step arrives, not just while- // connecting: a run that has started but not yet reported leaves the card otherwise empty.- const upcomingSteps =- waitingForSteps && mode ? (selfDriving ? SELF_DRIVING_UPCOMING_STEPS : UPCOMING_STEPS[mode]) : null-- return (- <div- className="rounded-lg border border-border bg-bg-light p-4 flex flex-col gap-3"- data-attr="installation-progress"- >- <CelebrationComponent />- <div className="flex items-start justify-between gap-2">- <div className="flex items-start gap-2.5 min-w-0">- {waitingForSteps && <Spinner className="text-xl shrink-0 mt-0.5 text-accent" textColored />}- <div className="min-w-0">- <h4 className={cn('font-semibold m-0', phase === 'error' && 'text-danger')}>{headline}</h4>- <p className="text-sm text-muted m-0">{subtitle}</p>- </div>- </div>- <div className="flex items-start gap-1 shrink-0">- {phase === 'completed' && <HedgehogWizard className="w-14 h-14 -my-2" aria-hidden="true" />}- {/* Dismiss once the run is settled — mid-run, hiding the only progress surface- (the FAB is suppressed while this panel is mounted) would orphan a live run.- 'idle' is dismissible too: it means the stream stopped permanently without ever- delivering state (deleted run, revoked access), and the persisted handle would- otherwise be an undismissable zombie across reloads. */}- {onDismiss && (phase === 'completed' || phase === 'error' || phase === 'idle') && (- <LemonButton- size="small"- icon={<IconX />}- onClick={onDismiss}- tooltip="Dismiss"- aria-label="Dismiss"- />- )}- </div>- </div>-- {steps.length > 0 ? (- // One flat rail for pipeline and wizard-reported steps alike.- <Timeline- items={steps.map((step) => ({- key: step.id,- icon: (- <StepIcon- status={step.status}- prState={step.id.endsWith(':pr') && prUrl ? (prMerged ? 'merged' : 'open') : undefined}- />- ),- content: (- <div- className={cn(- 'text-sm truncate flex items-center gap-1.5',- step.status === 'pending' && 'text-muted',- step.status === 'failed' && 'text-danger font-medium',- step.status === 'in_progress' && 'font-medium'- )}- >- <span className="truncate">- {step.id.endsWith(':pr') && prMerged ? 'PR merged, congratulations!' : step.label}- </span>- </div>- ),- detail: step.detail && (- <div className="text-xs text-muted truncate ph-no-capture">{step.detail}</div>- ),- }))}- />- ) : (- upcomingSteps && (- <Timeline- ariaLabel="Upcoming setup steps"- items={upcomingSteps.map((label) => ({- key: label,- icon: <StepIcon status="pending" />,- content: <div className="text-sm text-muted">{label}</div>,- }))}- />- )- )}-- {continueHint && phase !== 'completed' && phase !== 'error' && (- <p className="text-xs text-muted m-0 border-t border-border pt-3">{continueHint}</p>- )}-- {phase === 'completed' &&- mode === 'local' && (- // The wizard's changes sit uncommitted on the user's machine — only the user can- // finish the last mile (review, deploy), so no button can carry this step.- <div className="flex flex-col gap-1.5">- <span className="text-xs font-semibold uppercase tracking-wide text-muted">Over to you</span>- <CheckList- items={[- {- icon: <IconSearch className="text-muted" />,- content: (- <span>- <strong>Review the changes</strong> in your editor before you commit.- </span>- ),- },- {- icon: <IconTerminal className="text-muted" />,- content: (- <span>- <strong>Try it locally</strong> and your events show up here right away.- </span>- ),- },- {- icon: <IconRocket className="text-muted" />,- content: (- <span>- <strong>Commit and deploy</strong> to get data from real users.- </span>- ),- },- ]}- />- </div>- )}-- {phase === 'error' && error?.detail && (- <LemonBanner type="error" hideIcon>- {error.detail}- </LemonBanner>- )}-- {phase === 'error' && (- // Self-serve recovery so the user isn't stuck. A usage-limited run skips the rerun, which- // stops at the same AI gateway limit, and hands the setup to the user's own coding agent.- <div className="flex flex-wrap gap-2">- {usageLimited ? (- <AgentPromptButton- actions={[- {- key: 'finish-setup',- label: 'setup prompt',- buildPrompt: () =>- `Set up PostHog in this project. Follow the instructions at ${docsUrl}`,- },- ]}- pinnedAgentKey="clipboard"- // PostHog AI cannot edit the user's codebase, so it cannot finish an SDK install.- excludeAgentKeys={['posthog-ai']}- appearance="lemon"- lemonType="primary"- onRun={({ agentKey }) => onAgentPromptRun?.(agentKey)}- data-attr="wizard-usage-limit-agent-prompt"- />- ) : (- onRetryLocally && (- <LemonButton type="primary" onClick={onRetryLocally} icon={<IconTerminal />}>- Run it yourself- </LemonButton>- )- )}- <LemonButton- type={usageLimited || onRetryLocally ? 'secondary' : 'primary'}- // The Lemon agent button only comes in small.- size={usageLimited ? 'small' : undefined}- to={docsUrl}- targetBlank- >- Read the docs- </LemonButton>- </div>- )}-- {prUrl &&- !prMerged &&- phase !== 'error' && (- // ph-no-capture: the label carries the customer's repo name and the href their PR- // url — neither may reach autocapture in the shared app analytics project.- <LemonButton- type="primary"- to={prUrl}- targetBlank- icon={<IconPullRequest />}- center- className="ph-no-capture"- >- <span className="truncate">{prNameLabel(prUrl)}</span>- </LemonButton>- )}-- {prUrl && prMerged && phase !== 'error' && (- <LemonBanner type="success" icon={<IconPullRequest />} className="ph-no-capture">- {/* ph-no-capture: the action href is the customer's PR url. */}- <div className="flex items-center gap-3">- <div className="flex-1 min-w-0">- <div className="text-sm font-semibold">Pull request successfully merged</div>- <div className="text-xs font-normal">- You're all set. Deploy the changes and your events start flowing.- </div>- </div>- <LemonButton type="secondary" size="small" to={prUrl} targetBlank className="shrink-0">- View PR- </LemonButton>- </div>- </LemonBanner>- )}-- {phase === 'completed' && progress.handoffText && onViewReport && (- <LemonButton- type={prUrl ? 'secondary' : 'primary'}- onClick={onViewReport}- icon={<IconDocument />}- center- data-attr="wizard-sync-view-report"- >- View setup report- </LemonButton>- )}- </div>- )-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.stories.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.stories.tsxdeleted file mode 100644index c7fb9e26cabf..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.stories.tsx+++ /dev/null@@ -1,338 +0,0 @@-import { Meta, StoryObj } from '@storybook/react'--import { InstallationProgressContent } from './InstallationProgressContent'-import { InstallationProgress, InstallationStepStatus } from './installationProgressLogic'--/**- * Every state of the Installation layer's progress view, driven by fixtures (the component is pure, so- * no streams/mocks). Covers the happy path and each failure point so the error UI is reviewable at a- * glance.- */-const meta: Meta<typeof InstallationProgressContent> = {- title: 'Scenes-Other/Onboarding/Shared/Installation Progress',- component: InstallationProgressContent,- // Provide the local-fallback callback to every story so the failed-run states show the full- // "Run it yourself" + "Read the docs" recovery (no-op on non-error phases).- argTypes: { onRetryLocally: { action: 'retry-locally' } },- // Most stories here render an in-progress spinner by design (connecting/running phases), which never- // resolves — skip the test runner's default "wait for loaders to hide" check.- parameters: { testOptions: { waitForLoadersToDisappear: false } },- // Width-bound to the onboarding card so the stepper wraps as it does in product.- decorators: [- (Story) => (- <div className="max-w-xl">- <Story />- </div>- ),- ],-}-export default meta-type Story = StoryObj<typeof InstallationProgressContent>--const STAGES = ['Provisioning sandbox', 'Cloning repository', 'Running setup wizard', 'Opening pull request']--// Pipeline steps with a status per stage (index-aligned to STAGES), with optional detail on one stage.-function steps(- statuses: InstallationStepStatus[],- detail?: { at: number; text: string }-): InstallationProgress['steps'] {- return STAGES.map((label, i) => ({- id: `setup:${i}`,- label,- status: statuses[i] ?? 'pending',- detail: detail && detail.at === i ? detail.text : null,- }))-}--function progress(overrides: Partial<InstallationProgress>): InstallationProgress {- return {- phase: 'running',- steps: [],- error: null,- prUrl: null,- prMerged: false,- isCurrent: true,- pendingInput: null,- startedBy: null,- handoffText: null,- ...overrides,- }-}--const SAMPLE_REPORT = [- '# PostHog setup report',- '',- 'Installed `posthog-js` and wired up event capture in `app/providers.tsx`.',- '',- '## Verify before merging',- '- [ ] Events arrive on the Activity page',- '- [ ] The API key lives in `.env.local`, not in source',-].join('\n')--export const Connecting: Story = {- args: { progress: progress({ phase: 'connecting' }), mode: 'cloud' },-}--export const ConnectingLocal: Story = {- args: { progress: progress({ phase: 'connecting' }), mode: 'local' },-}--export const RunningProvisioning: Story = {- args: { progress: progress({ steps: steps(['in_progress', 'pending', 'pending', 'pending']) }) },-}--// The wizard's own sub-steps (session tasks) replace the pipeline's aggregate wizard stage in the-// flat timeline, indistinguishable from pipeline steps.-const wizardSubSteps: InstallationProgress['steps'] = [- { id: 'wizard-task:a', label: 'Detected Next.js', status: 'completed', detail: null, source: 'wizard' },- { id: 'wizard-task:b', label: 'Installing the PostHog SDK', status: 'in_progress', detail: null, source: 'wizard' },- { id: 'wizard-task:c', label: 'Wiring up event capture', status: 'pending', detail: null, source: 'wizard' },-]--export const RunningWizard: Story = {- args: {- progress: progress({- steps: (() => {- const stages = steps(['completed', 'completed', 'in_progress', 'pending'])- return [...stages.slice(0, 2), ...wizardSubSteps, ...stages.slice(3)]- })(),- }),- },-}--export const Completed: Story = {- args: {- progress: progress({- phase: 'completed',- steps: steps(['completed', 'completed', 'completed', 'completed']),- prUrl: 'https://github.com/acme-co/web/pull/42',- handoffText: SAMPLE_REPORT,- }),- mode: 'cloud',- },- argTypes: { onViewReport: { action: 'view-report' } },-}--// The local run's final handoff: the wizard finished on the user's machine, so the review + deploy-// steps are theirs — plus the setup report the agent wrote as the payoff CTA.-export const CompletedLocalHandoff: Story = {- args: {- progress: progress({- phase: 'completed',- steps: [- { id: 'a', label: 'Detected Next.js', status: 'completed', detail: null },- { id: 'b', label: 'Installed the PostHog SDK', status: 'completed', detail: null },- { id: 'c', label: 'Wired up event capture', status: 'completed', detail: null },- { id: 'd', label: 'Created a dashboard', status: 'completed', detail: null },- ],- handoffText: SAMPLE_REPORT,- }),- mode: 'local',- },- argTypes: { onDismiss: { action: 'dismissed' }, onViewReport: { action: 'view-report' } },-}--// The PR is open but the run keeps going (keeping CI green): "Pull request ready" headline + the review-// CTA surface mid-run, and the keep-green step shows as active rather than the run looking stuck.-export const PullRequestReady: Story = {- args: {- progress: progress({- phase: 'running',- prUrl: 'https://github.com/acme-co/web/pull/42',- steps: [- { id: 'setup:sandbox', label: 'Set up sandbox', status: 'completed', detail: null },- { id: 'setup:clone', label: 'Cloned repository', status: 'completed', detail: null },- { id: 'setup:wizard', label: 'Ran PostHog setup wizard', status: 'completed', detail: null },- { id: 'setup:agent', label: 'Started agent', status: 'completed', detail: null },- { id: 'deliver:pr', label: 'Opened pull request', status: 'completed', detail: null },- { id: 'deliver:ci', label: 'Keeping CI green', status: 'in_progress', detail: null },- ],- }),- },-}--export const PullRequestMerged: Story = {- args: {- progress: progress({- phase: 'running',- prUrl: 'https://github.com/acme-co/web/pull/42',- prMerged: true,- steps: [- { id: 'setup:sandbox', label: 'Set up sandbox', status: 'completed', detail: null },- { id: 'setup:clone', label: 'Cloned repository', status: 'completed', detail: null },- { id: 'setup:wizard', label: 'Ran PostHog setup wizard', status: 'completed', detail: null },- { id: 'setup:agent', label: 'Started agent', status: 'completed', detail: null },- { id: 'deliver:pr', label: 'Pull request merged', status: 'completed', detail: null },- ],- }),- },-}--export const CompletedMerged: Story = {- args: {- progress: progress({- phase: 'completed',- prUrl: 'https://github.com/acme-co/web/pull/42',- prMerged: true,- steps: [- { id: 'setup:sandbox', label: 'Set up sandbox', status: 'completed', detail: null },- { id: 'setup:clone', label: 'Cloned repository', status: 'completed', detail: null },- { id: 'setup:wizard', label: 'Ran PostHog setup wizard', status: 'completed', detail: null },- { id: 'deliver:pr', label: 'Pull request merged', status: 'completed', detail: null },- ],- }),- },-}--export const FailedProvisioning: Story = {- args: {- progress: progress({- phase: 'error',- steps: steps(['failed', 'pending', 'pending', 'pending']),- error: { title: 'Installation failed', detail: 'Could not provision a sandbox, capacity limit reached.' },- }),- },-}--export const FailedClone: Story = {- args: {- progress: progress({- phase: 'error',- steps: steps(['completed', 'failed', 'pending', 'pending']),- error: { title: 'Installation failed', detail: 'git clone failed: repository not found or no access.' },- }),- },-}--export const FailedWizard: Story = {- args: {- progress: progress({- phase: 'error',- steps: steps(['completed', 'completed', 'failed', 'pending']),- error: { title: 'Installation failed', detail: 'PostHog setup wizard failed with exit code 1.' },- }),- },-}--export const FailedUsageLimit: Story = {- args: {- progress: progress({- phase: 'error',- steps: steps(['completed', 'completed', 'failed', 'pending']),- error: {- title: 'AI usage limit reached',- detail: 'The setup agent ran out of AI usage before it finished. Your own coding agent can finish the setup from our docs.',- kind: 'usage_limit',- },- }),- },-}--// A run whose stream never delivered any state: no pipeline steps to show, only the recovery CTAs.-export const LostContact: Story = {- args: {- progress: progress({- phase: 'error',- steps: [],- error: {- title: 'Setup lost contact',- detail: 'We stopped hearing back from this run. Run the wizard yourself, or dismiss it and start over.',- },- }),- },-}--export const FailedNoDetail: Story = {- args: {- progress: progress({- phase: 'error',- steps: steps(['completed', 'completed', 'completed', 'failed']),- error: { title: 'Installation failed', detail: null },- }),- },-}--// The floating FAB variant, terminal, so the dismiss affordance shows.-export const FloatingDismissible: Story = {- args: {- progress: progress({- phase: 'completed',- steps: steps(['completed', 'completed', 'completed', 'completed']),- prUrl: 'https://github.com/acme-co/web/pull/42',- }),- },- argTypes: { onDismiss: { action: 'dismissed' } },- decorators: [- (Story) => (- <div className="w-[340px]">- <Story />- </div>- ),- ],-}--// Every state in one canvas for review (GROW-98). Reuses the individual stories' fixtures so each one-// keeps a single source of truth.-export const AllStates: Story = {- parameters: { controls: { disable: true } },- render: () => {- const states: { label: string; args: Story['args'] }[] = [- { label: 'Connecting (cloud)', args: Connecting.args },- { label: 'Connecting (local)', args: ConnectingLocal.args },- { label: 'Running: provisioning', args: RunningProvisioning.args },- { label: 'Running: wizard', args: RunningWizard.args },- { label: 'Pull request ready', args: PullRequestReady.args },- { label: 'Completed', args: Completed.args },- { label: 'Completed: local handoff', args: CompletedLocalHandoff.args },- { label: 'Failed: provisioning', args: FailedProvisioning.args },- { label: 'Failed: wizard', args: FailedWizard.args },- { label: 'Failed: no detail', args: FailedNoDetail.args },- ]- return (- <div className="flex flex-col gap-5">- {states.map(({ label, args }) => (- <div key={label} className="flex flex-col gap-1">- <span className="text-xs font-medium text-muted">{label}</span>- <InstallationProgressContent- progress={args!.progress!}- mode={args!.mode}- onViewReport={() => {}}- onRetryLocally={() => {}}- />- </div>- ))}- </div>- )- },-}--// Configure the progress view live from the controls panel (GROW-98).-interface PlaygroundArgs {- phase: InstallationProgress['phase']- completedSteps: number- currentTask: string- prReady: boolean-}--export const Playground: StoryObj<PlaygroundArgs> = {- argTypes: {- phase: { control: 'select', options: ['connecting', 'running', 'completed', 'error'] },- completedSteps: { control: { type: 'range', min: 0, max: 4 } },- currentTask: { control: 'text' },- prReady: { control: 'boolean' },- },- args: { phase: 'running', completedSteps: 2, currentTask: 'Detecting Next.js', prReady: false },- render: (args) => {- const statuses: InstallationStepStatus[] = [0, 1, 2, 3].map((i) =>- i < args.completedSteps ? 'completed' : i === args.completedSteps ? 'in_progress' : 'pending'- )- const built = progress({- phase: args.phase,- steps: steps(statuses, args.currentTask ? { at: args.completedSteps, text: args.currentTask } : undefined),- prUrl: args.prReady || args.phase === 'completed' ? 'https://github.com/acme-co/web/pull/42' : null,- error:- args.phase === 'error' ? { title: 'Installation failed', detail: 'Something stopped the run.' } : null,- })- return <InstallationProgressContent progress={built} onRetryLocally={() => {}} />- },-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.tsxdeleted file mode 100644index 7b27c7b5db9f..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.tsx+++ /dev/null@@ -1,101 +0,0 @@-import { useActions, useValues } from 'kea'-import { type ReactNode, useEffect } from 'react'--import { onboardingEventUsageLogic } from '../../onboardingEventUsageLogic'-import { finishedLocalRunLogic } from './finishedLocalRunLogic'-import { InstallationProgressContent } from './InstallationProgressContent'-import { installationProgressLogic } from './installationProgressLogic'-import { wizardSyncUiLogic } from './wizardSyncUiLogic'--/**- * Container: streams a run's progress from the Installation layer and renders it — the same view for- * both modes, cloud runs just additionally track the TaskRun pipeline (`mode: 'cloud'` with the run- * handle; `mode: 'local'` reads only the wizard session stream). Inline on the install step (sets- * the inline-panel claim to hide the detached widget) or inside the FAB itself (`floating`).- */-export function InstallationProgressView({- mode,- runId,- taskId,- workflowId,- continueHint,- docsUrl,- floating = false,- onDismiss,- onRetryLocally,-}: {- mode: 'local' | 'cloud'- /** The TaskRun handle — required for cloud runs, absent for local ones. */- runId?: string- taskId?: string- /** Wizard program to track. Defaults to the SDK install. */- workflowId?: string- /** Shown while the run is in flight, to say it keeps going if the user navigates away. */- continueHint?: ReactNode- docsUrl?: string- /** Rendered in the floating FAB rather than inline on the install step. */- floating?: boolean- onDismiss?: () => void- /** Forwarded to the failed-run fallback (see InstallationProgressContent). */- onRetryLocally?: () => void-}): JSX.Element {- const { installationProgress, latestSession } = useValues(- installationProgressLogic({ mode, runId, taskId, workflowId })- )- const { claimInlinePanel, releaseInlinePanel, openHandoffDoc } = useActions(wizardSyncUiLogic)- const { dismissLocalRun } = useActions(finishedLocalRunLogic)- const { reportWizardSyncHandoffShown, reportWizardSyncHandoffDocOpened, reportWizardSyncUsageLimitAgentOpened } =- useActions(onboardingEventUsageLogic)-- // While shown inline on the install step, hide the floating FAB so the same run isn't in two places.- useEffect(() => {- if (floating) {- return- }- claimInlinePanel(mode)- return () => releaseInlinePanel(mode)- }, [floating, mode, claimInlinePanel, releaseInlinePanel])-- const runKey = mode === 'cloud' ? runId : latestSession?.session_id- const completed = installationProgress.phase === 'completed'- const prOpened = !!installationProgress.prUrl-- // The completed-handoff funnel (exposure + CTA impression), deduped per run inside the events- // logic so remounts and the FAB showing the same run don't double count.- useEffect(() => {- if (completed && runKey) {- reportWizardSyncHandoffShown({ runKey, mode, surface: 'inline', prOpened })- }- }, [completed, runKey, mode, prOpened, reportWizardSyncHandoffShown])-- const handoffText = installationProgress.handoffText- const handleViewReport =- handoffText && runKey- ? () => {- reportWizardSyncHandoffDocOpened({ runKey, mode, trigger: 'button' })- openHandoffDoc({ key: runKey, text: handoffText })- }- : undefined-- // Local runs always get a dismissal: it releases the install-step takeover and the FAB in one- // move, and nothing else knows the session to clear. Cloud dismissal stays with the caller- // (it owns the persisted run handle).- const defaultLocalDismiss =- mode === 'local' && latestSession ? () => dismissLocalRun(latestSession.session_id) : undefined-- return (- <InstallationProgressContent- workflowId={workflowId}- continueHint={continueHint}- docsUrl={docsUrl}- progress={installationProgress}- mode={mode}- onViewReport={handleViewReport}- onDismiss={onDismiss ?? defaultLocalDismiss}- onRetryLocally={onRetryLocally}- onAgentPromptRun={- runKey ? (agent) => reportWizardSyncUsageLimitAgentOpened({ runKey, mode, agent }) : undefined- }- />- )-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/PipStrip.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/PipStrip.tsxdeleted file mode 100644index de4ec3addda3..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/PipStrip.tsx+++ /dev/null@@ -1,24 +0,0 @@-import { cn } from 'lib/utils/css-classes'--import { pipClass } from './helpers'-import { InstallationStepStatus } from './installationProgressLogic'--/** One thin bar per step, colored by status — the run-at-a-glance strip on the compact surfaces. */-export function PipStrip({- steps,- className,-}: {- steps: { id: string; status: InstallationStepStatus }[]- className?: string-}): JSX.Element | null {- if (steps.length === 0) {- return null- }- return (- <div className={cn('flex items-center gap-1 w-full', className)}>- {steps.map((step) => (- <span key={step.id} className={cn('h-1 flex-1 rounded-full', pipClass(step.status))} />- ))}- </div>- )-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/StatusGlyph.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/StatusGlyph.tsxdeleted file mode 100644index 57d2f8a06dc8..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/StatusGlyph.tsx+++ /dev/null@@ -1,22 +0,0 @@-import { IconCheckCircle, IconPullRequest, IconQuestion, IconWarning } from '@posthog/icons'-import { Spinner } from '@posthog/lemon-ui'--import { InstallationProgress } from './installationProgressLogic'--// Leading glyph for the prominent task line: it carries the run's tone (accent while working, green on-// success, red on failure). Shared by the collapsed card, the launcher, the dialog, and the inbox rail.-export function StatusGlyph({ progress }: { progress: InstallationProgress }): JSX.Element {- if (progress.phase === 'completed') {- return <IconCheckCircle className="text-success text-xl shrink-0" />- }- if (progress.phase === 'error') {- return <IconWarning className="text-danger text-xl shrink-0" />- }- if (progress.prMerged) {- return <IconPullRequest className="text-purple text-xl shrink-0" />- }- if (progress.pendingInput) {- return <IconQuestion className="text-warning text-xl shrink-0" />- }- return <Spinner className="text-xl shrink-0 text-accent" textColored />-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/StepIcon.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/StepIcon.tsxdeleted file mode 100644index 716caf482e10..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/StepIcon.tsx+++ /dev/null@@ -1,31 +0,0 @@-import { IconCheckCircle, IconPullRequest, IconX } from '@posthog/icons'-import { Spinner } from '@posthog/lemon-ui'--import { InstallationStepStatus } from './installationProgressLogic'--// Timeline dot for a single step.-export function StepIcon({- status,- prState,-}: {- status: InstallationStepStatus- prState?: 'open' | 'merged'-}): JSX.Element {- if (status === 'completed') {- // GitHub's PR color language: green while open, purple once merged.- if (prState === 'merged') {- return <IconPullRequest className="text-purple text-base" />- }- if (prState === 'open') {- return <IconPullRequest className="text-success text-base" />- }- return <IconCheckCircle className="text-success text-base" />- }- if (status === 'failed') {- return <IconX className="text-danger text-base" />- }- if (status === 'in_progress') {- return <Spinner className="text-base" textColored />- }- return <span className="w-4 h-4 rounded-full border-2 border-border" />-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/Timeline.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/Timeline.tsxdeleted file mode 100644index 055bb1cdbfb5..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/Timeline.tsx+++ /dev/null@@ -1,33 +0,0 @@-import { type ReactNode } from 'react'--export interface TimelineItem {- key: string- /** The dot: any glyph (StepIcon, a spinner, a plain circle). */- icon: ReactNode- content: ReactNode- detail?: ReactNode-}--/**- * A vertical icon-and-connector rail — the progress card's step list, for both live steps and the- * upcoming-plan preview. Call sites decide what each dot and row says; the geometry lives here so- * the preview-to-live swap keeps rows perfectly in place.- */-export function Timeline({ items, ariaLabel }: { items: TimelineItem[]; ariaLabel?: string }): JSX.Element {- return (- <ol className="flex flex-col m-0 p-0 list-none" aria-label={ariaLabel}>- {items.map((item, i) => (- <li key={item.key} className="flex gap-3">- <div className="flex flex-col items-center pt-0.5">- {item.icon}- {i < items.length - 1 && <div className="w-px flex-1 bg-border my-1 min-h-[0.75rem]" />}- </div>- <div className="flex-1 min-w-0 pb-3">- {item.content}- {item.detail}- </div>- </li>- ))}- </ol>- )-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsxdeleted file mode 100644index 08e036c74b44..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsx+++ /dev/null@@ -1,340 +0,0 @@-import { Meta, StoryObj } from '@storybook/react'-import { waitFor } from '@testing-library/dom'-import userEvent from '@testing-library/user-event'-import { useMountedLogic } from 'kea'--import { FEATURE_FLAGS } from 'lib/constants'-import { useDelayedOnMountEffect, useOnMountEffect } from 'lib/hooks/useOnMountEffect'--import { mswDecorator, useStorybookMocks } from '~/mocks/browser'-import { billingJson } from '~/mocks/fixtures/_billing'-import preflightJson from '~/mocks/fixtures/_preflight.json'-import { IntegrationType } from '~/types'--import { activeCloudRunLogic } from './activeCloudRunLogic'-import { WizardCloudRunBlock } from './WizardCloudRunBlock'-import { wizardCloudRunLogic } from './wizardCloudRunLogic'-import { WizardCommandBlock } from './WizardCommandBlock'-import { WizardInstallOptions } from './WizardInstallOptions'--/**- * Stories for the "open a PR for me" cloud-run option: the block's own states, rendered on their own- * rather than through an onboarding scene.- *- * In the product the block sits on the onboarding install step, and `Install Step` already- * snapshots it in that setting, so driving a scene from here would duplicate those snapshots.- * These stories cover what no scene story does: not-connected, repo picking, queued, and the toggle- * back to running it yourself.- *- * The block only appears when ONBOARDING_WIZARD_CLOUD_RUN='test' (set via the featureFlags parameter)- * and preflight reports cloud/dev (so `isCloudOrDev` is true).- */--const githubIntegration: IntegrationType = {- id: 1,- kind: 'github',- display_name: 'acme-co',- icon_url: '/static/services/github.png',- config: { account: { name: 'acme-co', type: 'Organization' }, repository_selection: 'all' },- created_at: '2024-01-01T00:00:00Z',-}--// Metadata-rich repos so the picker's option rows (language, default branch, recency, private/archived,-// write access) are exercised. pushed_at values are relative to the story's mockDate (2023-05-25).-const githubReposResponse = {- repositories: [- {- id: 1,- name: 'web',- full_name: 'acme-co/web',- private: false,- default_branch: 'main',- language: 'TypeScript',- pushed_at: '2023-05-24T10:00:00Z',- archived: false,- can_push: true,- },- {- id: 2,- name: 'api',- full_name: 'acme-co/api',- private: true,- default_branch: 'master',- language: 'Python',- pushed_at: '2023-05-11T10:00:00Z',- archived: false,- can_push: true,- },- {- id: 3,- name: 'mobile-app',- full_name: 'acme-co/mobile-app',- private: true,- default_branch: 'develop',- language: 'Swift',- pushed_at: '2023-02-01T10:00:00Z',- archived: true,- can_push: false,- },- ],- has_more: false,-}--const meta: Meta = {- title: 'Scenes-Other/Onboarding/Shared/Wizard Cloud Run',- parameters: {- layout: 'fullscreen',- viewMode: 'story',- mockDate: '2023-05-25',- featureFlags: {- [FEATURE_FLAGS.ONBOARDING_WIZARD_CLOUD_RUN]: 'test',- },- // The block is mid-flight by design in several of these (connecting/polling/queued) — skip the- // test runner's default "wait for loaders to hide" check.- testOptions: { waitForLoadersToDisappear: false },- },- decorators: [- mswDecorator({- get: {- '/_preflight': { ...preflightJson, cloud: true, realm: 'cloud' },- '/stats': {},- '/events': {},- '/api/billing/': { ...billingJson },- '/api/environments/:team_id/integrations/:id/github_repos': githubReposResponse,- },- post: {- // Accepting the kickoff lets the live (non-snapshot) story walk all the way to the- // queued state by clicking the button.- '/api/wizard/cloud_run': () => [201, { task_id: 'task-1', run_id: 'run-1', status: 'queued' }],- },- patch: {- '/api/environments/:team_id/add_product_intent/': {},- },- }),- ],-}-export default meta--type Story = StoryObj--// The block seeds its state from a delayed-mount effect, and the repo picker's options arrive over a-// mocked request, so play-function waits need a load-tolerant budget: on a busy CI shard an-// under-budgeted wait fails all three retries instead of flaking once.-const WAIT_OPTIONS = { timeout: 30000, interval: 200 }--/**- * The block on its own, with a given set of integrations and optionally driven into a later state.- *- * Deliberately not rendered through an onboarding scene. The block lives on the onboarding install- * step, and `Install Step` already snapshots it in place. Driving a scene from here- * would duplicate those snapshots rather than capture what this file is about: the block's own- * states, which no scene story covers.- */-function cloudRunStory({- integrations,- drive,- waitForSelector,- extraPlay,-}: {- integrations: IntegrationType[]- drive?: () => void- waitForSelector: string- extraPlay?: () => Promise<void>-}): Story {- return {- render: () => {- useMountedLogic(wizardCloudRunLogic)- useMountedLogic(activeCloudRunLogic)-- useStorybookMocks({- get: {- '/api/projects/:team_id/integrations': { results: integrations },- },- })-- useDelayedOnMountEffect(() => {- // activeCloudRun is persisted (survives a refresh mid-run) — clear any handle left- // over from an earlier story in the same browser session before driving this one.- activeCloudRunLogic.actions.clearActiveCloudRun()- drive?.()- })-- return (- <div className="max-w-xl">- <WizardCloudRunBlock />- </div>- )- },- parameters: { testOptions: { waitForSelector } },- play: extraPlay ? async () => await extraPlay() : undefined,- }-}--/** No GitHub integration yet — the block offers a "Connect GitHub" button. */-export const NotConnected: Story = cloudRunStory({- integrations: [],- waitForSelector: '[data-attr="wizard-cloud-run-connect-github"]',-})--/** GitHub connected, no repo chosen — repo picker shown, "Install PostHog here" disabled. */-export const Connected: Story = cloudRunStory({- integrations: [githubIntegration],- waitForSelector: '[data-attr="wizard-cloud-run-open-pr"]',-})--/** Repo selected — the primary button is enabled and ready to fire. The picker's- * option keys are repo names, so we select by name ('web' → labelled 'acme-co/web'). */-export const RepoSelected: Story = cloudRunStory({- integrations: [githubIntegration],- drive: () => wizardCloudRunLogic.actions.setSelectedRepository('web'),- waitForSelector: '[data-attr="wizard-cloud-run-open-pr"]',-})--/** Repo picker opened — shows the metadata-rich option rows: language, default branch, recency, a lock- * for private repos, an "Archived" tag, and a "No write access" warning where we can't open PRs. */-export const RepoPickerOpen: Story = cloudRunStory({- integrations: [githubIntegration],- waitForSelector: '[data-attr="select-github-repository"]',- extraPlay: async () => {- // LemonInput puts data-attr on the <input> element itself, so match the input directly —- // a descendant selector like `[data-attr=...] input` never matches anything.- await waitFor(() => {- if (!document.querySelector('input[data-attr="select-github-repository"]')) {- throw new Error('repo picker not ready')- }- }, WAIT_OPTIONS)- await userEvent.click(document.querySelector('input[data-attr="select-github-repository"]') as Element)- // full_name only appears in the open dropdown (nothing is selected), so this confirms it's open.- await waitFor(() => {- if (!Array.from(document.querySelectorAll('span')).some((el) => el.textContent === 'acme-co/mobile-app')) {- throw new Error('repo options not open')- }- }, WAIT_OPTIONS)- },-})--/** Run kicked off — non-blocking confirmation; the FAB takes over from here. */-export const PullRequestQueued: Story = {- render: () => {- useMountedLogic(wizardCloudRunLogic)- useMountedLogic(activeCloudRunLogic)-- useStorybookMocks({- get: {- '/api/projects/:team_id/integrations': { results: [githubIntegration] },- },- })-- useOnMountEffect(() => {- activeCloudRunLogic.actions.clearActiveCloudRun()- wizardCloudRunLogic.actions.setSelectedRepository('web')- wizardCloudRunLogic.actions.startCloudRunSuccess()- })-- return (- <div className="max-w-xl">- <WizardCloudRunBlock />- </div>- )- },- parameters: { testOptions: { waitForSelector: '[data-attr="wizard-cloud-run-queued"]' } },-}--/**- * The other half of the same wizard — toggling to "Run it yourself" reveals the CLI command. The- * toggle belongs to `WizardInstallOptions`, which hosts the block, so this one renders that instead.- */-export const RunItYourself: Story = {- render: () => {- useMountedLogic(wizardCloudRunLogic)- useMountedLogic(activeCloudRunLogic)-- useStorybookMocks({- get: {- '/api/projects/:team_id/integrations': { results: [] },- },- })-- useDelayedOnMountEffect(() => {- activeCloudRunLogic.actions.clearActiveCloudRun()- })-- return (- <div className="max-w-xl">- <WizardInstallOptions localBlock={<WizardCommandBlock />} />- </div>- )- },- parameters: { testOptions: { waitForSelector: '[data-attr="wizard-command-block"]' } },- play: async () => {- await waitFor(() => {- if (!document.querySelector('[data-attr="wizard-mode-local"]')) {- throw new Error('install-mode toggle not ready')- }- }, WAIT_OPTIONS)- await userEvent.click(document.querySelector('[data-attr="wizard-mode-local"]') as Element)- },-}--interface PlaygroundArgs {- githubConnected: boolean- repository: '' | 'web' | 'api' | 'mobile-app'- pullRequestQueued: boolean-}--/**- * Interactive harness for the whole cloud-run flow: the controls panel drives whether GitHub is- * connected, which repo is picked, and whether the PR has been queued. Keyed on the args so flipping- * a control remounts the block and re-derives state from scratch — the logic reducers (selected repo,- * run status) don't reset on their own, and the connected/not state comes from a render-time mock.- */-function CloudRunPlayground({ githubConnected, repository, pullRequestQueued }: PlaygroundArgs): JSX.Element {- useMountedLogic(wizardCloudRunLogic)- useMountedLogic(activeCloudRunLogic)-- useStorybookMocks({- get: {- '/api/projects/:team_id/integrations': {- results: githubConnected ? [githubIntegration] : [],- },- },- })-- useDelayedOnMountEffect(() => {- activeCloudRunLogic.actions.clearActiveCloudRun()- if (repository) {- wizardCloudRunLogic.actions.setSelectedRepository(repository)- }- if (pullRequestQueued) {- wizardCloudRunLogic.actions.startCloudRunSuccess()- }- })-- return (- <div className="max-w-xl">- <WizardCloudRunBlock />- </div>- )-}--/** Fully controllable: flip GitHub on/off, pick a repo, and queue the PR straight from the controls panel. */-export const Playground: StoryObj<PlaygroundArgs> = {- args: { githubConnected: true, repository: 'web', pullRequestQueued: false },- argTypes: {- githubConnected: {- control: 'boolean',- description: 'Whether a GitHub integration exists — off shows the "Connect GitHub" button',- },- repository: {- control: 'select',- options: ['', 'web', 'api', 'mobile-app'],- description: 'Repository to pre-select — empty leaves "Install PostHog here" disabled',- },- pullRequestQueued: {- control: 'boolean',- description: 'Whether the run has been kicked off — on shows the queued confirmation',- },- },- render: (args) => <CloudRunPlayground key={JSON.stringify(args)} {...args} />,- parameters: { testOptions: { waitForSelector: '[data-attr="wizard-cloud-run-open-pr"]' } },-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.tsxdeleted file mode 100644index 2e2f197ff898..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.tsx+++ /dev/null@@ -1,153 +0,0 @@-import { useActions, useValues } from 'kea'-import { useEffect, useRef } from 'react'--import { IconCheckCircle, IconChevronDown, IconGithub, IconPullRequest } from '@posthog/icons'-import { LemonBanner, LemonButton } from '@posthog/lemon-ui'--import { GitHubRepositoryPicker } from 'lib/integrations/GitHubIntegrationHelpers'-import { eventUsageLogic } from 'lib/utils/eventUsageLogic'-import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'--import { activeCloudRunLogic } from './activeCloudRunLogic'-import { InstallationProgressView } from './InstallationProgressView'-import { wizardCloudRunLogic } from './wizardCloudRunLogic'-import { WizardModeShell, type WizardShellHog } from './WizardModeShell'--/**- * The primary, "we'll do it for you" way to run the wizard: connect GitHub, pick a- * repo, and we run the same instrumentation wizard on our infra and open a pull- * request you review and merge. Shares WizardModeShell (hog + framework badges)- * with the local command tab so both read as one wizard.- *- * Deliberately non-blocking: kicking off a run flips to live progress — the- * Installation layer (installationProgressLogic / InstallationProgressView)- * streams the run's pipeline — and the user can hit Continue right away.- */-export function WizardCloudRunBlock({- onQueued,- hog,- onRetryLocally,-}: {- onQueued?: () => void- hog?: WizardShellHog- /** Forwarded to the install progress view so a failed run can offer "Run it yourself". */- onRetryLocally?: () => void-}): JSX.Element {- const { isCloudOrDev } = useWizardCommand()- const { githubIntegration, selectedRepository, cloudRunStatus, connectGitHubUrl } = useValues(wizardCloudRunLogic)- const { activeCloudRun } = useValues(activeCloudRunLogic)- const { setSelectedRepository, startCloudRun } = useActions(wizardCloudRunLogic)- const { clearActiveCloudRun } = useActions(activeCloudRunLogic)- const { reportIntegrationConnectClicked } = useActions(eventUsageLogic)-- // Fire onQueued once per kickoff, the moment the run is handed off. It advances the install step- // (GROW-96), so it must not repeat while the status stays 'queued' (the callback identity changes- // each render). Reset when the run leaves 'queued' so a later run can advance the flow again.- const queuedAdvancedRef = useRef(false)- useEffect(() => {- if (cloudRunStatus === 'queued') {- if (!queuedAdvancedRef.current) {- queuedAdvancedRef.current = true- onQueued?.()- }- } else {- queuedAdvancedRef.current = false- }- }, [cloudRunStatus, onQueued])-- // The cloud wizard only targets cloud (US/EU) and dev instances; nothing to- // offer on self-hosted.- if (!isCloudOrDev) {- return <></>- }-- // A spawned run (persisted handle) shows live progress and survives revisits, where the local- // cloudRunStatus resets. While a run is active the parent blocks the local command (GROW-95), so- // this is the only thing the cloud tab shows.- if (activeCloudRun) {- return (- <InstallationProgressView- mode="cloud"- runId={activeCloudRun.runId}- taskId={activeCloudRun.taskId}- onRetryLocally={onRetryLocally}- onDismiss={clearActiveCloudRun}- />- )- }-- if (cloudRunStatus === 'queued') {- const repoLabel = selectedRepository ? <span className="font-mono">{selectedRepository}</span> : 'your repo'- // The brief window after kickoff before the run handle settles and the Installation layer- // takes over above.- return (- <LemonBanner type="info">- <div className="space-y-1" data-attr="wizard-cloud-run-queued">- <div className="font-semibold">Starting your cloud run…</div>- <div className="text-sm text-muted">- Kicking off the wizard on {repoLabel}. Progress will appear here in a moment and stays in the- corner as you keep going.- </div>- </div>- </LemonBanner>- )- }-- return (- <WizardModeShell hog={hog} data-attr="wizard-cloud-run-block">- <p className="text-sm text-muted mb-0">- We'll run the wizard against your repo and open a pull request with the SDK installed and events- flowing. Review it and merge whenever you're ready.- </p>-- {!githubIntegration ? (- <LemonButton- type="secondary"- icon={<IconGithub />}- to={connectGitHubUrl}- disableClientSideRouting- data-attr="wizard-cloud-run-connect-github"- className="self-start"- onClick={() => reportIntegrationConnectClicked('github', 'github', 'onboarding_wizard')}- >- Connect GitHub- </LemonButton>- ) : (- <div className="flex w-full flex-col gap-2">- <div className="flex items-center gap-2">- <div className="relative flex-1">- <IconGithub className="absolute left-2 top-1/2 -translate-y-1/2 z-10 text-base text-muted pointer-events-none" />- <GitHubRepositoryPicker- integrationId={githubIntegration.id}- value={selectedRepository ?? ''}- onChange={(repository) => setSelectedRepository(repository)}- // Make the combobox read as a dropdown, not a text field: the LemonInput- // root defaults to `cursor: text` (unlayered SCSS), so override with `!`.- className="pl-7 pr-7 !cursor-pointer"- />- {!selectedRepository && (- <IconChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 z-10 text-base text-muted pointer-events-none" />- )}- </div>- <LemonButton- type="primary"- icon={<IconPullRequest />}- onClick={() => startCloudRun()}- loading={cloudRunStatus === 'submitting'}- disabledReason={selectedRepository ? undefined : 'Pick a repository first'}- data-attr="wizard-cloud-run-open-pr"- >- Install PostHog here- </LemonButton>- </div>- <div className="flex items-center gap-1.5 text-xs text-muted">- <IconCheckCircle className="text-success" />- <span>- Connected{githubIntegration.display_name ? ` to ${githubIntegration.display_name}` : ''}- </span>- </div>- </div>- )}- </WizardModeShell>- )-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardHandoffDialog.stories.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardHandoffDialog.stories.tsxdeleted file mode 100644index 39f3a1c70e5b..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardHandoffDialog.stories.tsx+++ /dev/null@@ -1,56 +0,0 @@-import { Meta, StoryObj } from '@storybook/react'-import { useActions, useMountedLogic } from 'kea'-import { useEffect } from 'react'--import { WizardHandoffDialog } from './WizardHandoffDialog'-import { wizardSyncUiLogic } from './wizardSyncUiLogic'--const SAMPLE_REPORT = [- '# PostHog setup report',- '',- 'Installed `posthog-js` and wired up event capture for a Next.js app.',- '',- '## What changed',- '- Added `instrumentation-client.ts` with the PostHog init',- '- Wrapped the app in `PostHogProvider` in `app/providers.tsx`',- '- Added `NEXT_PUBLIC_POSTHOG_KEY` to `.env.local`',- '',- '## Events instrumented',- '| Event | Where |',- '| --- | --- |',- '| `signed_up` | `app/signup/page.tsx` |',- '| `checkout_started` | `app/checkout/page.tsx` |',- '',- '## Verify before merging',- '- [ ] Events arrive on the Activity page',- '- [ ] The API key lives in `.env.local`, not in source',- '- [ ] `pnpm build` passes',-].join('\n')--// The dialog reads from wizardSyncUiLogic, so the story opens a doc through the same action the-// announce path and the "View setup report" buttons use.-function OpenedHandoffDialog(): JSX.Element {- useMountedLogic(wizardSyncUiLogic)- const { openHandoffDoc } = useActions(wizardSyncUiLogic)- useEffect(() => {- openHandoffDoc({ key: 'story-run', text: SAMPLE_REPORT })- }, [openHandoffDoc])- return <WizardHandoffDialog />-}--const meta: Meta = {- title: 'Scenes-Other/Onboarding/Shared/Wizard Handoff Dialog',- component: WizardHandoffDialog,- parameters: {- layout: 'fullscreen',- viewMode: 'story',- testOptions: { waitForLoadersToDisappear: false },- },-}-export default meta--type Story = StoryObj<typeof WizardHandoffDialog>--export const Opened: Story = {- render: () => <OpenedHandoffDialog />,-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardHandoffDialog.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardHandoffDialog.tsxdeleted file mode 100644index b59d17011326..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardHandoffDialog.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonModal } from '@posthog/lemon-ui'--import { LazyLemonMarkdown } from 'lib/lemon-ui/LemonMarkdown/LazyLemonMarkdown'--import { wizardSyncUiLogic } from './wizardSyncUiLogic'--/**- * The handoff doc dialog: renders the markdown report a wizard run produced. Mounted once app-wide- * (next to the FAB) rather than per surface, so the one-time auto-open works no matter which scene- * the user is on; the run surfaces reopen it through `openHandoffDoc`.- */-export function WizardHandoffDialog(): JSX.Element {- const { handoffDoc } = useValues(wizardSyncUiLogic)- const { closeHandoffDoc } = useActions(wizardSyncUiLogic)- return (- <LemonModal- isOpen={!!handoffDoc}- onClose={closeHandoffDoc}- title="Setup report"- description="The agent wrote this report about the run it just finished."- width={640}- // The report is opened from inside the installation-progress modal (WizardSyncDialog),- // which sits at the default modal z-index, so lift the handoff above it — still below- // popovers/tooltips (1200+). 1167 is the only free LemonModal z-index: 1161 is shared- // with SessionPlayerModal, and since this dialog mounts at app boot and auto-opens, a- // tie there would land the report behind an open recording (later-mounted modal wins).- zIndex="1167"- >- {/* ph-no-capture: the report describes the customer's codebase (file paths, event- names, framework detail) and must not reach autocapture. disableImages: the text is- agent output, so an inline image would fire a request to an arbitrary URL. */}- <div className="ph-no-capture" data-attr="wizard-handoff-doc">- <LazyLemonMarkdown disableImages>{handoffDoc?.text ?? ''}</LazyLemonMarkdown>- </div>- </LemonModal>- )-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardInstallOptions.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardInstallOptions.tsxdeleted file mode 100644index c9394840333c..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardInstallOptions.tsx+++ /dev/null@@ -1,133 +0,0 @@-import { useActions, useValues } from 'kea'-import { useState } from 'react'--import { IconCloud, IconTerminal } from '@posthog/icons'-import { LemonSegmentedButton } from '@posthog/lemon-ui'--import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'--import { useWizardCommand } from '../useWizardCommand'-import { activeCloudRunLogic } from './activeCloudRunLogic'-import { WizardCloudRunBlock } from './WizardCloudRunBlock'-import { WizardFrameworkBadges, type WizardShellHog } from './WizardModeShell'--export type WizardInstallMode = 'cloud' | 'local'--export interface WizardInstallOptionsProps {- /** The local "run it yourself" arm. Callers supply their own command block. */- localBlock: React.ReactNode- /** Passed to the cloud run block; `null` keeps the compact onboarding card free of the hedgehog. */- hog?: WizardShellHog- /** Called when a cloud run is queued (e.g. advance or unblock the step). */- onQueued?: () => void- /** Instrumentation hook, fired when the user switches between cloud and local. */- onModeSelected?: (mode: WizardInstallMode) => void- /**- * Force the cloud arm off regardless of the experiment flag. The cloud runner only executes the- * base integration program, so offering it for any other program would queue a run that can- * never succeed.- */- offerCloudRun?: boolean- /**- * Treat a persisted cloud run as absent. A run queued on another step only executes the base- * integration program, so a dedicated-program step must keep showing its own command instead- * of the run's progress.- */- ignoreActiveCloudRun?: boolean- /** Replaces the default framework badge row. */- badges?: React.ReactNode-}--/**- * One wizard, two ways to run it: have us run it and open a PR (the cloud run), or run the CLI- * yourself. A segmented control switches between them. The cloud path only exists behind- * ONBOARDING_WIZARD_CLOUD_RUN (the AB test arm) on cloud/dev. Elsewhere this collapses to just- * the caller's local block, so the control arm is unchanged.- */-export function WizardInstallOptions({- localBlock,- hog,- onQueued,- onModeSelected,- offerCloudRun = true,- ignoreActiveCloudRun = false,- badges: badgesOverride,-}: WizardInstallOptionsProps): JSX.Element {- const cloudRunEnabled = useFeatureFlag('ONBOARDING_WIZARD_CLOUD_RUN', 'test')- const { isCloudOrDev } = useWizardCommand()- const { activeCloudRun: persistedCloudRun } = useValues(activeCloudRunLogic)- const activeCloudRun = ignoreActiveCloudRun ? null : persistedCloudRun- const { clearActiveCloudRun } = useActions(activeCloudRunLogic)- const [mode, setMode] = useState<WizardInstallMode>('cloud')-- const offerCloud = offerCloudRun && cloudRunEnabled && isCloudOrDev-- // GROW-95: once a cloud run is spawned you cannot also run it locally, so the local tab is blocked- // and the view pins to the cloud run's progress until it is cleared (e.g. via the failure fallback).- const localBlocked = !!activeCloudRun- const effectiveMode: WizardInstallMode = localBlocked ? 'cloud' : mode-- // A failed cloud run's fallback: drop the dead run (unblocks local, clears its FAB) and switch to- // the command.- const runItYourself = (): void => {- clearActiveCloudRun()- setMode('local')- }-- // The frameworks are the same whichever way the wizard runs, so the badge list rides with the- // options everywhere. Self-hosted gets no wizard, so no badges either.- const badges = isCloudOrDev && <div className="pb-2">{badgesOverride ?? <WizardFrameworkBadges />}</div>-- if (!offerCloud) {- // A persisted run outlives the experiment arm: keep rendering its progress (with the local- // fallback) even when the flag no longer offers new cloud runs, so nothing is stranded.- return (- <div className="flex flex-col gap-4">- {badges}- {activeCloudRun ? (- <WizardCloudRunBlock hog={hog} onRetryLocally={runItYourself} onQueued={onQueued} />- ) : (- localBlock- )}- </div>- )- }-- return (- <div className="flex flex-col gap-4">- {badges}- <LemonSegmentedButton- fullWidth- value={effectiveMode}- onChange={(value) => {- // LemonSegmentedButton fires onChange on any option click, including the one- // already selected — only report actual switches.- if (value !== effectiveMode) {- onModeSelected?.(value)- }- setMode(value)- }}- options={[- {- value: 'cloud',- label: 'Open a pull request',- icon: <IconCloud />,- 'data-attr': 'wizard-mode-cloud',- },- {- value: 'local',- label: 'Run it yourself',- icon: <IconTerminal />,- disabledReason: localBlocked ? 'A cloud run is in progress.' : undefined,- 'data-attr': 'wizard-mode-local',- },- ]}- />- {effectiveMode === 'cloud' ? (- <WizardCloudRunBlock hog={hog} onRetryLocally={runItYourself} onQueued={onQueued} />- ) : (- localBlock- )}- </div>- )-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.stories.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.stories.tsxdeleted file mode 100644index 9deee463afde..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.stories.tsx+++ /dev/null@@ -1,312 +0,0 @@-import { Meta, StoryObj } from '@storybook/react'--import { InstallationProgress, InstallationStepStatus } from './installationProgressLogic'-import { WizardSyncCard, WizardSyncMode } from './WizardSyncCard'--/**- * The detached wizard sync widget (collapsed), driven by fixtures so every cloud and local state is- * reviewable in isolation. The component is pure, so no streams or mocks are needed.- */-const meta: Meta<typeof WizardSyncCard> = {- title: 'Scenes-Other/Onboarding/Shared/Wizard Sync Card',- component: WizardSyncCard,- argTypes: {- onExpand: { action: 'expand' },- onDismiss: { action: 'dismiss' },- },- // Most stories here render an in-progress spinner by design (connecting/running phases), which never- // resolves — skip the test runner's default "wait for loaders to hide" check.- parameters: { testOptions: { waitForLoadersToDisappear: false } },- decorators: [- (Story) => (- <div className="bg-primary p-8 flex justify-end">- <Story />- </div>- ),- ],-}-export default meta-type Story = StoryObj<typeof WizardSyncCard>--// Cloud pipeline steps with a status per stage, plus an optional live detail on one stage.-function cloudSteps(- statuses: InstallationStepStatus[],- detail?: { at: number; text: string }-): InstallationProgress['steps'] {- const labels = [- 'Set up sandbox',- 'Cloned repository',- 'Ran PostHog setup wizard',- 'Started agent',- 'Opened pull request',- 'Keeping CI green',- ]- return labels.map((label, i) => ({- id: `setup:${i}`,- label,- status: statuses[i] ?? 'pending',- detail: detail && detail.at === i ? detail.text : null,- }))-}--function progress(overrides: Partial<InstallationProgress>): InstallationProgress {- return {- phase: 'running',- steps: [],- error: null,- prUrl: null,- prMerged: false,- isCurrent: true,- pendingInput: null,- startedBy: null,- handoffText: null,- ...overrides,- }-}--export const Connecting: Story = {- args: { mode: 'cloud', elapsedSeconds: 3, progress: progress({ phase: 'connecting' }) },-}--// Local, the agent is blocked on a wizard_ask in the terminal: the question leads the card in the-// warning tone. The call to go back to the terminal leads; the question sits under it.-export const LocalWaitingForInput: Story = {- args: {- mode: 'local',- elapsedSeconds: 74,- progress: progress({- steps: [- { id: '0', label: 'Detect framework', status: 'completed', detail: null },- { id: '1', label: 'Install the SDK', status: 'in_progress', detail: null },- { id: '2', label: 'Instrument events', status: 'pending', detail: null },- ],- pendingInput: {- id: 'ask-1',- askedAt: '2026-01-01T00:01:00Z',- questionCount: 1,- sensitive: false,- prompts: ['Which region is your project in?'],- },- }),- },-}--// A secret was asked for, so no prompt text is published and the call to action stands alone.-export const LocalWaitingForSensitiveInput: Story = {- args: {- mode: 'local',- elapsedSeconds: 74,- progress: progress({- steps: [- { id: '0', label: 'Detect framework', status: 'completed', detail: null },- { id: '1', label: 'Install the SDK', status: 'in_progress', detail: null },- { id: '2', label: 'Instrument events', status: 'pending', detail: null },- ],- pendingInput: {- id: 'ask-2',- askedAt: '2026-01-01T00:01:00Z',- questionCount: 1,- sensitive: true,- prompts: [],- },- }),- },-}--// Cloud, wizard phase: the wizard's live sub-task ("Capturing events") leads the card.-export const CloudWizardRunning: Story = {- args: {- mode: 'cloud',- elapsedSeconds: 134,- progress: progress({- steps: cloudSteps(['completed', 'completed', 'in_progress', 'pending', 'pending', 'pending'], {- at: 2,- text: 'Capturing events',- }),- }),- },-}--// Cloud, agent has opened the PR and is keeping CI green.-export const CloudKeepingCiGreen: Story = {- args: {- mode: 'cloud',- elapsedSeconds: 921,- progress: progress({- prUrl: 'https://github.com/acme-co/web/pull/42',- steps: cloudSteps(['completed', 'completed', 'completed', 'completed', 'completed', 'in_progress']),- }),- },-}--// Local run: the wizard's own tasks are the steps.-export const LocalRunning: Story = {- args: {- mode: 'local',- elapsedSeconds: 47,- progress: progress({- steps: [- { id: 'plan', label: 'Plan event tracking', status: 'completed', detail: null },- { id: 'install', label: 'Install PostHog', status: 'in_progress', detail: null },- { id: 'capture', label: 'Capture events', status: 'pending', detail: null },- { id: 'verify', label: 'Verify it works', status: 'pending', detail: null },- ],- }),- },-}--// Local run started by a teammate: the chip names them instead of "On your machine".-export const LocalRunningStartedByTeammate: Story = {- args: {- mode: 'local',- elapsedSeconds: 47,- startedByLabel: 'Edwin',- progress: progress({- steps: [- { id: 'plan', label: 'Plan event tracking', status: 'completed', detail: null },- { id: 'install', label: 'Install PostHog', status: 'in_progress', detail: null },- { id: 'capture', label: 'Capture events', status: 'pending', detail: null },- ],- }),- },-}--export const Completed: Story = {- args: {- mode: 'cloud',- elapsedSeconds: 1820,- progress: progress({- phase: 'completed',- prUrl: 'https://github.com/acme-co/web/pull/42',- steps: cloudSteps(['completed', 'completed', 'completed', 'completed', 'completed', 'completed']),- }),- },-}--// A finished local run: no PR to review, so the setup report the agent wrote is the footer payoff,-// and the X reads as a real dismissal.-export const CompletedLocal: Story = {- args: {- mode: 'local',- elapsedSeconds: 421,- progress: progress({- phase: 'completed',- steps: [- { id: 'a', label: 'Detected Next.js', status: 'completed', detail: null },- { id: 'b', label: 'Installed the PostHog SDK', status: 'completed', detail: null },- { id: 'c', label: 'Wired up event capture', status: 'completed', detail: null },- ],- handoffText: '# PostHog setup report\n\nInstalled `posthog-js` and wired up event capture.',- }),- dismissTooltip: 'Dismiss',- },- argTypes: { onViewReport: { action: 'view-report' } },-}--// A run still nominally in flight that has gone quiet: the clock is replaced by the reason it stopped-// meaning anything, and the X dismisses rather than minimizes.-export const Stalled: Story = {- args: {- mode: 'cloud',- elapsedSeconds: 42 * 3600,- stale: true,- dismissTooltip: 'Dismiss',- progress: progress({- steps: cloudSteps(['completed', 'completed', 'in_progress', 'pending', 'pending', 'pending']),- }),- },-}--export const Failed: Story = {- args: {- mode: 'cloud',- elapsedSeconds: 312,- progress: progress({- phase: 'error',- steps: cloudSteps(['completed', 'completed', 'failed', 'pending', 'pending', 'pending']),- error: { title: 'Setup hit a snag', detail: 'The setup wizard could not finish.' },- }),- },-}--// Every state in one canvas, for side-by-side review (GROW-98). Reuses the individual stories' args so-// there is a single source of truth for each fixture.-export const AllStates: Story = {- parameters: { controls: { disable: true } },- render: () => {- const states: { label: string; args: Story['args'] }[] = [- { label: 'Connecting', args: Connecting.args },- { label: 'Cloud, wizard running', args: CloudWizardRunning.args },- { label: 'Cloud, keeping CI green', args: CloudKeepingCiGreen.args },- { label: 'Local, running', args: LocalRunning.args },- { label: 'Local, started by a teammate', args: LocalRunningStartedByTeammate.args },- { label: 'Completed', args: Completed.args },- { label: 'Completed, local (report payoff)', args: CompletedLocal.args },- { label: 'Stalled', args: Stalled.args },- { label: 'Failed', args: Failed.args },- ]- return (- <div className="flex flex-col gap-5 items-end">- {states.map(({ label, args }) => (- <div key={label} className="flex flex-col gap-1 items-end">- <span className="text-xs text-muted">{label}</span>- <WizardSyncCard- progress={args!.progress!}- elapsedSeconds={args!.elapsedSeconds!}- mode={args!.mode!}- stale={args!.stale}- startedByLabel={args!.startedByLabel}- onViewReport={() => {}}- onExpand={() => {}}- onDismiss={() => {}}- />- </div>- ))}- </div>- )- },-}--// Configure the card live from the controls panel (GROW-98): pick phase, mode, how many steps are done,-// the current task label, and elapsed, and the fixture is built from those.-interface PlaygroundArgs {- phase: InstallationProgress['phase']- mode: WizardSyncMode- elapsedSeconds: number- completedSteps: number- currentTask: string-}--export const Playground: StoryObj<PlaygroundArgs> = {- argTypes: {- phase: { control: 'select', options: ['connecting', 'running', 'completed', 'error'] },- mode: { control: 'inline-radio', options: ['cloud', 'local'] },- elapsedSeconds: { control: { type: 'number', min: 0 } },- completedSteps: { control: { type: 'range', min: 0, max: 6 } },- currentTask: { control: 'text' },- },- args: { phase: 'running', mode: 'cloud', elapsedSeconds: 134, completedSteps: 2, currentTask: 'Capturing events' },- render: (args) => {- const statuses: InstallationStepStatus[] = [0, 1, 2, 3, 4, 5].map((i) =>- i < args.completedSteps ? 'completed' : i === args.completedSteps ? 'in_progress' : 'pending'- )- const built = progress({- phase: args.phase,- steps: cloudSteps(- statuses,- args.currentTask ? { at: args.completedSteps, text: args.currentTask } : undefined- ),- prUrl: args.phase === 'completed' ? 'https://github.com/acme-co/web/pull/42' : null,- error: args.phase === 'error' ? { title: 'Setup hit a snag', detail: 'Something stopped the run.' } : null,- })- return (- <WizardSyncCard- progress={built}- elapsedSeconds={args.elapsedSeconds}- mode={args.mode}- onExpand={() => {}}- onDismiss={() => {}}- />- )- },-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.tsxdeleted file mode 100644index b7764735d81e..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.tsx+++ /dev/null@@ -1,185 +0,0 @@-import { IconCloud, IconDocument, IconExpand45, IconLaptop, IconPullRequest, IconX } from '@posthog/icons'-import { LemonButton } from '@posthog/lemon-ui'--import { cn } from 'lib/utils/css-classes'--import {- currentTaskLabel,- elapsedLabel,- formatElapsed,- pendingQuestionLabel,- prNameLabel,- stepCounts,- syncHeadline,- toneTextClass,- localModeLabel,-} from './helpers'-import { InstallationProgress } from './installationProgressLogic'-import { PipStrip } from './PipStrip'-import { StatusGlyph } from './StatusGlyph'--export type WizardSyncMode = 'cloud' | 'local'--// Tiny chip naming where the run is happening, so cloud and local runs read distinctly.-function ModeChip({ mode, startedByLabel }: { mode: WizardSyncMode; startedByLabel?: string | null }): JSX.Element {- return (- <span className="inline-flex items-center gap-1 text-xs text-muted">- {mode === 'cloud' ? <IconCloud className="text-sm" /> : <IconLaptop className="text-sm" />}- {mode === 'cloud' ? 'Cloud run' : localModeLabel(startedByLabel)}- </span>- )-}--/**- * The collapsed detached widget: the wizard's current task takes top billing, with the phase, where it- * is running, elapsed time, and a per-step pip strip as supporting context. Pure and position-agnostic- * (the FAB wrapper pins it to the corner) so every state is storyable. Clicking the body, or the expand- * control, opens the full dialog.- */-export function WizardSyncCard({- progress,- elapsedSeconds,- mode,- stale = false,- onViewReport,- onExpand,- onDismiss,- dismissTooltip = 'Dismiss',- startedByLabel,-}: {- progress: InstallationProgress- elapsedSeconds: number- mode: WizardSyncMode- /** The run has gone quiet: the clock is replaced by the reason it stopped meaning anything. */- stale?: boolean- /** A teammate's name for a local run they started (null when it's the viewer's own run or unknown). */- startedByLabel?: string | null- /** Opens the run's handoff doc (the setup report) — the completed card's payoff for runs with- * no PR. Only rendered when the progress actually carries a doc. */- onViewReport?: () => void- onExpand: () => void- onDismiss?: () => void- /** What the X actually does here — "Minimize" while the run is live, "Dismiss" once terminal. */- dismissTooltip?: string-}): JSX.Element {- const { completed, total } = stepCounts(progress.steps)- const task = currentTaskLabel(progress)- const question = pendingQuestionLabel(progress)- const isRunning = progress.phase !== 'completed' && progress.phase !== 'error'-- return (- <div- className="w-[340px] bg-surface-primary rounded-xl border border-primary shadow-xl shadow-black/10 overflow-hidden"- role="status"- aria-live="polite"- data-attr="wizard-sync-card"- >- <button- type="button"- onClick={onExpand}- aria-label="Expand setup details"- className="w-full text-left flex flex-col gap-2.5 px-3.5 py-3 hover:bg-fill-highlight-50 transition-colors cursor-pointer"- >- <div className="flex items-center gap-2.5">- <StatusGlyph progress={progress} />- <div className="flex-1 min-w-0">- <p- className={cn('m-0 text-sm font-semibold truncate', toneTextClass(progress))}- title={task ?? undefined}- >- {task}- </p>- <p className="m-0 text-xs text-muted truncate">{syncHeadline(progress)}</p>- {question && (- // ph-no-capture: the prompt is whatever the wizard asked, so it can- // carry project detail that must not reach autocapture.- <p className="m-0 text-xs text-tertiary truncate ph-no-capture" title={question}>- {question}- </p>- )}- </div>- <span className="text-xs text-muted tabular-nums shrink-0" title={formatElapsed(elapsedSeconds)}>- {elapsedLabel(elapsedSeconds, stale)}- </span>- </div>-- {total > 0 ? (- <div className="flex items-center gap-2">- <PipStrip steps={progress.steps} className="flex-1" />- <span className="text-xs text-muted tabular-nums shrink-0">- {completed}/{total}- </span>- </div>- ) : (- isRunning && (- // No step detail yet (connecting, or a polling-mode run where step- // notifications are stream-borne): an indeterminate strip keeps the card- // visibly alive instead of looking stalled.- <div- className="h-1 rounded-full bg-fill-highlight-100 overflow-hidden"- aria-label="Setup in progress"- >- <div className="h-full w-1/3 rounded-full bg-accent animate-pulse" />- </div>- )- )}- </button>-- <div className="flex items-center justify-between gap-2 px-3.5 py-2 border-t border-primary">- <ModeChip mode={mode} startedByLabel={startedByLabel} />- <div className="flex items-center gap-1">- {progress.prUrl && (- // ph-no-capture: the label carries the customer's repo name and the href- // their PR url — neither may reach autocapture in shared app analytics.- // Truncated: owner + repo can reach ~140 chars and this footer sits inside- // a fixed 340px card next to the mode chip and two icon buttons.- <LemonButton- size="xsmall"- // The PR is the run's payoff: promote it once the run has finished.- type={progress.phase === 'completed' ? 'primary' : 'secondary'}- to={progress.prUrl}- targetBlank- icon={<IconPullRequest />}- onClick={(e) => e.stopPropagation()}- className="ph-no-capture"- tooltip={prNameLabel(progress.prUrl)}- >- <span className="truncate max-w-32">{prNameLabel(progress.prUrl)}</span>- </LemonButton>- )}- {progress.phase === 'completed' && !progress.prUrl && progress.handoffText && onViewReport && (- <LemonButton- size="xsmall"- type="primary"- icon={<IconDocument />}- onClick={(e) => {- e.stopPropagation()- onViewReport()- }}- tooltip="What the agent set up, and what to check before you commit"- data-attr="wizard-sync-card-view-report"- >- Setup report- </LemonButton>- )}- <LemonButton- size="xsmall"- icon={<IconExpand45 />}- onClick={onExpand}- tooltip="See all the details"- aria-label="Expand"- />- {onDismiss && (- <LemonButton- size="xsmall"- icon={<IconX />}- onClick={onDismiss}- tooltip={dismissTooltip}- aria-label={dismissTooltip}- />- )}- </div>- </div>- </div>- )-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncDebugPanel.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncDebugPanel.tsxdeleted file mode 100644index 94ac7643b3bc..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncDebugPanel.tsx+++ /dev/null@@ -1,107 +0,0 @@-import { useActions, useValues } from 'kea'-import { useState } from 'react'--import { IconChevronDown, IconChevronRight } from '@posthog/icons'--import { dayjs } from 'lib/dayjs'-import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { LemonTag } from 'lib/lemon-ui/LemonTag'-import { pluralize } from 'lib/utils/strings'-import { type SyncDebugKind, wizardSyncDebugLogic } from 'lib/wizard-sync/wizardSyncDebugLogic'--const KIND_COLORS: Record<SyncDebugKind, string> = {- connect: 'text-muted',- open: 'text-success',- poll: 'text-default',- event: 'text-default',- error: 'text-danger',- complete: 'text-success',- disconnect: 'text-muted',-}--function formatTs(at: number): string {- return dayjs(at).format('HH:mm:ss.SSS')-}--function formatGap(gapMs: number | null): string {- return gapMs === null ? '' : ` (+${(gapMs / 1000).toFixed(2)}s)`-}--/**- * Dev-only floating panel (bottom-left) surfacing what the wizard sync transports are doing: which- * mode each source runs in (SSE vs polling), when polls/events land and the gap between them, and a- * timestamped log. Renders nothing in production builds and stays hidden until a sync source emits.- */-export function WizardSyncDebugPanel(): JSX.Element | null {- if (process.env.NODE_ENV !== 'development') {- return null- }- return <WizardSyncDebugPanelContent />-}--function WizardSyncDebugPanelContent(): JSX.Element | null {- const { entries, sources } = useValues(wizardSyncDebugLogic)- const { clearSyncDebugLog } = useActions(wizardSyncDebugLogic)- const [collapsed, setCollapsed] = useState(false)-- const sourceList = Object.values(sources)- if (sourceList.length === 0) {- return null- }-- return (- <div className="fixed bottom-2 left-2 z-[9999] max-w-lg rounded border bg-surface-primary shadow-md text-xs">- <div className="flex items-center gap-1 px-2 py-1 border-b">- <LemonButton- size="xsmall"- icon={collapsed ? <IconChevronRight /> : <IconChevronDown />}- onClick={() => setCollapsed(!collapsed)}- tooltip={collapsed ? 'Expand' : 'Collapse'}- aria-label={collapsed ? 'Expand wizard sync debug panel' : 'Collapse wizard sync debug panel'}- />- <span className="font-semibold">Wizard sync debug</span>- <span className="text-muted">({pluralize(entries.length, 'event')})</span>- <div className="flex-1" />- <LemonButton size="xsmall" onClick={clearSyncDebugLog}>- Clear- </LemonButton>- </div>- {!collapsed && (- <>- <div className="px-2 py-1 space-y-1 border-b">- {sourceList.map((info) => (- <div key={info.source} className="flex items-center gap-2">- <LemonTag type={info.mode === 'polling' ? 'warning' : 'success'} size="small">- {info.mode ?? '?'}- </LemonTag>- <span className="font-mono truncate max-w-40" title={info.source}>- {info.source}- </span>- {info.mode === 'polling' && info.intervalMs !== null && (- <span className="text-muted">~{info.intervalMs / 1000}s ±20%</span>- )}- <span className="text-muted">- {pluralize(info.ticks, info.mode === 'polling' ? 'poll' : 'event')}- </span>- {info.lastAt !== null && (- <span className="text-muted">- last {formatTs(info.lastAt)}- {formatGap(info.lastGapMs)}- </span>- )}- </div>- ))}- </div>- <div className="max-h-48 overflow-y-auto overflow-x-auto px-2 py-1 font-mono whitespace-nowrap">- {entries.map((entry) => (- <div key={entry.id} className={KIND_COLORS[entry.kind]}>- {formatTs(entry.at)} [{entry.kind}] {entry.source}: {entry.message}- {formatGap(entry.gapMs)}- </div>- ))}- </div>- </>- )}- </div>- )-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncDialog.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncDialog.tsxdeleted file mode 100644index 09af569a19a3..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncDialog.tsx+++ /dev/null@@ -1,78 +0,0 @@-import { LemonButton, LemonModal } from '@posthog/lemon-ui'--import { cn } from 'lib/utils/css-classes'--import { elapsedLabel, localModeLabel, syncHeadline, toneTextClass } from './helpers'-import { InstallationProgressContent } from './InstallationProgressContent'-import { InstallationProgress } from './installationProgressLogic'-import { WizardSyncMode } from './WizardSyncCard'--// The expanded "all the details" dialog: the full pipeline plus the terminal payoff or failure.-// Rendered by the FAB and by the inbox rail's Installation card, which claims the run away from-// the FAB — hence its own file rather than living with either surface.-export function WizardSyncDialog({- progress,- elapsedSeconds,- mode,- isOpen,- onClose,- onClear,- onCancel,- onViewReport,- cancelling = false,- stale = false,- startedByLabel,-}: {- progress: InstallationProgress- elapsedSeconds: number- mode: WizardSyncMode- isOpen: boolean- onClose: () => void- onClear?: () => void- onCancel?: () => void- /** Opens the run's handoff doc (the setup report) when the progress carries one. */- onViewReport?: () => void- cancelling?: boolean- /** The run has gone quiet for long enough that it can be dismissed without orphaning live work. */- stale?: boolean- /** A teammate's name for a local run they started (null when it's the viewer's own run or unknown). */- startedByLabel?: string | null-}): JSX.Element {- const isTerminal = progress.phase === 'completed' || progress.phase === 'error'- return (- <LemonModal isOpen={isOpen} onClose={onClose} title="PostHog setup" width={480}>- <div className="flex flex-col gap-3">- <div className="flex items-center justify-between text-xs">- <span className={cn('font-medium', toneTextClass(progress))}>{syncHeadline(progress)}</span>- <span className="text-muted tabular-nums">- {mode === 'cloud' ? 'Cloud run' : localModeLabel(startedByLabel)} ·{' '}- {elapsedLabel(elapsedSeconds, stale)}- </span>- </div>- <InstallationProgressContent progress={progress} mode={mode} onViewReport={onViewReport} />- {/* A stale run gets the same exit as a terminal one: nothing is reporting on it, so- leaving Cancel as the only control would strand the user behind a request that- cannot bring it back. Cancel stays available below for as long as the run is not- terminal, since the backend may still be holding a sandbox for it. */}- {(isTerminal || stale) && onClear && (- <LemonButton type="secondary" onClick={onClear} className="self-end">- Dismiss this run- </LemonButton>- )}- {!isTerminal && onCancel && (- <LemonButton- type="secondary"- status="danger"- onClick={onCancel}- loading={cancelling}- disabledReason={cancelling ? 'Cancelling the run' : undefined}- className="self-end"- data-attr="wizard-sync-cancel-run"- >- Cancel run- </LemonButton>- )}- </div>- </LemonModal>- )-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsxdeleted file mode 100644index 628458e556de..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsx+++ /dev/null@@ -1,120 +0,0 @@-import { useActions, useMountedLogic, useValues } from 'kea'--import { activeCloudRunLogic, CloudRunHandle } from './activeCloudRunLogic'-import { finishedLocalRunLogic } from './finishedLocalRunLogic'-import { isStreamLost } from './helpers'-import { progressFromFinishedLocalRun } from './installationProgress'-import { installationProgressLogic } from './installationProgressLogic'-import { wizardActiveSessionDetectorLogic } from './wizardActiveSessionDetectorLogic'-import { WizardSyncSurface } from './WizardSyncSurface'-import { wizardSyncUiLogic } from './wizardSyncUiLogic'--// A cloud run: the Installation layer streams the pipeline; elapsed comes from the handle's kickoff stamp.-function WizardSyncCloudFab({ handle }: { handle: CloudRunHandle }): JSX.Element {- const { installationProgress, taskRunState, lastActivityAt, taskConnectionStatus, isStalled } = useValues(- installationProgressLogic({ mode: 'cloud', runId: handle.runId, taskId: handle.taskId })- )- const { cancellingRun } = useValues(activeCloudRunLogic)- const { clearActiveCloudRun, cancelActiveCloudRun } = useActions(activeCloudRunLogic)- const isTerminal = installationProgress.phase === 'completed' || installationProgress.phase === 'error'- return (- <WizardSyncSurface- progress={installationProgress}- startedAt={handle.startedAt}- endedAt={isTerminal ? (taskRunState?.completed_at ?? taskRunState?.updated_at) : undefined}- lastActivityAt={lastActivityAt}- streamLost={isStreamLost(taskConnectionStatus, isStalled)}- mode="cloud"- runKey={handle.runId}- onClear={clearActiveCloudRun}- onCancel={cancelActiveCloudRun}- cancelling={cancellingRun}- />- )-}--// A finished local run rendered from its persisted snapshot: the session stream gates itself off-// shortly after a terminal phase (INC-886), but the handoff stays until the user dismisses it.-function WizardSyncFinishedLocalFab(): JSX.Element | null {- const { finishedLocalRun } = useValues(finishedLocalRunLogic)- const { dismissLocalRun } = useActions(finishedLocalRunLogic)- if (!finishedLocalRun) {- return null- }- return (- <WizardSyncSurface- progress={progressFromFinishedLocalRun(finishedLocalRun)}- startedAt={finishedLocalRun.startedAt}- endedAt={finishedLocalRun.finishedAt}- mode="local"- runKey={finishedLocalRun.sessionId}- onClear={() => dismissLocalRun(finishedLocalRun.sessionId)}- />- )-}--// A live local run: the wizard session stream is the source; elapsed comes from its started_at.-function WizardSyncLocalFab({ workflowId }: { workflowId: string }): JSX.Element | null {- const { installationProgress, latestSession } = useValues(installationProgressLogic({ mode: 'local', workflowId }))- const { dismissedSessionId } = useValues(finishedLocalRunLogic)- const { dismissLocalRun } = useActions(finishedLocalRunLogic)- // No session on the stream yet, or the user already dismissed this one — fall back to the- // persisted finished run (if any) rather than rendering nothing.- if (!latestSession || latestSession.session_id === dismissedSessionId) {- return <WizardSyncFinishedLocalFab />- }- const isTerminal = installationProgress.phase === 'completed' || installationProgress.phase === 'error'- return (- <WizardSyncSurface- progress={installationProgress}- startedAt={latestSession.started_at}- endedAt={isTerminal ? latestSession.updated_at : undefined}- mode="local"- runKey={latestSession.session_id}- onClear={() => dismissLocalRun(latestSession.session_id)}- />- )-}--// Gate the local SSE behind the cheap detector poll, so a stream is opened only when a run is in-// flight. Once the detector gates the stream off (terminal grace expired), the persisted finished-// run keeps the handoff on screen without any stream.-function WizardSyncLocalGate(): JSX.Element | null {- useMountedLogic(wizardActiveSessionDetectorLogic)- // Stream whichever program the detector found live, so a self-driving run is surfaced by the- // same widget rather than being mistaken for an SDK install (or missed entirely).- const { shouldStream, activeWorkflowId } = useValues(wizardActiveSessionDetectorLogic)- if (!shouldStream || !activeWorkflowId) {- return <WizardSyncFinishedLocalFab />- }- return <WizardSyncLocalFab workflowId={activeWorkflowId} />-}--/**- * The single detached wizard sync widget, mounted app-wide (AuthenticatedShell). It surfaces whichever- * run is in flight, cloud or local, in one place: a cloud run (the persisted handle) takes precedence,- * otherwise a local wizard session detected by the poll, otherwise a finished local run the user has- * not yet dismissed. Replaces the earlier separate cloud-run and per-mode corner widgets so there is- * one corner widget, never two.- */-export function WizardSyncFab(): JSX.Element | null {- const { activeCloudRun } = useValues(activeCloudRunLogic)- const { inlineCloudPanelMounted, inlineLocalPanelMounted } = useValues(wizardSyncUiLogic)-- // Deliberately not gated on the cloud-run flag: a persisted handle is proof the run started- // while the user was on the test arm, and a mid-experiment flag change must not strand an- // in-flight run with no surface (and no way to dismiss it). Only STARTING runs is flag-gated.- // Checked before the inline-panel claim because that claim is made by surfaces that only ever- // render the *local* run: letting it win here would leave a concurrent cloud run with no- // progress, no cancel and no dismiss for as long as the inline surface is open.- if (activeCloudRun && !inlineCloudPanelMounted) {- return <WizardSyncCloudFab handle={activeCloudRun} />- }- // An inline install-step progress view is already showing this run, so stay out of its way. The FAB- // is for after the user moves on from the install step. Both inline views (cloud and local) claim- // the inline-panel claim, so the run is never shown in two places.- if (inlineLocalPanelMounted || (activeCloudRun && inlineCloudPanelMounted)) {- return null- }- return <WizardSyncLocalGate />-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncLauncher.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncLauncher.tsxdeleted file mode 100644index 10396bde6ce1..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncLauncher.tsx+++ /dev/null@@ -1,41 +0,0 @@-import { cn } from 'lib/utils/css-classes'--import { elapsedLabel } from './helpers'-import { InstallationProgress } from './installationProgressLogic'-import { StatusGlyph } from './StatusGlyph'--// The minimized state: a small pill that restores the card. This is the "activate it back" affordance.-export function WizardSyncLauncher({- progress,- elapsedSeconds,- stale = false,- onRestore,-}: {- progress: InstallationProgress- elapsedSeconds: number- stale?: boolean- onRestore: () => void-}): JSX.Element {- return (- <button- type="button"- onClick={onRestore}- aria-label="Show PostHog setup progress"- data-attr="wizard-sync-launcher"- className={cn(- 'flex items-center gap-2 rounded-full bg-surface-primary border shadow-lg shadow-black/10 pl-2 pr-3 py-1.5 hover:bg-fill-highlight-50 transition-colors cursor-pointer',- // A minimized run that finished (or failed) should read at a glance, not hide as a- // neutral pill.- progress.phase === 'completed'- ? 'border-success'- : progress.phase === 'error'- ? 'border-danger'- : 'border-primary'- )}- >- <StatusGlyph progress={progress} />- <span className="text-sm font-medium">PostHog setup</span>- <span className="text-xs text-muted tabular-nums">{elapsedLabel(elapsedSeconds, stale)}</span>- </button>- )-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncSurface.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncSurface.tsxdeleted file mode 100644index 9687196c2aca..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncSurface.tsx+++ /dev/null@@ -1,163 +0,0 @@-import { useActions, useValues } from 'kea'-import { useEffect, useRef } from 'react'--import { elapsedSecondsFrom } from 'lib/utils/datetime'-import { userLogic } from 'scenes/userLogic'--import { onboardingEventUsageLogic } from '../../onboardingEventUsageLogic'-import { isRunStale, resolveStartedByLabel } from './helpers'-import { useNow } from './hooks'-import { InstallationProgress } from './installationProgressLogic'-import { WizardSyncCard, WizardSyncMode } from './WizardSyncCard'-import { WizardSyncDialog } from './WizardSyncDialog'-import { WizardSyncLauncher } from './WizardSyncLauncher'-import { wizardSyncUiLogic } from './wizardSyncUiLogic'--// Corner anchor for the collapsed card and the minimized launcher. The dialog is a portal, so it-// positions itself.-const CORNER = 'fixed bottom-[calc(1.25rem+var(--terminal-dock-height,0px))] right-5 z-[60]'--// Shared presentation for a single run: the collapsed card or, once dismissed, the launcher, plus the-// dialog. Owns the elapsed clock and reads the shared dismiss/expand UI state.-export function WizardSyncSurface({- progress,- startedAt,- endedAt,- lastActivityAt = null,- streamLost = false,- mode,- runKey,- onClear,- onCancel,- cancelling = false,-}: {- progress: InstallationProgress- startedAt: string | undefined- /** When the run finished — freezes the elapsed timer so a finished run that stays on screen- * until dismissed shows its duration, not a clock that keeps counting. */- endedAt?: string- /** When the run's stream last delivered anything (cloud runs only), for the staleness check. */- lastActivityAt?: number | null- /** Nothing is currently carrying this run's updates (cloud runs only): the stream failed or- * closed, or the logic has already given up on it. Silence only counts as staleness while this- * holds. See `isStreamLost` for why a stream still connecting does not qualify. */- streamLost?: boolean- mode: WizardSyncMode- runKey: string- onClear?: () => void- /** Cancels the run server-side (cloud runs only) — shown in the dialog while the run is live. */- onCancel?: () => void- cancelling?: boolean-}): JSX.Element {- const { dismissedKey, dialogOpen } = useValues(wizardSyncUiLogic)- const { dismiss, restore, openDialog, closeDialog, openHandoffDoc } = useActions(wizardSyncUiLogic)- const { user } = useValues(userLogic)- const startedByLabel = resolveStartedByLabel(progress.startedBy, user?.email)- const {- reportWizardSyncExpanded,- reportWizardSyncMinimized,- reportWizardSyncRestored,- reportWizardSyncRunDismissed,- reportWizardSyncHandoffShown,- reportWizardSyncHandoffDocOpened,- } = useActions(onboardingEventUsageLogic)- // `now` also feeds the staleness check, which needs a live clock while the run is non-terminal.- const endMs = endedAt ? new Date(endedAt).getTime() : NaN- const now = useNow(!Number.isNaN(endMs))- const elapsedSeconds = startedAt ? elapsedSecondsFrom(startedAt, Number.isNaN(endMs) ? now : endMs) : 0- // Input-required overrides minimize: the user who tucked the widget away mid-run is exactly the- // one who will miss the prompt. The server clearing pending_input restores their choice.- const minimized = dismissedKey === runKey && !progress.pendingInput- const isTerminal = progress.phase === 'completed' || progress.phase === 'error'- // Only cloud runs can zombie like this: their handle is persisted browser state that outlives the- // run, where a local run is gated by the session detector's own liveness poll.- const stale = mode === 'cloud' && !isTerminal && isRunStale(startedAt, lastActivityAt, streamLost, now)- const eventProps = { runKey, mode, phase: progress.phase }-- // The completed-handoff funnel (exposure + CTA impression) — deduped per run inside the events- // logic, so this fires safely even when the inline panel reported the same run first.- const completed = progress.phase === 'completed'- const prOpened = !!progress.prUrl- useEffect(() => {- if (completed) {- reportWizardSyncHandoffShown({ runKey, mode, surface: 'fab', prOpened })- }- }, [completed, runKey, mode, prOpened, reportWizardSyncHandoffShown])- const handoffText = progress.handoffText- const handleViewReport = handoffText- ? () => {- reportWizardSyncHandoffDocOpened({ runKey, mode, trigger: 'button' })- openHandoffDoc({ key: runKey, text: handoffText })- }- : undefined- // One-shot: a double-click can land two dispatches before the surface unmounts, which would- // double-fire the dismissal telemetry and re-run onClear.- const clearedRef = useRef(false)- // Clearing a finished run also closes the dialog before the surface unmounts.- const handleClear = onClear- ? () => {- if (clearedRef.current) {- return- }- clearedRef.current = true- reportWizardSyncRunDismissed({ ...eventProps, elapsedSeconds })- closeDialog()- onClear()- }- : undefined- const handleMinimize = (): void => {- reportWizardSyncMinimized(eventProps)- dismiss(runKey)- }- const dismissible = isTerminal || prOpened || stale-- return (- <>- <div className={CORNER}>- {minimized ? (- <WizardSyncLauncher- progress={progress}- elapsedSeconds={elapsedSeconds}- stale={stale}- onRestore={() => {- reportWizardSyncRestored(eventProps)- restore()- }}- />- ) : (- <WizardSyncCard- progress={progress}- elapsedSeconds={elapsedSeconds}- mode={mode}- stale={stale}- startedByLabel={startedByLabel}- onViewReport={handleViewReport}- onExpand={() => {- reportWizardSyncExpanded(eventProps)- openDialog()- }}- // Mid-run the X only minimizes, since hiding a live run for good would- // orphan it. Once the run is terminal, the PR exists, or the run has gone- // quiet long enough to count as stale, the X becomes the real dismissal- // (the run never leaves on its own).- onDismiss={dismissible && handleClear ? handleClear : handleMinimize}- dismissTooltip={dismissible && handleClear ? 'Dismiss' : 'Minimize'}- />- )}- </div>- <WizardSyncDialog- progress={progress}- elapsedSeconds={elapsedSeconds}- mode={mode}- stale={stale}- startedByLabel={startedByLabel}- onViewReport={handleViewReport}- isOpen={dialogOpen}- onClose={closeDialog}- onClear={handleClear}- onCancel={onCancel}- cancelling={cancelling}- />- </>- )-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.tsdeleted file mode 100644index 3c3d3b43c707..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.ts+++ /dev/null@@ -1,358 +0,0 @@-import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER, MOCK_TEAM_ID } from 'lib/api.mock'--import { expectLogic } from 'kea-test-utils'--import { projectLogic } from 'scenes/projectLogic'--import { initKeaTests } from '~/test/init'-import type { AppContext, OnboardingSkippedReason, TeamType } from '~/types'--import { tasksActiveWizardRunRetrieve, tasksRunsCancelCreate } from 'products/tasks/frontend/generated/api'--import {- activeCloudRunLogic,- CloudRunHandle,- CloudRunReconciliation,- RECONCILE_INTERVAL_MS,- reconcileCloudRun,- scopedCloudRun,-} from './activeCloudRunLogic'--jest.mock('products/tasks/frontend/generated/api', () => ({- tasksActiveWizardRunRetrieve: jest.fn(),- tasksRunsCancelCreate: jest.fn(),-}))--const mockActiveWizardRun = tasksActiveWizardRunRetrieve as jest.Mock-const mockRunCancel = tasksRunsCancelCreate as jest.Mock--const RUN_STARTED_AT = '2026-01-01T00:00:00Z'--const handle: CloudRunHandle = {- taskId: 'task-1',- runId: 'run-1',- startedAt: '2026-01-01T00:00:00Z',- projectId: 2,-}--// userLogic reads the bootstrapped user out of the app context, so seeding it there is how a test-// picks which kind of account is looking at the run.-function initAs(onboardingSkippedReason: OnboardingSkippedReason, team: TeamType = MOCK_DEFAULT_TEAM): void {- window.POSTHOG_APP_CONTEXT = {- ...window.POSTHOG_APP_CONTEXT,- current_user: { ...MOCK_DEFAULT_USER, onboarding_skipped_reason: onboardingSkippedReason },- } as unknown as AppContext- initKeaTests(true, team)-}--describe('activeCloudRunLogic', () => {- describe('scopedCloudRun', () => {- it.each([- // The persisted handle is browser-wide localStorage — a fresh account inheriting another- // project's run must never surface it.- ['a handle from another project', handle, 7, null],- ['a legacy handle without a projectId', { ...handle, projectId: undefined }, 2, null],- ['no current project resolved yet', handle, null, null],- ['no handle at all', null, 2, null],- ['a handle for the current project', handle, 2, handle],- ])('returns %s correctly', (_name, persisted, currentProjectId, expected) => {- expect(scopedCloudRun(persisted, currentProjectId as number | null)).toEqual(expected)- })- })-- describe('reconcileCloudRun', () => {- const serverRun = { run_id: 'run-2' }- const cases: [string, CloudRunHandle | null, { run_id: string } | null, boolean, CloudRunReconciliation][] = [- // 204: the server drops terminal and stale runs, so whatever the client holds is retired.- // Retiring works for every account, adoption does not.- ['clears a handle the server no longer reports', handle, null, false, 'clear'],- ['clears a handle for an adopting client too', handle, null, true, 'clear'],- ['keeps nothing when there is nothing to clear', null, null, false, 'keep'],- // The drop-flow signup: the run was started server-side, so this browser never had a handle.- ['adopts a server run the client never wrote', null, serverRun, true, 'adopt'],- // The endpoint is team-scoped and names no creator, so an answer to a client that cannot- // have started a run server-side may well be a teammate's run. Taking it would put their- // task titles, event plan and errors on this user's screen, behind this user's Cancel.- ['leaves a team run alone for anyone else', null, serverRun, false, 'keep'],- // The run's outcome reaches the surfaces through its stream; clearing here would drop the- // finished-run handoff before the user dismissed it.- ['keeps a terminal answer for the run it already tracks', handle, { run_id: handle.runId }, true, 'keep'],- // A held handle is never displaced, not even for the account adoption is open to.- ['keeps the local handle against a different run the team is running', handle, serverRun, true, 'keep'],- ]- it.each(cases)('%s', (_name, local, server, canAdopt, expected) => {- expect(reconcileCloudRun(local, server, canAdopt)).toBe(expected)- })- })-- describe('hydrateFromServer', () => {- let logic: ReturnType<typeof activeCloudRunLogic.build>-- beforeEach(() => {- // The handle is persisted to localStorage, so clear it or a seeded run leaks across tests.- window.localStorage.clear()- // The app context survives between tests, so reset the user or a provisioned one leaks.- initAs(null)- mockActiveWizardRun.mockReset()- projectLogic.mount()- })-- afterEach(() => {- logic?.unmount()- })-- it('seeds a run started server-side for the drop-flow signup', async () => {- // The provisioned signup is the one account whose run is started server-side, so this- // browser never wrote a handle for it and the server answer is the only way to find it.- initAs('provisioned', { ...MOCK_DEFAULT_TEAM, completed_snippet_onboarding: false })- mockActiveWizardRun.mockResolvedValue({- task_id: 'srv-task',- run_id: 'srv-run',- status: 'in_progress',- started_at: '2026-02-02T00:00:00Z',- })- logic = activeCloudRunLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions(['hydrateFromServer', 'setActiveCloudRun'])- expect(mockActiveWizardRun).toHaveBeenCalledWith(String(MOCK_TEAM_ID))- expect(logic.values.activeCloudRun).toMatchObject({- taskId: 'srv-task',- runId: 'srv-run',- projectId: MOCK_TEAM_ID,- })- })-- it('never seeds a teammate onto the team run', async () => {- // The endpoint is team-scoped and names no creator, so a member who joined mid-onboarding- // would otherwise take over whatever the team is running: its task titles, event plan and- // errors on their screen, and their Cancel button pointed at it.- initAs(null, { ...MOCK_DEFAULT_TEAM, completed_snippet_onboarding: false })- mockActiveWizardRun.mockResolvedValue({- task_id: 'srv-task',- run_id: 'srv-run',- status: 'in_progress',- started_at: '2026-02-02T00:00:00Z',- })- logic = activeCloudRunLogic()- logic.mount()- await expectLogic(logic).toFinishAllListeners()-- expect(logic.values.activeCloudRun).toBeNull()- // Nothing this member can do with the answer, so it does not cost a request either.- expect(mockActiveWizardRun).not.toHaveBeenCalled()- })-- it('spends no request on mount for a finished-onboarding team holding no handle', async () => {- // This logic is mounted app-wide, so without the gate every authenticated pageload in the- // product would cost one request to an endpoint that can only answer "nothing here".- mockActiveWizardRun.mockResolvedValue(undefined)- logic = activeCloudRunLogic()- logic.mount()- await expectLogic(logic).toFinishAllListeners()-- expect(mockActiveWizardRun).not.toHaveBeenCalled()- })-- it('reconciles a handle held by a team that already finished onboarding', async () => {- // The gate is about what a request can achieve, not about who the user is: a handle- // always needs checking, whatever the team's onboarding state.- mockActiveWizardRun.mockResolvedValue(undefined)- logic = activeCloudRunLogic()- logic.mount()- await expectLogic(logic).toFinishAllListeners()- expect(mockActiveWizardRun).not.toHaveBeenCalled()-- logic.actions.setActiveCloudRun('task-1', 'run-1', RUN_STARTED_AT, MOCK_TEAM_ID)-- await expectLogic(logic).toDispatchActions(['hydrateFromServer', 'clearActiveCloudRun'])- })-- it('reconciles again when the tab becomes visible, while a handle is held', async () => {- // Confirming the same run keeps the handle in place, so the second trigger has something- // to check.- mockActiveWizardRun.mockResolvedValue({- task_id: 'task-1',- run_id: 'run-1',- status: 'in_progress',- started_at: RUN_STARTED_AT,- })- logic = activeCloudRunLogic()- logic.mount()- logic.actions.setActiveCloudRun('task-1', 'run-1', RUN_STARTED_AT, MOCK_TEAM_ID)- await expectLogic(logic).toDispatchActions(['hydrateFromServer'])- const callsAfterMount = mockActiveWizardRun.mock.calls.length-- document.dispatchEvent(new Event('visibilitychange'))-- await expectLogic(logic).toDispatchActions(['hydrateFromServer'])- expect(mockActiveWizardRun.mock.calls.length).toBe(callsAfterMount + 1)- })-- it('spends no request on tab focus without a handle', async () => {- mockActiveWizardRun.mockResolvedValue(undefined)- logic = activeCloudRunLogic()- logic.mount()- await expectLogic(logic).toFinishAllListeners()-- document.dispatchEvent(new Event('visibilitychange'))- await expectLogic(logic).toFinishAllListeners()-- expect(mockActiveWizardRun).not.toHaveBeenCalled()- })-- it('reconciles on the interval only while a handle is held', () => {- jest.useFakeTimers()- try {- // Confirming the same run keeps the handle, so the interval has something to check.- mockActiveWizardRun.mockResolvedValue({- task_id: 'task-1',- run_id: 'run-1',- status: 'in_progress',- started_at: RUN_STARTED_AT,- })- logic = activeCloudRunLogic()- logic.mount()- const callsAfterMount = mockActiveWizardRun.mock.calls.length-- // No handle: nothing to retire, so the tick must not spend a request.- jest.advanceTimersByTime(RECONCILE_INTERVAL_MS)- expect(mockActiveWizardRun.mock.calls.length).toBe(callsAfterMount)-- logic.actions.setActiveCloudRun('task-1', 'run-1', RUN_STARTED_AT, MOCK_TEAM_ID)- const callsWithHandle = mockActiveWizardRun.mock.calls.length- jest.advanceTimersByTime(RECONCILE_INTERVAL_MS)- expect(mockActiveWizardRun.mock.calls.length).toBe(callsWithHandle + 1)- } finally {- jest.useRealTimers()- }- })-- it('does not swap a held handle for another run the team is running', async () => {- // The endpoint answers with the newest onboarding run in the project, whoever started it,- // so a teammate's run must not take over this user's surfaces (or their Cancel button).- mockActiveWizardRun.mockResolvedValue({- task_id: 'srv-task',- run_id: 'srv-run',- status: 'in_progress',- started_at: '2026-04-04T00:00:00Z',- })- logic = activeCloudRunLogic()- logic.mount()- logic.actions.setActiveCloudRun('local-task', 'local-run', '2026-03-03T00:00:00Z', MOCK_TEAM_ID)-- logic.actions.hydrateFromServer()- await expectLogic(logic).toFinishAllListeners()- expect(logic.values.activeCloudRun).toMatchObject({ taskId: 'local-task' })- })-- it('cancels the active run and recovers the button once the request settles', async () => {- // Server-side hydration confirms the same run, so it must not clear the local handle mid-test.- mockActiveWizardRun.mockResolvedValue({- task_id: 'task-1',- run_id: 'run-1',- status: 'in_progress',- started_at: '2026-01-01T00:00:00Z',- })- mockRunCancel.mockResolvedValue({ id: 'run-1', status: 'cancelled' })- logic = activeCloudRunLogic()- logic.mount()- logic.actions.setActiveCloudRun('task-1', 'run-1', '2026-01-01T00:00:00Z', MOCK_TEAM_ID)-- logic.actions.cancelActiveCloudRun()- expect(logic.values.cancellingRun).toBe(true)- await expectLogic(logic).toDispatchActions(['cancelActiveCloudRun', 'cancelActiveCloudRunSuccess'])-- expect(mockRunCancel).toHaveBeenCalledWith(String(MOCK_TEAM_ID), 'task-1', 'run-1')- // The handle stays: the run stream delivers the terminal status, and the user dismisses- // the finished run as usual. Cancelling resets so a dead stream can't strand a- // permanently disabled button (a repeat cancel is idempotent server-side).- expect(logic.values.activeCloudRun).not.toBeNull()- expect(logic.values.cancellingRun).toBe(false)- })-- it('recovers the cancel button when the cancel request fails', async () => {- mockActiveWizardRun.mockResolvedValue({- task_id: 'task-1',- run_id: 'run-1',- status: 'in_progress',- started_at: '2026-01-01T00:00:00Z',- })- mockRunCancel.mockRejectedValue(new Error('temporal unavailable'))- logic = activeCloudRunLogic()- logic.mount()- logic.actions.setActiveCloudRun('task-1', 'run-1', '2026-01-01T00:00:00Z', MOCK_TEAM_ID)-- logic.actions.cancelActiveCloudRun()- await expectLogic(logic).toDispatchActions(['cancelActiveCloudRun', 'cancelActiveCloudRunFailure'])-- // A failed cancel must not strand the button in a loading state or drop the run.- expect(logic.values.cancellingRun).toBe(false)- expect(logic.values.activeCloudRun).not.toBeNull()- })-- it('resets an in-flight cancelling state when a new run handle is set', () => {- // The flag belongs to the run it was set for; a new run (startCloudRun or server- // hydration) must start with a usable Cancel button, not one disabled by the old run.- mockActiveWizardRun.mockResolvedValue(undefined)- mockRunCancel.mockReturnValue(new Promise(() => {}))- logic = activeCloudRunLogic()- logic.mount()- logic.actions.setActiveCloudRun('task-1', 'run-1', '2026-01-01T00:00:00Z', MOCK_TEAM_ID)- logic.actions.cancelActiveCloudRun()- expect(logic.values.cancellingRun).toBe(true)-- logic.actions.setActiveCloudRun('task-2', 'run-2', '2026-01-02T00:00:00Z', MOCK_TEAM_ID)-- expect(logic.values.cancellingRun).toBe(false)- })-- it('does not call the cancel endpoint without an active handle', async () => {- mockActiveWizardRun.mockResolvedValue(undefined)- logic = activeCloudRunLogic()- logic.mount()-- logic.actions.cancelActiveCloudRun()- await expectLogic(logic).toDispatchActions(['cancelActiveCloudRun', 'cancelActiveCloudRunFailure'])-- expect(mockRunCancel).not.toHaveBeenCalled()- })-- it('clears a stale local handle when the server reports no active run', async () => {- // A returning user whose run finished or was abandoned still has a handle in localStorage.- // Reconciliation must retire it, or the install card and FAB keep claiming setup is in- // flight forever.- mockActiveWizardRun.mockResolvedValue(undefined)- logic = activeCloudRunLogic()- logic.mount()- logic.actions.setActiveCloudRun('stale-task', 'stale-run', '2026-01-01T00:00:00Z', MOCK_TEAM_ID)- expect(logic.values.activeCloudRun).not.toBeNull()-- logic.actions.hydrateFromServer()-- await expectLogic(logic).toDispatchActions(['hydrateFromServer', 'clearActiveCloudRun'])- expect(logic.values.activeCloudRun).toBeNull()- })-- it('does not let an answer about an older run retire the one just started', async () => {- // A kickoff can land while a reconcile is in flight. That answer was computed before the- // new run existed, so applying its 204 would clear a run that is only just starting.- let answer: (value: unknown) => void = () => {}- mockActiveWizardRun.mockReturnValue(- new Promise((resolve) => {- answer = resolve- })- )- logic = activeCloudRunLogic()- logic.mount()- logic.actions.setActiveCloudRun('old-task', 'old-run', '2026-01-01T00:00:00Z', MOCK_TEAM_ID)- logic.actions.hydrateFromServer()-- logic.actions.setActiveCloudRun('new-task', 'new-run', '2026-01-02T00:00:00Z', MOCK_TEAM_ID)- answer(undefined)- await expectLogic(logic).toFinishAllListeners()-- expect(logic.values.activeCloudRun).toMatchObject({ taskId: 'new-task', runId: 'new-run' })- })- })-})diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.tsdeleted file mode 100644index 95243a6c92c5..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts+++ /dev/null@@ -1,319 +0,0 @@-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'-import { subscriptions } from 'kea-subscriptions'--import { lemonToast } from '@posthog/lemon-ui'--import { projectLogic } from 'scenes/projectLogic'-import { teamLogic } from 'scenes/teamLogic'-import { userLogic } from 'scenes/userLogic'--import type { TeamType } from '~/types'--import { tasksActiveWizardRunRetrieve, tasksRunsCancelCreate } from 'products/tasks/frontend/generated/api'-import type { WizardCloudRunDTOApi } from 'products/tasks/frontend/generated/api.schemas'--import type { TeamPublicType } from '../../../../types'--export interface CloudRunHandle {- taskId: string- runId: string- /** ISO timestamp stamped at kickoff so the sync widget can show elapsed time (the cloud stream- * carries no start field). Optional: runs persisted before this field existed will not have it. */- startedAt?: string- /** Project the run belongs to. Optional: runs persisted before this field existed will not have- * it — those are treated as stale and never surfaced (see `activeCloudRun`). */- projectId?: number-}--// The persisted handle, but only when it belongs to the given project. Handles without a projectId-// predate the stamp and can't be attributed, so they're stale by definition.-export function scopedCloudRun(handle: CloudRunHandle | null, currentProjectId: number | null): CloudRunHandle | null {- return handle?.projectId != null && handle.projectId === currentProjectId ? handle : null-}--// How often the persisted handle is re-checked against the server while one is held. The run stream-// is the fast path for a run's outcome; this is the backstop for the cases where it never reports-// one (stream never opened, tab was asleep, the run was ended from somewhere else).-export const RECONCILE_INTERVAL_MS = 60 * 1000--export type CloudRunReconciliation = 'keep' | 'clear' | 'adopt'--/**- * How a server answer reconciles against the persisted handle. The server owns the "is there an- * active run" truth (it drops terminal and stale runs), so a 204 retires whatever the client holds.- * A payload naming the run we already track settles it in place: terminal or not, its outcome- * reaches the surfaces through the run stream, and clearing it here would drop the finished-run- * handoff before the user dismissed it.- *- * Nothing is ever adopted onto a client that already holds a handle, and adoption at all requires- * `canAdopt`. The endpoint is TEAM-scoped: it answers with the newest onboarding cloud run anywhere- * in the project, whoever started it, and carries no creator. So an unconditional adopt would point- * a user's progress surfaces, the wizard-session stream behind them, and their Cancel button at a- * run that is not theirs. `canAdopt` is the drop-flow signup (`isProvisionedUser`), the one account- * whose run is started server-side and therefore never had a local handle to adopt from.- */-export function reconcileCloudRun(- local: CloudRunHandle | null,- server: { run_id: string } | null,- canAdopt: boolean-): CloudRunReconciliation {- if (!local) {- return server && canAdopt ? 'adopt' : 'keep'- }- return server ? 'keep' : 'clear'-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface activeCloudRunLogicValues {- currentProjectId: number | null // projectLogic- currentTeam: TeamPublicType | TeamType | null // teamLogic- isProvisionedUser: boolean // userLogic- activeCloudRun: CloudRunHandle | null- canHydrateFromServer: boolean- cancellingRun: boolean- persistedCloudRun: CloudRunHandle | null-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface activeCloudRunLogicActions {- cancelActiveCloudRun: () => {- value: true- }- cancelActiveCloudRunFailure: () => {- value: true- }- cancelActiveCloudRunSuccess: () => {- value: true- }- clearActiveCloudRun: () => {- value: true- }- hydrateFromServer: () => {- value: true- }- setActiveCloudRun: (- taskId: string,- runId: string,- startedAt: string,- projectId: number- ) => {- projectId: number- runId: string- startedAt: string- taskId: string- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface activeCloudRunLogicMeta {- __keaTypeGenInternalSelectorTypes: {- activeCloudRun: (- persistedCloudRun: CloudRunHandle | null,- currentProjectId: number | null- ) => CloudRunHandle | null- canHydrateFromServer: (- currentProjectId: number | null,- currentTeam: TeamPublicType | TeamType | null,- activeCloudRun: CloudRunHandle | null,- isProvisionedUser: boolean- ) => boolean- }-}--export type activeCloudRunLogicType = MakeLogicType<- activeCloudRunLogicValues,- activeCloudRunLogicActions,- Record<string, any>,- activeCloudRunLogicMeta->--/**- * Holds the active cloud-run handle app-wide so the global progress FAB can keep showing a run after- * the user advances past (or unmounts) the install step. Persisted so it also survives a refresh during- * a long run. The install step writes it on kickoff; the FAB clears it on dismiss.- *- * The persisted handle lives in localStorage, which is shared across every account and project on this- * browser — so `activeCloudRun` only surfaces a handle stamped with the current project. Without that- * gate a fresh account inherits the previous account's run and greets the user with a progress widget- * for a run that isn't theirs.- *- * localStorage is also the only thing keeping the handle alive: nothing else expires it, so it is- * reconciled against the server (`hydrateFromServer`). While a handle is held that happens on mount,- * whenever the tab becomes visible, and every RECONCILE_INTERVAL_MS, whoever holds it. With no- * handle only the mount reconcile runs, and only for the drop-flow signup on a team still in- * onboarding, the one case a server answer can seed from.- */-export const activeCloudRunLogic = kea<activeCloudRunLogicType>([- path(['scenes', 'onboarding', 'activeCloudRunLogic']),- connect(() => ({- values: [projectLogic, ['currentProjectId'], teamLogic, ['currentTeam'], userLogic, ['isProvisionedUser']],- })),- actions({- setActiveCloudRun: (taskId: string, runId: string, startedAt: string, projectId: number) => ({- taskId,- runId,- startedAt,- projectId,- }),- clearActiveCloudRun: true,- // Set by the inline install-step progress view while it's mounted, so the floating FAB hides- // and the two never render the same run at once.- // Last-writer-wins boolean, not a refcount: at most ONE inline view may be mounted at a time,- // or the first unmount un-hides the FAB while the second view is still on screen.- // Reconcile the persisted handle against the server's view of the project's active wizard- // cloud run: seeds a handle the client never wrote (drop-flow signups start the run- // server-side) and retires one the server no longer reports.- hydrateFromServer: true,- // Ask the backend to cancel the active run (terminates the workflow and tears down the- // sandbox). The handle is kept: the run stream delivers the terminal `cancelled` status,- // so the surface shows the outcome and the user dismisses it like any finished run.- cancelActiveCloudRun: true,- cancelActiveCloudRunSuccess: true,- cancelActiveCloudRunFailure: true,- }),- reducers({- persistedCloudRun: [- null as CloudRunHandle | null,- { persist: true },- {- setActiveCloudRun: (_, { taskId, runId, startedAt, projectId }) => ({- taskId,- runId,- startedAt,- projectId,- }),- clearActiveCloudRun: () => null,- },- ],- // Guards the Cancel button against double-submission while the request is in flight.- // It resets on success too: the terminal status normally arrives via the stream and- // removes the button, but if the stream disconnects first, a permanently disabled- // button would strand the user — a repeat cancel is idempotent server-side. A new- // handle also resets it, since the flag belongs to the run it was set for.- cancellingRun: [- false,- {- cancelActiveCloudRun: () => true,- cancelActiveCloudRunSuccess: () => false,- cancelActiveCloudRunFailure: () => false,- clearActiveCloudRun: () => false,- setActiveCloudRun: () => false,- },- ],- }),- selectors({- activeCloudRun: [- (s) => [s.persistedCloudRun, s.currentProjectId],- (persistedCloudRun: CloudRunHandle | null, currentProjectId: number | null): CloudRunHandle | null =>- scopedCloudRun(persistedCloudRun, currentProjectId),- ],- // Whether a reconcile is worth a request, checked as inputs load rather than once on mount,- // so a run whose project resolved late still gets reconciled. This logic is mounted app-wide- // (the FAB lives in the authenticated shell), so the gate keeps the unconditional pageload- // request off the accounts it can do nothing for. A held handle always needs checking,- // whoever holds it. With no handle the only thing a request can do is seed one, which is- // only ever offered to the drop-flow signup on a team still in onboarding (see- // reconcileCloudRun for why adoption is not open to everyone), so nobody else spends one.- canHydrateFromServer: [- (s) => [s.currentProjectId, s.currentTeam, s.activeCloudRun, s.isProvisionedUser],- (- currentProjectId: number | null,- currentTeam: TeamType | null,- activeCloudRun: CloudRunHandle | null,- isProvisionedUser: boolean- ): boolean =>- currentProjectId != null &&- currentTeam != null &&- (activeCloudRun !== null || (isProvisionedUser && !currentTeam.completed_snippet_onboarding)),- ],- }),- listeners(({ actions, values }) => ({- cancelActiveCloudRun: async () => {- const handle = values.activeCloudRun- const projectId = values.currentProjectId- if (!handle || projectId == null) {- actions.cancelActiveCloudRunFailure()- return- }- try {- await tasksRunsCancelCreate(String(projectId), handle.taskId, handle.runId)- actions.cancelActiveCloudRunSuccess()- } catch {- lemonToast.error('Could not cancel the run. Please try again.')- actions.cancelActiveCloudRunFailure()- }- },- hydrateFromServer: async () => {- const projectId = values.currentProjectId- if (projectId == null) {- return- }- // The handle the answer will be about. A kickoff (or a dismiss) can land while the- // request is in flight, and the server was never asked about that run: applying a 204- // computed before it existed would retire a run the user just started.- const requestedRunId = values.activeCloudRun?.runId ?? null- try {- const response = await tasksActiveWizardRunRetrieve(String(projectId))- if ((values.activeCloudRun?.runId ?? null) !== requestedRunId) {- return- }- const server = (response as WizardCloudRunDTOApi | undefined) ?? null- const decision = reconcileCloudRun(values.activeCloudRun, server, values.isProvisionedUser)- if (decision === 'clear') {- actions.clearActiveCloudRun()- } else if (decision === 'adopt' && server) {- actions.setActiveCloudRun(- server.task_id,- server.run_id,- server.started_at ?? new Date().toISOString(),- projectId- )- }- } catch {- // Best-effort: a failed reconcile leaves the handle exactly as it was.- }- },- })),- subscriptions(({ actions }) => ({- // Fires once on mount (with the current value) and again whenever readiness changes, so- // hydration runs as soon as the project is available — not just if it happened to be ready at- // mount. hydrateFromServer is idempotent, so a no-op false value is harmless.- canHydrateFromServer: (canHydrate: boolean) => {- if (canHydrate) {- actions.hydrateFromServer()- }- },- })),- afterMount(({ actions, values, cache }) => {- // A run can finish or be cancelled while this tab sits in the background. Opting out of the- // disposables pause is what makes this fire at all: a paused listener is detached, so it- // would never hear the tab come back.- cache.disposables.add(- () => {- const onVisibilityChange = (): void => {- // Guarded like the interval below: with no handle there is nothing to retire,- // and a request per tab focus for every account in the app buys nothing the- // mount reconcile has not already covered.- if (!document.hidden && values.activeCloudRun) {- actions.hydrateFromServer()- }- }- document.addEventListener('visibilitychange', onVisibilityChange)- return () => document.removeEventListener('visibilitychange', onVisibilityChange)- },- 'reconcile-on-visible',- { pauseOnPageHidden: false }- )- // Only while a handle is held: with none there is nothing to retire, and a server-side run- // reaches the FAB through the mount reconcile anyway. The interval keeps the disposables- // pause, so a background tab does not poll.- cache.disposables.add(() => {- const timer = window.setInterval(() => {- if (values.activeCloudRun) {- actions.hydrateFromServer()- }- }, RECONCILE_INTERVAL_MS)- return () => window.clearInterval(timer)- }, 'reconcile-interval')- }),-])diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/finishedLocalRunLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/finishedLocalRunLogic.tsdeleted file mode 100644index 86814a558eed..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/finishedLocalRunLogic.ts+++ /dev/null@@ -1,163 +0,0 @@-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'--import { projectLogic } from 'scenes/projectLogic'--import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'--import { startedByFromSession } from './helpers'-import { wizardSyncUiLogic } from './wizardSyncUiLogic'--/** A terminal local wizard run, snapshotted so its handoff outlives the session stream. */-export interface FinishedLocalRunHandle {- sessionId: string- /** Project the run belongs to — the handle lives in localStorage, shared across accounts. */- projectId: number- startedAt: string- finishedAt: string- runPhase: 'completed' | 'error'- tasks: { id: string; title: string; status: string }[]- error: { message?: string } | null- startedBy?: { name: string; email: string } | null- /** The run's markdown handoff doc, kept so the doc dialog outlives the stream too. */- handoffText?: string | null-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface finishedLocalRunLogicValues {- currentProjectId: number | null // projectLogic- dismissedSessionId: string | null- finishedLocalRun: FinishedLocalRunHandle | null- persistedFinishedLocalRun: FinishedLocalRunHandle | null-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface finishedLocalRunLogicActions {- handoffDocReceived: (doc: { key: string; startedByEmail: string | null; text: string }) => {- key: string- startedByEmail: string | null- text: string- } // wizardSyncUiLogic- dismissLocalRun: (sessionId: string) => {- sessionId: string- }- recordFinishedLocalRun: (session: WizardSessionDTOApi) => {- session: WizardSessionDTOApi- }- setFinishedLocalRun: (handle: FinishedLocalRunHandle) => {- handle: FinishedLocalRunHandle- }- supersedeFinishedLocalRun: (sessionId: string) => {- sessionId: string- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface finishedLocalRunLogicMeta {- __keaTypeGenInternalSelectorTypes: {- finishedLocalRun: (- persistedFinishedLocalRun: FinishedLocalRunHandle | null,- currentProjectId: number | null- ) => FinishedLocalRunHandle | null- }-}--export type finishedLocalRunLogicType = MakeLogicType<- finishedLocalRunLogicValues,- finishedLocalRunLogicActions,- Record<string, any>,- finishedLocalRunLogicMeta->--/**- * Keeps a finished local wizard run on screen until the user dismisses it. The live session stream- * gates itself off shortly after a run goes terminal (INC-886), which used to take the FAB down with- * it — dismissing the handoff surface is the user's call, not a timer's. Written by the Installation- * layer's local bookkeeping the moment a watched run turns terminal; persisted so a reload doesn't- * eat the handoff; superseded silently when a new local run starts.- */-export const finishedLocalRunLogic = kea<finishedLocalRunLogicType>([- path(['scenes', 'onboarding', 'finishedLocalRunLogic']),- connect(() => ({- values: [projectLogic, ['currentProjectId']],- actions: [wizardSyncUiLogic, ['handoffDocReceived']],- })),- actions({- recordFinishedLocalRun: (session: WizardSessionDTOApi) => ({ session }),- setFinishedLocalRun: (handle: FinishedLocalRunHandle) => ({ handle }),- // A different local run went live — the previous run's handoff is superseded, not dismissed- // (no telemetry; mirrors setActiveCloudRun overwriting the previous cloud handle).- supersedeFinishedLocalRun: (sessionId: string) => ({ sessionId }),- // The user's explicit dismissal — the only path that removes a finished run without a- // replacement. Remembered so an SSE redelivery of the same terminal session can't resurrect- // the surface.- dismissLocalRun: (sessionId: string) => ({ sessionId }),- }),- reducers({- persistedFinishedLocalRun: [- null as FinishedLocalRunHandle | null,- { persist: true },- {- setFinishedLocalRun: (_, { handle }) => handle,- supersedeFinishedLocalRun: (state, { sessionId }) =>- state && state.sessionId !== sessionId ? null : state,- dismissLocalRun: (state, { sessionId }) => (state?.sessionId === sessionId ? null : state),- },- ],- dismissedSessionId: [- null as string | null,- { persist: true },- {- dismissLocalRun: (_, { sessionId }) => sessionId,- },- ],- }),- selectors({- finishedLocalRun: [- (s) => [s.persistedFinishedLocalRun, s.currentProjectId],- (- persistedFinishedLocalRun: FinishedLocalRunHandle | null,- currentProjectId: number | null- ): FinishedLocalRunHandle | null =>- persistedFinishedLocalRun && persistedFinishedLocalRun.projectId === currentProjectId- ? persistedFinishedLocalRun- : null,- ],- }),- listeners(({ actions, values }) => ({- recordFinishedLocalRun: ({ session }) => {- const isTerminal = session.run_phase === 'completed' || session.run_phase === 'error'- if (!isTerminal || session.session_id === values.dismissedSessionId) {- return- }- const projectId = values.currentProjectId- if (projectId === null) {- return- }- actions.setFinishedLocalRun({- sessionId: session.session_id,- projectId,- startedAt: session.started_at,- finishedAt: session.updated_at,- runPhase: session.run_phase === 'error' ? 'error' : 'completed',- tasks: (session.tasks ?? []).map((t) => ({ id: t.id, title: t.title, status: t.status })),- error: (session.error as { message?: string } | null) ?? null,- startedBy: startedByFromSession(session),- handoffText: session.handoff_text ?? null,- })- },- })),- afterMount(({ actions, values }) => {- // A handle restored from a previous pageload may carry a doc the user never saw (the run- // finished after they left) — announce it so the one-time auto-open can still happen. The- // live path's announcements come from the Installation layer's session bookkeeping instead.- // Completed only, mirroring that path: the reopen buttons don't exist on errored runs.- const handle = values.finishedLocalRun- if (handle?.runPhase === 'completed' && handle.handoffText) {- actions.handoffDocReceived({- key: handle.sessionId,- text: handle.handoffText,- startedByEmail: handle.startedBy?.email ?? null,- })- }- }),-])diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.test.tsdeleted file mode 100644index fc4822a81a17..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.test.ts+++ /dev/null@@ -1,152 +0,0 @@-import {- activeStep,- currentTaskLabel,- elapsedLabel,- formatElapsed,- isRunStale,- isStreamLost,- pendingQuestionLabel,- prName,- STALE_RUN_MAX_AGE_MS,- STALE_RUN_SILENCE_MS,-} from './helpers'-import type { InstallationProgress, InstallationStep } from './installationProgressLogic'-import type { TaskRunConnectionStatus } from './taskRunStreamLogic'--const NOW = new Date('2026-01-01T12:00:00Z').getTime()-const iso = (msBeforeNow: number): string => new Date(NOW - msBeforeNow).toISOString()--describe('wizard-sync helpers', () => {- it.each([- ['m:ss under an hour', 125, '2:05'],- ['h:mm:ss past the hour', 3725, '1:02:05'],- ['clamps negatives to zero', -10, '0:00'],- // The clock is driven by a persisted handle that outlives the run it names, so a run nobody- // settled would otherwise count up for as long as the browser keeps the handle.- ['clamps a runaway clock to the display cap', 42 * 3600, '6:00:00+'],- ])('formatElapsed %s', (_name, seconds, expected) => {- expect(formatElapsed(seconds)).toBe(expected)- })-- it('elapsedLabel replaces a stale run clock with the reason it stopped mattering', () => {- expect(elapsedLabel(125, false)).toBe('2:05')- expect(elapsedLabel(125, true)).toBe('Stalled')- })-- describe('isRunStale', () => {- it.each([- ['a run that just reported', iso(60_000), NOW - 60_000, true, false],- [- 'a run silent past the window with no stream left',- iso(60 * 60_000),- NOW - STALE_RUN_SILENCE_MS - 1000,- true,- true,- ],- // The long agent phase and the 15 minute CI follow-up sleep both publish nothing. A run- // whose stream is up is being watched, however little it has to say.- [- 'a run silent past the window on a live stream',- iso(60 * 60_000),- NOW - STALE_RUN_SILENCE_MS - 1000,- false,- false,- ],- // No activity at all: the kickoff stamp is what the silence is measured from.- ['a run that never reported, still inside the window', iso(60_000), null, true, false],- ['a run that never reported, past the window', iso(STALE_RUN_SILENCE_MS + 1000), null, true, true],- // The age cap is the second gate: a handle this old outlived a full day of reloads, so it- // stands whatever the transport is doing.- ['a fresh report on a day-old handle', iso(STALE_RUN_MAX_AGE_MS + 1000), NOW - 1000, false, true],- // A legacy handle carries no kickoff stamp, so neither gate has anything to measure.- ['a handle with no startedAt and no activity', undefined, null, true, false],- ])('%s', (_name, startedAt, lastActivityAt, streamLost, expected) => {- expect(isRunStale(startedAt, lastActivityAt, streamLost, NOW)).toBe(expected)- })- })-- describe('isStreamLost', () => {- const cases: [string, TaskRunConnectionStatus, boolean, boolean][] = [- ['an open stream is carrying updates', 'open', false, false],- // Every mount of a long-lived run starts here, and so does every reconnect. Calling these- // lost would stale a healthy run for the length of a connect and offer to dismiss it.- ['a stream still connecting has not failed yet', 'connecting', false, false],- ['a stream not yet started has not failed yet', 'idle', false, false],- ['a failed stream is lost', 'error', false, true],- ['a closed stream is lost', 'closed', false, true],- // The stream that never gets past connecting: the run logic gives up after its own- // window and says so here, so a permanently connecting stream is still reachable.- ['a stream the logic gave up on is lost whatever it reports', 'connecting', true, true],- ]- it.each(cases)('%s', (_name, status, isStalled, expected) => {- expect(isStreamLost(status, isStalled)).toBe(expected)- })- })-- it('activeStep prefers the wizard sub-step over the pipeline stage containing it', () => {- // The card headline would otherwise read "Running setup wizard" while the wizard is- // reporting something more specific like "Install SDK".- const stage: InstallationStep = {- id: 'setup:wizard',- label: 'Running setup wizard',- status: 'in_progress',- detail: null,- }- const sub: InstallationStep = {- id: 'wizard-task:a',- label: 'Install SDK',- status: 'in_progress',- detail: null,- source: 'wizard',- }- expect(activeStep([stage, sub])?.label).toBe('Install SDK')- expect(activeStep([stage])?.label).toBe('Running setup wizard')- expect(activeStep([])).toBeNull()- })-- // The PR CTA interpolates this into the button label — a bad parse would render- // "Review null" or leak a mangled identifier instead of falling back to "Review PR".- it.each([- ['https://github.com/acme-co/web/pull/42', 'acme-co/web#42'],- ['https://github.com/acme-co/web/pull/42/files', 'acme-co/web#42'],- ['https://github.com/acme-co/web/pull/42?diff=split', 'acme-co/web#42'],- ['https://github.example.com/acme-co/web/pull/7', 'acme-co/web#7'],- ['https://gitlab.com/acme-co/web/-/merge_requests/42', null],- ['https://github.com/acme-co/web', null],- ['not a url', null],- ])('prName(%s) → %s', (url, expected) => {- expect(prName(url)).toBe(expected)- })-- describe('a pending question', () => {- const withQuestion = (prompts: string[], sensitive = false): InstallationProgress =>- ({- phase: 'running',- steps: [{ id: '1', label: 'Install the SDK', status: 'in_progress', detail: null }],- error: null,- prUrl: null,- prMerged: false,- isCurrent: true,- pendingInput: { id: 'ask-1', askedAt: iso(0), questionCount: 1, sensitive, prompts },- }) as InstallationProgress-- // The user is looking at the app, not the terminal, so the prominent line has to be the- // instruction to go back there. Leading with the question buried that.- it('leads with the call to action, not the question', () => {- const progress = withQuestion(['Which region is your project in?'])- expect(currentTaskLabel(progress)).toBe('Your terminal needs your attention')- expect(currentTaskLabel(progress)).not.toContain('region')- })-- it('carries the question separately, so it can render below the call to action', () => {- expect(pendingQuestionLabel(withQuestion(['Which region is your project in?']))).toBe(- 'Which region is your project in?'- )- })-- it('has no question to show for a sensitive ask', () => {- expect(pendingQuestionLabel(withQuestion([], true))).toBeNull()- expect(currentTaskLabel(withQuestion([], true))).toBe('Your terminal needs your attention')- })- })-})diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.tsdeleted file mode 100644index 84cfd0110b9d..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.ts+++ /dev/null@@ -1,217 +0,0 @@-import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'--import type { InstallationProgress, InstallationStep, InstallationStepStatus } from './installationProgressLogic'-import type { TaskRunConnectionStatus } from './taskRunStreamLogic'--// Prefer a real name; fall back to email so we never render a blank attribution.-export function startedByFromSession(session: WizardSessionDTOApi | null): { name: string; email: string } | null {- const createdBy = session?.created_by- if (!createdBy) {- return null- }- return { name: createdBy.first_name || createdBy.email, email: createdBy.email }-}--export function sessionErrorMessage(session: WizardSessionDTOApi | null): string | undefined {- return (session?.error as { message?: string } | null)?.message-}--// Ceiling on the displayed elapsed time. The clock is driven by a persisted handle that outlives the-// run it names, so without a cap a run nobody ever settled counts up for as long as the browser keeps-// the handle. Display only: telemetry keeps the true elapsed.-export const MAX_DISPLAY_ELAPSED_SECONDS = 6 * 60 * 60--// "m:ss", or "h:mm:ss" once a run passes the hour mark (cloud runs can be long). Anything past the-// display cap reads as the cap with a trailing "+".-export function formatElapsed(totalSeconds: number): string {- const raw = Math.max(0, Math.floor(totalSeconds))- const s = Math.min(MAX_DISPLAY_ELAPSED_SECONDS, raw)- const hours = Math.floor(s / 3600)- const minutes = Math.floor((s % 3600) / 60)- const seconds = s % 60- const ss = seconds.toString().padStart(2, '0')- const clamped = raw > s ? '+' : ''- if (hours > 0) {- return `${hours}:${minutes.toString().padStart(2, '0')}:${ss}${clamped}`- }- return `${minutes}:${ss}${clamped}`-}--// Silence alone says nothing about a cloud run: the pipeline is designed to go quiet for long-// stretches, publishing nothing between the agent starting and the PR opening, and its CI follow-up-// loop sleeps a quarter hour at a time. So the silence window only counts while the stream that-// would carry those updates is down, and it is set wider than the longest designed quiet period.-// The age cap is the second, independent gate, for a handle that survived a day of reloads without-// its run ever settling.-export const STALE_RUN_SILENCE_MS = 30 * 60 * 1000-export const STALE_RUN_MAX_AGE_MS = 24 * 60 * 60 * 1000--/**- * Whether the transport that would carry a run's updates is down, which is what turns silence into- * evidence. `idle` and `connecting` are the states every stream passes through before it has had a- * chance to say anything, including on each mount of a run that is already hours old and on every- * reconnect in between: counting them would call a healthy long run stale for the length of a- * connect, and offer a dismiss that orphans it. A stream that never gets past them is still caught,- * by `isStalled`, which the run logic sets once it gives up.- */-export function isStreamLost(status: TaskRunConnectionStatus, isStalled: boolean): boolean {- return isStalled || status === 'error' || status === 'closed'-}--/**- * Whether a still-running run has gone stale, meaning its surfaces should offer a dismiss instead of- * only a minimize. `lastActivityAt` is when the stream last delivered anything (null when it never- * has, in which case the handle's kickoff stamp stands in), and `streamLost` says whether the- * transport that would deliver more is down right now. The stamp is a client clock and the silence- * window is wide enough to absorb the skew against it.- */-export function isRunStale(- startedAt: string | undefined,- lastActivityAt: number | null,- streamLost: boolean,- now: number-): boolean {- const startedMs = startedAt ? new Date(startedAt).getTime() : NaN- if (!Number.isNaN(startedMs) && now - startedMs > STALE_RUN_MAX_AGE_MS) {- return true- }- if (!streamLost) {- return false- }- const silentSince = lastActivityAt ?? startedMs- return !Number.isNaN(silentSince) && now - silentSince > STALE_RUN_SILENCE_MS-}--// What the widgets print where the elapsed clock goes. A stale run's clock is meaningless, so it is-// replaced by the reason it stopped mattering.-export function elapsedLabel(elapsedSeconds: number, stale: boolean = false): string {- return stale ? 'Stalled' : formatElapsed(elapsedSeconds)-}--// The short status line shown in the collapsed card header.-export function syncHeadline(progress: InstallationProgress): string {- if (progress.phase === 'completed') {- return 'PostHog is set up'- }- if (progress.phase === 'error') {- return progress.error?.title ?? 'Setup hit a snag'- }- if (progress.prMerged) {- return 'Pull request merged'- }- if (progress.prUrl) {- return 'Pull request ready'- }- if (progress.pendingInput) {- return 'Waiting for your answer'- }- if (progress.phase === 'connecting') {- return 'Getting ready'- }- return 'Setting up PostHog'-}--export function activeStep(steps: InstallationStep[]): InstallationStep | null {- const inProgress = steps.filter((s) => s.status === 'in_progress')- // Prefer the wizard's own sub-step over the pipeline stage that contains it — "Installing the- // SDK" says more than "Running setup wizard" when both are in flight.- return inProgress.find((s) => s.source === 'wizard') ?? inProgress[0] ?? null-}--// The prominent line: the active step's live detail (the wizard's current sub-task) when present,-// otherwise the step label. This is what gives the wizard's own work top billing in the card.-export function currentTaskLabel(progress: InstallationProgress): string | null {- if (progress.phase === 'error') {- return progress.error?.detail ?? 'Something stopped the run'- }- if (progress.prMerged) {- return 'PR merged, congratulations!'- }- if (progress.phase === 'completed') {- return progress.prUrl ? 'Pull request is ready to review' : 'Everything is wired up'- }- if (progress.pendingInput) {- // The run is blocked and the user is usually looking at the app, not the terminal, so the- // prominent line is the call to go back there. The question itself is secondary, since- // knowing there is one is what unblocks the run.- return 'Your terminal needs your attention'- }- const step = activeStep(progress.steps)- if (step) {- return step.detail ?? step.label- }- return progress.phase === 'connecting' ? 'Connecting to your run' : 'Getting things ready'-}--/**- * The pending question, shown below the call to action rather than in place of it. Null when nothing- * is pending and for sensitive asks, which publish no prompt text at all.- */-export function pendingQuestionLabel(progress: InstallationProgress): string | null {- return progress.pendingInput?.prompts[0] ?? null-}--export function stepCounts(steps: InstallationStep[]): { completed: number; total: number } {- return {- completed: steps.filter((s) => s.status === 'completed').length,- total: steps.length,- }-}--// "owner/repo#123" from a GitHub-style PR url, or null when it doesn't parse (self-hosted forges,-// unexpected shapes) — callers fall back to a generic label. The name makes the CTA concrete: the-// user may have kicked off runs against more than one repo, and "Review PR" doesn't say which.-export function prName(url: string): string | null {- const match = url.match(/^https?:\/\/[^/]+\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[/?#]|$)/)- return match ? `${match[1]}/${match[2]}#${match[3]}` : null-}--// The review CTA's label, shared by the inline view and the sync card.-export function prNameLabel(prUrl: string): string {- const name = prName(prUrl)- return name ? `Review ${name}` : 'Review PR'-}--// Accent tone for the whole widget, driven by phase. One accent plus the two terminal colors keeps it-// colorful without going loud.-export function toneTextClass(progress: InstallationProgress): string {- if (progress.phase === 'completed') {- return 'text-success'- }- if (progress.phase === 'error') {- return 'text-danger'- }- if (progress.pendingInput) {- return 'text-warning'- }- return 'text-accent'-}--// Fill color for a single progress pip, one per step.-export function pipClass(status: InstallationStepStatus): string {- switch (status) {- case 'completed':- return 'bg-success'- case 'in_progress':- return 'bg-accent animate-pulse'- case 'failed':- return 'bg-danger'- default:- return 'bg-border'- }-}--export function localModeLabel(startedByLabel?: string | null): string {- return startedByLabel ? `On ${startedByLabel}'s machine` : 'On your machine'-}--/** The teammate's name, or null for the viewer's own run (matched on email) or an unknown initiator. */-export function resolveStartedByLabel(- startedBy: InstallationProgress['startedBy'],- currentUserEmail: string | undefined-): string | null {- if (!startedBy || startedBy.email === currentUserEmail) {- return null- }- return startedBy.name-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/hooks.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/hooks.tsdeleted file mode 100644index f812dd466212..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/hooks.ts+++ /dev/null@@ -1,112 +0,0 @@-import { useActions, useMountedLogic, useValues } from 'kea'-import type React from 'react'-import { useEffect, useRef, useState } from 'react'--import { useHogfetti } from 'lib/components/Hogfetti/Hogfetti'-import { elapsedSecondsFrom } from 'lib/utils/datetime'-import { inStorybookTestRunner } from 'lib/utils/dom'--import { installationProgressLogic } from './installationProgressLogic'-import { wizardActiveSessionDetectorLogic, watchWorkflowWhileMounted } from './wizardActiveSessionDetectorLogic'-import { SELF_DRIVING_WORKFLOW_ID } from './workflows'--// 1Hz clock for the elapsed timer, scoped to a mounted run so nothing ticks when no run is active.-// `frozen` stops the interval entirely — a finished run shows its fixed duration, so ticking for it-// would be pure re-render churn.-export function useNow(frozen: boolean = false): number {- const [now, setNow] = useState(() => Date.now())- useEffect(() => {- if (frozen) {- return- }- const id = window.setInterval(() => setNow(Date.now()), 1000)- return () => window.clearInterval(id)- }, [frozen])- return now-}--/** Seconds a run has been going: live-ticking until `endedAt` is known, then frozen at the final- * duration. Returns 0 until `startedAt` exists. */-export function useRunElapsedSeconds(startedAt: string | null | undefined, endedAt?: string | null): number {- const endMs = endedAt ? new Date(endedAt).getTime() : NaN- const now = useNow(!Number.isNaN(endMs))- return startedAt ? elapsedSecondsFrom(startedAt, Number.isNaN(endMs) ? now : endMs) : 0-}--/**- * Whether a self-driving wizard run is going right now, for surfaces the run sends the user to- * mid-flight (the GitHub connect round trip) that need to hand them back to their terminal.- * Answers only for the self-driving program — an SDK-install run in flight returns false; ask the- * detector's `activeWorkflowId` directly for the any-program question.- *- * Registers the program with the detector while mounted rather than relying on the onboarding- * variant flag, because the wizard is also run standalone against accounts that are long past- * onboarding — those users would otherwise never be watched.- */-export function useSelfDrivingRunInFlight(): boolean {- return useSelfDrivingRunState().inFlight-}--/**- * The same question as `useSelfDrivingRunInFlight`, plus whether the detector has actually answered- * it. Callers whose wrong branch is costly — sending someone into the app mid-run — need the- * difference: `inFlight === false` is "no run" only once `resolved` is true, and before that it just- * means nobody has polled yet. The detector's first poll is jittered up to 30s, so that window is- * long enough to matter, which is why mounting here also asks for a targeted check.- */-export function useSelfDrivingRunState(): { inFlight: boolean; resolved: boolean } {- useMountedLogic(wizardActiveSessionDetectorLogic)- const { activeWorkflowId, hasResolvedSessionState } = useValues(wizardActiveSessionDetectorLogic)- const { check } = useActions(wizardActiveSessionDetectorLogic)-- useEffect(() => watchWorkflowWhileMounted(SELF_DRIVING_WORKFLOW_ID), [])- useEffect(() => {- if (!hasResolvedSessionState) {- check()- }- // Mount-only: a later unresolved state means a poll is already in flight or scheduled.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [])-- return { inFlight: activeWorkflowId === SELF_DRIVING_WORKFLOW_ID, resolved: hasResolvedSessionState }-}--/**- * Whether a local wizard run should take over the install step: a session exists on the stream AND it- * has been observed fresh (stale terminal rows from previous runs don't count). Mounts the local- * Installation layer — and with it the wizard session stream — so use it only where the takeover can- * actually render (the sync-enabled install steps).- */-export function useLocalWizardRunActive(workflowId?: string): boolean {- const { installationProgress } = useValues(installationProgressLogic({ mode: 'local', workflowId }))- return installationProgress.isCurrent-}--export function canCelebrate(): boolean {- return !inStorybookTestRunner() && !window.matchMedia('(prefers-reduced-motion: reduce)').matches-}--/**- * Hogfetti for a PR merged while the user is watching, exactly once per mount. Gated on the live- * false → true transition: starts null so the first hydrated state (SSE replay / poll snapshot- * arrives async after mount) arms the detector instead of reading as a transition — otherwise every- * reload of a merged run re-fires. Quiet in the storybook test runner and under reduced motion.- */-export function useMergeCelebration(prMerged: boolean): { CelebrationComponent: React.FC } {- const { trigger: triggerHogfetti, HogfettiComponent } = useHogfetti()- const prevMergedRef = useRef<boolean | null>(null)- const mergeCelebratedRef = useRef(false)- useEffect(() => {- const prev = prevMergedRef.current- prevMergedRef.current = prMerged- if (prev === null || prev || !prMerged || mergeCelebratedRef.current) {- return- }- if (!canCelebrate()) {- return- }- mergeCelebratedRef.current = true- triggerHogfetti()- }, [prMerged, triggerHogfetti])- return { CelebrationComponent: HogfettiComponent }-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgress.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgress.tsdeleted file mode 100644index b49403cc9790..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgress.ts+++ /dev/null@@ -1,370 +0,0 @@-import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'--import type { FinishedLocalRunHandle } from './finishedLocalRunLogic'-import { sessionErrorMessage, startedByFromSession } from './helpers'-import type {- InstallationError,- InstallationErrorKind,- InstallationPhase,- InstallationProgress,- InstallationStep,- InstallationStepStatus,- WizardPendingInput,-} from './installationProgressLogic'-import { taskRunPrMerged, taskRunPrUrl, TaskRunProgressStep, TaskRunStreamState } from './taskRunStreamLogic'--/**- * Pure builders that turn the raw streams (TaskRun pipeline, wizard session) into the one normalized- * `InstallationProgress` the UI renders. No kea, no I/O — `installationProgressLogic` wires these to- * its connected values, and the tests exercise them directly.- */--// A session counts as "current" if it was updated within the last 10 minutes. Lets the install step-// ignore stale terminal sessions left over from previous runs / test data when a user lands on the-// app, while still re-surfacing recently-completed runs after a quick navigation away and back.-const SESSION_CURRENT_THRESHOLD_MS = 10 * 60 * 1000--export function isSessionFresh(session: WizardSessionDTOApi, now: number): boolean {- const updatedAt = new Date(session.updated_at).getTime()- return !Number.isNaN(updatedAt) && now - updatedAt < SESSION_CURRENT_THRESHOLD_MS-}--// Tolerance for the sandbox clock minting `started_at` slightly behind our kickoff stamp.-const RUN_SESSION_SKEW_MS = 5 * 60 * 1000--// Whether a session belongs to this cloud run: it started inside the run's own window. Used for-// the handoff doc, which must outlive the recency gate — the wizard stage ends hours before the-// pipeline does, so by completion the session is long past `isSessionFresh`, yet its doc is still-// this run's report. A session from a previous run keeps failing this check by starting earlier.-export function isSessionFromRun(session: WizardSessionDTOApi, runStartedAt: string): boolean {- const sessionStart = new Date(session.started_at).getTime()- const runStart = new Date(runStartedAt).getTime()- return !Number.isNaN(sessionStart) && !Number.isNaN(runStart) && sessionStart >= runStart - RUN_SESSION_SKEW_MS-}--// A dead wizard can't clear its own prompt (the clearing push never arrives), so the attention state-// must go quiet with the session: gated on the server's staleness verdict and a live (running) phase.-export function pendingInputFromSession(session: WizardSessionDTOApi | null): WizardPendingInput | null {- if (!session || session.is_stale || session.run_phase !== 'running') {- return null- }- const raw = session.pending_input- if (!raw?.id) {- return null- }- // The prompt text goes straight into JSX, and the type is the serializer's promise rather than a- // runtime guarantee, so keep non-strings out: a row written before the field was typed would- // otherwise crash the render of an app-wide widget.- const prompts = Array.isArray(raw.prompts) ? raw.prompts.filter((p): p is string => typeof p === 'string') : []- return {- id: raw.id,- askedAt: raw.asked_at ?? session.updated_at,- questionCount: raw.question_count ?? 1,- sensitive: raw.sensitive === true,- prompts: raw.sensitive === true ? [] : prompts,- }-}--// The AI gateway refuses with a 402 when the run's token cap or the org's quota runs out. The wizard-// forwards the raw gateway JSON, which tells the user nothing, so replace it with a next step.-const USAGE_LIMIT_ERROR_REGEX = /\b(?:token_cap_exceeded|insufficient_quota)\b/i--export function errorKindFromMessage(message?: string | null): InstallationErrorKind | null {- return message && USAGE_LIMIT_ERROR_REGEX.test(message) ? 'usage_limit' : null-}--function runError(title: string, detail?: string | null): InstallationError {- if (errorKindFromMessage(detail) === 'usage_limit') {- return {- title: 'AI usage limit reached',- detail: 'The setup agent ran out of AI usage before it finished. Your own coding agent can finish the setup from our docs.',- kind: 'usage_limit',- }- }- return { title, detail: detail ?? null }-}--const STEP_STATUSES: Record<string, InstallationStepStatus> = {- pending: 'pending',- in_progress: 'in_progress',- completed: 'completed',- failed: 'failed',- canceled: 'failed',-}--// The stages every cloud run walks, in order — the timeline's fixed plan. Labels match the-// connecting preview (UPCOMING_STEPS) so the handoff between the two is seamless; announced steps-// override them with the backend's own labels.-const CLOUD_PIPELINE_SKELETON: { group: string; step: string; label: string }[] = [- { group: 'setup', step: 'sandbox', label: 'Setting up sandbox' },- { group: 'setup', step: 'clone', label: 'Cloning repository' },- { group: 'setup', step: 'wizard', label: 'Running setup wizard' },- { group: 'deliver', step: 'pr', label: 'Opening a pull request' },-]--function stepStatus(raw: string): InstallationStepStatus {- return STEP_STATUSES[raw] ?? 'pending'-}--// Cloud: the TaskRun is the spine (phase, steps, PR url, terminal error); the wizard session's own-// tasks expand into the timeline as wizard-sourced steps nested after the pipeline's wizard stage-// (absent while the cloud wizard hasn't reported yet — degrades to the bare TaskRun pipeline).-export function cloudProgress(- taskRunState: TaskRunStreamState | null,- progressSteps: TaskRunProgressStep[],- taskConnectionStatus: string,- latestSession: WizardSessionDTOApi | null,- isStalled: boolean = false,- now: number = Date.now(),- /** When this run kicked off (from the persisted handle) — scopes the handoff doc to the run. */- runStartedAt: string | null = null-): InstallationProgress {- let phase: InstallationPhase- let stalledError: InstallationError | null = null- if (!taskRunState && isStalled) {- // The stream never delivered any run state (deleted or access-revoked run, a stream that- // stayed silent past taskRunStreamLogic's no-state window). `idle` renders as a spinner with- // no way out, so surface the dead end: the error phase carries the retry CTAs and the- // dismiss control.- phase = 'error'- stalledError = {- title: 'Setup lost contact',- detail: 'We stopped hearing back from this run. Run the wizard yourself, or dismiss it and start over.',- }- } else if (!taskRunState) {- phase = taskConnectionStatus === 'connecting' ? 'connecting' : 'idle'- } else if (taskRunState.status === 'queued' && isStalled) {- // The run never left the queue (see taskRunStreamLogic's stall timer) — nothing is actually- // running, so an eternal spinner would be a lie.- phase = 'error'- stalledError = {- title: "Setup hasn't started",- detail: 'The run has been queued for a while without starting. Please try again in a bit.',- }- } else if (taskRunState.status === 'completed') {- phase = 'completed'- } else if (taskRunState.status === 'failed' || taskRunState.status === 'cancelled') {- phase = 'error'- } else if (taskRunState.status === 'queued') {- // Queued means nothing has started yet — "getting ready", not "running".- phase = 'connecting'- } else {- phase = 'running'- }-- // A completed run has nothing in flight: clamp a lingering in-progress step (e.g. "Keeping- // CI green", emitted in-progress when the PR opened) to completed so the timeline matches.- const clamp = (status: InstallationStepStatus): InstallationStepStatus =>- phase === 'completed' && status === 'in_progress' ? 'completed' : status-- // 'Started agent' is internal plumbing — it tells the user nothing about their setup. Hide it;- // the pending "Opening a pull request" row (flipped in-progress below) narrates that window.- const announced = progressSteps.filter((p) => p.step !== 'agent')- const mapStep = (p: TaskRunProgressStep): InstallationStep => ({- id: `${p.group}:${p.step}`,- label: p.label,- status: clamp(stepStatus(p.status)),- // The "pr" step carries the PR url in `detail` (surfaced as the CTA, not as raw step text).- detail: p.step === 'pr' ? null : p.detail,- })- // Every cloud run walks the same pipeline, so the whole plan is visible from the start as- // pending rows — announced steps light their slot up in place (keeping the backend's label and- // detail), and anything outside the skeleton (e.g. "Keeping CI green") appends in arrival- // order. Skipped when no run state exists yet: the view's connecting preview owns that window.- let pipelineSteps: InstallationStep[]- if (taskRunState) {- const byName = new Map(announced.map((p) => [p.step, p]))- pipelineSteps = CLOUD_PIPELINE_SKELETON.map((sk) => {- const real = byName.get(sk.step)- return real- ? mapStep(real)- : { id: `${sk.group}:${sk.step}`, label: sk.label, status: 'pending' as const, detail: null }- })- const skeletonNames = new Set(CLOUD_PIPELINE_SKELETON.map((sk) => sk.step))- pipelineSteps.push(...announced.filter((p) => !skeletonNames.has(p.step)).map(mapStep))- } else {- pipelineSteps = announced.map(mapStep)- }-- // The session stream is keyed by workflow only and replays the latest session on connect even- // when it's a stale terminal row from a previous (possibly local) run — apply the same freshness- // gate the local path uses before letting it near this run's timeline or error detail. A fresh- // unrelated session can still slip in (the cloud wizard posts to the same workflow by design).- const session = latestSession && isSessionFresh(latestSession, now) ? latestSession : null-- // The cloud wizard reports its own sub-steps on the session stream — once they exist they- // REPLACE the pipeline's aggregate "wizard" stage in the timeline (the tasks are that stage,- // told in more detail). Until then the stage row stands in. When the stage hasn't been- // announced at all (e.g. polling mode where step notifications are stream-borne), slot the- // tasks before the first not-yet-completed pipeline step so in-flight wizard work never- // renders after the PR stage.- const wizardSteps: InstallationStep[] = (session?.tasks ?? []).map((t) => ({- id: `wizard-task:${t.id}`,- label: t.title,- status: clamp(stepStatus(t.status)),- detail: null,- source: 'wizard',- }))- const wizardStageIndex = pipelineSteps.findIndex((s) => s.id.endsWith(':wizard'))- let steps: InstallationStep[]- if (wizardStageIndex !== -1 && wizardSteps.length > 0) {- steps = [- ...pipelineSteps.slice(0, wizardStageIndex),- ...wizardSteps,- ...pipelineSteps.slice(wizardStageIndex + 1),- ]- } else if (wizardSteps.length > 0) {- const firstUnfinished = pipelineSteps.findIndex((s) => s.status !== 'completed')- const insertIndex = firstUnfinished === -1 ? pipelineSteps.length : firstUnfinished- steps = [...pipelineSteps.slice(0, insertIndex), ...wizardSteps, ...pipelineSteps.slice(insertIndex)]- } else {- steps = pipelineSteps- }-- const prUrl = taskRunPrUrl(taskRunState, progressSteps)- const prMerged = taskRunPrMerged(taskRunState)-- // A merged PR ends the story: the CI-babysitting row would otherwise keep spinning forever- // (the workflow's follow-up loop skips closed PRs, so nothing will ever complete it).- if (prMerged) {- steps = steps.filter((s) => !s.id.endsWith(':ci'))- }-- // The pipeline goes quiet between agent start and the PR opening: everything reads completed- // while the agent is still writing code, committing, and drafting the PR — which looks stalled.- // Flip the still-pending PR slot to in-progress with an honest detail line for that window; the- // real deliver-stage step replaces it when it arrives.- const allDoneExceptPr = steps.every((s) => s.id.endsWith(':pr') || s.status === 'completed')- if (phase === 'running' && !prUrl && allDoneExceptPr) {- steps = steps.map((s) =>- s.id.endsWith(':pr') && s.status === 'pending'- ? {- ...s,- status: 'in_progress' as const,- detail: 'The agent is committing its changes and drafting the PR',- }- : s- )- }-- const error =- phase === 'error'- ? (stalledError ??- runError(- // A cancelled run is a deliberate stop (Cancel button or closing the setup PR),- // not a broken installation — presenting it as a failure reads as a bug.- taskRunState?.status === 'cancelled' ? 'Run cancelled' : 'Installation failed',- taskRunState?.error_message ?? sessionErrorMessage(session)- ))- : null-- // The doc rides the run-window check, not the recency gate: the cloud wizard finishes (and- // publishes its report) hours before the pipeline completes, so by the time the completed- // surfaces would show the button the session is long stale. Without a run window (no handle),- // fall back to the recency-gated session rather than trusting an arbitrary old row.- const handoffSession =- latestSession && runStartedAt !== null- ? isSessionFromRun(latestSession, runStartedAt)- ? latestSession- : null- : session-- return {- phase,- steps,- error,- prUrl,- prMerged,- isCurrent: phase !== 'idle',- pendingInput: phase === 'running' ? pendingInputFromSession(session) : null,- startedBy: startedByFromSession(session),- handoffText: handoffSession?.handoff_text ?? null,- }-}--// Local: the wizard session is the only source. `sessionIsCurrent` is the sticky freshness flag —-// the SSE replays the latest session on connect even when it's a stale terminal row from a previous-// run, and those must not read as a run in flight. `dismissed` is the user's explicit dismissal of-// this session — it wins over freshness, so a dismissed run releases the install-step takeover.-export function localProgress(- latestSession: WizardSessionDTOApi | null,- sessionConnectionStatus: string,- sessionIsCurrent: boolean,- dismissed: boolean = false-): InstallationProgress {- if (!latestSession) {- return {- phase: sessionConnectionStatus === 'connecting' ? 'connecting' : 'idle',- steps: [],- error: null,- prUrl: null,- prMerged: false,- isCurrent: false,- pendingInput: null,- startedBy: null,- handoffText: null,- }- }-- // A CLI that dies without pushing a terminal phase leaves the row mid-run forever. The server- // computes staleness against the same threshold the detector trusts, so treat it the way the- // cloud path treats a stalled run: surface the dead end, because `connecting` and `running` both- // render as a spinner that `InstallationProgressContent` offers no way out of.- const stalled = latestSession.is_stale && latestSession.run_phase !== 'completed'-- let phase: InstallationPhase- if (latestSession.run_phase === 'completed') {- phase = 'completed'- } else if (latestSession.run_phase === 'error' || stalled) {- phase = 'error'- } else if (sessionConnectionStatus === 'connecting' || sessionConnectionStatus === 'error') {- phase = 'connecting'- } else {- phase = 'running'- }-- const steps: InstallationStep[] = (latestSession.tasks ?? []).map((t) => ({- id: t.id,- label: t.title,- status: stepStatus(t.status),- detail: null,- }))-- let error: InstallationError | null = null- if (latestSession.run_phase === 'error') {- error = runError('Wizard hit an error', sessionErrorMessage(latestSession))- } else if (stalled) {- error = {- title: 'Setup lost contact',- detail: 'We stopped hearing back from this run. Run the wizard yourself, or dismiss it and start over.',- }- }-- return {- phase,- steps,- error,- prUrl: null,- prMerged: false,- isCurrent: sessionIsCurrent && !dismissed,- pendingInput: phase === 'running' && !dismissed ? pendingInputFromSession(latestSession) : null,- startedBy: startedByFromSession(latestSession),- handoffText: latestSession.handoff_text ?? null,- }-}--// A finished local run rendered from its persisted snapshot, after the live session stream has-// gated itself off — same shape the live path produces for the same terminal session.-export function progressFromFinishedLocalRun(handle: FinishedLocalRunHandle): InstallationProgress {- return {- phase: handle.runPhase,- steps: handle.tasks.map((t) => ({ id: t.id, label: t.title, status: stepStatus(t.status), detail: null })),- error: handle.runPhase === 'error' ? runError('Wizard hit an error', handle.error?.message) : null,- prUrl: null,- prMerged: false,- isCurrent: true,- pendingInput: null,- startedBy: handle.startedBy ?? null,- handoffText: handle.handoffText ?? null,- }-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressCopy.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressCopy.tsdeleted file mode 100644index a36e2b8706cb..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressCopy.ts+++ /dev/null@@ -1,85 +0,0 @@-import { InstallationMode, InstallationProgress } from './installationProgressLogic'--/**- * The header copy for a run, one branch per phase. The self-driving program sets up scouts and- * signal sources rather than installing an SDK, so the "what just happened" copy has to follow the- * program — wording matches the CLI's own outro so the terminal and the browser tell the same story.- */-export function syncCopy({- progress,- mode,- selfDriving,- prReady,-}: {- progress: InstallationProgress- mode?: InstallationMode- selfDriving: boolean- /** A PR exists while the run is still going — surfaced as ready rather than "setting up". */- prReady: boolean-}): { headline: string; subtitle: string } {- const { phase, error, prUrl, prMerged } = progress-- if (phase === 'completed') {- const headline = selfDriving ? 'Self-driving is on' : 'PostHog is wired up'- if (prUrl) {- return {- headline,- subtitle: prMerged- ? 'Your pull request is merged. Deploy the changes and data starts flowing.'- : 'Review and merge the pull request, then deploy. Data starts flowing the moment it ships.',- }- }- if (selfDriving) {- return {- headline,- subtitle: 'Your scouts are watching. First findings hit your inbox within about 30 minutes.',- }- }- return {- headline,- subtitle: mode === 'local' ? 'The wizard finished its work on your machine.' : "You're all set.",- }- }-- if (phase === 'error') {- return { headline: error?.title ?? "Setup didn't finish", subtitle: "We couldn't finish the setup." }- }-- if (prReady) {- return prMerged- ? {- headline: 'Pull request merged',- subtitle: 'Deploy the changes and data starts flowing. The run will wrap up on its own.',- }- : {- headline: 'Pull request ready',- subtitle: "Review it whenever you like; we'll keep CI green in the meantime.",- }- }-- const headline = selfDriving ? 'Setting up self-driving' : 'Setting up PostHog'- if (phase === 'connecting') {- return { headline, subtitle: (mode && CONNECTING_SUBTITLE[mode]) ?? 'Getting things ready…' }- }- if (phase === 'idle') {- return { headline, subtitle: 'Not hearing back from this run right now. You can dismiss it and start over.' }- }- return { headline, subtitle: 'Working on it. Feel free to keep going.' }-}--const CONNECTING_SUBTITLE: Record<InstallationMode, string> = {- cloud: 'Firing up a sandbox for your repo. The wizard takes it from there.',- local: 'Waiting for the wizard in your terminal to check in.',-}--// What's about to happen, shown as pending timeline rows while the stream connects. Same geometry-// (and, for cloud, the same gerund phrasing) as the streamed steps that replace them, so the swap-// reads as the plan lighting up rather than the card rewriting itself.-export const UPCOMING_STEPS: Record<InstallationMode, string[]> = {- cloud: ['Setting up sandbox', 'Cloning repository', 'Running setup wizard', 'Opening a pull request'],- local: ['Detecting your framework', 'Installing the PostHog SDK', 'Wiring up event capture'],-}--// The self-driving program does different work, so previewing the SDK-install steps would promise-// the wrong thing while we wait for the run to report in.-export const SELF_DRIVING_UPCOMING_STEPS = ['Connecting GitHub', 'Choosing signal sources', 'Tailoring your scouts']diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.tsdeleted file mode 100644index 6a78bbd2fe54..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.ts+++ /dev/null@@ -1,796 +0,0 @@-import { initKeaTests } from '~/test/init'--import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'--import type { FinishedLocalRunHandle } from './finishedLocalRunLogic'-import {- cloudProgress,- isSessionFresh,- localProgress,- pendingInputFromSession,- progressFromFinishedLocalRun,-} from './installationProgress'-import { resetWizardSyncTelemetryForTests, runLocalSessionBookkeeping } from './installationProgressLogic'-import { wizardActiveSessionDetectorLogic } from './wizardActiveSessionDetectorLogic'-import { POSTHOG_INTEGRATION_WORKFLOW_ID, SELF_DRIVING_WORKFLOW_ID } from './workflows'--// Matches the fixtures' timestamps so sessions read as fresh where intended.-const NOW = new Date('2026-01-01T00:00:30Z').getTime()-const USAGE_LIMIT_ERROR = {- title: 'AI usage limit reached',- detail: 'The setup agent ran out of AI usage before it finished. Your own coding agent can finish the setup from our docs.',- kind: 'usage_limit',-}-import { TaskRunProgressStep, TaskRunStreamState } from './taskRunStreamLogic'--function taskState(overrides: Partial<TaskRunStreamState> = {}): TaskRunStreamState {- return {- status: 'in_progress',- stage: null,- output: null,- branch: null,- error_message: null,- updated_at: '2026-01-01T00:00:00Z',- completed_at: null,- ...overrides,- }-}--function step(overrides: Partial<TaskRunProgressStep> = {}): TaskRunProgressStep {- return {- step: 'clone',- status: 'in_progress',- label: 'Cloning repository',- group: 'setup',- detail: null,- ...overrides,- }-}--function session(overrides: Partial<WizardSessionDTOApi> = {}): WizardSessionDTOApi {- return {- session_id: 's',- team_id: 1,- workflow_id: 'posthog-integration',- skill_id: '',- started_at: '2026-01-01T00:00:00Z',- run_phase: 'running',- tasks: [],- event_plan: null,- error: null,- created_at: '2026-01-01T00:00:00Z',- updated_at: '2026-01-01T00:00:00Z',- is_stale: false,- ...overrides,- } as unknown as WizardSessionDTOApi-}--describe('installationProgressLogic merge', () => {- describe('cloudProgress', () => {- it.each([- ['no state + idle connection → idle', null, 'idle', 'idle'],- ['no state + connecting → connecting', null, 'connecting', 'connecting'],- ['no state + open connection → idle', null, 'open', 'idle'],- // Queued means nothing has started yet — presenting it as "running" told users the- // wizard was working when no worker had picked the run up.- ['queued → connecting', 'queued', 'open', 'connecting'],- ['in_progress → running', 'in_progress', 'open', 'running'],- ['completed → completed', 'completed', 'open', 'completed'],- ['failed → error', 'failed', 'open', 'error'],- ['cancelled → error', 'cancelled', 'open', 'error'],- ])('phase: %s', (_name, status, conn, expected) => {- const state = status === null ? null : taskState({ status })- expect(cloudProgress(state, [], conn, null).phase).toBe(expected)- })-- it.each([- // A deliberate cancel (button or PR close) must not read as a broken installation.- ['cancelled', 'Run cancelled'],- ['failed', 'Installation failed'],- ])('titles a terminal %s run as %s', (status, expectedTitle) => {- const result = cloudProgress(taskState({ status, error_message: 'Stopped by user' }), [], 'open', null)- expect(result.error?.title).toBe(expectedTitle)- expect(result.error?.detail).toBe('Stopped by user')- })-- it('surfaces a stalled queued run as an error instead of an eternal spinner', () => {- const result = cloudProgress(taskState({ status: 'queued' }), [], 'open', null, true)- expect(result.phase).toBe('error')- expect(result.error?.title).toBe("Setup hasn't started")- })-- it('ignores the stall flag once the run has left the queue', () => {- expect(cloudProgress(taskState({ status: 'in_progress' }), [], 'open', null, true).phase).toBe('running')- })-- it('surfaces a run that never delivered any state as an error, not an eternal idle spinner', () => {- // `idle` renders a spinner with no recovery controls, so a stream that stayed silent has- // to resolve to the error phase (which carries the retry CTAs and the dismiss control).- const result = cloudProgress(null, [], 'open', null, true)- expect(result.phase).toBe('error')- expect(result.error?.title).toBe('Setup lost contact')- expect(result.isCurrent).toBe(true)- })-- it.each([- ['pending', 'pending'],- ['in_progress', 'in_progress'],- ['completed', 'completed'],- ['failed', 'failed'],- ['canceled', 'failed'],- ['something-else', 'pending'],- ])('maps backend step status %s → %s', (raw, expected) => {- const result = cloudProgress(taskState(), [step({ status: raw })], 'open', null)- expect(result.steps.find((s) => s.id === 'setup:clone')?.status).toBe(expected)- })-- it('maps a step to id/label/detail', () => {- const result = cloudProgress(- taskState(),- [step({ group: 'setup', step: 'clone', label: 'Cloning', detail: 'shallow' })],- 'open',- null- )- expect(result.steps.find((s) => s.id === 'setup:clone')).toEqual({- id: 'setup:clone',- label: 'Cloning',- status: 'in_progress',- detail: 'shallow',- })- })-- it('replaces the wizard stage with the session tasks once they exist', () => {- const result = cloudProgress(- taskState(),- [- step({ step: 'clone', status: 'completed', label: 'Cloned repository' }),- step({ step: 'wizard', status: 'in_progress', label: 'Running setup wizard' }),- step({ step: 'pr', status: 'pending', label: 'Opening pull request', group: 'deliver' }),- ],- 'open',- session({- tasks: [- { id: 'a', title: 'Detect framework', status: 'completed' },- { id: 'b', title: 'Install SDK', status: 'in_progress' },- ],- }),- false,- NOW- )- expect(result.steps.map((s) => [s.label, s.status, s.source ?? null])).toEqual([- ['Setting up sandbox', 'pending', null],- ['Cloned repository', 'completed', null],- ['Detect framework', 'completed', 'wizard'],- ['Install SDK', 'in_progress', 'wizard'],- ['Opening pull request', 'pending', null],- ])- })-- it('slots session tasks into the skeleton wizard slot before any stage is announced', () => {- const result = cloudProgress(- taskState(),- [],- 'open',- session({ tasks: [{ id: 'a', title: 'Detect framework', status: 'in_progress' }] }),- false,- NOW- )- expect(result.steps.map((s) => [s.label, s.status, s.source ?? null])).toEqual([- ['Setting up sandbox', 'pending', null],- ['Cloning repository', 'pending', null],- ['Detect framework', 'in_progress', 'wizard'],- ['Opening a pull request', 'pending', null],- ])- })-- it('keeps the announced wizard stage when there is no session', () => {- const result = cloudProgress(- taskState(),- [step({ step: 'wizard', status: 'in_progress', detail: 'own detail' })],- 'open',- null- )- expect(result.steps.find((s) => s.id === 'setup:wizard')?.detail).toBe('own detail')- })-- it('clamps lingering in-progress wizard tasks once the run completes', () => {- const result = cloudProgress(- taskState({ status: 'completed' }),- [step({ step: 'wizard', status: 'completed' })],- 'open',- session({ tasks: [{ id: 'a', title: 'Install SDK', status: 'in_progress' }] }),- false,- NOW- )- expect(result.steps.find((s) => s.source === 'wizard')).toMatchObject({- label: 'Install SDK',- status: 'completed',- })- expect(result.steps.find((s) => s.id === 'setup:wizard')).toBeUndefined()- })-- it('uses the task run error message on failure', () => {- expect(- cloudProgress(taskState({ status: 'failed', error_message: 'boom' }), [], 'open', null).error- ).toEqual({- title: 'Installation failed',- detail: 'boom',- })- })-- it('falls back to the wizard session error message', () => {- expect(- cloudProgress(- taskState({ status: 'failed', error_message: null }),- [],- 'open',- session({ error: { message: 'wizard boom' } }),- false,- NOW- ).error- ).toEqual({ title: 'Installation failed', detail: 'wizard boom' })- })-- it('replaces a raw gateway usage limit refusal with a usage limit message', () => {- expect(- cloudProgress(- taskState({- status: 'failed',- error_message: 'posthog-gateway API error (402) token_cap_exceeded',- }),- [],- 'open',- null- ).error- ).toEqual(USAGE_LIMIT_ERROR)- })-- it('error detail is null when neither source has a message', () => {- expect(cloudProgress(taskState({ status: 'failed', error_message: null }), [], 'open', null).error).toEqual(- {- title: 'Installation failed',- detail: null,- }- )- })-- it('has no error outside an error phase', () => {- expect(cloudProgress(taskState({ status: 'in_progress' }), [], 'open', null).error).toBeNull()- })-- it.each([- [- 'output with pr_url',- taskState({ status: 'completed', output: { pr_url: 'https://x/pull/1' } }),- 'https://x/pull/1',- ],- ['output without pr_url', taskState({ status: 'completed', output: {} }), null],- ['null output', taskState({ status: 'completed', output: null }), null],- ['no task state', null, null],- ])('prUrl: %s', (_name, state, expected) => {- expect(cloudProgress(state, [], 'open', null).prUrl).toBe(expected)- })-- it('isCurrent is false only when idle', () => {- expect(cloudProgress(null, [], 'idle', null).isCurrent).toBe(false)- expect(cloudProgress(taskState({ status: 'in_progress' }), [], 'open', null).isCurrent).toBe(true)- expect(cloudProgress(taskState({ status: 'completed' }), [], 'open', null).isCurrent).toBe(true)- })- })-- describe('localProgress', () => {- it.each([- ['no session + connecting → connecting', null, 'connecting', 'connecting'],- ['no session + open → idle', null, 'open', 'idle'],- ['no session + idle → idle', null, 'idle', 'idle'],- ['completed → completed', { run_phase: 'completed' }, 'open', 'completed'],- ['error → error', { run_phase: 'error' }, 'open', 'error'],- ['running + open → running', { run_phase: 'running' }, 'open', 'running'],- ['running + connecting conn → connecting', { run_phase: 'running' }, 'connecting', 'connecting'],- ['running + error conn → connecting', { run_phase: 'running' }, 'error', 'connecting'],- // A CLI that dies without pushing a terminal phase: without this the step spins forever,- // and InstallationProgressContent only offers a way out on a terminal phase.- ['running + server-flagged stale → error', { run_phase: 'running', is_stale: true }, 'open', 'error'],- ])('phase: %s', (_name, sessionOverrides, conn, expected) => {- const s = sessionOverrides === null ? null : session(sessionOverrides as Partial<WizardSessionDTOApi>)- expect(localProgress(s, conn, true).phase).toBe(expected)- })-- it('maps session tasks to steps', () => {- const result = localProgress(- session({- run_phase: 'running',- tasks: [- { id: 'a', title: 'Detect framework', status: 'completed' },- { id: 'b', title: 'Install SDK', status: 'in_progress' },- ],- }),- 'open',- true- )- expect(result.steps).toEqual([- { id: 'a', label: 'Detect framework', status: 'completed', detail: null },- { id: 'b', label: 'Install SDK', status: 'in_progress', detail: null },- ])- })-- it('explains the dead end when a run goes stale without a terminal phase', () => {- expect(localProgress(session({ run_phase: 'running', is_stale: true }), 'open', true).error).toEqual({- title: 'Setup lost contact',- detail: 'We stopped hearing back from this run. Run the wizard yourself, or dismiss it and start over.',- })- })-- it('surfaces the wizard error on the error phase', () => {- expect(- localProgress(session({ run_phase: 'error', error: { message: 'wizard boom' } }), 'open', true).error- ).toEqual({- title: 'Wizard hit an error',- detail: 'wizard boom',- })- })-- it.each([- ['token cap', 'API Error: 402 {"error":{"code":"token_cap_exceeded","message":"cap reached"}}', true],- ['quota', 'API Error: 402 {"error":{"type":"insufficient_quota"}}', true],- ['uppercase code', 'API Error: 402 TOKEN_CAP_EXCEEDED', true],- ['prefixed code', 'API Error: 402 my_token_cap_exceeded', false],- ['suffixed code', 'API Error: 402 insufficient_quota_v2', false],- ])('maps a gateway refusal with a %s to the usage limit message', (_name, message, usageLimit) => {- expect(localProgress(session({ run_phase: 'error', error: { message } }), 'open', true).error).toEqual(- usageLimit ? USAGE_LIMIT_ERROR : { title: 'Wizard hit an error', detail: message }- )- })-- it('error detail is null when the session has no error message', () => {- expect(localProgress(session({ run_phase: 'error', error: null }), 'open', true).error).toEqual({- title: 'Wizard hit an error',- detail: null,- })- })-- it('has no error outside the error phase', () => {- expect(localProgress(session({ run_phase: 'running' }), 'open', true).error).toBeNull()- })-- it('never has a pr url', () => {- expect(localProgress(session({ run_phase: 'completed' }), 'open', true).prUrl).toBeNull()- })-- it('carries the handoff doc so the report button and dialog can render it', () => {- expect(localProgress(session({ handoff_text: '# report' }), 'open', true).handoffText).toBe('# report')- expect(localProgress(session(), 'open', true).handoffText).toBeNull()- })-- it('isCurrent mirrors the sticky freshness flag, never a bare session', () => {- // A stale terminal row replayed by the SSE on connect must not read as a run in flight —- // that is what used to hijack the install step before the freshness guard.- expect(localProgress(null, 'open', true).isCurrent).toBe(false)- expect(localProgress(session({ run_phase: 'running' }), 'open', false).isCurrent).toBe(false)- expect(localProgress(session({ run_phase: 'running' }), 'open', true).isCurrent).toBe(true)- })-- it('a dismissed session is not current even while fresh', () => {- // Dismissal must release the install-step takeover immediately — the sticky freshness- // flag alone would keep the completed panel pinned until the next remount.- expect(localProgress(session({ run_phase: 'completed' }), 'open', true, true).isCurrent).toBe(false)- })-- it('names the initiator, preferring first name and falling back to email', () => {- // The card reads "On <name>'s machine"; a blank first_name must fall back to email so it- // never renders "On 's machine".- expect(- localProgress(session({ created_by: { id: 1, first_name: 'Edwin', email: '[email protected]' } }), 'open', true)- .startedBy- ).toEqual({ name: 'Edwin', email: '[email protected]' })- expect(- localProgress(session({ created_by: { id: 1, first_name: '', email: '[email protected]' } }), 'open', true)- .startedBy- ).toEqual({ name: '[email protected]', email: '[email protected]' })- expect(localProgress(session(), 'open', true).startedBy).toBeNull()- })- })-- describe('pendingInput', () => {- const pending = {- id: 'ask-1',- asked_at: '2026-01-01T00:00:10Z',- question_count: 1,- sensitive: false,- prompts: ['Which region is your project in?'],- }-- it('surfaces an open wizard_ask on a live session', () => {- const result = localProgress(session({ run_phase: 'running', pending_input: pending }), 'open', true)- expect(result.pendingInput).toEqual({- id: 'ask-1',- askedAt: '2026-01-01T00:00:10Z',- questionCount: 1,- sensitive: false,- prompts: ['Which region is your project in?'],- })- })-- it.each([- // A dead wizard never sends the clearing push — staleness is the only way out.- ['stale session', session({ run_phase: 'running', pending_input: pending, is_stale: true })],- ['terminal session', session({ run_phase: 'completed', pending_input: pending })],- ['no pending_input on the row', session({ run_phase: 'running', pending_input: null })],- ])('gated off for a %s', (_name, s) => {- expect(pendingInputFromSession(s)).toBeNull()- })-- it('withholds prompts on sensitive asks even if the row carries them', () => {- const result = pendingInputFromSession(- session({ run_phase: 'running', pending_input: { ...pending, sensitive: true } })- )- expect(result?.sensitive).toBe(true)- expect(result?.prompts).toEqual([])- })-- it('the next push without the field reads as dismissed', () => {- const withQuestion = localProgress(session({ run_phase: 'running', pending_input: pending }), 'open', true)- const cleared = localProgress(session({ run_phase: 'running', pending_input: null }), 'open', true)- expect(withQuestion.pendingInput).not.toBeNull()- expect(cleared.pendingInput).toBeNull()- })- })-- describe('progressFromFinishedLocalRun', () => {- const handle = (overrides: Partial<FinishedLocalRunHandle> = {}): FinishedLocalRunHandle => ({- sessionId: 's',- projectId: 1,- startedAt: '2026-01-01T00:00:00Z',- finishedAt: '2026-01-01T00:05:00Z',- runPhase: 'completed',- tasks: [- { id: 'a', title: 'Detect framework', status: 'completed' },- { id: 'b', title: 'Install SDK', status: 'canceled' },- ],- error: null,- ...overrides,- })-- it('renders the snapshot like the live path rendered the same terminal session', () => {- // The FAB switches from the live stream to this snapshot when the stream gates itself- // off — a mapping drift would make the card visibly rewrite itself at that moment.- expect(progressFromFinishedLocalRun(handle())).toEqual({- phase: 'completed',- steps: [- { id: 'a', label: 'Detect framework', status: 'completed', detail: null },- { id: 'b', label: 'Install SDK', status: 'failed', detail: null },- ],- error: null,- prUrl: null,- prMerged: false,- isCurrent: true,- pendingInput: null,- startedBy: null,- handoffText: null,- })- })-- it('carries the snapshotted initiator so the finished-run handoff can still name them', () => {- // The handle outlives the session stream; without this the card would drop the- // attribution the moment it switched from the live stream to the snapshot.- const result = progressFromFinishedLocalRun(- handle({ startedBy: { name: 'Edwin', email: '[email protected]' } })- )- expect(result.startedBy).toEqual({ name: 'Edwin', email: '[email protected]' })- })-- it('surfaces the persisted error on failed runs', () => {- const result = progressFromFinishedLocalRun(handle({ runPhase: 'error', error: { message: 'boom' } }))- expect(result.phase).toBe('error')- expect(result.error).toEqual({ title: 'Wizard hit an error', detail: 'boom' })- })- })-- describe('isSessionFresh', () => {- const NOW = new Date('2026-01-01T00:00:00Z').getTime()- it.each([- ['updated just now', '2026-01-01T00:00:00Z', true],- ['updated 9 minutes ago', '2025-12-31T23:51:00Z', true],- ['updated 11 minutes ago', '2025-12-31T23:49:00Z', false],- ['unparseable timestamp', 'not-a-date', false],- ])('%s → %s', (_name, updatedAt, expected) => {- expect(isSessionFresh(session({ updated_at: updatedAt }), NOW)).toBe(expected)- })- })-- describe('cloudProgress agent-gap bridging', () => {- const NOW_MS = new Date('2026-01-01T00:00:30Z').getTime()- it('flips the pending PR slot to in-progress and hides the agent plumbing row', () => {- // The quiet window between agent start and the PR opening must not read as stalled,- // and 'Started agent' is internal plumbing the user shouldn't see at all.- const result = cloudProgress(- taskState(),- [- step({ step: 'sandbox', status: 'completed', label: 'Set up sandbox' }),- step({ step: 'clone', status: 'completed', label: 'Cloned repository' }),- step({ step: 'wizard', status: 'completed', label: 'Ran setup wizard' }),- step({ step: 'agent', status: 'completed', label: 'Started agent' }),- ],- 'open',- null- )- expect(result.steps.map((s) => [s.label, s.status])).toEqual([- ['Set up sandbox', 'completed'],- ['Cloned repository', 'completed'],- ['Ran setup wizard', 'completed'],- ['Opening a pull request', 'in_progress'],- ])- })-- it.each([- ['a step is still in flight', [step({ step: 'wizard', status: 'in_progress' })], null],- [- 'a deliver-stage step already exists',- [- step({ step: 'agent', status: 'completed' }),- step({ step: 'pr', status: 'completed', group: 'deliver', detail: 'https://x/pull/1' }),- ],- null,- ],- ['the run has completed', [step({ step: 'agent', status: 'completed' })], 'completed'],- ])('does not synthesize when %s', (_name, progressSteps, status) => {- const result = cloudProgress(- taskState(status ? { status } : {}),- progressSteps as TaskRunProgressStep[],- 'open',- null,- false,- NOW_MS- )- expect(result.steps.find((s) => s.id.endsWith(':pr'))?.status ?? 'pending').not.toBe('in_progress')- })- })-- describe('cloudProgress handoff doc run-window gate', () => {- const NOW_MS = new Date('2026-01-01T06:00:00Z').getTime()- // The wizard stage published its doc at ~00:00 and the pipeline completed hours later, so- // the session is far past the recency gate by the time the completed surfaces render.- const staleWithDoc = session({- started_at: '2026-01-01T00:00:00Z',- updated_at: '2026-01-01T00:05:00Z',- run_phase: 'completed',- handoff_text: '# report',- })- const completedRun = taskState({ status: 'completed' })-- it("keeps the doc from this run's session long after it went stale", () => {- // Regression: gating the doc on isSessionFresh meant cloud users could never see it —- // the button checks phase === completed, which flips hours after the wizard stage.- const result = cloudProgress(completedRun, [], 'open', staleWithDoc, false, NOW_MS, '2025-12-31T23:55:00Z')- expect(result.handoffText).toBe('# report')- })-- it("rejects a session that predates the run (a previous run's doc)", () => {- const result = cloudProgress(completedRun, [], 'open', staleWithDoc, false, NOW_MS, '2026-01-01T01:00:00Z')- expect(result.handoffText).toBeNull()- })-- it('falls back to the recency gate when no run window is known', () => {- expect(cloudProgress(completedRun, [], 'open', staleWithDoc, false, NOW_MS).handoffText).toBeNull()- const freshWithDoc = session({- updated_at: '2026-01-01T05:59:00Z',- run_phase: 'completed',- handoff_text: '# report',- })- expect(cloudProgress(completedRun, [], 'open', freshWithDoc, false, NOW_MS).handoffText).toBe('# report')- })- })-- describe('cloudProgress session freshness gate', () => {- const NOW_MS = new Date('2026-01-01T00:00:30Z').getTime()- it('ignores a stale session for both the timeline and the error fallback', () => {- // A stale terminal row replayed on connect must not leak a previous run's tasks or error- // text into a fresh cloud run.- const stale = session({- updated_at: '2025-12-01T00:00:00Z',- tasks: [{ id: 'a', title: 'Old task', status: 'completed' }],- error: { message: 'old boom' },- })- const running = cloudProgress(taskState(), [], 'open', stale, false, NOW_MS)- expect(running.steps.filter((s) => s.source === 'wizard')).toEqual([])- const failed = cloudProgress(- taskState({ status: 'failed', error_message: null }),- [],- 'open',- stale,- false,- NOW_MS- )- expect(failed.error?.detail).toBeNull()- })-- it('replaces the skeleton wizard slot with wizard tasks', () => {- const result = cloudProgress(- taskState(),- [- step({ step: 'clone', status: 'completed', label: 'Cloned repository' }),- step({ step: 'pr', status: 'pending', label: 'Opening pull request', group: 'deliver' }),- ],- 'open',- session({ tasks: [{ id: 'a', title: 'Install SDK', status: 'in_progress' }] }),- false,- NOW_MS- )- expect(result.steps.map((s) => s.label)).toEqual([- 'Setting up sandbox',- 'Cloned repository',- 'Install SDK',- 'Opening pull request',- ])- })- })-- describe('runLocalSessionBookkeeping', () => {- const spyActions = (): {- markSessionCurrent: jest.Mock- recordFinishedLocalRun: jest.Mock- supersedeFinishedLocalRun: jest.Mock- handoffDocReceived: jest.Mock- reportWizardSyncSessionDetected: jest.Mock- reportWizardSyncSessionFinished: jest.Mock- } => ({- markSessionCurrent: jest.fn(),- recordFinishedLocalRun: jest.fn(),- supersedeFinishedLocalRun: jest.fn(),- handoffDocReceived: jest.fn(),- reportWizardSyncSessionDetected: jest.fn(),- reportWizardSyncSessionFinished: jest.fn(),- })- const fresh = (overrides: Partial<WizardSessionDTOApi> = {}): WizardSessionDTOApi =>- session({ updated_at: new Date(Date.now() - 1000).toISOString(), ...overrides })-- beforeEach(() => resetWizardSyncTelemetryForTests())-- it('marks the session current and reports detected once per session across redeliveries', () => {- const actions = spyActions()- const s = fresh({ session_id: 'dup' })- runLocalSessionBookkeeping(s, null, POSTHOG_INTEGRATION_WORKFLOW_ID, actions)- runLocalSessionBookkeeping(s, s, POSTHOG_INTEGRATION_WORKFLOW_ID, actions)- expect(actions.markSessionCurrent).toHaveBeenCalledTimes(2)- expect(actions.reportWizardSyncSessionDetected).toHaveBeenCalledTimes(1)- })-- it('ignores a stale session entirely for freshness and reach telemetry', () => {- const actions = spyActions()- runLocalSessionBookkeeping(- session({ updated_at: '2020-01-01T00:00:00Z' }),- null,- POSTHOG_INTEGRATION_WORKFLOW_ID,- actions- )- expect(actions.markSessionCurrent).not.toHaveBeenCalled()- expect(actions.reportWizardSyncSessionDetected).not.toHaveBeenCalled()- })-- it('reports finished only on an observed transition into a terminal phase, once', () => {- const actions = spyActions()- const running = fresh({ session_id: 'fin', run_phase: 'running' })- const done = fresh({ session_id: 'fin', run_phase: 'completed' })- runLocalSessionBookkeeping(done, null, POSTHOG_INTEGRATION_WORKFLOW_ID, actions) // replayed terminal state: no transition- expect(actions.reportWizardSyncSessionFinished).not.toHaveBeenCalled()- runLocalSessionBookkeeping(done, running, POSTHOG_INTEGRATION_WORKFLOW_ID, actions)- runLocalSessionBookkeeping(done, running, POSTHOG_INTEGRATION_WORKFLOW_ID, actions)- expect(actions.reportWizardSyncSessionFinished).toHaveBeenCalledTimes(1)- })-- it.each([- ['usage limit refusal', 'API Error: 402 token_cap_exceeded', 'usage_limit'],- ['different error', 'boom', null],- ])('reports the error kind for a %s', (_name, message, errorKind) => {- const actions = spyActions()- runLocalSessionBookkeeping(- fresh({ session_id: `kind-${message}`, run_phase: 'error', error: { message } }),- fresh({ session_id: `kind-${message}`, run_phase: 'running' }),- POSTHOG_INTEGRATION_WORKFLOW_ID,- actions- )- expect(actions.reportWizardSyncSessionFinished).toHaveBeenCalledWith(expect.objectContaining({ errorKind }))- })-- it.each([- // Recording must fire on every fresh terminal delivery (a replayed terminal state after- // a remount is exactly when the FAB needs its snapshot back), never on stale ones —- // otherwise a finished run's handoff vanishes with the stream, or a stale row from a- // previous run resurrects a surface the user never watched.- ['fresh completed session', { run_phase: 'completed' }, true, true],- ['fresh errored session', { run_phase: 'error' }, true, true],- ['fresh running session', { run_phase: 'running' }, true, false],- ['stale completed session', { run_phase: 'completed', updated_at: '2020-01-01T00:00:00Z' }, false, false],- ])('records the finished-run handle for a %s: %s', (_name, overrides, isFresh, expectRecorded) => {- const actions = spyActions()- const s = isFresh- ? fresh(overrides as Partial<WizardSessionDTOApi>)- : session(overrides as Partial<WizardSessionDTOApi>)- runLocalSessionBookkeeping(s, null, POSTHOG_INTEGRATION_WORKFLOW_ID, actions)- expect(actions.recordFinishedLocalRun).toHaveBeenCalledTimes(expectRecorded ? 1 : 0)- })-- it('supersedes the previous finished run when a fresh run goes live', () => {- // Starting over must replace the old handoff with the live run — otherwise dismissing- // requires clearing two surfaces, or the old completed card reappears mid-new-run.- const actions = spyActions()- runLocalSessionBookkeeping(- fresh({ session_id: 'new-run', run_phase: 'running' }),- null,- POSTHOG_INTEGRATION_WORKFLOW_ID,- actions- )- expect(actions.supersedeFinishedLocalRun).toHaveBeenCalledWith('new-run')- expect(actions.recordFinishedLocalRun).not.toHaveBeenCalled()- })-- it.each([- // The doc must ride the same freshness gate as everything else (a stale row's doc- // re-announced on every app load would fight the once-only auto-open downstream), and- // it must wait for the completed push: the reopen buttons only exist on completed runs,- // so announcing an errored (or still-running) run's doc would burn the one auto-open on- // a dialog the user can never get back to.- ['fresh completed session with a doc', fresh({ run_phase: 'completed', handoff_text: '# report' }), 1],- ['fresh completed session without a doc', fresh({ run_phase: 'completed' }), 0],- ['fresh running session with a doc', fresh({ handoff_text: '# report' }), 0],- ['fresh errored session with a doc', fresh({ run_phase: 'error', handoff_text: '# report' }), 0],- [- 'stale completed session with a doc',- session({ run_phase: 'completed', handoff_text: '# report', updated_at: '2020-01-01T00:00:00Z' }),- 0,- ],- ])('announces the handoff doc only for a %s', (_name, s, expectedCalls) => {- const actions = spyActions()- runLocalSessionBookkeeping(s, null, POSTHOG_INTEGRATION_WORKFLOW_ID, actions)- expect(actions.handoffDocReceived).toHaveBeenCalledTimes(expectedCalls)- if (expectedCalls > 0) {- expect(actions.handoffDocReceived).toHaveBeenCalledWith({- key: s.session_id,- text: '# report',- startedByEmail: null,- })- }- })-- it('tolerates a malformed session with null tasks', () => {- const actions = spyActions()- const s = fresh({ session_id: 'null-tasks', tasks: null as unknown as WizardSessionDTOApi['tasks'] })- expect(() => runLocalSessionBookkeeping(s, null, POSTHOG_INTEGRATION_WORKFLOW_ID, actions)).not.toThrow()- expect(actions.reportWizardSyncSessionDetected).toHaveBeenCalledWith(- expect.objectContaining({ taskCount: 0 })- )- })-- it('stamps telemetry with the workflow being tracked', () => {- const actions = spyActions()- runLocalSessionBookkeeping(fresh({ session_id: 'sd-run' }), null, SELF_DRIVING_WORKFLOW_ID, actions)- expect(actions.reportWizardSyncSessionDetected).toHaveBeenCalledWith(- expect.objectContaining({ workflowId: SELF_DRIVING_WORKFLOW_ID })- )- })-- // The FAB streams whatever the detector says is live, so the detector has to carry WHICH- // program that is. Recording only "something is running" made the FAB open the SDK-install- // stream for a self-driving run and render nothing.- it('tells the app-wide session detector which workflow went live', () => {- // `started_at` too must be recent: the detector's eligibility check caps a session's- // lifetime at an hour, and the shared fixture's is fixed in the past.- const live = (sessionId: string): WizardSessionDTOApi =>- fresh({ session_id: sessionId, started_at: new Date(Date.now() - 1000).toISOString() })-- initKeaTests()- const detector = wizardActiveSessionDetectorLogic()- detector.mount()- try {- runLocalSessionBookkeeping(live('sd'), null, SELF_DRIVING_WORKFLOW_ID, spyActions())- expect(detector.values.activeWorkflowId).toBe(SELF_DRIVING_WORKFLOW_ID)- expect(detector.values.hasActiveSession).toBe(true)-- runLocalSessionBookkeeping(live('pi'), null, POSTHOG_INTEGRATION_WORKFLOW_ID, spyActions())- expect(detector.values.activeWorkflowId).toBe(POSTHOG_INTEGRATION_WORKFLOW_ID)- } finally {- detector.unmount()- }- })- })-})diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.tsdeleted file mode 100644index d9c3c987ef84..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.ts+++ /dev/null@@ -1,536 +0,0 @@-import {- MakeLogicType,- actions,- afterMount,- beforeUnmount,- connect,- kea,- key,- listeners,- path,- props,- reducers,- selectors,-} from 'kea'--import { elapsedSecondsFrom } from 'lib/utils/datetime'-import { eventUsageLogic } from 'lib/utils/eventUsageLogic'--import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'-import { wizardSessionStreamLogic } from 'products/wizard/frontend/wizardSessionStreamLogic'--import type { WizardConnectionStatus } from '../../../../../../products/wizard/frontend/wizardSessionStreamLogic'-import { activeCloudRunLogic } from './activeCloudRunLogic'-import type { CloudRunHandle } from './activeCloudRunLogic'-import { finishedLocalRunLogic } from './finishedLocalRunLogic'-import { sessionErrorMessage } from './helpers'-import { cloudProgress, errorKindFromMessage, isSessionFresh, localProgress } from './installationProgress'-import { taskRunStreamLogic, TaskRunProgressStep, TaskRunStreamState } from './taskRunStreamLogic'-import type { TaskRunConnectionStatus } from './taskRunStreamLogic'-import {- isSessionActive,- watchWorkflowWhileMounted,- wizardActiveSessionDetectorLogic,-} from './wizardActiveSessionDetectorLogic'-import { wizardSyncUiLogic } from './wizardSyncUiLogic'-import { resolveWorkflowId } from './workflows'--// Per-session telemetry guards, deliberately module-scoped rather than on the kea `cache`: the logic-// unmounts whenever its last consumer does (FAB gate flips, install step navigated away), and a-// remount wipes `cache` — so a cache-based guard would let the SSE redeliver a still-in-flight-// session and re-fire these events. Keying by session_id at module scope makes "once per session"-// hold across remounts for the whole page load.-const reportedDetectedSessions = new Set<string>()-const reportedFinishedSessions = new Set<string>()--// One "share" of the wizard session transport per mounted instance. wizardSessionStreamLogic-// connect/disconnect is NOT refcounted and the keyed instance is shared across instances of this-// logic, so nobody may cut the transport out from under a co-mounted consumer: shares are released-// on unmount (and early, by a cloud instance whose run went terminal), and only the LAST release-// disconnects. Without this, a finishing cloud run would kill the stream for the still-mounted-// local instance and the "Run it yourself" recovery flow would go deaf until a full remount.-// Keyed by stream, not global: `wizardSessionStreamLogic` is itself keyed per workflow, so a single-// flat set would both collide (two workflows share the instance key `local`) and leak (the last-// release of ANY workflow would disconnect only its own stream, stranding the others).-const sessionStreamShares = new Map<string, Set<string>>()--function releaseSessionShare(streamKey: string, shareKey: string, disconnectSession: () => void): void {- const shares = sessionStreamShares.get(streamKey)- if (!shares?.delete(shareKey)) {- return- }- if (shares.size === 0) {- sessionStreamShares.delete(streamKey)- disconnectSession()- }-}--function acquireSessionShare(streamKey: string, shareKey: string): void {- const shares = sessionStreamShares.get(streamKey) ?? new Set<string>()- shares.add(shareKey)- sessionStreamShares.set(streamKey, shares)-}--export function resetWizardSyncTelemetryForTests(): void {- reportedDetectedSessions.clear()- reportedFinishedSessions.clear()- sessionStreamShares.clear()-}--/**- * Identity of one mounted instance. Shared by `key()` and the stream-share bookkeeping, which must- * agree — if they drift, the refcount releases a share nobody holds and the transport leaks.- */-function instanceKey(props: InstallationProgressLogicProps): string {- const mode = props.mode === 'cloud' ? `cloud:${props.runId ?? ''}` : 'local'- return `${resolveWorkflowId(props.workflowId)}:${mode}`-}--/**- * The `wizardSessionStreamLogic` instance an install-progress instance shares. Mirrors that logic's- * own key. `skillId` is deliberately left unset: the CLI reassigns `session.skillId` per agent run,- * so a self-driving run's skill flips to the framework name mid-session and a skill-scoped- * subscription would drop out partway through.- */-function sessionStreamKey(props: InstallationProgressLogicProps): string {- return `${resolveWorkflowId(props.workflowId)}::*`-}--export type InstallationMode = 'local' | 'cloud'-export type InstallationPhase = 'idle' | 'connecting' | 'running' | 'completed' | 'error'-export type InstallationStepStatus = 'pending' | 'in_progress' | 'completed' | 'failed'--export interface InstallationStep {- id: string- label: string- status: InstallationStepStatus- detail: string | null- /** Set on steps reported by the wizard itself (session tasks), as opposed to the run pipeline —- * the timeline renders them nested under the pipeline's wizard stage. */- source?: 'wizard'-}--/** The wizard's in-flight `wizard_ask` prompt, published on the session row while the CLI is- * blocked on the user. Sensitive asks (secrets) carry no prompt text by design. */-export interface WizardPendingInput {- id: string- askedAt: string- questionCount: number- sensitive: boolean- prompts: string[]-}--/** Set when the AI gateway stopped the run, so the UI offers the user's own agent in place of a retry. */-export type InstallationErrorKind = 'usage_limit'--export interface InstallationError {- title: string- detail: string | null- kind?: InstallationErrorKind-}--export interface InstallationProgress {- phase: InstallationPhase- steps: InstallationStep[]- error: InstallationError | null- prUrl: string | null- /** The bound PR was merged (webhook-recorded on the run's output). */- prMerged: boolean- isCurrent: boolean- /** Set while the wizard is waiting on the user in the terminal — the widget's attention state.- * Cleared by the next session push without the field (answered, cancelled, or timed out). */- pendingInput: WizardPendingInput | null- /** Who started the run (null when unknown). `email` is for the "is this me?" check. */- startedBy: { name: string; email: string } | null- /** Markdown handoff doc the wizard produced (its setup report), once the run has one. Sticky on- * the session row, so it survives later pushes and the finished-run snapshot. */- handoffText: string | null-}--export interface InstallationProgressLogicProps {- mode: InstallationMode- runId?: string- taskId?: string- /** Wizard program to track. Defaults to the SDK install (`posthog-integration`). */- workflowId?: string-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface installationProgressLogicValues {- activeCloudRun: CloudRunHandle | null // activeCloudRunLogic- dismissedSessionId: string | null // finishedLocalRunLogic- isStalled: boolean // taskRunStreamLogic- lastActivityAt: number | null // taskRunStreamLogic- progressSteps: TaskRunProgressStep[] // taskRunStreamLogic- taskConnectionStatus: TaskRunConnectionStatus // taskRunStreamLogic- taskRunState: TaskRunStreamState | null // taskRunStreamLogic- latestSession: WizardSessionDTOApi | null // wizardSessionStreamLogic- sessionConnectionStatus: WizardConnectionStatus // wizardSessionStreamLogic- installationProgress: InstallationProgress- sessionIsCurrent: boolean-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface installationProgressLogicActions {- reportWizardSyncSessionDetected: (props: {- runPhase: string- skillId: string- taskCount: number- workflowId: string- }) => {- runPhase: string- skillId: string- taskCount: number- workflowId: string- } // eventUsageLogic- reportWizardSyncSessionFinished: (props: {- completedTaskCount: number- elapsedSeconds: number- errorKind: InstallationErrorKind | null- outcome: string- skillId: string- taskCount: number- workflowId: string- }) => {- completedTaskCount: number- elapsedSeconds: number- errorKind: 'usage_limit' | null- outcome: string- skillId: string- taskCount: number- workflowId: string- } // eventUsageLogic- recordFinishedLocalRun: (session: WizardSessionDTOApi) => {- session: WizardSessionDTOApi- } // finishedLocalRunLogic- supersedeFinishedLocalRun: (sessionId: string) => {- sessionId: string- } // finishedLocalRunLogic- connectTaskRun: () => {- value: true- } // taskRunStreamLogic- disconnectTaskRun: () => {- value: true- } // taskRunStreamLogic- taskRunStreamCompleted: () => {- value: true- } // taskRunStreamLogic- connectSession: () => {- value: true- } // wizardSessionStreamLogic- disconnectSession: () => {- value: true- } // wizardSessionStreamLogic- sessionUpdated: (session: WizardSessionDTOApi) => {- session: WizardSessionDTOApi- } // wizardSessionStreamLogic- handoffDocReceived: (doc: { key: string; startedByEmail: string | null; text: string }) => {- key: string- startedByEmail: string | null- text: string- } // wizardSyncUiLogic- markSessionCurrent: () => {- value: true- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface installationProgressLogicMeta {- key: string- __keaTypeGenInternalSelectorTypes: {- installationProgress: (- taskRunState: TaskRunStreamState | null,- progressSteps: TaskRunProgressStep[],- taskConnectionStatus: TaskRunConnectionStatus,- latestSession: WizardSessionDTOApi | null,- sessionConnectionStatus: WizardConnectionStatus,- sessionIsCurrent: boolean,- isStalled: boolean,- dismissedSessionId: string | null,- activeCloudRun: CloudRunHandle | null,- arg: any,- arg2: any- ) => InstallationProgress- }-}--export type installationProgressLogicType = MakeLogicType<- installationProgressLogicValues,- installationProgressLogicActions,- InstallationProgressLogicProps,- installationProgressLogicMeta->--/**- * The Installation layer: one normalized `InstallationProgress` the UI renders, hiding which underlying- * stream(s) feed it.- * - `mode: 'local'` — the wizard session stream only (the local CLI is the writer).- * - `mode: 'cloud'` — the TaskRun pipeline (provision → clone → wizard → agent → PR, plus terminal- * status, PR url, error) merged with the wizard session stream (wizard-stage detail).- *- * Both sources are always connected; in local mode the task source is a no-op (empty runId), so the- * merge selector can reference its values unconditionally and just branch on `mode`.- */-export const installationProgressLogic = kea<installationProgressLogicType>([- props({} as InstallationProgressLogicProps),- // Must include the workflow: kea mutates props in place on a cache hit, so two workflows sharing- // a key would leave the second one's `connect` wiring pinned to the first one's stream.- key(instanceKey),- path((key) => ['scenes', 'onboarding', 'installationProgressLogic', key]),- connect((props: InstallationProgressLogicProps) => ({- values: [- taskRunStreamLogic({ runId: props.runId ?? '', taskId: props.taskId ?? '' }),- [- 'taskRunState',- 'progressSteps',- 'connectionStatus as taskConnectionStatus',- 'isStalled',- 'lastActivityAt',- ],- wizardSessionStreamLogic({ workflowId: resolveWorkflowId(props.workflowId) }),- ['latestSession', 'connectionStatus as sessionConnectionStatus'],- finishedLocalRunLogic,- ['dismissedSessionId'],- activeCloudRunLogic,- ['activeCloudRun'],- ],- actions: [- taskRunStreamLogic({ runId: props.runId ?? '', taskId: props.taskId ?? '' }),- [- 'connect as connectTaskRun',- 'disconnect as disconnectTaskRun',- 'streamCompleted as taskRunStreamCompleted',- ],- wizardSessionStreamLogic({ workflowId: resolveWorkflowId(props.workflowId) }),- ['connect as connectSession', 'disconnect as disconnectSession', 'sessionUpdated'],- eventUsageLogic,- ['reportWizardSyncSessionDetected', 'reportWizardSyncSessionFinished'],- finishedLocalRunLogic,- ['recordFinishedLocalRun', 'supersedeFinishedLocalRun'],- wizardSyncUiLogic,- ['handoffDocReceived'],- ],- })),- actions({- // Sticky flag — set the first time we observe a session that's recent enough to count as- // live. Old terminal sessions sitting in the DB stay invisible to the install step.- markSessionCurrent: true,- }),- reducers({- sessionIsCurrent: [- false,- {- markSessionCurrent: () => true,- },- ],- }),- selectors({- installationProgress: [- (s) => [- s.taskRunState,- s.progressSteps,- s.taskConnectionStatus,- s.latestSession,- s.sessionConnectionStatus,- s.sessionIsCurrent,- s.isStalled,- s.dismissedSessionId,- s.activeCloudRun,- (_, props) => props.mode,- (_, props) => props.runId,- ],- (- taskRunState: TaskRunStreamState | null,- progressSteps: TaskRunProgressStep[],- taskConnectionStatus: import('./taskRunStreamLogic').TaskRunConnectionStatus,- latestSession: WizardSessionDTOApi | null,- sessionConnectionStatus: import('products/wizard/frontend/wizardSessionStreamLogic').WizardConnectionStatus,- sessionIsCurrent: boolean,- isStalled: boolean,- dismissedSessionId: string | null,- activeCloudRun: CloudRunHandle | null,- mode,- runId- ): InstallationProgress =>- mode === 'cloud'- ? cloudProgress(- taskRunState,- progressSteps,- taskConnectionStatus,- latestSession,- isStalled,- Date.now(),- // The kickoff stamp scopes the handoff doc to this run (see cloudProgress);- // a handle for a different run means no window rather than a wrong one.- activeCloudRun?.runId === runId ? (activeCloudRun?.startedAt ?? null) : null- )- : localProgress(- latestSession,- sessionConnectionStatus,- sessionIsCurrent,- !!latestSession && latestSession.session_id === dismissedSessionId- ),- ],- }),- listeners(({ actions, props, cache }) => ({- // Once the cloud run is terminal there is nothing left for the session source to enrich —- // release this instance's share so an undismissed finished run doesn't keep a session- // stream/poll alive app-wide. The share accounting protects a co-mounted local instance,- // whose "Run it yourself" recovery flow must outlive a finishing cloud run.- taskRunStreamCompleted: () => {- if (props.mode !== 'cloud') {- return- }- releaseSessionShare(sessionStreamKey(props), instanceKey(props), actions.disconnectSession)- },- // Local-run bookkeeping, owned by the single local-mode instance so cloud instances (which- // share the session stream purely for wizard-stage detail) don't double-fire it.- sessionUpdated: ({ session }) => {- if (props.mode !== 'local') {- return- }- const prev = (cache.prevSession ?? null) as WizardSessionDTOApi | null- cache.prevSession = session- runLocalSessionBookkeeping(session, prev, resolveWorkflowId(props.workflowId), actions)- },- })),- afterMount(({ actions, props, cache, values }) => {- actions.connectTaskRun()- acquireSessionShare(sessionStreamKey(props), instanceKey(props))- actions.connectSession()- if (props.mode === 'local') {- // The detector's REST poll is only useful to the local instance (it gates the FAB's- // local stream and receives markActive sync) — mounting it from cloud instances would- // run a background poll for the whole run for nothing (INC-886 family).- cache.unwatchWorkflow = watchWorkflowWhileMounted(resolveWorkflowId(props.workflowId))- // Seed from a session already on the shared stream: the listener only sees NEW- // deliveries, so a remount would otherwise wait for the next tick (long in polling- // backoff) and flap the install-step takeover back to the command block.- if (values.latestSession) {- cache.prevSession = values.latestSession- runLocalSessionBookkeeping(values.latestSession, null, resolveWorkflowId(props.workflowId), actions)- }- }- }),- beforeUnmount(({ actions, props, cache }) => {- actions.disconnectTaskRun()- releaseSessionShare(sessionStreamKey(props), instanceKey(props), actions.disconnectSession)- if (cache.unwatchWorkflow) {- cache.unwatchWorkflow()- cache.unwatchWorkflow = undefined- }- }),-])--// The local instance's per-delivery bookkeeping, shared by the sessionUpdated listener and the-// mount-time seed:-// - freshness: flip the sticky current flag so the install step can take over-// - reach/outcome telemetry, once per session_id (module-scoped guards survive remounts)-// - detector sync: keep the FAB's stream gate alive across navigation, and let a terminal-// session schedule its teardown grace window-// - finished-run handle: snapshot a fresh terminal run so its handoff surface outlives the-// stream, and supersede the previous run's handle once a new run goes live-// - handoff doc: announce a fresh session's doc so the one-time auto-open dialog can fire-export function runLocalSessionBookkeeping(- session: WizardSessionDTOApi,- prev: WizardSessionDTOApi | null,- workflowId: string,- actions: {- markSessionCurrent: () => void- recordFinishedLocalRun: (session: WizardSessionDTOApi) => void- supersedeFinishedLocalRun: (sessionId: string) => void- handoffDocReceived: (doc: { key: string; text: string; startedByEmail: string | null }) => void- reportWizardSyncSessionDetected: (props: {- workflowId: string- skillId: string- runPhase: string- taskCount: number- }) => void- reportWizardSyncSessionFinished: (props: {- workflowId: string- skillId: string- outcome: string- errorKind: InstallationErrorKind | null- taskCount: number- completedTaskCount: number- elapsedSeconds: number- }) => void- }-): void {- const now = Date.now()- // Tolerate a malformed delivery: reducers already stored the session, and throwing here would- // silently skip the detector/telemetry bookkeeping for this update.- const tasks = session.tasks ?? []- const isTerminalPhase = session.run_phase === 'completed' || session.run_phase === 'error'- if (isSessionFresh(session, now)) {- actions.markSessionCurrent()- // The handoff surface must outlive the stream (the detector gates it off shortly after a- // terminal phase): snapshot fresh terminal runs, and let a fresh run going live supersede- // a previous run's snapshot.- if (isTerminalPhase) {- actions.recordFinishedLocalRun(session)- } else {- actions.supersedeFinishedLocalRun(session.session_id)- }- // Freshness-gated like the rest: a stale row's doc was either seen already or belongs to a- // run nobody is watching. The seen-keys guard makes redeliveries a no-op. Completed only:- // the buttons that reopen the doc are gated on the completed phase, so announcing it for an- // errored run would burn the one auto-open on a dialog the user can never get back to.- if (- session.run_phase === 'completed' &&- typeof session.handoff_text === 'string' &&- session.handoff_text.length > 0- ) {- actions.handoffDocReceived({- key: session.session_id,- text: session.handoff_text,- startedByEmail: session.created_by?.email ?? null,- })- }- // Reach metric: count each live wizard session the sync surfaces, once per session_id.- // Gated on freshness so stale terminal rows sitting in the DB — which never reach the- // user — don't inflate the funnel.- if (!reportedDetectedSessions.has(session.session_id)) {- reportedDetectedSessions.add(session.session_id)- actions.reportWizardSyncSessionDetected({- workflowId,- skillId: session.skill_id,- runPhase: session.run_phase,- taskCount: tasks.length,- })- }- }- // Gate on the detector's shared eligibility predicate (server staleness + lifetime cap +- // terminal phase) so the SSE and REST paths agree on when streaming may continue — a wedged- // CLI heartbeating `updated_at` past the lifetime cap stops re-arming markActive, letting- // teardown actually run. Only schedule teardown on the eligible → ineligible *transition* so- // repeated re-polls don't reset the clock. The detector is mounted by the local instance's- // afterMount, which always precedes this bookkeeping.- const detector = wizardActiveSessionDetectorLogic.findMounted()- if (detector) {- const eligible = isSessionActive(session)- const wasEligible = isSessionActive(prev)- if (eligible) {- detector.actions.markActive(workflowId)- } else if (wasEligible) {- detector.actions.scheduleMarkInactive()- }- }- // Outcome metric: fire once when a run the user watched live reaches a terminal phase.- // Terminal phases are sticky, so this transition is observed at most once per session — the- // id guard covers any SSE redelivery.- if (prev && session.run_phase !== prev.run_phase) {- if (isTerminalPhase && !reportedFinishedSessions.has(session.session_id)) {- reportedFinishedSessions.add(session.session_id)- actions.reportWizardSyncSessionFinished({- workflowId,- skillId: session.skill_id,- outcome: session.run_phase,- errorKind: errorKindFromMessage(sessionErrorMessage(session)),- taskCount: tasks.length,- completedTaskCount: tasks.filter((t) => t.status === 'completed').length,- elapsedSeconds: elapsedSecondsFrom(session.started_at, now),- })- }- }-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.test.tsdeleted file mode 100644index 2e4ba638e807..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.test.ts+++ /dev/null@@ -1,623 +0,0 @@-import { MOCK_TEAM_ID } from 'lib/api.mock'-import { installMockEventSource, MockEventSource } from 'lib/wizard-sync/eventSource.mock'--import { expectLogic } from 'kea-test-utils'--import { ApiError } from 'lib/api-error'-import {- DEFAULT_POLLING_INTERVAL_SECS,- jitteredIntervalMs,- MAX_POLLING_INTERVAL_SECS,- POLL_JITTER_RATIO,- resolvePollingIntervalMs,- SSE_RECONNECT_BASE_MS,- SSE_RECONNECT_MAX_MS,- sseReconnectDelayMs,-} from 'lib/wizard-sync/pollLoop'-import { projectLogic } from 'scenes/projectLogic'--import { initKeaTests } from '~/test/init'--import { tasksActiveWizardRunRetrieve, tasksRunsRetrieve } from 'products/tasks/frontend/generated/api'-import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'--import { activeCloudRunLogic } from './activeCloudRunLogic'-import {- cloudRunCompletionReport,- mergeProgressStep,- NO_STATE_STALL_MS,- parseStreamErrorMessage,- parseTaskRunStreamMessage,- TaskRunProgressStep,- taskRunDetailToStreamState,- taskRunPrUrl,- taskRunStreamLogic,- TaskRunStreamState,-} from './taskRunStreamLogic'--jest.mock('products/tasks/frontend/generated/api', () => ({- getTasksRunsStreamRetrieveUrl: jest.fn(() => '/mock-run-stream'),- tasksRunsRetrieve: jest.fn(),- tasksActiveWizardRunRetrieve: jest.fn(),- tasksRunsCancelCreate: jest.fn(),-}))--const mockActiveWizardRun = tasksActiveWizardRunRetrieve as jest.Mock-const mockRunRetrieve = tasksRunsRetrieve as jest.Mock--function step(overrides: Partial<TaskRunProgressStep> = {}): TaskRunProgressStep {- return {- step: 'clone',- status: 'in_progress',- label: 'Cloning repository',- group: 'setup',- detail: null,- ...overrides,- }-}--function runState(overrides: Partial<TaskRunStreamState> = {}): TaskRunStreamState {- return {- status: 'in_progress',- stage: 'wizard',- output: null,- branch: null,- error_message: null,- updated_at: '2026-01-01T00:05:00Z',- completed_at: null,- ...overrides,- }-}--describe('taskRunStreamLogic helpers', () => {- describe('mergeProgressStep', () => {- it('appends a new step', () => {- expect(mergeProgressStep([], step())).toEqual([step()])- })-- it('updates an existing (group, step) in place, preserving order', () => {- const clone = step({ step: 'clone' })- const wizard = step({ step: 'wizard', label: 'Running wizard' })- const cloneDone = step({ step: 'clone', status: 'completed', label: 'Cloned' })- expect(mergeProgressStep([clone, wizard], cloneDone)).toEqual([cloneDone, wizard])- })-- it('treats the same step name in a different group as distinct', () => {- const inSetup = step({ step: 'open', group: 'setup' })- const inPr = step({ step: 'open', group: 'pr_create' })- expect(mergeProgressStep([inSetup], inPr)).toEqual([inSetup, inPr])- })- })-- describe('parseTaskRunStreamMessage', () => {- it('parses a task_run_state event with all fields', () => {- const raw = JSON.stringify({- type: 'task_run_state',- status: 'failed',- stage: 'wizard',- output: { pr_url: 'https://x/pull/1' },- branch: 'main',- error_message: 'boom',- updated_at: '2026-01-01T00:00:00Z',- completed_at: '2026-01-01T00:01:00Z',- })- expect(parseTaskRunStreamMessage(raw)).toEqual({- kind: 'state',- state: {- status: 'failed',- stage: 'wizard',- output: { pr_url: 'https://x/pull/1' },- branch: 'main',- error_message: 'boom',- updated_at: '2026-01-01T00:00:00Z',- completed_at: '2026-01-01T00:01:00Z',- },- })- })-- it('defaults missing optional task_run_state fields to null', () => {- const raw = JSON.stringify({- type: 'task_run_state',- status: 'in_progress',- updated_at: '2026-01-01T00:00:00Z',- })- expect(parseTaskRunStreamMessage(raw)).toEqual({- kind: 'state',- state: {- status: 'in_progress',- stage: null,- output: null,- branch: null,- error_message: null,- updated_at: '2026-01-01T00:00:00Z',- completed_at: null,- },- })- })-- it('parses a _posthog/progress notification into a step', () => {- const raw = JSON.stringify({- type: 'notification',- notification: {- method: '_posthog/progress',- params: {- step: 'clone',- status: 'in_progress',- label: 'Cloning',- group: 'setup',- detail: 'shallow',- },- },- })- expect(parseTaskRunStreamMessage(raw)).toEqual({- kind: 'step',- step: { step: 'clone', status: 'in_progress', label: 'Cloning', group: 'setup', detail: 'shallow' },- })- })-- it('defaults a step with no detail to null', () => {- const raw = JSON.stringify({- type: 'notification',- notification: {- method: '_posthog/progress',- params: { step: 'clone', status: 'completed', label: 'Cloned', group: 'setup' },- },- })- expect(parseTaskRunStreamMessage(raw)).toEqual({- kind: 'step',- step: { step: 'clone', status: 'completed', label: 'Cloned', group: 'setup', detail: null },- })- })-- it.each([- [- 'a non-progress notification',- { type: 'notification', notification: { method: 'other', params: { step: 'x' } } },- ],- [- 'a progress notification without params',- { type: 'notification', notification: { method: '_posthog/progress' } },- ],- ['a notification without a notification field', { type: 'notification' }],- ['a keepalive', { type: 'keepalive' }],- ['an unknown type', { type: 'whatever' }],- ])('returns null for %s', (_name, payload) => {- expect(parseTaskRunStreamMessage(JSON.stringify(payload))).toBeNull()- })-- it('throws on invalid JSON', () => {- expect(() => parseTaskRunStreamMessage('not json')).toThrow(SyntaxError)- })- })-- describe('resolvePollingIntervalMs', () => {- it.each([- ['a valid payload interval', { polling_interval_secs: 10 }, 10_000],- ['a sub-minimum interval (floored so it cannot hammer the endpoint)', { polling_interval_secs: 0 }, 1000],- ['a negative interval', { polling_interval_secs: -5 }, 1000],- ['a non-numeric interval', { polling_interval_secs: 'fast' }, DEFAULT_POLLING_INTERVAL_SECS * 1000],- ['a missing payload', null, DEFAULT_POLLING_INTERVAL_SECS * 1000],- ['a payload without the key', {}, DEFAULT_POLLING_INTERVAL_SECS * 1000],- [- 'an over-maximum interval (clamped so sync cannot silently stall)',- { polling_interval_secs: 3600 },- MAX_POLLING_INTERVAL_SECS * 1000,- ],- [- 'a huge interval that would overflow the int32 setTimeout delay and fire immediately',- { polling_interval_secs: 1_700_000_000 },- MAX_POLLING_INTERVAL_SECS * 1000,- ],- ])('resolves %s', (_name, payload, expectedMs) => {- expect(resolvePollingIntervalMs(payload)).toBe(expectedMs)- })- })-- describe('sseReconnectDelayMs', () => {- // A CLOSED EventSource never retries natively, so these delays are the only thing standing- // between a dropped stream and a permanently dead run card.- it.each([- ['the first attempt starts at the base', 1, SSE_RECONNECT_BASE_MS],- ['a zero attempt is treated as the first', 0, SSE_RECONNECT_BASE_MS],- ['consecutive attempts back off exponentially', 3, SSE_RECONNECT_BASE_MS * 4],- ['the backoff caps at the ceiling', 10, SSE_RECONNECT_MAX_MS],- ])('%s', (_name, attempt, expectedMs) => {- // Mid-roll jitter resolves to the un-jittered delay.- expect(sseReconnectDelayMs(attempt, () => 0.5)).toBe(expectedMs)- })-- it('jitters the delay so dropped clients do not reconnect in lockstep', () => {- expect(sseReconnectDelayMs(1, () => 0)).toBe(SSE_RECONNECT_BASE_MS * (1 - POLL_JITTER_RATIO))- expect(sseReconnectDelayMs(1, () => 1)).toBe(SSE_RECONNECT_BASE_MS * (1 + POLL_JITTER_RATIO))- })- })-- describe('jitteredIntervalMs', () => {- it.each([- ['the lower jitter bound', 0, 3000 * (1 - POLL_JITTER_RATIO)],- ['the base cadence at mid-roll', 0.5, 3000],- ['the upper jitter bound', 1, 3000 * (1 + POLL_JITTER_RATIO)],- ])('spreads ticks within ±20%% — %s', (_name, roll, expectedMs) => {- expect(jitteredIntervalMs(3000, () => roll)).toBe(expectedMs)- })- })-- describe('taskRunDetailToStreamState', () => {- it('projects a REST snapshot onto the SSE state shape, coercing missing fields to null', () => {- const dto = {- id: 'run-1',- task: 'task-1',- stage: undefined,- branch: undefined,- status: 'in_progress',- environment: 'sandbox',- error_message: null,- output: undefined,- state: {},- artifacts: [],- } as unknown as TaskRunDetailDTOApi- expect(taskRunDetailToStreamState(dto)).toEqual({- status: 'in_progress',- stage: null,- output: null,- branch: null,- error_message: null,- updated_at: '',- completed_at: null,- })- })-- it('carries the terminal fields the completion report depends on', () => {- const dto = {- id: 'run-1',- task: 'task-1',- stage: 'pr',- branch: 'posthog-setup',- status: 'completed',- environment: 'sandbox',- error_message: null,- output: { pr_url: 'https://x/pull/1' },- state: {},- artifacts: [],- updated_at: '2026-01-01T00:05:00Z',- completed_at: '2026-01-01T00:04:30Z',- } as unknown as TaskRunDetailDTOApi- expect(taskRunDetailToStreamState(dto)).toEqual({- status: 'completed',- stage: 'pr',- output: { pr_url: 'https://x/pull/1' },- branch: 'posthog-setup',- error_message: null,- updated_at: '2026-01-01T00:05:00Z',- completed_at: '2026-01-01T00:04:30Z',- })- })- })-- describe('parseStreamErrorMessage', () => {- // The browser dispatches transport failures under the same `error` name, so a payload that- // does not carry a message must not be mistaken for the server giving up on the stream.- it.each([- ['the server error payload', '{"error": "Stream not available"}', 'Stream not available'],- ['a payload without an error field', '{"type": "task_run_state"}', null],- ['a non-string error field', '{"error": 42}', null],- ['invalid JSON', 'not json', null],- ])('reads %s', (_name, rawData, expected) => {- expect(parseStreamErrorMessage(rawData)).toBe(expected)- })- })-- describe('taskRunPrUrl', () => {- it('prefers the terminal output url over the pr progress step', () => {- const state = runState({ output: { pr_url: 'https://x/pull/2' } })- const steps = [step({ step: 'pr', group: 'pr_create', detail: 'https://x/pull/1' })]- expect(taskRunPrUrl(state, steps)).toBe('https://x/pull/2')- })-- it('falls back to the pr progress step detail when the output has no url', () => {- const steps = [step({ step: 'pr', group: 'pr_create', detail: 'https://x/pull/1' })]- expect(taskRunPrUrl(runState(), steps)).toBe('https://x/pull/1')- })-- it('ignores a pr step whose detail is not a url', () => {- const steps = [step({ step: 'pr', group: 'pr_create', detail: 'Opening a pull request' })]- expect(taskRunPrUrl(runState(), steps)).toBeNull()- })-- it('returns null with no state and no pr step', () => {- expect(taskRunPrUrl(null, [step()])).toBeNull()- })- })-- describe('cloudRunCompletionReport', () => {- const startedAt = '2026-01-01T00:00:00Z'-- it('reports an observed transition into completed, with duration and the PR', () => {- const report = cloudRunCompletionReport(- runState({ status: 'in_progress' }),- runState({- status: 'completed',- output: { pr_url: 'https://x/pull/1' },- completed_at: '2026-01-01T00:04:30Z',- }),- [],- startedAt- )- expect(report).toEqual({- status: 'completed',- durationSeconds: 270,- prOpened: true,- prUrl: 'https://x/pull/1',- })- })-- it('reports a failed run with no PR opened', () => {- const report = cloudRunCompletionReport(- runState({ status: 'in_progress' }),- runState({ status: 'failed', error_message: 'boom', completed_at: '2026-01-01T00:04:30Z' }),- [],- startedAt- )- expect(report).toEqual({ status: 'failed', durationSeconds: 270, prOpened: false, prUrl: null })- })-- it('takes the PR url from the pr progress step when the output lacks one', () => {- const report = cloudRunCompletionReport(- runState({ status: 'in_progress' }),- runState({ status: 'completed', completed_at: '2026-01-01T00:04:30Z' }),- [step({ step: 'pr', group: 'pr_create', detail: 'https://x/pull/1' })],- startedAt- )- expect(report).toMatchObject({ prOpened: true, prUrl: 'https://x/pull/1' })- })-- it('falls back to updated_at for the duration when completed_at is missing', () => {- const report = cloudRunCompletionReport(- runState({ status: 'in_progress' }),- runState({ status: 'cancelled', updated_at: '2026-01-01T00:02:00Z' }),- [],- startedAt- )- expect(report).toMatchObject({ status: 'cancelled', durationSeconds: 120 })- })-- it('reports a null duration without a kickoff timestamp', () => {- const report = cloudRunCompletionReport(- runState({ status: 'in_progress' }),- runState({ status: 'completed', completed_at: '2026-01-01T00:04:30Z' }),- [],- undefined- )- expect(report).toMatchObject({ durationSeconds: null })- })-- it.each([- ['the update is not terminal', runState({ status: 'in_progress' }), runState({ status: 'queued' })],- // A stream (re)connecting to a finished run replays the terminal state with no prior- // observation — the backend task_run_* events cover unwatched completions.- ['no previous state was observed', null, runState({ status: 'completed' })],- [- 'the previous state was already terminal',- runState({ status: 'completed' }),- runState({ status: 'completed' }),- ],- ])('returns null when %s', (_name, previous, state) => {- expect(cloudRunCompletionReport(previous, state, [], startedAt)).toBeNull()- })- })-})--// The first backoff step is 2s ±20%, so this window always contains the retry and never the second-// step's (4s -20% = 3.2s).-const PAST_FIRST_RECONNECT_MS = 2600-const RUN_STARTED_AT = '2026-01-01T00:00:00Z'--describe('taskRunStreamLogic transport', () => {- let logic: ReturnType<typeof taskRunStreamLogic.build>- let restoreEventSource: () => void- let mounted = false-- beforeEach(async () => {- // The run handle is persisted to localStorage, so a leftover from another test would decide- // whether this run is the active one.- window.localStorage.clear()- initKeaTests()- // Reconciliation must confirm the run under test, or it would clear the handle mid-test and- // the stream would refuse to connect.- mockActiveWizardRun.mockResolvedValue({- task_id: 'task-1',- run_id: 'run-1',- status: 'in_progress',- started_at: RUN_STARTED_AT,- })- mockRunRetrieve.mockReset()- restoreEventSource = installMockEventSource()- logic = taskRunStreamLogic({ taskId: 'task-1', runId: 'run-1' })- logic.mount()- mounted = true- activeCloudRunLogic.actions.setActiveCloudRun('task-1', 'run-1', RUN_STARTED_AT, MOCK_TEAM_ID)- await expectLogic(projectLogic).toMatchValues({ currentProjectId: MOCK_TEAM_ID })- jest.useFakeTimers()- })-- afterEach(() => {- if (mounted) {- logic.unmount()- mounted = false- }- jest.useRealTimers()- restoreEventSource()- })-- it('reconnects after a fatal close, which the browser never retries on its own', async () => {- logic.actions.connect()- MockEventSource.last().emitOpen()- await expectLogic(logic).toDispatchActions(['connectionOpened'])-- MockEventSource.last().emitTransportError(MockEventSource.CLOSED)- await expectLogic(logic).toDispatchActions(['connectionErrored'])- expect(MockEventSource.instances).toHaveLength(1)-- jest.advanceTimersByTime(PAST_FIRST_RECONNECT_MS)- await expectLogic(logic).toDispatchActions(['connect'])- expect(MockEventSource.instances).toHaveLength(2)- })-- it('backs off between consecutive fatal closes', async () => {- logic.actions.connect()- MockEventSource.last().emitTransportError(MockEventSource.CLOSED)- await expectLogic(logic).toDispatchActions(['connectionErrored'])- jest.advanceTimersByTime(PAST_FIRST_RECONNECT_MS)- expect(MockEventSource.instances).toHaveLength(2)-- // No successful open in between, so the second attempt waits out the doubled window.- MockEventSource.last().emitTransportError(MockEventSource.CLOSED)- await expectLogic(logic).toDispatchActions(['connectionErrored'])- jest.advanceTimersByTime(PAST_FIRST_RECONNECT_MS)- expect(MockEventSource.instances).toHaveLength(2)-- jest.advanceTimersByTime(SSE_RECONNECT_MAX_MS)- expect(MockEventSource.instances).toHaveLength(3)- })-- it('leaves a transient drop to the browser, which retries it natively', async () => {- logic.actions.connect()- MockEventSource.last().emitOpen()- await expectLogic(logic).toDispatchActions(['connectionOpened'])-- MockEventSource.last().emitTransportError(MockEventSource.CONNECTING)- await expectLogic(logic).toDispatchActions(['connectionErrored'])-- jest.advanceTimersByTime(SSE_RECONNECT_MAX_MS)- expect(MockEventSource.instances).toHaveLength(1)- })-- it('cancels a pending reconnect on disconnect', async () => {- logic.actions.connect()- MockEventSource.last().emitTransportError(MockEventSource.CLOSED)- await expectLogic(logic).toDispatchActions(['connectionErrored'])-- logic.actions.disconnect()- jest.advanceTimersByTime(SSE_RECONNECT_MAX_MS)- expect(MockEventSource.instances).toHaveLength(1)- })-- it('cancels a pending reconnect on unmount', async () => {- logic.actions.connect()- MockEventSource.last().emitTransportError(MockEventSource.CLOSED)- await expectLogic(logic).toDispatchActions(['connectionErrored'])-- logic.unmount()- mounted = false- jest.advanceTimersByTime(SSE_RECONNECT_MAX_MS)- expect(MockEventSource.instances).toHaveLength(1)- })-- // The run-detail fallback resolves outside kea, so its dispatches land a few microtasks after- // the event that triggered it.- const flushFallback = async (): Promise<void> => {- for (let i = 0; i < 5; i++) {- await Promise.resolve()- }- }-- const runDetail = (overrides: Record<string, unknown> = {}): TaskRunDetailDTOApi =>- ({- id: 'run-1',- status: 'in_progress',- stage: null,- output: null,- branch: null,- error_message: null,- updated_at: '2026-01-01T00:05:00Z',- completed_at: null,- ...overrides,- }) as unknown as TaskRunDetailDTOApi-- it('settles a finished run from its detail when the server has no stream to serve', async () => {- mockRunRetrieve.mockResolvedValue(- runDetail({ status: 'completed', completed_at: '2026-01-01T00:06:00Z', output: { pr_url: 'https://x/1' } })- )- logic.actions.connect()- MockEventSource.last().emitOpen()- await expectLogic(logic).toDispatchActions(['connectionOpened'])-- // A named `error` event carries a payload; a transport failure does not. Only the former- // means the server gave up waiting for the run's stream key.- MockEventSource.last().emitNamed('error', '{"error": "Stream not available"}')- await flushFallback()-- expect(mockRunRetrieve).toHaveBeenCalledWith(String(MOCK_TEAM_ID), 'task-1', 'run-1')- expect(logic.values.taskRunState).toMatchObject({ status: 'completed' })- expect(logic.values.isComplete).toBe(true)- // Nothing more will ever be published for a finished run, so no retry is scheduled either.- jest.advanceTimersByTime(SSE_RECONNECT_MAX_MS)- expect(MockEventSource.instances).toHaveLength(1)- })-- it('reconnects when the stream is unavailable but the run is still live', async () => {- mockRunRetrieve.mockResolvedValue(runDetail({ status: 'in_progress' }))- logic.actions.connect()- MockEventSource.last().emitNamed('error', '{"error": "Stream not available"}')- await flushFallback()-- expect(logic.values.taskRunState).toMatchObject({ status: 'in_progress' })- jest.advanceTimersByTime(PAST_FIRST_RECONNECT_MS)- expect(MockEventSource.instances).toHaveLength(2)- })-- it('marks the stream dead when the run detail is gone for good', async () => {- mockRunRetrieve.mockRejectedValue(new ApiError('not found', 404))- logic.actions.connect()- MockEventSource.last().emitNamed('error', '{"error": "Stream not available"}')- await flushFallback()-- expect(logic.values.isStalled).toBe(true)- // A deleted or access-revoked run is not worth retrying.- jest.advanceTimersByTime(SSE_RECONNECT_MAX_MS)- expect(MockEventSource.instances).toHaveLength(1)- })-- it('reports a stall when the stream delivers no state at all', async () => {- logic.actions.connect()- MockEventSource.last().emitOpen()- await expectLogic(logic).toDispatchActions(['connectionOpened'])-- jest.advanceTimersByTime(NO_STATE_STALL_MS)- expect(logic.values.isStalled).toBe(true)- })-- it('stamps lastActivityAt from delivered updates, never from connection events', async () => {- logic.actions.connect()- const stream = MockEventSource.last()- stream.emitOpen()- await expectLogic(logic).toDispatchActions(['connectionOpened'])- // A stream that reconnects forever without ever saying anything must not read as a run that- // is alive: only what the pipeline actually delivers counts as activity.- expect(logic.values.lastActivityAt).toBeNull()-- stream.emitMessage(- JSON.stringify({ type: 'task_run_state', status: 'in_progress', updated_at: '2026-01-01T00:05:00Z' })- )- await expectLogic(logic).toDispatchActions(['taskRunStateUpdated'])- expect(logic.values.lastActivityAt).toEqual(expect.any(Number))- })-- it('keeps the no-state stall through a scheduled reconnect', async () => {- // The regression: a reconnect clears isStalled, and a per-connect timer would be re-armed- // for another full window (or, armed once per lifetime, never re-armed at all), putting the- // surfaces back on the eternal spinner with no way out.- logic.actions.connect()- MockEventSource.last().emitOpen()- jest.advanceTimersByTime(NO_STATE_STALL_MS)- expect(logic.values.isStalled).toBe(true)-- mockRunRetrieve.mockRejectedValue(new Error('network hiccup'))- MockEventSource.last().emitNamed('error', '{"error": "Stream not available"}')- await flushFallback()- jest.advanceTimersByTime(PAST_FIRST_RECONNECT_MS)-- expect(MockEventSource.instances).toHaveLength(2)- expect(logic.values.isStalled).toBe(true)- })-})diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.tsdeleted file mode 100644index a619bd819bea..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts+++ /dev/null@@ -1,635 +0,0 @@-import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'--import { isPermanentPollError, sseReconnectDelayMs } from 'lib/wizard-sync/pollLoop'-import { logSyncDebug } from 'lib/wizard-sync/wizardSyncDebugLogic'-import { projectLogic } from 'scenes/projectLogic'--import { getTasksRunsStreamRetrieveUrl, tasksRunsRetrieve } from 'products/tasks/frontend/generated/api'-import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'--import { onboardingEventUsageLogic } from '../../onboardingEventUsageLogic'-import { activeCloudRunLogic } from './activeCloudRunLogic'-import type { CloudRunHandle } from './activeCloudRunLogic'--export type TaskRunConnectionStatus = 'idle' | 'connecting' | 'open' | 'closed' | 'error'--// How long a run may sit in `queued` before we call it stalled. Workers normally pick a run up in-// seconds; minutes of silence means the pipeline isn't running at all.-export const QUEUED_STALL_MS = 2 * 60 * 1000--// How long the stream may stay connected without delivering ANY run state before we give up. A-// deleted or access-revoked run, a stream key that never materializes, or a transport stuck in a-// reconnect loop would otherwise leave surfaces spinning on `idle` indefinitely. Longer than the-// server's own wait for a missing stream key, so a slow-to-start run gets one full server-side-// wait plus reconnect slack. The first state event disarms it.-export const NO_STATE_STALL_MS = 4 * 60 * 1000--// Payload of the stream's named `error` events (e.g. {"error": "Stream not available"} once the-// server gives up waiting for the run's stream key). Returns the message, or null when the data is-// not such a payload.-export function parseStreamErrorMessage(rawData: string): string | null {- try {- const payload = JSON.parse(rawData) as { error?: unknown }- return typeof payload.error === 'string' ? payload.error : null- } catch {- return null- }-}--// Project the REST run snapshot onto the same shape the SSE `task_run_state` events carry, so the-// stream and the run-detail fallback feed `taskRunStateUpdated` identically and the rest of the-// logic stays transport-agnostic.-export function taskRunDetailToStreamState(dto: TaskRunDetailDTOApi): TaskRunStreamState {- return {- status: dto.status,- stage: dto.stage ?? null,- output: (dto.output as { pr_url?: string | null; pr_merged?: boolean | null } | null) ?? null,- branch: dto.branch ?? null,- error_message: dto.error_message ?? null,- updated_at: dto.updated_at ?? '',- completed_at: dto.completed_at ?? null,- }-}--/**- * Shapes of the SSE payloads the task-run stream pushes (see the tasks stream view). These are stream- * messages, not REST serializers, so they're typed here rather than imported from the generated client.- */-export interface TaskRunStreamState {- status: string // queued | in_progress | completed | failed | cancelled- stage: string | null- output: { pr_url?: string | null; pr_merged?: boolean | null } | null- branch: string | null- error_message: string | null- updated_at: string- completed_at: string | null-}--export interface TaskRunProgressStep {- step: string- status: string // in_progress | completed | failed | ...- label: string- group: string- detail: string | null-}--export interface TaskRunStreamLogicProps {- taskId: string- runId: string-}--export type TaskRunStreamMessage =- | { kind: 'state'; state: TaskRunStreamState }- | { kind: 'step'; step: TaskRunProgressStep }--// Merge a progress step into the list: last-write-wins per (group, step), preserving arrival order.-export function mergeProgressStep(steps: TaskRunProgressStep[], step: TaskRunProgressStep): TaskRunProgressStep[] {- const idx = steps.findIndex((s) => s.step === step.step && s.group === step.group)- if (idx === -1) {- return [...steps, step]- }- const next = [...steps]- next[idx] = step- return next-}--// Parse one SSE data payload into a typed message, or null if it isn't one we act on (keepalive, a-// non-progress notification, an unknown type). Throws on invalid JSON — the caller surfaces that.-export function parseTaskRunStreamMessage(rawData: string): TaskRunStreamMessage | null {- const payload = JSON.parse(rawData) as TaskRunStreamState & {- type?: string- notification?: { method?: string; params?: TaskRunProgressStep }- }- if (payload.type === 'notification') {- const params = payload.notification?.params- if (payload.notification?.method !== '_posthog/progress' || !params) {- return null- }- return {- kind: 'step',- step: {- step: params.step,- status: params.status,- label: params.label,- group: params.group,- detail: params.detail ?? null,- },- }- }- if (payload.type === 'task_run_state') {- return {- kind: 'state',- state: {- status: payload.status,- stage: payload.stage ?? null,- output: payload.output ?? null,- branch: payload.branch ?? null,- error_message: payload.error_message ?? null,- updated_at: payload.updated_at,- completed_at: payload.completed_at ?? null,- },- }- }- return null-}--export const TERMINAL_TASK_RUN_STATUSES = ['completed', 'failed', 'cancelled'] as const-export type TerminalTaskRunStatus = (typeof TERMINAL_TASK_RUN_STATUSES)[number]--function isTerminalStatus(status: string): status is TerminalTaskRunStatus {- return (TERMINAL_TASK_RUN_STATUSES as readonly string[]).includes(status)-}--// The agent opens the PR mid-run (while it keeps CI green), so the url arrives via the "pr" progress-// step before the run reaches a terminal output. Prefer the terminal output when present.-export function taskRunPrUrl(state: TaskRunStreamState | null, steps: TaskRunProgressStep[]): string | null {- // Both sources originate from agent output over the stream — only ever surface http(s) URLs.- const outputUrl = state?.output?.pr_url- const prStepUrl = steps.find((s) => s.step === 'pr')?.detail- return (- (outputUrl && outputUrl.startsWith('http') ? outputUrl : null) ??- (prStepUrl && prStepUrl.startsWith('http') ? prStepUrl : null)- )-}--export function taskRunPrMerged(state: TaskRunStreamState | null): boolean {- return state?.output?.pr_merged === true-}--export interface CloudRunCompletionReport {- status: TerminalTaskRunStatus- durationSeconds: number | null- prOpened: boolean- prUrl: string | null-}--/**- * The v2 onboarding funnel's terminal cloud-run event (GROW-89), or null when this state update is- * not one to report. Only an OBSERVED transition into a terminal status counts: a stream that- * (re)connects to an already-finished run replays that state, and reporting it would double-count- * the run — the backend `task_run_completed` / `task_run_failed` events already cover runs that- * finish while nobody is watching.- */-export function cloudRunCompletionReport(- previous: TaskRunStreamState | null,- state: TaskRunStreamState,- progressSteps: TaskRunProgressStep[],- startedAt: string | undefined-): CloudRunCompletionReport | null {- if (!isTerminalStatus(state.status) || !previous || isTerminalStatus(previous.status)) {- return null- }- // Duration since kickoff (the handle's startedAt) — the stream carries no started_at of its own.- // The backend's `duration_seconds` (created_at → completed_at) stays the authoritative figure.- const endedAt = state.completed_at ?? state.updated_at- const elapsedMs = startedAt && endedAt ? new Date(endedAt).getTime() - new Date(startedAt).getTime() : NaN- const durationSeconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.round(elapsedMs / 1000)) : null- const prUrl = taskRunPrUrl(state, progressSteps)- return { status: state.status, durationSeconds, prOpened: !!prUrl, prUrl }-}--// Terminal outcomes already reported this pageload, keyed by run id. Guards against a re-observed-// transition (e.g. the stream replaying history after a remount) double-counting a run. Mirrors the-// wizard tracker's once-per-session report guards.-const reportedTerminalRuns = new Set<string>()--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface taskRunStreamLogicValues {- activeCloudRun: CloudRunHandle | null // activeCloudRunLogic- currentProjectId: number | null // projectLogic- connectionStatus: TaskRunConnectionStatus- isComplete: boolean- isStalled: boolean- lastActivityAt: number | null- lastError: string | null- progressSteps: TaskRunProgressStep[]- taskRunState: TaskRunStreamState | null-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface taskRunStreamLogicActions {- reportOnboardingCloudRunCompleted: (props: {- durationSeconds: number | null- prOpened: boolean- prUrl: string | null- runId: string- status: 'cancelled' | 'completed' | 'failed'- taskId: string- }) => {- durationSeconds: number | null- prOpened: boolean- prUrl: string | null- runId: string- status: 'cancelled' | 'completed' | 'failed'- taskId: string- } // onboardingEventUsageLogic- connect: () => {- value: true- }- connectionErrored: (error: string) => {- error: string- }- connectionOpened: () => {- value: true- }- connectionSkipped: () => {- value: true- }- disconnect: () => {- value: true- }- progressStepUpdated: (step: TaskRunProgressStep) => {- step: TaskRunProgressStep- }- runStalled: () => {- value: true- }- streamCompleted: () => {- value: true- }- taskRunStateUpdated: (state: TaskRunStreamState) => {- state: TaskRunStreamState- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface taskRunStreamLogicMeta {- key: string-}--export type taskRunStreamLogicType = MakeLogicType<- taskRunStreamLogicValues,- taskRunStreamLogicActions,- TaskRunStreamLogicProps,- taskRunStreamLogicMeta->--/**- * Raw SSE consumer for a single TaskRun (the cloud-run pipeline: provision → clone → wizard → agent →- * PR). A private source for the Installation layer — `installationProgressLogic` merges this with the- * wizard session stream and exposes a single `InstallationProgress`. Keyed per run so multiple coexist.- *- * Data events (`task_run_state`, `_posthog/progress` notifications) arrive unnamed via `onmessage`;- * `stream-end` closes the stream; rotation (`end`) and transient drops are handled by EventSource's- * native reconnect (it replays the `Last-Event-ID` cursor the server stamps on every event). Fatal- * closes (readyState CLOSED, e.g. any non-200 on a (re)connect) never retry natively, so the logic- * schedules its own backed-off reconnect, per the posthog/api/streaming.py consumer contract. A named- * `error` event means the server has no stream to serve, so the run is settled from its REST detail- * instead; a stream that stays silent past NO_STATE_STALL_MS is reported stalled.- *- * When the `onboarding-wizard-sync-mode` flag resolves to `polling` (GROW-118), the EventSource is- * replaced by an interval that re-fetches the run's REST snapshot and feeds it through the same- * `taskRunStateUpdated` action. Polling carries run state only — `_posthog/progress` step- * notifications are stream-borne, so the step timeline stays empty and surfaces degrade to the- * coarse run status. The interval comes from the flag payload's `polling_interval_secs`.- */-export const taskRunStreamLogic = kea<taskRunStreamLogicType>([- props({} as TaskRunStreamLogicProps),- key((props) => props.runId),- path((key) => ['scenes', 'onboarding', 'taskRunStreamLogic', key]),- connect(() => ({- values: [projectLogic, ['currentProjectId'], activeCloudRunLogic, ['activeCloudRun']],- actions: [onboardingEventUsageLogic, ['reportOnboardingCloudRunCompleted']],- })),- actions({- connect: true,- disconnect: true,- taskRunStateUpdated: (state: TaskRunStreamState) => ({ state }),- progressStepUpdated: (step: TaskRunProgressStep) => ({ step }),- connectionOpened: true,- connectionErrored: (error: string) => ({ error }),- // Connect was requested but this run isn't the project's active cloud run — observable so- // surfaces render idle instead of an eternal "connecting" spinner.- connectionSkipped: true,- streamCompleted: true,- runStalled: true,- }),- reducers({- taskRunState: [- null as TaskRunStreamState | null,- {- // Reconnects (tab-visibility resume) replay historical state events; PR facts only- // move forward, so a replayed pre-merge state must not regress them mid-replay.- taskRunStateUpdated: (prev, { state }) => {- if (!prev?.output) {- return state- }- const output = { ...state.output }- // A state event that replaces the PR (resumed run, new branch) carries its own- // url; don't drag the prior PR's merge onto it. Pin only while the url matches.- if (output.pr_url && prev.output.pr_url && output.pr_url !== prev.output.pr_url) {- return { ...state, output }- }- if (prev.output.pr_url && !output.pr_url) {- output.pr_url = prev.output.pr_url- }- if (prev.output.pr_merged && !output.pr_merged) {- output.pr_merged = prev.output.pr_merged- }- return { ...state, output }- },- },- ],- // When the stream last delivered anything about the run, on the client's clock. Deliberately- // not derived from the run's own `updated_at`, which the backend only moves on status and- // stage transitions, so a reconnect replaying an old state would read as fresh news. Nor- // from connection events, or a stream that reconnects forever without ever saying anything- // would keep looking healthy. Note this goes quiet on a perfectly healthy run: the pipeline- // publishes nothing through the agent phase, so silence alone is never enough to judge a run- // dead (see isRunStale, which also requires the transport to be down).- lastActivityAt: [- null as number | null,- {- taskRunStateUpdated: () => Date.now(),- progressStepUpdated: () => Date.now(),- },- ],- // Last-write-wins per (group, step), kept in arrival order so the UI renders a stable timeline.- progressSteps: [- [] as TaskRunProgressStep[],- {- progressStepUpdated: (state, { step }) => mergeProgressStep(state, step),- },- ],- connectionStatus: [- 'idle' as TaskRunConnectionStatus,- {- connect: () => 'connecting',- connectionOpened: () => 'open',- connectionErrored: () => 'error',- connectionSkipped: () => 'idle',- disconnect: () => 'closed',- streamCompleted: () => 'closed',- },- ],- isComplete: [- false,- {- streamCompleted: () => true,- },- ],- lastError: [- null as string | null,- {- connect: () => null,- taskRunStateUpdated: () => null,- connectionErrored: (_, { error }) => error,- },- ],- // The run is stuck: either it sat in `queued` past the stall window (the backend never picked- // it up, e.g. no Temporal worker is running) or the stream stayed silent past- // NO_STATE_STALL_MS without ever delivering state. Surfaces render this as a failure instead- // of an eternal spinner. Cleared as soon as the run reports any non-queued state.- isStalled: [- false,- {- runStalled: () => true,- taskRunStateUpdated: (state, { state: runState }) => (runState.status === 'queued' ? state : false),- connect: () => false,- },- ],- }),- listeners(({ values, actions, props, cache, selectors }) => ({- taskRunStateUpdated: ({ state }, _breakpoint, _action, previousState) => {- // The run's terminal state flows through here no matter which surface is watching (inline- // install view, sources step, FAB, sidebar button), so this is where the funnel's cloud-run- // outcome is reported (GROW-89) — the keyed logic dedupes concurrent surfaces to one listener.- const previous = selectors.taskRunState(previousState)- // startedAt travels on the persisted run handle; ignore it if the handle is a different run.- const startedAt = values.activeCloudRun?.runId === props.runId ? values.activeCloudRun.startedAt : undefined- const report = cloudRunCompletionReport(previous, state, values.progressSteps, startedAt)- if (report && !reportedTerminalRuns.has(props.runId)) {- reportedTerminalRuns.add(props.runId)- actions.reportOnboardingCloudRunCompleted({- taskId: props.taskId,- runId: props.runId,- ...report,- })- }- // State arrived, so this run is not the "nothing ever came back" case whatever its status.- cache.disposables.dispose('no-state-stall')- // Arm a stall timer while the run reports `queued`; any other status disarms it. The timer- // rides disposables so unmount (and tab-hide) tears it down with everything else.- if (state.status !== 'queued') {- cache.disposables.dispose('queued-stall')- return- }- if (values.isStalled) {- return- }- cache.disposables.add(() => {- const timer = window.setTimeout(() => actions.runStalled(), QUEUED_STALL_MS)- return () => window.clearTimeout(timer)- }, 'queued-stall')- },- connect: () => {- // A connect (manual or scheduled) supersedes any pending reconnect timer, so the two can- // never race a second stream open.- cache.disposables.dispose('task-run-reconnect')- // Whether this is a scheduled retry of a failed cycle or a fresh attempt (mount, or a- // surface asking to reconnect). Only the latter earns a new no-state window below.- const resumingCycle = cache.reconnectScheduled === true- cache.reconnectScheduled = false- // No run to stream — the Installation layer connects this source even in local mode (where- // there's no TaskRun), so stay idle rather than opening a stream to a non-existent run.- if (!props.runId) {- return- }- const projectId = values.currentProjectId- if (projectId === null) {- actions.connectionErrored('No current project, cannot open task run stream.')- return- }- // Defense in depth: only sync while this run is the project's active cloud run. If the- // persisted handle is gone (dismissed, superseded) or belongs to another run, no wizard- // run is happening for this key — never hold a background stream/poll open for it.- if (values.activeCloudRun?.runId !== props.runId) {- logSyncDebug(`run ${props.runId.slice(0, 8)}`, 'connect', 'skipped: not the active cloud run')- actions.connectionSkipped()- return- }-- // SSE only, deliberately NOT governed by the onboarding-wizard-sync-mode flag: that flag- // controls the WIZARD SESSION transport (whose infra can't take SSE fan-out yet, see- // wizardSessionStreamLogic), while the per-run TaskRun stream is low-cardinality — one- // connection per active cloud run — and its REST detail carries no progress steps, so a- // polled fallback would render an empty pipeline. Cloud runs must work with the session- // transport in either mode, so the two transports stay independent.- const debugSource = `run ${props.runId.slice(0, 8)}`-- logSyncDebug(debugSource, 'connect', 'opening EventSource', { mode: 'sse' })- cache.disposables.add((): (() => void) => {- const url = getTasksRunsStreamRetrieveUrl(String(projectId), props.taskId, props.runId)- const eventSource = new EventSource(url, { withCredentials: true })-- eventSource.onopen = (): void => {- // Mode rides along here too: the connect event can predate the debug panel's- // mount (and get dropped), but open/events always land after it.- logSyncDebug(debugSource, 'open', 'SSE connection open', { mode: 'sse' })- cache.sseReconnectAttempt = 0- actions.connectionOpened()- }- eventSource.onmessage = (event: MessageEvent<string>): void => {- try {- const message = parseTaskRunStreamMessage(event.data)- if (message?.kind === 'step') {- logSyncDebug(- debugSource,- 'event',- `step ${message.step.group}/${message.step.step} → ${message.step.status}`- )- actions.progressStepUpdated(message.step)- } else if (message?.kind === 'state') {- logSyncDebug(- debugSource,- 'event',- `state → ${message.state.status}${message.state.stage ? `/${message.state.stage}` : ''}`- )- actions.taskRunStateUpdated(message.state)- } else {- logSyncDebug(debugSource, 'event', 'message ignored (keepalive/unknown type)')- }- } catch (err) {- logSyncDebug(debugSource, 'error', `failed to parse SSE payload: ${String(err)}`)- actions.connectionErrored(`Failed to parse SSE payload: ${String(err)}`)- }- }- // Completion sentinel. Dispose the whole disposable (which closes the EventSource)- // rather than just closing: a registered-but-closed source would otherwise be- // reopened by the disposables plugin on tab-visibility resume.- eventSource.addEventListener('stream-end', () => {- logSyncDebug(debugSource, 'complete', 'stream-end received')- actions.streamCompleted()- cache.disposables.dispose('task-run-sync')- })- const scheduleReconnect = (reason: string): void => {- // The run-detail fallback can resolve after an unmount, and there is no stream- // left to reconnect once the logic is gone.- if (cache.disposables.isDisposed) {- return- }- const attempt = ((cache.sseReconnectAttempt as number | undefined) ?? 0) + 1- cache.sseReconnectAttempt = attempt- const delayMs = sseReconnectDelayMs(attempt)- const suffix = `reconnecting in ~${Math.round(delayMs / 1000)}s`- logSyncDebug(debugSource, 'error', `${reason}, ${suffix}`)- actions.connectionErrored(`${reason}, ${suffix}`)- // The timer rides disposables so an unmount tears it down, and a hidden tab- // pauses it instead of reconnecting in the background.- cache.disposables.add(() => {- const timer = window.setTimeout(() => {- // Marks the connect as a continuation of this failed cycle, not a fresh- // attempt: the no-state deadline below must not move with every retry.- cache.reconnectScheduled = true- actions.connect()- }, delayMs)- return () => window.clearTimeout(timer)- }, 'task-run-reconnect')- }-- // One recovery per opened stream: the server may emit its error event more than once- // before the close lands, and the run detail only needs fetching once.- let recovering = false- const recoverFromStreamError = (reason: string): void => {- if (recovering) {- return- }- recovering = true- // The server closes cleanly right after this event, which the browser would answer- // by reconnecting into the same wait indefinitely. Drop the transport and settle the- // run from its REST snapshot instead.- cache.disposables.dispose('task-run-sync')- void (async () => {- try {- const detail = await tasksRunsRetrieve(String(projectId), props.taskId, props.runId)- const state = taskRunDetailToStreamState(detail)- logSyncDebug(debugSource, 'event', `run detail → ${state.status} (stream unavailable)`)- actions.taskRunStateUpdated(state)- if (isTerminalStatus(state.status)) {- // Nothing further will ever be published for a finished run.- actions.streamCompleted()- return- }- scheduleReconnect(reason)- } catch (err) {- if (isPermanentPollError(err)) {- // Deleted run, or access revoked: the stream is dead for good, so stop- // retrying and let the surfaces offer retry/dismiss.- logSyncDebug(debugSource, 'error', `run detail unavailable: ${String(err)}`)- actions.runStalled()- actions.connectionErrored(reason)- return- }- scheduleReconnect(reason)- }- })()- }-- // Both the server's named `error` event and the browser's transport failures dispatch- // under the name `error`; only the former is a MessageEvent carrying a payload, so- // `data` is what tells them apart.- eventSource.addEventListener('error', (event: Event): void => {- const rawData = (event as MessageEvent<unknown>).data- if (typeof rawData === 'string') {- recoverFromStreamError(parseStreamErrorMessage(rawData) ?? 'Stream unavailable')- return- }- // CLOSED → browser gave up (any non-200 on a (re)connect lands here and it will- // never retry on its own), so schedule our own reconnect with backoff; anything- // else → it's already retrying (rides the Last-Event-ID cursor), so just surface- // "reconnecting".- if (eventSource.readyState === EventSource.CLOSED) {- scheduleReconnect('EventSource connection closed')- } else {- logSyncDebug(debugSource, 'error', 'SSE transport error, reconnecting')- actions.connectionErrored('EventSource transport error, reconnecting')- }- })-- return () => eventSource.close()- }, 'task-run-sync')-- // Give up if the stream never delivers ANY run state (see NO_STATE_STALL_MS). The- // deadline is absolute, not a fresh window per connect: a transport stuck in a reconnect- // loop retries faster than the window is long, so a per-connect timer would be pushed- // back forever and never trip. A fresh attempt does get a fresh window, since it is a- // real chance for the run to report. The first state event disarms the whole thing.- if (!values.taskRunState) {- if (!resumingCycle || cache.noStateDeadline === undefined) {- cache.noStateDeadline = Date.now() + NO_STATE_STALL_MS- }- const remainingMs = (cache.noStateDeadline as number) - Date.now()- if (remainingMs <= 0) {- // Past the deadline with nothing to show for it, and the reducer cleared- // `isStalled` on the way into this listener. Re-report it now: waiting on a timer- // that has already expired would drop the surfaces back to an eternal spinner.- actions.runStalled()- } else {- cache.disposables.add(() => {- const timer = window.setTimeout(() => {- cache.disposables.dispose('no-state-stall')- if (values.taskRunState) {- return- }- // Nothing is coming. Drop any pending reconnect too: the retry loop is- // not what is going to fix this, and the surfaces now offer their own.- cache.disposables.dispose('task-run-reconnect')- actions.runStalled()- }, remainingMs)- return () => window.clearTimeout(timer)- }, 'no-state-stall')- }- }- },- disconnect: () => {- // Tolerant of an empty/absent runId: local mode builds this logic with runId ''.- logSyncDebug(`run ${String(props.runId ?? '').slice(0, 8)}`, 'disconnect', 'disconnected')- cache.disposables.dispose('task-run-sync')- cache.disposables.dispose('task-run-reconnect')- cache.disposables.dispose('queued-stall')- cache.disposables.dispose('no-state-stall')- // The next connect is a new attempt, not a continuation of the cycle torn down here.- cache.reconnectScheduled = false- },- })),-])diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.test.tsdeleted file mode 100644index 70a14f550fa2..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.test.ts+++ /dev/null@@ -1,295 +0,0 @@-import { expectLogic } from 'kea-test-utils'--import { ApiError } from 'lib/api-error'--import { initKeaTests } from '~/test/init'--import { wizardSessionsLatestRetrieve } from 'products/wizard/frontend/generated/api'-import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'--import { isSessionActive, wizardActiveSessionDetectorLogic } from './wizardActiveSessionDetectorLogic'--jest.mock('products/wizard/frontend/generated/api', () => ({- wizardSessionsLatestRetrieve: jest.fn(),-}))--const mockLatestRetrieve = wizardSessionsLatestRetrieve as jest.Mock--function makeSession(overrides: Partial<WizardSessionDTOApi> = {}): WizardSessionDTOApi {- return {- session_id: 'sess-1',- team_id: 997,- workflow_id: 'posthog-integration',- skill_id: 'install',- started_at: new Date().toISOString(),- run_phase: 'running',- tasks: [],- event_plan: null,- error: null,- pending_input: null,- handoff_text: null,- created_by: null,- created_at: new Date().toISOString(),- updated_at: new Date().toISOString(),- is_stale: false,- ...overrides,- }-}--describe('wizardActiveSessionDetectorLogic', () => {- let logic: ReturnType<typeof wizardActiveSessionDetectorLogic.build>-- beforeEach(() => {- initKeaTests()- mockLatestRetrieve.mockReset()- logic = wizardActiveSessionDetectorLogic()- logic.mount()- })-- afterEach(() => {- logic?.unmount()- })-- describe('isSessionActive', () => {- it('treats a running, fresh session as active', () => {- expect(isSessionActive(makeSession({ run_phase: 'running' }))).toBe(true)- })-- it('treats a null session as inactive', () => {- expect(isSessionActive(null)).toBe(false)- })-- it('treats terminal phases as inactive', () => {- expect(isSessionActive(makeSession({ run_phase: 'completed' }))).toBe(false)- expect(isSessionActive(makeSession({ run_phase: 'error' }))).toBe(false)- })-- it('treats a server-flagged stale session as inactive', () => {- expect(isSessionActive(makeSession({ is_stale: true }))).toBe(false)- })-- it('treats a session past the max lifetime as inactive', () => {- const startedAt = new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()- expect(isSessionActive(makeSession({ started_at: startedAt }))).toBe(false)- })- })-- it('marks active when the poll returns a live session', async () => {- mockLatestRetrieve.mockResolvedValue(makeSession({ run_phase: 'running' }))-- await expectLogic(logic, () => {- logic.actions.check()- })- .toDispatchActions(['markActive'])- .toMatchValues({ hasActiveSession: true, shouldStream: true })- })-- it('stays inactive when the poll returns no session (204/null)', async () => {- mockLatestRetrieve.mockResolvedValue(null)-- await expectLogic(logic, () => {- logic.actions.check()- })- .toDispatchActions(['markInactive'])- .toMatchValues({ hasActiveSession: false, shouldStream: false })- })-- it('permanently disables the detector on a 401', async () => {- mockLatestRetrieve.mockRejectedValue(new ApiError('unauthorized', 401))-- await expectLogic(logic, () => {- logic.actions.check()- })- .toDispatchActions(['markPermanentlyDisabled'])- .toMatchValues({ permanentlyDisabled: true })-- // A permanently disabled detector swallows further polls without calling the endpoint.- const callsAfterDisable = mockLatestRetrieve.mock.calls.length- await expectLogic(logic, () => {- logic.actions.check()- }).toFinishAllListeners()- expect(mockLatestRetrieve.mock.calls.length).toBe(callsAfterDisable)- })-- it('permanently disables the detector on a 403', async () => {- mockLatestRetrieve.mockRejectedValue(new ApiError('forbidden', 403))-- await expectLogic(logic, () => {- logic.actions.check()- })- .toDispatchActions(['markPermanentlyDisabled'])- .toMatchValues({ permanentlyDisabled: true })- })-- it('does NOT permanently disable on a 404 (transient deploy-window route gap)', async () => {- mockLatestRetrieve.mockRejectedValue(new ApiError('not found', 404))-- await expectLogic(logic, () => {- logic.actions.check()- })- .toDispatchActions(['setLastError'])- .toNotHaveDispatchedActions(['markPermanentlyDisabled'])- .toMatchValues({ permanentlyDisabled: false })- })-- // With two programs watched, a failure on the live one plus an empty answer from the other is- // indistinguishable from "no run" unless the error is taken into account — and acting on it- // would tear down a run that is still going.- it('does not tear down a live run when one watched program fails and the other returns empty', async () => {- logic.actions.watchWorkflow('self-driving')- mockLatestRetrieve.mockResolvedValue(makeSession({ run_phase: 'running' }))- await expectLogic(logic, () => {- logic.actions.check()- })- .toDispatchActions(['markActive'])- .toMatchValues({ hasActiveSession: true })-- mockLatestRetrieve.mockImplementation(async (_projectId: string, params: { workflow_id: string }) => {- if (params.workflow_id === 'self-driving') {- throw new ApiError('boom', 500)- }- return null- })-- await expectLogic(logic, () => {- logic.actions.check()- })- .toDispatchActions(['pollFailed'])- .toNotHaveDispatchedActions(['markInactive', 'scheduleMarkInactive'])- .toMatchValues({ hasActiveSession: true })- })-- describe('hasResolvedSessionState', () => {- it('starts unresolved and resolves on a settled poll, in either direction', async () => {- expect(logic.values.hasResolvedSessionState).toBe(false)-- mockLatestRetrieve.mockResolvedValue(null)- await expectLogic(logic, () => {- logic.actions.check()- })- .toDispatchActions(['markInactive'])- .toMatchValues({ hasResolvedSessionState: true })- })-- // Without this, an access-denied user would leave every consumer waiting on a verdict that- // can never arrive (the inbox takeover would never show).- it('resolves on a permanent access denial', async () => {- mockLatestRetrieve.mockRejectedValue(new ApiError('unauthorized', 401))- await expectLogic(logic, () => {- logic.actions.check()- })- .toDispatchActions(['markPermanentlyDisabled'])- .toMatchValues({ hasResolvedSessionState: true, hasActiveSession: false })- })-- // The regression this guards: markInactive doubling as the project-switch reset, which- // stamped the new project "resolved, not running" before its first poll answered.- it('goes back to unresolved on resetSessionState', () => {- logic.actions.markActive('self-driving')- expect(logic.values.hasResolvedSessionState).toBe(true)-- logic.actions.resetSessionState()- expect(logic.values.hasResolvedSessionState).toBe(false)- expect(logic.values.activeWorkflowId).toBeNull()- })- })-- describe('workflow watch refcounting', () => {- it('keeps watching while any registration is open, stops after the last', () => {- logic.actions.watchWorkflow('self-driving')- logic.actions.watchWorkflow('self-driving')- expect(logic.values.watchedWorkflows).toContain('self-driving')-- logic.actions.unwatchWorkflow('self-driving')- expect(logic.values.watchedWorkflows).toContain('self-driving')-- logic.actions.unwatchWorkflow('self-driving')- expect(logic.values.watchedWorkflows).not.toContain('self-driving')- })-- // An unbalanced release must not poison the next registration (a negative count would make- // one watchWorkflow insufficient to start watching again).- it('an extra unwatch does not drive the count negative', () => {- logic.actions.unwatchWorkflow('self-driving')- logic.actions.watchWorkflow('self-driving')- expect(logic.values.watchedWorkflows).toContain('self-driving')- })- })-- it('defers teardown (scheduleMarkInactive) when an active session goes terminal', async () => {- logic.actions.markActive('posthog-integration')- await expectLogic(logic).toMatchValues({ hasActiveSession: true })-- mockLatestRetrieve.mockResolvedValue(makeSession({ run_phase: 'completed' }))-- await expectLogic(logic, () => {- logic.actions.check()- })- .toDispatchActions(['scheduleMarkInactive'])- .toNotHaveDispatchedActions(['markInactive'])- // Teardown is deferred behind the grace window, so the stream stays up for now.- .toMatchValues({ hasActiveSession: true, shouldStream: true })- })-- // The grace window is the anti-INC-886 mechanism: a terminal/empty poll schedules- // teardown rather than ripping the stream down immediately, and a fresh active- // signal inside the window cancels it. These assert the timer actually fires,- // gets cancelled, and isn't pushed out by repeat schedules.- describe('grace-window teardown', () => {- beforeEach(() => {- jest.useFakeTimers()- })-- afterEach(() => {- jest.useRealTimers()- })-- it('fires markInactive once the 30s grace window elapses', async () => {- logic.actions.markActive('posthog-integration')- logic.actions.scheduleMarkInactive()-- // Just before the deadline: the stream is still up.- await expectLogic(logic, () => {- jest.advanceTimersByTime(29_000)- }).toMatchValues({ hasActiveSession: true })-- // Crossing the 30s deadline tears it down.- await expectLogic(logic, () => {- jest.advanceTimersByTime(2_000)- })- .toDispatchActions(['markInactive'])- .toMatchValues({ hasActiveSession: false, shouldStream: false })- })-- it('cancels the pending teardown when markActive fires inside the window', async () => {- logic.actions.markActive('posthog-integration')- logic.actions.scheduleMarkInactive()-- jest.advanceTimersByTime(15_000)- // A fresh active signal (e.g. an SSE heartbeat) cancels the scheduled teardown.- logic.actions.markActive('posthog-integration')-- await expectLogic(logic, () => {- jest.advanceTimersByTime(60_000)- })- .toNotHaveDispatchedActions(['markInactive'])- .toMatchValues({ hasActiveSession: true, shouldStream: true })- })-- it('keeps the original deadline when scheduleMarkInactive is repeated (idempotent)', async () => {- logic.actions.markActive('posthog-integration')- logic.actions.scheduleMarkInactive() // deadline = now + 30s-- jest.advanceTimersByTime(20_000)- logic.actions.scheduleMarkInactive() // must NOT push the deadline out to now + 30s-- // 10s more reaches the *original* 30s deadline → teardown fires. If the repeat- // had reset the clock, markInactive wouldn't fire until 30s from the repeat.- await expectLogic(logic, () => {- jest.advanceTimersByTime(10_000)- })- .toDispatchActions(['markInactive'])- .toMatchValues({ hasActiveSession: false })- })- })-})diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.tsdeleted file mode 100644index 448e7265ba99..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.ts+++ /dev/null@@ -1,512 +0,0 @@-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'-import { subscriptions } from 'kea-subscriptions'-import posthog from 'posthog-js'--import { ApiError } from 'lib/api-error'-import { projectLogic } from 'scenes/projectLogic'-import { userLogic } from 'scenes/userLogic'--// Cross-product import (onboarding core → wizard product) is intentional: this-// detector is the single client that owns the wizard latest-session poll. Going-// through the generated facade keeps types in sync with the backend serializer.-import { wizardSessionsLatestRetrieve } from 'products/wizard/frontend/generated/api'-import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'--import { POSTHOG_INTEGRATION_WORKFLOW_ID } from './workflows'--/** Always watched: the SDK install is what the app-wide FAB and nav button exist for. */-const WORKFLOW_ID = POSTHOG_INTEGRATION_WORKFLOW_ID--// Cheap REST repoll cadence used to surface a wizard run that was kicked off-// from outside the install step (e.g. user copied the command then navigated-// away to the dashboard before the CLI registered the session). The kea-// disposables plugin auto-pauses this while the tab is hidden, so an idle-// user reading mail isn't paying for it.-const REPOLL_INTERVAL_MS = 60 * 1000--// Jitter window applied to the very first poll after mount, so a fleet-wide-// reload (deploy rollout, pgbouncer restart) doesn't synchronize the herd-// against the wizard latest-session endpoint.-const INITIAL_POLL_JITTER_MS = 30 * 1000--// Throttle for visibility-resume rechecks. The kea disposables plugin re-runs-// our setup on every `visibilitychange → visible`, which fires `check()` plus-// a fresh interval. Without throttling, rapid alt-tab flapping would translate-// into a burst of REST calls per tab per second.-const VISIBILITY_RESUME_THROTTLE_MS = 5 * 1000--// Grace window after a terminal phase before we let the SSE stream tear down.-// Gives the FAB time to show the completion / error UI before the connection-// drops.-const TERMINAL_GRACE_MS = 30 * 1000--// Hard upper bound on how long a single session keeps the FAB / SSE mounted,-// regardless of how often the CLI heartbeats `updated_at`. Protects against a-// wedged CLI publishing heartbeats forever, which would otherwise reproduce-// INC-886 at single-user scale.-const MAX_SESSION_LIFETIME_MS = 60 * 60 * 1000--// After this many polls in a row fail, we stop withholding a verdict. Consumers that wait for one-// (the inbox takeover) would otherwise stay suppressed for the whole session on a degraded endpoint,-// with nothing in the UI to explain why. Failing open costs a wrong takeover during an outage;-// failing closed costs every new team its onboarding.-const MAX_CONSECUTIVE_POLL_FAILURES = 3--/**- * Keep the detector mounted and watching a program until the returned cleanup runs. The one way to- * hold a watch open, so the mount/watch pairing (and its teardown order: unwatch before unmount,- * settling the refcount while the logic is still alive) can't be reassembled wrong at call sites.- * The always-watched default program needs no registration, so it's skipped.- */-export function watchWorkflowWhileMounted(workflowId: string): () => void {- const unmount = wizardActiveSessionDetectorLogic.mount()- const needsWatch = workflowId !== WORKFLOW_ID- if (needsWatch) {- wizardActiveSessionDetectorLogic.actions.watchWorkflow(workflowId)- }- return () => {- if (needsWatch) {- wizardActiveSessionDetectorLogic.actions.unwatchWorkflow(workflowId)- }- unmount()- }-}--/**- * Whether a run belongs to the person looking at it. The latest-session endpoint scopes by team and- * program, not by user, so a teammate running the wizard would otherwise take over this browser's- * single verdict slot: their run would tear down the viewer's widget, and their self-driving run- * would suppress onboarding for someone who has no run at all. Runs from before attribution existed- * carry no `created_by`, and those stay eligible rather than disappearing from the UI.- */-function isOwnSession(session: WizardSessionDTOApi, userId: number | null): boolean {- return !session.created_by || userId === null || session.created_by.id === userId-}--/** Sorts unparseable timestamps last rather than letting NaN scramble the comparison. */-function startedAtMs(session: WizardSessionDTOApi): number {- const parsed = new Date(session.started_at).getTime()- return Number.isNaN(parsed) ? -Infinity : parsed-}--export function isSessionActive(session: WizardSessionDTOApi | null | undefined): session is WizardSessionDTOApi {- if (!session) {- return false- }- if (session.run_phase === 'completed' || session.run_phase === 'error') {- return false- }- // Server already computes staleness against the same 10-minute threshold- // the FAB uses for "is this still the user's current run". Trusting the- // server avoids a client-clock-skew failure mode where a forward-skewed- // browser never sees the FAB.- if (session.is_stale) {- return false- }- const startedAt = new Date(session.started_at).getTime()- if (!Number.isNaN(startedAt) && Date.now() - startedAt > MAX_SESSION_LIFETIME_MS) {- return false- }- return true-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardActiveSessionDetectorLogicValues {- currentProjectId: number | null // projectLogic- activeWorkflowId: string | null- consecutivePollFailures: number- extraWorkflowCounts: Record<string, number>- hasActiveSession: boolean- hasResolvedSessionState: boolean- lastError: string | null- permanentlyDisabled: boolean- shouldStream: boolean- watchedWorkflows: string[]-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardActiveSessionDetectorLogicActions {- cancelScheduledMarkInactive: () => {- value: true- }- check: () => {- value: true- }- markActive: (workflowId: string) => {- workflowId: string- }- markInactive: () => {- value: true- }- markPermanentlyDisabled: () => {- value: true- }- markResolutionUnavailable: () => {- value: true- }- pollFailed: () => {- value: true- }- resetSessionState: () => {- value: true- }- scheduleMarkInactive: () => {- value: true- }- setLastError: (error: string | null) => {- error: string | null- }- unwatchWorkflow: (workflowId: string) => {- workflowId: string- }- watchWorkflow: (workflowId: string) => {- workflowId: string- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardActiveSessionDetectorLogicMeta {- __keaTypeGenInternalSelectorTypes: {- hasActiveSession: (activeWorkflowId: string | null) => boolean- watchedWorkflows: (extraWorkflowCounts: Record<string, number>) => string[]- shouldStream: (hasActiveSession: boolean) => boolean- }-}--export type wizardActiveSessionDetectorLogicType = MakeLogicType<- wizardActiveSessionDetectorLogicValues,- wizardActiveSessionDetectorLogicActions,- Record<string, any>,- wizardActiveSessionDetectorLogicMeta->--/**- * Decides whether the global wizard FAB should subscribe to the SSE stream.- *- * The FAB used to mount the streaming logic eagerly on every authenticated- * page, which kept one pgbouncer slot pinned per logged-in user for the test- * arm — see INC-886. This logic gates the stream behind a cheap REST poll so- * the SSE only opens when we have evidence a wizard run is actually in flight.- *- * Sources of truth for `hasActiveSession`, in priority order:- * - `markActive()` from the install step's tracker logic, the moment the SSE- * sees a real session — flips the detector synchronously so the FAB- * survives a navigation away from the install step.- * - REST `wizardSessionsLatestRetrieve(workflow_id=posthog-integration)`,- * polled on mount (jittered), on tab visibility return (throttled), and- * on a 60s loop while the tab is visible.- */-export const wizardActiveSessionDetectorLogic = kea<wizardActiveSessionDetectorLogicType>([- path(['scenes', 'onboarding', 'wizardActiveSessionDetectorLogic']),- connect(() => ({- values: [projectLogic, ['currentProjectId']],- })),- actions({- check: true,- // Surfaces register the wizard program they care about while mounted, so a user who never- // enters the self-driving flow keeps paying for exactly one poll per tick.- watchWorkflow: (workflowId: string) => ({ workflowId }),- unwatchWorkflow: (workflowId: string) => ({ workflowId }),- markActive: (workflowId: string) => ({ workflowId }),- markInactive: true,- // Back to "nobody knows" — for context changes (project switch) where the previous verdict- // no longer describes anything. Distinct from markInactive, which is a verdict.- resetSessionState: true,- scheduleMarkInactive: true,- cancelScheduledMarkInactive: true,- setLastError: (error: string | null) => ({ error }),- // Permanent kill — the backend told us we have no business calling this- // endpoint (401/403 access denial). Set once and we stop polling for the- // rest of the session lifetime.- markPermanentlyDisabled: true,- // Enough polls failed that we can't keep consumers waiting for a verdict. Unlike- // markInactive this is not a claim about any run, so it leaves activeWorkflowId alone —- // it only unblocks the surfaces gated on hasResolvedSessionState.- markResolutionUnavailable: true,- pollFailed: true,- }),- reducers({- // Which program's run is live, so the FAB streams the one that is actually running rather- // than assuming the SDK install.- activeWorkflowId: [- null as string | null,- {- markActive: (_, { workflowId }) => workflowId,- markInactive: () => null,- markPermanentlyDisabled: () => null,- resetSessionState: () => null,- },- ],- // Refcounted: several instances can watch the same program, and the last one out removes it.- extraWorkflowCounts: [- {} as Record<string, number>,- {- watchWorkflow: (state, { workflowId }) =>- workflowId === WORKFLOW_ID ? state : { ...state, [workflowId]: (state[workflowId] ?? 0) + 1 },- unwatchWorkflow: (state, { workflowId }) => {- const next = (state[workflowId] ?? 0) - 1- if (next > 0) {- return { ...state, [workflowId]: next }- }- const { [workflowId]: _dropped, ...rest } = state- return rest- },- },- ],- // Whether the detector has ever reached a verdict (a poll settled, a stream reported in, or- // polling was killed outright). `activeWorkflowId === null` is ambiguous on its own: it also- // covers "nobody has asked yet", and the two need different treatment — a consumer that- // must not act on a wrong "not running" (the inbox takeover) waits for this instead.- hasResolvedSessionState: [- false,- {- markActive: () => true,- markInactive: () => true,- scheduleMarkInactive: () => true,- // Access denial means there will never be a verdict; "resolved, not running" is the- // only answer consumers can act on.- markPermanentlyDisabled: () => true,- markResolutionUnavailable: () => true,- // A verdict about the previous project says nothing about the new one.- resetSessionState: () => false,- },- ],- // Consecutive failed polls, so a persistently broken endpoint eventually stops withholding- // a verdict. Any settled poll clears it.- consecutivePollFailures: [- 0,- {- markActive: () => 0,- markInactive: () => 0,- scheduleMarkInactive: () => 0,- resetSessionState: () => 0,- pollFailed: (state: number) => state + 1,- },- ],- lastError: [- null as string | null,- {- setLastError: (_, { error }) => error,- markActive: () => null,- },- ],- permanentlyDisabled: [- false,- {- markPermanentlyDisabled: () => true,- },- ],- }),- selectors({- hasActiveSession: [- (s) => [s.activeWorkflowId],- (activeWorkflowId: string | null): boolean => activeWorkflowId !== null,- ],- watchedWorkflows: [- (s) => [s.extraWorkflowCounts],- (extraWorkflowCounts: Record<string, number>): string[] => [- ...new Set([WORKFLOW_ID, ...Object.keys(extraWorkflowCounts)]),- ],- ],- shouldStream: [(s) => [s.hasActiveSession], (hasActiveSession: boolean): boolean => hasActiveSession],- }),- listeners(({ actions, values, cache }) => ({- check: async () => {- if (values.permanentlyDisabled) {- return- }- const projectId = values.currentProjectId- if (projectId === null) {- return- }- // Concurrent-poll guard. The next-poll wins; older resolutions are- // ignored — without this, an older "empty" can overwrite a newer- // "active" if responses race.- const seq = (cache.pollSeq = (cache.pollSeq ?? 0) + 1)- // Settled rather than all-or-nothing: one program's failure must not discard another's- // successful answer, or a flaky response for the SDK install would hide a self-driving- // run the server reported correctly.- const results = await Promise.allSettled(- values.watchedWorkflows.map(- async (workflowId): Promise<WizardSessionDTOApi | null> =>- // 204 (no run) returns an empty body, which the api client resolves to null.- (await wizardSessionsLatestRetrieve(- String(projectId),- { workflow_id: workflowId },- { headers: { 'X-Wizard-Poll-Source': 'detector' } }- )) || null- )- )- if (seq !== cache.pollSeq) {- return- }-- const sessions: (WizardSessionDTOApi | null)[] = []- const errors: unknown[] = []- for (const result of results) {- if (result.status === 'fulfilled') {- sessions.push(result.value)- } else {- errors.push(result.reason)- }- }-- // A cancelled fetch (unmount / navigation) is not a real failure; skip the whole poll so- // it doesn't pollute lastError or telemetry.- if (errors.some((err) => err instanceof Error && err.name === 'AbortError')) {- return- }-- // 401/403 are structural access denials: the user can't or shouldn't talk to this- // endpoint. Stop polling permanently rather than burning load on a URL we know is wrong- // — but only when every program agrees, so one program's denial can't silence a healthy- // one. A 404 is deliberately excluded: during a rolling deploy the /latest/ route is- // absent on old pods, so a transient 404 falls through to the retry path and self-heals.- const denials = errors.filter(- (err) => err instanceof ApiError && (err.status === 401 || err.status === 403)- )- if (denials.length > 0 && denials.length === results.length) {- const denial = denials[0] as ApiError- posthog.captureException(denial, {- tags: { feature: 'wizard-active-session-detector', reason: 'permanently_disabled' },- extra: { status: denial.status },- })- actions.setLastError(`wizard latest-session endpoint returned ${denial.status} — disabling detector`)- actions.markPermanentlyDisabled()- cache.disposables.dispose('rest-poll')- return- }-- for (const err of errors) {- // Transient REST failure (including a deploy-window 404) — surface it via- // lastError + Sentry. The next poll retries.- posthog.captureException(err, {- tags: { feature: 'wizard-active-session-detector', reason: 'transient' },- })- }- if (errors.length > 0) {- actions.setLastError(errors[0] instanceof Error ? (errors[0] as Error).message : String(errors[0]))- }-- // Newest wins when two programs both look live — a user who kicked off self-driving- // after an SDK install should see the run they just started. Parsed rather than compared- // as strings: the CLI mints these timestamps, so offset and fractional-second precision- // aren't guaranteed to be uniform, and lexicographic order would rank them wrong.- // Read rather than connected: `userLogic` loads the user on mount, and this detector runs- // app-wide, so connecting it would pull that fetch into every surface that mounts us. In- // the app it is always already mounted; if it somehow isn't, no id means no filtering.- const userId = userLogic.findMounted()?.values.user?.id ?? null- const live = sessions- .filter(isSessionActive)- .filter((session) => isOwnSession(session, userId))- .sort((a, b) => startedAtMs(b) - startedAtMs(a))[0]- if (live) {- actions.markActive(live.workflow_id)- return- }-- if (errors.length > 0) {- // "Nothing live" is only a verdict when every program answered. A failure on the- // program that is actually running, alongside an empty answer from the other, looks- // identical to "no run" from here — and tearing down over that would kill a live- // run's widget. Leave the state alone and count the failure toward giving up on a- // verdict, so consumers waiting on one aren't stranded either.- actions.pollFailed()- if (values.consecutivePollFailures >= MAX_CONSECUTIVE_POLL_FAILURES) {- actions.markResolutionUnavailable()- }- return- }-- if (values.hasActiveSession) {- // Was streaming, REST now reports terminal / empty: defer- // teardown so any in-flight terminal UI gets its grace- // window via the same shared scheduler the tracker uses.- actions.scheduleMarkInactive()- } else {- actions.markInactive()- }- },- markActive: () => {- actions.cancelScheduledMarkInactive()- },- markInactive: () => {- cache.markInactiveAt = undefined- cache.disposables.dispose('mark-inactive-grace')- },- resetSessionState: () => {- cache.markInactiveAt = undefined- cache.disposables.dispose('mark-inactive-grace')- },- scheduleMarkInactive: () => {- // Idempotent: if a teardown timer is already scheduled, keep the- // existing one rather than resetting the 30s clock. Without this,- // repeated terminal SSE pings (or every 60s REST poll while the- // terminal session is still in the active window) would push the- // teardown out indefinitely — re-introducing the INC-886 pattern.- if (cache.disposables.registry.has('mark-inactive-grace')) {- return- }- // Deadline-based teardown. The disposables plugin re-runs this setup- // on every `visibilitychange → visible`; pinning an absolute wall-- // clock deadline (rather than a fresh TERMINAL_GRACE_MS timeout each- // resume) means rapid alt-tabbing schedules only the *remaining*- // time and can't starve teardown.- cache.markInactiveAt = Date.now() + TERMINAL_GRACE_MS- cache.disposables.add(() => {- const remaining = Math.max(0, (cache.markInactiveAt ?? 0) - Date.now())- const id = window.setTimeout(() => actions.markInactive(), remaining)- return () => window.clearTimeout(id)- }, 'mark-inactive-grace')- },- cancelScheduledMarkInactive: () => {- cache.markInactiveAt = undefined- cache.disposables.dispose('mark-inactive-grace')- },- })),- subscriptions(({ actions }) => ({- // Project switching mid-session: drop any stale "active" state from the- // previous project and force a fresh poll against the new project id.- currentProjectId: (projectId: number | null, prev: number | null | undefined) => {- if (projectId === prev) {- return- }- // kea-subscriptions fires this once on mount with `prev === undefined`. Skip- // that initial call so the jittered afterMount poll owns the first check —- // otherwise every client polls immediately on a deploy reload, the exact- // synchronized REST spike the jitter exists to spread out (INC-886).- if (prev === undefined) {- return- }- actions.resetSessionState()- if (projectId !== null) {- actions.check()- }- },- })),- afterMount(({ actions, cache }) => {- // Disposables auto-pause/resume on visibilitychange, so a hidden tab- // pays nothing and a tab returning to foreground re-runs setup —- // which, throttled, fires a `check()` plus a fresh 60s interval.- cache.disposables.add(() => {- // Stagger the initial call across the fleet so a deploy rollout- // doesn't translate into a synchronized REST spike on the wizard- // latest-session endpoint. Throttled by `cache.lastResumeAt` (the- // instant of the previous setup run) so a rapid alt-tab can't bypass- // the jitter via the disposables resume path.- const now = Date.now()- const sinceLastResume = now - (cache.lastResumeAt ?? 0)- cache.lastResumeAt = now- const initialDelay =- sinceLastResume < VISIBILITY_RESUME_THROTTLE_MS- ? VISIBILITY_RESUME_THROTTLE_MS - sinceLastResume- : Math.random() * INITIAL_POLL_JITTER_MS- const initialId = window.setTimeout(() => actions.check(), initialDelay)- const intervalId = window.setInterval(() => actions.check(), REPOLL_INTERVAL_MS)- return () => {- window.clearTimeout(initialId)- window.clearInterval(intervalId)- }- }, 'rest-poll')- }),-])diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.tsdeleted file mode 100644index d996b48c484d..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.ts+++ /dev/null@@ -1,258 +0,0 @@-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'--import { lemonToast } from '@posthog/lemon-ui'--import api, { ApiError } from 'lib/api'-import { integrationsLogic } from 'lib/integrations/integrationsLogic'-import { teamLogic } from 'scenes/teamLogic'--import { IntegrationType } from '~/types'--import { getIntegrationsAuthorizeRetrieveUrl } from 'products/integrations/frontend/generated/api'--import type { SDK } from '../../../../types'-import { onboardingEventUsageLogic } from '../../onboardingEventUsageLogic'-// onboardingLogic gives the GitHub-connect return URL for the active flow, and sdksLogic carries the-// user's manual SDK pick (the cloud wizard's skill hint). Both no-op gracefully outside onboarding.-import { onboardingLogic } from '../../onboardingLogic'-import { sdksLogic } from '../../sdks/sdksLogic'-import { activeCloudRunLogic } from './activeCloudRunLogic'--export type CloudRunStatus =- | 'idle' // No request in flight — show connect / repo-pick / start UI.- | 'submitting' // POST to kick off the run is in flight.- | 'queued' // Run accepted — the user can keep moving; the FAB carries progress.- | 'error' // Kickoff failed.--// Shared with the local CLI wizard so the existing session-sync FAB and the-// install-step tracker pick up cloud runs with no extra wiring — a cloud run is-// the same instrumentation workflow, just executed on our infra rather than on-// the user's machine.-export const WIZARD_CLOUD_RUN_WORKFLOW_ID = 'posthog-integration'--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardCloudRunLogicValues {- githubIntegrations: IntegrationType[] // integrationsLogic- installStepReturnUrl: string // onboardingLogic- selectedSDK: SDK | null // sdksLogic- currentProjectId: number | string // teamLogic- cloudRunRunId: string | null- cloudRunStatus: CloudRunStatus- cloudRunTaskId: string | null- connectGitHubUrl: string- githubIntegration: IntegrationType | null- isGithubConnected: boolean- selectedRepository: string | null- skillId: string | undefined-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardCloudRunLogicActions {- clearActiveCloudRun: () => {- value: true- } // activeCloudRunLogic- setActiveCloudRun: (- taskId: string,- runId: string,- startedAt: string,- projectId: number- ) => {- projectId: number- runId: string- startedAt: string- taskId: string- } // activeCloudRunLogic- loadIntegrations: (_?: any) => any // integrationsLogic- reportOnboardingCloudRunQueued: (props: { repository: string; runId: string; taskId: string }) => {- repository: string- runId: string- taskId: string- } // onboardingEventUsageLogic- setCloudRunHandle: (- taskId: string,- runId: string- ) => {- runId: string- taskId: string- }- setSelectedRepository: (repository: string | null) => {- repository: string | null- }- startCloudRun: () => {- value: true- }- startCloudRunFailure: () => {- value: true- }- startCloudRunSuccess: () => {- value: true- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardCloudRunLogicMeta {- __keaTypeGenInternalSelectorTypes: {- githubIntegration: (githubIntegrations: IntegrationType[]) => IntegrationType | null- isGithubConnected: (githubIntegration: IntegrationType | null) => boolean- connectGitHubUrl: (currentProjectId: number | string, installStepReturnUrl: string) => string- skillId: (selectedSDK: SDK | null) => string | undefined- }-}--export type wizardCloudRunLogicType = MakeLogicType<- wizardCloudRunLogicValues,- wizardCloudRunLogicActions,- Record<string, any>,- wizardCloudRunLogicMeta->--/**- * Drives the "open a PR for me" option on the install step:- * - resolves the team's GitHub integration (or the URL to connect one)- * - holds the chosen repository- * - kicks off the cloud run and tracks its lifecycle- *- * Live progress and the "your PR is ready" payoff are not owned here — the cloud- * run posts wizard sessions under WIZARD_CLOUD_RUN_WORKFLOW_ID, so the existing- * session-sync surfaces (the Installation layer + the global FAB) render them- * automatically. This logic only has to get the run started without blocking the- * user from continuing onboarding.- */-export const wizardCloudRunLogic = kea<wizardCloudRunLogicType>([- path(['scenes', 'onboarding', 'wizardCloudRunLogic']),- connect(() => ({- values: [- integrationsLogic,- ['githubIntegrations'],- teamLogic,- ['currentProjectId'],- onboardingLogic,- ['installStepReturnUrl'],- sdksLogic,- ['selectedSDK'],- ],- actions: [- integrationsLogic,- ['loadIntegrations'],- activeCloudRunLogic,- ['setActiveCloudRun', 'clearActiveCloudRun'],- onboardingEventUsageLogic,- ['reportOnboardingCloudRunQueued'],- ],- })),- actions({- setSelectedRepository: (repository: string | null) => ({ repository }),- startCloudRun: true,- startCloudRunSuccess: true,- startCloudRunFailure: true,- setCloudRunHandle: (taskId: string, runId: string) => ({ taskId, runId }),- }),- reducers({- selectedRepository: [- null as string | null,- {- setSelectedRepository: (_, { repository }) => repository,- },- ],- cloudRunStatus: [- 'idle' as CloudRunStatus,- {- startCloudRun: () => 'submitting',- startCloudRunSuccess: () => 'queued',- startCloudRunFailure: () => 'error',- // Dismissing the run (the FAB's dismiss or "Run it yourself") drops the handle, so a- // lingering 'queued' here would re-show the kickoff banner for a run that's gone.- clearActiveCloudRun: () => 'idle',- // Picking a different repo after a failure clears the error so the- // primary button is actionable again.- setSelectedRepository: (state) => (state === 'error' ? 'idle' : state),- },- ],- // The run handle returned by the kickoff POST. The Installation layer streams progress by run id.- cloudRunTaskId: [- null as string | null,- {- setCloudRunHandle: (_, { taskId }) => taskId,- },- ],- cloudRunRunId: [- null as string | null,- {- setCloudRunHandle: (_, { runId }) => runId,- },- ],- }),- selectors({- githubIntegration: [- (s) => [s.githubIntegrations],- (githubIntegrations: IntegrationType[]): IntegrationType | null => githubIntegrations[0] ?? null,- ],- isGithubConnected: [- (s) => [s.githubIntegration],- (githubIntegration: IntegrationType | null): boolean => !!githubIntegration,- ],- connectGitHubUrl: [- (s) => [s.currentProjectId, s.installStepReturnUrl],- (currentProjectId: number | string, installStepReturnUrl: string): string =>- // Full-page redirect to install/authorize the GitHub App, then back to- // the install step. integrationsLogic's callback appends the new- // integration id, and loadIntegrations() repopulates githubIntegration,- // so the block advances from "connect" to "pick a repo" on return.- `${getIntegrationsAuthorizeRetrieveUrl(String(currentProjectId))}?${new URLSearchParams({- kind: 'github',- next: installStepReturnUrl,- })}`,- ],- // The cloud wizard auto-detects the framework, so this is a hint rather than a- // requirement — only set when the user happens to have picked an SDK manually.- skillId: [- (s) => [s.selectedSDK],- (selectedSDK: null | import('~/types').SDK): string | undefined => selectedSDK?.key,- ],- }),- listeners(({ values, actions }) => ({- startCloudRun: async () => {- const { githubIntegration, selectedRepository, currentProjectId } = values- if (!githubIntegration || !selectedRepository || !currentProjectId) {- actions.startCloudRunFailure()- return- }- // The picker holds the bare repo name; the endpoint wants "owner/repo", where the owner- // is the GitHub integration's account.- const owner = githubIntegration.config?.account?.name- const repository =- selectedRepository.includes('/') || !owner ? selectedRepository : `${owner}/${selectedRepository}`- try {- // Kicks off the cloud run (clone repo → run the wizard → open a PR via a Temporal- // workflow) and returns the run handle. Live progress is surfaced by the Installation- // layer (installationProgressLogic), which streams this run's TaskRun pipeline merged- // with the wizard session detail.- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.- const { task_id, run_id } = await api.create<{ task_id: string; run_id: string; status: string }>(- 'api/wizard/cloud_run',- {- project_id: currentProjectId,- repository,- }- )- actions.setCloudRunHandle(task_id, run_id)- // teamLogic's currentProjectId can be the '@current' placeholder pre-load; by kickoff- // time the team is loaded, so this is a plain numeric coercion in practice.- actions.setActiveCloudRun(task_id, run_id, new Date().toISOString(), Number(currentProjectId))- // Frontend side of the kickoff, pairing with the backend `task_run_created` (GROW-89).- actions.reportOnboardingCloudRunQueued({ taskId: task_id, runId: run_id, repository })- actions.startCloudRunSuccess()- } catch (e) {- const detail = e instanceof ApiError ? e.detail : null- lemonToast.error(detail || 'Could not start the cloud run. Please try again.')- actions.startCloudRunFailure()- }- },- startCloudRunSuccess: () => {- // The POST only queues the run — it isn't done. The real outcome (running → completed/error)- // is reported by the wizard sync surfaces (inline tracker + FAB) when enabled, so keep this a- // neutral acknowledgement rather than claiming the PR is on its way.- lemonToast.info('Cloud run queued')- },- })),-])diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.test.tsdeleted file mode 100644index e800141a9b4f..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.test.ts+++ /dev/null@@ -1,91 +0,0 @@-import { MOCK_DEFAULT_USER } from 'lib/api.mock'--import { userLogic } from 'scenes/userLogic'--import { initKeaTests } from '~/test/init'--import { wizardSyncUiLogic } from './wizardSyncUiLogic'--describe('wizardSyncUiLogic inline panel refcount', () => {- let logic: ReturnType<typeof wizardSyncUiLogic.build>-- beforeEach(() => {- initKeaTests()- logic = wizardSyncUiLogic()- logic.mount()- })-- afterEach(() => {- logic?.unmount()- })-- // Two surfaces can show the same run inline (install step + inbox rail); the FAB must stay- // hidden until the LAST one goes away, and an unbalanced release must not wedge it hidden.- it('stays claimed until the last panel releases', () => {- logic.actions.claimInlinePanel('local')- logic.actions.claimInlinePanel('local')- expect(logic.values.inlineLocalPanelMounted).toBe(true)-- logic.actions.releaseInlinePanel('local')- expect(logic.values.inlineLocalPanelMounted).toBe(true)-- logic.actions.releaseInlinePanel('local')- expect(logic.values.inlineLocalPanelMounted).toBe(false)- })-- it('an extra release does not drive the count negative', () => {- logic.actions.releaseInlinePanel('local')- logic.actions.claimInlinePanel('local')- expect(logic.values.inlineLocalPanelMounted).toBe(true)- })-- // A local run shown in the inbox rail must not silence the detached surface for a cloud run- // running alongside it, which would leave the cloud run with no progress, cancel or dismiss.- it('tracks the two modes separately', () => {- logic.actions.claimInlinePanel('local')- expect(logic.values.inlineLocalPanelMounted).toBe(true)- expect(logic.values.inlineCloudPanelMounted).toBe(false)- expect(logic.values.inlinePanelMounted).toBe(true)- })-- // The one-time auto-open is the feature's contract: the SSE replays the latest session on every- // connect, so without the seen guard the doc dialog would pop on every reload and navigation.- // seenHandoffDocKeys persists to localStorage, so each test uses its own doc keys.- describe('handoff doc auto-open', () => {- it('opens on the first announcement only, keyed per run', () => {- logic.actions.handoffDocReceived({ key: 'run-1', text: '# report', startedByEmail: null })- expect(logic.values.handoffDoc).toEqual({ key: 'run-1', text: '# report' })-- logic.actions.closeHandoffDoc()- logic.actions.handoffDocReceived({ key: 'run-1', text: '# report', startedByEmail: null })- expect(logic.values.handoffDoc).toBeNull()-- logic.actions.handoffDocReceived({ key: 'run-2', text: '# other', startedByEmail: null })- expect(logic.values.handoffDoc).toEqual({ key: 'run-2', text: '# other' })- })-- it('a doc already read through the button never auto-opens later', () => {- logic.actions.openHandoffDoc({ key: 'run-3', text: '# report' })- logic.actions.closeHandoffDoc()-- logic.actions.handoffDocReceived({ key: 'run-3', text: '# report', startedByEmail: null })- expect(logic.values.handoffDoc).toBeNull()- })-- it("does not auto-open for a teammate's run", () => {- userLogic.mount()- userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)-- logic.actions.handoffDocReceived({ key: 'run-4', text: '# report', startedByEmail: '[email protected]' })- expect(logic.values.handoffDoc).toBeNull()-- // The runner themselves (or an unattributed run) still gets the auto-open.- logic.actions.handoffDocReceived({- key: 'run-5',- text: '# report',- startedByEmail: MOCK_DEFAULT_USER.email,- })- expect(logic.values.handoffDoc).toEqual({ key: 'run-5', text: '# report' })- })- })-})diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.tsdeleted file mode 100644index 27509c0105ba..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.ts+++ /dev/null@@ -1,203 +0,0 @@-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'--import { userLogic } from 'scenes/userLogic'--import type { UserType } from '~/types'--import { onboardingEventUsageLogic } from '../../onboardingEventUsageLogic'--// Enough to outlast any realistic run history on one browser without letting the persisted list-// grow forever.-const SEEN_HANDOFF_DOC_KEYS_CAP = 20--/** Where a run is executing: in the user's terminal, or on our infrastructure. */-export type WizardSyncMode = 'cloud' | 'local'--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardSyncUiLogicValues {- user: UserType | null // userLogic- dialogOpen: boolean- dismissedKey: string | null- handoffDoc: {- key: string- text: string- } | null- inlineCloudPanelMounted: boolean- inlineLocalPanelMounted: boolean- inlinePanelCounts: Record<WizardSyncMode, number>- inlinePanelMounted: boolean- seenHandoffDocKeys: string[]-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardSyncUiLogicActions {- reportWizardSyncHandoffDocOpened: (props: {- mode: 'cloud' | 'local'- runKey: string- trigger: 'auto' | 'button'- }) => {- mode: 'cloud' | 'local'- runKey: string- trigger: 'auto' | 'button'- } // onboardingEventUsageLogic- claimInlinePanel: (mode: WizardSyncMode) => {- mode: WizardSyncMode- }- closeDialog: () => {- value: true- }- closeHandoffDoc: () => {- value: true- }- dismiss: (key: string) => {- key: string- }- handoffDocReceived: (doc: { key: string; startedByEmail: string | null; text: string }) => {- key: string- startedByEmail: string | null- text: string- }- openDialog: () => {- value: true- }- openHandoffDoc: (doc: { key: string; text: string }) => {- key: string- text: string- }- releaseInlinePanel: (mode: WizardSyncMode) => {- mode: WizardSyncMode- }- restore: () => {- value: true- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardSyncUiLogicMeta {- __keaTypeGenInternalSelectorTypes: {- inlineCloudPanelMounted: (inlinePanelCounts: Record<WizardSyncMode, number>) => boolean- inlineLocalPanelMounted: (inlinePanelCounts: Record<WizardSyncMode, number>) => boolean- inlinePanelMounted: (inlineCloudPanelMounted: boolean, inlineLocalPanelMounted: boolean) => boolean- }-}--export type wizardSyncUiLogicType = MakeLogicType<- wizardSyncUiLogicValues,- wizardSyncUiLogicActions,- Record<string, any>,- wizardSyncUiLogicMeta->--/**- * UI state for the detached wizard sync widget, shared app-wide (mounted by WizardSyncFab):- * - `dismissedKey`: the run the user minimized. Keyed by run id (cloud) or session id (local) so a- * fresh run is never born already-minimized, and a minimize survives navigation (persisted).- * - `dialogOpen`: whether the "all the details" dialog is showing.- * - `inlineCloudPanelMounted` / `inlineLocalPanelMounted`: a scene is already showing a run inline- * (the onboarding install step, the inbox), so the detached surface for *that* run stands down- * rather than showing it twice. Refcounted: a boolean would let one panel's unmount un-hide the- * widget while another is still showing. Tracked per mode because cloud and local runs can be in- * flight at once, and a surface that only ever renders one of them must not silence the other.- * - `handoffDoc`: the markdown handoff doc dialog currently showing (content is fed by whichever- * source announced or opened it). `seenHandoffDocKeys` (persisted) makes the announce-driven- * open a strictly once-per-run event: SSE replays, remounts, and reloads re-announce the same- * doc, and only the first announcement may pop the dialog. The button reopens it at will.- *- * The widget itself owns no run data; the per-mode inner components feed it the normalized progress.- */-export const wizardSyncUiLogic = kea<wizardSyncUiLogicType>([- path(['scenes', 'onboarding', 'wizardSyncUiLogic']),- connect(() => ({- values: [userLogic, ['user']],- actions: [onboardingEventUsageLogic, ['reportWizardSyncHandoffDocOpened']],- })),- actions({- dismiss: (key: string) => ({ key }),- restore: true,- openDialog: true,- closeDialog: true,- claimInlinePanel: (mode: WizardSyncMode) => ({ mode }),- releaseInlinePanel: (mode: WizardSyncMode) => ({ mode }),- // A run's handoff doc was delivered (live session push, SSE replay, or a persisted- // finished-run handle restored on pageload). Announcements are idempotent; the listener- // decides whether this one gets the one-time auto-open.- handoffDocReceived: (doc: { key: string; text: string; startedByEmail: string | null }) => doc,- openHandoffDoc: (doc: { key: string; text: string }) => doc,- closeHandoffDoc: true,- }),- reducers({- dismissedKey: [- null as string | null,- { persist: true },- {- dismiss: (_, { key }) => key,- restore: () => null,- },- ],- dialogOpen: [- false,- {- openDialog: () => true,- closeDialog: () => false,- restore: () => false,- },- ],- inlinePanelCounts: [- { cloud: 0, local: 0 } as Record<WizardSyncMode, number>,- {- claimInlinePanel: (state, { mode }) => ({ ...state, [mode]: state[mode] + 1 }),- releaseInlinePanel: (state, { mode }) => ({ ...state, [mode]: Math.max(0, state[mode] - 1) }),- },- ],- handoffDoc: [- null as { key: string; text: string } | null,- {- openHandoffDoc: (_, { key, text }) => ({ key, text }),- closeHandoffDoc: () => null,- },- ],- seenHandoffDocKeys: [- [] as string[],- { persist: true },- {- // Any open counts as seen — a doc the user already read through the button must not- // auto-open later.- openHandoffDoc: (state, { key }) =>- state.includes(key) ? state : [...state, key].slice(-SEEN_HANDOFF_DOC_KEYS_CAP),- },- ],- }),- selectors({- inlineCloudPanelMounted: [- (s) => [s.inlinePanelCounts],- (inlinePanelCounts: Record<WizardSyncMode, number>): boolean => inlinePanelCounts.cloud > 0,- ],- inlineLocalPanelMounted: [- (s) => [s.inlinePanelCounts],- (inlinePanelCounts: Record<WizardSyncMode, number>): boolean => inlinePanelCounts.local > 0,- ],- /** Any run is shown inline — for surfaces that don't distinguish which one, like the nav item. */- inlinePanelMounted: [- (s) => [s.inlineCloudPanelMounted, s.inlineLocalPanelMounted],- (inlineCloudPanelMounted: boolean, inlineLocalPanelMounted: boolean): boolean =>- inlineCloudPanelMounted || inlineLocalPanelMounted,- ],- }),- listeners(({ actions, values }) => ({- handoffDocReceived: ({ key, text, startedByEmail }) => {- if (values.seenHandoffDocKeys.includes(key)) {- return- }- // A teammate's run: popping a dialog because someone else's terminal finished would be- // an interruption, not a handoff. They still get the button on the run's surfaces.- // Not marked seen, so the doc can still auto-open for the teammate who did run it.- const ownEmail = values.user?.email- if (startedByEmail && ownEmail && startedByEmail !== ownEmail) {- return- }- actions.openHandoffDoc({ key, text })- // Announcements only come from local runs (cloud runs surface their doc via the button).- actions.reportWizardSyncHandoffDocOpened({ runKey: key, mode: 'local', trigger: 'auto' })- },- })),-])diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/workflows.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/workflows.tsdeleted file mode 100644index c6b847d8df69..000000000000--- a/frontend/src/scenes/onboarding/shared/wizard-sync/workflows.ts+++ /dev/null@@ -1,22 +0,0 @@-/**- * Wizard program identifiers. In code these are "workflows", after the wire field the CLI sends- * (`workflow_id`); "program" is the CLI's user-facing word for the same thing.- *- * The CLI sends its program id as `workflow_id` on every session push, so each program is its own- * session channel. Kept in their own module because both the session detector and the installation- * progress layer need them, and those two import each other.- */--/** The SDK install — what the app-wide sync surfaces watch by default. */-export const POSTHOG_INTEGRATION_WORKFLOW_ID = 'posthog-integration'--/** `wizard self-driving`, the program that sets up the self-driving Inbox. */-export const SELF_DRIVING_WORKFLOW_ID = 'self-driving'--/**- * Which wizard program a surface is tracking. Defaulted rather than required so every existing- * consumer keeps watching the SDK install without passing anything.- */-export function resolveWorkflowId(workflowId?: string): string {- return workflowId ?? POSTHOG_INTEGRATION_WORKFLOW_ID-}diff --git a/frontend/src/scenes/onboarding/simple/OnboardingMcpStep.tsx b/frontend/src/scenes/onboarding/simple/OnboardingMcpStep.tsxindex 52296e53a721..841b9ec30867 100644--- a/frontend/src/scenes/onboarding/simple/OnboardingMcpStep.tsx+++ b/frontend/src/scenes/onboarding/simple/OnboardingMcpStep.tsx@@ -6,7 +6,7 @@ import { Spinner } from '@posthog/lemon-ui'import { OnboardingStepKey } from '~/types'import { OnboardingStep } from '../OnboardingStep'-import { WizardCommandBlock } from '../shared/wizard-sync/WizardCommandBlock'+import { WizardCommandBlock } from '../shared/wizard-command/WizardCommandBlock'import { PurpleWizardHog } from '../shared/wizardHog'import { onboardingMcpStepLogic } from './onboardingMcpStepLogic'diff --git a/frontend/src/scenes/onboarding/welcome/WelcomeCelebration.tsx b/frontend/src/scenes/onboarding/welcome/WelcomeCelebration.tsxindex 83c57ffdf7a2..6e108b087272 100644--- a/frontend/src/scenes/onboarding/welcome/WelcomeCelebration.tsx+++ b/frontend/src/scenes/onboarding/welcome/WelcomeCelebration.tsx@@ -2,12 +2,16 @@ import { useActions, useValues } from 'kea'import { useEffect } from 'react'import { useHogfetti } from 'lib/components/Hogfetti/Hogfetti'+import { inStorybookTestRunner } from 'lib/utils/dom'import { ProductKey } from '~/queries/schema/schema-general'-import { canCelebrate } from '../shared/wizard-sync/hooks'import { onboardingWelcomeLogic } from './onboardingWelcomeLogic'+function canCelebrate(): boolean {+ return !inStorybookTestRunner() && !window.matchMedia('(prefers-reduced-motion: reduce)').matches+}+export function WelcomeCelebration({ productKey }: { productKey: ProductKey }): JSX.Element {const { celebratedProductKeys } = useValues(onboardingWelcomeLogic)const { markCelebrated } = useActions(onboardingWelcomeLogic)diff --git a/frontend/src/scenes/settings/environment/SDKInstallOptions.tsx b/frontend/src/scenes/settings/environment/SDKInstallOptions.tsxindex 5913e1110cf4..83517f419e5a 100644--- a/frontend/src/scenes/settings/environment/SDKInstallOptions.tsx+++ b/frontend/src/scenes/settings/environment/SDKInstallOptions.tsx@@ -4,7 +4,7 @@ import { IconChevronDown, IconChevronRight } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'-import { WizardCommandBlock } from 'scenes/onboarding/shared/wizard-sync/WizardCommandBlock'+import { WizardCommandBlock } from 'scenes/onboarding/shared/wizard-command/WizardCommandBlock'import { SDKSetupInstructions } from './SDKSetupInstructions'diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.tsindex 977fec0ba444..73a8a751f45e 100644--- a/frontend/src/scenes/userLogic.ts+++ b/frontend/src/scenes/userLogic.ts@@ -1070,8 +1070,8 @@ export const userLogic = kea<userLogicType>([},],// True for accounts created by a partner drop flow (onboarding skipped with reason- // 'provisioned'). Drives the provisioned welcome experience — background-install FAB,- // welcome dialog, quick-start seeding, and the homepage banner.+ // 'provisioned'). Drives the provisioned welcome experience: welcome dialog, quick-start+ // seeding, and the homepage banner.isProvisionedUser: [(s) => [s.user],(user: UserType | null): boolean => user?.onboarding_skipped_reason === 'provisioned',diff --git a/frontend/src/scenes/welcome/WelcomeDialog.stories.tsx b/frontend/src/scenes/welcome/WelcomeDialog.stories.tsxindex 17f98ec4c39f..76dfc5e806ba 100644--- a/frontend/src/scenes/welcome/WelcomeDialog.stories.tsx+++ b/frontend/src/scenes/welcome/WelcomeDialog.stories.tsx@@ -1,10 +1,9 @@-import { MOCK_DEFAULT_USER, MOCK_TEAM_ID } from 'lib/api.mock'+import { MOCK_DEFAULT_USER } from 'lib/api.mock'import { Meta, StoryFn } from '@storybook/react'import { useMountedLogic } from 'kea'import { useEffect } from 'react'-import { activeCloudRunLogic } from 'scenes/onboarding/shared/wizard-sync/activeCloudRunLogic'import { userLogic } from 'scenes/userLogic'import { mswDecorator } from '~/mocks/browser'@@ -190,16 +189,12 @@ NoInviter.decorators = [}),]-// Partner-provisioned account: the dialog leads with the background-install card and the flagship-// product tour (a different card order than invited users get).+// Partner-provisioned account: the dialog leads with the flagship product tour (a different card+// order than invited users get).function ProvisionedTemplate(): JSX.Element {useMountedLogic(userLogic)- useMountedLogic(activeCloudRunLogic)useEffect(() => {welcomeDialogLogic.mount()- // Seed an active cloud run so the "we're setting up PostHog in your repo" card shows- // (storybook app context sets current_project to MOCK_TEAM_ID).- activeCloudRunLogic.actions.setActiveCloudRun('task-1', 'run-1', new Date().toISOString(), MOCK_TEAM_ID)}, [])return <WelcomeDialog />}diff --git a/frontend/src/scenes/welcome/WelcomeDialog.tsx b/frontend/src/scenes/welcome/WelcomeDialog.tsxindex 747750e190bf..dde76ca2e340 100644--- a/frontend/src/scenes/welcome/WelcomeDialog.tsx+++ b/frontend/src/scenes/welcome/WelcomeDialog.tsx@@ -10,7 +10,6 @@ import { userLogic } from 'scenes/userLogic'import { AskMaxCard } from './cards/AskMaxCard'import { FlagshipProductsCard } from './cards/FlagshipProductsCard'-import { InstallProgressCard } from './cards/InstallProgressCard'import { PopularDashboardsCard } from './cards/PopularDashboardsCard'import { ProductsInUseCard } from './cards/ProductsInUseCard'import { RecentActivityCard } from './cards/RecentActivityCard'@@ -123,11 +122,10 @@ export function WelcomeDialog(): JSX.Element | null {) : (<p className="text-muted text-sm m-0">{introCopy}</p>)}- {/* Provisioned/new accounts lead with the background install + a tour of what PostHog- offers; invited users get their team's context first and the product tour lower down. */}+ {/* Provisioned/new accounts lead with a tour of what PostHog offers; invited users get+ their team's context first and the product tour lower down. */}{isProvisionedUser ? (<>- <InstallProgressCard /><FlagshipProductsCard /><AskMaxCard /><SuggestedNextStepsCard />diff --git a/frontend/src/scenes/welcome/cards/InstallProgressCard.stories.tsx b/frontend/src/scenes/welcome/cards/InstallProgressCard.stories.tsxdeleted file mode 100644index 49df7118162f..000000000000--- a/frontend/src/scenes/welcome/cards/InstallProgressCard.stories.tsx+++ /dev/null@@ -1,35 +0,0 @@-import { MOCK_TEAM_ID } from 'lib/api.mock'--import { Meta, StoryFn } from '@storybook/react'-import { useMountedLogic } from 'kea'-import { useEffect } from 'react'--import { activeCloudRunLogic } from 'scenes/onboarding/shared/wizard-sync/activeCloudRunLogic'--import { mswDecorator } from '~/mocks/browser'--import { InstallProgressCard } from './InstallProgressCard'--const meta: Meta<typeof InstallProgressCard> = {- title: 'Scenes-Other/Welcome/InstallProgressCard',- component: InstallProgressCard,- parameters: {- layout: 'padded',- },- decorators: [mswDecorator({})],-}-export default meta--// The card only renders while there's an active cloud run for the current project, so seed one-// (the storybook app context sets current_project to MOCK_TEAM_ID).-export const Default: StoryFn<typeof InstallProgressCard> = () => {- useMountedLogic(activeCloudRunLogic)- useEffect(() => {- activeCloudRunLogic.actions.setActiveCloudRun('task-1', 'run-1', new Date().toISOString(), MOCK_TEAM_ID)- }, [])- return (- <div className="max-w-[608px]">- <InstallProgressCard />- </div>- )-}diff --git a/frontend/src/scenes/welcome/cards/InstallProgressCard.tsx b/frontend/src/scenes/welcome/cards/InstallProgressCard.tsxdeleted file mode 100644index 7f779595a51c..000000000000--- a/frontend/src/scenes/welcome/cards/InstallProgressCard.tsx+++ /dev/null@@ -1,32 +0,0 @@-import { useValues } from 'kea'--import { IconGithub } from '@posthog/icons'--import { LemonCard } from 'lib/lemon-ui/LemonCard'-import { activeCloudRunLogic } from 'scenes/onboarding/shared/wizard-sync/activeCloudRunLogic'--// Shown to partner-provisioned users while their setup wizard cloud run is in flight. The live-// progress + PR link live in the setup FAB (bottom-right); this card just makes the background-// work legible from inside the welcome dialog and points at it.-export function InstallProgressCard(): JSX.Element | null {- const { activeCloudRun } = useValues(activeCloudRunLogic)-- if (!activeCloudRun) {- return null- }-- return (- <LemonCard hoverEffect={false} className="p-4">- <div className="flex items-start gap-3">- <IconGithub className="text-2xl shrink-0 mt-0.5" />- <div>- <h2 className="text-lg font-semibold mb-1">We're setting up PostHog in your repo</h2>- <p className="text-sm text-muted m-0">- A pull request that wires up PostHog is being prepared in the background. Follow its progress in- the setup panel in the bottom-right corner - it'll link the pull request as soon as it's open.- </p>- </div>- </div>- </LemonCard>- )-}diff --git a/products/ai_observability/frontend/onboarding/steps.tsx b/products/ai_observability/frontend/onboarding/steps.tsxindex 070629d8be9f..67448d3f28a4 100644--- a/products/ai_observability/frontend/onboarding/steps.tsx+++ b/products/ai_observability/frontend/onboarding/steps.tsx@@ -10,7 +10,7 @@ import geminiImage from 'scenes/onboarding/shared/logos/gemini.svg'import { LangChainLogo } from 'scenes/onboarding/shared/logos/LangChainLogo'import { OpenAILogo } from 'scenes/onboarding/shared/logos/OpenAILogo'import { OpenRouterLogo } from 'scenes/onboarding/shared/logos/OpenRouterLogo'-import type { WizardBadgeItem } from 'scenes/onboarding/shared/wizard-sync/WizardModeShell'+import type { WizardBadgeItem } from 'scenes/onboarding/shared/wizard-command/WizardModeShell'import { type ProductOnboardingProvider } from 'scenes/onboarding/types'import { urls } from 'scenes/urls'diff --git a/products/mcp_analytics/frontend/emptyState/MCPAnalyticsSetupActions.tsx b/products/mcp_analytics/frontend/emptyState/MCPAnalyticsSetupActions.tsxindex 9b99dbdcce16..76477f75185a 100644--- a/products/mcp_analytics/frontend/emptyState/MCPAnalyticsSetupActions.tsx+++ b/products/mcp_analytics/frontend/emptyState/MCPAnalyticsSetupActions.tsx@@ -6,12 +6,10 @@ import { LemonButton, LemonModal } from '@posthog/lemon-ui'import { CodeSnippet } from 'lib/components/CodeSnippet/CodeSnippet'import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'import type { ProductEmptyStateMode } from 'lib/components/ProductEmptyState/types'-import { preflightLogic } from 'lib/logic/preflightLogic'import { ProductKey } from '~/queries/schema/schema-general'import { mcpAnalyticsSetupLogic } from './mcpAnalyticsSetupLogic'-import { MCPAnalyticsSetupProgress } from './MCPAnalyticsSetupProgress'export function MCPAnalyticsSetupActions({mode,@@ -23,7 +21,6 @@ export function MCPAnalyticsSetupActions({const { agentPromptOpen, agentPrompt } = useValues(mcpAnalyticsSetupLogic)const { setAgentPromptOpen } = useActions(mcpAnalyticsSetupLogic)const { reportSetupInteraction } = useActions(productSetupStatusLogic({ productKey: ProductKey.MCP_ANALYTICS }))- const { isCloudOrDev } = useValues(preflightLogic)return (<>@@ -61,7 +58,6 @@ export function MCPAnalyticsSetupActions({arrives.</p></LemonModal>- {isCloudOrDev && !preview ? <MCPAnalyticsSetupProgress mode={mode} /> : null}</>)}diff --git a/products/mcp_analytics/frontend/emptyState/MCPAnalyticsSetupProgress.tsx b/products/mcp_analytics/frontend/emptyState/MCPAnalyticsSetupProgress.tsxdeleted file mode 100644index 18e47b0f1e3a..000000000000--- a/products/mcp_analytics/frontend/emptyState/MCPAnalyticsSetupProgress.tsx+++ /dev/null@@ -1,36 +0,0 @@-import { useActions, useValues } from 'kea'-import { useEffect } from 'react'--import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'-import type { ProductEmptyStateMode } from 'lib/components/ProductEmptyState/types'-import { installationProgressLogic } from 'scenes/onboarding/shared/wizard-sync/installationProgressLogic'-import { InstallationProgressView } from 'scenes/onboarding/shared/wizard-sync/InstallationProgressView'-import { teamLogic } from 'scenes/teamLogic'--import { ProductKey } from '~/queries/schema/schema-general'--export function MCPAnalyticsSetupProgress({ mode }: { mode: ProductEmptyStateMode }): JSX.Element | null {- const { installationProgress, latestSession } = useValues(- installationProgressLogic({ mode: 'local', workflowId: 'mcp-analytics' })- )- const { reportSetupInteraction } = useActions(productSetupStatusLogic({ productKey: ProductKey.MCP_ANALYTICS }))- const sessionId = latestSession?.session_id- const { isCurrent, phase } = installationProgress- const { currentTeamId } = useValues(teamLogic)- const matchesProject = latestSession?.team_id === currentTeamId-- useEffect(() => {- if (isCurrent && matchesProject && sessionId) {- reportSetupInteraction('wizard session observed', mode, null, false, { session_id: sessionId, phase })- }- }, [isCurrent, matchesProject, sessionId, phase, mode, reportSetupInteraction])-- return isCurrent && matchesProject ? (- <InstallationProgressView- mode="local"- workflowId="mcp-analytics"- docsUrl="https://posthog.com/docs/mcp-analytics/installation"- continueHint="After setup, call an existing tool from your server to verify that its event arrives here."- />- ) : null-}diff --git a/products/signals/frontend/inbox/InboxScene.stories.tsx b/products/signals/frontend/inbox/InboxScene.stories.tsxindex c35b247d200d..5951b004bc02 100644--- a/products/signals/frontend/inbox/InboxScene.stories.tsx+++ b/products/signals/frontend/inbox/InboxScene.stories.tsx@@ -1,12 +1,9 @@import type { Decorator, Meta, StoryObj } from '@storybook/react'import { waitFor, within } from '@testing-library/dom'-import { useMountedLogic } from 'kea'import { router } from 'kea-router'import { useEffect } from 'react'import { FEATURE_FLAGS } from 'lib/constants'-import { wizardActiveSessionDetectorLogic } from 'scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic'-import { SELF_DRIVING_WORKFLOW_ID } from 'scenes/onboarding/shared/wizard-sync/workflows'import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'@@ -228,26 +225,6 @@ export const EmptyWithManyScouts: Story = {],}-export const InstallingSelfDriving: Story = {- decorators: [- (Story) => {- useMountedLogic(wizardActiveSessionDetectorLogic)- useEffect(() => {- wizardActiveSessionDetectorLogic.actions.markActive(SELF_DRIVING_WORKFLOW_ID)- return () => wizardActiveSessionDetectorLogic.actions.markInactive()- }, [])- return <Story />- },- mswDecorator({- get: {- '/api/projects/:id/signals/reports': () => [200, { results: [], count: 0, next: null, previous: null }],- '/api/projects/:id/signals/source_configs': () => [200, { results: [], count: 0 }],- '/api/projects/:id/signals/scout/configs': () => [200, []],- },- }),- ],-}-// Fresh project: nothing watching and nothing in the inbox → the full-pane welcome page (no tab row).export const SelfDrivingOnboarding: Story = {name: 'Welcome page with GitHub and manual setup',diff --git a/products/signals/frontend/inbox/components/SelfDrivingInstallingHint.tsx b/products/signals/frontend/inbox/components/SelfDrivingInstallingHint.tsxdeleted file mode 100644index c313c13f636c..000000000000--- a/products/signals/frontend/inbox/components/SelfDrivingInstallingHint.tsx+++ /dev/null@@ -1,23 +0,0 @@-import type React from 'react'--import { Spinner } from '@posthog/lemon-ui'--import { useSelfDrivingRunInFlight } from 'scenes/onboarding/shared/wizard-sync/hooks'--/**- * A quiet one-liner for empty states while the self-driving wizard is mid-run: the surface is empty- * because setup hasn't finished, not because nothing works. The caller words what this surface is- * waiting on; renders nothing when no run is going.- */-export function SelfDrivingInstallingHint({ children }: { children: React.ReactNode }): JSX.Element | null {- const runInFlight = useSelfDrivingRunInFlight()- if (!runInFlight) {- return null- }- return (- <span className="inline-flex items-center gap-1.5 text-xs text-tertiary mt-1">- <Spinner className="text-sm" />- {children}- </span>- )-}diff --git a/products/signals/frontend/inbox/components/emptyState/InboxWaitingForWork.tsx b/products/signals/frontend/inbox/components/emptyState/InboxWaitingForWork.tsxindex 0730df8992d5..f2250f006a89 100644--- a/products/signals/frontend/inbox/components/emptyState/InboxWaitingForWork.tsx+++ b/products/signals/frontend/inbox/components/emptyState/InboxWaitingForWork.tsx@@ -5,13 +5,11 @@ import { Link } from '@posthog/lemon-ui'import { urls } from 'scenes/urls'-import { inboxOnboardingLogic } from '../../logics/inboxOnboardingLogic'import { inboxSetupLogic } from '../../logics/inboxSetupLogic'import { scoutFleetLogic } from '../../logics/scoutFleetLogic'import { signalSourcesLogic } from '../../signalSourcesLogic'import { SignalSourceConfig, SignalSourceProduct, SignalSourceType } from '../../types'import { FirstReportProgress } from './FirstReportProgress'-import { InstallingFlowRow } from './InstallingFlowRow'import { ScoutFlowRow } from './ScoutFlowRow'import { SignalSourceFlowRow } from './SignalSourceFlowRow'@@ -42,7 +40,6 @@ export function InboxWaitingForWork(): JSX.Element {const { sourceConfigs, sourceConfigsLoading, hasEmittingScanner } = useValues(signalSourcesLogic)const { scoutConfigs, scoutConfigsLoading } = useValues(scoutFleetLogic)- const { isWizardRunning } = useValues(inboxOnboardingLogic)const { completed, savedState, firstReportProgress } = useValues(inboxSetupLogic)const enabledSources = [...uniqueEnabledSources(sourceConfigs),@@ -87,12 +84,8 @@ export function InboxWaitingForWork(): JSX.Element {<h3 className="m-0 text-sm font-semibold">Sources</h3><p className="m-0 text-xs text-tertiary">Events that start an investigation</p></div>- <span- className={`flex items-center gap-1 text-xs ${isWizardRunning ? 'text-warning' : 'text-success'}`}- >- {isWizardRunning ? (- 'Installing'- ) : sourcesLoading ? (+ <span className="flex items-center gap-1 text-xs text-success">+ {sourcesLoading ? ('Loading') : (<>@@ -110,8 +103,7 @@ export function InboxWaitingForWork(): JSX.Element {outcome={completed ? 'Investigate and create a report.' : undefined}/>))}- {isWizardRunning ? <InstallingFlowRow type="source" /> : null}- {!sourcesLoading && !isWizardRunning && visibleSources.length === 0 ? (+ {!sourcesLoading && visibleSources.length === 0 ? (<p className="m-0 p-3 text-xs text-tertiary">No sources are active.</p>) : null}</div>@@ -133,12 +125,8 @@ export function InboxWaitingForWork(): JSX.Element {<h3 className="m-0 text-sm font-semibold">Scouts</h3><p className="m-0 text-xs text-tertiary">Scheduled checks across your data</p></div>- <span- className={`flex items-center gap-1 text-xs ${isWizardRunning ? 'text-warning' : 'text-success'}`}- >- {isWizardRunning ? (- 'Installing'- ) : scoutsLoading ? (+ <span className="flex items-center gap-1 text-xs text-success">+ {scoutsLoading ? ('Loading') : (<>@@ -152,8 +140,7 @@ export function InboxWaitingForWork(): JSX.Element {{visibleScouts.map((scout) => (<ScoutFlowRow key={scout.id} scout={scout} />))}- {isWizardRunning ? <InstallingFlowRow type="scout" /> : null}- {!scoutsLoading && !isWizardRunning && visibleScouts.length === 0 ? (+ {!scoutsLoading && visibleScouts.length === 0 ? (<p className="m-0 p-3 text-xs text-tertiary">No scouts are active.</p>) : null}</div>diff --git a/products/signals/frontend/inbox/components/emptyState/InstallingFlowRow.tsx b/products/signals/frontend/inbox/components/emptyState/InstallingFlowRow.tsxdeleted file mode 100644index 49086ce6a630..000000000000--- a/products/signals/frontend/inbox/components/emptyState/InstallingFlowRow.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { IconBolt, IconCompass } from '@posthog/icons'-import { Spinner } from '@posthog/lemon-ui'--export function InstallingFlowRow({ type }: { type: 'source' | 'scout' }): JSX.Element {- const Icon = type === 'source' ? IconBolt : IconCompass- const title = type === 'source' ? 'Connecting sources' : 'Creating scheduled scouts'- const description =- type === 'source'- ? 'The setup agent is choosing and connecting signal sources.'- : 'The setup agent is creating scouts for this project.'-- return (- <div className="grid grid-cols-[2rem_minmax(0,1fr)_auto] items-center gap-3 border-b border-primary px-1 py-3 last:border-b-0">- <div className="relative flex size-8 items-center justify-center rounded-full border border-primary bg-bg-light text-tertiary">- <Icon />- <span- className="absolute -right-0.5 -top-0.5 size-2.5 rounded-full border-2 border-bg-light bg-warning motion-safe:animate-pulse"- aria-hidden- />- </div>- <div className="min-w-0">- <div className="text-sm font-medium">{title}</div>- <div className="mt-0.5 text-xs text-tertiary">{description}</div>- </div>- <Spinner className="text-sm text-warning" />- </div>- )-}diff --git a/products/signals/frontend/inbox/components/shell/InstallationCard.tsx b/products/signals/frontend/inbox/components/shell/InstallationCard.tsxdeleted file mode 100644index b74c0e830022..000000000000--- a/products/signals/frontend/inbox/components/shell/InstallationCard.tsx+++ /dev/null@@ -1,85 +0,0 @@-import { useActions, useValues } from 'kea'-import { useEffect } from 'react'--import { cn } from 'lib/utils/css-classes'-import { onboardingEventUsageLogic } from 'scenes/onboarding/onboardingEventUsageLogic'-import { currentTaskLabel, syncHeadline, toneTextClass } from 'scenes/onboarding/shared/wizard-sync/helpers'-import { useRunElapsedSeconds } from 'scenes/onboarding/shared/wizard-sync/hooks'-import { installationProgressLogic } from 'scenes/onboarding/shared/wizard-sync/installationProgressLogic'-import { PipStrip } from 'scenes/onboarding/shared/wizard-sync/PipStrip'-import { StatusGlyph } from 'scenes/onboarding/shared/wizard-sync/StatusGlyph'-import { WizardSyncDialog } from 'scenes/onboarding/shared/wizard-sync/WizardSyncDialog'-import { wizardSyncUiLogic } from 'scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic'--/**- * Rail-sized summary of a live wizard run: glyph + headline, the step it is on, and the pip strip.- * A miniature of the detached widget's collapsed card, restyled to sit among the setup widgets.- * Clicking it opens the same "all the details" dialog the detached widget uses.- */-export function InstallationCard({ workflowId }: { workflowId: string }): JSX.Element {- const { installationProgress, latestSession } = useValues(installationProgressLogic({ mode: 'local', workflowId }))- const { claimInlinePanel, releaseInlinePanel } = useActions(wizardSyncUiLogic)- const { dialogOpen } = useValues(wizardSyncUiLogic)- const { openDialog, closeDialog, openHandoffDoc } = useActions(wizardSyncUiLogic)- const { reportWizardSyncHandoffDocOpened } = useActions(onboardingEventUsageLogic)-- // This card is the local run's surface while the rail shows it, so the detached widget stands- // down for that run. A cloud run in flight at the same time keeps its own surface.- useEffect(() => {- claimInlinePanel('local')- return () => releaseInlinePanel('local')- }, [claimInlinePanel, releaseInlinePanel])-- // Elapsed clock, frozen at the run's last update once it reaches a terminal phase.- const isTerminal = installationProgress.phase === 'completed' || installationProgress.phase === 'error'- const elapsedSeconds = useRunElapsedSeconds(- latestSession?.started_at,- isTerminal ? latestSession?.updated_at : null- )-- // `currentTaskLabel` over the raw step so a run waiting on the user surfaces the question- // it is blocked on, which is the whole point of noticing it from here.- const detail = currentTaskLabel(installationProgress)-- const handoffText = installationProgress.handoffText- const runKey = latestSession?.session_id- const handleViewReport =- handoffText && runKey- ? () => {- reportWizardSyncHandoffDocOpened({ runKey, mode: 'local', trigger: 'button' })- openHandoffDoc({ key: runKey, text: handoffText })- }- : undefined- return (- <>- <button- type="button"- onClick={openDialog}- aria-label="Show setup progress details"- data-attr="inbox-installation-widget"- className="flex flex-col gap-1.5 rounded border border-primary bg-surface-primary px-2.5 py-2 text-left cursor-pointer transition-colors hover:border-secondary"- >- <div className="flex items-center gap-2 min-w-0 w-full">- <span className="shrink-0 [&_svg]:size-4 [&_.Spinner]:text-base">- <StatusGlyph progress={installationProgress} />- </span>- <span className={cn('text-[13px] font-medium truncate', toneTextClass(installationProgress))}>- {syncHeadline(installationProgress)}- </span>- </div>- {/* Wizard-supplied, so it can carry project detail that must not reach autocapture- — and this whole card is a clickable element, whose text autocapture would take. */}- {detail && <p className="m-0 text-xs text-secondary truncate w-full ph-no-capture">{detail}</p>}- <PipStrip steps={installationProgress.steps} />- </button>- <WizardSyncDialog- progress={installationProgress}- elapsedSeconds={elapsedSeconds}- mode="local"- isOpen={dialogOpen}- onClose={closeDialog}- onViewReport={handleViewReport}- />- </>- )-}diff --git a/products/signals/frontend/inbox/components/shell/InstallationSetupSection.tsx b/products/signals/frontend/inbox/components/shell/InstallationSetupSection.tsxdeleted file mode 100644index a6b11ad6a759..000000000000--- a/products/signals/frontend/inbox/components/shell/InstallationSetupSection.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { useValues } from 'kea'-import { useMountedLogic } from 'kea'--import { wizardActiveSessionDetectorLogic } from 'scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic'--import { SettingsSection } from '../tabs/SettingsSection'-import { InstallationCard } from './InstallationCard'--/**- * The "Installation" block of the Settings tab, present only while a wizard run is in flight.- * Renders its own section wrapper so the heading disappears with the run.- */-export function InstallationSetupSection(): JSX.Element | null {- // The detector's cheap poll is what tells us a run exists at all; mounting it here means the- // tab doesn't depend on the FAB being rendered to find the run.- useMountedLogic(wizardActiveSessionDetectorLogic)- const { shouldStream, activeWorkflowId } = useValues(wizardActiveSessionDetectorLogic)-- if (!shouldStream || !activeWorkflowId) {- return null- }-- return (- <SettingsSection title="Installation" description="The setup agent is still running in your repository.">- <InstallationCard workflowId={activeWorkflowId} />- </SettingsSection>- )-}diff --git a/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx b/products/signals/frontend/inbox/components/tabs/SettingsTab.tsxindex 2b0edda42c99..2f95ce52f16a 100644--- a/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx+++ b/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx@@ -11,7 +11,6 @@ import { RepoRoutingRules } from '../config/RepoRoutingRules'import { SelfDrivingSection } from '../config/SelfDrivingSection'import { SlackNotificationsSection } from '../config/SlackNotificationsSection'import { InboxUsageWidget } from '../shell/InboxUsageWidget'-import { InstallationSetupSection } from '../shell/InstallationSetupSection'import { UsageOverview } from '../spend/UsageOverview'import { SettingsSection } from './SettingsSection'@@ -24,7 +23,6 @@ export function SettingsTab(): JSX.Element {return (<div className="mx-auto flex w-full max-w-4xl flex-col gap-8 px-6 py-6">- <InstallationSetupSection /><SettingsSectiontitle="Autonomy"description="How much agents do on their own: opening pull requests, and how many reports arrive each day."diff --git a/products/signals/frontend/inbox/logics/inboxOnboardingLogic.test.ts b/products/signals/frontend/inbox/logics/inboxOnboardingLogic.test.tsindex ac519e21c824..ba71668aa3e7 100644--- a/products/signals/frontend/inbox/logics/inboxOnboardingLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxOnboardingLogic.test.ts@@ -1,5 +1,3 @@-import { SELF_DRIVING_WORKFLOW_ID } from 'scenes/onboarding/shared/wizard-sync/workflows'-import type { SignalScoutConfigApi } from 'products/signals/frontend/generated/api.schemas'import {@@ -10,8 +8,6 @@ import {InboxSettledUiState,OnboardingModeInputs,resolveDisplayMode,- resolveWizardState,- WizardStateInputs,} from './inboxOnboardingLogic'describe('inboxOnboardingLogic', () => {@@ -22,8 +18,6 @@ describe('inboxOnboardingLogic', () => {areCountsResolved: true,hasExistingWork: false,bannerDismissed: false,- isWizardRunning: false,- isWizardStateResolved: true,isRefetching: false,}@@ -55,12 +49,6 @@ describe('inboxOnboardingLogic', () => {{ isSelfDrivingSetUp: true, areCountsResolved: false },{ mode: 'none', reason: 'already_set_up' },],- // ...and no wait on the wizard detector either – its answer can't flip a set-up verdict.- [- 'set up, wizard state unknown (skipped)',- { isSelfDrivingSetUp: true, isWizardStateResolved: false },- { mode: 'none', reason: 'already_set_up' },- ],// Not set up + nothing in the inbox → full-pane takeover (nothing to block).['not set up, empty inbox', {}, { mode: 'takeover', reason: null }],// Not set up but work exists → non-blocking banner, so existing work stays accessible.@@ -77,39 +65,14 @@ describe('inboxOnboardingLogic', () => {{ bannerDismissed: true },{ mode: 'takeover', reason: null },],- // A run in flight is setup in progress: telling the user to go run the wizard would- // contradict the progress widget already showing it running.- [- 'wizard running, would otherwise take over',- { isWizardRunning: true },- { mode: 'none', reason: 'wizard_running' },- ],- [- 'wizard running, would otherwise banner',- { isWizardRunning: true, hasExistingWork: true },- { mode: 'none', reason: 'wizard_running' },- ],- // Until the detector has actually checked, "not running" is absence of evidence: the- // config/count loaders settle far faster than the detector's jittered poll, so acting on it- // would show the takeover to someone landing in the inbox mid-run.- [- 'wizard state unknown, would otherwise take over',- { isWizardStateResolved: false },- { mode: 'pending', reason: 'wizard_state_unknown' },- ],// Known work rules the takeover out – every remaining outcome renders the normal inbox, so// show it immediately; the banner joins once the remaining checks settle.- [- 'wizard state unknown, would otherwise banner',- { isWizardStateResolved: false, hasExistingWork: true },- { mode: 'none', reason: 'wizard_state_unknown' },- ],['with work, config still loading',{ isSetupLoaded: false, hasExistingWork: true },{ mode: 'none', reason: 'setup_loading' },],- // A refetch in flight (wizard just finished, or the user came back to the tab) means+ // A refetch in flight (the user came back to the tab) means// the loaded values may be stale – never commit to the takeover on them.['refetch in flight, would otherwise take over',@@ -167,26 +130,4 @@ describe('inboxOnboardingLogic', () => {expect(resolveDisplayMode(resolvedMode, lastSettledUiState)).toBe(expected)})})-- describe('resolveWizardState', () => {- const base: WizardStateInputs = {- hasResolvedSessionState: false,- watchedWorkflows: [SELF_DRIVING_WORKFLOW_ID],- verdictWaitExpired: false,- }-- it.each<[string, Partial<WizardStateInputs>, boolean]>([- // The detector answered, so `isWizardRunning` can be acted on however it landed.- ['detector settled', { hasResolvedSessionState: true }, true],- // Not watching the self-driving program: the detector's verdict could never flip- // `isWizardRunning`, so waiting on it would cost every inbox user a hold for nothing.- ['not watching the self-driving program', { watchedWorkflows: [] }, true],- // Watching and unsettled is the one case that genuinely has no answer yet.- ['watching, detector still pending', {}, false],- // The backstop. Without it, a detector whose polls keep erroring hides the only prompt to set self-driving up, for the whole session.- ['deadline elapsed with no verdict', { verdictWaitExpired: true }, true],- ])('%s', (_label, overrides, expected) => {- expect(resolveWizardState({ ...base, ...overrides })).toBe(expected)- })- })})diff --git a/products/signals/frontend/inbox/logics/inboxOnboardingLogic.ts b/products/signals/frontend/inbox/logics/inboxOnboardingLogic.tsindex cbd782fa9bc5..2badf12563d6 100644--- a/products/signals/frontend/inbox/logics/inboxOnboardingLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxOnboardingLogic.ts@@ -2,8 +2,6 @@ import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reduimport { router } from 'kea-router'import { subscriptions } from 'kea-subscriptions'-import { wizardActiveSessionDetectorLogic } from 'scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic'-import { SELF_DRIVING_WORKFLOW_ID } from 'scenes/onboarding/shared/wizard-sync/workflows'import { teamLogic } from 'scenes/teamLogic'import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'@@ -15,21 +13,10 @@ import { inboxSetupLogic } from './inboxSetupLogic'import { INBOX_REPORT_SECTION_LIST_PARAMS, reportListLogic } from './reportListLogic'import { scoutFleetLogic } from './scoutFleetLogic'-// Spread for the mount-time wizard check. Short enough that a user arriving from onboarding gets-// their verdict almost immediately, long enough that a fleet-wide reload doesn't land as one spike.-const MOUNT_CHECK_JITTER_MS = 3 * 1000-// Throttle for the return-to-tab refetch. The disposables plugin re-runs setup on every// `visibilitychange → visible`; without a floor, alt-tab flapping turns into request bursts.const VISIBILITY_REFETCH_THROTTLE_MS = 5 * 1000-// Ceiling on how long the wizard verdict may hold the prompt back. The verdict can never arrive:-// the shortcut below needs the feature-flag payload, which an ad blocker can drop entirely, and a-// detector whose endpoint keeps erroring only settles after enough consecutive failures. Both leave-// someone who has not set self-driving up on an inbox that never offers to. Well past the sub-second-// window the guard exists for (jitter plus one request), so capping it costs the normal path nothing.-const WIZARD_VERDICT_DEADLINE_MS = 15 * 1000-/** How the self-driving onboarding presents itself over the inbox. */export type InboxOnboardingMode = 'takeover' | 'banner' | 'none' | 'pending'@@ -44,14 +31,8 @@ export const INBOX_LAST_UI_STATE_STORAGE_KEY = 'inbox-onboarding-last-ui-state'/*** Why the onboarding is not showing. `null` whenever it is.- *- * `'wizard_running'` is the deliberate suppression; every other value is an input the decision is- * still waiting on, or a user who does not need onboarding at all. Carried into telemetry so a- * withheld prompt is distinguishable from an absent one.*/export type InboxOnboardingSuppressionReason =- | 'wizard_running'- | 'wizard_state_unknown'| 'setup_loading'| 'already_set_up'| 'counts_loading'@@ -64,34 +45,6 @@ export interface InboxOnboardingDecision {reason: InboxOnboardingSuppressionReason}-export interface WizardStateInputs {- /** The detector reached a verdict: a poll settled, a stream reported in, or polling was killed. */- hasResolvedSessionState: boolean- /** Programs the detector polls. */- watchedWorkflows: string[]- /** The deadline above elapsed with no verdict, so waiting longer only withholds the prompt. */- verdictWaitExpired: boolean-}--/**- * Whether `isWizardRunning === false` can be acted on.- *- * Trivially true when the detector isn't watching the self-driving program (no surface registered):- * its verdict could never flip `isWizardRunning`, so waiting on it, or polling eagerly for it, would- * cost every inbox user something for nothing.- *- * The deadline is the backstop for a detector that never answers. A takeover that waits is a worse- * first second than one that renders at once, but a takeover that never renders is the only failure- * a user can't recover from by waiting.- */-export function resolveWizardState({- hasResolvedSessionState,- watchedWorkflows,- verdictWaitExpired,-}: WizardStateInputs): boolean {- return hasResolvedSessionState || !watchedWorkflows.includes(SELF_DRIVING_WORKFLOW_ID) || verdictWaitExpired-}-export interface OnboardingModeInputs {/** Every watcher loader has settled, so the set-up verdict is trustworthy. */isSetupLoaded: boolean@@ -103,13 +56,8 @@ export interface OnboardingModeInputs {hasExistingWork: boolean/** The banner was dismissed this session. */bannerDismissed: boolean- /** A self-driving wizard run is in flight, so setup is already under way elsewhere. */- isWizardRunning: boolean- /** The wizard detector has actually checked, so `isWizardRunning === false` is a verdict rather- * than "nobody asked yet". */- isWizardStateResolved: boolean/** A config/count refetch is in flight, so the loaded values may be about to change (e.g. the- * wizard just finished, or the user returned to the tab). */+ * user returned to the tab). */isRefetching: boolean}@@ -119,13 +67,11 @@ export interface OnboardingModeInputs {* While the takeover is still on the table but the inputs haven't settled, the verdict is* `'pending'`: the scene renders a neutral skeleton with no tab bar, so the user never sees the* normal inbox flash in and get replaced by the welcome takeover (or vice versa). As soon as any- * settled input rules the takeover out – self-driving is set up, a wizard run is in flight, or- * work already exists (the banner is additive, not a replacement) – the normal inbox shows+ * settled input rules the takeover out – self-driving is set up, or work already exists (the banner is additive, not a replacement) – the normal inbox shows* immediately without waiting on the rest.** Each outcome carries the input it is waiting on (or the reason it is withheld), so telemetry can- * tell a prompt nobody needed from one that never resolved. `resolveWizardState` bounds the one- * wait that can hang forever.+ * tell a prompt nobody needed from one that never resolved.*/export function computeOnboardingDecision({isSetupLoaded,@@ -133,43 +79,29 @@ export function computeOnboardingDecision({areCountsResolved,hasExistingWork,bannerDismissed,- isWizardRunning,- isWizardStateResolved,isRefetching,}: OnboardingModeInputs): InboxOnboardingDecision {- // A run in flight is setup in progress: sources and scouts land as it goes, so telling the user- // to go and run the wizard would contradict the progress widget already showing it running.- if (isWizardRunning) {- return { mode: 'none', reason: 'wizard_running' }- }- // Set-up users go straight to their inbox the moment the config check lands – neither the- // wizard detector nor the report counts could flip their verdict to an onboarding.+ // Set-up users go straight to their inbox the moment the config check lands – the report+ // counts could not flip their verdict to an onboarding.if (isSetupLoaded && isSelfDrivingSetUp) {return { mode: 'none', reason: 'already_set_up' }}// Work already in the inbox rules the takeover out: the only remaining outcomes (banner /// none) both render the normal inbox, so show it now rather than holding a skeleton. The- // non-blocking banner joins once the config and wizard checks settle.+ // non-blocking banner joins once the config check settles.if (areCountsResolved && hasExistingWork) {if (!isSetupLoaded) {return { mode: 'none', reason: 'setup_loading' }}- if (!isWizardStateResolved) {- return { mode: 'none', reason: 'wizard_state_unknown' }- }return bannerDismissed ? { mode: 'none', reason: 'banner_dismissed' } : { mode: 'banner', reason: null }}// The takeover is still possible. Until every input has settled – configs (is anything- // watching?), counts (is there work to keep?), and the wizard detector (is a run in flight?) –- // committing to either UI risks flashing it and swapping it out, so hold the neutral skeleton.- // A refetch in flight means the loaded values may be stale in the same way (the wizard just- // finished, or the user returned to the tab), so it holds the takeover back too.+ // watching?) and counts (is there work to keep?) – committing to either UI risks flashing it+ // and swapping it out, so hold the neutral skeleton. A refetch in flight means the loaded values+ // may be stale in the same way (the user returned to the tab), so it holds the takeover back too.if (!isSetupLoaded) {return { mode: 'pending', reason: 'setup_loading' }}- if (!isWizardStateResolved) {- return { mode: 'pending', reason: 'wizard_state_unknown' }- }if (!areCountsResolved) {return { mode: 'pending', reason: 'counts_loading' }}@@ -235,23 +167,17 @@ export interface inboxOnboardingLogicValues {sourceConfigs: SignalSourceConfig[] | null // signalSourcesLogicsourceConfigsLoading: boolean // signalSourcesLogiccurrentTeamId: number | null // teamLogic- activeWorkflowId: string | null // wizardActiveSessionDetectorLogic- hasResolvedSessionState: boolean // wizardActiveSessionDetectorLogic- watchedWorkflows: string[] // wizardActiveSessionDetectorLogicareCountsResolved: booleanbannerDismissed: booleanhasExistingWork: booleanisRefetching: booleanisSelfDrivingSetUp: booleanisSetupLoaded: boolean- isWizardRunning: boolean- isWizardStateResolved: booleanlastSettledUiState: InboxSettledUiState | nulllastSettledUiStateByTeam: Record<string, InboxSettledUiState>onboardingDecision: InboxOnboardingDecisiononboardingMode: InboxOnboardingModeresolvedOnboardingMode: InboxOnboardingMode- verdictWaitExpired: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -260,15 +186,9 @@ export interface inboxOnboardingLogicActions {loadReportsCount: (_?: void | undefined) => void // reportListLogicloadScoutConfigs: (_?: void | undefined) => void // scoutFleetLogicloadSourceConfigs: () => any // signalSourcesLogic- checkWizardSession: () => {- value: true- } // wizardActiveSessionDetectorLogicdismissBanner: () => {value: true}- expireWizardVerdictWait: () => {- value: true- }refreshSetupState: () => {value: true}@@ -297,12 +217,6 @@ export interface inboxOnboardingLogicMeta {reportsCountLoading: boolean) => booleanhasExistingWork: (pullsCount: number | null, reportsCount: number | null) => boolean- isWizardRunning: (activeWorkflowId: string | null) => boolean- isWizardStateResolved: (- hasResolvedSessionState: boolean,- watchedWorkflows: string[],- verdictWaitExpired: boolean- ) => booleanisRefetching: (sourceConfigsLoading: boolean,scoutConfigsLoading: boolean,@@ -315,8 +229,6 @@ export interface inboxOnboardingLogicMeta {areCountsResolved: boolean,hasExistingWork: boolean,bannerDismissed: boolean,- isWizardRunning: boolean,- isWizardStateResolved: boolean,isRefetching: boolean) => InboxOnboardingDecisionresolvedOnboardingMode: (onboardingDecision: InboxOnboardingDecision) => InboxOnboardingMode@@ -329,7 +241,6 @@ export interface inboxOnboardingLogicMeta {lastSettledUiState: InboxSettledUiState | null,searchParams: Record<string, any>,isSelfDrivingSetUp: boolean,- isWizardRunning: boolean,setupInProgress: boolean,setupCompleted: boolean,setupStateLoading: boolean@@ -348,8 +259,7 @@ export type inboxOnboardingLogicType = MakeLogicType<* Decides how the self-driving onboarding presents itself. A project that completed the in-app* setup goes straight to its inbox, and one that is mid-setup keeps the takeover. For every other* project, "set up" is read from what ends up watching: at least one signal source or scout.- * `enabledSourcesCount` counts Replay Vision too, which reaches the inbox on its own, and a setup- * agent run detected in flight counts as setup under way.+ * `enabledSourcesCount` counts Replay Vision too, which reaches the inbox on its own.** When self-driving is NOT set up, the presentation depends on whether there's anything to show:* - nothing landed yet (no reports or PRs) → the inbox becomes a locked "Welcome" tab whose body is@@ -381,17 +291,12 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([listParams: INBOX_REPORT_SECTION_LIST_PARAMS['needs-decision'],}),['count as reportsCount', 'countLoading as reportsCountLoading'],- // Already mounted app-wide by the sync widget; connecting here just reads its verdict.- wizardActiveSessionDetectorLogic,- ['activeWorkflowId', 'hasResolvedSessionState', 'watchedWorkflows'],teamLogic,['currentTeamId'],router,['searchParams'],],actions: [- wizardActiveSessionDetectorLogic,- ['check as checkWizardSession'],signalSourcesLogic,['loadSourceConfigs'],scoutFleetLogic,@@ -408,14 +313,13 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([actions({dismissBanner: true,- expireWizardVerdictWait: true,setLastSettledUiState: (teamId: number, uiState: InboxSettledUiState) => ({ teamId, uiState }),refreshSetupState: true,}),listeners(({ actions }) => ({- // Re-pull everything the verdict is computed from. Fired when the wizard run ends and when- // the user returns to a tab whose verdict still says "not set up".+ // Re-pull everything the verdict is computed from. Fired when the user returns to a tab whose+ // verdict still says "not set up".refreshSetupState: () => {actions.loadSourceConfigs()actions.loadScoutConfigs()@@ -431,12 +335,6 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([dismissBanner: () => true,},],- verdictWaitExpired: [- false,- {- expireWizardVerdictWait: () => true,- },- ],// Keyed by team: the verdict is per team, and a cached verdict from another team must not// leak into this one's first paint after a project switch.lastSettledUiStateByTeam: [@@ -482,17 +380,8 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([(pullsCount: number | null, reportsCount: number | null): boolean =>(pullsCount ?? 0) + (reportsCount ?? 0) > 0,],- isWizardRunning: [- (s) => [s.activeWorkflowId],- (activeWorkflowId: string | null): boolean => activeWorkflowId === SELF_DRIVING_WORKFLOW_ID,- ],- isWizardStateResolved: [- (s) => [s.hasResolvedSessionState, s.watchedWorkflows, s.verdictWaitExpired],- (hasResolvedSessionState: boolean, watchedWorkflows: string[], verdictWaitExpired: boolean): boolean =>- resolveWizardState({ hasResolvedSessionState, watchedWorkflows, verdictWaitExpired }),- ],// A config or count request is in flight. While true, the verdict must not commit to the- // takeover: the wizard may just have finished, and the loaded values are about to change.+ // takeover: the loaded values are about to change.isRefetching: [(s) => [s.sourceConfigsLoading, s.scoutConfigsLoading, s.pullsCountLoading, s.reportsCountLoading],(@@ -512,8 +401,6 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([s.areCountsResolved,s.hasExistingWork,s.bannerDismissed,- s.isWizardRunning,- s.isWizardStateResolved,s.isRefetching,],(@@ -522,8 +409,6 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([areCountsResolved: boolean,hasExistingWork: boolean,bannerDismissed: boolean,- isWizardRunning: boolean,- isWizardStateResolved: boolean,isRefetching: boolean): InboxOnboardingDecision =>computeOnboardingDecision({@@ -532,8 +417,6 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([areCountsResolved,hasExistingWork,bannerDismissed,- isWizardRunning,- isWizardStateResolved,isRefetching,}),],@@ -557,7 +440,6 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([s.lastSettledUiState,s.searchParams,s.isSelfDrivingSetUp,- s.isWizardRunning,s.setupInProgress,s.setupCompleted,s.setupStateLoading,@@ -567,7 +449,6 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([lastSettledUiState: InboxSettledUiState | null,searchParams: Record<string, unknown>,isSelfDrivingSetUp: boolean,- isWizardRunning: boolean,setupInProgress: boolean,setupCompleted: boolean,setupStateLoading: boolean@@ -581,7 +462,7 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([if (setupStateLoading) {return 'pending'}- if (searchParams.setup === 'github-first' && !isSelfDrivingSetUp && !isWizardRunning) {+ if (searchParams.setup === 'github-first' && !isSelfDrivingSetUp) {return 'takeover'}return resolveDisplayMode(resolvedOnboardingMode, lastSettledUiState)@@ -611,25 +492,8 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([}actions.setLastSettledUiState(teamId, resolvedMode === 'takeover' ? 'takeover' : 'inbox')},- // A wizard run ending in this tab means sources and scouts probably just landed: re-pull- // them so the verdict flips to the real inbox without a page reload. `isRefetching` holds- // the takeover back until the fresh data arrives.- isWizardRunning: (isWizardRunning: boolean, previousIsWizardRunning: boolean | undefined) => {- if (previousIsWizardRunning === true && !isWizardRunning) {- actions.refreshSetupState()- }- },})),- // The detector's own first poll is jittered up to 30s to spread deploy-reload herds; someone- // landing in the inbox straight from onboarding can't wait that out with the takeover verdict- // hanging on the answer. One targeted poll on mount settles it in a request — gated on the- // verdict actually being pending, so the herd the jitter protects against (every inbox-parked- // tab reloading on a deploy) isn't reintroduced for users whose takeover can't be suppressed.- // The gate is pending for the whole self-driving arm on a fresh mount, though, so the poll- // still keeps a short jitter of its own: a deploy that reloads every inbox-parked tab spreads- // over a few seconds instead of arriving as one spike, while a user coming from onboarding- // still gets their answer far inside the 30s window.afterMount(({ actions, values, cache }) => {// Refetch on return to the tab, but only while the verdict still says "not set up": that// is the copy-the-command flow (terminal → wizard → back to this tab), where the configs@@ -650,33 +514,5 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([}return () => {}}, 'refetch-on-return')-- if (values.isWizardStateResolved) {- return- }- cache.disposables.add(() => {- // The plugin re-runs this on every return to a visible tab; the latch keeps it a- // one-shot rather than a poll of its own.- if (cache.mountCheckFired) {- return () => {}- }- const id = window.setTimeout(() => {- cache.mountCheckFired = true- actions.checkWizardSession()- }, Math.random() * MOUNT_CHECK_JITTER_MS)- return () => window.clearTimeout(id)- }, 'mount-wizard-check')-- // Backstop for a verdict that never lands. Runs while the tab is hidden too: a user who- // opens the inbox in a background tab and comes back to it should find the prompt already- // decided, not a timer that only started when they looked.- cache.disposables.add(- () => {- const id = window.setTimeout(() => actions.expireWizardVerdictWait(), WIZARD_VERDICT_DEADLINE_MS)- return () => window.clearTimeout(id)- },- 'wizard-verdict-deadline',- { pauseOnPageHidden: false }- )}),])diff --git a/products/wizard/frontend/WizardRunsScene.tsx b/products/wizard/frontend/WizardRunsScene.tsxindex b3f985c3319e..071a552b0bba 100644--- a/products/wizard/frontend/WizardRunsScene.tsx+++ b/products/wizard/frontend/WizardRunsScene.tsx@@ -39,7 +39,6 @@ export const scene: SceneExport = {export function WizardRunsScene(): JSX.Element {const wizardUiEnabled = useFeatureFlag('WIZARD_UI_ENABLED')- const runSyncEnabled = useFeatureFlag('WIZARD_RUN_SYNC', 'wizard-run')const { user } = useValues(userLogic)const {environment,@@ -242,7 +241,7 @@ export function WizardRunsScene(): JSX.Element {onCopyCommand={copyCommand}/>- {runSyncEnabled && currentProjectId ? (+ {currentProjectId ? (<WizardRunSceneSyncDetailsDialog projectId={String(currentProjectId)} onRunAgain={runAgain} />) : (<WizardRunDetailsDialog onRunAgain={runAgain} />diff --git a/products/wizard/frontend/runs/WizardRunError.tsx b/products/wizard/frontend/runs/WizardRunError.tsxdeleted file mode 100644index 2bf64656b4f8..000000000000--- a/products/wizard/frontend/runs/WizardRunError.tsx+++ /dev/null@@ -1,18 +0,0 @@-import type { WizardRunErrorDetails } from './wizardRunErrorCatalog'--export function WizardRunError({ error }: { error: WizardRunErrorDetails }): JSX.Element {- return (- <div className="space-y-2">- <div>- <div className="font-semibold">{error.title}</div>- {error.description !== error.title && <div className="text-sm">{error.description}</div>}- </div>- {error.resolution && (- <div>- <div className="text-sm font-semibold">What to do?</div>- <div className="text-sm">{error.resolution}</div>- </div>- )}- </div>- )-}diff --git a/products/wizard/frontend/runs/WizardRunSyncCard.stories.tsx b/products/wizard/frontend/runs/WizardRunSyncCard.stories.tsxdeleted file mode 100644index fb0a4947f06f..000000000000--- a/products/wizard/frontend/runs/WizardRunSyncCard.stories.tsx+++ /dev/null@@ -1,135 +0,0 @@-import type { Meta, StoryObj } from '@storybook/react'-import { useState } from 'react'--import type { WizardRunApi, WizardRunTaskApi } from '../generated/api.schemas'-import { WizardRunSyncCard } from './WizardRunSyncCard'-import { WizardRunSyncRunPicker } from './WizardRunSyncRunPicker'--const run: WizardRunApi = {- id: '00000000-0000-4000-8000-000000000001',- team_id: 1,- created_by_id: 1,- created_by: null,- environment: 'cloud',- workspace: { type: 'git_repository', repository: 'example/project' },- program: {- id: 'setup',- name: 'PostHog setup',- description: 'Set up analytics',- wizard_version: '1.0.0',- command: [],- tags: [],- required_programs: [],- supported_environments: ['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: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: null,- completed_at: null,- failed_at: null,- error_message: null,-})--const meta: Meta<typeof WizardRunSyncCard> = {- title: 'Products/Wizard/Wizard run sync card',- component: WizardRunSyncCard,- parameters: { layout: 'fullscreen', testOptions: { waitForLoadersToDisappear: false } },- decorators: [- (Story) => (- <div className="flex min-h-[640px] items-end justify-end bg-primary p-8">- <Story />- </div>- ),- ],- args: {- run,- elapsedSeconds: 134,- tasks: [- task('Identify the existing analytics integration', 'completed'),- task('Install the SDK and configure capture', 'running'),- task('Verify events in PostHog', 'created'),- ],- onExpand: () => {},- onExpandIcon: () => {},- onClose: () => {},- onHide: () => {},- },-}--export default meta-type Story = StoryObj<typeof meta>--export const Running: Story = {}--export const MultipleRuns: Story = {- render: function MultipleRunCard(args) {- const runs = [- run,- {- ...run,- id: '00000000-0000-4000-8000-000000000002',- environment: 'local' as const,- workspace: { type: 'local_folder' as const, project_name: 'example-project' },- created_at: '2026-09-23T09:30:00Z',- },- {- ...run,- id: '00000000-0000-4000-8000-000000000003',- status: 'completed' as const,- stage: null,- finished_at: '2026-09-23T09:05:00Z',- workspace: { type: 'git_repository' as const, repository: 'example/other-project' },- created_at: '2026-09-23T09:00:00Z',- },- ]- const [selectedRun, setSelectedRun] = useState<WizardRunApi>(run)-- return (- <WizardRunSyncCard- {...args}- run={selectedRun}- tasks={selectedRun.id === run.id ? args.tasks : []}- runPicker={- <WizardRunSyncRunPicker- runs={runs}- activeCount={2}- currentRunId={selectedRun.id}- onSelect={setSelectedRun}- onOpen={() => {}}- />- }- />- )- },-}--export const LocalRunning: Story = {- args: {- run: {- ...run,- environment: 'local',- workspace: { type: 'local_folder', project_name: 'example-project' },- stage: null,- },- },-}--export const Completed: Story = {- args: {- run: { ...run, status: 'completed', stage: null },- tasks: [task('Install the SDK and configure capture', 'running')],- },-}diff --git a/products/wizard/frontend/runs/WizardRunSyncCard.test.tsx b/products/wizard/frontend/runs/WizardRunSyncCard.test.tsxdeleted file mode 100644index 080f941ae202..000000000000--- a/products/wizard/frontend/runs/WizardRunSyncCard.test.tsx+++ /dev/null@@ -1,72 +0,0 @@-import { cleanup, fireEvent, render, screen } from '@testing-library/react'--import type { WizardRunApi, WizardRunTaskApi } from '../generated/api.schemas'-import { WizardRunSyncCard } from './WizardRunSyncCard'-import { WizardRunSyncRunPicker } from './WizardRunSyncRunPicker'--const run = {- status: 'running',- stage: 'executing_wizard',- program: { name: 'PostHog setup' },- workspace: { type: 'local_folder', project_name: 'example-project' },- environment: 'local',-} as WizardRunApi--const tasks = [{ name: 'Install the SDK', status: 'running' }] as WizardRunTaskApi[]--describe('WizardRunSyncCard', () => {- afterEach(cleanup)-- it('shows the current task only during the running stage', () => {- const props = {- run,- tasks,- elapsedSeconds: 10,- onExpand: jest.fn(),- onExpandIcon: jest.fn(),- onClose: jest.fn(),- onHide: jest.fn(),- }- const { rerender } = render(<WizardRunSyncCard {...props} />)-- expect(screen.getByText('Install the SDK')).toBeTruthy()-- rerender(<WizardRunSyncCard {...props} run={{ ...run, stage: 'creating_artifacts' }} />)- expect(screen.queryByText('Install the SDK')).toBeNull()-- rerender(<WizardRunSyncCard {...props} run={{ ...run, status: 'completed', stage: null }} />)- expect(screen.getByText('Completed successfully')).toBeTruthy()- expect(screen.queryByText('Install the SDK')).toBeNull()- })-- it('switches to a different run without restarting the selected run', () => {- const currentRun = { ...run, id: 'current', created_at: '2026-01-01T10:00:00Z' }- const otherRun = {- ...currentRun,- id: 'other',- status: 'completed' as const,- workspace: { type: 'local_folder' as const, project_name: 'other-project' },- }- const onSelect = jest.fn()- render(- <WizardRunSyncRunPicker- runs={[currentRun, otherRun]}- activeCount={1}- currentRunId={currentRun.id}- onSelect={onSelect}- onOpen={jest.fn()}- />- )-- const trigger = screen.getByLabelText('Switch Wizard run, 2 recent runs, 1 active runs')- fireEvent.click(trigger)- expect(screen.getByText('Completed')).toBeTruthy()- expect(screen.getByText('In progress')).toBeTruthy()- fireEvent.click(screen.getByText('example-project'))- expect(onSelect).not.toHaveBeenCalled()-- fireEvent.click(trigger)- fireEvent.click(screen.getByText('other-project'))- expect(onSelect).toHaveBeenCalledWith(otherRun)- })-})diff --git a/products/wizard/frontend/runs/WizardRunSyncCard.tsx b/products/wizard/frontend/runs/WizardRunSyncCard.tsxdeleted file mode 100644index d5a78965bf1a..000000000000--- a/products/wizard/frontend/runs/WizardRunSyncCard.tsx+++ /dev/null@@ -1,155 +0,0 @@-import type { ReactNode } from 'react'--import { IconCheckCircle, IconCloud, IconExpand45, IconLaptop, IconWarning, IconX } from '@posthog/icons'-import { LemonButton, LemonMenu, Spinner } from '@posthog/lemon-ui'--import { cn } from 'lib/utils/css-classes'-import { formatElapsed } from 'scenes/onboarding/shared/wizard-sync/helpers'--import type { WizardRunApi, WizardRunTaskApi } from '../generated/api.schemas'-import type { WizardRunProgressState } from '../wizardRunDisplay'-import {- wizardRunCurrentState,- wizardRunProgressState,- wizardRunStagePosition,- wizardWorkspaceLabel,-} from '../wizardRunDisplay'--function RunStatusGlyph({ status }: { status: WizardRunApi['status'] }): JSX.Element {- if (status === 'completed') {- return <IconCheckCircle className="shrink-0 text-xl text-success" />- }- if (status === 'failed' || status === 'cancelled') {- return <IconWarning className="shrink-0 text-xl text-danger" />- }- return <Spinner className="shrink-0 text-xl text-accent" textColored />-}--function pipClass(state: WizardRunProgressState): string {- switch (state) {- case 'complete':- return 'bg-success'- case 'active':- return 'bg-accent animate-pulse'- case 'failed':- return 'bg-danger'- default:- return 'bg-border'- }-}--export function WizardRunSyncCard({- run,- tasks,- elapsedSeconds,- onExpand,- onExpandIcon,- onClose,- onHide,- runPicker,-}: {- run: WizardRunApi- tasks: readonly WizardRunTaskApi[]- elapsedSeconds: number- onExpand: () => void- onExpandIcon: () => void- onClose: () => void- onHide: () => void- runPicker?: ReactNode-}): JSX.Element {- const currentTask =- run.status === 'running' && wizardRunStagePosition(run) === 2- ? tasks.find((task) => task.status === 'running')- : undefined- const currentState = wizardRunCurrentState(run)- const states = [0, 1, 2, 3].map((step) => wizardRunProgressState(run, step))- const completed = states.filter((state) => state === 'complete').length- const workspace = wizardWorkspaceLabel(run)-- return (- <div- className="w-[340px] max-w-full overflow-hidden rounded-xl border border-primary bg-surface-primary shadow-xl shadow-black/10"- role="status"- aria-live="polite"- data-attr="wizard-run-sync-card"- >- {runPicker && <div className="border-b border-primary px-2 py-1">{runPicker}</div>}- <button- type="button"- onClick={onExpand}- aria-label="Expand Wizard run details"- className="flex w-full cursor-pointer flex-col gap-2.5 px-3.5 py-3 text-left transition-colors hover:bg-fill-highlight-50"- >- <div className="flex items-center gap-2.5">- <RunStatusGlyph status={run.status} />- <div className="min-w-0 flex-1">- <p- className={cn(- 'm-0 truncate text-sm font-semibold ph-no-capture',- run.status === 'completed'- ? 'text-success'- : run.status === 'failed' || run.status === 'cancelled'- ? 'text-danger'- : 'text-accent'- )}- title={currentTask?.name}- >- {currentTask?.name ?? currentState}- </p>- <p className="m-0 truncate text-xs text-muted">- {currentTask ? currentState : run.program.name}- </p>- </div>- <span className="shrink-0 text-xs tabular-nums text-muted">{formatElapsed(elapsedSeconds)}</span>- </div>- <div className="flex items-center gap-2">- <div className="flex w-full items-center gap-1" aria-hidden="true">- {states.map((state, index) => (- <span key={index} className={cn('h-1 flex-1 rounded-full', pipClass(state))} />- ))}- </div>- <span className="shrink-0 text-xs tabular-nums text-muted">- {completed}/{states.length}- </span>- </div>- </button>- <div className="flex items-center justify-between gap-2 border-t border-primary px-3.5 py-2">- <span className="flex min-w-0 items-center gap-1 text-xs text-muted ph-no-capture">- {run.environment === 'cloud' ? (- <IconCloud className="shrink-0" />- ) : (- <IconLaptop className="shrink-0" />- )}- <span className="shrink-0">{run.environment === 'cloud' ? 'Cloud run' : 'Local run'}</span>- <span aria-hidden="true">·</span>- <span className="truncate" title={workspace}>- {workspace}- </span>- </span>- <div className="flex shrink-0 items-center gap-1">- <LemonButton- size="xsmall"- icon={<IconExpand45 />}- onClick={onExpandIcon}- tooltip="See all the details"- aria-label="Expand"- />- <LemonMenu- items={[- { label: 'Close', onClick: onClose },- { label: "Don't show this run again", onClick: onHide },- ]}- placement="top-end"- >- <LemonButton- size="xsmall"- icon={<IconX />}- tooltip="Close options"- aria-label="Close options"- />- </LemonMenu>- </div>- </div>- </div>- )-}diff --git a/products/wizard/frontend/runs/WizardRunSyncDetailsDialog.tsx b/products/wizard/frontend/runs/WizardRunSyncDetailsDialog.tsxdeleted file mode 100644index 691efce50291..000000000000--- a/products/wizard/frontend/runs/WizardRunSyncDetailsDialog.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { useActions, useMountedLogic } from 'kea'-import { useEffect } from 'react'--import type { WizardRunApi, WizardRunTaskApi } from '../generated/api.schemas'-import { type WizardRunDetailSource, wizardRunDetailsLogic } from '../wizardRunDetailsLogic'-import { WizardRunDetailsDialog } from './WizardRunDetailsDialog'--export function WizardRunSyncDetailsDialog({- run,- tasks,- source,- onClose,-}: {- run: WizardRunApi- tasks: readonly WizardRunTaskApi[]- source: WizardRunDetailSource- onClose: () => void-}): JSX.Element {- useMountedLogic(wizardRunDetailsLogic)- const { selectRun } = useActions(wizardRunDetailsLogic)-- useEffect(() => {- selectRun(run, source)- return () => selectRun(null)- }, [run, selectRun, source])-- return <WizardRunDetailsDialog tasks={tasks} onClose={onClose} />-}diff --git a/products/wizard/frontend/runs/WizardRunSyncFab.tsx b/products/wizard/frontend/runs/WizardRunSyncFab.tsxdeleted file mode 100644index 509a609b9722..000000000000--- a/products/wizard/frontend/runs/WizardRunSyncFab.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { useValues } from 'kea'--import { projectLogic } from 'scenes/projectLogic'--import { WizardRunSyncProject } from './WizardRunSyncProject'--export function WizardRunSyncFab(): JSX.Element | null {- const { currentProjectId } = useValues(projectLogic)-- return currentProjectId ? (- <WizardRunSyncProject key={currentProjectId} projectId={String(currentProjectId)} />- ) : null-}diff --git a/products/wizard/frontend/runs/WizardRunSyncProject.tsx b/products/wizard/frontend/runs/WizardRunSyncProject.tsxdeleted file mode 100644index e9f633ac9cb7..000000000000--- a/products/wizard/frontend/runs/WizardRunSyncProject.tsx+++ /dev/null@@ -1,93 +0,0 @@-import { useActions, useMountedLogic, useValues } from 'kea'-import { Suspense, lazy, useState } from 'react'--import { lemonToast } from '@posthog/lemon-ui'--import { useInterval } from 'lib/hooks/useInterval'-import { elapsedSecondsFrom } from 'lib/utils/datetime'-import { retryImport } from 'lib/utils/retryImport'-import { ChunkLoadErrorBoundary } from 'scenes/ChunkLoadErrorBoundary'-import { sceneLogic } from 'scenes/sceneLogic'--import type { WizardRunApi } from '../generated/api.schemas'-import { wizardRunDetailsLogic } from '../wizardRunDetailsLogic'-import type { WizardRunDetailSource } from '../wizardRunDetailsLogic'-import { wizardRunIsActive } from '../wizardRunDisplay'-import { WizardRunSyncCard } from './WizardRunSyncCard'-import { wizardRunSyncLogic } from './wizardRunSyncLogic'-import { WizardRunSyncRunPicker } from './WizardRunSyncRunPicker'--// Every logged-in page renders this component, and the dialog opens only on click.-const WizardRunSyncDetailsDialog = lazy(() =>- retryImport(() => import('./WizardRunSyncDetailsDialog').then((m) => ({ default: m.WizardRunSyncDetailsDialog })))-)--export function WizardRunSyncProject({ projectId }: { projectId: string }): JSX.Element {- const logic = wizardRunSyncLogic({ projectId })- useMountedLogic(logic)- const { activeCount, visibleRuns, closedRunIds, dismissedRunIds, run, tasks } = useValues(logic)- const { closeRun, dismissRun, expandFab, selectRun: selectSyncRun } = useActions(logic)- const { sceneKey } = useValues(sceneLogic)- const [dialogRun, setDialogRun] = useState<{ run: WizardRunApi; source: WizardRunDetailSource } | null>(null)- const [now, setNow] = useState(Date.now)- const runHidden = run && (closedRunIds.includes(run.id) || dismissedRunIds.includes(run.id))- useInterval(() => setNow(Date.now()), run && !runHidden && wizardRunIsActive(run) ? 1000 : null)-- const endMs = run?.finished_at ? new Date(run.finished_at).getTime() : now- const elapsedSeconds = run ? elapsedSecondsFrom(run.started_at ?? run.created_at, endMs) : 0-- const openDetails = (source: WizardRunDetailSource): void => {- if (!run) {- return- }- if (sceneKey === 'wizardRuns') {- wizardRunDetailsLogic.actions.selectRun(run, source)- } else {- setDialogRun({ run, source })- }- }-- return (- <>- {run && !runHidden && (- <div className="fixed bottom-5 right-5 z-[60] max-w-[calc(100vw-2.5rem)]">- <WizardRunSyncCard- run={run}- tasks={tasks}- elapsedSeconds={elapsedSeconds}- runPicker={- (activeCount > 1 || visibleRuns.length > 1) && (- <WizardRunSyncRunPicker- runs={visibleRuns}- activeCount={activeCount}- currentRunId={run.id}- onSelect={selectSyncRun}- onOpen={() => expandFab(visibleRuns.length)}- />- )- }- onExpand={() => openDetails('fab_click')}- onExpandIcon={() => openDetails('fab_expand_icon_click')}- onClose={() => closeRun(run.id)}- onHide={() => {- dismissRun(run.id)- lemonToast.info('You can still follow this run on the Wizard page.')- }}- />- </div>- )}- {dialogRun && (- <ChunkLoadErrorBoundary>- <Suspense fallback={null}>- <WizardRunSyncDetailsDialog- run={dialogRun.run}- tasks={dialogRun.run.id === run?.id ? tasks : []}- source={dialogRun.source}- onClose={() => setDialogRun(null)}- />- </Suspense>- </ChunkLoadErrorBoundary>- )}- </>- )-}diff --git a/products/wizard/frontend/runs/WizardRunSyncRunPicker.tsx b/products/wizard/frontend/runs/WizardRunSyncRunPicker.tsxdeleted file mode 100644index 276af44bc02e..000000000000--- a/products/wizard/frontend/runs/WizardRunSyncRunPicker.tsx+++ /dev/null@@ -1,64 +0,0 @@-import { IconCheck, IconChevronDown, IconCloud, IconLaptop } from '@posthog/icons'-import { LemonButton, LemonMenu, type LemonMenuItems } from '@posthog/lemon-ui'--import { urls } from 'scenes/urls'--import type { WizardRunApi } from '../generated/api.schemas'-import { wizardRunIsActive, wizardRunTerminalLabel, wizardWorkspaceLabel } from '../wizardRunDisplay'--export function WizardRunSyncRunPicker({- runs,- activeCount,- currentRunId,- onSelect,- onOpen,-}: {- runs: readonly WizardRunApi[]- activeCount: number- currentRunId: string- onSelect: (run: WizardRunApi) => void- onOpen: () => void-}): JSX.Element {- const currentIndex = runs.findIndex((run) => run.id === currentRunId)- const items: LemonMenuItems = runs.map((run) => ({- label: (- <span className="block min-w-0 text-left ph-no-capture">- <span className="block truncate font-medium">{wizardWorkspaceLabel(run)}</span>- <span className="block text-xs text-muted">- {wizardRunIsActive(run) ? 'In progress' : wizardRunTerminalLabel(run.status)}- </span>- <span className="block truncate text-xs text-muted">- {run.program.name} ·{' '}- {new Date(run.created_at).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}- </span>- </span>- ),- icon: run.environment === 'cloud' ? <IconCloud /> : <IconLaptop />,- sideIcon: run.id === currentRunId ? <IconCheck aria-label="Selected run" /> : undefined,- active: run.id === currentRunId,- onClick: (): void => {- if (run.id !== currentRunId) {- onSelect(run)- }- },- }))-- items.push({ label: 'View all runs', to: urls.wizardRuns() })-- return (- <LemonMenu items={items} matchWidth placement="top-end">- <LemonButton- size="xsmall"- fullWidth- sideIcon={<IconChevronDown />}- aria-label={`Switch Wizard run, ${runs.length} recent runs, ${activeCount} active runs`}- // Keep the analytics selector stable when the picker layout changes.- data-attr="wizard-run-sync-stack"- onClick={onOpen}- >- <span>{currentIndex >= 0 ? `Run ${currentIndex + 1} of ${runs.length}` : 'Recent runs'}</span>- {activeCount > 0 && <span className="ml-auto text-muted">{`${activeCount} active`}</span>}- </LemonButton>- </LemonMenu>- )-}diff --git a/products/wizard/frontend/runs/wizardRunSyncLogic.test.ts b/products/wizard/frontend/runs/wizardRunSyncLogic.test.tsindex 561489801512..fc347c010d7e 100644--- a/products/wizard/frontend/runs/wizardRunSyncLogic.test.ts+++ b/products/wizard/frontend/runs/wizardRunSyncLogic.test.ts@@ -1,7 +1,6 @@import { installMockEventSource, MockEventSource } from 'lib/wizard-sync/eventSource.mock'import { expectLogic } from 'kea-test-utils'-import posthog from 'posthog-js'import { initKeaTests } from '~/test/init'@@ -32,9 +31,7 @@ describe('wizardRunSyncLogic', () => {let logic: ReturnType<typeof wizardRunSyncLogic.build>beforeEach(() => {- localStorage.clear()initKeaTests()- jest.spyOn(posthog, 'capture').mockClear()restoreEventSource = installMockEventSource()mockWizardRunsList.mockReset()mockRunPages({ count: 2, results: [run('newer')] })@@ -60,7 +57,6 @@ describe('wizardRunSyncLogic', () => {created_after: '2026-09-28T00:00:00Z',limit: 5,})- expect(logic.values.activeCount).toBe(2)expect(logic.values.run?.id).toBe('newer')expect(MockEventSource.instances).toHaveLength(1)@@ -84,42 +80,8 @@ describe('wizardRunSyncLogic', () => {expect(logic.values.tasks).toEqual([])})- it('keeps a selected run when it completes and lets another active run be selected', async () => {- await expectLogic(logic).toFinishAllListeners()- const newerStream = MockEventSource.last()- const older = run('older')- mockRunPages({ count: 2, results: [run('newer'), older] })- logic.actions.checkRuns()- await expectLogic(logic).toFinishAllListeners()-- logic.actions.selectRun(older)- expect(logic.values.run?.id).toBe('older')- expect(newerStream.readyState).toBe(MockEventSource.CLOSED)- expect(MockEventSource.last().url).toBe('/api/projects/1/wizard/runs/older/stream/')-- const olderStream = MockEventSource.last()- mockRunPages({ count: 3, results: [run('latest'), run('newer'), older] })- logic.actions.checkRuns()- await expectLogic(logic).toFinishAllListeners()- expect(logic.values.run?.id).toBe('older')- expect(MockEventSource.instances).toHaveLength(2)-- const completed = { ...older, status: 'completed' as const, stage: null }- mockRunPages({ count: 2, results: [run('latest'), run('newer')] }, [completed])- olderStream.emitMessage(JSON.stringify({ status: 'completed', stage: null, tasks: [] }))- await expectLogic(logic).toFinishAllListeners()- expect(logic.values.run?.id).toBe('older')- expect(logic.values.visibleRuns.map((run) => run.id)).toEqual(['latest', 'newer', 'older'])- expect(logic.values.activeCount).toBe(2)- expect(MockEventSource.instances).toHaveLength(2)- expect(olderStream.readyState).toBe(MockEventSource.CLOSED)-- logic.actions.selectRun(run('latest'))- expect(MockEventSource.instances).toHaveLength(3)- })-it.each(['completed', 'failed', 'cancelled'] as const)(- 'loads %s runs after reloading, keeps them selectable, and respects dismissal',+ 'loads %s runs after reloading and switches to the next active run',async (status) => {await expectLogic(logic).toFinishAllListeners()const stream = MockEventSource.last()@@ -146,15 +108,7 @@ describe('wizardRunSyncLogic', () => {logic.actions.checkRuns()await expectLogic(logic).toFinishAllListeners()expect(logic.values.run?.id).toBe('next')- logic.actions.selectRun(terminal)- expect(MockEventSource.last().readyState).toBe(MockEventSource.CLOSED)expect(MockEventSource.instances).toHaveLength(2)-- logic.actions.dismissRun('newer')- expect(logic.values.run?.id).toBe('next')- logic.actions.checkRuns()- await expectLogic(logic).toFinishAllListeners()- expect(logic.values.visibleRuns.map((run) => run.id)).toEqual(['next'])})@@ -163,96 +117,15 @@ describe('wizardRunSyncLogic', () => {mockRunPages({ count: 1, results: [run('newer')] }, [run('newer')])logic.actions.checkRuns()await expectLogic(logic).toFinishAllListeners()- expect(logic.values.visibleRuns.map((run) => run.id)).toEqual(['newer'])- expect(logic.values.activeCount).toBe(1)+ expect(logic.values.runs.map((run) => run.id)).toEqual(['newer'])const completed = { ...run('newer'), status: 'completed' as const, stage: null }mockRunPages({ count: 1, results: [run('newer')] }, [completed])logic.actions.checkRuns()await expectLogic(logic).toFinishAllListeners()- expect(logic.values.visibleRuns).toEqual([completed])+ expect(logic.values.runs).toEqual([completed])expect(logic.values.run?.status).toBe('completed')- expect(logic.values.activeCount).toBe(0)expect(MockEventSource.last().readyState).toBe(MockEventSource.CLOSED)})-- it('keeps a dismissed run hidden while polling and streams the next run', async () => {- await expectLogic(logic).toFinishAllListeners()- const stream = MockEventSource.last()-- logic.actions.dismissRun('newer')- expect(stream.readyState).toBe(MockEventSource.CLOSED)- expect(logic.values.dismissedRunIds).toEqual(['newer'])-- logic.actions.checkRuns()- await expectLogic(logic).toFinishAllListeners()- expect(MockEventSource.instances).toHaveLength(1)-- mockRunPages({ count: 1, results: [run('next')] })- logic.actions.checkRuns()- await expectLogic(logic).toFinishAllListeners()- expect(logic.values.run?.id).toBe('next')- expect(MockEventSource.instances).toHaveLength(2)-- mockRunPages({ count: 1, results: [run('newer')] })- logic.actions.checkRuns()- await expectLogic(logic).toFinishAllListeners()- expect(logic.values.dismissedRunIds).toEqual(['newer'])- expect(MockEventSource.instances).toHaveLength(2)-- logic.unmount()- logic = wizardRunSyncLogic({ projectId: '1' })- logic.mount()- await expectLogic(logic).toFinishAllListeners()- expect(logic.values.dismissedRunIds).toEqual(['newer'])- expect(MockEventSource.instances).toHaveLength(2)- })-- it('closes the current run until the page reloads', async () => {- await expectLogic(logic).toFinishAllListeners()-- logic.actions.closeRun('newer')- expect(logic.values.closedRunIds).toEqual(['newer'])- expect(logic.values.dismissedRunIds).toEqual([])- expect(MockEventSource.last().readyState).toBe(MockEventSource.CLOSED)-- logic.actions.checkRuns()- await expectLogic(logic).toFinishAllListeners()- expect(MockEventSource.instances).toHaveLength(1)-- logic.unmount()- logic = wizardRunSyncLogic({ projectId: '1' })- logic.mount()- await expectLogic(logic).toFinishAllListeners()- expect(logic.values.closedRunIds).toEqual([])- expect(MockEventSource.instances).toHaveLength(2)-- mockRunPages({ count: 1, results: [run('next')] })- logic.actions.checkRuns()- await expectLogic(logic).toFinishAllListeners()- expect(logic.values.run?.id).toBe('next')- expect(MockEventSource.instances).toHaveLength(3)- })-- it('tracks FAB expansion and both close options', async () => {- await expectLogic(logic).toFinishAllListeners()-- logic.actions.expandFab(3)- logic.actions.closeRun('newer')- logic.actions.dismissRun('older')-- expect(posthog.capture).toHaveBeenCalledWith('wizard run sync fab expanded', {- event_source: 'wizard_ui',- runs_count: 3,- })- expect(posthog.capture).toHaveBeenCalledWith(- 'wizard run sync fab closed',- expect.objectContaining({ wizard_run_id: 'newer', type: 'dismiss' })- )- expect(posthog.capture).toHaveBeenCalledWith(- 'wizard run sync fab closed',- expect.objectContaining({ wizard_run_id: 'older', type: 'close_forever' })- )- })})diff --git a/products/wizard/frontend/runs/wizardRunSyncLogic.ts b/products/wizard/frontend/runs/wizardRunSyncLogic.tsindex 46740f44dbfb..ad4651a7c2c2 100644--- a/products/wizard/frontend/runs/wizardRunSyncLogic.ts+++ b/products/wizard/frontend/runs/wizardRunSyncLogic.ts@@ -1,5 +1,4 @@-import { MakeLogicType, actions, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'-import posthog from 'posthog-js'+import { MakeLogicType, actions, events, kea, key, listeners, path, props, reducers } from 'kea'import { getWizardRunsStreamRetrieveUrl, wizardRunsList } from '../generated/api'import type { WizardRunApi, WizardRunTaskApi, WizardRunTaskListApi } from '../generated/api.schemas'@@ -7,9 +6,7 @@ import { wizardRunIsActive } from '../wizardRunDisplay'const RUN_POLL_MS = 30_000-// Cutoff for wizard runs to be shown in the FAB.-// This prevents users who already ran the wizard to get a FAB-// for older runs.+// 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@@ -25,27 +22,18 @@ export interface wizardRunSyncLogicProps {}export interface wizardRunSyncLogicValues {- activeCount: numberruns: WizardRunApi[]- visibleRuns: WizardRunApi[]- closedRunIds: string[]- dismissedRunIds: string[]run: WizardRunApi | null- selectedRunId: string | nulltasks: readonly WizardRunTaskApi[]}export interface wizardRunSyncLogicActions {checkRuns: () => { value: true }- runsLoaded: (count: number, runs: WizardRunApi[]) => { count: number; runs: WizardRunApi[] }+ runsLoaded: (runs: WizardRunApi[]) => { runs: WizardRunApi[] }clearTasks: () => { value: true }runUpdated: (state: RunStreamState) => { state: RunStreamState }showRun: (run: WizardRunApi | null) => { run: WizardRunApi | null }- selectRun: (run: WizardRunApi) => { run: WizardRunApi }connectRun: () => { value: true }- closeRun: (runId: string) => { runId: string }- dismissRun: (runId: string) => { runId: string }- expandFab: (runsCount: number) => { runsCount: number }}export type wizardRunSyncLogicType = MakeLogicType<@@ -60,44 +48,21 @@ export const wizardRunSyncLogic = kea<wizardRunSyncLogicType>([key((logicProps) => logicProps.projectId),actions({checkRuns: true,- runsLoaded: (count: number, runs: WizardRunApi[]) => ({ count, runs }),+ runsLoaded: (runs: WizardRunApi[]) => ({ runs }),clearTasks: true,runUpdated: (state: RunStreamState) => ({ state }),showRun: (run: WizardRunApi | null) => ({ run }),- selectRun: (run: WizardRunApi) => ({ run }),connectRun: true,- closeRun: (runId: string) => ({ runId }),- dismissRun: (runId: string) => ({ runId }),- expandFab: (runsCount: number) => ({ runsCount }),}),reducers({- activeCount: [0, { runsLoaded: (_, { count }) => count }],runs: [[] as WizardRunApi[], { runsLoaded: (_, { runs }) => runs }],- closedRunIds: [[] as string[], { closeRun: (current, { runId }) => [...current, runId] }],- dismissedRunIds: [- [] as string[],- { persist: true },- { dismissRun: (current, { runId }) => (current.includes(runId) ? current : [...current, runId]) },- ],- selectedRunId: [- null as string | null,- {- runsLoaded: (current, { runs }) => (current && runs.some((run) => run.id === current) ? current : null),- selectRun: (_, { run }) => run.id,- closeRun: (current, { runId }) => (current === runId ? null : current),- dismissRun: (current, { runId }) => (current === runId ? null : current),- },- ],run: [null as WizardRunApi | null,{runsLoaded: (current, { runs }) =>current ? (runs.find((run) => run.id === current.id) ?? current) : null,showRun: (_, { run }) => run,- selectRun: (_, { run }) => run,runUpdated: (current, { state }) => (current ? { ...current, ...state } : null),- closeRun: () => null,- dismissRun: () => null,},],tasks: [@@ -105,20 +70,10 @@ export const wizardRunSyncLogic = kea<wizardRunSyncLogicType>([{clearTasks: () => [],showRun: () => [],- selectRun: () => [],runUpdated: (_, { state }) => state.tasks,- closeRun: () => [],- dismissRun: () => [],},],}),- selectors({- visibleRuns: [- (s) => [s.runs, s.closedRunIds, s.dismissedRunIds],- (runs: WizardRunApi[], closedRunIds: string[], dismissedRunIds: string[]): WizardRunApi[] =>- runs.filter((run) => !closedRunIds.includes(run.id) && !dismissedRunIds.includes(run.id)),- ],- }),listeners(({ actions, cache, props: logicProps, values }) => ({checkRuns: async () => {if (cache.checking) {@@ -140,7 +95,7 @@ export const wizardRunSyncLogic = kea<wizardRunSyncLogicType>([const activeRuns = activePage.results.map((run) => recentPage.results.find((recentRun) => recentRun.id === run.id) ?? run).filter(wizardRunIsActive)- actions.runsLoaded(activePage.count - (activePage.results.length - activeRuns.length), [+ actions.runsLoaded([...activeRuns,...recentPage.results.filter((run) => !activeRuns.some((activeRun) => activeRun.id === run.id)),])@@ -151,26 +106,15 @@ export const wizardRunSyncLogic = kea<wizardRunSyncLogicType>([}},runsLoaded: () => {- const nextRun =- values.visibleRuns.find((run) => run.id === values.selectedRunId) ??- values.visibleRuns[0] ??- (values.run && !wizardRunIsActive(values.run) ? values.run : null)+ const nextRun = values.runs[0] ?? (values.run && !wizardRunIsActive(values.run) ? values.run : null)if (nextRun?.id !== values.run?.id) {actions.showRun(nextRun)}actions.connectRun()},- selectRun: () => {- actions.connectRun()- },connectRun: () => {const run = values.run- if (- !run ||- values.closedRunIds.includes(run.id) ||- values.dismissedRunIds.includes(run.id) ||- !wizardRunIsActive(run)- ) {+ if (!run || !wizardRunIsActive(run)) {cache.disposables.dispose('run-stream')cache.connectedRunId = undefinedreturn@@ -199,32 +143,6 @@ export const wizardRunSyncLogic = kea<wizardRunSyncLogicType>([return () => stream.close()}, 'run-stream')},- closeRun: ({ runId }) => {- posthog.capture('wizard run sync fab closed', {- event_source: 'wizard_ui',- wizard_run_id: runId,- type: 'dismiss',- })- cache.disposables.dispose('run-stream')- cache.connectedRunId = undefined- actions.runsLoaded(values.activeCount, values.runs)- },- dismissRun: ({ runId }) => {- posthog.capture('wizard run sync fab closed', {- event_source: 'wizard_ui',- wizard_run_id: runId,- type: 'close_forever',- })- cache.disposables.dispose('run-stream')- cache.connectedRunId = undefined- actions.runsLoaded(values.activeCount, values.runs)- },- expandFab: ({ runsCount }) => {- posthog.capture('wizard run sync fab expanded', {- event_source: 'wizard_ui',- runs_count: runsCount,- })- },})),events(({ actions, cache }) => ({afterMount: () => {diff --git a/products/wizard/frontend/wizardRunDisplay.ts b/products/wizard/frontend/wizardRunDisplay.tsindex 53b467c11455..27ff684a83b6 100644--- a/products/wizard/frontend/wizardRunDisplay.ts+++ b/products/wizard/frontend/wizardRunDisplay.ts@@ -1,5 +1,4 @@import { WizardRunApi, WizardRunStageEnumApi } from './generated/api.schemas'-import { wizardRunErrorDetails } from './runs/wizardRunErrorCatalog'export const MAX_RENDERED_WIZARD_DIFF_BYTES = 2 * 1024 * 1024// Byte size does not bound DOM nodes: many short lines can pass the byte cap and still stall the page.@@ -132,32 +131,3 @@ export function formatArtifactSize(sizeBytes: number): string {}return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`}--export function wizardRunCurrentState(run: WizardRunApi): string {- if (run.status === 'completed') {- return 'Completed successfully'- }- if (run.status === 'failed') {- return wizardRunErrorDetails(run.error_code, run.error_message).title- }- if (run.status === 'cancelled') {- return 'Run canceled'- }-- switch (run.stage) {- case WizardRunStageEnumApi.Dispatching:- return 'Starting the Wizard Worker'- case WizardRunStageEnumApi.Provisioning:- return 'Provisioning the Wizard Worker'- case WizardRunStageEnumApi.PreparingWorkspace:- return 'Preparing the repository'- case WizardRunStageEnumApi.ExecutingWizard:- return run.program.name.endsWith('audit')- ? `Running the ${run.program.name}`- : `Running ${run.program.name}`- case WizardRunStageEnumApi.CreatingArtifacts:- return 'Creating run artifacts'- default:- return run.status === 'running' ? 'Running the Wizard' : 'Starting the Wizard run'- }-}diff --git a/products/wizard/frontend/wizardSessionStreamLogic.test.ts b/products/wizard/frontend/wizardSessionStreamLogic.test.tsdeleted file mode 100644index dfb919b9c802..000000000000--- a/products/wizard/frontend/wizardSessionStreamLogic.test.ts+++ /dev/null@@ -1,208 +0,0 @@-import { installMockEventSource, MockEventSource } from 'lib/wizard-sync/eventSource.mock'--import { expectLogic } from 'kea-test-utils'-import posthog from 'posthog-js'--import { ApiError } from 'lib/api-error'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { SSE_RECONNECT_MAX_MS } from 'lib/wizard-sync/pollLoop'-import { projectLogic } from 'scenes/projectLogic'--import { initKeaTests } from '~/test/init'--import { wizardSessionsLatestRetrieve } from './generated/api'-import type { WizardSessionDTOApi } from './generated/api.schemas'-import { wizardSessionStreamLogic } from './wizardSessionStreamLogic'--jest.mock('./generated/api', () => ({- wizardSessionsLatestRetrieve: jest.fn(),- getWizardSessionsStreamRetrieveUrl: jest.fn(() => '/mock-stream-url'),-}))--const mockLatestRetrieve = wizardSessionsLatestRetrieve as jest.Mock--function makeSession(overrides: Partial<WizardSessionDTOApi> = {}): WizardSessionDTOApi {- return {- session_id: 'sess-1',- team_id: 997,- workflow_id: 'posthog-integration',- skill_id: 'install',- started_at: '2026-01-01T00:00:00Z',- run_phase: 'running',- tasks: [],- event_plan: null,- error: null,- pending_input: null,- handoff_text: null,- created_by: null,- created_at: '2026-01-01T00:00:00Z',- updated_at: '2026-01-01T00:00:00Z',- is_stale: false,- ...overrides,- }-}--// Max jittered gap for the default 3s interval is 3.6s — advancing past it guarantees the next tick.-const PAST_MAX_JITTERED_INTERVAL_MS = 4000--describe('wizardSessionStreamLogic polling mode', () => {- let logic: ReturnType<typeof wizardSessionStreamLogic.build>-- beforeEach(async () => {- initKeaTests()- mockLatestRetrieve.mockReset()- logic = wizardSessionStreamLogic({ workflowId: 'posthog-integration' })- logic.mount()- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE], {- [FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE]: 'polling',- })- // connect() no-ops into an error without a project — wait for the test bootstrap to provide one.- await expectLogic(projectLogic).toMatchValues({ currentProjectId: expect.any(Number) })- jest.useFakeTimers()- })-- afterEach(() => {- logic?.unmount()- jest.useRealTimers()- })-- it('polls the latest session and feeds it through sessionUpdated', async () => {- const session = makeSession()- mockLatestRetrieve.mockResolvedValue(session)-- logic.actions.connect()- await expectLogic(logic)- .toDispatchActions(['connectionOpened', 'sessionUpdated'])- .toMatchValues({ latestSession: session, connectionStatus: 'open' })-- expect(mockLatestRetrieve).toHaveBeenCalledWith(- expect.any(String),- {- workflow_id: 'posthog-integration',- skill_id: undefined,- },- { headers: { 'X-Wizard-Poll-Source': 'transport' } }- )- })-- it('keeps polling through a 204 (no session yet) without clobbering latestSession', async () => {- // The generated client resolves an empty 204 body to null (getJSONOrNull), not undefined.- mockLatestRetrieve.mockResolvedValue(null)-- logic.actions.connect()- await expectLogic(logic)- .toDispatchActions(['connectionOpened'])- .toNotHaveDispatchedActions(['sessionUpdated'])- .toMatchValues({ latestSession: null, connectionStatus: 'open' })-- jest.advanceTimersByTime(PAST_MAX_JITTERED_INTERVAL_MS)- await Promise.resolve()- expect(mockLatestRetrieve).toHaveBeenCalledTimes(2)- })-- it('stops polling on disconnect', async () => {- mockLatestRetrieve.mockResolvedValue(makeSession())-- logic.actions.connect()- await expectLogic(logic).toDispatchActions(['sessionUpdated'])- expect(mockLatestRetrieve).toHaveBeenCalledTimes(1)-- logic.actions.disconnect()- jest.advanceTimersByTime(PAST_MAX_JITTERED_INTERVAL_MS)- await Promise.resolve()- expect(mockLatestRetrieve).toHaveBeenCalledTimes(1)- })-- it('stops polling permanently on a 404', async () => {- mockLatestRetrieve.mockRejectedValue(new ApiError('not found', 404))-- logic.actions.connect()- await expectLogic(logic).toDispatchActions(['connectionErrored']).toMatchValues({ connectionStatus: 'error' })- expect(mockLatestRetrieve).toHaveBeenCalledTimes(1)-- jest.advanceTimersByTime(10 * PAST_MAX_JITTERED_INTERVAL_MS)- await Promise.resolve()- expect(mockLatestRetrieve).toHaveBeenCalledTimes(1)- })-- it('backs off after a transient error instead of retrying at full cadence', async () => {- mockLatestRetrieve.mockRejectedValueOnce(new Error('network hiccup')).mockResolvedValue(makeSession())-- logic.actions.connect()- await expectLogic(logic).toDispatchActions(['connectionErrored'])- expect(mockLatestRetrieve).toHaveBeenCalledTimes(1)-- // One failure doubles the 3s base to 6s (±20% jitter → at least 4.8s): the base window- // must NOT produce a retry...- jest.advanceTimersByTime(PAST_MAX_JITTERED_INTERVAL_MS)- await Promise.resolve()- expect(mockLatestRetrieve).toHaveBeenCalledTimes(1)-- // ...but the backed-off window must.- jest.advanceTimersByTime(PAST_MAX_JITTERED_INTERVAL_MS)- await expectLogic(logic).toDispatchActions(['sessionUpdated'])- expect(mockLatestRetrieve).toHaveBeenCalledTimes(2)- })-})--// The first backoff step is 2s ±20%, so this window always contains the retry.-const PAST_FIRST_RECONNECT_MS = 2600--describe('wizardSessionStreamLogic SSE mode', () => {- let logic: ReturnType<typeof wizardSessionStreamLogic.build>- let restoreEventSource: () => void- let capture: jest.SpyInstance-- beforeEach(async () => {- // Resolved feature flags are persisted, so the polling suite above would otherwise decide- // this suite's transport too.- window.localStorage.clear()- initKeaTests()- mockLatestRetrieve.mockReset()- restoreEventSource = installMockEventSource()- capture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as never)- logic = wizardSessionStreamLogic({ workflowId: 'posthog-integration' })- logic.mount()- // connect() no-ops into an error without a project — wait for the test bootstrap to provide one.- await expectLogic(projectLogic).toMatchValues({ currentProjectId: expect.any(Number) })- jest.useFakeTimers()- })-- afterEach(() => {- logic?.unmount()- jest.useRealTimers()- restoreEventSource()- capture.mockRestore()- })-- const transportErrors = (): unknown[] =>- capture.mock.calls.filter(([event]) => event === 'wizard sync transport error')-- it('reconnects after a fatal close and reports the transport error once per connect cycle', async () => {- logic.actions.connect()- MockEventSource.last().emitOpen()- await expectLogic(logic).toDispatchActions(['connectionOpened'])-- MockEventSource.last().emitTransportError(MockEventSource.CLOSED)- await expectLogic(logic).toDispatchActions(['connectionErrored'])- jest.advanceTimersByTime(PAST_FIRST_RECONNECT_MS)- expect(MockEventSource.instances).toHaveLength(2)-- // A stream that stays fatally closed retries for as long as the tab is open. One capture per- // backoff step would be one every 30s per tab, enough to drown the transport comparison.- MockEventSource.last().emitTransportError(MockEventSource.CLOSED)- await expectLogic(logic).toDispatchActions(['connectionErrored'])- expect(transportErrors()).toHaveLength(1)- })-- it('cancels a pending reconnect on disconnect', async () => {- logic.actions.connect()- MockEventSource.last().emitTransportError(MockEventSource.CLOSED)- await expectLogic(logic).toDispatchActions(['connectionErrored'])-- logic.actions.disconnect()- jest.advanceTimersByTime(SSE_RECONNECT_MAX_MS)- expect(MockEventSource.instances).toHaveLength(1)- })-})diff --git a/products/wizard/frontend/wizardSessionStreamLogic.ts b/products/wizard/frontend/wizardSessionStreamLogic.tsdeleted file mode 100644index f34e42e2b4d9..000000000000--- a/products/wizard/frontend/wizardSessionStreamLogic.ts+++ /dev/null@@ -1,341 +0,0 @@-import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'-import posthog from 'posthog-js'--import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic, getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'-import {- createPollLoop,- isPermanentPollError,- resolvePollingIntervalMs,- resolveWizardSyncMode,- sseReconnectDelayMs,- type WizardSyncMode,-} from 'lib/wizard-sync/pollLoop'-import { logSyncDebug } from 'lib/wizard-sync/wizardSyncDebugLogic'-import { projectLogic } from 'scenes/projectLogic'--import type { FeatureFlagsSet } from '../../../frontend/src/lib/logic/featureFlagLogic'-import { getWizardSessionsStreamRetrieveUrl, wizardSessionsLatestRetrieve } from './generated/api'-import type { WizardSessionDTOApi } from './generated/api.schemas'--export type WizardConnectionStatus = 'idle' | 'connecting' | 'open' | 'closed' | 'error'--export interface WizardSessionStreamLogicProps {- workflowId: string- /**- * Optional. When omitted, the backend pattern-subscribes to all skills under- * the workflow. Useful when the framework / skill the wizard will run isn't- * known up front (the common onboarding case).- */- skillId?: string-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardSessionStreamLogicValues {- featureFlags: FeatureFlagsSet // featureFlagLogic- currentProjectId: number | null // projectLogic- connectionStatus: WizardConnectionStatus- lastError: string | null- latestSession: WizardSessionDTOApi | null-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardSessionStreamLogicActions {- connect: () => {- value: true- }- connectionErrored: (error: string) => {- error: string- }- connectionOpened: () => {- value: true- }- disconnect: () => {- value: true- }- sessionUpdated: (session: WizardSessionDTOApi) => {- session: WizardSessionDTOApi- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardSessionStreamLogicMeta {- key: string-}--export type wizardSessionStreamLogicType = MakeLogicType<- wizardSessionStreamLogicValues,- wizardSessionStreamLogicActions,- WizardSessionStreamLogicProps,- wizardSessionStreamLogicMeta->--/**- * Subscribes to the SSE stream for a wizard workflow (optionally a specific skill)- * and exposes the latest WizardSession state plus connection status.- *- * Each (workflowId, skillId) pair gets its own logic instance keyed by props, so- * multiple subscriptions coexist in the app. Omitting skillId pattern-subscribes- * to every skill under the workflow.- *- * When the `onboarding-wizard-sync-mode` flag resolves to `polling` (GROW-118), the- * EventSource is replaced by a poll loop that re-fetches the latest session via- * `wizard/sessions/latest/` and feeds it through the same `sessionUpdated` action.- * The loop (shared with `taskRunStreamLogic`) backs off on consecutive errors, stops on- * permanent ones (401/403/404), and backs off on consecutive empty responses — so an- * endpoint with no session (not started yet, or killswitched to 204) winds down instead- * of being polled at full cadence forever. Consumers stop it via `disconnect`;- * `installationProgressLogic` does so once a cloud run reaches a terminal state.- *- * Usage:- *- * // Listen to any skill under the posthog-integration workflow:- * const { latestSession } = useValues(- * wizardSessionStreamLogic({ workflowId: 'posthog-integration' })- * )- *- * // Or pin to one skill:- * const { latestSession } = useValues(- * wizardSessionStreamLogic({ workflowId: 'posthog-integration', skillId: 'nextjs' })- * )- */-export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([- props({} as WizardSessionStreamLogicProps),- key((props) => `${props.workflowId}::${props.skillId ?? '*'}`),- path((key) => ['products', 'wizard', 'wizardSessionStreamLogic', key]),- connect(() => ({- values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags']],- })),- actions({- connect: true,- disconnect: true,- sessionUpdated: (session: WizardSessionDTOApi) => ({ session }),- connectionOpened: true,- connectionErrored: (error: string) => ({ error }),- }),- reducers({- latestSession: [- null as WizardSessionDTOApi | null,- {- sessionUpdated: (_, { session }) => session,- },- ],- connectionStatus: [- 'idle' as WizardConnectionStatus,- {- connect: () => 'connecting',- connectionOpened: () => 'open',- connectionErrored: () => 'error',- disconnect: () => 'closed',- },- ],- lastError: [- null as string | null,- {- connect: () => null,- sessionUpdated: () => null,- connectionErrored: (_, { error }) => error,- },- ],- }),- listeners(({ values, actions, props, cache }) => ({- connect: () => {- // A connect (manual or scheduled) supersedes any pending reconnect timer, so the two can- // never race a second transport open.- cache.disposables.dispose('session-reconnect')- // A scheduled retry continues the connect cycle that failed rather than starting a new- // one, so it must leave the telemetry guards below alone. Resetting them here would emit- // one transport-error capture per backoff step for as long as the stream stays closed,- // which is once every 30s per tab and enough to swamp the SSE-vs-polling comparison.- const resumingCycle = cache.reconnectScheduled === true- cache.reconnectScheduled = false- const projectId = values.currentProjectId- if (projectId === null) {- actions.connectionErrored('No current project — cannot open wizard session stream.')- return- }-- // Per-connect-cycle transport telemetry: one "ready" (first session delivered) and at- // most one "error" per cycle, so SSE and polling performance stay comparable without- // an event per delivery or per EventSource retry.- if (!resumingCycle) {- cache.connectStartedAt = Date.now()- cache.transportReadyReported = false- cache.transportErrorReported = false- }-- const debugSource = `session ${props.workflowId}::${props.skillId ?? '*'}`-- // Mode is re-sampled on every connect, and the setFeatureFlags listener below reconnects- // when the resolved mode changes — so a flag flip (or flags arriving after a cold-cache- // connect) swaps the transport live instead of waiting for a remount.- const syncMode: WizardSyncMode = resolveWizardSyncMode(- values.featureFlags[FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE]- )- cache.syncMode = syncMode-- if (syncMode === 'polling') {- const intervalMs = resolvePollingIntervalMs(- getFeatureFlagPayload(FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE)- )- logSyncDebug(debugSource, 'connect', `polling every ~${intervalMs / 1000}s (±20% jitter)`, {- mode: 'polling',- intervalMs,- })- cache.disposables.add(- createPollLoop({- intervalMs,- tick: async () => {- // 204 (no session yet, or killswitched) resolves to null — classify as- // empty so the loop backs off instead of polling at full cadence forever.- const session = await wizardSessionsLatestRetrieve(- String(projectId),- {- workflow_id: props.workflowId,- skill_id: props.skillId,- },- { headers: { 'X-Wizard-Poll-Source': 'transport' } }- )- logSyncDebug(- debugSource,- 'poll',- session- ? `poll ok: ${session.run_phase} (${session.skill_id})`- : 'poll ok: no session yet',- { mode: 'polling', intervalMs }- )- // Only on first open / recovery from error — not every tick.- if (values.connectionStatus !== 'open') {- actions.connectionOpened()- }- if (!session) {- return 'empty'- }- actions.sessionUpdated(session)- return 'ok'- },- onError: (err) => {- logSyncDebug(debugSource, 'error', `poll failed: ${String(err)}`)- actions.connectionErrored(`Failed to poll wizard session: ${String(err)}`)- return isPermanentPollError(err) ? 'stop' : 'retry'- },- // Dispose the key so a later tab-visibility resume doesn't restart a loop- // that ended itself.- onLoopEnd: () => cache.disposables.dispose('session-sync'),- }),- 'session-sync'- )- return- }-- logSyncDebug(debugSource, 'connect', 'opening EventSource', { mode: 'sse' })- cache.disposables.add((): (() => void) => {- const url = getWizardSessionsStreamRetrieveUrl(String(projectId), {- workflow_id: props.workflowId,- skill_id: props.skillId,- })- const eventSource = new EventSource(url, { withCredentials: true })-- eventSource.onopen = (): void => {- // Mode rides along here too: the connect event can predate the debug panel's- // mount (and get dropped), but open/events always land after it.- logSyncDebug(debugSource, 'open', 'SSE connection open', { mode: 'sse' })- cache.sseReconnectAttempt = 0- actions.connectionOpened()- }- eventSource.onmessage = (event: MessageEvent<string>): void => {- try {- const session = JSON.parse(event.data) as WizardSessionDTOApi- logSyncDebug(debugSource, 'event', `session → ${session.run_phase} (${session.skill_id})`, {- mode: 'sse',- })- actions.sessionUpdated(session)- } catch (err) {- logSyncDebug(debugSource, 'error', `failed to parse SSE payload: ${String(err)}`)- actions.connectionErrored(`Failed to parse SSE payload: ${String(err)}`)- }- }- eventSource.onerror = (): void => {- // EventSource readyState distinguishes terminal close vs transient retry:- // CLOSED (2) → browser gave up (any non-200 on a (re)connect lands here)- // and will NOT auto-reconnect, so schedule our own reconnect- // with backoff.- // CONNECTING (0) → browser is already retrying; ride it out, surface- // the state so the UI can show "reconnecting".- if (eventSource.readyState === EventSource.CLOSED) {- const attempt = ((cache.sseReconnectAttempt as number | undefined) ?? 0) + 1- cache.sseReconnectAttempt = attempt- const delayMs = sseReconnectDelayMs(attempt)- logSyncDebug(- debugSource,- 'error',- `SSE closed, reconnecting in ~${Math.round(delayMs / 1000)}s`- )- actions.connectionErrored(- `EventSource connection closed, reconnecting in ~${Math.round(delayMs / 1000)}s`- )- // The timer rides disposables so an unmount tears it down, and a hidden tab- // pauses it instead of reconnecting in the background. connect() re-samples- // the sync-mode flag, so a mid-outage flip to polling takes effect here too.- cache.disposables.add(() => {- const timer = window.setTimeout(() => {- cache.reconnectScheduled = true- actions.connect()- }, delayMs)- return () => window.clearTimeout(timer)- }, 'session-reconnect')- } else {- logSyncDebug(debugSource, 'error', 'SSE transport error, reconnecting')- actions.connectionErrored('EventSource transport error, reconnecting')- }- }-- return () => eventSource.close()- }, 'session-sync')- },- disconnect: () => {- logSyncDebug(`session ${props.workflowId}::${props.skillId ?? '*'}`, 'disconnect', 'disconnected')- cache.disposables.dispose('session-sync')- cache.disposables.dispose('session-reconnect')- // The next connect is a new cycle, not a continuation of the one that was torn down.- cache.reconnectScheduled = false- },- sessionUpdated: () => {- if (cache.transportReadyReported || cache.connectStartedAt === undefined) {- return- }- cache.transportReadyReported = true- posthog.capture('wizard sync transport ready', {- transport: cache.syncMode ?? 'sse',- workflow_id: props.workflowId,- ms_since_connect: Date.now() - cache.connectStartedAt,- })- },- connectionErrored: ({ error }) => {- if (cache.transportErrorReported || cache.connectStartedAt === undefined) {- return- }- cache.transportErrorReported = true- posthog.capture('wizard sync transport error', {- transport: cache.syncMode ?? 'sse',- workflow_id: props.workflowId,- error,- })- },- // Flags can resolve after a cold-cache connect (posthog-js loads them async), and ops can flip- // the mode mid-incident. Reconnect when the resolved mode differs from the running transport —- // the keyed disposable makes the swap idempotent.- [featureFlagLogic.actionTypes.setFeatureFlags]: () => {- if (cache.syncMode === undefined) {- return- }- if (values.connectionStatus === 'idle' || values.connectionStatus === 'closed') {- return- }- const mode = resolveWizardSyncMode(values.featureFlags[FEATURE_FLAGS.ONBOARDING_WIZARD_SYNC_MODE])- if (mode !== cache.syncMode) {- actions.connect()- }- },- })),-])