:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(onboarding): implement the self-driving onboarding (#75697)
Fernando Gomes600dc971e0c2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5f7b9dc91deb..e569750d796d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1157,13 +1157,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.516fbd0686a9e9ffde7fce1307cca9c8da7ffffb94c8d1aff69879ca1fbff4c1.srPreLwX2Y8NAiV5quanM34MVbj8hLTvjPafzTnNphA+ hash: v1.k794b7964.f23aecf6ced3a0a5187194cc3e7b7d2908be00cd1cef463aee61c0335c61d1a1.Cpd3UrvoUfWC8OCXv54mEs7LmMrhOCylorsVY3w3pP0components-integrations-slack--slack-full-page-connected-all-scopes--light:- hash: v1.k794b7964.d67103068c1769fcbc9b73d2d472cbc8becf8f4ac720db12f9b51e17bca27e8c.HpECk9oniUBmDkSVrid7Ei1WMkvAdUszmOmoR7KlVNk+ hash: v1.k794b7964.0fb31dd9edbb2348ad73cef42960602be6cbe75044a9c2cf46aa6d6646d8b81a.8sYKZtq2DPh0p6Am8XQ2SqFXnu7RKKX-xwhhHQiH9Kgcomponents-integrations-slack--slack-full-page-connected-missing-scopes--dark:- hash: v1.k794b7964.a539c0c6b139be8b2eec344b254cd01028bac871ff8b4d477e6cc48e15863693.gCj3tOIGjekec54-OAhECGq1_a5WMMcUyRQExWK4Vss+ hash: v1.k794b7964.c0e430ead6faea3fa1f8c385890aeb60ad1bb7b40f689c8d4efc1835a9cc03df.PKE6jjGu0stUZ9OWPLtG5Cuo5bi2wYFN8spJwjnIBkgcomponents-integrations-slack--slack-full-page-connected-missing-scopes--light:- hash: v1.k794b7964.e6e97d3dd1d13648064da338889864b5119061e67137a2af0d237ab4ea504adc.73GI8Q_e92ciQUA4cgFCg67refxdU6pm2PWBnREYClo+ hash: v1.k794b7964.6b4e3c863acc55242757829ec3e5eaed38b26d8b7af143280699987201c0b4de.nsT7VOr5_EtbCurSzIcyixWMhoAoyltvdJqa1Ipv_tAcomponents-integrations-slack--slack-integration--dark:hash: v1.k794b7964.1bcb0a5391d8290b0bdc18f53b3a3363dad6c03cfce5ffb28bdc4d8b26185f5d._h-SOFA2XkHyVKX9pGcZQItPw6XVxVXbouougXrIqkocomponents-integrations-slack--slack-integration--light:@@ -7487,9 +7487,9 @@ snapshots:scenes-other-billing-product--billing-product-without-addons--light:hash: v1.k794b7964.04856a286b0b3933aa364d7f73c56420e890f19d7f490a5aa12ae5616bf3258b.xQP5mvdnr6fC8UHtO4XZU4e-_cG8ZLzhKbnq_Ezmv10scenes-other-integration-landing-page--connected--dark:- hash: v1.k794b7964.6241e074770cbf36da292d6cbd6f8dde7a89b9b5699a79db0e0cc796915900f5.gXumNEPfBbrb0JLEEWhm66PKFXBR0ZAQoF6EfQiy9X8+ hash: v1.k794b7964.1a2abf46a5f43ec0e9bcf1f02115c68f3fab54fc8e8aec6f903e2481689d9a8c.oi6z4uOWfKTWAHVA_UhnCwGg-Zjal3CQ1Se4fDLVOMQscenes-other-integration-landing-page--connected--light:- hash: v1.k794b7964.ba48a93a593c5f797a544b13c655b8059d3543626607d8fb27d40861d209c50a.fqR6y3FcAFj555Q9VsR2DDKUtyI_BTR-Y9VR-576kN0+ hash: v1.k794b7964.3db01e8e2c1f2a9c6b622e06bd5ac66345cdd92961f70349829cdce36cddd2a9.BjXhubo71g8DdCf1Eih4H-AnYpXQnxwL48JtTfIjHWMscenes-other-integration-landing-page--no-permission--dark:hash: v1.k794b7964.674e5a613b6d3f2933862db144b0fab805875bfb9926e2f1f49e502c375363f5.HHRhYsPPj9lhRPMJvLxGHitZUPgG5-Zg9K3k26fM2kIscenes-other-integration-landing-page--no-permission--light:@@ -7622,58 +7622,22 @@ snapshots:hash: v1.k794b7964.aaff710f4f8a004ff7bc73a2709377bd3ac83bccafec478086396c0beae1e832.jqsB3nXBYy8WbHSVAPz-o8Vu46etxe4uDx3zXbtlf-Uscenes-other-onboarding-legacy-product-selection--base--light:hash: v1.k794b7964.d5a6e4d5e44b84e7a1b0a9eb095fb62a08eea227968860911c9e23757eb99d33.mrMEqKjXZgfMivqJdaamdN2nJVc-I_8Sccv6XXQylg8- scenes-other-onboarding-self-driving-connect-data--connecting--dark:- hash: v1.k794b7964.59f96f7b6102b81524fe52d51ca88ca8dadb1702a307fd7976737864a9088a53.j9swRCt2XdmhgzxnD9vTqp0_THZ27ZLJO4KAML1nd8M- scenes-other-onboarding-self-driving-connect-data--connecting--light:- hash: v1.k794b7964.5b338475ab40e23c3c7df99665746ec76622e5a063c35969ee683a4a5179a1d3.bmqzZNaoDdYh0PgVo1bGwG74TZOTsucwzPpOq3BJs4c- scenes-other-onboarding-self-driving-connect-data--loading--dark:- hash: v1.k794b7964.cff95b9c6cd8993906e6c5d3734a032440d3ccb0017fe5da49357a240533f528.7mwRCH5QJocTHdBTG2C0tKZh7c9M4K4r5Dk5O7TFkpE- scenes-other-onboarding-self-driving-connect-data--loading--light:- hash: v1.k794b7964.003f072de0cb2b35ef54ac9f418af4a58f29fd9c646b399b6423ee678732ad53.MFgP16Oth2lA2cLlya5Jk4ZNML0MDMweplWVhkAshUg- scenes-other-onboarding-self-driving-connect-data--picker--dark:- hash: v1.k794b7964.cff95b9c6cd8993906e6c5d3734a032440d3ccb0017fe5da49357a240533f528.YjMz8mKbADTS5vupqwjYh9NXCHZb3OUP5lbR9Kr_WkM- scenes-other-onboarding-self-driving-connect-data--picker--light:- hash: v1.k794b7964.f083877853d6068a01c9f31582525d06f727b0c442d2485aae9e55ee33cbdd91.rvIq6BlK_PQe16XO_kmNScu6Xc9OqxZMhhkEzRwja4c- scenes-other-onboarding-self-driving-connect-data--searching--dark:- hash: v1.k794b7964.4dfe30e4eb72702ecbe738b0171e9b4b1248c7650702bc3b1036abde0f882cf5.recxMx45ifz2eajErQC8SW9KYExDkFg3w2JPdK6aLEo- scenes-other-onboarding-self-driving-connect-data--searching--light:- hash: v1.k794b7964.d5096577fad44f35c23e70a3ce2baf1fde5619b4ccc62d200639b8260d23deaa.pMBUMoeKsJVRcHMBLKz7_V0Y9pvLE_v5cZwHDCqKiHo- scenes-other-onboarding-self-driving-connect-data--searching-empty--dark:- hash: v1.k794b7964.c085d8e2525a239ebfa0674ce610350da4d7fd5f574fb7a5adbd51e4e632595c.RrH7b3NCUgkFMiFu-F79iUolp7s26q5Lpu0DeRBK66w- scenes-other-onboarding-self-driving-connect-data--searching-empty--light:- hash: v1.k794b7964.024aa0fc5f3b8a45b26908456dda88616f4c20aace6107556a0f38d1be7933cb.CMuGracqauaJk87a_SiKc3BOf2wDfoAXaiVqCuARwGI- scenes-other-onboarding-self-driving-connect-data--with-connected-source--dark:- hash: v1.k794b7964.9ff8c7351c60e7795d73c6bd8b5acfbc68f98bbd9723e06dadb41d5741fb3da9.MqSNygYUXQFNBTvWGY9HySvx1DhuVOMmdtUH2B_OPwk- scenes-other-onboarding-self-driving-connect-data--with-connected-source--light:- hash: v1.k794b7964.06446de6c861c43300008a041b7b4a1e17722178ed540089489ead06b6224f0b.KIKpfLbHHTn7U63D8lOtW-1xbvWEFkJeKKYuJ-8u0jU- scenes-other-onboarding-self-driving-turn-on-your-sources--codebase-not-connected--dark:- hash: v1.k794b7964.f0b260fd91ecf3b551fa05abf6cf9bd4dd941167116076b52bc7e473faad750d.DkujYAeFuy54kB6B2KshFMgGbZuk9qNsvjDYGsZ3sTI- scenes-other-onboarding-self-driving-turn-on-your-sources--codebase-not-connected--light:- hash: v1.k794b7964.e0fcaa079f4277b0f8f377c48d5af25dd13880d434c3288a4f6fa68eb1fd5f61.xRiQvZhEvquByeOMDLvOC5lzJCHjTEU0ZqTekw0-ogc- scenes-other-onboarding-self-driving-turn-on-your-sources--default--dark:- hash: v1.k794b7964.55cc900bbf87d5f49763dde7a1e797a2d642701d020a6c1eb227a80b5f922bef.dDdu7RseEZA3Z8ygeQvWG_XLh0xLyigchsQ-vegSTqo- scenes-other-onboarding-self-driving-turn-on-your-sources--default--light:- hash: v1.k794b7964.ce56c10cb866870e46cbf39b72472fa8b775b28c4b43bdc271b7389a4c17cb58.2a3e3ocSCfiycoBKmqh8KTWsLKoJ9xNsxOBs6ly1vMk- scenes-other-onboarding-self-driving-turn-on-your-sources--installing--dark:- hash: v1.k794b7964.8609ff257bfd96471493de9057ca62c9dfe0b1be9acc68040901a190a723b7a1.1t02u9Nc49DI1MH5Ru2URseb9bmwG1KkrYmGL15VcPc- scenes-other-onboarding-self-driving-turn-on-your-sources--installing--light:- hash: v1.k794b7964.590622ed5297b876808a485cec16410eb702136bbdcb79095aa6008570391411._g7ycFESkKS1Yq1Sxg-lQ6rwsEFSV_ewojLgqiE0ptEscenes-other-onboarding-shared-installation-progress--all-states--dark:- hash: v1.k794b7964.43f9476179509106d3956800578f0ffec7b55113b91bfb001971af44db535b13.TJ6oEw_MWvCvLZxOLHSKQk1eqNNEFzDxUyhQrPXQpyE+ hash: v1.k794b7964.ebc77004f3ed2739bf9f824cc8291f1516fd30ae503a2f13e5a322a7cdf57613.ZHmXxoJNvy8sinEkadiq2GQsihmvPseDr7WiIY1wO5gscenes-other-onboarding-shared-installation-progress--all-states--light:- hash: v1.k794b7964.e54778063d1d0784847b7c72edbabf486833cdb26ba0477e67589e51b35a740c.OonSw5OD_pYc3--2OmBfZnNA2rPr6MlMsjY0NptjO5s+ hash: v1.k794b7964.d4d3b47f954d5f43a73a66dc29e885e94e5a09575d21cbfba9d8209b8284d9a2.fP9Jt39r3NTu_IElQmz-pISGpEjruyU-fe8xgvghp08scenes-other-onboarding-shared-installation-progress--completed--dark:hash: v1.k794b7964.d2fdb0dfb10d93ae58d7d9a5cca2b0078ddb92de8f07340f99abbe970b204c29.Wml3hzGqTjQVPrTV50wkCSK4mqqx6wVkbpNM07WdbJcscenes-other-onboarding-shared-installation-progress--completed--light:hash: v1.k794b7964.74b0637f974fc0281ca86808393158b9d5949394896c369a0454b54db6416303.UgEYkmdUPnElm5kCjQC7Nqtk0BVXpYqvS_iQxMQII74scenes-other-onboarding-shared-installation-progress--completed-local-handoff--dark:- hash: v1.k794b7964.36cf7228ba594332bed453ada313646e689878696d65f2e732ef4f20b9942b27.f5PtRTQsoB2LQF0JI-0_pmtiH7Lkd8HH3BnE6uSLoGU+ hash: v1.k794b7964.a1bbfc19bd743396afb9f0fc6c754fec526b3fa6365df8cf7d1ddab0113580a3.spFKy1nJRNCPBrgKdpMlhaVjXrRvup7VhCD2t6ECO4Qscenes-other-onboarding-shared-installation-progress--completed-local-handoff--light:- hash: v1.k794b7964.4a53675912241c2dfbaceb0b4bd25788fcecd47803f6ebe6d75ffb1810c746d5.izLDjwc0DedAbUpHnbQo-nTnDxjO0zg1UKADiHXFIZA+ hash: v1.k794b7964.b70acf5dde641c02c9e5dc873e4e5645d5e9e8d310e30a6fa7515eef50b2c883.I306JX9K5dYkqwtcrwVjlgYVHwpuaZ-sM25phr676EUscenes-other-onboarding-shared-installation-progress--completed-merged--dark:- hash: v1.k794b7964.59a18f19344e8510cf5def3582d0654bb80c62ee554ca271b40d53a8eb3713e3.DHa_cKzZ4cnbK8w3_I8RLMQ-7R8fTU0KTX3iV3njrlU+ hash: v1.k794b7964.e41a47c6d198618b61635ee98c7424dcd8893284a69cf72c2cd18bbcbf1bce4c.Q8Ahyvmp_7fhazPC-B3XSNQd9igBc1zLpI5tzQYOMqcscenes-other-onboarding-shared-installation-progress--completed-merged--light:- hash: v1.k794b7964.dfc3ec5bd36f9c2dedd18b806a879e1264834545658e97ea5f929e46ae28c7db.1uMBtikg1qmNWO2jhLUHjr61vpdXSZ-jTSe40buHfmU+ hash: v1.k794b7964.6851fb25e6e775bcdeb9ca37ce3702c3c2a4ec48753a9d68b07fa16749cfe93a.tuRuktZ34Id7jRX_HwlO0gJdRruayWVjMvX74l33VIcscenes-other-onboarding-shared-installation-progress--connecting--dark:hash: v1.k794b7964.c979fc93fe8ea9d6a8d7ecfc667cba31879bfcafce56b1f09ae143d43e77efce.cHHBvXk9MnAaTdks6cwqJLv_--qKj8AwUXIv6FZRV3Uscenes-other-onboarding-shared-installation-progress--connecting--light:@@ -7683,37 +7647,37 @@ snapshots:scenes-other-onboarding-shared-installation-progress--connecting-local--light:hash: v1.k794b7964.4691e4cc4f73c17168f502c50bcfb9654eaac629609a1362c21a21ef3025d02d.DiXbWHT2TBOodnBTsRpvL56LZU-ISxFUg2BpvsE3rL8scenes-other-onboarding-shared-installation-progress--failed-clone--dark:- hash: v1.k794b7964.b367d6930c3a427c3c76721541da2b5a69d6026a2af7048a1928887374013702.urUNAcXj_1KReMrBdJVZvz9zOMH5sYrLU_Lxt2m5ivQ+ hash: v1.k794b7964.70ffe6826a0c102c60c4aae8cda14b9a8d63898542334bf258d0b1f3dc85cce3.KbYx6q0WrGLiQh8AnwTRAMIa5yyHXzSghEVJFjdthh4scenes-other-onboarding-shared-installation-progress--failed-clone--light:- hash: v1.k794b7964.19d4372a7d94d2d4374aec17b89ce081fa9f16bed1761c8a391ff665e4fb12a0.u7T3W8M_lk4z0SQYP8A_Pk6repyaqaa6zYmsg4SvjIU+ hash: v1.k794b7964.94c4fc6b8198ed716157034597c767e3ae39885871562e988a079e3270efc731.1sYwXTZigpehFl_vV0bOKZtVtv4pRtUNLrIPw37a5U8scenes-other-onboarding-shared-installation-progress--failed-no-detail--dark:hash: v1.k794b7964.58610476a191d7d7ed2c8594ffffbd14d485ae8ff3b3cb52650034c879982ee8.alL7O2YP-vp0_l-YCMpnXOaX-FfhEV9eO6vHSH3izBQscenes-other-onboarding-shared-installation-progress--failed-no-detail--light:hash: v1.k794b7964.5991f74c2c2c03dfc42df0586a3a5526c2c1c3077dbb4cce75ba192be46316c7.Gs16jzYhNytlMnlz_X-_bKYcDFBDNdYgliVKiONjP1Qscenes-other-onboarding-shared-installation-progress--failed-provisioning--dark:- hash: v1.k794b7964.6f232eda4339190a4f8f5083c2d1c5e50b94b673d1fd7ab1fda8a95b4d3bce08.pIpvTN2U9JI0QloopLC0cjg1GvHO1CF3wpZRcp-zIzc+ hash: v1.k794b7964.7fcafd04ed6c719a8ad01cebc7abcc7265a3f677a2398e6ee19004eac26d1eff.kASMuoxhwilbDbtUhEblU0HnMTCXcWhk0aGBx34zYYkscenes-other-onboarding-shared-installation-progress--failed-provisioning--light:- hash: v1.k794b7964.cc7c7f9cd6e345a1dad49131a3dfbb57404fa4bd3b16bcf322d48c748c4c6e97.SItaoRxjP5W9HM04_8mbOWIOw4fWQ92iS8RMwY3tij8+ hash: v1.k794b7964.ae9111e8e758485d7791e5d85cd44d5cd5ffb2d5ec8948b1a9bb360455bc6674.O0Mx_17KqsoiMCWOgBgvn9w30i-uCzJpz05Jk9K3Iscscenes-other-onboarding-shared-installation-progress--failed-wizard--dark:- hash: v1.k794b7964.28b342b3c5c42ea9ea6817a9a5ebdc06215d631806df5b95f020ead507842f0b.rQ2WyE3OniJop5jxpLouAswEIERBDEKAjmqOJMYQO2o+ hash: v1.k794b7964.3a1cef199fe6ff0b83ed59eb7c203067ceb40d28992890194f4b65eb54037063.G8lqwGkC_dmlyq1MoxtZlaWREPKsfAmXjlt1i3opb-wscenes-other-onboarding-shared-installation-progress--failed-wizard--light:- hash: v1.k794b7964.8d687e80b53eb492b92b67f6906c9603f98e5a4063448954b79081da9c76bd81.b104GyJ_V3bIcjApMDPTG_Jym9KleG8p30R4kUlQIMQ+ hash: v1.k794b7964.0fb344f11f3320139a596e39e0e980e9ecda58bab2cc7447c3e2876bf98ee9f7.bJH5sO50ROg-bcX5kue9erVDrEy4jni186glKF8rt-4scenes-other-onboarding-shared-installation-progress--floating-dismissible--dark:hash: v1.k794b7964.a21998e89bf8467ab55efee9b035db51afb042ebe36551e9a47273ddf2e67609.AODFzzcBWc0nJzj1J_lobuSKcS21_mFsYR-ITbTH21Yscenes-other-onboarding-shared-installation-progress--floating-dismissible--light:hash: v1.k794b7964.4355159959fbe751c547f2900ca7113b7da45a0319fc712998780ffda13ae155.qNAp9aF20iIG8GW2eU-heTT4kKRwhJEvcoiZzeojdJgscenes-other-onboarding-shared-installation-progress--lost-contact--dark:- hash: v1.k794b7964.0c823488913bc658132cbacd34dbfa099c952d4285be11f466c1faab2aa176de.2Yn_3R4IZA1r64pwys8AM3xEDicPJSw9gJ0vxCVWwVM+ hash: v1.k794b7964.dae9f74c48a511842537f9ec2ccf1e76b6909b6dbc318665a24091ef369ee1b0.A475B62vNvHQlT0-mfSGoaJIzoOGVUzqCnNB-DT7vvYscenes-other-onboarding-shared-installation-progress--lost-contact--light:- hash: v1.k794b7964.0bfdd92c602253db00b1204978e4e14b4e1562e484f1610f2595465c470eeb8c.mAtv6ApOmQhhgbyFrqf9ye1xKLKGMLGD6C-ORG2AVYQ+ hash: v1.k794b7964.cf38a26713c8ed464a7de37e7edfb1c9774673f4e310cec29a1db98cb96419e0.CFI0ueTLg5KlXQvzl2TaKR_CpKonqflTgzi513HRD_wscenes-other-onboarding-shared-installation-progress--playground--dark:hash: v1.k794b7964.73dd3b1ca302d1d915814fb1c93516188ee3a6c010a9deedc21aba892b0c4eaa.TED9G6l7yoWOiiXzoG27nGeTlcy4E02tWrI0-iEqOBMscenes-other-onboarding-shared-installation-progress--playground--light:hash: v1.k794b7964.136fe9ea63b8e3301642e87d677f6e9d46f1796683a666a3ab18ee23fbbf5539.4sb2JpWGGJR3UBjBelT0C_Y2JvuppqCQCzwvFT5RptIscenes-other-onboarding-shared-installation-progress--pull-request-merged--dark:- hash: v1.k794b7964.ed63a038b7850e6fca64b61fddc7d786b95612b0cb313d1a8fec7e1e300cf7a7.KpidhTaObETHkR2JsrXbAl9Cgh7vqmF12CGN2DZYejI+ hash: v1.k794b7964.638b946e49e098d04583d90f6053b75d9597545a5b5a6312eb9d8b49ce06cc5a.K30fdLzVMN7H433eGeF5ISIPzVLjOJEE7Br824UVNwMscenes-other-onboarding-shared-installation-progress--pull-request-merged--light:- hash: v1.k794b7964.46a6ac2335f607534242f15615f19b9f75cb81c2d48099cfa9772f57df091d76.3Na2Ka58ITzwK3nfOXc8iuwudjObb8rH6LUoDAahiw0+ hash: v1.k794b7964.814693ea93fbe19868432c9a60ad3b5d59d0c88ec63b6c240dac5db2cb238099.QtWxBAEYXexElR040I3uVGt4k_szR5SODeH12s3ZyCMscenes-other-onboarding-shared-installation-progress--pull-request-ready--dark:hash: v1.k794b7964.c0dd7977c4b4e125098401eb4643e2896f600b116c04bf0ff56f09de25579835.x7qV5sJxPaxI27L4YuzDnvP5qLdsHcFQtGRM1cQE23cscenes-other-onboarding-shared-installation-progress--pull-request-ready--light:@@ -7727,33 +7691,33 @@ snapshots:scenes-other-onboarding-shared-installation-progress--running-wizard--light:hash: v1.k794b7964.c6ad24b9d785ebe203a5bd7f52d8ce95c22627709eb99f43a8035c27805a6a4d.65BK591qtOlIdohy6c4QY_b0-4qLXTGPiilnI8BuMp8scenes-other-onboarding-shared-wizard-cloud-run--connected--dark:- hash: v1.k794b7964.0c903b9c3884ef83e1a10473b1e9acdbebc5b38b588a99bed35441b8b7ee8c0b.Omb8q4H4h2Szw69UvEHIVm7KSTReG7XazA2tF2VIfls+ hash: v1.k794b7964.1ce5366ddf7653d94db593d6cad5f279dded5f538ef74ef2dd030995cd4e88c8.kr68p-keSbcj193CXgPaLnTbsPks4qA1GWl6LjGab48scenes-other-onboarding-shared-wizard-cloud-run--connected--light:- hash: v1.k794b7964.4a4081541ed8303ac183359a9ca8e594b33d3b056abb86e0e936599fae609f4b.sa0g40gecP98ZMFLV-1TfJ5A-KmwkkYf2nlpb8W-u7A+ hash: v1.k794b7964.7ebfa7872852aacf3e3ae1fb35ad66970df87660446283c0318e6b59eb69e940.Ey8rwc9TnU1jVe_qEHx9cRJ4D4eC1_5lggbCT5VJ0d4scenes-other-onboarding-shared-wizard-cloud-run--not-connected--dark:- hash: v1.k794b7964.50a8969eeeb71152057cc1ea24c33d8713adae1126df02b125876e65834d36d3.iDwWz7kkpm32mhrWTdXxKPszWBR6n37l-Vot9hENRFU+ hash: v1.k794b7964.acdef11c6b1058dacf532d05fd67636244f201a1c52f7c902de5e7249fc45075.LMxfSHX_C1FXJXo3DZdahPSeBIvUoJ2Tu0BtNoP5VT4scenes-other-onboarding-shared-wizard-cloud-run--not-connected--light:- hash: v1.k794b7964.2fae86241c7b429587b0957389248c1365b660eb1bb7565d01b33ab620e38f0d.GXO6gusmhMMKFWM_5nLZqX746CL3UPZNnvZ4jj5oWzA+ hash: v1.k794b7964.046d88670afad91c9214519ccb751537a46d8f90170c5465cd6956720245efc5.N8CSJNxVehmP96bOtythkT4H3KHWuSV4kBVC-bXcJ7sscenes-other-onboarding-shared-wizard-cloud-run--playground--dark:- hash: v1.k794b7964.c83127f9e424470e3a9dbef3100148560455f9b3a9b5a17c82c67a63e10bd6c4.xJzDCfkU3USYFTZTg6vU9Hu8pkFjckrjs6Xy8qje1qM+ hash: v1.k794b7964.ac153cecf12df4984b50f911c82a953d0e9ec3b77d3ec7aae64980c21ec0e84c.maA8DUvFiPq_6Kln4Q9WZAl6VNkWB62Wwx8G_GDfOzwscenes-other-onboarding-shared-wizard-cloud-run--playground--light:- hash: v1.k794b7964.23701c15f744c0137a71c7ca2f1e94b57bc6deb4a3e943542cecaa676cd7b928.A1E1GKjD7V8u9sVsw9ArM6v9jh_zY3wW_aV0WDMkncc+ hash: v1.k794b7964.89b12fe7e6f467daa70d1e8e2b0775c620137ebf940fd1dd1cdb8fc6e6d6d51f.L4uxBbKm6JjeA_3zz9amB89ihed2ZNAaUXpLmyLNX7Iscenes-other-onboarding-shared-wizard-cloud-run--pull-request-queued--dark:hash: v1.k794b7964.3069f1824db30b78cdb1142ad23c4d2cce49abe8e3919dc8ddc91d2c44dc8c47.sSk9IT_qsJUC2r_UP3L3JN7rnu9mgm88YK2eCSaTU1Uscenes-other-onboarding-shared-wizard-cloud-run--pull-request-queued--light:hash: v1.k794b7964.7ec7e9d1698b2e62f5228a13c1991d64086be0fbc9840457922b154816df2431.nTPGOZUNcBJ1gNrgTQKjPqKNAbhaFCjmCARBoKuu2loscenes-other-onboarding-shared-wizard-cloud-run--repo-picker-open--dark:- hash: v1.k794b7964.1a977cbb0a6a59c9c68182be1a30768abfe0d98ddd11cdace4a415d08b1e053d.uJCiReQqjQhBLVYGSmMSn3XpIwEaQ-aPfvRaqU8TgS8+ hash: v1.k794b7964.86fa9c4496b5d280b84b90c0302a90fe624103308f8950fe74fe20fb82007366.sHbVDI4ZO7poJbeaA1bkMpEoMiMJcPqysKIJw8Bi6awscenes-other-onboarding-shared-wizard-cloud-run--repo-picker-open--light:- hash: v1.k794b7964.216f9a849d9a48cfecdcedaa318a996d7bf66c65b6e497bc96d8a7043bcba4ff.nPN0rXCSllfOEB414bqIPAGN4gMB07O7rAZmtC460Xk+ hash: v1.k794b7964.f62c285e332b519ece409508fe0e0fce4e84a2eb9c0d85fc60c0c768160459d6.Gcsq5CXVb9m8E8V9aJBbZ1FMc3RzBrxfT7Ks5qrMSI0scenes-other-onboarding-shared-wizard-cloud-run--repo-selected--dark:- hash: v1.k794b7964.c83127f9e424470e3a9dbef3100148560455f9b3a9b5a17c82c67a63e10bd6c4.eptdbuPervntKMHipq7abx7efzF8oT1sm7zKS2Jhtxg+ hash: v1.k794b7964.ac153cecf12df4984b50f911c82a953d0e9ec3b77d3ec7aae64980c21ec0e84c.7S1T_r89HZTVdEnJ5u5ng8O0ieDiyMg2QfudRL9hJQsscenes-other-onboarding-shared-wizard-cloud-run--repo-selected--light:- hash: v1.k794b7964.23701c15f744c0137a71c7ca2f1e94b57bc6deb4a3e943542cecaa676cd7b928.gC0HQGAXbp5d4Yxqu-5lJlkR8LYFMHUeXh9YEbdvCFI+ hash: v1.k794b7964.89b12fe7e6f467daa70d1e8e2b0775c620137ebf940fd1dd1cdb8fc6e6d6d51f.OvuTsg8C0z8E4iE9S6aMFub_i2dmpQP4kaC02XM8bM8scenes-other-onboarding-shared-wizard-cloud-run--run-it-yourself--dark:- hash: v1.k794b7964.c342ae6e7d6cbb05a01a9c8f6de0cc356aa9951d8541df40b34717d88dd142b3.Ivg2GWt6-i4caJOyc9Ack1SujpDKAIceZbZGjKFRn30+ hash: v1.k794b7964.5a35f0677ffb11febcba8084a0ccb558ecff39d861a8cd8c6501671f47a1fac2.Of5i_K-cfe3g96_a6dHtRI0PeaDjaJ0rdWZMi6O4aG0scenes-other-onboarding-shared-wizard-cloud-run--run-it-yourself--light:- hash: v1.k794b7964.6929d887dd4bcc9ac0c6fcc32e16d829771b0f97f38af905b7e62752c0b39a97.p5weyrIGjeKhnV6FuarEp-O82xPcQjs8cKYuLGLiEzc+ hash: v1.k794b7964.8cff144ac77c6006b48a62a014070b994affcef9058056e2a95b8f4e22084c76.hP6I6QLsGi3k_TebVwrWapvf_CjCVBsmTFQ81_8HVfoscenes-other-onboarding-shared-wizard-sync-card--all-states--dark:hash: v1.k794b7964.65526a55e7a2c0658e60e0c330a015430f561d3d80b3c2463408d6120b6cd078.a3tsBW_wyWyuhTAvUbgNVRx6rqStiMURSToOppQEIbgscenes-other-onboarding-shared-wizard-sync-card--all-states--light:diff --git a/frontend/src/layout/panel-layout/InstallationStatusNavButton.stories.tsx b/frontend/src/layout/panel-layout/InstallationStatusNavButton.stories.tsxindex d8c903fae3bc..8e84ba8e3d7b 100644--- a/frontend/src/layout/panel-layout/InstallationStatusNavButton.stories.tsx+++ b/frontend/src/layout/panel-layout/InstallationStatusNavButton.stories.tsx@@ -111,7 +111,7 @@ function useCloudRun(overrides?: Partial<CloudRunHandle>): void {function useLocalSession(): void {useMountedLogic(wizardActiveSessionDetectorLogic)useEffect(() => {- wizardActiveSessionDetectorLogic.actions.markActive()+ wizardActiveSessionDetectorLogic.actions.markActive('posthog-integration')}, [])}diff --git a/frontend/src/layout/panel-layout/InstallationStatusNavButton.tsx b/frontend/src/layout/panel-layout/InstallationStatusNavButton.tsxindex 73513e632b41..1ffe2f719c6a 100644--- a/frontend/src/layout/panel-layout/InstallationStatusNavButton.tsx+++ b/frontend/src/layout/panel-layout/InstallationStatusNavButton.tsx@@ -8,6 +8,7 @@ import { elapsedSecondsFrom } from 'lib/utils/datetime'import { activeCloudRunLogic, type CloudRunHandle } from 'scenes/onboarding/shared/wizard-sync/activeCloudRunLogic'import { installationProgressLogic } from 'scenes/onboarding/shared/wizard-sync/installationProgressLogic'import { wizardActiveSessionDetectorLogic } from 'scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic'+import { urls } from 'scenes/urls'import { installationStatusNavLogic, type NavInstallationPhase } from './installationStatusNavLogic'@@ -80,7 +81,7 @@ export function InstallationStatusNavButton({ iconOnly = false }: { iconOnly?: b}function InstallationStatusNavButtonInner({ iconOnly }: { iconOnly: boolean }): JSX.Element | null {- const { shouldShow, isRunActive, phase: logicPhase, onboardingUrl } = useValues(installationStatusNavLogic)+ const { shouldShow, isRunActive, phase: logicPhase } = useValues(installationStatusNavLogic)const { openDialog } = useActions(installationStatusNavLogic)// The detector must be mounted to run the cheap REST poll that surfaces local sessions.@@ -122,7 +123,7 @@ function InstallationStatusNavButtonInner({ iconOnly }: { iconOnly: boolean }):if (isRunActive) {openDialog()} else {- window.location.href = onboardingUrl+ window.location.href = urls.onboarding()}}diff --git a/frontend/src/layout/panel-layout/installationStatusNavLogic.ts b/frontend/src/layout/panel-layout/installationStatusNavLogic.tsindex 8989b146744b..fb8fcab91df1 100644--- a/frontend/src/layout/panel-layout/installationStatusNavLogic.ts+++ b/frontend/src/layout/panel-layout/installationStatusNavLogic.ts@@ -4,7 +4,6 @@ import { activeCloudRunLogic } from 'scenes/onboarding/shared/wizard-sync/activeimport { wizardActiveSessionDetectorLogic } from 'scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic'import { wizardSyncUiLogic } from 'scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic'import { teamLogic } from 'scenes/teamLogic'-import { urls } from 'scenes/urls'import type { CloudRunHandle } from '../../scenes/onboarding/shared/wizard-sync/activeCloudRunLogic'import type { TeamPublicType, TeamType } from '../../types'@@ -14,13 +13,12 @@ export type NavInstallationPhase = 'running' | 'completed' | 'error' | 'connecti// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface installationStatusNavLogicValues {activeCloudRun: CloudRunHandle | null // activeCloudRunLogic- panelMounted: boolean // activeCloudRunLogiccurrentTeam: TeamPublicType | TeamType | null // teamLogichasOnboardedAnyProduct: boolean // teamLogichasActiveSession: boolean // wizardActiveSessionDetectorLogicdialogOpen: boolean // wizardSyncUiLogic+ inlinePanelMounted: boolean // wizardSyncUiLogicisRunActive: boolean- onboardingUrl: stringphase: NavInstallationPhaseshouldShow: boolean}@@ -40,7 +38,7 @@ export interface installationStatusNavLogicMeta {currentTeam: TeamPublicType | TeamType | null,activeCloudRun: CloudRunHandle | null,hasActiveSession: boolean,- panelMounted: boolean+ inlinePanelMounted: boolean) => booleanisRunActive: (activeCloudRun: CloudRunHandle | null, hasActiveSession: boolean) => booleanphase: (isRunActive: boolean) => NavInstallationPhase@@ -69,20 +67,26 @@ export const installationStatusNavLogic = kea<installationStatusNavLogicType>([connect(() => ({values: [activeCloudRunLogic,- ['activeCloudRun', 'panelMounted'],+ ['activeCloudRun'],wizardActiveSessionDetectorLogic,['hasActiveSession'],teamLogic,['hasOnboardedAnyProduct', 'currentTeam'],wizardSyncUiLogic,- ['dialogOpen'],+ ['dialogOpen', 'inlinePanelMounted'],],actions: [wizardSyncUiLogic, ['openDialog']],})),selectors({/** Whether the nav item should render at all. */shouldShow: [- (s) => [s.hasOnboardedAnyProduct, s.currentTeam, s.activeCloudRun, s.hasActiveSession, s.panelMounted],+ (s) => [+ s.hasOnboardedAnyProduct,+ s.currentTeam,+ s.activeCloudRun,+ s.hasActiveSession,+ s.inlinePanelMounted,+ ],(hasOnboardedAnyProduct: boolean,currentTeam: null | import('../../types').TeamPublicType | import('../../types').TeamType,@@ -90,10 +94,10 @@ export const installationStatusNavLogic = kea<installationStatusNavLogicType>([| null| import('scenes/onboarding/shared/wizard-sync/activeCloudRunLogic').CloudRunHandle,hasActiveSession: boolean,- panelMounted: boolean+ inlinePanelMounted: boolean): boolean => {// Panel-mounted inline progress already shows the run — avoid double-surfacing- if (panelMounted) {+ if (inlinePanelMounted) {return false}// Cloud or local run in flight@@ -124,8 +128,5 @@ export const installationStatusNavLogic = kea<installationStatusNavLogicType>([(s) => [s.isRunActive],(isRunActive: boolean): NavInstallationPhase => (isRunActive ? 'running' : 'idle'),],-- /** URL to navigate to on click when no run is active. */- onboardingUrl: [() => [], (): string => urls.onboarding()],}),])diff --git a/frontend/src/lib/utils/async.test.ts b/frontend/src/lib/utils/async.test.tsindex c7c786dfab33..b40da7173810 100644--- a/frontend/src/lib/utils/async.test.ts+++ b/frontend/src/lib/utils/async.test.ts@@ -23,10 +23,13 @@ describe('async utils', () => {// A promise that never resolves nor rejects — the stalled-fetch scenario.const neverSettles = new Promise<string>(() => {})const wrapped = withTimeout(neverSettles, 10000, 'loadRecents timed out')- const assertion = expect(wrapped).rejects.toThrow(PromiseTimeoutError)+ // Captured before the clock moves, so the rejection always has a handler; `expect().rejects`+ // can't be used here because it has to be awaited, and nothing rejects until timers advance.+ const settled = wrapped.catch((error: unknown) => error)await jest.advanceTimersByTimeAsync(10000)- await assertion- await expect(wrapped).rejects.toThrow('loadRecents timed out')+ const error = await settled+ expect(error).toBeInstanceOf(PromiseTimeoutError)+ expect((error as Error).message).toBe('loadRecents timed out')})it('does not time out a promise that resolves just before the deadline', async () => {@@ -52,9 +55,9 @@ describe('async utils', () => {received = signalreturn new Promise<string>(() => {}) // never settles}, 10000)- const assertion = expect(wrapped).rejects.toThrow(PromiseTimeoutError)+ const settled = wrapped.catch((error: unknown) => error)await jest.advanceTimersByTimeAsync(10000)- await assertion+ expect(await settled).toBeInstanceOf(PromiseTimeoutError)expect(received?.aborted).toBe(true)})})diff --git a/frontend/src/scenes/billing/PaymentEntryModal.tsx b/frontend/src/scenes/billing/PaymentEntryModal.tsxindex 2afbbd848437..1743bcb78366 100644--- a/frontend/src/scenes/billing/PaymentEntryModal.tsx+++ b/frontend/src/scenes/billing/PaymentEntryModal.tsx@@ -11,6 +11,12 @@ import { paymentEntryLogic } from './paymentEntryLogic'const stripeJs = async (): Promise<typeof import('@stripe/stripe-js')> => await import('@stripe/stripe-js')+// Covers every way Stripe.js can fail to become usable: a blocked script, a network failure, or no+// publishable key at all on an instance without Stripe configured. Only the first is worth a retry,+// so the message offers a way out of the other two instead of looping the user on "try again".+const STRIPE_UNAVAILABLE_MESSAGE =+ "We couldn't load the payment form. Disable any ad blocker and reload the page. If it keeps failing, contact support."+export const PaymentForm = (): JSX.Element => {const { stripeError, isLoading, redirectPath } = useValues(paymentEntryLogic)const { setStripeError, clearErrors, hidePaymentEntryModal, pollAuthorizationStatus, setLoading } =@@ -22,7 +28,16 @@ export const PaymentForm = (): JSX.Element => {const handleSubmit = async (event: React.MouseEvent<HTMLElement>): Promise<void> => {clearErrors()event.preventDefault()+ // Stripe.js never became usable: no publishable key, a blocked script, or a load failure.+ // Returning quietly leaves a button that does nothing at all, which reads as a broken app+ // and gives neither the user nor a support ticket anything to go on.if (!stripe || !elements) {+ setStripeError(STRIPE_UNAVAILABLE_MESSAGE)+ posthog.captureException(new Error('payment entry stripe unavailable'), {+ has_stripe: !!stripe,+ has_elements: !!elements,+ has_public_key: !!window.STRIPE_PUBLIC_KEY,+ })return}setLoading(true)@@ -66,7 +81,7 @@ export const PaymentForm = (): JSX.Element => {export const PaymentEntryModal = (): JSX.Element => {const { clientSecret, paymentEntryModalOpen, apiError } = useValues(paymentEntryLogic)- const { hidePaymentEntryModal, initiateAuthorization } = useActions(paymentEntryLogic)+ const { hidePaymentEntryModal, initiateAuthorization, setStripeError } = useActions(paymentEntryLogic)const [stripePromise, setStripePromise] = useState<any>(null)useEffect(() => {@@ -77,9 +92,17 @@ export const PaymentEntryModal = (): JSX.Element => {const publicKey = window.STRIPE_PUBLIC_KEY!setStripePromise(await loadStripe(publicKey))}- void loadStripeJs()+ // `loadStripe` rejects outright when the key is missing (an instance without Stripe+ // configured, e.g. local dev), so without a catch this is an unhandled rejection and the+ // only symptom is an inert form.+ void loadStripeJs().catch((error) => {+ posthog.captureException(new Error('payment entry stripe load failed', { cause: error }))+ // Surfaced now rather than on the first click: otherwise the modal just shows a+ // blank payment area, and the only way to find out is to submit it.+ setStripeError(STRIPE_UNAVAILABLE_MESSAGE)+ })}- }, [paymentEntryModalOpen, stripePromise])+ }, [paymentEntryModalOpen, stripePromise, setStripeError])useEffect(() => {if (paymentEntryModalOpen) {diff --git a/frontend/src/scenes/billing/inboxPricing.test.ts b/frontend/src/scenes/billing/inboxPricing.test.tsnew file mode 100644index 000000000000..a9c7d0e80af8--- /dev/null+++ b/frontend/src/scenes/billing/inboxPricing.test.ts@@ -0,0 +1,103 @@+import { creditsPerPr, findInboxProduct, freePrs, pricePerPrUsd } from 'scenes/billing/inboxPricing'++import { BillingPlanType, BillingProductV2Type, BillingTierType } from '~/types'++/** 1500 credits to a PR, matching the inbox product's `display_divisor`. */+const CREDITS_PER_PR = 1500++const tier = (unitAmountUsd: string): BillingTierType =>+ ({ unit_amount_usd: unitAmountUsd, up_to: null }) as BillingTierType++const plan = (overrides: Partial<BillingPlanType>): BillingPlanType =>+ ({ flat_rate: false, unit_amount_usd: null, tiers: null, ...overrides }) as BillingPlanType++const inbox = (overrides: Partial<BillingProductV2Type> = {}): BillingProductV2Type =>+ ({+ type: 'inbox',+ name: 'Inbox',+ display_divisor: CREDITS_PER_PR,+ free_allocation: 4500,+ subscribed: false,+ tiers: null,+ unit_amount_usd: null,+ plans: [],+ ...overrides,+ }) as BillingProductV2Type++describe('inboxPricing', () => {+ describe('findInboxProduct', () => {+ it('matches on product type', () => {+ const product = inbox()+ expect(findInboxProduct([{ type: 'product_analytics' } as BillingProductV2Type, product])).toBe(product)+ })++ it('returns null when billing has no inbox product', () => {+ expect(findInboxProduct([{ type: 'product_analytics' } as BillingProductV2Type])).toBeNull()+ expect(findInboxProduct(undefined)).toBeNull()+ })+ })++ describe('creditsPerPr', () => {+ it('is the display divisor', () => {+ expect(creditsPerPr(inbox())).toBe(CREDITS_PER_PR)+ })++ // Without a divisor we cannot convert credits to PRs, and a wrong conversion is worse than+ // no number at all.+ it('is null without a usable divisor', () => {+ expect(creditsPerPr(inbox({ display_divisor: undefined }))).toBeNull()+ expect(creditsPerPr(inbox({ display_divisor: 0 }))).toBeNull()+ expect(creditsPerPr(null)).toBeNull()+ })+ })++ describe('pricePerPrUsd', () => {+ it('scales the first paid tier on a subscribed product', () => {+ expect(pricePerPrUsd(inbox({ subscribed: true, tiers: [tier('0'), tier('0.01')] }))).toBe(15)+ })++ // The whole reason for the plan fallback: an unsubscribed customer sits on the free plan,+ // which has no Stripe price, so the product carries no tiers and no unit amount. Without+ // this the price silently disappears for exactly the users being asked to pick a plan.+ it('falls back to the paid plan when the product has no price', () => {+ const product = inbox({+ plans: [+ plan({ plan_key: 'free-20260617', free_allocation: 4500 }),+ plan({ plan_key: 'paid-20260617', tiers: [tier('0.01')] }),+ ],+ })+ expect(pricePerPrUsd(product)).toBe(15)+ })++ it('prefers the product price over the plan fallback', () => {+ const product = inbox({+ subscribed: true,+ tiers: [tier('0.02')],+ plans: [plan({ plan_key: 'paid-20260617', tiers: [tier('0.01')] })],+ })+ expect(pricePerPrUsd(product)).toBe(30)+ })++ it('uses the unit amount when there are no tiers', () => {+ expect(pricePerPrUsd(inbox({ unit_amount_usd: '0.01' }))).toBe(15)+ })++ it('is null when no plan carries a price', () => {+ expect(pricePerPrUsd(inbox({ plans: [plan({ plan_key: 'free-20260617' })] }))).toBeNull()+ expect(pricePerPrUsd(inbox({ display_divisor: undefined, tiers: [tier('0.01')] }))).toBeNull()+ expect(pricePerPrUsd(null)).toBeNull()+ })+ })++ describe('freePrs', () => {+ it('converts the free allocation to whole PRs', () => {+ expect(freePrs(inbox())).toBe(3)+ })++ it('is zero without an allocation or a divisor', () => {+ expect(freePrs(inbox({ free_allocation: 0 }))).toBe(0)+ expect(freePrs(inbox({ display_divisor: undefined }))).toBe(0)+ expect(freePrs(null)).toBe(0)+ })+ })+})diff --git a/frontend/src/scenes/billing/inboxPricing.ts b/frontend/src/scenes/billing/inboxPricing.tsnew file mode 100644index 000000000000..aa3f785f399c--- /dev/null+++ b/frontend/src/scenes/billing/inboxPricing.ts@@ -0,0 +1,65 @@+import { calculateFreeTier } from 'scenes/billing/billing-utils'++import { BillingProductV2Type, BillingTierType } from '~/types'++/**+ * The Inbox billing product — a flat per-PR credit charge for the work agents ship. This is the key+ * billing uses everywhere (it is also the key into `custom_limits_usd`), so surfaces match on it+ * rather than on `usage_key` (the product reports usage under `signals_credits`).+ */+export const INBOX_PRODUCT_TYPE = 'inbox'++export function findInboxProduct(products: BillingProductV2Type[] | undefined): BillingProductV2Type | null {+ return products?.find((product) => product.type === INBOX_PRODUCT_TYPE) ?? null+}++/** Marginal USD price of a single credit, from the first paid tier (falling back to the unit price). */+function tierPriceUsd(tiers: BillingTierType[] | null | undefined, unitAmountUsd: string | null): number | null {+ const paidTier = tiers?.find((tier) => parseFloat(tier.unit_amount_usd) > 0)+ if (paidTier) {+ return parseFloat(paidTier.unit_amount_usd)+ }+ return unitAmountUsd ? parseFloat(unitAmountUsd) : null+}++/**+ * Marginal USD price of a single credit.+ *+ * The product's own tiers only exist once there's a Stripe price behind the customer's current+ * plan, and the free plan has none. So for anyone not yet subscribed (every user being asked to+ * pick a plan) the product carries no price at all, and the paid plan in `plans` is the only place+ * the number lives. Reading the product first keeps a subscribed customer on the price they're+ * actually charged, including any override.+ */+function perCreditUsd(product: BillingProductV2Type): number | null {+ const fromProduct = tierPriceUsd(product.tiers, product.unit_amount_usd)+ if (fromProduct !== null) {+ return fromProduct+ }+ // The key has to be present to say anything: `!plan_key?.startsWith('free')` is also true for a+ // plan carrying no key at all, which would price the paywall off an unidentified plan.+ const paidPlan = product.plans?.find(+ (plan) => plan.plan_key && !plan.plan_key.startsWith('free') && !plan.flat_rate+ )+ return paidPlan ? tierPriceUsd(paidPlan.tiers, paidPlan.unit_amount_usd) : null+}++/** The API's credits → PR divisor. Null means we can't safely talk in PRs. */+export function creditsPerPr(product: BillingProductV2Type | null): number | null {+ return product?.display_divisor && product.display_divisor > 0 ? product.display_divisor : null+}++export function pricePerPrUsd(product: BillingProductV2Type | null): number | null {+ const credits = creditsPerPr(product)+ if (!product || !credits) {+ return null+ }+ const perCredit = perCreditUsd(product)+ return perCredit != null ? perCredit * credits : null+}++/** PRs included each month before anything is charged. */+export function freePrs(product: BillingProductV2Type | null): number {+ const credits = creditsPerPr(product)+ return product && credits ? Math.round(calculateFreeTier(product) / credits) : 0+}diff --git a/frontend/src/scenes/inbox/components/InboxReportList.tsx b/frontend/src/scenes/inbox/components/InboxReportList.tsxindex a79d566d404a..8f7610470e2c 100644--- a/frontend/src/scenes/inbox/components/InboxReportList.tsx+++ b/frontend/src/scenes/inbox/components/InboxReportList.tsx@@ -23,7 +23,7 @@ export interface InboxReportCardProps {interface InboxReportListProps extends ReportListLogicProps {Card: ComponentType<InboxReportCardProps>- emptyState: { icon: JSX.Element; title: string; description: string }+ emptyState: { icon: JSX.Element; title: string; description: string; extra?: JSX.Element }}/**@@ -155,6 +155,7 @@ function InboxReportListInner({ tabKey, Card, emptyState }: InboxReportListProps</div><h3 className="text-base font-semibold m-0">{emptyState.title}</h3><p className="text-sm text-tertiary m-0">{emptyState.description}</p>+ {emptyState.extra}</div>) : (<>diff --git a/frontend/src/scenes/inbox/components/SelfDrivingInstallingHint.tsx b/frontend/src/scenes/inbox/components/SelfDrivingInstallingHint.tsxnew file mode 100644index 000000000000..c313c13f636c--- /dev/null+++ b/frontend/src/scenes/inbox/components/SelfDrivingInstallingHint.tsx@@ -0,0 +1,23 @@+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/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsx b/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsxindex 3241ffb93480..8c40d2269ff1 100644--- a/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsx+++ b/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsx@@ -24,6 +24,7 @@ import { SignalSourcesPanel } from '../config/SignalSourcesPanel'import { SlackNotificationsSection } from '../config/SlackNotificationsSection'import { AgentSetupModalKey, agentSetupModalLogic } from './agentSetupModalLogic'import { InboxUsageWidget } from './InboxUsageWidget'+import { InstallationSetupSection } from './InstallationSetupSection'type WidgetTone = 'todo' | 'done' | 'neutral'/** Visual weight reflecting how important / frequently edited a part of the setup is. */@@ -294,7 +295,7 @@ function NotificationsWidget(): JSX.Element {/** Section heading styled like a LemonTabs label (same 14px scale, tertiary color) so the* rail reads as a sibling of the tab bar rather than a louder header. */-function SetupSection({ title, children }: { title: string; children: React.ReactNode }): JSX.Element {+export function SetupSection({ title, children }: { title: string; children: React.ReactNode }): JSX.Element {return (<div className="flex flex-col"><h4 className="text-sm font-medium text-tertiary mt-0 mb-3.5">{title}</h4>@@ -371,6 +372,7 @@ export function AgentSetupColumn({ layout }: { layout: 'rail' | 'stacked' }): JSlayout === 'stacked' ? 'mx-auto w-full max-w-2xl px-6 py-6' : 'px-4 py-3')}>+ <InstallationSetupSection /><SetupSection title="Agents"><SignalSourcesWidget /><ScoutTroopWidget />diff --git a/frontend/src/scenes/inbox/components/shell/InstallationCard.tsx b/frontend/src/scenes/inbox/components/shell/InstallationCard.tsxnew file mode 100644index 000000000000..cd7fc5c21b61--- /dev/null+++ b/frontend/src/scenes/inbox/components/shell/InstallationCard.tsx@@ -0,0 +1,72 @@+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { cn } from 'lib/utils/css-classes'+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 } = useActions(wizardSyncUiLogic)++ // 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)+ 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}+ />+ </>+ )+}diff --git a/frontend/src/scenes/inbox/components/shell/InstallationSetupSection.tsx b/frontend/src/scenes/inbox/components/shell/InstallationSetupSection.tsxnew file mode 100644index 000000000000..886ee1df72be--- /dev/null+++ b/frontend/src/scenes/inbox/components/shell/InstallationSetupSection.tsx@@ -0,0 +1,28 @@+import { useValues } from 'kea'+import { useMountedLogic } from 'kea'++import { wizardActiveSessionDetectorLogic } from 'scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic'++import { SetupSection } from './AgentSetupColumn'+import { InstallationCard } from './InstallationCard'++/**+ * The "Installation" block of the inbox setup column, 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+ // rail 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 (+ <SetupSection title="Installation">+ <InstallationCard workflowId={activeWorkflowId} />+ </SetupSection>+ )+}diff --git a/frontend/src/scenes/inbox/components/tabs/PullRequestsTab.tsx b/frontend/src/scenes/inbox/components/tabs/PullRequestsTab.tsxindex 2bc9e09ea923..9aeb8929044c 100644--- a/frontend/src/scenes/inbox/components/tabs/PullRequestsTab.tsx+++ b/frontend/src/scenes/inbox/components/tabs/PullRequestsTab.tsx@@ -3,6 +3,7 @@ import { IconPullRequest } from '@posthog/icons'import { INBOX_FLAT_TAB_LIST_PARAMS } from '../../logics/reportListLogic'import { ReportCard } from '../cards/ReportCard'import { InboxReportList } from '../InboxReportList'+import { SelfDrivingInstallingHint } from '../SelfDrivingInstallingHint'export function PullRequestsTab(): JSX.Element {return (@@ -15,6 +16,11 @@ export function PullRequestsTab(): JSX.Element {title: 'No pull requests right now',description:'When an agent ships a code change, the PR draft lands here for you to review and publish.',+ extra: (+ <SelfDrivingInstallingHint>+ Pull requests will be opened as soon as live data comes in.+ </SelfDrivingInstallingHint>+ ),}}/>)diff --git a/frontend/src/scenes/inbox/components/tabs/ReportsTab.tsx b/frontend/src/scenes/inbox/components/tabs/ReportsTab.tsxindex f2719a50f4ef..02ff18be3141 100644--- a/frontend/src/scenes/inbox/components/tabs/ReportsTab.tsx+++ b/frontend/src/scenes/inbox/components/tabs/ReportsTab.tsx@@ -3,6 +3,7 @@ import { IconNotebook } from '@posthog/icons'import { INBOX_FLAT_TAB_LIST_PARAMS } from '../../logics/reportListLogic'import { ReportCard } from '../cards/ReportCard'import { InboxReportList } from '../InboxReportList'+import { SelfDrivingInstallingHint } from '../SelfDrivingInstallingHint'export function ReportsTab(): JSX.Element {return (@@ -15,6 +16,11 @@ export function ReportsTab(): JSX.Element {title: 'No reports yet',description:"Reports are what agents surface when there's something worth your judgment but no clean code change to draft.",+ extra: (+ <SelfDrivingInstallingHint>+ Reports will start arriving as soon as live data comes in.+ </SelfDrivingInstallingHint>+ ),}}/>)diff --git a/frontend/src/scenes/inbox/logics/inboxOnboardingLogic.test.ts b/frontend/src/scenes/inbox/logics/inboxOnboardingLogic.test.tsindex 116037df88ef..e6bc78911dcc 100644--- a/frontend/src/scenes/inbox/logics/inboxOnboardingLogic.test.ts+++ b/frontend/src/scenes/inbox/logics/inboxOnboardingLogic.test.ts@@ -7,6 +7,8 @@ describe('computeOnboardingMode', () => {areCountsResolved: true,hasExistingWork: false,bannerDismissed: false,+ isWizardRunning: false,+ isWizardStateResolved: true,}it.each<[string, Partial<OnboardingModeInputs>, InboxOnboardingMode]>([@@ -29,6 +31,19 @@ describe('computeOnboardingMode', () => {['not set up, with work, banner dismissed', { hasExistingWork: true, bannerDismissed: true }, 'none'],// Dismissing the banner has no effect on the takeover (the takeover has no dismiss).['not set up, empty inbox, banner dismissed', { bannerDismissed: true }, 'takeover'],+ // 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 }, 'none'],+ ['wizard running, would otherwise banner', { isWizardRunning: true, hasExistingWork: true }, 'none'],+ // 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 }, 'none'],+ [+ 'wizard state unknown, would otherwise banner',+ { isWizardStateResolved: false, hasExistingWork: true },+ 'none',+ ],])('%s', (_label, overrides, expected) => {expect(computeOnboardingMode({ ...base, ...overrides })).toBe(expected)})diff --git a/frontend/src/scenes/inbox/logics/inboxOnboardingLogic.ts b/frontend/src/scenes/inbox/logics/inboxOnboardingLogic.tsindex ec0c04ad0a65..4f26bc1ac849 100644--- a/frontend/src/scenes/inbox/logics/inboxOnboardingLogic.ts+++ b/frontend/src/scenes/inbox/logics/inboxOnboardingLogic.ts@@ -1,4 +1,8 @@-import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'++import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { wizardActiveSessionDetectorLogic } from 'scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic'+import { SELF_DRIVING_WORKFLOW_ID } from 'scenes/onboarding/shared/wizard-sync/workflows'import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'@@ -7,6 +11,10 @@ import type { SignalSourceConfig } from '../types'import { INBOX_FLAT_TAB_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+/** How the self-driving onboarding presents itself over the inbox. */export type InboxOnboardingMode = 'takeover' | 'banner' | 'none'@@ -21,6 +29,11 @@ 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}/**@@ -37,7 +50,21 @@ export function computeOnboardingMode({areCountsResolved,hasExistingWork,bannerDismissed,+ isWizardRunning,+ isWizardStateResolved,}: OnboardingModeInputs): InboxOnboardingMode {+ // 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 'none'+ }+ // The config and count loaders settle in under a second; the wizard detector answers on its own+ // polling cadence. Until it has, "not running" is absence of evidence, and acting on it here is+ // exactly the wrong-takeover case for someone landing in the inbox mid-run — so hold the normal+ // inbox, same as the other unsettled inputs below.+ if (!isWizardStateResolved) {+ return 'none'+ }// Until the config check resolves we don't know the verdict – stay on the normal inbox skeleton.if (!isSetupLoaded) {return 'none'@@ -59,6 +86,7 @@ export function computeOnboardingMode({// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface inboxOnboardingLogicValues {+ receivedFeatureFlags: boolean // featureFlagLogicpullsCount: number | null // reportListLogicpullsCountLoading: boolean // reportListLogicreportsCount: number | null // reportListLogic@@ -67,16 +95,24 @@ export interface inboxOnboardingLogicValues {scoutConfigs: SignalScoutConfig[] | null // scoutFleetLogicenabledSourcesCount: number // signalSourcesLogicsourceConfigs: SignalSourceConfig[] | null // signalSourcesLogic+ activeWorkflowId: string | null // wizardActiveSessionDetectorLogic+ hasResolvedSessionState: boolean // wizardActiveSessionDetectorLogic+ watchedWorkflows: string[] // wizardActiveSessionDetectorLogicareCountsResolved: booleanbannerDismissed: booleanhasExistingWork: booleanisSelfDrivingSetUp: booleanisSetupLoaded: boolean+ isWizardRunning: boolean+ isWizardStateResolved: booleanonboardingMode: InboxOnboardingMode}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface inboxOnboardingLogicActions {+ checkWizardSession: () => {+ value: true+ } // wizardActiveSessionDetectorLogicdismissBanner: () => {value: true}@@ -94,12 +130,20 @@ export interface inboxOnboardingLogicMeta {reportsCountLoading: boolean) => booleanhasExistingWork: (pullsCount: number | null, reportsCount: number | null) => boolean+ isWizardRunning: (activeWorkflowId: string | null) => boolean+ isWizardStateResolved: (+ hasResolvedSessionState: boolean,+ watchedWorkflows: string[],+ receivedFeatureFlags: boolean+ ) => booleanonboardingMode: (isSetupLoaded: boolean,isSelfDrivingSetUp: boolean,areCountsResolved: boolean,hasExistingWork: boolean,- bannerDismissed: boolean+ bannerDismissed: boolean,+ isWizardRunning: boolean,+ isWizardStateResolved: boolean) => InboxOnboardingMode}}@@ -141,7 +185,13 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([['count as pullsCount', 'countLoading as pullsCountLoading'],reportListLogic({ tabKey: 'reports', listParams: INBOX_FLAT_TAB_LIST_PARAMS.reports }),['count as reportsCount', 'countLoading as reportsCountLoading'],+ // Already mounted app-wide by the sync widget; connecting here just reads its verdict.+ wizardActiveSessionDetectorLogic,+ ['activeWorkflowId', 'hasResolvedSessionState', 'watchedWorkflows'],+ featureFlagLogic,+ ['receivedFeatureFlags'],],+ actions: [wizardActiveSessionDetectorLogic, ['check as checkWizardSession']],})),actions({@@ -189,14 +239,41 @@ 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,+ ],+ // Trivially resolved when the detector isn't watching the self-driving program (control+ // variant, 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. That shortcut needs flags in hand though: `watchedWorkflows` is derived from the+ // onboarding variant, and before the flags land it reads as the control arm for everyone,+ // which would let the takeover render for a user whose run is mid-flight and then flicker+ // back out once the flags arrive.+ isWizardStateResolved: [+ (s) => [s.hasResolvedSessionState, s.watchedWorkflows, s.receivedFeatureFlags],+ (hasResolvedSessionState: boolean, watchedWorkflows: string[], receivedFeatureFlags: boolean): boolean =>+ hasResolvedSessionState ||+ (receivedFeatureFlags && !watchedWorkflows.includes(SELF_DRIVING_WORKFLOW_ID)),+ ],onboardingMode: [- (s) => [s.isSetupLoaded, s.isSelfDrivingSetUp, s.areCountsResolved, s.hasExistingWork, s.bannerDismissed],+ (s) => [+ s.isSetupLoaded,+ s.isSelfDrivingSetUp,+ s.areCountsResolved,+ s.hasExistingWork,+ s.bannerDismissed,+ s.isWizardRunning,+ s.isWizardStateResolved,+ ],(isSetupLoaded: boolean,isSelfDrivingSetUp: boolean,areCountsResolved: boolean,hasExistingWork: boolean,- bannerDismissed: boolean+ bannerDismissed: boolean,+ isWizardRunning: boolean,+ isWizardStateResolved: boolean): InboxOnboardingMode =>computeOnboardingMode({isSetupLoaded,@@ -204,7 +281,36 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([areCountsResolved,hasExistingWork,bannerDismissed,+ isWizardRunning,+ isWizardStateResolved,}),],}),++ // 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 }) => {+ 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')+ }),])diff --git a/frontend/src/scenes/inbox/logics/inboxUsageLogic.ts b/frontend/src/scenes/inbox/logics/inboxUsageLogic.tsindex c6319e3ae24b..622e7169ac3d 100644--- a/frontend/src/scenes/inbox/logics/inboxUsageLogic.ts+++ b/frontend/src/scenes/inbox/logics/inboxUsageLogic.ts@@ -8,8 +8,13 @@ import { ApiError } from 'lib/api-error'import { FEATURE_FLAGS } from 'lib/constants'import { Dayjs } from 'lib/dayjs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { calculateFreeTier } from 'scenes/billing/billing-utils'import { billingLogic } from 'scenes/billing/billingLogic'+import {+ INBOX_PRODUCT_TYPE,+ creditsPerPr as deriveCreditsPerPr,+ freePrs as deriveFreePrs,+ pricePerPrUsd as derivePricePerPrUsd,+} from 'scenes/billing/inboxPricing'import { teamLogic } from 'scenes/teamLogic'import { BillingProductV2Type } from '~/types'@@ -21,26 +26,11 @@ import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'import type { BillingType } from '../../../types'import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'-// The inbox/signals billing product type (a flat per-PR credit charge). This is the identifier-// billing uses everywhere — it's also the key into `custom_limits_usd` — so we match on it rather-// than `usage_key` (the product reports usage under `signals_credits`).-const INBOX_PRODUCT_TYPE = 'inbox'-export type InboxUsageStatus = 'normal' | 'warning' | 'limit'// Above this fraction of the limit we warn the user before they run out.const WARNING_THRESHOLD = 0.8-/** Marginal USD price of a single credit, from the first paid tier (falling back to the product- * unit price). Used with `creditsPerPr` to derive the per-PR price without hardcoding anything. */-function perCreditUsd(product: BillingProductV2Type): number | null {- const paidTier = product.tiers?.find((tier) => parseFloat(tier.unit_amount_usd) > 0)- if (paidTier) {- return parseFloat(paidTier.unit_amount_usd)- }- return product.unit_amount_usd ? parseFloat(product.unit_amount_usd) : null-}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface inboxUsageLogicValues {billing: BillingType | null // billingLogic@@ -184,8 +174,8 @@ export interface inboxUsageLogicMeta {) => booleanisSubscribed: (product: BillingProductV2Type | null) => booleancreditsPerPr: (product: BillingProductV2Type | null) => number | null- pricePerPrUsd: (product: BillingProductV2Type | null, creditsPerPr: number | null) => number | null- freePrs: (product: BillingProductV2Type | null, creditsPerPr: number | null) => number+ pricePerPrUsd: (product: BillingProductV2Type | null) => number | null+ freePrs: (product: BillingProductV2Type | null) => numberusedPrs: (product: BillingProductV2Type | null,creditsPerPr: number | null,@@ -359,24 +349,13 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([// Credits per PR — the API's credits → PR divisor. Null means we can't safely show PRs.creditsPerPr: [(s) => [s.product],- (product: BillingProductV2Type | null): number | null =>- product?.display_divisor && product.display_divisor > 0 ? product.display_divisor : null,+ (product: BillingProductV2Type | null): number | null => deriveCreditsPerPr(product),],pricePerPrUsd: [- (s) => [s.product, s.creditsPerPr],- (product: BillingProductV2Type | null, creditsPerPr: number | null): number | null => {- if (!product || !creditsPerPr) {- return null- }- const perCredit = perCreditUsd(product)- return perCredit != null ? perCredit * creditsPerPr : null- },- ],- freePrs: [- (s) => [s.product, s.creditsPerPr],- (product: BillingProductV2Type | null, creditsPerPr: number | null): number =>- product && creditsPerPr ? Math.round(calculateFreeTier(product) / creditsPerPr) : 0,+ (s) => [s.product],+ (product: BillingProductV2Type | null): number | null => derivePricePerPrUsd(product),],+ freePrs: [(s) => [s.product], (product: BillingProductV2Type | null): number => deriveFreePrs(product)],usedPrs: [(s) => [s.product, s.creditsPerPr, s.refundSummary],(diff --git a/frontend/src/scenes/integrations/IntegrationFullPage.tsx b/frontend/src/scenes/integrations/IntegrationFullPage.tsxindex 93512a68e47e..62c3952196c9 100644--- a/frontend/src/scenes/integrations/IntegrationFullPage.tsx+++ b/frontend/src/scenes/integrations/IntegrationFullPage.tsx@@ -7,6 +7,7 @@ import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArimport { TeamMembershipLevel } from 'lib/constants'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'+import { useSelfDrivingRunState } from 'scenes/onboarding/shared/wizard-sync/hooks'import { urls } from 'scenes/urls'import { IntegrationType } from '~/types'@@ -201,9 +202,41 @@ function ConnectedView({</div>) : null}- <LemonButton type="primary" to={urls.projectHomepage()}>- Go to PostHog- </LemonButton>+ <ConnectedNextStep /></>)}++/**+ * 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.+ */+function ConnectedNextStep(): JSX.Element {+ const { inFlight, resolved } = useSelfDrivingRunState()++ // 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>+ )+ }++ return (+ <LemonButton type="primary" to={urls.projectHomepage()}>+ Go to PostHog+ </LemonButton>+ )+}diff --git a/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts b/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.tsindex 7292242b9fa0..a458f0d25e33 100644--- a/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts+++ b/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts@@ -499,10 +499,10 @@ describe('onboardingLogic — flow composition', () => {})})- describe('completeContextOnboarding', () => {+ describe('completeSelfDrivingOnboarding', () => {it('persists both onboarding completion signals', async () => {await expectLogic(logic, () => {- logic.actions.completeContextOnboarding()+ logic.actions.completeSelfDrivingOnboarding()}).toDispatchActions([(action) => {if (action.type !== logic.actionTypes.updateCurrentTeam) {diff --git a/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx b/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsxindex 7babbc1e0344..9b6221248643 100644--- a/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx+++ b/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx@@ -10,7 +10,6 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { isKeyOf } from 'lib/utils/guards'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'-import { getRelativeNextPath } from 'lib/utils/url'import { billingLogic } from 'scenes/billing/billingLogic'import { resolveOnboardingFlowVariant } from 'scenes/onboarding/onboardingVariants'import { availableOnboardingProducts } from 'scenes/onboarding/shared/utils'@@ -100,7 +99,7 @@ export interface onboardingLogicActions {openGlobalSetup: () => {value: true} // globalSetupLogic- reportContextOnboardingCompleted: (productKey: string) => {+ reportSelfDrivingOnboardingCompleted: (productKey: string) => {productKey: string} // onboardingEventUsageLogicopenSidePanel: (@@ -124,12 +123,12 @@ export interface onboardingLogicActions {clearProductKey: () => {value: true}- completeContextOnboarding: () => {- value: true- }completeOnboarding: (options?: { redirectUrlOverride?: string }) => {redirectUrlOverride: string | undefined}+ completeSelfDrivingOnboarding: () => {+ value: true+ }goToNextStep: () => {value: true}@@ -258,7 +257,7 @@ export const onboardingLogic = kea<onboardingLogicType>([globalSetupLogic,['openGlobalSetup'],onboardingEventUsageLogic,- ['reportContextOnboardingCompleted'],+ ['reportSelfDrivingOnboardingCompleted'],],})),actions({@@ -273,7 +272,7 @@ export const onboardingLogic = kea<onboardingLogicType>([}),// Completion for the context-first flow, which has no selected product. Marks onboarding done// (so sceneLogic stops redirecting here) and credits the sources the user turned on.- completeContextOnboarding: true,+ completeSelfDrivingOnboarding: true,setSubscribedDuringOnboarding: (subscribedDuringOnboarding: boolean) => ({ subscribedDuringOnboarding }),setTeamPropertiesForProduct: (productKey: ProductKey) => ({ productKey }),setWaitForBilling: (waitForBilling: boolean) => ({ waitForBilling }),@@ -799,7 +798,7 @@ export const onboardingLogic = kea<onboardingLogicType>([lemonToast.error("Couldn't save onboarding progress. Please try again.")}},- completeContextOnboarding: async () => {+ completeSelfDrivingOnboarding: async () => {// Idempotency guard — Finish can fire twice on a double-click.if (values.isCompleting) {return@@ -821,7 +820,7 @@ export const onboardingLogic = kea<onboardingLogicType>([for (const productKey of products) {// Same `onboarding completed` event name as the legacy flow, stamped `version: 2`// so dashboards can split the flows without a rename (GROW-89).- actions.reportContextOnboardingCompleted(productKey)+ actions.reportSelfDrivingOnboardingCompleted(productKey)actions.recordProductIntentOnboardingComplete({ product_type: productKey })}// Persist both completion signals before navigating. updateCurrentTeam is not optimistic,@@ -835,9 +834,11 @@ export const onboardingLogic = kea<onboardingLogicType>([completed_snippet_onboarding: true,has_completed_onboarding_for: completedMap,})- router.actions.push(- getRelativeNextPath(router.values.searchParams['next'], window.location) ?? urls.default()- )+ // Always the inbox: it is where the wizard's output lands, so it's the only ending+ // that continues the flow. `next` is deliberately ignored — the onboarding gate+ // stamps it with whatever page it bounced the user off (sceneLogic), so honouring+ // it would send most people back to /home instead.+ router.actions.push(urls.inbox())} catch {lemonToast.error("Couldn't finish onboarding. Please try again.")} finally {diff --git a/frontend/src/scenes/onboarding/legacy/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx b/frontend/src/scenes/onboarding/legacy/sdks/OnboardingInstallStep/WizardInstallStep/index.tsxindex 902aff955020..9007a53ed92c 100644--- a/frontend/src/scenes/onboarding/legacy/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx+++ b/frontend/src/scenes/onboarding/legacy/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx@@ -8,10 +8,8 @@ import { OnboardingStepKey, type SDK } from '~/types'import { onboardingEventUsageLogic } from '../../../../onboardingEventUsageLogic'import { activeCloudRunLogic } from '../../../../shared/wizard-sync/activeCloudRunLogic'-import {- InstallationProgressView,- useLocalWizardRunActive,-} from '../../../../shared/wizard-sync/InstallationProgressView'+import { useLocalWizardRunActive } from '../../../../shared/wizard-sync/hooks'+import { InstallationProgressView } from '../../../../shared/wizard-sync/InstallationProgressView'import { WizardCommandBlock } from '../../../../shared/wizard-sync/WizardCommandBlock'import { WizardInstallOptions } from '../../../../shared/wizard-sync/WizardInstallOptions'import { OnboardingStep } from '../../../OnboardingStep'@@ -26,10 +24,10 @@ import { WizardInstallIntro } from './WizardInstallIntro'// 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.function LegacyInstallOptions(): JSX.Element {- const { reportContextOnboardingInstallModeSelected } = useActions(onboardingEventUsageLogic)+ const { reportSelfDrivingOnboardingInstallModeSelected } = useActions(onboardingEventUsageLogic)return (<WizardInstallOptions- onModeSelected={reportContextOnboardingInstallModeSelected}+ onModeSelected={reportSelfDrivingOnboardingInstallModeSelected}localBlock={<WizardCommandBlock />}/>)diff --git a/frontend/src/scenes/onboarding/onboardingEventUsageLogic.ts b/frontend/src/scenes/onboarding/onboardingEventUsageLogic.tsindex 92f61388107b..f69929aec24d 100644--- a/frontend/src/scenes/onboarding/onboardingEventUsageLogic.ts+++ b/frontend/src/scenes/onboarding/onboardingEventUsageLogic.ts@@ -6,14 +6,17 @@ import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogimport { resolveOnboardingFlowVariant } from './onboardingVariants'-/** Steps of the context-first onboarding flow (`ContextOnboarding.tsx`), in order. */-export type ContextOnboardingStepId = 'welcome' | 'install' | 'sources' | 'warehouse' | 'billing' | 'invite'+/** Steps the self-driving flow can report. Earlier versions also emitted `sources`, `warehouse`,+ * and `invite`; those events still exist in historical funnels. */+export type SelfDrivingOnboardingStepId = 'welcome' | 'install' | 'billing'// GROW-89: both onboarding flows fire the same funnel event names during the transition, told apart-// by `version` (1 = legacy, 2 = context-first redesign) and `flow_variant`. Reusing names keeps-// every existing dashboard and alert on the v1 events working; the legacy flow's events live in+// by `version` (1 = legacy, 2 = redesign) and `flow_variant`. Reusing names keeps every existing+// dashboard and alert on the v1 events working; the legacy flow's events live in// `eventUsageLogic`, stamped `{version: 1, flow_variant: 'legacy'}`.-const CONTEXT_ONBOARDING_EVENT_PROPS = { version: 2, flow_variant: 'context_first' } as const+// `context_first` is the redesign's original codename, frozen here because live funnels filter on+// it — the code vocabulary is "self-driving", the wire vocabulary stays put.+const SELF_DRIVING_ONBOARDING_EVENT_PROPS = { version: 2, flow_variant: 'context_first' } as const/** Arm of the cloud-wizard AB test (GROW-117): `test` offers the cloud run, `control` is local-only. */export type CloudRunExperimentArm = 'control' | 'test'@@ -62,7 +65,7 @@ export interface onboardingEventUsageLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface onboardingEventUsageLogicActions {- reportContextOnboardingCloudRunCompleted: (props: {+ reportSelfDrivingOnboardingCloudRunCompleted: (props: {durationSeconds: number | nullprOpened: booleanprUrl: string | null@@ -77,40 +80,31 @@ export interface onboardingEventUsageLogicActions {status: 'cancelled' | 'completed' | 'failed'taskId: string}- reportContextOnboardingCloudRunQueued: (props: { repository: string; runId: string; taskId: string }) => {+ reportSelfDrivingOnboardingCloudRunQueued: (props: { repository: string; runId: string; taskId: string }) => {repository: stringrunId: stringtaskId: string}- reportContextOnboardingCompleted: (productKey: string) => {+ reportSelfDrivingOnboardingCompleted: (productKey: string) => {productKey: string}- reportContextOnboardingInstallModeSelected: (mode: 'cloud' | 'local') => {+ reportSelfDrivingOnboardingInstallModeSelected: (mode: 'cloud' | 'local') => {mode: 'cloud' | 'local'}- reportContextOnboardingPlanSelected: (plan: 'free' | 'pay_as_you_go') => {+ reportSelfDrivingOnboardingPlanSelected: (plan: 'free' | 'pay_as_you_go') => {plan: 'free' | 'pay_as_you_go'}- reportContextOnboardingSourceToggled: (- productKey: string,- toggle: string,- enabled: boolean- ) => {- enabled: boolean- productKey: string- toggle: string- }- reportContextOnboardingStarted: () => {+ reportSelfDrivingOnboardingStarted: () => {value: true}- reportContextOnboardingStepCompleted: (stepId: ContextOnboardingStepId) => {- stepId: ContextOnboardingStepId+ reportSelfDrivingOnboardingStepCompleted: (stepId: SelfDrivingOnboardingStepId) => {+ stepId: SelfDrivingOnboardingStepId}- reportContextOnboardingStepSkipped: (stepId: ContextOnboardingStepId) => {- stepId: ContextOnboardingStepId+ reportSelfDrivingOnboardingStepSkipped: (stepId: SelfDrivingOnboardingStepId) => {+ stepId: SelfDrivingOnboardingStepId}- reportContextOnboardingStepViewed: (stepId: ContextOnboardingStepId) => {- stepId: ContextOnboardingStepId+ reportSelfDrivingOnboardingStepViewed: (stepId: SelfDrivingOnboardingStepId) => {+ stepId: SelfDrivingOnboardingStepId}reportWizardSyncDashboardCtaClicked: (props: {mode: 'cloud' | 'local'@@ -175,11 +169,11 @@ export type onboardingEventUsageLogicType = MakeLogicType<>/**- * Funnel events for the context-first onboarding flow (v2) — a dedicated logic rather than more+ * Funnel events for the self-driving onboarding flow (v2) — a dedicated logic rather than more* surface on the giant `eventUsageLogic`, following `sessionRecordingEventUsageLogic`'s split.* Shared funnel signals (started, step completed/skipped, completed) reuse the legacy event names- * with `version: 2`; signals the legacy flow doesn't have (step viewed, install mode, source- * toggles, plan, cloud run) get their own names.+ * with `version: 2`; signals the legacy flow doesn't have (step viewed, install mode, plan, cloud+ * run) get their own names.*/export const onboardingEventUsageLogic = kea<onboardingEventUsageLogicType>([path(['scenes', 'onboarding', 'onboardingEventUsageLogic']),@@ -187,22 +181,18 @@ export const onboardingEventUsageLogic = kea<onboardingEventUsageLogicType>([values: [featureFlagLogic, ['featureFlags']],})),actions({- reportContextOnboardingStarted: true,- reportContextOnboardingStepViewed: (stepId: ContextOnboardingStepId) => ({ stepId }),- reportContextOnboardingStepCompleted: (stepId: ContextOnboardingStepId) => ({ stepId }),- reportContextOnboardingStepSkipped: (stepId: ContextOnboardingStepId) => ({ stepId }),- reportContextOnboardingCompleted: (productKey: string) => ({ productKey }),- reportContextOnboardingInstallModeSelected: (mode: 'cloud' | 'local') => ({ mode }),- reportContextOnboardingSourceToggled: (productKey: string, toggle: string, enabled: boolean) => ({- productKey,- toggle,- enabled,- }),- reportContextOnboardingPlanSelected: (plan: 'free' | 'pay_as_you_go') => ({ plan }),+ reportSelfDrivingOnboardingStarted: true,+ reportSelfDrivingOnboardingStepViewed: (stepId: SelfDrivingOnboardingStepId) => ({ stepId }),+ reportSelfDrivingOnboardingStepCompleted: (stepId: SelfDrivingOnboardingStepId) => ({ stepId }),+ reportSelfDrivingOnboardingStepSkipped: (stepId: SelfDrivingOnboardingStepId) => ({ stepId }),+ reportSelfDrivingOnboardingCompleted: (productKey: string) => ({ productKey }),+ reportSelfDrivingOnboardingInstallModeSelected: (mode: 'cloud' | 'local') => ({ mode }),+ reportSelfDrivingOnboardingPlanSelected: (plan: 'free' | 'pay_as_you_go') => ({ plan }),// Cloud-run funnel events mirror the backend `task_run_created` / `task_run_completed`// lifecycle events (products/tasks/backend/models.py) and reuse their property names.- reportContextOnboardingCloudRunQueued: (props: { taskId: string; runId: string; repository: string }) => props,- reportContextOnboardingCloudRunCompleted: (props: {+ reportSelfDrivingOnboardingCloudRunQueued: (props: { taskId: string; runId: string; repository: string }) =>+ props,+ reportSelfDrivingOnboardingCloudRunCompleted: (props: {taskId: stringrunId: stringstatus: 'completed' | 'failed' | 'cancelled'@@ -243,68 +233,61 @@ export const onboardingEventUsageLogic = kea<onboardingEventUsageLogicType>([}),listeners(({ values }) => ({// The flow always enters at the welcome step, so `started` carries a fixed entry point- // (legacy uses e.g. 'product_selection').- reportContextOnboardingStarted: () => {+ // (legacy uses e.g. 'product_selection'). It has to match the `step_key` on the first+ // `onboarding step viewed`, or funnels segmenting on it disagree with themselves.+ reportSelfDrivingOnboardingStarted: () => {posthog.capture('onboarding started', {entry_point: 'welcome',- ...CONTEXT_ONBOARDING_EVENT_PROPS,+ ...SELF_DRIVING_ONBOARDING_EVENT_PROPS,})},- reportContextOnboardingStepViewed: ({ stepId }) => {+ reportSelfDrivingOnboardingStepViewed: ({ stepId }) => {posthog.capture('onboarding step viewed', {step_key: stepId,- ...CONTEXT_ONBOARDING_EVENT_PROPS,+ ...SELF_DRIVING_ONBOARDING_EVENT_PROPS,})},- reportContextOnboardingStepCompleted: ({ stepId }) => {+ reportSelfDrivingOnboardingStepCompleted: ({ stepId }) => {posthog.capture('onboarding step completed', {step_key: stepId,- ...CONTEXT_ONBOARDING_EVENT_PROPS,+ ...SELF_DRIVING_ONBOARDING_EVENT_PROPS,})},- reportContextOnboardingStepSkipped: ({ stepId }) => {+ reportSelfDrivingOnboardingStepSkipped: ({ stepId }) => {posthog.capture('onboarding step skipped', {step_key: stepId,- ...CONTEXT_ONBOARDING_EVENT_PROPS,+ ...SELF_DRIVING_ONBOARDING_EVENT_PROPS,})},- reportContextOnboardingCompleted: ({ productKey }) => {+ reportSelfDrivingOnboardingCompleted: ({ productKey }) => {posthog.capture('onboarding completed', {product_key: productKey,- ...CONTEXT_ONBOARDING_EVENT_PROPS,+ ...SELF_DRIVING_ONBOARDING_EVENT_PROPS,})},- reportContextOnboardingInstallModeSelected: ({ mode }) => {+ reportSelfDrivingOnboardingInstallModeSelected: ({ mode }) => {posthog.capture('onboarding install mode selected', {mode,...wizardSyncEventProps(values.featureFlags),})},- reportContextOnboardingSourceToggled: ({ productKey, toggle, enabled }) => {- posthog.capture('onboarding context source toggled', {- product_key: productKey,- toggle,- enabled,- ...CONTEXT_ONBOARDING_EVENT_PROPS,- })- },- reportContextOnboardingPlanSelected: ({ plan }) => {+ reportSelfDrivingOnboardingPlanSelected: ({ plan }) => {posthog.capture('onboarding plan selected', {plan,- ...CONTEXT_ONBOARDING_EVENT_PROPS,+ ...SELF_DRIVING_ONBOARDING_EVENT_PROPS,})},// Deliberately NOT capturing the repository name or PR URL: they identify customers'// (often private) repos and this event lands in the shared app analytics project. The// backend task_run_* lifecycle events carry them server-side; task_id/run_id join to them.- reportContextOnboardingCloudRunQueued: ({ taskId, runId }) => {+ reportSelfDrivingOnboardingCloudRunQueued: ({ taskId, runId }) => {posthog.capture('onboarding cloud run queued', {task_id: taskId,run_id: runId,...wizardSyncEventProps(values.featureFlags),})},- reportContextOnboardingCloudRunCompleted: ({ taskId, runId, status, durationSeconds, prOpened }) => {+ reportSelfDrivingOnboardingCloudRunCompleted: ({ taskId, runId, status, durationSeconds, prOpened }) => {posthog.capture('onboarding cloud run completed', {task_id: taskId,run_id: runId,diff --git a/frontend/src/scenes/onboarding/self-driving/ContextBillingStep.tsx b/frontend/src/scenes/onboarding/self-driving/ContextBillingStep.tsxdeleted file mode 100644index bb6c79c70d3a..000000000000--- a/frontend/src/scenes/onboarding/self-driving/ContextBillingStep.tsx+++ /dev/null@@ -1,224 +0,0 @@-import { useActions, useValues } from 'kea'--import { IconCheck } from '@posthog/icons'-import { LemonButton, Spinner } from '@posthog/lemon-ui'--import { BillingUpgradeCTA } from 'lib/components/BillingUpgradeCTA'-import { pluralize } from 'lib/utils/strings'-import { billingLogic } from 'scenes/billing/billingLogic'-import { paymentEntryLogic } from 'scenes/billing/paymentEntryLogic'-import { onboardingEventUsageLogic } from 'scenes/onboarding/onboardingEventUsageLogic'-import { availableOnboardingProducts } from 'scenes/onboarding/shared/utils'--import { ProductKey } from '~/queries/schema/schema-general'-import { type BillingProductV2Type } from '~/types'--/**- * Inline billing step body for the context-first onboarding flow.- *- * No flow navigation lives here; the parent shell owns Back/Continue/Skip. The only action this- * step fires is the payment-entry flow, which opens the globally mounted PaymentEntryModal (see- * layout/GlobalModals) over the card and returns to the same URL. Nothing here redirects away.- */--// Compact free-tier allowance, shown so "start free" reads as an honest offer rather than a teaser.-function FreeTierRow({ value, unit, name }: { value: number; unit: string; name: string }): JSX.Element {- const formatted = Intl.NumberFormat('en', {- notation: 'compact',- compactDisplay: 'short',- maximumFractionDigits: 1,- }).format(value)-- return (- <li className="flex items-center gap-2">- <IconCheck className="size-4 text-success shrink-0" />- <span className="text-sm">- <strong>- {formatted} {pluralize(value, unit, undefined, false)}- </strong>{' '}- <span className="text-muted">/ month {name}, free</span>- </span>- </li>- )-}--function FreeTierSummary(): JSX.Element | null {- const { billing } = useValues(billingLogic)-- const allowances = (billing?.products ?? [])- .filter((product) => product.type in availableOnboardingProducts)- .map((product) => {- const freePlan = product.plans.find((plan) => plan.plan_key?.startsWith('free'))- return {- name: product.name,- unit: freePlan?.unit ?? '',- value: freePlan?.free_allocation ?? 0,- }- })- .filter((allowance) => allowance.unit && allowance.value > 0)-- if (allowances.length === 0) {- return null- }-- return (- <ul className="flex flex-col gap-1.5 m-0 p-0 list-none">- {allowances.map((allowance) => (- <FreeTierRow key={allowance.name} value={allowance.value} unit={allowance.unit} name={allowance.name} />- ))}- </ul>- )-}--function SubscribedState({ onContinue }: { onContinue: () => void }): JSX.Element {- return (- <div className="flex flex-col gap-3">- <div className="flex items-start gap-3 p-4 border border-success rounded-lg bg-success-highlight">- <IconCheck className="size-5 text-success shrink-0 mt-0.5" />- <div className="flex-1 min-w-0">- <p className="m-0 text-sm font-semibold">You're on the pay-as-you-go plan</p>- <p className="m-0 text-xs text-muted">- Every tool is unlocked. You still get the monthly free tier on each. You only pay for usage- beyond it.- </p>- </div>- </div>- <p className="text-xs text-muted m-0">Change or cancel any time from billing settings.</p>- <LemonButton type="primary" status="alt" onClick={onContinue} className="self-end">- Continue- </LemonButton>- </div>- )-}--function PlanChoice({- platformProduct,- onContinue,-}: {- platformProduct: BillingProductV2Type | null- onContinue: () => void-}): JSX.Element {- const { startPaymentEntryFlow } = useActions(paymentEntryLogic)- const { reportContextOnboardingPlanSelected } = useActions(onboardingEventUsageLogic)- // Guard the subscribe button against double-submit: `isLoading` covers the returning-customer- // activate call, `paymentEntryModalOpen` covers a new customer once the Stripe modal is up.- const { isLoading, paymentEntryModalOpen } = useValues(paymentEntryLogic)- const subscribing = isLoading || paymentEntryModalOpen-- // Reported at the pick, not at payment completion — whether payment then resolves is billing's- // own funnel (GROW-89).- const subscribe = (): void => {- reportContextOnboardingPlanSelected('pay_as_you_go')- // Returning the user to the same URL keeps them in the onboarding flow once payment resolves.- startPaymentEntryFlow(platformProduct, window.location.pathname + window.location.search)- }- const continueFree = (): void => {- reportContextOnboardingPlanSelected('free')- onContinue()- }-- return (- <div className="flex flex-wrap gap-3">- <p className="text-sm text-muted m-0 w-full">- Start free, no card required. You only pay for usage past the monthly free tier on each tool.- </p>-- <div className="flex flex-1 basis-72 flex-col gap-3 p-4 border border-primary rounded-lg">- <div className="flex items-baseline justify-between gap-2">- <p className="m-0 text-base font-semibold">Free</p>- <p className="m-0 text-sm text-muted">$0 / month</p>- </div>- <FreeTierSummary />- <p className="m-0 text-xs text-muted">- Usage pauses at the free tier instead of charging you. Good for trying things out.- </p>- <LemonButton- type="secondary"- fullWidth- center- onClick={continueFree}- className="mt-auto"- data-attr="context-onboarding-free"- >- Continue on free- </LemonButton>- </div>-- <div className="flex flex-1 basis-72 flex-col gap-3 p-4 border-2 border-accent rounded-lg">- <div className="flex items-baseline justify-between gap-2">- <div>- <p className="m-0 text-base font-semibold">Pay-as-you-go</p>- <p className="m-0 text-xs text-muted">Free tier included</p>- </div>- <p className="m-0 text-sm text-muted">based on usage</p>- </div>- <ul className="flex flex-col gap-1.5 m-0 p-0 list-none">- {[- 'Every tool unlocked, no caps',- 'Same monthly free tier on each tool',- 'Add a card now, pay only past the free tier',- ].map((line) => (- <li key={line} className="flex items-center gap-2">- <IconCheck className="size-4 text-success shrink-0" />- <span className="text-sm">{line}</span>- </li>- ))}- </ul>- <BillingUpgradeCTA- type="primary"- status="alt"- fullWidth- center- className="mt-auto"- loading={subscribing}- disabledReason={subscribing ? 'Opening payment…' : undefined}- disableClientSideRouting- onClick={subscribe}- data-attr="context-onboarding-subscribe"- >- Add payment method- </BillingUpgradeCTA>- </div>- </div>- )-}--export function ContextBillingStep({ onContinue }: { onContinue: () => void }): JSX.Element {- const { billing, billingLoading } = useValues(billingLogic)-- if (!billing && billingLoading) {- return (- <div className="flex items-center justify-center py-12">- <Spinner className="text-2xl text-muted size-8" />- </div>- )- }-- // No billing at all (e.g. self-hosted without a license), so nothing to subscribe to here.- if (!billing) {- return (- <div className="flex flex-col gap-3">- <p className="text-sm text-muted m-0">- Billing isn't configured on this instance, so there's nothing to pick here.- </p>- <div className="flex items-center justify-between gap-2">- <LemonButton type="secondary" to="https://posthog.com/pricing" targetBlank>- See pricing- </LemonButton>- <LemonButton type="primary" status="alt" onClick={onContinue}>- Continue- </LemonButton>- </div>- </div>- )- }-- if (billing.has_active_subscription) {- return <SubscribedState onContinue={onContinue} />- }-- const platformProduct =- billing.products?.find((product) => product.type === ProductKey.PLATFORM_AND_SUPPORT) ?? null-- return <PlanChoice platformProduct={platformProduct} onContinue={onContinue} />-}diff --git a/frontend/src/scenes/onboarding/self-driving/ContextInviteStep.tsx b/frontend/src/scenes/onboarding/self-driving/ContextInviteStep.tsxdeleted file mode 100644index 06a1a6051e3c..000000000000--- a/frontend/src/scenes/onboarding/self-driving/ContextInviteStep.tsx+++ /dev/null@@ -1,62 +0,0 @@-import { useActions, useValues } from 'kea'--import { IconCheckCircle } from '@posthog/icons'-import { LemonButton } from '@posthog/lemon-ui'--import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'-import { inviteLogic } from 'scenes/settings/organization/inviteLogic'-import { InviteTeamMatesComponent } from 'scenes/settings/organization/InviteModal'--/**- * Body of the "Invite your team" step in the context-first onboarding flow.- *- * Reuses the real bulk-invite UI (`InviteTeamMatesComponent`) and logic (`inviteLogic`) so teammates- * can be invited by email inline, no redirect to settings. Navigation (Back/Continue/Skip) is owned- * by the parent shell; this renders body content only.- */-export function ContextInviteStep(): JSX.Element {- const { preflight } = useValues(preflightLogic)- const { invitesToSend, canSubmit, isInviting, inviteContainsOwnerLevel } = useValues(inviteLogic)- const { inviteTeamMembers } = useActions(inviteLogic)-- const emailServiceAvailable = !!preflight?.email_service_available- const hasFilledEmail = invitesToSend.some(({ target_email }) => !!target_email)- const hasInvalidEmail = invitesToSend.some(({ isValid }) => !isValid)-- const sendDisabledReason = hasInvalidEmail- ? 'Enter a valid email address'- : inviteContainsOwnerLevel && !canSubmit- ? 'Type "send invites" to confirm inviting owners'- : !canSubmit- ? 'Fill out all fields first'- : undefined-- return (- <div className="flex flex-col gap-4">- <p className="text-sm text-muted m-0">- PostHog gets better with the people who know the product. Bring your teammates in so they can steer the- agents too.- </p>-- {/* Reuses the real invite rows + logic: email, optional name, org level, add/remove. */}- <InviteTeamMatesComponent hideProjectAccessSelector />-- {/* Only email-based invites get a dedicated send action; without an email service each row- generates its own invite link via the component's per-row submit button. */}- {emailServiceAvailable && (- <div className="flex justify-end">- <LemonButton- type="primary"- icon={<IconCheckCircle />}- onClick={() => inviteTeamMembers()}- loading={isInviting}- disabledReason={!hasFilledEmail ? 'Add a teammate to invite' : sendDisabledReason}- data-attr="context-onboarding-send-invites"- >- Send invites- </LemonButton>- </div>- )}- </div>- )-}diff --git a/frontend/src/scenes/onboarding/self-driving/ContextOnboarding.tsx b/frontend/src/scenes/onboarding/self-driving/ContextOnboarding.tsxdeleted file mode 100644index 1e87115af551..000000000000--- a/frontend/src/scenes/onboarding/self-driving/ContextOnboarding.tsx+++ /dev/null@@ -1,652 +0,0 @@-import { useActions, useAsyncActions, useValues } from 'kea'-import { router } from 'kea-router'-import { type ReactNode, useEffect, useState } from 'react'--import { IconArrowLeft, IconArrowRight, IconCheckCircle, IconGithub } from '@posthog/icons'-import { LemonButton, LemonSwitch, LemonTag, Link } from '@posthog/lemon-ui'--import { AuthorizedUrlList } from 'lib/components/AuthorizedUrlList/AuthorizedUrlList'-import { AuthorizedUrlListType } from 'lib/components/AuthorizedUrlList/authorizedUrlListLogic'-import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'-import { Spinner } from 'lib/lemon-ui/Spinner'-import { cn } from 'lib/utils/css-classes'-import { teamLogic } from 'scenes/teamLogic'--import { ProductKey } from '~/queries/schema/schema-general'-import type { TeamType } from '~/types'--import selfDrivingHog from 'public/hedgehog/self-driving-hog.png'--// Deliberate self-driving → legacy import: onboardingLogic owns the completion flow (marking the-// team onboarded, redirecting out) for both variants.-import { onboardingLogic } from '../legacy/onboardingLogic'-import { type ContextOnboardingStepId, onboardingEventUsageLogic } from '../onboardingEventUsageLogic'-import { useWizardCommand } from '../shared/useWizardCommand'-import { availableOnboardingProducts, getProductIcon, toSentenceCase } from '../shared/utils'-import { activeCloudRunLogic, type CloudRunHandle } from '../shared/wizard-sync/activeCloudRunLogic'-import { installationProgressLogic } from '../shared/wizard-sync/installationProgressLogic'-import { InstallationProgressView, useLocalWizardRunActive } from '../shared/wizard-sync/InstallationProgressView'-import { wizardCloudRunLogic } from '../shared/wizard-sync/wizardCloudRunLogic'-import { WizardCommandBlock } from '../shared/wizard-sync/WizardCommandBlock'-import { WizardInstallOptions } from '../shared/wizard-sync/WizardInstallOptions'-import { ContextBillingStep } from './ContextBillingStep'-import { ContextInviteStep } from './ContextInviteStep'-import { ContextWarehouseStep } from './ContextWarehouseStep'--/**- * Context-first onboarding (prototype, legacy variant). A fixed linear flow, one thing per step,- * that replaces "pick a use case → pick products". Steps configure the context PostHog runs on.- * Real where cheap (install command, source toggles → team props); warehouse/billing/invite and- * completion wiring are still thin and marked for follow-up.- */--// ---- Steps -----------------------------------------------------------------------------------------function WelcomeStep(): JSX.Element {- return (- <div className="flex flex-col items-center text-center gap-5">- <img src={selfDrivingHog} alt="A hedgehog riding in a self-driving car" className="w-full rounded-lg" />- <div className="flex flex-col gap-2">- <h1 className="text-2xl font-bold m-0">Let's make your product self-driving</h1>- <p className="text-muted max-w-md mx-auto m-0">- PostHog runs on your product's context. We'll get it flowing in a few steps, then agents can start- finding and fixing things, with you steering.- </p>- </div>- </div>- )-}--// One wizard, two ways to run it — the shared WizardInstallOptions owns the cloud/local switching-// and framework badges; this wraps it in the self-driving copy and manual-docs fallback.-function InstallOptions({ onContinue }: { onContinue: () => void }): JSX.Element {- const cloudRunEnabled = useFeatureFlag('ONBOARDING_WIZARD_CLOUD_RUN', 'test')- const { isCloudOrDev } = useWizardCommand()- const { reportContextOnboardingInstallModeSelected } = useActions(onboardingEventUsageLogic)- const offerCloud = cloudRunEnabled && isCloudOrDev-- // Self-hosted: the wizard CLI / cloud run only target cloud + dev, so both wizard blocks render- // nothing. Show a real, actionable fallback instead of an empty step.- if (!isCloudOrDev) {- return (- <div className="flex flex-col gap-3">- <p className="text-sm text-muted m-0">- Install the PostHog SDK for your framework and your product's context starts flowing in, ready for- agents to act on.- </p>- <LemonButton type="primary" to="https://posthog.com/docs/getting-started/install" targetBlank>- Read the install docs- </LemonButton>- </div>- )- }-- return (- <div className="flex flex-col gap-4">- {/* Establishes the priority order: the easy path (we run it, you get a PR) up front; the- toggle below is the actor sub-choice; manual docs are the quiet fallback at the bottom. */}- {offerCloud ? (- <p className="text-sm text-muted text-center m-0">- Get your product's context flowing so agents can start finding and fixing things. The easiest way is- to let us set it up and open a PR you just review and merge.- </p>- ) : (- <p className="text-sm text-muted text-center m-0">- Run the wizard to get your product's context flowing so agents can start finding and fixing things.- </p>- )}- {/* GROW-96: kicking off the cloud run is the step's "next" action, so onQueued advances the flow. */}- <WizardInstallOptions- hideHog- onQueued={onContinue}- onModeSelected={reportContextOnboardingInstallModeSelected}- localBlock={<WizardCommandBlock hideHog />}- />- <p className="text-xs text-muted m-0 text-center">- Rather wire it up by hand?{' '}- <Link to="https://posthog.com/docs/getting-started/install" target="_blank">- Read the install docs- </Link>- </p>- </div>- )-}--// When wizard sync is on and a LOCAL run is in flight, swap the options for the live tracker. A cloud-// run is already surfaced by the unified Installation layer (WizardCloudRunBlock → InstallationProgressView),-// and the cloud wizard posts to the same session — so suppress the local run view when a cloud run is-// active to avoid showing two progress components.-function InstallStepWithSync({ onContinue }: { onContinue: () => void }): JSX.Element {- const isLocalRunActive = useLocalWizardRunActive()- const { activeCloudRun } = useValues(activeCloudRunLogic)- // The view claims the shared inline-panel flag itself, so no FAB coordination is needed here.- const showLocalRun = isLocalRunActive && !activeCloudRun- return showLocalRun ? <InstallationProgressView mode="local" /> : <InstallOptions onContinue={onContinue} />-}--function InstallStep({ onContinue }: { onContinue: () => void }): JSX.Element {- const isSyncEnabled = useFeatureFlag('ONBOARDING_WIZARD_SYNC', 'test')- return isSyncEnabled ? <InstallStepWithSync onContinue={onContinue} /> : <InstallOptions onContinue={onContinue} />-}--interface ToolToggle {- label: string- description?: string- checked: boolean- onChange: (checked: boolean) => void- disabled?: boolean-}--interface ToolSource {- productKey: ProductKey- /** Whether this tool is configured to produce meaningful context. */- active: boolean- /** Shown under the tool name when context comes from something other than the toggles below. */- note?: string- toggles: ToolToggle[]- /** Extra config rendered under the toggles (e.g. web analytics authorized domains). */- extra?: ReactNode- /** Spans both grid columns — for the card that carries extra config (web analytics domains). */- wide?: boolean-}--// Tint a `rgb(r g b)` color string into a faint background fill for the icon chip.-function tint(color: string): string {- return color.replace(/\)$/, ' / 0.12)')-}--// Card status reflects config, the SDK, and any in-flight install. The install delivers the SDK every-// source needs, so while it runs a turned-on source is "Installing" and a turned-off one reads-// "Available" — turn it on and it gets installed too. Otherwise it's "Active" once events arrive,-// "Needs install" if on with nothing running, or "Off".-function statusFor(- active: boolean,- sdkInstalled: boolean,- installing: boolean-): { type: 'muted' | 'success' | 'warning' | 'primary'; label: string; loading?: boolean } {- if (!active) {- return installing ? { type: 'muted', label: 'Available' } : { type: 'muted', label: 'Off' }- }- if (installing) {- return { type: 'primary', label: 'Installing', loading: true }- }- return sdkInstalled ? { type: 'success', label: 'Active' } : { type: 'warning', label: 'Needs install' }-}--function ToolCard({- source,- sdkInstalled,- installing,-}: {- source: ToolSource- sdkInstalled: boolean- installing: boolean-}): JSX.Element {- const product = availableOnboardingProducts[source.productKey as keyof typeof availableOnboardingProducts]- const color = product?.iconColor ?? 'var(--color-text-secondary)'- const status = statusFor(source.active, sdkInstalled, installing)-- return (- <div- className={cn(- 'flex h-full flex-col gap-3 p-4 rounded-lg border transition-colors',- source.active ? 'border-accent' : 'border-primary',- source.wide && 'sm:col-span-2'- )}- >- <div className="flex items-center gap-3">- <div- className="size-9 rounded-md flex items-center justify-center shrink-0"- // eslint-disable-next-line react/forbid-dom-props- style={{ backgroundColor: tint(color) }}- >- {getProductIcon(product?.icon, { iconColor: color, className: 'text-lg' })}- </div>- <div className="flex-1 min-w-0">- <p className="m-0 text-sm font-semibold">{toSentenceCase(product?.name ?? source.productKey)}</p>- {source.note && <p className="m-0 text-xs text-muted">{source.note}</p>}- </div>- <LemonTag type={status.type} icon={status.loading ? <Spinner textColored /> : undefined}>- {status.label}- </LemonTag>- </div>- <div className="flex flex-col gap-2">- {source.toggles.map((toggle) => (- <div key={toggle.label} className="flex items-center justify-between gap-3">- <div className="min-w-0">- <p className={cn('m-0 text-sm', toggle.disabled && 'text-muted')}>{toggle.label}</p>- {toggle.description && <p className="m-0 text-xs text-muted">{toggle.description}</p>}- </div>- <LemonSwitch- checked={toggle.checked}- onChange={toggle.onChange}- disabled={toggle.disabled}- size="small"- />- </div>- ))}- </div>- {source.extra && <div>{source.extra}</div>}- </div>- )-}--interface CodebaseAccess {- connected: boolean- /** GitHub org/account the integration is connected to, shown in the connected state. */- displayName: string | null- /** OAuth URL to connect GitHub (activate codebase access) from here. */- connectUrl: string-}--// Codebase access is a context source too — agents read the connected repo. Unlike the SDK-backed-// sources it doesn't ride the install; it's live as soon as GitHub is connected, so a user who skipped-// connecting during install can turn it on here.-function CodebaseAccessCard({ codebase }: { codebase: CodebaseAccess }): JSX.Element {- return (- <div- className={cn(- 'flex h-full flex-col gap-3 p-4 rounded-lg border transition-colors',- codebase.connected ? 'border-accent' : 'border-primary'- )}- >- <div className="flex items-center gap-3">- <div- className="size-9 rounded-md flex items-center justify-center shrink-0"- // eslint-disable-next-line react/forbid-dom-props- style={{ backgroundColor: tint('rgb(100 116 139)') }}- >- <IconGithub className="text-lg" />- </div>- <div className="flex-1 min-w-0">- <p className="m-0 text-sm font-semibold">Codebase access</p>- <p className="m-0 text-xs text-muted">Let agents read your code to find and fix issues.</p>- </div>- <LemonTag type={codebase.connected ? 'success' : 'muted'}>- {codebase.connected ? 'Active' : 'Off'}- </LemonTag>- </div>- {codebase.connected ? (- <div className="flex items-center gap-1.5 text-xs text-muted mt-auto">- <IconCheckCircle className="text-success" />- <span>Connected{codebase.displayName ? ` to ${codebase.displayName}` : ''}</span>- </div>- ) : (- <LemonButton- type="secondary"- size="small"- icon={<IconGithub />}- to={codebase.connectUrl}- disableClientSideRouting- className="self-start mt-auto"- >- Connect GitHub- </LemonButton>- )}- </div>- )-}--function SourcesStep(): JSX.Element {- const { activeCloudRun } = useValues(activeCloudRunLogic)- // GitHub connection drives the codebase-access source, available whether or not a run is in flight.- const { githubIntegration, connectGitHubUrl } = useValues(wizardCloudRunLogic)- const codebase: CodebaseAccess = {- connected: !!githubIntegration,- displayName: githubIntegration?.display_name ?? null,- connectUrl: connectGitHubUrl,- }- // Subscribe to the install stream only when a run exists — keeps this step from opening an SSE for- // everyone who never triggered one.- return activeCloudRun ? (- <SourcesStepWithRun run={activeCloudRun} codebase={codebase} />- ) : (- <SourcesStepInner installing={false} repository={null} codebase={codebase} />- )-}--// While a cloud run is connecting/running, the sources it would feed aren't live yet. Pass that down-// along with the repo it's landing in, so the step can name the install target once.-function SourcesStepWithRun({ run, codebase }: { run: CloudRunHandle; codebase: CodebaseAccess }): JSX.Element {- const { installationProgress } = useValues(- installationProgressLogic({ mode: 'cloud', runId: run.runId, taskId: run.taskId })- )- const { selectedRepository } = useValues(wizardCloudRunLogic)- const installing = installationProgress.phase === 'connecting' || installationProgress.phase === 'running'- return (- <SourcesStepInner- installing={installing}- repository={installing ? selectedRepository : null}- codebase={codebase}- />- )-}--// Exported for Storybook: the presentational sources step takes `installing`, the install's repo, and the-// codebase-access state as props, so stories can render every state without standing up the live logics.-export function SourcesStepInner({- installing,- repository,- codebase,-}: {- installing: boolean- repository: string | null- codebase: CodebaseAccess-}): JSX.Element {- const { currentTeam } = useValues(teamLogic)- const { updateCurrentTeam } = useAsyncActions(teamLogic)- const { reportContextOnboardingSourceToggled } = useActions(onboardingEventUsageLogic)-- const autocaptureOn = !currentTeam?.autocapture_opt_out- const replayOn = !!currentTeam?.session_recording_opt_in- // Web analytics scopes to the team's authorized domains (app_urls); without one it has nothing to track.- const hasAuthorizedDomain = (currentTeam?.app_urls?.length ?? 0) > 0- // Every source here collects through the posthog-js SDK; ingested_event is our proxy for it being- // installed and sending. Until then, turned-on sources read as "Needs install".- const sdkInstalled = !!currentTeam?.ingested_event-- // Report to the v2 funnel (GROW-89) only after the PATCH lands: on failure the switch snaps back- // to the team's real state, so a funnel event would record a toggle that never happened.- // `toggle` names the switch — a card can carry several.- const toggleSource = (productKey: ProductKey, toggle: string, enabled: boolean, patch: Partial<TeamType>): void => {- void updateCurrentTeam(patch)- .then(() => reportContextOnboardingSourceToggled(productKey, toggle, enabled))- .catch(() => {}) // a failed write is not a toggle; the UI already reflects the revert- }-- const sources: ToolSource[] = [- {- productKey: ProductKey.PRODUCT_ANALYTICS,- active: autocaptureOn,- toggles: [- {- label: 'Autocapture events',- description: 'Clicks, pageviews, and inputs captured automatically.',- checked: autocaptureOn,- onChange: (checked) =>- toggleSource(ProductKey.PRODUCT_ANALYTICS, 'autocapture', checked, {- autocapture_opt_out: !checked,- }),- },- {- label: 'Heatmaps',- description: 'Aggregate clicks, scrolls, and mouse movement.',- checked: !!currentTeam?.heatmaps_opt_in,- onChange: (checked) =>- toggleSource(ProductKey.PRODUCT_ANALYTICS, 'heatmaps', checked, { heatmaps_opt_in: checked }),- },- ],- },- {- productKey: ProductKey.SESSION_REPLAY,- active: replayOn,- toggles: [- {- label: 'Record sessions',- checked: replayOn,- onChange: (checked) =>- toggleSource(ProductKey.SESSION_REPLAY, 'session_recording', checked, {- session_recording_opt_in: checked,- }),- },- {- label: 'Console logs',- checked: !!currentTeam?.capture_console_log_opt_in,- onChange: (checked) =>- toggleSource(ProductKey.SESSION_REPLAY, 'console_logs', checked, {- capture_console_log_opt_in: checked,- }),- disabled: !replayOn,- },- {- label: 'Network performance',- checked: !!currentTeam?.capture_performance_opt_in,- onChange: (checked) =>- toggleSource(ProductKey.SESSION_REPLAY, 'network_performance', checked, {- capture_performance_opt_in: checked,- }),- disabled: !replayOn,- },- ],- },- {- productKey: ProductKey.ERROR_TRACKING,- active: !!currentTeam?.autocapture_exceptions_opt_in,- toggles: [- {- label: 'Capture exceptions',- description: 'Errors and stack traces as they happen.',- checked: !!currentTeam?.autocapture_exceptions_opt_in,- onChange: (checked) =>- toggleSource(ProductKey.ERROR_TRACKING, 'exception_autocapture', checked, {- autocapture_exceptions_opt_in: checked,- }),- },- ],- },- {- productKey: ProductKey.WEB_ANALYTICS,- active: autocaptureOn && hasAuthorizedDomain,- toggles: [- {- label: 'Web vitals',- description: 'Load times and layout shifts from real users.',- checked: !!currentTeam?.autocapture_web_vitals_opt_in,- onChange: (checked) =>- toggleSource(ProductKey.WEB_ANALYTICS, 'web_vitals', checked, {- autocapture_web_vitals_opt_in: checked,- }),- },- ],- extra: (- <div className="flex flex-col gap-1.5">- <p className="m-0 text-sm">Authorized domains</p>- <p className="m-0 text-xs text-muted">Add the domains you want web analytics to track.</p>- <AuthorizedUrlList- type={AuthorizedUrlListType.WEB_ANALYTICS}- allowWildCards={false}- showLaunch={false}- displaySuggestions={false}- hideEmptyState- addText="Add a domain"- />- </div>- ),- },- ]-- return (- <div className="flex flex-col gap-4">- <p className="text-sm text-muted m-0">- {!installing ? (- "Active sources feed context to PostHog. Turn on what's relevant — you can change these any time."- ) : repository ? (- <>- Installing PostHog into <span className="font-mono text-default">{repository}</span>. Turn on- anything you want included.- </>- ) : (- 'Installing PostHog. Turn on anything you want included.'- )}- </p>- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">- <CodebaseAccessCard codebase={codebase} />- {sources.map((source) => (- <ToolCard- key={source.productKey}- source={source}- sdkInstalled={sdkInstalled}- installing={installing}- />- ))}- </div>- </div>- )-}--// ---- Shell -----------------------------------------------------------------------------------------interface StepDef {- id: ContextOnboardingStepId- title: string- Content: (props: { onContinue: () => void }) => JSX.Element- skippable?: boolean- /** Step provides its own primary action (e.g. plan picks), so suppress the footer Continue. */- hideContinue?: boolean- /** Tailwind `max-w-*` for the card on this step. Defaults to `max-w-xl`; wider steps (e.g. billing- * with side-by-side plan cards) opt into more room. */- maxWidth?: string-}--const STEPS: StepDef[] = [- { id: 'welcome', title: '', Content: WelcomeStep },- { id: 'install', title: 'Install PostHog', Content: InstallStep },- { id: 'sources', title: 'Turn on your sources', Content: SourcesStep, skippable: true, maxWidth: 'max-w-3xl' },- { id: 'warehouse', title: 'Connect your data', Content: ContextWarehouseStep, skippable: true },- {- id: 'billing',- title: 'Pick a plan',- Content: ContextBillingStep,- hideContinue: true,- maxWidth: 'max-w-3xl',- },- { id: 'invite', title: 'Invite your team', Content: ContextInviteStep, skippable: true },-]--// The card: chrome (sm+ panel; full-bleed on mobile) plus the content flex-column. Width varies per-// step via StepDef.maxWidth — LegacyOnboarding just provides the backdrop + logo.-const CARD_CLASSES =- 'relative w-full flex flex-col gap-5 overflow-hidden p-0 transition-[max-width] duration-300 sm:max-h-[calc(100dvh-7rem)] sm:p-8 md:p-10 sm:bg-surface-primary sm:rounded-xl sm:shadow-md sm:border sm:border-primary'--export function ContextOnboarding(): JSX.Element {- const { completeContextOnboarding } = useActions(onboardingLogic)- const { isCompleting } = useValues(onboardingLogic)- const {- reportContextOnboardingStarted,- reportContextOnboardingStepViewed,- reportContextOnboardingStepCompleted,- reportContextOnboardingStepSkipped,- } = useActions(onboardingEventUsageLogic)- // Initialize from the URL so a refresh — or an OAuth callback that lands back on ?step=install- // (e.g. the GitHub connect flow) — resumes where it left off instead of restarting at welcome.- const [stepIndex, setStepIndex] = useState(() => {- const fromUrl = STEPS.findIndex((s) => s.id === router.values.searchParams['step'])- return fromUrl >= 0 ? fromUrl : 0- })-- const step = STEPS[stepIndex]- const isFirst = stepIndex === 0- const isLast = stepIndex === STEPS.length - 1-- // Funnel (GROW-89): `started` fires once per fresh entry — a ?step= resume (refresh, OAuth- // callback) is a continuation, not a new start. `step viewed` fires for every step shown,- // including the one this mounts on.- useOnMountEffect(() => {- if (stepIndex === 0) {- reportContextOnboardingStarted()- }- })- useEffect(() => {- reportContextOnboardingStepViewed(STEPS[stepIndex].id)- }, [stepIndex, reportContextOnboardingStepViewed])-- // Keep ?step= in sync as the user moves so the URL stays resumable, preserving any other params- // (like the integration ids the GitHub callback appends).- const goToStep = (index: number): void => {- setStepIndex(index)- router.actions.replace(router.values.location.pathname, {- ...router.values.searchParams,- step: STEPS[index].id,- })- }-- const advance = (): void => {- if (isLast) {- // Marks onboarding complete (credits the sources turned on) and navigates out, so- // sceneLogic doesn't bounce the user back into onboarding.- completeContextOnboarding()- return- }- goToStep(stepIndex + 1)- }- // Leaving a step forward is either completing it (Continue / the step's own primary action,- // e.g. a queued cloud run or a plan pick) or skipping it — reported separately so the funnel- // can tell drop-off from opt-out.- const completeStep = (): void => {- reportContextOnboardingStepCompleted(step.id)- advance()- }- const skipStep = (): void => {- reportContextOnboardingStepSkipped(step.id)- advance()- }- const goBack = (): void => goToStep(Math.max(0, stepIndex - 1))-- return (- // This div is the card: chrome + per-step width. On sm+ it's capped to the viewport so the middle- // scrolls internally; on mobile the chrome drops and content flows (the page scrolls).- <div className={cn(CARD_CLASSES, step.maxWidth ?? 'max-w-xl')}>- {/* Pinned header: back button + progress share one row. Equal-width side slots keep the- progress dots centered in the card regardless of whether the back button is shown. */}- <div className="shrink-0 flex flex-col items-center gap-4">- <div className="flex items-center gap-2 w-full">- <div className="w-8 shrink-0 flex justify-start">- {!isFirst && (- <LemonButton- icon={<IconArrowLeft />}- size="small"- onClick={goBack}- tooltip="Go back"- aria-label="Go back"- />- )}- </div>- <div className="flex-1 flex items-center justify-center gap-1.5">- {STEPS.map((s, i) => (- <div- key={s.id}- className={`h-1.5 rounded-full transition-all ${- i === stepIndex ? 'w-6 bg-accent' : 'w-1.5 bg-border'- }`}- />- ))}- </div>- <div className="w-8 shrink-0" />- </div>- {step.title && <h1 className="text-2xl font-bold text-center m-0">{step.title}</h1>}- </div>-- {/* Scrollable middle: fade edges + hover scrollbar so tall steps don't hard-crop. */}- <ScrollableShadows direction="vertical" styledScrollbars className="flex-1 min-h-0" contentClassName="px-1">- <step.Content onContinue={completeStep} />- </ScrollableShadows>-- {/* Pinned footer — omitted when the step has neither Skip nor a footer Continue (it supplies- its own actions, e.g. the plan picks on billing). */}- {(step.skippable || !step.hideContinue) && (- <div className="shrink-0 flex items-center justify-between gap-2">- {step.skippable ? (- <LemonButton type="tertiary" size="small" onClick={skipStep}>- Skip for now- </LemonButton>- ) : (- <span />- )}- {!step.hideContinue && (- <LemonButton- type="primary"- status="alt"- sideIcon={<IconArrowRight />}- onClick={completeStep}- loading={isLast && isCompleting}- >- {isLast ? 'Finish' : isFirst ? 'Get started' : 'Continue'}- </LemonButton>- )}- </div>- )}- </div>- )-}diff --git a/frontend/src/scenes/onboarding/self-driving/ContextWarehouseStep.stories.tsx b/frontend/src/scenes/onboarding/self-driving/ContextWarehouseStep.stories.tsxdeleted file mode 100644index cbb8238ab9dc..000000000000--- a/frontend/src/scenes/onboarding/self-driving/ContextWarehouseStep.stories.tsx+++ /dev/null@@ -1,242 +0,0 @@-import type { Meta, StoryObj } from '@storybook/react'-import { waitFor } from '@testing-library/dom'-import userEvent from '@testing-library/user-event'--import { mswDecorator } from '~/mocks/browser'-import { toPaginatedResponse } from '~/mocks/handlers'-import { ExternalDataSourceType, SourceConfig } from '~/queries/schema/schema-general'--import { ContextWarehouseStep } from './ContextWarehouseStep'--// The catalog endpoint (`external_data_sources/wizard`) returns the source picker contents.-// Stripe carries a flat secret-key field so the inline wizard renders a visible form input when-// selected — the real Stripe config nests auth behind a select + OAuth option, which would pull in-// integration calls we don't need to demonstrate the connect form.-const AVAILABLE_SOURCES: Record<string, SourceConfig> = {- Stripe: {- name: 'Stripe' as ExternalDataSourceType,- label: 'Stripe',- iconPath: '/static/services/stripe.png',- caption: 'Connect your Stripe account to sync revenue, subscriptions, and invoices into PostHog.',- featured: true,- fields: [- {- name: 'stripe_secret_key',- label: 'API key',- type: 'password',- required: true,- placeholder: 'rk_live_...',- secret: true,- },- ],- },- Hubspot: {- name: 'Hubspot' as ExternalDataSourceType,- label: 'HubSpot',- iconPath: '/static/services/hubspot.png',- caption: '',- featured: true,- fields: [],- },- Postgres: {- name: 'Postgres' as ExternalDataSourceType,- label: 'PostgreSQL',- iconPath: '/static/services/postgres.png',- caption: '',- featured: true,- fields: [],- },- Zendesk: {- name: 'Zendesk' as ExternalDataSourceType,- label: 'Zendesk',- iconPath: '/static/services/zendesk.png',- caption: '',- featured: true,- fields: [],- },- // Non-featured sources sit behind the "Show N more" toggle.- Salesforce: {- name: 'Salesforce' as ExternalDataSourceType,- label: 'Salesforce',- iconPath: '/static/services/salesforce.png',- caption: '',- featured: false,- fields: [],- },- Snowflake: {- name: 'Snowflake' as ExternalDataSourceType,- label: 'Snowflake',- iconPath: '/static/services/snowflake.png',- caption: '',- featured: false,- fields: [],- },- Chargebee: {- name: 'Chargebee' as ExternalDataSourceType,- label: 'Chargebee',- iconPath: '/static/services/chargebee.png',- caption: '',- featured: false,- fields: [],- },-}--// One already-connected source so the green "Connected" row renders. The `connectors` selector flags-// a catalog source as connected when this list holds a matching `source_type`.-const CONNECTED_STRIPE_SOURCE = {- id: 'stripe-source-id',- source_type: 'Stripe',- prefix: '',- status: 'Completed',- schemas: [],- created_at: '2026-06-01T00:00:00Z',-}--// Wrap the step in a card that mirrors the real onboarding surface so the body reads like the-// actual scene rather than a bare component.-function OnboardingCard({ children }: { children: React.ReactNode }): JSX.Element {- return (- <div className="min-h-screen bg-primary p-8">- <div className="max-w-xl mx-auto bg-surface-primary border border-primary rounded-xl p-8">- <h2 className="text-xl font-semibold mb-4">Connect your data</h2>- {children}- </div>- </div>- )-}--const meta: Meta<typeof ContextWarehouseStep> = {- title: 'Scenes-Other/Onboarding/Self-Driving/Connect data',- component: ContextWarehouseStep,- parameters: {- layout: 'fullscreen',- viewMode: 'story',- mockDate: '2026-06-26',- },- decorators: [- (Story) => (- <OnboardingCard>- <Story />- </OnboardingCard>- ),- mswDecorator({- get: {- '/api/environments/:team_id/external_data_sources/wizard': () => [200, AVAILABLE_SOURCES],- },- }),- ],-}-export default meta--type Story = StoryObj<typeof ContextWarehouseStep>--// Picker — the default view: featured sources listed with a "Show more" toggle below.-export const Picker: Story = {}--// Searching — typing filters the list to the single matching source.-export const Searching: Story = {- play: async ({ canvasElement }) => {- const searchInput = await waitFor(() => {- const input = canvasElement.querySelector<HTMLInputElement>('input[type="search"]')- if (!input) {- throw new Error('Search input not rendered')- }- return input- })-- await userEvent.type(searchInput, 'stripe')-- // Only Stripe should remain, and the other featured sources should be filtered out.- await waitFor(() => {- if (!canvasElement.textContent?.includes('Stripe')) {- throw new Error('Filtered source not visible')- }- if (canvasElement.textContent?.includes('PostgreSQL')) {- throw new Error('Non-matching source still visible')- }- })- },-}--// SearchingEmpty — a query that matches nothing surfaces the empty state.-export const SearchingEmpty: Story = {- play: async ({ canvasElement }) => {- const searchInput = await waitFor(() => {- const input = canvasElement.querySelector<HTMLInputElement>('input[type="search"]')- if (!input) {- throw new Error('Search input not rendered')- }- return input- })-- await userEvent.type(searchInput, 'nonexistent source')-- await waitFor(() => {- if (!canvasElement.textContent?.includes('No sources match')) {- throw new Error('Empty state not visible')- }- })- },-}--// Connecting — clicking a source row swaps the picker for the inline source wizard, pre-selected to-// Stripe and showing its connection form (the "API key" field).-export const Connecting: Story = {- play: async ({ canvasElement }) => {- const stripeRow = await waitFor(() => {- const row = Array.from(canvasElement.querySelectorAll<HTMLButtonElement>('button')).find((button) =>- button.textContent?.includes('Stripe')- )- if (!row) {- throw new Error('Stripe source row not rendered')- }- return row- })-- await userEvent.click(stripeRow)-- // The inline wizard's step-2 form should render the Stripe secret-key input.- await waitFor(() => {- if (!canvasElement.querySelector('[data-attr="stripe_secret_key"]')) {- throw new Error('Wizard connection form not rendered')- }- })- },-}--// WithConnectedSource — one source already connected shows as a green "Connected" row above the-// remaining picker.-export const WithConnectedSource: Story = {- parameters: {- msw: {- mocks: {- get: {- '/api/environments/:team_id/external_data_sources/': () => [- 200,- toPaginatedResponse([CONNECTED_STRIPE_SOURCE]),- ],- },- },- },- },- play: async ({ canvasElement }) => {- await waitFor(() => {- if (!canvasElement.textContent?.includes('Connected')) {- throw new Error('Connected row not rendered')- }- })- },-}--// Loading — the catalog request never resolves, so the skeleton placeholder stays on screen.-export const Loading: Story = {- parameters: {- msw: {- mocks: {- get: {- '/api/environments/:team_id/external_data_sources/wizard': () => new Promise(() => {}),- },- },- },- },-}diff --git a/frontend/src/scenes/onboarding/self-driving/ContextWarehouseStep.tsx b/frontend/src/scenes/onboarding/self-driving/ContextWarehouseStep.tsxdeleted file mode 100644index 900a632e0ec1..000000000000--- a/frontend/src/scenes/onboarding/self-driving/ContextWarehouseStep.tsx+++ /dev/null@@ -1,158 +0,0 @@-import { BindLogic, useValues } from 'kea'-import { useState } from 'react'--import { IconArrowLeft, IconCheckCircle, IconPlus } from '@posthog/icons'-import { LemonButton, LemonCard, LemonInput, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'--import { ExternalDataSourceType, SourceConfig } from '~/queries/schema/schema-general'--import { availableSourcesLogic } from 'products/data_warehouse/frontend/scenes/NewSourceScene/availableSourcesLogic'-import { NewSourcesWizard } from 'products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene'-import { sourceWizardLogic } from 'products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic'-import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'--/**- * "Connect your data" body for the context-first onboarding flow. Lets the user connect an external- * data source (Stripe, Postgres, Hubspot, …) inline (picker plus the real source wizard) so business- * context (revenue, usage, support) lands in PostHog for agents to reason over. No full-page redirect.- *- * Body content only: the parent shell owns the title, progress, and Back/Skip/Continue navigation.- * Reuses availableSourcesLogic (the source catalog) and sourceWizardLogic (connect flow + the- * already-connected join). This component mounts no new logic of its own.- */-export function ContextWarehouseStep(): JSX.Element {- const { availableSources, availableSourcesLoading } = useValues(availableSourcesLogic)-- if (availableSourcesLoading) {- return (- <div className="flex flex-col gap-2">- <LemonSkeleton className="h-4 w-2/3" />- <LemonSkeleton className="h-12" repeat={3} />- </div>- )- }-- // availableSourcesLogic returns null on a 403 (no warehouse access) and leaves it null on any- // load error. Once loading has finished, null means "couldn't load" — show that, not a skeleton- // forever. The step is skippable, so the user can still move on.- if (availableSources === null) {- return (- <p className="text-sm text-muted m-0">- Couldn't load data sources right now. You can connect one later from settings, or skip for now to keep- going.- </p>- )- }-- return (- <BindLogic logic={sourceWizardLogic} props={{ availableSources }}>- <ContextWarehouseStepInner />- </BindLogic>- )-}--function ContextWarehouseStepInner(): JSX.Element {- const { connectors } = useValues(sourceWizardLogic)- // null = picker, otherwise show the inline wizard pre-selected to this source.- const [connectingTo, setConnectingTo] = useState<ExternalDataSourceType | null>(null)- const [showAll, setShowAll] = useState(false)- const [search, setSearch] = useState('')-- const releasedConnectors = connectors.filter((c: SourceConfig) => !c.unreleasedSource)- const connectedConnectors = releasedConnectors.filter((c: SourceConfig) => c.existingSource)- const connectableConnectors = releasedConnectors.filter((c: SourceConfig) => !c.existingSource)-- const featuredConnectors = connectableConnectors.filter((c: SourceConfig) => c.featured)- const hiddenConnectors = connectableConnectors.filter((c: SourceConfig) => !c.featured)- // A search shows every matching source; with no search, lead with featured + a "show more" toggle.- const searchTerm = search.trim().toLowerCase()- const pickerConnectors = searchTerm- ? connectableConnectors.filter((c: SourceConfig) => (c.label ?? c.name).toLowerCase().includes(searchTerm))- : showAll- ? connectableConnectors- : featuredConnectors-- if (connectingTo) {- return (- <div className="flex flex-col gap-3">- <div>- <LemonButton- type="tertiary"- size="small"- icon={<IconArrowLeft />}- onClick={() => setConnectingTo(null)}- >- Back to sources- </LemonButton>- </div>- <LemonCard hoverEffect={false} className="p-4">- <NewSourcesWizard- hideBackButton- initialSource={connectingTo}- allowedSources={connectableConnectors.map((c: SourceConfig) => c.name)}- onComplete={() => setConnectingTo(null)}- />- </LemonCard>- </div>- )- }-- return (- <div className="flex flex-col gap-4">- <p className="text-sm text-muted m-0">- Pull in business context like revenue, usage, and support so agents can connect it to product behavior.- No ETL; PostHog syncs directly. 1M rows synced free every month.- </p>-- {connectedConnectors.length > 0 && (- <div className="flex flex-col gap-2">- {connectedConnectors.map((connector: SourceConfig) => (- <div- key={connector.name}- className="flex items-center gap-3 p-3 rounded-lg border border-success bg-success-highlight"- >- <SourceIcon type={connector.name} size="small" disableTooltip />- <span className="flex-1 min-w-0 font-medium text-sm truncate">- {connector.label ?? connector.name}- </span>- <LemonTag type="success" icon={<IconCheckCircle />}>- Connected- </LemonTag>- </div>- ))}- </div>- )}-- <LemonInput type="search" placeholder="Search sources" value={search} onChange={setSearch} />-- {pickerConnectors.length > 0 ? (- <div className="flex flex-col gap-2">- {pickerConnectors.map((connector: SourceConfig) => (- <button- key={connector.name}- type="button"- onClick={() => setConnectingTo(connector.name)}- className="flex items-center gap-3 p-3 rounded-lg border border-primary bg-surface-primary text-left cursor-pointer hover:border-accent"- >- <SourceIcon type={connector.name} size="small" disableTooltip />- <span className="flex-1 min-w-0 font-medium text-sm truncate">- {connector.label ?? connector.name}- </span>- <span className="text-xs text-muted shrink-0">Connect</span>- </button>- ))}- </div>- ) : (- searchTerm && <p className="text-sm text-muted m-0">No sources match "{search}".</p>- )}-- {!searchTerm && !showAll && hiddenConnectors.length > 0 && (- <div>- <LemonButton type="secondary" size="small" icon={<IconPlus />} onClick={() => setShowAll(true)}>- Show {hiddenConnectors.length} more source{hiddenConnectors.length === 1 ? '' : 's'}- </LemonButton>- </div>- )}- </div>- )-}diff --git a/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboarding.tsx b/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboarding.tsxindex 7e391324d5d5..d63acba1d0d5 100644--- a/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboarding.tsx+++ b/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboarding.tsx@@ -2,7 +2,7 @@ import './SelfDrivingOnboarding.scss'import { Logo } from 'lib/brand'-import { ContextOnboarding } from './ContextOnboarding'+import { SelfDrivingOnboardingFlow } from './SelfDrivingOnboardingFlow'/*** Host for the self-driving onboarding experience: dotted backdrop, logo, and a centered card that@@ -16,9 +16,9 @@ export function SelfDrivingOnboarding(): JSX.Element | null {<span className="block mb-6"><Logo size="lg" /></span>- {/* The card chrome and its per-step width live inside ContextOnboarding (so the width can vary+ {/* The card chrome and its per-step width live inside the flow (so the width can varyby step); here we just center it under the logo. */}- <ContextOnboarding />+ <SelfDrivingOnboardingFlow /></div>)}diff --git a/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboardingFlow.tsx b/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboardingFlow.tsxnew file mode 100644index 000000000000..360e67208315--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboardingFlow.tsx@@ -0,0 +1,196 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'+import { useEffect, useState } from 'react'++import { IconArrowLeft, IconArrowRight } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'+import { cn } from 'lib/utils/css-classes'++// Deliberate self-driving → legacy import: onboardingLogic owns the completion flow (marking the+// team onboarded, redirecting out) for both variants.+import { onboardingLogic } from '../legacy/onboardingLogic'+import { onboardingEventUsageLogic, type SelfDrivingOnboardingStepId } from '../onboardingEventUsageLogic'+import { BillingStep } from './steps/BillingStep'+import { InstallStep } from './steps/InstallStep'+import { WelcomeStep } from './steps/WelcomeStep'++/**+ * The self-driving onboarding: run the wizard, pick a plan, land in the inbox.+ *+ * The wizard's `self-driving` program does the actual configuration — GitHub, signal sources,+ * scouts — so this flow deliberately owns almost nothing. It shows the command, streams the run's+ * progress, and takes payment. Anything it asked for itself would be a second place to set the+ * same thing.+ */++interface StepDef {+ id: SelfDrivingOnboardingStepId+ title: string+ Content: (props: { onContinue: () => void; completing: boolean }) => JSX.Element+ skippable?: boolean+ /** Step provides its own primary action (e.g. plan picks), so suppress the footer Continue. */+ hideContinue?: boolean+ /** Tailwind `max-w-*` for the card on this step. Defaults to `max-w-xl`; wider steps (e.g. billing+ * with side-by-side plan cards) opt into more room. */+ maxWidth?: string+}++/**+ * Say what this is, run the wizard, pick a plan. The wizard does the real configuration (sources,+ * scouts, GitHub), so the app's job is to show the run and get out of the way — anything this flow+ * asked for separately would be a second place to set the same thing.+ */+const STEPS: StepDef[] = [+ { id: 'welcome', title: '', Content: WelcomeStep },+ { id: 'install', title: 'Install PostHog', Content: InstallStep },+ {+ id: 'billing',+ title: 'Pick a plan',+ Content: BillingStep,+ hideContinue: true,+ maxWidth: 'max-w-3xl',+ },+]++// The card: chrome (sm+ panel; full-bleed on mobile) plus the content flex-column. Width varies per+// step via StepDef.maxWidth — SelfDrivingOnboarding just provides the backdrop + logo.+const CARD_CLASSES =+ 'relative w-full flex flex-col gap-5 overflow-hidden p-0 transition-[max-width] duration-300 sm:max-h-[calc(100dvh-7rem)] sm:p-8 md:p-10 sm:bg-surface-primary sm:rounded-xl sm:shadow-md sm:border sm:border-primary'++export function SelfDrivingOnboardingFlow(): JSX.Element {+ const { completeSelfDrivingOnboarding } = useActions(onboardingLogic)+ const { isCompleting } = useValues(onboardingLogic)+ const {+ reportSelfDrivingOnboardingStarted,+ reportSelfDrivingOnboardingStepViewed,+ reportSelfDrivingOnboardingStepCompleted,+ reportSelfDrivingOnboardingStepSkipped,+ } = useActions(onboardingEventUsageLogic)+ // Initialize from the URL so a refresh — or an OAuth callback that lands back on ?step=install+ // (e.g. the GitHub connect flow) — resumes where it left off instead of restarting at welcome.+ const [stepIndex, setStepIndex] = useState(() => {+ const fromUrl = STEPS.findIndex((s) => s.id === router.values.searchParams['step'])+ return fromUrl >= 0 ? fromUrl : 0+ })++ const step = STEPS[stepIndex]+ const isFirst = stepIndex === 0+ const isLast = stepIndex === STEPS.length - 1++ // Funnel (GROW-89): `started` fires once per fresh entry — a ?step= resume (refresh, OAuth+ // callback) is a continuation, not a new start. `step viewed` fires for every step shown,+ // including the one this mounts on.+ useOnMountEffect(() => {+ if (stepIndex === 0) {+ reportSelfDrivingOnboardingStarted()+ }+ })+ useEffect(() => {+ reportSelfDrivingOnboardingStepViewed(STEPS[stepIndex].id)+ }, [stepIndex, reportSelfDrivingOnboardingStepViewed])++ // Keep ?step= in sync as the user moves so the URL stays resumable, preserving any other params+ // (like the integration ids the GitHub callback appends).+ const goToStep = (index: number): void => {+ setStepIndex(index)+ router.actions.replace(router.values.location.pathname, {+ ...router.values.searchParams,+ step: STEPS[index].id,+ })+ }++ const advance = (): void => {+ if (isLast) {+ // Marks onboarding complete (credits the sources turned on) and navigates out, so+ // sceneLogic doesn't bounce the user back into onboarding.+ completeSelfDrivingOnboarding()+ return+ }+ goToStep(stepIndex + 1)+ }+ // Leaving a step forward is either completing it (Continue / the step's own primary action,+ // e.g. a queued cloud run or a plan pick) or skipping it — reported separately so the funnel+ // can tell drop-off from opt-out.+ const completeStep = (): void => {+ reportSelfDrivingOnboardingStepCompleted(step.id)+ advance()+ }+ const skipStep = (): void => {+ reportSelfDrivingOnboardingStepSkipped(step.id)+ advance()+ }+ const goBack = (): void => goToStep(Math.max(0, stepIndex - 1))++ return (+ // This div is the card: chrome + per-step width. On sm+ it's capped to the viewport so the middle+ // scrolls internally; on mobile the chrome drops and content flows (the page scrolls).+ <div className={cn(CARD_CLASSES, step.maxWidth ?? 'max-w-xl')}>+ {/* Pinned header: back button + progress share one row. Equal-width side slots keep the+ progress dots centered in the card regardless of whether the back button is shown. */}+ <div className="shrink-0 flex flex-col items-center gap-4">+ <div className="flex items-center gap-2 w-full">+ <div className="w-8 shrink-0 flex justify-start">+ {!isFirst && (+ <LemonButton+ icon={<IconArrowLeft />}+ size="small"+ onClick={goBack}+ tooltip="Go back"+ aria-label="Go back"+ />+ )}+ </div>+ <div+ className="flex-1 flex items-center justify-center gap-1.5"+ role="group"+ aria-label={`Step ${stepIndex + 1} of ${STEPS.length}`}+ >+ {STEPS.map((s, i) => (+ <div+ key={s.id}+ className={`h-1.5 rounded-full transition-all ${+ i === stepIndex ? 'w-6 bg-accent' : 'w-1.5 bg-border'+ }`}+ />+ ))}+ </div>+ <div className="w-8 shrink-0" />+ </div>+ {step.title && <h1 className="text-2xl font-bold text-center m-0">{step.title}</h1>}+ </div>++ {/* Scrollable middle: fade edges + hover scrollbar so tall steps don't hard-crop. */}+ <ScrollableShadows direction="vertical" styledScrollbars className="flex-1 min-h-0" contentClassName="px-1">+ <step.Content onContinue={completeStep} completing={isLast && isCompleting} />+ </ScrollableShadows>++ {/* Pinned footer — omitted when the step has neither Skip nor a footer Continue (it supplies+ its own actions, e.g. the plan picks on billing). */}+ {(step.skippable || !step.hideContinue) && (+ <div className="shrink-0 flex items-center justify-between gap-2">+ {step.skippable ? (+ <LemonButton type="tertiary" size="small" onClick={skipStep}>+ Skip for now+ </LemonButton>+ ) : (+ <span />+ )}+ {!step.hideContinue && (+ <LemonButton+ type="primary"+ status="alt"+ sideIcon={<IconArrowRight />}+ onClick={completeStep}+ loading={isLast && isCompleting}+ >+ {isLast ? 'Finish' : isFirst ? 'Get started' : 'Continue'}+ </LemonButton>+ )}+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/SourcesStep.stories.tsx b/frontend/src/scenes/onboarding/self-driving/SourcesStep.stories.tsxdeleted file mode 100644index af3b7eefdcbe..000000000000--- a/frontend/src/scenes/onboarding/self-driving/SourcesStep.stories.tsx+++ /dev/null@@ -1,76 +0,0 @@-import type { Meta, StoryObj } from '@storybook/react'-import { type ReactNode } from 'react'--import { mswDecorator } from '~/mocks/browser'-import preflightJson from '~/mocks/fixtures/_preflight.json'--import { SourcesStepInner } from './ContextOnboarding'--/**- * The "Turn on your sources" step in isolation. Rendered as the presentational sub-component- * (SourcesStepInner) with `installing` driven by an arg — mirrors the ContextWarehouseStep pattern, so- * the in-flight state is exercised without standing up the cloud-run TaskRun stream (no EventSource).- *- * Source active/off state comes from the default mock team (autocapture is on by default, so Product- * analytics renders active); the badge each card shows then depends on `installing` and the SDK.- */--// Wrap the step in a card that mirrors the real onboarding surface (the sources step is the wide variant).-function OnboardingCard({ children }: { children: ReactNode }): JSX.Element {- return (- <div className="min-h-screen bg-primary p-8">- <div className="max-w-3xl mx-auto bg-surface-primary border border-primary rounded-xl p-8">- <h1 className="text-2xl font-bold text-center mb-5">Turn on your sources</h1>- {children}- </div>- </div>- )-}--const meta: Meta<typeof SourcesStepInner> = {- title: 'Scenes-Other/Onboarding/Self-Driving/Turn on your sources',- component: SourcesStepInner,- parameters: {- layout: 'fullscreen',- viewMode: 'story',- mockDate: '2023-05-25',- },- decorators: [- (Story) => (- <OnboardingCard>- <Story />- </OnboardingCard>- ),- mswDecorator({- get: {- '/_preflight': { ...preflightJson, cloud: true, realm: 'cloud' },- '/stats': {},- '/events': {},- },- }),- ],-}-export default meta--type Story = StoryObj<typeof SourcesStepInner>--const CONNECTED_CODEBASE = { connected: true, displayName: 'acme-co', connectUrl: '#' }--/** Default: each card shows its config status — "Active" once events flow, "Needs install" when turned- * on with nothing installed, "Off" when disabled. Codebase access is connected, so it reads "Active". */-export const Default: Story = { args: { installing: false, repository: null, codebase: CONNECTED_CODEBASE } }--/** While an install is in flight (into the named repo), turned-on sources read "Installing" and- * turned-off ones read "Available" — turn any on and it gets installed too. */-export const Installing: Story = {- args: { installing: true, repository: 'acme-co/web', codebase: CONNECTED_CODEBASE },- // The install-in-progress spinner is the point of this story — it never resolves, so skip- // the test runner's default "wait for loaders to hide" check.- parameters: { testOptions: { waitForLoadersToDisappear: false } },-}--/** GitHub not connected — the codebase-access card offers a "Connect GitHub" button to activate it as a- * source, independent of the SDK install. */-export const CodebaseNotConnected: Story = {- args: { installing: false, repository: null, codebase: { connected: false, displayName: null, connectUrl: '#' } },-}diff --git a/frontend/src/scenes/onboarding/self-driving/components/PlanCard.tsx b/frontend/src/scenes/onboarding/self-driving/components/PlanCard.tsxnew file mode 100644index 000000000000..c297fa05c042--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/components/PlanCard.tsx@@ -0,0 +1,45 @@+import { type ReactNode } from 'react'++import { LemonCard } from 'lib/lemon-ui/LemonCard'+import { cn } from 'lib/utils/css-classes'++/**+ * One plan option: header (name + price), body, footnote, and a bottom-pinned CTA. The two plan+ * cards differ only in this data plus whether they carry the accent border, so the shape lives here+ * and the call sites read as content.+ */+export function PlanCard({+ title,+ titleCaption,+ priceLabel,+ highlighted = false,+ footnote,+ cta,+ children,+}: {+ title: string+ /** Small line under the title (e.g. "Free allowance included"). */+ titleCaption?: string+ /** Right-aligned price text in the header. */+ priceLabel?: string | null+ /** Accent border, for the plan we want the eye on. */+ highlighted?: boolean+ footnote?: string+ cta: ReactNode+ children: ReactNode+}): JSX.Element {+ return (+ <LemonCard hoverEffect={false} focused={highlighted} className={cn('flex flex-1 basis-72 flex-col gap-3 p-4')}>+ <div className="flex items-baseline justify-between gap-2">+ <div>+ <p className="m-0 text-base font-semibold">{title}</p>+ {titleCaption && <p className="m-0 text-xs text-muted">{titleCaption}</p>}+ </div>+ {priceLabel && <p className="m-0 text-sm text-muted">{priceLabel}</p>}+ </div>+ {children}+ {footnote && <p className="m-0 text-xs text-muted">{footnote}</p>}+ <div className="mt-auto">{cta}</div>+ </LemonCard>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/components/PlanChoice.tsx b/frontend/src/scenes/onboarding/self-driving/components/PlanChoice.tsxnew file mode 100644index 000000000000..163d5a1f7bea--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/components/PlanChoice.tsx@@ -0,0 +1,126 @@+import { useActions, useValues } from 'kea'++import { LemonButton } from '@posthog/lemon-ui'++import { BillingUpgradeCTA } from 'lib/components/BillingUpgradeCTA'+import { pluralize } from 'lib/utils/strings'+import { freePrs, pricePerPrUsd } from 'scenes/billing/inboxPricing'+import { paymentEntryLogic } from 'scenes/billing/paymentEntryLogic'+import { onboardingEventUsageLogic } from 'scenes/onboarding/onboardingEventUsageLogic'+import { PlanCard } from 'scenes/onboarding/self-driving/components/PlanCard'+import { SelfDrivingPricing } from 'scenes/onboarding/self-driving/components/SelfDrivingPricing'+import { ToolFreeTiers } from 'scenes/onboarding/self-driving/components/ToolFreeTiers'+import { formatUsd } from 'scenes/onboarding/self-driving/utils'+import { CheckList } from 'scenes/onboarding/shared/components/CheckList'++import { type BillingProductV2Type } from '~/types'++/** The free vs pay-as-you-go pick, under the pricing headline. */+export function PlanChoice({+ platformProduct,+ inboxProduct,+ products,+ onContinue,+ completing,+}: {+ platformProduct: BillingProductV2Type | null+ inboxProduct: BillingProductV2Type | null+ products: BillingProductV2Type[] | undefined+ onContinue: () => void+ /** The free pick finishes onboarding, which writes to the team before navigating. */+ completing: boolean+}): JSX.Element {+ const { startPaymentEntryFlow } = useActions(paymentEntryLogic)+ const { reportSelfDrivingOnboardingPlanSelected } = useActions(onboardingEventUsageLogic)+ // Guard the subscribe button against double-submit: `isLoading` covers the returning-customer+ // activate call, `paymentEntryModalOpen` covers a new customer once the Stripe modal is up.+ const { isLoading, paymentEntryModalOpen } = useValues(paymentEntryLogic)+ const subscribing = isLoading || paymentEntryModalOpen++ const included = freePrs(inboxProduct)+ const perPrUsd = pricePerPrUsd(inboxProduct)++ // Reported at the pick, not at payment completion — whether payment then resolves is billing's+ // own funnel (GROW-89).+ const subscribe = (): void => {+ reportSelfDrivingOnboardingPlanSelected('pay_as_you_go')+ // Returning the user to the same URL keeps them in the onboarding flow once payment resolves.+ startPaymentEntryFlow(platformProduct, window.location.pathname + window.location.search)+ }+ const continueFree = (): void => {+ reportSelfDrivingOnboardingPlanSelected('free')+ onContinue()+ }++ return (+ <div className="flex flex-wrap gap-3">+ <SelfDrivingPricing product={inboxProduct} />++ <PlanCard+ title="Free"+ priceLabel="$0 / month"+ footnote="Agents pause shipping once the free pull requests are used up, instead of charging you."+ cta={+ <LemonButton+ type="secondary"+ fullWidth+ center+ onClick={continueFree}+ loading={completing}+ data-attr="self-driving-onboarding-free"+ >+ Start free+ </LemonButton>+ }+ >+ <CheckList+ items={[+ {+ content:+ included > 0 ? (+ <>+ <strong>{pluralize(included, 'pull request', undefined)}</strong> a month,+ shipped and reviewed+ </>+ ) : (+ 'A monthly allowance of shipped pull requests'+ ),+ },+ { content: 'No payment method needed' },+ ]}+ />+ </PlanCard>++ <PlanCard+ title="Pay-as-you-go"+ titleCaption="Free allowance included"+ priceLabel={perPrUsd !== null ? `${formatUsd(perPrUsd)} per shipped PR` : null}+ highlighted+ cta={+ <BillingUpgradeCTA+ type="primary"+ status="alt"+ fullWidth+ center+ loading={subscribing}+ disabledReason={subscribing ? 'Opening payment…' : undefined}+ disableClientSideRouting+ onClick={subscribe}+ data-attr="self-driving-onboarding-subscribe"+ >+ Add payment method+ </BillingUpgradeCTA>+ }+ >+ <CheckList+ items={[+ { content: 'Agents keep shipping past the free allowance' },+ { content: 'Set a spend limit whenever you want' },+ ]}+ />+ </PlanCard>++ <ToolFreeTiers products={products} />+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingInstallOptions.tsx b/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingInstallOptions.tsxnew file mode 100644index 000000000000..68ad8a5215e3--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingInstallOptions.tsx@@ -0,0 +1,70 @@+import { useActions } from 'kea'++import { IconCheckCircle } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { onboardingEventUsageLogic } from 'scenes/onboarding/onboardingEventUsageLogic'+import { CheckList } from 'scenes/onboarding/shared/components/CheckList'+import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'+import { WizardCommandBlock } from 'scenes/onboarding/shared/wizard-sync/WizardCommandBlock'+import { WizardInstallOptions } from 'scenes/onboarding/shared/wizard-sync/WizardInstallOptions'++/** What the self-driving run wires up, so the command isn't a leap of faith. */+const WIZARD_SETS_UP = [+ 'Connects your GitHub, so agents can open pull requests',+ 'Picks the signal sources and scouts worth watching',+ 'Sends findings to your inbox as they land',+]++// The self-driving run is interactive: it asks about your issue tracker, walks you through the+// GitHub App install, and proposes scouts. The cloud runner can't do any of that (it runs headless+// and the CLI rejects `--ci` for this program), so the cloud arm is forced off here rather than+// being left to the experiment flag.+export function SelfDrivingInstallOptions({ onContinue }: { onContinue: () => void }): JSX.Element {+ const { isCloudOrDev } = useWizardCommand()+ const { reportSelfDrivingOnboardingInstallModeSelected } = useActions(onboardingEventUsageLogic)++ // Self-hosted: the wizard CLI only targets cloud + dev, so the command block renders nothing.+ // Show a real, actionable fallback instead of an empty step.+ if (!isCloudOrDev) {+ return (+ <div className="flex flex-col gap-3">+ <p className="text-sm text-muted m-0">+ Install the PostHog SDK for your framework and your product's context starts flowing in, ready for+ agents to act on.+ </p>+ <LemonButton type="primary" to="https://posthog.com/docs/getting-started/install" targetBlank>+ Read the install docs+ </LemonButton>+ </div>+ )+ }++ return (+ <div className="flex flex-col gap-4">+ <p className="text-sm text-muted text-center m-0">+ Run this in your project. It sets everything up and hands back an inbox that's already working.+ </p>+ <WizardInstallOptions+ hideHog+ offerCloudRun={false}+ onQueued={onContinue}+ onModeSelected={reportSelfDrivingOnboardingInstallModeSelected}+ localBlock={+ <WizardCommandBlock+ hideHog+ subcommand="self-driving"+ description="Takes about ten minutes. It'll ask you a few things along the way."+ />+ }+ />+ <CheckList+ size="xs"+ items={WIZARD_SETS_UP.map((line) => ({+ icon: <IconCheckCircle />,+ content: <span className="text-muted">{line}</span>,+ }))}+ />+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingPricing.tsx b/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingPricing.tsxnew file mode 100644index 000000000000..f459b8703643--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingPricing.tsx@@ -0,0 +1,40 @@+import { pluralize } from 'lib/utils/strings'+import { freePrs, pricePerPrUsd } from 'scenes/billing/inboxPricing'+import { StatFigure } from 'scenes/onboarding/self-driving/components/StatFigure'+import { formatUsd } from 'scenes/onboarding/self-driving/utils'++import { type BillingProductV2Type } from '~/types'++/**+ * The headline: what self-driving costs, before the plans that differ only in what happens after+ * the free PRs run out.+ *+ * The numbers are optional on purpose. Billing may not carry the inbox product (an instance without+ * it in its plans config, or a request that came back thin), and the pricing model is still the+ * point of this screen, so the copy stands on its own and only the figures drop out.+ */+export function SelfDrivingPricing({ product }: { product: BillingProductV2Type | null }): JSX.Element {+ const included = freePrs(product)+ const perPr = pricePerPrUsd(product)++ return (+ <div className="w-full flex flex-col gap-3 p-4 rounded-lg border border-accent bg-accent-highlight">+ <p className="m-0 text-sm font-semibold">You pay for shipped work, nothing else</p>+ {(included > 0 || perPr !== null) && (+ <div className="flex flex-wrap items-start gap-x-10 gap-y-3">+ {included > 0 && (+ <StatFigure+ value={included}+ label={`${pluralize(included, 'pull request', undefined, false)} a month, free`}+ />+ )}+ {perPr !== null && <StatFigure value={formatUsd(perPr)} label="per pull request after that" />}+ </div>+ )}+ <p className="m-0 text-xs text-muted">+ Scouts, signals, and reports never cost anything. You're charged only when an agent ships a pull request+ you can review.+ </p>+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/components/StatFigure.tsx b/frontend/src/scenes/onboarding/self-driving/components/StatFigure.tsxnew file mode 100644index 000000000000..c63adce4d0fd--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/components/StatFigure.tsx@@ -0,0 +1,9 @@+/** A big figure with a small caption — the pricing headline's number pairs. */+export function StatFigure({ value, label }: { value: string | number; label: string }): JSX.Element {+ return (+ <div>+ <p className="m-0 text-2xl font-bold leading-tight">{value}</p>+ <p className="m-0 text-xs text-muted">{label}</p>+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/components/SubscribedState.tsx b/frontend/src/scenes/onboarding/self-driving/components/SubscribedState.tsxnew file mode 100644index 000000000000..e07aa83ce9f0--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/components/SubscribedState.tsx@@ -0,0 +1,25 @@+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'++/** The billing step's short-circuit for a team that already subscribed: confirm and move on. */+export function SubscribedState({+ onContinue,+ completing,+}: {+ onContinue: () => void+ completing: boolean+}): JSX.Element {+ return (+ <div className="flex flex-col gap-3">+ <LemonBanner type="success">+ <p className="m-0 text-sm font-semibold">You're on pay-as-you-go</p>+ <p className="m-0 text-xs font-normal">+ Agents keep watching and reporting for free. You only pay when one ships a PR.+ </p>+ </LemonBanner>+ <p className="text-xs text-muted m-0">Change or cancel any time from billing settings.</p>+ <LemonButton type="primary" status="alt" onClick={onContinue} loading={completing} className="self-end">+ Go to your inbox+ </LemonButton>+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/components/ToolFreeTiers.tsx b/frontend/src/scenes/onboarding/self-driving/components/ToolFreeTiers.tsxnew file mode 100644index 000000000000..99ee64d27127--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/components/ToolFreeTiers.tsx@@ -0,0 +1,43 @@+import { pluralize } from 'lib/utils/strings'+import { compact } from 'scenes/onboarding/self-driving/utils'+import { CheckList } from 'scenes/onboarding/shared/components/CheckList'+import { availableOnboardingProducts } from 'scenes/onboarding/shared/utils'++import { type BillingProductV2Type } from '~/types'++/**+ * Monthly free allowance on the tools the wizard turns on, so the plan reads as the whole platform+ * rather than PRs alone. It sits under both plans because subscribing changes nothing about it:+ * every tool keeps the same free tier either way.+ */+export function ToolFreeTiers({ products }: { products: BillingProductV2Type[] | undefined }): JSX.Element | null {+ const allowances = (products ?? [])+ .filter((product) => product.type in availableOnboardingProducts)+ .map((product) => {+ const freePlan = product.plans.find((plan) => plan.plan_key?.startsWith('free'))+ return { name: product.name, unit: freePlan?.unit ?? '', value: freePlan?.free_allocation ?? 0 }+ })+ .filter((allowance) => allowance.unit && allowance.value > 0)++ if (allowances.length === 0) {+ return null+ }++ return (+ <div className="w-full flex flex-col gap-2">+ <p className="m-0 text-xs text-muted">Every other tool keeps its free tier on both plans:</p>+ <CheckList+ size="xs"+ className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-1"+ items={allowances.map(({ name, unit, value }) => ({+ content: (+ <span className="text-muted">+ <strong className="font-semibold text-default">{name}</strong>: {compact(value)}{' '}+ {pluralize(value, unit, undefined, false)} a month+ </span>+ ),+ }))}+ />+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/steps/BillingStep.tsx b/frontend/src/scenes/onboarding/self-driving/steps/BillingStep.tsxnew file mode 100644index 000000000000..45c6cdda9af8--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/steps/BillingStep.tsx@@ -0,0 +1,75 @@+import { useValues } from 'kea'++import { LemonButton, Spinner } from '@posthog/lemon-ui'++import { billingLogic } from 'scenes/billing/billingLogic'+import { findInboxProduct } from 'scenes/billing/inboxPricing'+import { PlanChoice } from 'scenes/onboarding/self-driving/components/PlanChoice'+import { SubscribedState } from 'scenes/onboarding/self-driving/components/SubscribedState'++import { ProductKey } from '~/queries/schema/schema-general'++/**+ * Billing step for the self-driving onboarding, and the last screen before the inbox.+ *+ * The thing being sold here is shipped work: agents watch and report for free, and a PR that lands+ * is what costs money. Every number comes off the billing product (`inbox`) rather than being+ * written down here, so a pricing change lands without a frontend deploy.+ *+ * No flow navigation lives here; the parent shell owns Back/Continue. The only action this step+ * fires is the payment-entry flow, which opens the globally mounted PaymentEntryModal (see+ * layout/GlobalModals) over the card and returns to the same URL.+ */+export function BillingStep({ onContinue, completing }: { onContinue: () => void; completing: boolean }): JSX.Element {+ const { billing, billingLoading } = useValues(billingLogic)++ if (!billing && billingLoading) {+ return (+ <div className="flex items-center justify-center py-12">+ <Spinner className="text-2xl text-muted size-8" />+ </div>+ )+ }++ // Either billing isn't set up on this instance (self-hosted without a license, or local dev) or+ // the request failed. We can't tell them apart from here, and neither is worth blocking setup+ // over, so say what we know and keep the flow moving.+ if (!billing) {+ return (+ <div className="flex flex-col gap-3">+ <p className="text-sm text-muted m-0">+ We couldn't load billing just now. Nothing is blocked. Your agents are set up, and you can pick a+ plan later from billing settings.+ </p>+ <div className="flex items-center justify-between gap-2">+ <LemonButton type="secondary" to="https://posthog.com/pricing" targetBlank>+ See pricing+ </LemonButton>+ <LemonButton type="primary" status="alt" onClick={onContinue} loading={completing}>+ Go to your inbox+ </LemonButton>+ </div>+ </div>+ )+ }++ if (billing.has_active_subscription) {+ return <SubscribedState onContinue={onContinue} completing={completing} />+ }++ // Subscribing still activates the whole catalog (billing expands `all_products:` server-side),+ // so the platform product stays the thing we hand the payment flow. The inbox product is what+ // this screen actually talks about, and where its numbers come from.+ const platformProduct =+ billing.products?.find((product) => product.type === ProductKey.PLATFORM_AND_SUPPORT) ?? null++ return (+ <PlanChoice+ platformProduct={platformProduct}+ inboxProduct={findInboxProduct(billing.products)}+ products={billing.products}+ onContinue={onContinue}+ completing={completing}+ />+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/steps/InstallStep.tsx b/frontend/src/scenes/onboarding/self-driving/steps/InstallStep.tsxnew file mode 100644index 000000000000..74236adcb017--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/steps/InstallStep.tsx@@ -0,0 +1,24 @@+import { useLocalWizardRunActive } from 'scenes/onboarding/shared/wizard-sync/hooks'+import { InstallationProgressView } from 'scenes/onboarding/shared/wizard-sync/InstallationProgressView'+import { SELF_DRIVING_WORKFLOW_ID } from 'scenes/onboarding/shared/wizard-sync/workflows'++import { SelfDrivingInstallOptions } from '../components/SelfDrivingInstallOptions'++/**+ * The step swaps to the live tracker as soon as the CLI registers a run. Sync is unconditional here+ * (no `ONBOARDING_WIZARD_SYNC` gate): without it this step is a static command with no feedback, and+ * watching the run is the whole point of the flow. There is no cloud run to coordinate with, so the+ * local session stream is the only source.+ */+export function InstallStep({ onContinue }: { onContinue: () => void }): JSX.Element {+ const isLocalRunActive = useLocalWizardRunActive(SELF_DRIVING_WORKFLOW_ID)+ return isLocalRunActive ? (+ <InstallationProgressView+ mode="local"+ workflowId={SELF_DRIVING_WORKFLOW_ID}+ continueHint="Keep answering the wizard in your terminal. Progress shows up here as it goes, so you can carry on with the rest of onboarding whenever you like."+ />+ ) : (+ <SelfDrivingInstallOptions onContinue={onContinue} />+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/steps/WelcomeStep.tsx b/frontend/src/scenes/onboarding/self-driving/steps/WelcomeStep.tsxnew file mode 100644index 000000000000..baca838e5957--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/steps/WelcomeStep.tsx@@ -0,0 +1,17 @@+import selfDrivingHog from 'public/hedgehog/self-driving-hog.png'++/** The opener: what self-driving is, before we ask anyone to paste a command. */+export function WelcomeStep(): JSX.Element {+ return (+ <div className="flex flex-col items-center text-center gap-5">+ <img src={selfDrivingHog} alt="A hedgehog riding in a self-driving car" className="w-full rounded-lg" />+ <div className="flex flex-col gap-2">+ <h1 className="text-2xl font-bold m-0">Let's make your product self-driving</h1>+ <p className="text-muted max-w-md mx-auto m-0">+ PostHog runs on your product's context. One command gets it flowing, then agents can start finding+ and fixing things, with you steering.+ </p>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/utils.ts b/frontend/src/scenes/onboarding/self-driving/utils.tsnew file mode 100644index 000000000000..c0075be1b7e9--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/utils.ts@@ -0,0 +1,4 @@+export const formatUsd = (usd: number): string => (Number.isInteger(usd) ? `$${usd}` : `$${usd.toFixed(2)}`)++export const compact = (value: number): string =>+ Intl.NumberFormat('en', { notation: 'compact', compactDisplay: 'short', maximumFractionDigits: 1 }).format(value)diff --git a/frontend/src/scenes/onboarding/shared/components/CheckList.tsx b/frontend/src/scenes/onboarding/shared/components/CheckList.tsxnew file mode 100644index 000000000000..e8f52f374aa7--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/components/CheckList.tsx@@ -0,0 +1,45 @@+import { type ReactNode } from 'react'++import { IconCheck } from '@posthog/icons'++import { cn } from 'lib/utils/css-classes'++export interface CheckListItem {+ /** Defaults to a green check; pass any icon to override per row. */+ icon?: ReactNode+ content: ReactNode+}++/**+ * A vertical list of icon-led rows — the feature/benefit lists on the plan cards, the install step,+ * and the handoff checklist. Call sites supply data; the row scaffolding lives here once.+ */+export function CheckList({+ items,+ size = 'sm',+ className,+}: {+ items: CheckListItem[]+ /** Row text size; icons scale with it. */+ size?: 'xs' | 'sm'+ className?: string+}): JSX.Element {+ return (+ <ul className={cn('flex flex-col gap-1.5 m-0 p-0 list-none', className)}>+ {items.map((item, i) => (+ <li key={i} className="flex items-start gap-2">+ <span+ className={cn(+ 'shrink-0 text-success',+ size === 'xs' ? '[&_svg]:size-3.5' : '[&_svg]:size-4',+ 'mt-0.5'+ )}+ >+ {item.icon ?? <IconCheck />}+ </span>+ <span className={size === 'xs' ? 'text-xs' : 'text-sm'}>{item.content}</span>+ </li>+ ))}+ </ul>+ )+}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressContent.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressContent.tsxnew file mode 100644index 000000000000..e2ead28c831c--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressContent.tsx@@ -0,0 +1,271 @@+import { type ReactNode } from 'react'++import * as wizardPng from '@posthog/brand/hoggies/png/wizard-1'+import { IconDashboard, IconPullRequest, IconRocket, IconSearch, IconTerminal, IconX } from '@posthog/icons'+import { LemonBanner, LemonButton, Spinner } from '@posthog/lemon-ui'++import { pngHoggie } from 'lib/brand/hoggies'+import { cn } from 'lib/utils/css-classes'+import { urls } from 'scenes/urls'++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 { DetectedDashboard } from './wizardDashboardLogic'+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,+ progress,+ mode,+ dashboard,+ onDashboardClick,+ onDismiss,+ onRetryLocally,+}: {+ 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+ /** Dashboard the wizard built, when detected — surfaced as the completed state's payoff. */+ dashboard?: DetectedDashboard | null+ /** Telemetry hook for the dashboard CTA — navigation itself rides the button's `to`. */+ onDashboardClick?: () => 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+}): JSX.Element {+ const { phase, steps, error, prUrl, prMerged } = progress++ // 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' && (+ // The cloud run failed — offer self-serve recovery so the user isn't stuck: run the wizard+ // themselves (switches the install step to the local command) or follow the manual docs.+ <div className="flex flex-wrap gap-2">+ {onRetryLocally && (+ <LemonButton type="primary" onClick={onRetryLocally} icon={<IconTerminal />}>+ Run it yourself+ </LemonButton>+ )}+ <LemonButton+ type={onRetryLocally ? 'secondary' : 'primary'}+ to="https://posthog.com/docs/getting-started/install"+ 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' && dashboard && (+ <div className="flex flex-col gap-2">+ <p className="text-sm text-muted m-0">+ The wizard also set up a dashboard for you. It fills up as soon as your events arrive. Feel free+ to look around.+ </p>+ <LemonButton+ type={prUrl ? 'secondary' : 'primary'}+ to={urls.dashboard(dashboard.id)}+ icon={<IconDashboard />}+ center+ tooltip={dashboard.name ?? undefined}+ onClick={onDashboardClick}+ >+ Preview your dashboard+ </LemonButton>+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.stories.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.stories.tsxindex 749263a7afa5..ebf9bf3e2c86 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.stories.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.stories.tsx@@ -1,7 +1,7 @@import { Meta, StoryObj } from '@storybook/react'+import { InstallationProgressContent } from './InstallationProgressContent'import { InstallationProgress, InstallationStepStatus } from './installationProgressLogic'-import { InstallationProgressContent } from './InstallationProgressView'/*** Every state of the Installation layer's progress view, driven by fixtures (the component is pure, sodiff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.tsxindex fa8c5d01d713..a868ff4e4124 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.tsx@@ -1,374 +1,25 @@import { useActions, useValues } from 'kea'-import { useEffect, useRef } from 'react'--import * as wizardPng from '@posthog/brand/hoggies/png/wizard-1'-import {- IconCheckCircle,- IconDashboard,- IconPullRequest,- IconRocket,- IconSearch,- IconTerminal,- IconX,-} from '@posthog/icons'-import { LemonButton, Spinner } from '@posthog/lemon-ui'--import { pngHoggie } from 'lib/brand/hoggies'-import { useHogfetti } from 'lib/components/Hogfetti/Hogfetti'-import { cn } from 'lib/utils/css-classes'-import { inStorybookTestRunner } from 'lib/utils/dom'-import { urls } from 'scenes/urls'+import { type ReactNode, useEffect } from 'react'import { onboardingEventUsageLogic } from '../../onboardingEventUsageLogic'-import { activeCloudRunLogic } from './activeCloudRunLogic'import { finishedLocalRunLogic } from './finishedLocalRunLogic'-import { prNameLabel } from './helpers'-import {- InstallationMode,- InstallationProgress,- installationProgressLogic,- InstallationStepStatus,-} from './installationProgressLogic'-import { DetectedDashboard, wizardDashboardLogic } from './wizardDashboardLogic'--const HedgehogWizard = pngHoggie(wizardPng)--// Timeline dot for a single step.-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" />-}--// 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.-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'],-}--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.',-}--/**- * Presentational renderer for an `InstallationProgress`: a text header, a connected step timeline, and- * the terminal payoff (PR link) or failure detail. Pure (no logic/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({- progress,- mode,- dashboard,- onDashboardClick,- onDismiss,- onRetryLocally,-}: {- progress: InstallationProgress- /** Tailors the connecting state (copy + upcoming-step preview) to where the run happens. */- mode?: InstallationMode- /** Dashboard the wizard built, when detected — surfaced as the completed state's payoff. */- dashboard?: DetectedDashboard | null- /** Telemetry hook for the dashboard CTA — navigation itself rides the button's `to`. */- onDashboardClick?: () => 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-}): JSX.Element {- const { phase, steps, error, prUrl, prMerged } = progress-- // 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. Gated on the- // false -> true transition so mounting an already-merged run (reloads, storybook snapshots)- // stays quiet; the test-runner guard keeps hogfetti out of visual regression captures.- const { trigger: triggerHogfetti, HogfettiComponent } = useHogfetti()- // Only a live false -> true transition celebrates. Start 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. One-shot per mount on top.- 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 (inStorybookTestRunner() || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {- return- }- mergeCelebratedRef.current = true- triggerHogfetti()- }, [prMerged, triggerHogfetti])-- const headline =- phase === 'completed'- ? 'PostHog is wired up'- : phase === 'error'- ? (error?.title ?? "Setup didn't finish")- : prReady- ? prMerged- ? 'Pull request merged'- : 'Pull request ready'- : 'Setting up PostHog'- const subtitle =- phase === 'completed'- ? prUrl- ? 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.'- : mode === 'local'- ? 'The wizard finished its work on your machine.'- : "You're all set."- : phase === 'error'- ? "We couldn't finish the setup."- : prReady- ? prMerged- ? 'Deploy the changes and data starts flowing. The run will wrap up on its own.'- : "Review it whenever you like; we'll keep CI green in the meantime."- : phase === 'connecting'- ? ((mode && CONNECTING_SUBTITLE[mode]) ?? 'Getting things ready…')- : phase === 'idle'- ? 'Not hearing back from this run right now. You can dismiss it and start over.'- : 'Working on it. Feel free to keep going.'-- // 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- const upcomingSteps = phase === 'connecting' && steps.length === 0 && mode ? 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"- >- <HogfettiComponent />- <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 ? (- <ol className="flex flex-col m-0 p-0 list-none">- {steps.map((step, i) => (- // One flat rail for pipeline and wizard-reported steps alike.- <li key={step.id} className="flex gap-3">- <div className="flex flex-col items-center pt-0.5">- <StepIcon- status={step.status}- prState={- step.id.endsWith(':pr') && prUrl ? (prMerged ? 'merged' : 'open') : undefined- }- />- {i < steps.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">- <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>- {step.detail && (- <div className="text-xs text-muted truncate ph-no-capture">{step.detail}</div>- )}- </div>- </li>- ))}- </ol>- ) : (- upcomingSteps && (- <ol className="flex flex-col m-0 p-0 list-none" aria-label="Upcoming setup steps">- {upcomingSteps.map((label, i) => (- <li key={label} className="flex gap-3">- <div className="flex flex-col items-center pt-0.5">- <StepIcon status="pending" />- {i < upcomingSteps.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 text-sm text-muted">{label}</div>- </li>- ))}- </ol>- )- )}-- {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>- <ul className="flex flex-col gap-1.5 m-0 p-0 list-none text-sm">- <li className="flex items-start gap-2">- <IconSearch className="text-muted text-base mt-0.5 shrink-0" />- <span>- <strong>Review the changes</strong> in your editor before you commit.- </span>- </li>- <li className="flex items-start gap-2">- <IconTerminal className="text-muted text-base mt-0.5 shrink-0" />- <span>- <strong>Try it locally</strong> and your events show up here right away.- </span>- </li>- <li className="flex items-start gap-2">- <IconRocket className="text-muted text-base mt-0.5 shrink-0" />- <span>- <strong>Commit and deploy</strong> to get data from real users.- </span>- </li>- </ul>- </div>- )}-- {phase === 'error' && error?.detail && (- <div className="text-sm text-danger bg-danger-highlight rounded p-2">{error.detail}</div>- )}-- {phase === 'error' && (- // The cloud run failed — offer self-serve recovery so the user isn't stuck: run the wizard- // themselves (switches the install step to the local command) or follow the manual docs.- <div className="flex flex-wrap gap-2">- {onRetryLocally && (- <LemonButton type="primary" onClick={onRetryLocally} icon={<IconTerminal />}>- Run it yourself- </LemonButton>- )}- <LemonButton- type={onRetryLocally ? 'secondary' : 'primary'}- to="https://posthog.com/docs/getting-started/install"- 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' && (- <div className="flex items-center gap-3 rounded-lg border border-[var(--color-purple-500)] p-3">- <span className="flex items-center justify-center rounded w-8 h-8 shrink-0 bg-[var(--color-purple-500)] text-white">- <IconPullRequest className="text-lg" />- </span>- <div className="flex-1 min-w-0">- <div className="text-sm font-semibold">Pull request successfully merged</div>- <div className="text-xs text-muted">- You're all set. Deploy the changes and your events start flowing.- </div>- </div>- {/* ph-no-capture: the href is the customer's PR url. */}- <LemonButton- type="secondary"- size="small"- to={prUrl}- targetBlank- className="ph-no-capture shrink-0"- >- View PR- </LemonButton>- </div>- )}-- {phase === 'completed' && dashboard && (- <div className="flex flex-col gap-2">- <p className="text-sm text-muted m-0">- The wizard also set up a dashboard for you. It fills up as soon as your events arrive. Feel free- to look around.- </p>- <LemonButton- type={prUrl ? 'secondary' : 'primary'}- to={urls.dashboard(dashboard.id)}- icon={<IconDashboard />}- center- tooltip={dashboard.name ?? undefined}- onClick={onDashboardClick}- >- Preview your dashboard- </LemonButton>- </div>- )}- </div>- )-}+import { InstallationProgressContent } from './InstallationProgressContent'+import { installationProgressLogic } from './installationProgressLogic'+import { wizardDashboardLogic } from './wizardDashboardLogic'+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- * `panelMounted` to hide the floating FAB) or inside the FAB itself (`floating`).+ * the inline-panel claim to hide the detached widget) or inside the FAB itself (`floating`).*/export function InstallationProgressView({mode,runId,taskId,+ workflowId,+ continueHint,floating = false,onDismiss,onRetryLocally,@@ -377,14 +28,20 @@ export function InstallationProgressView({/** The TaskRun handle — required for cloud runs, absent for local ones. */runId?: stringtaskId?: 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/** Rendered in the floating FAB rather than inline on the install step. */floating?: booleanonDismiss?: () => void/** Forwarded to the failed-run fallback (see InstallationProgressContent). */onRetryLocally?: () => void}): JSX.Element {- const { installationProgress, latestSession } = useValues(installationProgressLogic({ mode, runId, taskId }))- const { setPanelMounted } = useActions(activeCloudRunLogic)+ const { installationProgress, latestSession } = useValues(+ installationProgressLogic({ mode, runId, taskId, workflowId })+ )+ const { claimInlinePanel, releaseInlinePanel } = useActions(wizardSyncUiLogic)const { detectedDashboard } = useValues(wizardDashboardLogic)const { dismissLocalRun } = useActions(finishedLocalRunLogic)const { reportWizardSyncHandoffShown, reportWizardSyncDashboardCtaShown, reportWizardSyncDashboardCtaClicked } =@@ -395,9 +52,9 @@ export function InstallationProgressView({if (floating) {return}- setPanelMounted(true)- return () => setPanelMounted(false)- }, [floating, setPanelMounted])+ claimInlinePanel(mode)+ return () => releaseInlinePanel(mode)+ }, [floating, mode, claimInlinePanel, releaseInlinePanel])const runKey = mode === 'cloud' ? runId : latestSession?.session_idconst completed = installationProgress.phase === 'completed'@@ -426,6 +83,8 @@ export function InstallationProgressView({return (<InstallationProgressContent+ workflowId={workflowId}+ continueHint={continueHint}progress={installationProgress}mode={mode}dashboard={dashboard}@@ -437,14 +96,3 @@ export function InstallationProgressView({/>)}--/**- * 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(): boolean {- const { installationProgress } = useValues(installationProgressLogic({ mode: 'local' }))- return installationProgress.isCurrent-}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/PipStrip.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/PipStrip.tsxnew file mode 100644index 000000000000..de4ec3addda3--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/PipStrip.tsx@@ -0,0 +1,24 @@+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.tsxnew file mode 100644index 000000000000..57d2f8a06dc8--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/StatusGlyph.tsx@@ -0,0 +1,22 @@+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.tsxnew file mode 100644index 000000000000..716caf482e10--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/StepIcon.tsx@@ -0,0 +1,31 @@+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.tsxnew file mode 100644index 000000000000..055bb1cdbfb5--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/Timeline.tsx@@ -0,0 +1,33 @@+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.tsxindex 2b6043bf977d..34a71097b093 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsx@@ -2,28 +2,31 @@ import { Meta, StoryObj } from '@storybook/react'import { waitFor } from '@testing-library/dom'import userEvent from '@testing-library/user-event'import { useMountedLogic } from 'kea'-import { router } from 'kea-router'import { FEATURE_FLAGS } from 'lib/constants'import { useDelayedOnMountEffect, useOnMountEffect } from 'lib/hooks/useOnMountEffect'-import { App } from 'scenes/App'-import { urls } from 'scenes/urls'import { mswDecorator, useStorybookMocks } from '~/mocks/browser'import { billingJson } from '~/mocks/fixtures/_billing'import preflightJson from '~/mocks/fixtures/_preflight.json'import { IntegrationType } from '~/types'-import { onboardingLogic } from '../../legacy/onboardingLogic'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 on the context-first onboarding install step.- * Rendered through the full `<App />` scene: the welcome step shows first, then a play function clicks- * "Get started" to land on the install step where the cloud-run block lives (it connects to- * onboardingLogic, so the scene is its natural habitat).+ * 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 legacy install step — the self-driving flow forces the cloud+ * arm off, because its run is interactive and the cloud runner is headless. `Legacy/Install Step`+ * already snapshots the block in that setting, so driving a scene from here would duplicate those+ * snapshots (and, if it drove the self-driving flow, snapshot a step where the block cannot appear).+ * 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).@@ -85,12 +88,13 @@ const meta: Meta = {layout: 'fullscreen',viewMode: 'story',mockDate: '2023-05-25',+ // Legacy flow, deliberately: the self-driving install step forces the cloud arm off (its run+ // is interactive and the cloud runner is headless), so the block only renders here.featureFlags: {[FEATURE_FLAGS.ONBOARDING_WIZARD_CLOUD_RUN]: 'test',- [FEATURE_FLAGS.ONBOARDING_FLOW_VARIANT]: 'self-driving',},- // These stories render the full app shell around a wizard step that's mid-flight by design- // (connecting/polling/queued) — skip the test runner's default "wait for loaders to hide" check.+ // 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: [@@ -117,28 +121,19 @@ export default metatype Story = StoryObj-// The scene mounts asynchronously after navigation (and only 500ms after mount does the delayed-// effect even start it), so play-function waits need a load-tolerant budget: on a busy CI shard-// the install step can take well past the global 15s default to render, and retries genuinely-// re-run play now — an under-budgeted wait fails all three attempts instead of flaking once.+// 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 }-// Click a footer/body button by its exact label, waiting for it to mount first.-async function clickButton(text: string): Promise<void> {- await waitFor(() => {- const btn = Array.from(document.querySelectorAll('button')).find((b) => b.textContent?.trim() === text)- if (!btn) {- throw new Error(`button "${text}" not ready`)- }- }, WAIT_OPTIONS)- const btn = Array.from(document.querySelectorAll('button')).find((b) => b.textContent?.trim() === text)- await userEvent.click(btn as Element)-}-/**- * Lands on the context-first install step with a given set of integrations, optionally driving- * wizardCloudRunLogic into a later state. The logic is mounted up front so `drive` can dispatch- * before the install-step block renders; the play then advances welcome → install.+ * 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 legacy install step+ * (the self-driving flow forces the cloud arm off — its run is interactive and the cloud runner is+ * headless), and `Legacy/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,@@ -153,7 +148,6 @@ function cloudRunStory({}): Story {return {render: () => {- useMountedLogic(onboardingLogic)useMountedLogic(wizardCloudRunLogic)useMountedLogic(activeCloudRunLogic)@@ -167,17 +161,17 @@ function cloudRunStory({// 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()- router.actions.push(urls.onboarding())drive?.()})- return <App />+ return (+ <div className="max-w-xl">+ <WizardCloudRunBlock />+ </div>+ )},parameters: { testOptions: { waitForSelector } },- play: async () => {- await clickButton('Get started')- await extraPlay?.()- },+ play: extraPlay ? async () => await extraPlay() : undefined,}}@@ -224,15 +218,9 @@ export const RepoPickerOpen: Story = cloudRunStory({},})-/**- * Run kicked off — non-blocking confirmation; the FAB takes over from here. Renders the block directly- * (not through the full click-through `<App />` flow the other stories use): the queued state only- * needs cloudRunStatus/selectedRepository seeded before mount, and going through "Get started" plus the- * install step's own async setup raced the delayed-mount effect that drives every other story here.- */+/** Run kicked off — non-blocking confirmation; the FAB takes over from here. */export const PullRequestQueued: Story = {render: () => {- useMountedLogic(onboardingLogic)useMountedLogic(wizardCloudRunLogic)useMountedLogic(activeCloudRunLogic)@@ -257,11 +245,33 @@ export const PullRequestQueued: Story = {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. */-export const RunItYourself: Story = cloudRunStory({- integrations: [],- waitForSelector: '[data-attr="wizard-command-block"]',- extraPlay: async () => {+/**+ * 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/environments/: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')@@ -269,7 +279,7 @@ export const RunItYourself: Story = cloudRunStory({}, WAIT_OPTIONS)await userEvent.click(document.querySelector('[data-attr="wizard-mode-local"]') as Element)},-})+}interface PlaygroundArgs {githubConnected: boolean@@ -280,11 +290,10 @@ interface PlaygroundArgs {/*** 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 scene and re-derives state from scratch — the logic reducers (selected repo,+ * 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(onboardingLogic)useMountedLogic(wizardCloudRunLogic)useMountedLogic(activeCloudRunLogic)@@ -298,7 +307,6 @@ function CloudRunPlayground({ githubConnected, repository, pullRequestQueued }:useDelayedOnMountEffect(() => {activeCloudRunLogic.actions.clearActiveCloudRun()- router.actions.push(urls.onboarding())if (repository) {wizardCloudRunLogic.actions.setSelectedRepository(repository)}@@ -307,7 +315,11 @@ function CloudRunPlayground({ githubConnected, repository, pullRequestQueued }:}})- return <App />+ 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. */@@ -330,7 +342,4 @@ export const Playground: StoryObj<PlaygroundArgs> = {},render: (args) => <CloudRunPlayground key={JSON.stringify(args)} {...args} />,parameters: { testOptions: { waitForSelector: '[data-attr="wizard-cloud-run-open-pr"]' } },- play: async () => {- await clickButton('Get started')- },}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCommandBlock.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCommandBlock.tsxindex 7234e670210b..6ac6968305e5 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCommandBlock.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCommandBlock.tsx@@ -1,12 +1,22 @@-import { useState } from 'react'+import { type ReactNode, useState } from 'react'import { CommandBlock } from 'lib/components/CommandBlock/CommandBlock'import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'import { WizardModeShell } from './WizardModeShell'-export function WizardCommandBlock({ hideHog = false }: { hideHog?: boolean } = {}): JSX.Element {- const { wizardCommand, isCloudOrDev } = useWizardCommand()+export function WizardCommandBlock({+ hideHog = false,+ subcommand,+ description,+}: {+ hideHog?: boolean+ /** Wizard subcommand to run, e.g. `self-driving`. Omit for the plain SDK install. */+ subcommand?: string+ /** Replaces the default "what this does" line when the subcommand does something else. */+ description?: ReactNode+} = {}): JSX.Element {+ const { wizardCommand, isCloudOrDev } = useWizardCommand(subcommand)const [castKey, setCastKey] = useState(0)// The `npx @posthog/wizard` CLI only targets cloud (US/EU) and dev instances —@@ -28,8 +38,12 @@ export function WizardCommandBlock({ hideHog = false }: { hideHog?: boolean } =onCopy={(key) => setCastKey(key)}/><p className="text-xs text-muted mb-0">- Auto-detects your framework, installs the SDK, and sets up event capture. Commit the changes and open a- PR when you're ready.+ {description ?? (+ <>+ Auto-detects your framework, installs the SDK, and sets up event capture. Commit the changes and+ open a PR when you're ready.+ </>+ )}</p></WizardModeShell>)diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardInstallOptions.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardInstallOptions.tsxindex cdaa82bc8142..7f163c4530b8 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardInstallOptions.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardInstallOptions.tsx@@ -22,6 +22,12 @@ export interface WizardInstallOptionsProps {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 self-driving flow runs a+ * program the cloud runner cannot execute (it rejects `--ci` and needs an interactive terminal),+ * so offering it there would queue a run that can never succeed.+ */+ offerCloudRun?: boolean}/**@@ -35,6 +41,7 @@ export function WizardInstallOptions({hideHog = false,onQueued,onModeSelected,+ offerCloudRun = true,}: WizardInstallOptionsProps): JSX.Element {const cloudRunEnabled = useFeatureFlag('ONBOARDING_WIZARD_CLOUD_RUN', 'test')const { isCloudOrDev } = useWizardCommand()@@ -42,7 +49,7 @@ export function WizardInstallOptions({const { clearActiveCloudRun } = useActions(activeCloudRunLogic)const [mode, setMode] = useState<WizardInstallMode>('cloud')- const offerCloud = cloudRunEnabled && isCloudOrDev+ 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).diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.tsxindex eff161e24fe5..c35d6e6c14c0 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.tsx@@ -1,15 +1,5 @@-import {- IconCheckCircle,- IconCloud,- IconDashboard,- IconExpand45,- IconLaptop,- IconPullRequest,- IconQuestion,- IconWarning,- IconX,-} from '@posthog/icons'-import { LemonButton, Spinner } from '@posthog/lemon-ui'+import { IconCloud, IconDashboard, IconExpand45, IconLaptop, IconPullRequest, IconX } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'import { cn } from 'lib/utils/css-classes'import { urls } from 'scenes/urls'@@ -19,39 +9,19 @@ import {elapsedLabel,formatElapsed,pendingQuestionLabel,- pipClass,prNameLabel,stepCounts,syncHeadline,toneTextClass,+ localModeLabel,} from './helpers'import { InstallationProgress } from './installationProgressLogic'+import { PipStrip } from './PipStrip'+import { StatusGlyph } from './StatusGlyph'import { DetectedDashboard } from './wizardDashboardLogic'export type WizardSyncMode = 'cloud' | 'local'-// Leading glyph for the prominent task line: it carries the run's tone (accent while working, green on-// success, red on failure). Shared with the launcher and dialog.-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 />-}--export function localModeLabel(startedByLabel?: string | null): string {- return startedByLabel ? `On ${startedByLabel}'s machine` : 'On your machine'-}-// 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 (@@ -139,11 +109,7 @@ export function WizardSyncCard({{total > 0 ? (<div className="flex items-center gap-2">- <div className="flex flex-1 items-center gap-1">- {progress.steps.map((step) => (- <span key={step.id} className={cn('h-1 flex-1 rounded-full', pipClass(step.status))} />- ))}- </div>+ <PipStrip steps={progress.steps} className="flex-1" /><span className="text-xs text-muted tabular-nums shrink-0">{completed}/{total}</span>diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncDialog.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncDialog.tsxnew file mode 100644index 000000000000..c2b2c75bff7c--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncDialog.tsx@@ -0,0 +1,85 @@+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 { DetectedDashboard } from './wizardDashboardLogic'+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,+ dashboard,+ isOpen,+ onClose,+ onClear,+ onCancel,+ cancelling = false,+ stale = false,+ startedByLabel,+ onDashboardClick,+}: {+ progress: InstallationProgress+ elapsedSeconds: number+ mode: WizardSyncMode+ dashboard?: DetectedDashboard | null+ isOpen: boolean+ onClose: () => void+ onClear?: () => void+ onCancel?: () => 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+ onDashboardClick?: () => void+}): 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}+ dashboard={dashboard}+ onDashboardClick={onDashboardClick}+ />+ {/* 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.tsxindex df162be1bd5a..b7714dff77cd 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsx@@ -1,317 +1,18 @@import { useActions, useMountedLogic, useValues } from 'kea'-import { useEffect, useRef, useState } from 'react'--import { LemonButton, LemonModal } from '@posthog/lemon-ui'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { cn } from 'lib/utils/css-classes'-import { elapsedSecondsFrom } from 'lib/utils/datetime'-import { userLogic } from 'scenes/userLogic'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { resolveOnboardingFlowVariant } from 'scenes/onboarding/onboardingVariants'-import { onboardingEventUsageLogic } from '../../onboardingEventUsageLogic'import { activeCloudRunLogic, CloudRunHandle } from './activeCloudRunLogic'import { finishedLocalRunLogic } from './finishedLocalRunLogic'-import { elapsedLabel, isRunStale, isStreamLost, syncHeadline, toneTextClass } from './helpers'-import {- InstallationProgress,- installationProgressLogic,- progressFromFinishedLocalRun,-} from './installationProgressLogic'-import { InstallationProgressContent } from './InstallationProgressView'+import { isStreamLost } from './helpers'+import { progressFromFinishedLocalRun } from './installationProgress'+import { installationProgressLogic } from './installationProgressLogic'import { wizardActiveSessionDetectorLogic } from './wizardActiveSessionDetectorLogic'-import { DetectedDashboard, wizardDashboardLogic } from './wizardDashboardLogic'-import { localModeLabel, StatusGlyph, WizardSyncCard, WizardSyncMode } from './WizardSyncCard'+import { WizardSyncSurface } from './WizardSyncSurface'import { wizardSyncUiLogic } from './wizardSyncUiLogic'-// The teammate's name, or null for the viewer's own run (matched on email) or an unknown initiator.-function resolveStartedByLabel(- startedBy: InstallationProgress['startedBy'],- currentUserEmail: string | undefined-): string | null {- if (!startedBy || startedBy.email === currentUserEmail) {- return null- }- return startedBy.name-}--// Corner anchor for the collapsed card and the minimized launcher. The dialog is a portal, so it-// positions itself.-const CORNER = 'fixed bottom-5 right-5 z-[60]'--// 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.-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-}--// The minimized state: a small pill that restores the card. This is the "activate it back" affordance.-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>- )-}--// The expanded "all the details" dialog: the full pipeline plus the terminal payoff or failure.-function WizardSyncDialog({- progress,- elapsedSeconds,- mode,- dashboard,- isOpen,- onClose,- onClear,- onCancel,- cancelling = false,- stale = false,- startedByLabel,- onDashboardClick,-}: {- progress: InstallationProgress- elapsedSeconds: number- mode: WizardSyncMode- dashboard?: DetectedDashboard | null- isOpen: boolean- onClose: () => void- onClear?: () => void- onCancel?: () => 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- onDashboardClick?: () => void-}): 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}- dashboard={dashboard}- onDashboardClick={onDashboardClick}- />- {/* 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>- )-}--// 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.-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 } = useActions(wizardSyncUiLogic)- const { user } = useValues(userLogic)- const startedByLabel = resolveStartedByLabel(progress.startedBy, user?.email)- const {- reportWizardSyncExpanded,- reportWizardSyncMinimized,- reportWizardSyncRestored,- reportWizardSyncRunDismissed,- reportWizardSyncHandoffShown,- reportWizardSyncDashboardCtaShown,- reportWizardSyncDashboardCtaClicked,- } = useActions(onboardingEventUsageLogic)- const { detectedDashboard } = useValues(wizardDashboardLogic)- 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 dashboard = progress.phase === 'completed' ? detectedDashboard : null- 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 dashboardVisible = !!dashboard- useEffect(() => {- if (dashboardVisible) {- reportWizardSyncDashboardCtaShown({ runKey, mode, surface: 'fab' })- }- }, [dashboardVisible, runKey, mode, reportWizardSyncDashboardCtaShown])- const handleDashboardClick = (): void => reportWizardSyncDashboardCtaClicked({ runKey, mode, surface: 'fab' })- // 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}- dashboard={dashboard}- onDashboardClick={handleDashboardClick}- 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}- dashboard={dashboard}- onDashboardClick={handleDashboardClick}- isOpen={dialogOpen}- onClose={closeDialog}- onClear={handleClear}- onCancel={onCancel}- cancelling={cancelling}- />- </>- )-}-// 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(@@ -357,8 +58,8 @@ function WizardSyncFinishedLocalFab(): JSX.Element | null {}// A live local run: the wizard session stream is the source; elapsed comes from its started_at.-function WizardSyncLocalFab(): JSX.Element | null {- const { installationProgress, latestSession } = useValues(installationProgressLogic({ mode: 'local' }))+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@@ -384,11 +85,13 @@ function WizardSyncLocalFab(): JSX.Element | null {// run keeps the handoff on screen without any stream.function WizardSyncLocalGate(): JSX.Element | null {useMountedLogic(wizardActiveSessionDetectorLogic)- const { shouldStream } = useValues(wizardActiveSessionDetectorLogic)- if (!shouldStream) {+ // 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 />+ return <WizardSyncLocalFab workflowId={activeWorkflowId} />}/**@@ -399,21 +102,29 @@ function WizardSyncLocalGate(): JSX.Element | null {* one corner widget, never two.*/export function WizardSyncFab(): JSX.Element | null {- const syncEnabled = useFeatureFlag('ONBOARDING_WIZARD_SYNC', 'test')- const { activeCloudRun, panelMounted } = useValues(activeCloudRunLogic)+ const syncFlagEnabled = useFeatureFlag('ONBOARDING_WIZARD_SYNC', 'test')+ const { featureFlags } = useValues(featureFlagLogic)+ const { activeCloudRun } = useValues(activeCloudRunLogic)+ const { inlineCloudPanelMounted, inlineLocalPanelMounted } = useValues(wizardSyncUiLogic)+ // The self-driving onboarding syncs unconditionally, so its users need the detached widget too+ // once they navigate away from the install step — the sync flag only gates the legacy arm.+ const syncEnabled = syncFlagEnabled || resolveOnboardingFlowVariant(featureFlags) === 'self-driving'- // 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- // panelMounted, so the run is never shown in two places.- if (panelMounted) {- return null- }// 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.- if (activeCloudRun) {+ // 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+ }if (syncEnabled) {return <WizardSyncLocalGate />}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncLauncher.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncLauncher.tsxnew file mode 100644index 000000000000..10396bde6ce1--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncLauncher.tsx@@ -0,0 +1,41 @@+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.tsxnew file mode 100644index 000000000000..7980d283728e--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncSurface.tsx@@ -0,0 +1,169 @@+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 { wizardDashboardLogic } from './wizardDashboardLogic'+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-5 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 } = useActions(wizardSyncUiLogic)+ const { user } = useValues(userLogic)+ const startedByLabel = resolveStartedByLabel(progress.startedBy, user?.email)+ const {+ reportWizardSyncExpanded,+ reportWizardSyncMinimized,+ reportWizardSyncRestored,+ reportWizardSyncRunDismissed,+ reportWizardSyncHandoffShown,+ reportWizardSyncDashboardCtaShown,+ reportWizardSyncDashboardCtaClicked,+ } = useActions(onboardingEventUsageLogic)+ const { detectedDashboard } = useValues(wizardDashboardLogic)+ // `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 dashboard = progress.phase === 'completed' ? detectedDashboard : null+ 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 dashboardVisible = !!dashboard+ useEffect(() => {+ if (dashboardVisible) {+ reportWizardSyncDashboardCtaShown({ runKey, mode, surface: 'fab' })+ }+ }, [dashboardVisible, runKey, mode, reportWizardSyncDashboardCtaShown])+ const handleDashboardClick = (): void => reportWizardSyncDashboardCtaClicked({ runKey, mode, surface: 'fab' })+ // 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}+ dashboard={dashboard}+ onDashboardClick={handleDashboardClick}+ 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}+ dashboard={dashboard}+ onDashboardClick={handleDashboardClick}+ isOpen={dialogOpen}+ onClose={closeDialog}+ onClear={handleClear}+ onCancel={onCancel}+ cancelling={cancelling}+ />+ </>+ )+}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.tsindex 0a91001b87b7..95243a6c92c5 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts@@ -71,7 +71,6 @@ export interface activeCloudRunLogicValues {activeCloudRun: CloudRunHandle | nullcanHydrateFromServer: booleancancellingRun: boolean- panelMounted: booleanpersistedCloudRun: CloudRunHandle | null}@@ -103,9 +102,6 @@ export interface activeCloudRunLogicActions {startedAt: stringtaskId: string}- setPanelMounted: (mounted: boolean) => {- mounted: boolean- }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -164,7 +160,6 @@ export const activeCloudRunLogic = kea<activeCloudRunLogicType>([// 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.- setPanelMounted: (mounted: boolean) => ({ mounted }),// 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.@@ -190,12 +185,6 @@ export const activeCloudRunLogic = kea<activeCloudRunLogicType>([clearActiveCloudRun: () => null,},],- panelMounted: [- false,- {- setPanelMounted: (_, { mounted }) => mounted,- },- ],// 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 disableddiff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.tsindex 1305970cad97..ba91d80225f5 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.ts@@ -196,3 +196,18 @@ export function pipClass(status: InstallationStepStatus): string {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.tsnew file mode 100644index 000000000000..f2ab983d3c7e--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/hooks.ts@@ -0,0 +1,108 @@+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+}++/**+ * 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 (inStorybookTestRunner() || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {+ 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.tsnew file mode 100644index 000000000000..5ca3c44052ce--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgress.ts@@ -0,0 +1,325 @@+import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'++import type { FinishedLocalRunHandle } from './finishedLocalRunLogic'+import { startedByFromSession } from './helpers'+import type {+ 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+}++// 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,+ }+}++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()+): InstallationProgress {+ let phase: InstallationPhase+ let stalledError: { title: string; detail: string | null } | 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 ?? {+ // 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.+ title: taskRunState?.status === 'cancelled' ? 'Run cancelled' : 'Installation failed',+ detail:+ taskRunState?.error_message ?? (session?.error as { message?: string } | null)?.message ?? null,+ })+ : null++ return {+ phase,+ steps,+ error,+ prUrl,+ prMerged,+ isCurrent: phase !== 'idle',+ pendingInput: phase === 'running' ? pendingInputFromSession(session) : null,+ startedBy: startedByFromSession(session),+ }+}++// 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,+ }+ }++ // 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: { title: string; detail: string | null } | null = null+ if (latestSession.run_phase === 'error') {+ error = {+ title: 'Wizard hit an error',+ detail: (latestSession.error as { message?: string } | null)?.message ?? null,+ }+ } 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),+ }+}++// 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'+ ? { title: 'Wizard hit an error', detail: handle.error?.message ?? null }+ : null,+ prUrl: null,+ prMerged: false,+ isCurrent: true,+ pendingInput: null,+ startedBy: handle.startedBy ?? null,+ }+}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressCopy.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressCopy.tsnew file mode 100644index 000000000000..a36e2b8706cb--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressCopy.ts@@ -0,0 +1,85 @@+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.tsindex c9dee592e25f..9c3a85a1ae2b 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.ts@@ -1,3 +1,5 @@+import { initKeaTests } from '~/test/init'+import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'import type { FinishedLocalRunHandle } from './finishedLocalRunLogic'@@ -7,9 +9,10 @@ import {localProgress,pendingInputFromSession,progressFromFinishedLocalRun,- resetWizardSyncTelemetryForTests,- runLocalSessionBookkeeping,-} from './installationProgressLogic'+} 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()@@ -266,6 +269,9 @@ describe('installationProgressLogic merge', () => {['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)@@ -289,6 +295,13 @@ describe('installationProgressLogic merge', () => {])})+ 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@@ -562,15 +575,20 @@ describe('installationProgressLogic merge', () => {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, actions)- runLocalSessionBookkeeping(s, s, actions)+ 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, actions)+ 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()})@@ -579,10 +597,10 @@ describe('installationProgressLogic merge', () => {const actions = spyActions()const running = fresh({ session_id: 'fin', run_phase: 'running' })const done = fresh({ session_id: 'fin', run_phase: 'completed' })- runLocalSessionBookkeeping(done, null, actions) // replayed terminal state: no transition+ runLocalSessionBookkeeping(done, null, POSTHOG_INTEGRATION_WORKFLOW_ID, actions) // replayed terminal state: no transitionexpect(actions.reportWizardSyncSessionFinished).not.toHaveBeenCalled()- runLocalSessionBookkeeping(done, running, actions)- runLocalSessionBookkeeping(done, running, actions)+ runLocalSessionBookkeeping(done, running, POSTHOG_INTEGRATION_WORKFLOW_ID, actions)+ runLocalSessionBookkeeping(done, running, POSTHOG_INTEGRATION_WORKFLOW_ID, actions)expect(actions.reportWizardSyncSessionFinished).toHaveBeenCalledTimes(1)})@@ -600,7 +618,7 @@ describe('installationProgressLogic merge', () => {const s = isFresh? fresh(overrides as Partial<WizardSessionDTOApi>): session(overrides as Partial<WizardSessionDTOApi>)- runLocalSessionBookkeeping(s, null, actions)+ runLocalSessionBookkeeping(s, null, POSTHOG_INTEGRATION_WORKFLOW_ID, actions)expect(actions.recordFinishedLocalRun).toHaveBeenCalledTimes(expectRecorded ? 1 : 0)})@@ -608,7 +626,12 @@ describe('installationProgressLogic merge', () => {// 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, actions)+ 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()})@@ -616,10 +639,42 @@ describe('installationProgressLogic merge', () => {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, actions)).not.toThrow()+ 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.tsindex 540df63bc8b5..105b3ef1bec2 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.ts@@ -22,55 +22,17 @@ import { wizardSessionStreamLogic } from 'products/wizard/frontend/wizardSessionimport type { WizardConnectionStatus } from '../../../../../../products/wizard/frontend/wizardSessionStreamLogic'import { activeCloudRunLogic } from './activeCloudRunLogic'import type { CloudRunHandle } from './activeCloudRunLogic'-import { finishedLocalRunLogic, FinishedLocalRunHandle } from './finishedLocalRunLogic'-import { startedByFromSession } from './helpers'-import {- taskRunPrMerged,- taskRunPrUrl,- taskRunStreamLogic,- TaskRunProgressStep,- TaskRunStreamState,-} from './taskRunStreamLogic'+import { finishedLocalRunLogic } from './finishedLocalRunLogic'+import { cloudProgress, isSessionFresh, localProgress } from './installationProgress'+import { taskRunStreamLogic, TaskRunProgressStep, TaskRunStreamState } from './taskRunStreamLogic'import type { TaskRunConnectionStatus } from './taskRunStreamLogic'-import { isSessionActive, wizardActiveSessionDetectorLogic } from './wizardActiveSessionDetectorLogic'+import {+ isSessionActive,+ watchWorkflowWhileMounted,+ wizardActiveSessionDetectorLogic,+} from './wizardActiveSessionDetectorLogic'import { wizardDashboardLogic } from './wizardDashboardLogic'--// The wizard session stream the local CLI publishes to — and the channel a cloud wizard reports its-// own sub-progress on.-const WORKFLOW_ID = 'posthog-integration'--// 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-}--// 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,- }-}+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@@ -86,25 +48,51 @@ const reportedFinishedSessions = new Set<string>()// 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.-const sessionStreamShares = new Set<string>()--function releaseSessionShare(shareKey: string, disconnectSession: () => void): void {- if (!sessionStreamShares.delete(shareKey)) {+// 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 (sessionStreamShares.size === 0) {+ 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 {- return props.mode === 'cloud' ? `cloud:${props.runId ?? ''}` : 'local'+ 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'@@ -150,269 +138,8 @@ export interface InstallationProgressLogicProps {mode: InstallationModerunId?: stringtaskId?: string-}--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()-): InstallationProgress {- let phase: InstallationPhase- let stalledError: { title: string; detail: string | null } | 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 ?? {- // 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.- title: taskRunState?.status === 'cancelled' ? 'Run cancelled' : 'Installation failed',- detail:- taskRunState?.error_message ?? (session?.error as { message?: string } | null)?.message ?? null,- })- : null-- return {- phase,- steps,- error,- prUrl,- prMerged,- isCurrent: phase !== 'idle',- pendingInput: phase === 'running' ? pendingInputFromSession(session) : null,- startedBy: startedByFromSession(session),- }-}--// 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,- }- }-- let phase: InstallationPhase- if (latestSession.run_phase === 'completed') {- phase = 'completed'- } else if (latestSession.run_phase === 'error') {- 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,- }))-- const error =- latestSession.run_phase === 'error'- ? {- title: 'Wizard hit an error',- detail: (latestSession.error as { message?: string } | null)?.message ?? null,- }- : null-- return {- phase,- steps,- error,- prUrl: null,- prMerged: false,- isCurrent: sessionIsCurrent && !dismissed,- pendingInput: phase === 'running' && !dismissed ? pendingInputFromSession(latestSession) : null,- startedBy: startedByFromSession(latestSession),- }-}--// 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'- ? { title: 'Wizard hit an error', detail: handle.error?.message ?? null }- : null,- prUrl: null,- prMerged: false,- isCurrent: true,- pendingInput: null,- startedBy: handle.startedBy ?? null,- }+ /** 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.@@ -527,7 +254,9 @@ export type installationProgressLogicType = MakeLogicType<*/export const installationProgressLogic = kea<installationProgressLogicType>([props({} as InstallationProgressLogicProps),- key((props) => (props.mode === 'cloud' ? `cloud:${props.runId ?? ''}` : 'local')),+ // 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: [@@ -539,7 +268,7 @@ export const installationProgressLogic = kea<installationProgressLogicType>(['isStalled','lastActivityAt',],- wizardSessionStreamLogic({ workflowId: WORKFLOW_ID }),+ wizardSessionStreamLogic({ workflowId: resolveWorkflowId(props.workflowId) }),['latestSession', 'connectionStatus as sessionConnectionStatus'],finishedLocalRunLogic,['dismissedSessionId'],@@ -553,7 +282,7 @@ export const installationProgressLogic = kea<installationProgressLogicType>(['disconnect as disconnectTaskRun','streamCompleted as taskRunStreamCompleted',],- wizardSessionStreamLogic({ workflowId: WORKFLOW_ID }),+ wizardSessionStreamLogic({ workflowId: resolveWorkflowId(props.workflowId) }),['connect as connectSession', 'disconnect as disconnectSession', 'sessionUpdated'],eventUsageLogic,['reportWizardSyncSessionDetected', 'reportWizardSyncSessionFinished'],@@ -619,7 +348,7 @@ export const installationProgressLogic = kea<installationProgressLogicType>([if (props.mode !== 'cloud') {return}- releaseSessionShare(instanceKey(props), actions.disconnectSession)+ releaseSessionShare(sessionStreamKey(props), instanceKey(props), actions.disconnectSession)// The cloud wizard builds a dashboard too — look it up so the completed surfaces can// link to it. startedAt travels on the persisted run handle; without it there's no run// window to scope the search to, so skip.@@ -637,33 +366,33 @@ export const installationProgressLogic = kea<installationProgressLogicType>([}const prev = (cache.prevSession ?? null) as WizardSessionDTOApi | nullcache.prevSession = session- runLocalSessionBookkeeping(session, prev, actions)+ runLocalSessionBookkeeping(session, prev, resolveWorkflowId(props.workflowId), actions)},})),afterMount(({ actions, props, cache, values }) => {actions.connectTaskRun()- sessionStreamShares.add(instanceKey(props))+ 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.detectorUnmount = wizardActiveSessionDetectorLogic.mount()+ 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, actions)+ runLocalSessionBookkeeping(values.latestSession, null, resolveWorkflowId(props.workflowId), actions)}}}),beforeUnmount(({ actions, props, cache }) => {actions.disconnectTaskRun()- releaseSessionShare(instanceKey(props), actions.disconnectSession)- if (cache.detectorUnmount) {- cache.detectorUnmount()- cache.detectorUnmount = undefined+ releaseSessionShare(sessionStreamKey(props), instanceKey(props), actions.disconnectSession)+ if (cache.unwatchWorkflow) {+ cache.unwatchWorkflow()+ cache.unwatchWorkflow = undefined}}),])@@ -679,6 +408,7 @@ export const installationProgressLogic = kea<installationProgressLogicType>([export function runLocalSessionBookkeeping(session: WizardSessionDTOApi,prev: WizardSessionDTOApi | null,+ workflowId: string,actions: {markSessionCurrent: () => voidrecordFinishedLocalRun: (session: WizardSessionDTOApi) => void@@ -720,7 +450,7 @@ export function runLocalSessionBookkeeping(if (!reportedDetectedSessions.has(session.session_id)) {reportedDetectedSessions.add(session.session_id)actions.reportWizardSyncSessionDetected({- workflowId: WORKFLOW_ID,+ workflowId,skillId: session.skill_id,runPhase: session.run_phase,taskCount: tasks.length,@@ -738,7 +468,7 @@ export function runLocalSessionBookkeeping(const eligible = isSessionActive(session)const wasEligible = isSessionActive(prev)if (eligible) {- detector.actions.markActive()+ detector.actions.markActive(workflowId)} else if (wasEligible) {detector.actions.scheduleMarkInactive()}@@ -750,7 +480,7 @@ export function runLocalSessionBookkeeping(if (isTerminalPhase && !reportedFinishedSessions.has(session.session_id)) {reportedFinishedSessions.add(session.session_id)actions.reportWizardSyncSessionFinished({- workflowId: WORKFLOW_ID,+ workflowId,skillId: session.skill_id,outcome: session.run_phase,taskCount: tasks.length,diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.tsindex 9d1fdedac447..06d36209a536 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts@@ -208,7 +208,7 @@ export interface taskRunStreamLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface taskRunStreamLogicActions {- reportContextOnboardingCloudRunCompleted: (props: {+ reportSelfDrivingOnboardingCloudRunCompleted: (props: {durationSeconds: number | nullprOpened: booleanprUrl: string | null@@ -289,7 +289,7 @@ export const taskRunStreamLogic = kea<taskRunStreamLogicType>([path((key) => ['scenes', 'onboarding', 'taskRunStreamLogic', key]),connect(() => ({values: [projectLogic, ['currentProjectId'], activeCloudRunLogic, ['activeCloudRun']],- actions: [onboardingEventUsageLogic, ['reportContextOnboardingCloudRunCompleted']],+ actions: [onboardingEventUsageLogic, ['reportSelfDrivingOnboardingCloudRunCompleted']],})),actions({connect: true,@@ -400,7 +400,7 @@ export const taskRunStreamLogic = kea<taskRunStreamLogicType>([const report = cloudRunCompletionReport(previous, state, values.progressSteps, startedAt)if (report && !reportedTerminalRuns.has(props.runId)) {reportedTerminalRuns.add(props.runId)- actions.reportContextOnboardingCloudRunCompleted({+ actions.reportSelfDrivingOnboardingCloudRunCompleted({taskId: props.taskId,runId: props.runId,...report,diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.test.tsindex 17362f07b517..1541cb002cec 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.test.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.test.ts@@ -131,8 +131,92 @@ describe('wizardActiveSessionDetectorLogic', () => {.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()+ logic.actions.markActive('posthog-integration')await expectLogic(logic).toMatchValues({ hasActiveSession: true })mockLatestRetrieve.mockResolvedValue(makeSession({ run_phase: 'completed' }))@@ -160,7 +244,7 @@ describe('wizardActiveSessionDetectorLogic', () => {})it('fires markInactive once the 30s grace window elapses', async () => {- logic.actions.markActive()+ logic.actions.markActive('posthog-integration')logic.actions.scheduleMarkInactive()// Just before the deadline: the stream is still up.@@ -177,12 +261,12 @@ describe('wizardActiveSessionDetectorLogic', () => {})it('cancels the pending teardown when markActive fires inside the window', async () => {- logic.actions.markActive()+ 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()+ logic.actions.markActive('posthog-integration')await expectLogic(logic, () => {jest.advanceTimersByTime(60_000)@@ -192,7 +276,7 @@ describe('wizardActiveSessionDetectorLogic', () => {})it('keeps the original deadline when scheduleMarkInactive is repeated (idempotent)', async () => {- logic.actions.markActive()+ logic.actions.markActive('posthog-integration')logic.actions.scheduleMarkInactive() // deadline = now + 30sjest.advanceTimersByTime(20_000)diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.tsindex 7b0ef98032b6..035cea789caa 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.ts@@ -3,7 +3,11 @@ import { subscriptions } from 'kea-subscriptions'import posthog from 'posthog-js'import { ApiError } from 'lib/api-error'+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { resolveOnboardingFlowVariant } from 'scenes/onboarding/onboardingVariants'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@@ -11,7 +15,10 @@ import { projectLogic } from 'scenes/projectLogic'import { wizardSessionsLatestRetrieve } from 'products/wizard/frontend/generated/api'import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'-const WORKFLOW_ID = 'posthog-integration'+import { POSTHOG_INTEGRATION_WORKFLOW_ID, SELF_DRIVING_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@@ -42,7 +49,50 @@ const TERMINAL_GRACE_MS = 30 * 1000// INC-886 at single-user scale.const MAX_SESSION_LIFETIME_MS = 60 * 60 * 1000-export function isSessionActive(session: WizardSessionDTOApi | null | undefined): boolean {+// 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}@@ -65,11 +115,17 @@ export function isSessionActive(session: WizardSessionDTOApi | null | undefined)// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface wizardActiveSessionDetectorLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogiccurrentProjectId: number | null // projectLogic+ activeWorkflowId: string | null+ consecutivePollFailures: number+ extraWorkflowCounts: Record<string, number>hasActiveSession: boolean+ hasResolvedSessionState: booleanlastError: string | nullpermanentlyDisabled: booleanshouldStream: boolean+ watchedWorkflows: string[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -80,8 +136,8 @@ export interface wizardActiveSessionDetectorLogicActions {check: () => {value: true}- markActive: () => {- value: true+ markActive: (workflowId: string) => {+ workflowId: string}markInactive: () => {value: true@@ -89,17 +145,34 @@ export interface wizardActiveSessionDetectorLogicActions {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>, featureFlags: FeatureFlagsSet) => string[]shouldStream: (hasActiveSession: boolean) => boolean}}@@ -130,12 +203,19 @@ export type wizardActiveSessionDetectorLogicType = MakeLogicType<export const wizardActiveSessionDetectorLogic = kea<wizardActiveSessionDetectorLogicType>([path(['scenes', 'onboarding', 'wizardActiveSessionDetectorLogic']),connect(() => ({- values: [projectLogic, ['currentProjectId']],+ values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags']],})),actions({check: true,- markActive: 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 }),@@ -143,14 +223,68 @@ export const wizardActiveSessionDetectorLogic = kea<wizardActiveSessionDetectorL// 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({- hasActiveSession: [+ // 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: () => false,- markPermanentlyDisabled: () => false,+ 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: [@@ -168,6 +302,23 @@ export const wizardActiveSessionDetectorLogic = kea<wizardActiveSessionDetectorL],}),selectors({+ hasActiveSession: [+ (s) => [s.activeWorkflowId],+ (activeWorkflowId: string | null): boolean => activeWorkflowId !== null,+ ],+ watchedWorkflows: [+ (s) => [s.extraWorkflowCounts, s.featureFlags],+ (extraWorkflowCounts: Record<string, number>, featureFlags: FeatureFlagsSet): string[] => {+ // Self-driving users are watched from the start, not only once an install-progress+ // instance registers: otherwise reloading any page mid-run loses the widget, because+ // nothing would be polling the program that is actually running.+ const base =+ resolveOnboardingFlowVariant(featureFlags) === 'self-driving'+ ? [WORKFLOW_ID, SELF_DRIVING_WORKFLOW_ID]+ : [WORKFLOW_ID]+ return [...new Set([...base, ...Object.keys(extraWorkflowCounts)])]+ },+ ],shouldStream: [(s) => [s.hasActiveSession], (hasActiveSession: boolean): boolean => hasActiveSession],}),listeners(({ actions, values, cache }) => ({@@ -183,64 +334,108 @@ export const wizardActiveSessionDetectorLogic = kea<wizardActiveSessionDetectorL// ignored — without this, an older "empty" can overwrite a newer// "active" if responses race.const seq = (cache.pollSeq = (cache.pollSeq ?? 0) + 1)- try {- // 204 (no run) returns an empty body, which the api client resolves to null.- const session: WizardSessionDTOApi | null =- (await wizardSessionsLatestRetrieve(- String(projectId),- { workflow_id: WORKFLOW_ID },- { headers: { 'X-Wizard-Poll-Source': 'detector' } }- )) || null- if (seq !== cache.pollSeq) {- return- }- if (isSessionActive(session)) {- actions.markActive()- } else 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()+ // 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 {- actions.markInactive()- }- } catch (err) {- if (seq !== cache.pollSeq) {- return+ errors.push(result.reason)}- // A cancelled fetch (unmount / navigation) is not a real failure;- // skip it so it doesn't pollute lastError or telemetry.- if (err instanceof Error && err.name === 'AbortError') {- return- }- if (err instanceof ApiError && err.status !== undefined) {- // 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. 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 once the- // rollout completes.- if (err.status === 401 || err.status === 403) {- posthog.captureException(err, {- tags: { feature: 'wizard-active-session-detector', reason: 'permanently_disabled' },- extra: { status: err.status },- })- actions.setLastError(- `wizard latest-session endpoint returned ${err.status} — disabling detector`- )- actions.markPermanentlyDisabled()- cache.disposables.dispose('rest-poll')- return- }- }- // Transient REST failure (including a deploy-window 404) — surface- // it via lastError + Sentry, but leave hasActiveSession as-is so- // SSE-driven state isn't clobbered. The next poll retries.+ }++ // 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' },})- actions.setLastError(err instanceof Error ? err.message : String(err))+ }+ 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: () => {@@ -250,6 +445,10 @@ export const wizardActiveSessionDetectorLogic = kea<wizardActiveSessionDetectorLcache.markInactiveAt = undefinedcache.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,@@ -276,7 +475,7 @@ export const wizardActiveSessionDetectorLogic = kea<wizardActiveSessionDetectorLcache.disposables.dispose('mark-inactive-grace')},})),- subscriptions(({ actions, cache }) => ({+ 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) => {@@ -290,8 +489,7 @@ export const wizardActiveSessionDetectorLogic = kea<wizardActiveSessionDetectorLif (prev === undefined) {return}- cache.disposables.dispose('mark-inactive-grace')- actions.markInactive()+ actions.resetSessionState()if (projectId !== null) {actions.check()}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.tsindex 5046a819f28d..23e9ce9b2223 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.ts@@ -64,7 +64,7 @@ export interface wizardCloudRunLogicActions {taskId: string} // activeCloudRunLogicloadIntegrations: () => any // integrationsLogic- reportContextOnboardingCloudRunQueued: (props: { repository: string; runId: string; taskId: string }) => {+ reportSelfDrivingOnboardingCloudRunQueued: (props: { repository: string; runId: string; taskId: string }) => {repository: stringrunId: stringtaskId: string@@ -138,7 +138,7 @@ export const wizardCloudRunLogic = kea<wizardCloudRunLogicType>([activeCloudRunLogic,['setActiveCloudRun', 'clearActiveCloudRun'],onboardingEventUsageLogic,- ['reportContextOnboardingCloudRunQueued'],+ ['reportSelfDrivingOnboardingCloudRunQueued'],],})),actions({@@ -243,7 +243,7 @@ export const wizardCloudRunLogic = kea<wizardCloudRunLogicType>([// 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.reportContextOnboardingCloudRunQueued({ taskId: task_id, runId: run_id, repository })+ actions.reportSelfDrivingOnboardingCloudRunQueued({ taskId: task_id, runId: run_id, repository })actions.startCloudRunSuccess()} catch (e) {const detail = e instanceof ApiError ? e.detail : nulldiff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.test.tsnew file mode 100644index 000000000000..81f8f1a6740f--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.test.ts@@ -0,0 +1,46 @@+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)+ })+})diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.tsindex 1cc5153438a2..8118a8378228 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardSyncUiLogic.ts@@ -1,13 +1,23 @@-import { MakeLogicType, actions, kea, path, reducers } from 'kea'+import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'++/** 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 {dialogOpen: booleandismissedKey: string | null+ inlineCloudPanelMounted: boolean+ inlineLocalPanelMounted: boolean+ inlinePanelCounts: Record<WizardSyncMode, number>+ inlinePanelMounted: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface wizardSyncUiLogicActions {+ claimInlinePanel: (mode: WizardSyncMode) => {+ mode: WizardSyncMode+ }closeDialog: () => {value: true}@@ -17,18 +27,40 @@ export interface wizardSyncUiLogicActions {openDialog: () => {value: true}+ releaseInlinePanel: (mode: WizardSyncMode) => {+ mode: WizardSyncMode+ }restore: () => {value: true}}-export type wizardSyncUiLogicType = MakeLogicType<wizardSyncUiLogicValues, wizardSyncUiLogicActions>+// 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.** The widget itself owns no run data; the per-mode inner components feed it the normalized progress.*/@@ -39,6 +71,8 @@ export const wizardSyncUiLogic = kea<wizardSyncUiLogicType>([restore: true,openDialog: true,closeDialog: true,+ claimInlinePanel: (mode: WizardSyncMode) => ({ mode }),+ releaseInlinePanel: (mode: WizardSyncMode) => ({ mode }),}),reducers({dismissedKey: [@@ -57,5 +91,28 @@ export const wizardSyncUiLogic = kea<wizardSyncUiLogicType>([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) }),+ },+ ],+ }),+ 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,+ ],}),])diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/workflows.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/workflows.tsnew file mode 100644index 000000000000..5298a51a82c3--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/workflows.ts@@ -0,0 +1,22 @@+/**+ * 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 the self-driving onboarding runs. */+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+}