: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): goals and product enablement in the self-driving onboarding (#77849)
Fernando Gomes1eec2f11f258
diff --git a/frontend/package.json b/frontend/package.jsonindex 88cf50e66cff..41e499772500 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -276,6 +276,7 @@"react-window": "^2.2.5","remark-breaks": "^4.0.0","remark-gfm": "^4.0.0",+ "rough-notation": "^0.5.1","rrule": "^2.8.1","simple-statistics": "^7.8.8","snappy-wasm": "^0.3.0",diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex dbb064eb6b9a..393f4ae33787 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6315,29 +6315,33 @@ snapshots:scenes-app-inbox-scene--self-driving-paused--light:hash: v1.k794b7964.54f6835c7d4a343bd6c9efef4189805b8dc5ea3347380b5d772ce55abaad79be.P7Ramt_0TgHAl4YgBsBumQ1QVxkb2ds9GsTaxbNAKRQscenes-app-inbox-signalsourcespanel--armed-but-tools-off--dark:- hash: v1.k794b7964.742013ce30e15b5b5d38b2e6939a899e6258c960bc38075c26d1bda289f5787c.glB0VlAeBYIngG4lWoiyaqpDKgMVnBLtxdeelz4aSME+ hash: v1.k794b7964.20050af8c990675d228756e418733c5a84800ab0e73268b3e84fcfaa77326033.UNceOt064IkgNJpcw8G21aEsRt_YUVxuwQcQVKE9rLcscenes-app-inbox-signalsourcespanel--armed-but-tools-off--light:- hash: v1.k794b7964.815db9957f9da19d00683803f633cb468a05e4f698f12629dc8d8c85328a42ec.Yu4wrqmDkHcq6TKV5LZRQ2NBcPhWgZfJd9Vt5V-gpsM+ hash: v1.k794b7964.f4db053221794d14ccfc7fc4b2db58561926e8926d1f86e14e5ddb0e7c33af8c.bzlhH-Oz8GQ-NWZbIVYFM5uNtShPRP8boC7zUw17Pakscenes-app-inbox-signalsourcespanel--arming-blocked--dark:- hash: v1.k794b7964.cd76b5e3e4039fdc0fee477acd65505cc85989515ba53bc518a963ae2a2b2561.WXyh2FRGYjY1C8aL_yAdZUVJfxW6sd5SarZ5DEZDxB8+ hash: v1.k794b7964.f0f8e6ee75faff8a85951d2064af260f1c632dec27f6f8bf985ae27a337d7921.eaoCUH22jbc6iiRsFISLR2MRtMFenX2NSOrs_qC3y1Yscenes-app-inbox-signalsourcespanel--arming-blocked--light:- hash: v1.k794b7964.25a78443d646dc69f69a12c882582efd41f1077e70f646d60e7cea8b3610d123.xd0X2Sxk_vFxvhV6D0k7EDctaS61tJWGuCXUnolntAE+ hash: v1.k794b7964.d9c20994fe99d71927a5fa272cd42da606fc7478a728560aff6e92f21729d367.kmiO-_9bvOGcx7Phf2q7dhuKyjQP8AxtaTA4t1ORYc0+ scenes-app-inbox-signalsourcespanel--event-definitions-unavailable--dark:+ hash: v1.k794b7964.c93df4a3587e8d72869fecea9a42afbb1b6ddda8cc4973c57614c413c3833987.bDB_pp6afKjWhk2R36qPRGrcxKqn86ic1gt93zYkA14+ scenes-app-inbox-signalsourcespanel--event-definitions-unavailable--light:+ hash: v1.k794b7964.a2c50f3003aed34c440e362882b3b8deecfa37c25b3c2b8d97bd2fb6151c421a.QxzAw2wSH-SgFTBYv2ZjTUOtI5k2sn3m_tiUJExYkVIscenes-app-inbox-signalsourcespanel--everything-healthy--dark:- hash: v1.k794b7964.de69ec220490357be3de892de5eabfc06fce9066a980c95bef3ba2ec8e4d7afc.HXtbOMlXNcHBRJslE0Bumji-Ybi3hUiP7_pMvwaEXfo+ hash: v1.k794b7964.e87417e8e548e011de059e4502a22f8d08acc9c18c49e17d1675535d79439049.pF_JHdGWr8AWgR0UpDIdZbFCjdM3G08-1IofaVJ9U3cscenes-app-inbox-signalsourcespanel--everything-healthy--light:- hash: v1.k794b7964.cfc383fae4c1881c8377972452337fbe070ea5c64541fa87d2e088427d5aa20e.oiktmtDX4MnFc2kQZz-G4huxMXKvsyjW8LjrEIAYO_A+ hash: v1.k794b7964.ff0aa89f58531c110b4575d72dd3fe170c9cd61e6723846301325eb84e740eb8.zKKNFUy6y8j1iIVNM0tPiOnXoZgO3f9pYO5xxZYlVAIscenes-app-inbox-signalsourcespanel--playground--dark:- hash: v1.k794b7964.fff26488df405308a15e62ec5e5f1d9098790376d5c7a2dbc74b56ac8f96db5a.FnxQMtSJHjd51i7554HmHV2VDtD3ZBPnmjyaiwGxB8I+ hash: v1.k794b7964.e8e4e30e2747b995e7cd20b9d1e073d8c92158362f32e288f40f44b781628bf4.PJIcVexkRlxvzyFWUTMS4_BqQl7Q2T1x2ufMs591KAkscenes-app-inbox-signalsourcespanel--playground--light:- hash: v1.k794b7964.e25f6d4d0820cc887752340ef581de7c1b67a1b6ef6fa9f7c93fdd4c5edef745.SnJd3cxBet51gMFec3lV3Yn_mFx0JlOx9pQhz2EGFfw+ hash: v1.k794b7964.1aa4b81b48bdb5820636df2b4eaf9aef3e65b79775c5f29d18132cceac6828c3.2Pv05tzAtuUky1gWdAjqabTlVCchf24mjEYvWm1TK44scenes-app-inbox-signalsourcespanel--server-side-exceptions-only--dark:- hash: v1.k794b7964.fff26488df405308a15e62ec5e5f1d9098790376d5c7a2dbc74b56ac8f96db5a.uYyWUYz23ovTwNTH2rmp88Rd8rmoIUzKWWp1OtGUsLw+ hash: v1.k794b7964.e8e4e30e2747b995e7cd20b9d1e073d8c92158362f32e288f40f44b781628bf4.isFB5fHez5FGxRmGxUyALxw1He2MuOYMZ_A3DeU9NFcscenes-app-inbox-signalsourcespanel--server-side-exceptions-only--light:- hash: v1.k794b7964.e25f6d4d0820cc887752340ef581de7c1b67a1b6ef6fa9f7c93fdd4c5edef745.AC3irtXDuYfoIjonKcrKoQiKM5cAzu1jisccASmMTpc- scenes-app-inbox-signalsourcespanel--tools-on-no-data-yet--dark:- hash: v1.k794b7964.203c1d6405e68ace50911e4f13d6edefc48895799412a148d8387d63614d3b41.aMGf7ZpBR4o3DWCom6TuEO-UzwqsaMVKgEYGMmBMss8- scenes-app-inbox-signalsourcespanel--tools-on-no-data-yet--light:- hash: v1.k794b7964.f610c72ee19f4f36e47157651dcfa007374c85d2b5e851e36c20844e37ba0c69.GvM2ToDHue-jV7R5WRULAKUeHr4CLiLLbzxjgxzUCw4+ hash: v1.k794b7964.1aa4b81b48bdb5820636df2b4eaf9aef3e65b79775c5f29d18132cceac6828c3.-Lzah6U8iQ65oCGO5K-t8yWZq_RvN7BtOIKuyhC2K98+ scenes-app-inbox-signalsourcespanel--tools-on-no-recent-data--dark:+ hash: v1.k794b7964.1fbe059d2093a6683e1cbfe30b569913c56e3e594d9f92092aec13343a681292.uql5SNStGflZ2au-7Kgw1X_5TS3oP_XDBTUHb-P3AH0+ scenes-app-inbox-signalsourcespanel--tools-on-no-recent-data--light:+ hash: v1.k794b7964.147252b7bbb68397e1e5625809ec372f1dc084add4ffd6e440d298ad83092cdf.sI9t_SA51MQuBfFQWlr7j6khN_HVZffGe2___bnG5owscenes-app-inbox-tabs--pull-requests--dark:hash: v1.k794b7964.474d8e744637e08afd4bb7540f0f5dafd6a79342c2f547188cb436b55f9ef8e7.PiyD1Zkhkot-_DKLU3W0T5uA7rvpTUTn5bKChCa3AV4scenes-app-inbox-tabs--pull-requests--light:@@ -7822,18 +7826,22 @@ snapshots:hash: v1.k794b7964.000a1ac36e3d4a36f800e888ef2b21721eee0122e9a10f20c7da21214e2375fa.2eiPdwSJ15FNVd183gSPvbFq-ywaCwnSkIS9Q_L3Mrwscenes-other-onboarding-legacy-weekly-reports--marketing-report--light:hash: v1.k794b7964.0e2a8e49d86bf85201eab7a83383dc110b5bfa4e375cdd115d31aceec6851ace.mbj1QmZoty5ZryyE-hjsIp-VqV-X05nlVS0S_5Z3UP8+ scenes-other-onboarding-self-driving--use-cases-dark--dark:+ hash: v1.k794b7964.5ae59c5409e81c4aad8bf3ab024f0cbec45e230b888c70d9358b07c0be26b1e5.ur7nHUhDZH1FVX2IH2JX-5yMufydHRbCt8mlcWZy97s+ scenes-other-onboarding-self-driving--use-cases-light--light:+ hash: v1.k794b7964.0696ec172c4a1b87f75a027360b5f339d4da1d2b30c26bde876edbff82bc3dd0.gvqJ14XHE4dLkhKJ-p3yhPVukRrYTQ2cG-9vcCv7lWEscenes-other-onboarding-shared-installation-progress--all-states--dark:- hash: v1.k794b7964.701a00d919735a8e926d138dbf37d3f999ffe860a38366ffad441d2ea9007dc3.At1SVb1kbXJdi1oQ6SNRG2h9FaXngLNhQiIfeDfBvag+ hash: v1.k794b7964.f27ec49d9f5135f7c07e378091bebea93949d910823f9f9d498f162baa1e5536.j1ZpoUvgIKsVhfaOTJ5j5M9ycLq6FAL3o1w-7te1Rqwscenes-other-onboarding-shared-installation-progress--all-states--light:- hash: v1.k794b7964.851e5525b9f7c4955768768dbe9be7e523626507c62719983a9987d88f377d28.N_3uzrW7wz7rBbjVkEfSPqnZCm37zpUXHdQC8c8tLEo+ hash: v1.k794b7964.1cf6769134895b499dd8e9a6543f9cb7b44223d0845b51a043d40705e8559be3.efhLRaM5eN3mDt_hhdE0LZ1nlcx2Cf1IWlyAYA8ukkcscenes-other-onboarding-shared-installation-progress--completed--dark:hash: v1.k794b7964.a5c39954664721c5f485671e2144a599f4bee52af9d43d3eba9d5469d10b34fb.RwKIupLIPaIjkqA-87qce-fCE6iJ9J4FlanTULVNY24scenes-other-onboarding-shared-installation-progress--completed--light:hash: v1.k794b7964.bcf5d2def507944709285c026e238335307c02ad344b7216536be2b9e29b344f.PO-TsJat5OfrttiFuq4wkZMAOx3I5QROXVLzBPvGg18scenes-other-onboarding-shared-installation-progress--completed-local-handoff--dark:- hash: v1.k794b7964.bbc57991c178d0788c6fab71dd72d254361384e0399da3c68e13d045ed1d17da.29t13LRsYq53GL20sxOGDEheK9WcztzEdoPAqVjAcaw+ hash: v1.k794b7964.54ae5f41796064680fe877e8abafbde8ea98cee8546285b5a02331e33fac858f.Kh-7hjN_VcotxJxZa4ApD0z8izu71VI8KI8bEbD7Vf0scenes-other-onboarding-shared-installation-progress--completed-local-handoff--light:- hash: v1.k794b7964.8ea61ff9bac8ab7b7d8c9b21deae5a8f6082d3ae397de87d12f6363bd2002f3a._AVZdbGBN7ZivWe9YKDJr0zGoX164EHUTgIUdG7rRkw+ hash: v1.k794b7964.2da3206b0aff090c537e232ded6436b7151c8be3c8e4d147c8009c2f85689331.umA7mNjx78a6a5LRGM-FdZVaQzIkYLaHoIMDdS7AmOQscenes-other-onboarding-shared-installation-progress--completed-merged--dark:hash: v1.k794b7964.e41a47c6d198618b61635ee98c7424dcd8893284a69cf72c2cd18bbcbf1bce4c.Q8Ahyvmp_7fhazPC-B3XSNQd9igBc1zLpI5tzQYOMqcscenes-other-onboarding-shared-installation-progress--completed-merged--light:diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex e705a67a0270..45977aea6037 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -47,6 +47,7 @@ const ERROR_FILTER_ALLOW_LIST = ['loadDatasetItemDetails', // Dataset item modals render their own retry state'loadDatasetItemVersions', // Dataset item modals render their own retry state'exportDataset', // Dataset scenes render their own retry state+ 'loadToolDataEvents',]/*diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex a2d7c710ec11..8dd9cc0412b3 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -10,6 +10,7 @@ import { objectClean } from 'lib/utils/objects'import { BillingUsageInteractionProps } from 'scenes/billing/types'import type { DashboardAddTileType } from 'scenes/dashboard/dashboardAddTileTypes'import { SharedMetric } from 'scenes/experiments/SharedMetrics/sharedMetricLogic'+import type { SelfDrivingOnboardingStepId } from 'scenes/onboarding/onboardingEventUsageLogic'import { ProductTourEvent } from 'scenes/product-tours/constants'import { NewSurvey, SURVEY_CREATED_SOURCE, SurveyTemplateType } from 'scenes/surveys/constants'import { userLogic } from 'scenes/userLogic'@@ -165,7 +166,12 @@ export interface ExperimentRecordingsBucketFailedContext {// by `version` (1 = legacy, 2 = context-first redesign) and `flow_variant`. Stamping properties// instead of renaming keeps every existing dashboard and alert on the v1 events working. The// redesign's v2 events live in `scenes/onboarding/onboardingEventUsageLogic`.-const LEGACY_ONBOARDING_EVENT_PROPS = { version: 1, flow_variant: 'legacy' } as const+export type OnboardingEventProperties = {+ flow_variant: 'context_first' | 'legacy'+ version: 1 | 2+}++const LEGACY_ONBOARDING_EVENT_PROPS: OnboardingEventProperties = { version: 1, flow_variant: 'legacy' }function retentionWindowDays(metric: ExperimentRetentionMetric): number | undefined {const unitToDays: Record<string, number> = { day: 1, week: 7, month: 30 }@@ -1605,8 +1611,12 @@ export interface eventUsageLogicActions {reportKey: stringrole: string | null}- reportOnboardingCompleted: (productKey: string) => {+ reportOnboardingCompleted: (+ productKey: string,+ properties?: OnboardingEventProperties+ ) => {productKey: string+ properties: OnboardingEventProperties | undefined}reportOnboardingProductSelectionPath: (path: 'ai' | 'browsing_history' | 'manual' | 'use_case',@@ -1634,22 +1644,30 @@ export interface eventUsageLogicActions {recommendationSource: stringselected: boolean}- reportOnboardingStarted: (entrypoint: string) => {+ reportOnboardingStarted: (+ entrypoint: string,+ properties?: OnboardingEventProperties+ ) => {entrypoint: string+ properties: OnboardingEventProperties | undefined}reportOnboardingStepCompleted: (- stepKey: OnboardingStepKey,- productKey?: string+ stepKey: OnboardingStepKey | SelfDrivingOnboardingStepId,+ productKey?: string,+ properties?: OnboardingEventProperties) => {productKey: string | undefined- stepKey: OnboardingStepKey+ properties: OnboardingEventProperties | undefined+ stepKey: OnboardingStepKey | SelfDrivingOnboardingStepId}reportOnboardingStepSkipped: (- stepKey: OnboardingStepKey,- productKey?: string+ stepKey: OnboardingStepKey | SelfDrivingOnboardingStepId,+ productKey?: string,+ properties?: OnboardingEventProperties) => {productKey: string | undefined- stepKey: OnboardingStepKey+ properties: OnboardingEventProperties | undefined+ stepKey: OnboardingStepKey | SelfDrivingOnboardingStepId}reportOnboardingUseCaseSelected: (useCase: string,@@ -2733,14 +2751,27 @@ export const eventUsageLogic = kea<eventUsageLogicType>([reportProductTourListViewed: true,reportProductUnsubscribed: (product: string) => ({ product }),reportSubscribedDuringOnboarding: (productKey: string) => ({ productKey }),- reportOnboardingStarted: (entrypoint: string) => ({ entrypoint }),- reportOnboardingStepCompleted: (stepKey: OnboardingStepKey, productKey?: string) => ({+ reportOnboardingStarted: (entrypoint: string, properties?: OnboardingEventProperties) => ({+ entrypoint,+ properties,+ }),+ reportOnboardingStepCompleted: (+ stepKey: OnboardingStepKey | SelfDrivingOnboardingStepId,+ productKey?: string,+ properties?: OnboardingEventProperties+ ) => ({stepKey,productKey,+ properties,}),- reportOnboardingStepSkipped: (stepKey: OnboardingStepKey, productKey?: string) => ({+ reportOnboardingStepSkipped: (+ stepKey: OnboardingStepKey | SelfDrivingOnboardingStepId,+ productKey?: string,+ properties?: OnboardingEventProperties+ ) => ({stepKey,productKey,+ properties,}),reportOnboardingAIReportSubscribed: (role: string | null, reportKey: string, experimentArm: string | null) => ({role,@@ -2752,7 +2783,10 @@ export const eventUsageLogic = kea<eventUsageLogicType>([reportKey,experimentArm,}),- reportOnboardingCompleted: (productKey: string) => ({ productKey }),+ reportOnboardingCompleted: (productKey: string, properties?: OnboardingEventProperties) => ({+ productKey,+ properties,+ }),reportOnboardingUseCaseSelected: (useCase: string, recommendedProducts: readonly string[]) => ({useCase,recommendedProducts,@@ -4139,26 +4173,29 @@ export const eventUsageLogic = kea<eventUsageLogicType>([product_key: productKey,})},- reportOnboardingStarted: ({ entrypoint }) => {+ reportOnboardingStarted: ({ entrypoint, properties }) => {posthog.capture('onboarding started', {entry_point: entrypoint,...LEGACY_ONBOARDING_EVENT_PROPS,+ ...properties,})},- reportOnboardingStepCompleted: ({ stepKey, productKey }) => {+ reportOnboardingStepCompleted: ({ stepKey, productKey, properties }) => {posthog.capture('onboarding step completed', {step_key: stepKey,// Optional — only set when the caller knows which product owns the step.// Lets dashboards split step funnels by product without joining elsewhere....(productKey ? { product_key: productKey } : {}),...LEGACY_ONBOARDING_EVENT_PROPS,+ ...properties,})},- reportOnboardingStepSkipped: ({ stepKey, productKey }) => {+ reportOnboardingStepSkipped: ({ stepKey, productKey, properties }) => {posthog.capture('onboarding step skipped', {step_key: stepKey,...(productKey ? { product_key: productKey } : {}),...LEGACY_ONBOARDING_EVENT_PROPS,+ ...properties,})},reportOnboardingAIReportSubscribed: ({ role, reportKey, experimentArm }) => {@@ -4177,10 +4214,11 @@ export const eventUsageLogic = kea<eventUsageLogicType>([...LEGACY_ONBOARDING_EVENT_PROPS,})},- reportOnboardingCompleted: ({ productKey }) => {+ reportOnboardingCompleted: ({ productKey, properties }) => {posthog.capture('onboarding completed', {product_key: productKey,...LEGACY_ONBOARDING_EVENT_PROPS,+ ...properties,})},reportOnboardingUseCaseSelected: ({ useCase, recommendedProducts }) => {diff --git a/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts b/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.tsindex 3c0790507816..c19c6316644d 100644--- a/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts+++ b/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts@@ -541,25 +541,6 @@ describe('onboardingLogic — flow composition', () => {})})- describe('completeSelfDrivingOnboarding', () => {- it('persists both onboarding completion signals', async () => {- await expectLogic(logic, () => {- logic.actions.completeSelfDrivingOnboarding()- }).toDispatchActions([- (action) => {- if (action.type !== logic.actionTypes.updateCurrentTeam) {- return false- }- expect(action.payload).toMatchObject({- completed_snippet_onboarding: true,- has_completed_onboarding_for: { [ProductKey.PRODUCT_ANALYTICS]: true },- })- return true- },- ])- })- })-describe('URL → state', () => {it('parses /onboarding/<productKey> and sets primary', async () => {await expectLogic(logic, () => {diff --git a/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx b/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsxindex 8d4cdad8c07f..f6cb32f97170 100644--- a/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx+++ b/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx@@ -35,7 +35,6 @@ import type {TeamType,UserType,} from '../../../types'-import { onboardingEventUsageLogic } from '../onboardingEventUsageLogic'import { arraysEqual, parseProductsParam, stepKeyToTitle } from './onboardingFlowUtils'import { appendSharedTrailingSteps, mayBeAppendedLater } from './sharedSteps'import { onboardingProviderRegistry } from './stepProviderRegistry'@@ -100,9 +99,6 @@ export interface onboardingLogicActions {openGlobalSetup: () => {value: true} // globalSetupLogic- reportSelfDrivingOnboardingCompleted: (productKey: string) => {- productKey: string- } // onboardingEventUsageLogicopenSidePanel: (tab: SidePanelTab,options?: string | undefined@@ -110,9 +106,9 @@ export interface onboardingLogicActions {options: string | undefinedtab: SidePanelTab} // sidePanelStateLogic- recordProductIntentOnboardingComplete: (args_0: { product_type: ProductKey }) => {- product_type: ProductKey- } // teamLogic+ recordProductIntentOnboardingComplete: (+ properties: import('scenes/teamLogic').ProductOnboardingCompleteProperties+ ) => import('scenes/teamLogic').ProductOnboardingCompleteProperties // teamLogicupdateCurrentTeam: (payload: Partial<TeamType>) => Partial<TeamType> // teamLogicupdateCurrentTeamSuccess: (currentTeam: TeamPublicType | TeamType,@@ -127,9 +123,6 @@ export interface onboardingLogicActions {completeOnboarding: (options?: { redirectUrlOverride?: string }) => {redirectUrlOverride: string | undefined}- completeSelfDrivingOnboarding: () => {- value: true- }goToNextStep: () => {value: true}@@ -260,8 +253,6 @@ export const onboardingLogic = kea<onboardingLogicType>([['openSidePanel'],globalSetupLogic,['openGlobalSetup'],- onboardingEventUsageLogic,- ['reportSelfDrivingOnboardingCompleted'],],})),actions({@@ -274,9 +265,6 @@ export const onboardingLogic = kea<onboardingLogicType>([completeOnboarding: (options?: { redirectUrlOverride?: string }) => ({redirectUrlOverride: options?.redirectUrlOverride,}),- // 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.- completeSelfDrivingOnboarding: true,setSubscribedDuringOnboarding: (subscribedDuringOnboarding: boolean) => ({ subscribedDuringOnboarding }),setTeamPropertiesForProduct: (productKey: ProductKey) => ({ productKey }),setWaitForBilling: (waitForBilling: boolean) => ({ waitForBilling }),@@ -828,55 +816,6 @@ export const onboardingLogic = kea<onboardingLogicType>([lemonToast.error("Couldn't save onboarding progress. Please try again.")}},- completeSelfDrivingOnboarding: async () => {- // Idempotency guard — Finish can fire twice on a double-click.- if (values.isCompleting) {- return- }- actions.setIsCompleting(true)- const team = values.currentTeam- // The posthog-js install always backs product analytics; credit the extra context sources- // the user turned on so their products are marked onboarded (and intents recorded).- const products: ProductKey[] = [ProductKey.PRODUCT_ANALYTICS]- if (team?.session_recording_opt_in) {- products.push(ProductKey.SESSION_REPLAY)- }- if (team?.autocapture_exceptions_opt_in) {- products.push(ProductKey.ERROR_TRACKING)- }- if (team?.surveys_opt_in) {- products.push(ProductKey.SURVEYS)- }- 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.reportSelfDrivingOnboardingCompleted(productKey)- actions.recordProductIntentOnboardingComplete({ product_type: productKey })- }- // Persist both completion signals before navigating. updateCurrentTeam is not optimistic,- // so leaving early would race stale state and bounce a not-yet-ingested team back here.- const completedMap: Record<string, boolean> = { ...team?.has_completed_onboarding_for }- for (const productKey of products) {- completedMap[productKey] = true- }- try {- await teamLogic.asyncActions.updateCurrentTeam({- completed_snippet_onboarding: true,- has_completed_onboarding_for: completedMap,- })- // 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 {- // Always reset: the context flow has no productKey, so the updateCurrentTeam- // success/failure listeners below (gated on productKey) never clear it for us.- actions.setIsCompleting(false)- }- },skipOnboarding: () => {// Quick Start does not auto-open here. The button remains in the scene title// bar so users can open it manually. Auto-opening it conflicted with the welcomediff --git a/frontend/src/scenes/onboarding/legacy/productSelection/productSelectionLogic.ts b/frontend/src/scenes/onboarding/legacy/productSelection/productSelectionLogic.tsindex d6788adb6615..2ca00674fde7 100644--- a/frontend/src/scenes/onboarding/legacy/productSelection/productSelectionLogic.ts+++ b/frontend/src/scenes/onboarding/legacy/productSelection/productSelectionLogic.ts@@ -79,8 +79,12 @@ export interface productSelectionLogicActions {recommendationSource: stringselected: boolean} // eventUsageLogic- reportOnboardingStarted: (entrypoint: string) => {+ reportOnboardingStarted: (+ entrypoint: string,+ properties?: import('lib/utils/eventUsageLogic').OnboardingEventProperties | undefined+ ) => {entrypoint: string+ properties: import('lib/utils/eventUsageLogic').OnboardingEventProperties | undefined} // eventUsageLogicsetOnCompleteOnboardingRedirectUrl: (url: string | null) => {url: string | nulldiff --git a/frontend/src/scenes/onboarding/legacy/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx b/frontend/src/scenes/onboarding/legacy/sdks/OnboardingInstallStep/WizardInstallStep/index.tsxindex 07e47f856947..dd6c2f5ef0b1 100644--- a/frontend/src/scenes/onboarding/legacy/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx+++ b/frontend/src/scenes/onboarding/legacy/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx@@ -25,10 +25,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({ wizardOverrides }: { wizardOverrides?: WizardOverrides }): JSX.Element {- const { reportSelfDrivingOnboardingInstallModeSelected } = useActions(onboardingEventUsageLogic)+ const { reportOnboardingInstallModeSelected } = useActions(onboardingEventUsageLogic)return (<WizardInstallOptions- onModeSelected={reportSelfDrivingOnboardingInstallModeSelected}+ onModeSelected={reportOnboardingInstallModeSelected}// The cloud runner only executes the base integration program, not dedicated subcommands,// so a dedicated-program step neither offers a run nor lets one queued elsewhere take over.offerCloudRun={!wizardOverrides}diff --git a/frontend/src/scenes/onboarding/onboardingEventUsageLogic.ts b/frontend/src/scenes/onboarding/onboardingEventUsageLogic.tsindex 0b7098723b0e..e4c1fa107740 100644--- a/frontend/src/scenes/onboarding/onboardingEventUsageLogic.ts+++ b/frontend/src/scenes/onboarding/onboardingEventUsageLogic.ts@@ -3,37 +3,31 @@ import posthog from 'posthog-js'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import type { OnboardingEventProperties } from 'lib/utils/eventUsageLogic'import { resolveOnboardingFlowVariant } from './onboardingVariants'-/** 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'+export type SelfDrivingOnboardingStepId =+ | 'welcome'+ | 'goals'+ | 'tools'+ | 'install'+ | 'authorized-urls'+ | 'ai-observability'+ | 'billing'-// GROW-89: both onboarding flows fire the same funnel event names during the transition, told apart-// 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'}`.-// `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+export const SELF_DRIVING_ONBOARDING_EVENT_PROPS: OnboardingEventProperties = {+ version: 2,+ flow_variant: 'context_first',+}-/** Arm of the cloud-wizard AB test (GROW-117): `test` offers the cloud run, `control` is local-only. */export type CloudRunExperimentArm = 'control' | 'test'-/**- * The user's experiment arm, or null when they are not enrolled: an unset/boolean flag value (not- * rolled out, targeting excludes them, flags not loaded yet) must NOT be collapsed into `control`,- * or never-enrolled users pollute the control cohort and bias the readout toward "no effect".- */export function resolveCloudRunExperimentArm(featureFlags: FeatureFlagsSet): CloudRunExperimentArm | null {const value = featureFlags[FEATURE_FLAGS.ONBOARDING_WIZARD_CLOUD_RUN]return value === 'test' || value === 'control' ? value : null}-// Wizard-sync events fire from BOTH onboarding variants (GROW-121): same v2 event shape, but-// flow_variant reflects whichever flow the user is actually in, and the cloud-run experiment arm-// rides along (GROW-117) so downstream metrics can split on either without a flag-persons join.function wizardSyncEventProps(featureFlags: FeatureFlagsSet): {version: 2flow_variant: string@@ -46,10 +40,6 @@ function wizardSyncEventProps(featureFlags: FeatureFlagsSet): {}}-// Once-per-run guards for the completed-handoff funnel (exposure → CTA shown → CTA clicked). The-// same run renders on several surfaces (inline panel, FAB card, dialog) and those remount freely —-// deduping here, keyed by run, keeps the funnel's denominators honest without every surface-// carrying its own guard.const reportedHandoffShownRuns = new Set<string>()export function resetCloudRunExperimentExposureForTests(): void {@@ -63,7 +53,7 @@ export interface onboardingEventUsageLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface onboardingEventUsageLogicActions {- reportSelfDrivingOnboardingCloudRunCompleted: (props: {+ reportOnboardingCloudRunCompleted: (props: {durationSeconds: number | nullprOpened: booleanprUrl: string | null@@ -78,31 +68,31 @@ export interface onboardingEventUsageLogicActions {status: 'cancelled' | 'completed' | 'failed'taskId: string}- reportSelfDrivingOnboardingCloudRunQueued: (props: { repository: string; runId: string; taskId: string }) => {+ reportOnboardingCloudRunQueued: (props: { repository: string; runId: string; taskId: string }) => {repository: stringrunId: stringtaskId: string}- reportSelfDrivingOnboardingCompleted: (productKey: string) => {- productKey: string+ reportOnboardingGoalSelected: (goal: string) => {+ goal: string}- reportSelfDrivingOnboardingInstallModeSelected: (mode: 'cloud' | 'local') => {+ reportOnboardingInstallModeSelected: (mode: 'cloud' | 'local') => {mode: 'cloud' | 'local'}- reportSelfDrivingOnboardingPlanSelected: (plan: 'free' | 'pay_as_you_go') => {+ reportOnboardingPlanSelected: (plan: 'free' | 'pay_as_you_go') => {plan: 'free' | 'pay_as_you_go'}- reportSelfDrivingOnboardingStarted: () => {- value: true- }- reportSelfDrivingOnboardingStepCompleted: (stepId: SelfDrivingOnboardingStepId) => {+ reportOnboardingStepViewed: (stepId: SelfDrivingOnboardingStepId) => {stepId: SelfDrivingOnboardingStepId}- reportSelfDrivingOnboardingStepSkipped: (stepId: SelfDrivingOnboardingStepId) => {- stepId: SelfDrivingOnboardingStepId- }- reportSelfDrivingOnboardingStepViewed: (stepId: SelfDrivingOnboardingStepId) => {- stepId: SelfDrivingOnboardingStepId+ reportOnboardingUseCaseSelected: (+ useCase: string,+ recommendedProducts: readonly string[],+ properties?: OnboardingEventProperties+ ) => {+ properties: OnboardingEventProperties | undefined+ recommendedProducts: readonly string[]+ useCase: string}reportWizardSyncExpanded: (props: { mode: 'cloud' | 'local'; phase: string; runKey: string }) => {mode: 'cloud' | 'local'@@ -157,31 +147,27 @@ export type onboardingEventUsageLogicType = MakeLogicType<onboardingEventUsageLogicActions>-/**- * 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, plan, cloud- * run) get their own names.- */export const onboardingEventUsageLogic = kea<onboardingEventUsageLogicType>([path(['scenes', 'onboarding', 'onboardingEventUsageLogic']),connect(() => ({values: [featureFlagLogic, ['featureFlags']],})),actions({- 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.- reportSelfDrivingOnboardingCloudRunQueued: (props: { taskId: string; runId: string; repository: string }) =>- props,- reportSelfDrivingOnboardingCloudRunCompleted: (props: {+ reportOnboardingStepViewed: (stepId: SelfDrivingOnboardingStepId) => ({ stepId }),+ reportOnboardingGoalSelected: (goal: string) => ({ goal }),+ reportOnboardingUseCaseSelected: (+ useCase: string,+ recommendedProducts: readonly string[],+ properties?: OnboardingEventProperties+ ) => ({+ useCase,+ recommendedProducts,+ properties,+ }),+ reportOnboardingInstallModeSelected: (mode: 'cloud' | 'local') => ({ mode }),+ reportOnboardingPlanSelected: (plan: 'free' | 'pay_as_you_go') => ({ plan }),+ reportOnboardingCloudRunQueued: (props: { taskId: string; runId: string; repository: string }) => props,+ reportOnboardingCloudRunCompleted: (props: {taskId: stringrunId: stringstatus: 'completed' | 'failed' | 'cancelled'@@ -189,8 +175,6 @@ export const onboardingEventUsageLogic = kea<onboardingEventUsageLogicType>([prOpened: booleanprUrl: string | null}) => props,- // Engagement with the shared wizard sync surface (FAB card / launcher / dialog), fired for- // both variants and both run modes (GROW-121).reportWizardSyncExpanded: (props: { runKey: string; mode: 'cloud' | 'local'; phase: string }) => props,reportWizardSyncMinimized: (props: { runKey: string; mode: 'cloud' | 'local'; phase: string }) => props,reportWizardSyncRestored: (props: { runKey: string; mode: 'cloud' | 'local'; phase: string }) => props,@@ -200,9 +184,6 @@ export const onboardingEventUsageLogic = kea<onboardingEventUsageLogicType>([phase: stringelapsedSeconds: number}) => props,- // The completed-handoff funnel: exposure (a run's completed state rendered anywhere) and- // the handoff doc dialog opening. Exposure is deduped per run per pageload here, so- // surfaces can report unconditionally. No doc content — same rule as repo names.reportWizardSyncHandoffShown: (props: {runKey: stringmode: 'cloud' | 'local'@@ -216,62 +197,46 @@ export const onboardingEventUsageLogic = kea<onboardingEventUsageLogicType>([}) => props,}),listeners(({ values }) => ({- // The flow always enters at the welcome step, so `started` carries a fixed entry point- // (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',- ...SELF_DRIVING_ONBOARDING_EVENT_PROPS,- })- },- reportSelfDrivingOnboardingStepViewed: ({ stepId }) => {+ reportOnboardingStepViewed: ({ stepId }) => {posthog.capture('onboarding step viewed', {step_key: stepId,...SELF_DRIVING_ONBOARDING_EVENT_PROPS,})},- reportSelfDrivingOnboardingStepCompleted: ({ stepId }) => {- posthog.capture('onboarding step completed', {- step_key: stepId,- ...SELF_DRIVING_ONBOARDING_EVENT_PROPS,- })- },- reportSelfDrivingOnboardingStepSkipped: ({ stepId }) => {- posthog.capture('onboarding step skipped', {- step_key: stepId,+ reportOnboardingGoalSelected: ({ goal }) => {+ posthog.capture('onboarding goal selected', {+ goal,...SELF_DRIVING_ONBOARDING_EVENT_PROPS,})},- reportSelfDrivingOnboardingCompleted: ({ productKey }) => {- posthog.capture('onboarding completed', {- product_key: productKey,+ reportOnboardingUseCaseSelected: ({ useCase, recommendedProducts, properties }) => {+ posthog.capture('onboarding use case selected', {+ use_case: useCase,+ recommended_products: recommendedProducts,...SELF_DRIVING_ONBOARDING_EVENT_PROPS,+ ...properties,})},- reportSelfDrivingOnboardingInstallModeSelected: ({ mode }) => {+ reportOnboardingInstallModeSelected: ({ mode }) => {posthog.capture('onboarding install mode selected', {mode,...wizardSyncEventProps(values.featureFlags),})},- reportSelfDrivingOnboardingPlanSelected: ({ plan }) => {+ reportOnboardingPlanSelected: ({ plan }) => {posthog.capture('onboarding plan selected', {plan,...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.- reportSelfDrivingOnboardingCloudRunQueued: ({ taskId, runId }) => {+ reportOnboardingCloudRunQueued: ({ taskId, runId }) => {posthog.capture('onboarding cloud run queued', {task_id: taskId,run_id: runId,...wizardSyncEventProps(values.featureFlags),})},- reportSelfDrivingOnboardingCloudRunCompleted: ({ taskId, runId, status, durationSeconds, prOpened }) => {+ reportOnboardingCloudRunCompleted: ({ 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/RoughMark.tsx b/frontend/src/scenes/onboarding/self-driving/RoughMark.tsxnew file mode 100644index 000000000000..2bf928268522--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/RoughMark.tsx@@ -0,0 +1,50 @@+import { useEffect, useRef } from 'react'+import { annotate } from 'rough-notation'+import type { RoughAnnotation } from 'rough-notation/lib/model'++/**+ * Minimal port of posthog.com's RoughAnnotation wrapper (src/components/Code/RoughAnnotation.tsx)+ * for the hand-drawn highlight/squiggle treatments of the site's visual language. Draws on mount -+ * onboarding steps are short-lived cards, so no scroll observer.+ */+export function RoughMark({+ children,+ type,+ color,+ strokeWidth = 2,+ padding = 2,+ multiline = false,+ delay = 0,+}: {+ children: React.ReactNode+ type: 'underline' | 'highlight'+ color: string+ strokeWidth?: number+ padding?: number+ multiline?: boolean+ delay?: number+}): JSX.Element {+ const ref = useRef<HTMLSpanElement>(null)++ useEffect(() => {+ if (!ref.current) {+ return+ }+ const annotation: RoughAnnotation = annotate(ref.current, {+ type,+ color,+ strokeWidth,+ padding,+ multiline,+ iterations: 2,+ animationDuration: 800,+ })+ const timeout = window.setTimeout(() => annotation.show(), delay)+ return () => {+ window.clearTimeout(timeout)+ annotation.remove()+ }+ }, [type, color, strokeWidth, padding, multiline, delay])++ return <span ref={ref}>{children}</span>+}diff --git a/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboarding.scss b/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboarding.scssindex 74c173018ff1..d7e5685e47c9 100644--- a/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboarding.scss+++ b/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboarding.scss@@ -9,13 +9,17 @@// Unlike paper-desk (light-only), the base color lives here too so it can flip with the theme without// competing against a Tailwind `bg-*` utility's cascade layer.@media (min-width: 640px) {+ // Experiment: posthog.com's garden look - layered greens with a soft light well behind the+ // window, plus the same subtle dot grid in a darker green..OnboardingDottedBg {- background-color: #eef0e7;+ background-color: #b5cd8f;background-image:- radial-gradient(72% 72% at 50% 38%, rgb(247 165 1 / 5%), transparent 70%),- radial-gradient(rgb(17 17 17 / 5.5%) 1.4px, transparent 1.4px);- background-repeat: no-repeat, repeat;+ radial-gradient(80% 70% at 50% 30%, rgb(255 253 240 / 45%), transparent 70%),+ linear-gradient(180deg, #cfe0ae 0%, #b5cd8f 55%, #9dbb78 100%),+ radial-gradient(rgb(45 74 22 / 9%) 1.4px, transparent 1.4px);+ background-repeat: no-repeat, no-repeat, repeat;background-size:+ auto,auto,16px 16px;}@@ -30,11 +34,11 @@}}-// Use-case / product cards: a soft warm off-white inset on the white card (light) and the secondary-// surface in dark. Slightly darker than the card so they read as recessed tiles rather than bright-// white islands. Not gated by breakpoint: these are content, present at every width.+// Use-case / product cards: a translucent white wash over the cream card so the rows lift slightly+// without reading as stark white islands (light); the secondary surface in dark. Not gated by+// breakpoint: these are content, present at every width..OnboardingProductCard {- background-color: #f5f6ee;+ background-color: rgb(255 255 255 / 55%);}[theme='dark'] .OnboardingProductCard {diff --git a/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboarding.stories.tsx b/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboarding.stories.tsxnew file mode 100644index 000000000000..988cf8f193bb--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboarding.stories.tsx@@ -0,0 +1,46 @@+import type { Meta, StoryObj } from '@storybook/react'+import { router } from 'kea-router'++import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'++import { SelfDrivingOnboarding } from './SelfDrivingOnboarding'++const meta: Meta<typeof SelfDrivingOnboarding> = {+ title: 'Scenes-Other/Onboarding/Self-driving',+ component: SelfDrivingOnboarding,+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ },+ decorators: [mswDecorator({})],+ render: () => {+ router.actions.replace(urls.onboarding(), { step: 'goals' })+ return <SelfDrivingOnboarding />+ },+}++export default meta++type Story = StoryObj<typeof SelfDrivingOnboarding>++export const UseCasesLight: Story = {+ globals: { theme: 'light' },+ parameters: {+ testOptions: {+ skipDarkMode: true,+ waitForSelector: '[data-attr="self-driving-goal-improve_experience"]',+ },+ },+}++export const UseCasesDark: Story = {+ globals: { theme: 'dark' },+ parameters: {+ testOptions: {+ skipLightMode: true,+ waitForSelector: '[data-attr="self-driving-goal-improve_experience"]',+ },+ },+}diff --git a/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboardingFlow.tsx b/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboardingFlow.tsxindex 360e67208315..62136c700c7f 100644--- a/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboardingFlow.tsx+++ b/frontend/src/scenes/onboarding/self-driving/SelfDrivingOnboardingFlow.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import { useEffect, useState } from 'react'+import { useEffect, useMemo, useState } from 'react'import { IconArrowLeft, IconArrowRight } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'@@ -8,28 +8,32 @@ 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'+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'-// 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 {+ onboardingEventUsageLogic,+ SELF_DRIVING_ONBOARDING_EVENT_PROPS,+ type SelfDrivingOnboardingStepId,+} from '../onboardingEventUsageLogic'+import { resolveSetup } from '../shared/useCases'+import type { OnboardingExtraStepId, OnboardingUseCaseKey } from '../shared/useCases'+import { wizardSyncUiLogic } from '../shared/wizard-sync/wizardSyncUiLogic'+import { InstallationTrackerGate } from './components/InstallationTracker'+import { onboardingLogic } from './onboardingLogic'+import { RoughMark } from './RoughMark'+import { AIObservabilityStep } from './steps/AIObservabilityStep'+import { AuthorizedUrlsStep } from './steps/AuthorizedUrlsStep'import { BillingStep } from './steps/BillingStep'import { InstallStep } from './steps/InstallStep'+import { ToolsStep } from './steps/ToolsStep'+import { UseCasesStep } from './steps/UseCasesStep'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.- */+import { useCaseSelectionLogic } from './useCaseSelectionLogic'interface StepDef {id: SelfDrivingOnboardingStepIdtitle: string- Content: (props: { onContinue: () => void; completing: boolean }) => JSX.Element+ Content: (props: { onContinue: () => void; onSkip: () => void; completing: boolean }) => JSX.Elementskippable?: boolean/** Step provides its own primary action (e.g. plan picks), so suppress the footer Continue. */hideContinue?: boolean@@ -38,75 +42,131 @@ interface StepDef {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,+// The steps a use case can declare as `extraSteps` - only ones that need the user's own input.+const EXTRA_STEPS: Record<OnboardingExtraStepId, StepDef> = {+ 'authorized-urls': {+ id: 'authorized-urls',+ title: 'Add your website URLs',+ Content: AuthorizedUrlsStep,+ hideContinue: true,+ },+ 'ai-observability': {+ id: 'ai-observability',+ title: 'Instrument your AI app',+ Content: AIObservabilityStep,hideContinue: true,- maxWidth: 'max-w-3xl',+ maxWidth: 'max-w-2xl',},-]+}++function buildSteps(useCase: OnboardingUseCaseKey | null): StepDef[] {+ return [+ { id: 'welcome', title: '', Content: WelcomeStep },+ // The step id stays 'goals' so existing funnel queries continue to work.+ {+ id: 'goals',+ title: 'What do you want to get done first?',+ Content: UseCasesStep,+ hideContinue: true,+ maxWidth: 'max-w-2xl',+ },+ // The use case's tool collection is shown before install so the user knows what they are getting.+ {+ id: 'tools',+ title: 'Your tools',+ Content: ToolsStep,+ hideContinue: true,+ maxWidth: 'max-w-2xl',+ },+ { id: 'install', title: 'Install PostHog', Content: InstallStep },+ // The declared use case FILTERS what comes after install: only steps it can't reach its+ // finish line without. These steps render their own action zone, so the footer Continue is+ // suppressed.+ ...(resolveSetup(useCase).extraSteps ?? []).map((id) => EXTRA_STEPS[id]),+ {+ 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'+ 'relative w-full flex flex-col gap-5 overflow-hidden p-0 sm:max-h-[calc(100dvh-7rem)] sm:p-8 md:p-10 sm:bg-surface-primary sm:rounded-2xl sm:shadow-[0_16px_40px_rgb(30_50_10_/_25%)] sm:border sm:border-primary'export function SelfDrivingOnboardingFlow(): JSX.Element {- const { completeSelfDrivingOnboarding } = useActions(onboardingLogic)+ const { claimInlinePanel, releaseInlinePanel } = useActions(wizardSyncUiLogic)+ // The flow surfaces the run itself (install-step tracker, header pill), so claim the inline+ // panel for its whole lifetime - the corner FAB never appears during onboarding.+ useEffect(() => {+ claimInlinePanel('local')+ return () => releaseInlinePanel('local')+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [])+ const { completeOnboarding } = 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 { reportOnboardingStarted, reportOnboardingStepCompleted, reportOnboardingStepSkipped } =+ useActions(eventUsageLogic)+ const { reportOnboardingStepViewed } = useActions(onboardingEventUsageLogic)+ // The step list depends on the declared use case (persisted, so a refresh keeps the+ // conditional steps in place).+ const { selectedUseCase } = useValues(useCaseSelectionLogic)+ const steps = useMemo(() => buildSteps(selectedUseCase), [selectedUseCase])+ // Track the current step by id, not index, so use-case changes (which insert/remove steps)+ // can't shift the user onto a different step. 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 [stepId, setStepId] = useState<SelfDrivingOnboardingStepId>(() => {+ const fromUrl = steps.find((s) => s.id === router.values.searchParams['step'])+ return fromUrl?.id ?? 'welcome'})- const step = STEPS[stepIndex]+ // If the current step left the list (e.g. the goal changed and removed it), fall back to the+ // start rather than rendering nothing.+ const stepIndex = Math.max(+ 0,+ steps.findIndex((s) => s.id === stepId)+ )+ const step = steps[stepIndex]const isFirst = stepIndex === 0- const isLast = stepIndex === STEPS.length - 1+ 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()+ reportOnboardingStarted('welcome', SELF_DRIVING_ONBOARDING_EVENT_PROPS)}})useEffect(() => {- reportSelfDrivingOnboardingStepViewed(STEPS[stepIndex].id)- }, [stepIndex, reportSelfDrivingOnboardingStepViewed])+ reportOnboardingStepViewed(step.id)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [step.id, reportOnboardingStepViewed])// 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)+ const target = steps[index]+ if (!target) {+ return+ }+ setStepId(target.id)router.actions.replace(router.values.location.pathname, {...router.values.searchParams,- step: STEPS[index].id,+ step: target.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()+ // Marks onboarding complete (credits the sources turned on, plus the declared use+ // case's product) and navigates out, so sceneLogic doesn't bounce the user back in.+ completeOnboarding(selectedUseCase)return}goToStep(stepIndex + 1)@@ -115,11 +175,11 @@ export function SelfDrivingOnboardingFlow(): JSX.Element {// 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)+ reportOnboardingStepCompleted(step.id, undefined, SELF_DRIVING_ONBOARDING_EVENT_PROPS)advance()}const skipStep = (): void => {- reportSelfDrivingOnboardingStepSkipped(step.id)+ reportOnboardingStepSkipped(step.id, undefined, SELF_DRIVING_ONBOARDING_EVENT_PROPS)advance()}const goBack = (): void => goToStep(Math.max(0, stepIndex - 1))@@ -146,9 +206,9 @@ export function SelfDrivingOnboardingFlow(): JSX.Element {<divclassName="flex-1 flex items-center justify-center gap-1.5"role="group"- aria-label={`Step ${stepIndex + 1} of ${STEPS.length}`}+ aria-label={`Step ${stepIndex + 1} of ${steps.length}`}>- {STEPS.map((s, i) => (+ {steps.map((s, i) => (<divkey={s.id}className={`h-1.5 rounded-full transition-all ${@@ -157,14 +217,31 @@ export function SelfDrivingOnboardingFlow(): JSX.Element {/>))}</div>- <div className="w-8 shrink-0" />+ <div className="min-w-8 shrink-0 flex justify-end">+ {/* Past the install step, the run keeps a quiet presence up here; on the+ install step itself the tracker lives in the content. */}+ {stepIndex > steps.findIndex((s) => s.id === 'install') && <InstallationTrackerGate />}+ </div></div>- {step.title && <h1 className="text-2xl font-bold text-center m-0">{step.title}</h1>}+ {step.title && (+ <h1 className="text-2xl font-bold text-center m-0">+ {/* The hand-drawn squiggle from the website's section headers - only on the+ goals step, where the question is the hero. Keyed by title so the+ annotation is redrawn at the text's width (it only measures on mount). */}+ {step.id === 'goals' ? (+ <RoughMark key={step.title} type="underline" color="#f54e00" padding={4}>+ {step.title}+ </RoughMark>+ ) : (+ 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} />+ <step.Content onContinue={completeStep} onSkip={skipStep} completing={isLast && isCompleting} /></ScrollableShadows>{/* Pinned footer — omitted when the step has neither Skip nor a footer Continue (it suppliesdiff --git a/frontend/src/scenes/onboarding/self-driving/components/InstallationTracker.tsx b/frontend/src/scenes/onboarding/self-driving/components/InstallationTracker.tsxnew file mode 100644index 000000000000..84ba6b4287c1--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/components/InstallationTracker.tsx@@ -0,0 +1,105 @@+import { useActions, useMountedLogic, useValues } from 'kea'+import { useEffect } from 'react'++import { cn } from 'lib/utils/css-classes'+import { userLogic } from 'scenes/userLogic'++import { elapsedLabel, resolveStartedByLabel, syncHeadline, toneTextClass } from '../../shared/wizard-sync/helpers'+import { useRunElapsedSeconds } from '../../shared/wizard-sync/hooks'+import { installationProgressLogic } from '../../shared/wizard-sync/installationProgressLogic'+import { StatusGlyph } from '../../shared/wizard-sync/StatusGlyph'+import {+ watchWorkflowWhileMounted,+ wizardActiveSessionDetectorLogic,+} from '../../shared/wizard-sync/wizardActiveSessionDetectorLogic'+import { WizardSyncDialog } from '../../shared/wizard-sync/WizardSyncDialog'+import { wizardSyncUiLogic } from '../../shared/wizard-sync/wizardSyncUiLogic'+import { SELF_DRIVING_WORKFLOW_ID } from '../../shared/wizard-sync/workflows'++/**+ * The self-driving flow's in-card run tracker: a compact clickable summary of the wizard run that+ * opens the full progress dialog. `card` replaces the install step's command block while the run is+ * going; `pill` sits in the flow header on the steps after it. The onboarding shows the run through+ * these (and claims the inline panel), so the corner FAB never appears here.+ */+export function InstallationTracker({ variant }: { variant: 'card' | 'pill' }): JSX.Element | null {+ const { installationProgress, latestSession } = useValues(+ installationProgressLogic({ mode: 'local', workflowId: SELF_DRIVING_WORKFLOW_ID })+ )+ const { dialogOpen } = useValues(wizardSyncUiLogic)+ const { openDialog, closeDialog, openHandoffDoc } = useActions(wizardSyncUiLogic)+ const { user } = useValues(userLogic)++ const isTerminal = installationProgress.phase === 'completed' || installationProgress.phase === 'error'+ const elapsedSeconds = useRunElapsedSeconds(+ latestSession?.started_at,+ isTerminal ? latestSession?.updated_at : undefined+ )++ if (!installationProgress.isCurrent) {+ return null+ }++ const handoffText = installationProgress.handoffText+ const runKey = latestSession?.session_id+ const handleViewReport =+ handoffText && runKey ? () => openHandoffDoc({ key: runKey, text: handoffText }) : undefined++ return (+ <>+ {variant === 'card' ? (+ <button+ type="button"+ onClick={openDialog}+ data-attr="self-driving-installation-tracker-card"+ className="OnboardingProductCard w-full flex items-center gap-3 p-4 rounded-lg border text-left cursor-pointer transition-all hover:shadow-sm"+ >+ <StatusGlyph progress={installationProgress} />+ <div className="flex-1 min-w-0 flex flex-col gap-0.5">+ <span className="text-sm font-semibold">PostHog setup</span>+ <span className={cn('text-xs', toneTextClass(installationProgress))}>+ {syncHeadline(installationProgress)}+ </span>+ </div>+ <span className="text-xs text-muted tabular-nums shrink-0">{elapsedLabel(elapsedSeconds)}</span>+ </button>+ ) : (+ <button+ type="button"+ onClick={openDialog}+ aria-label="Show PostHog setup progress"+ data-attr="self-driving-installation-tracker-pill"+ className="flex items-center gap-1.5 rounded-full border bg-surface-primary pl-1.5 pr-2.5 py-1 hover:bg-fill-highlight-50 transition-colors cursor-pointer"+ >+ <StatusGlyph progress={installationProgress} />+ <span className="text-xs text-muted tabular-nums whitespace-nowrap">+ {elapsedLabel(elapsedSeconds)}+ </span>+ </button>+ )}+ <WizardSyncDialog+ progress={installationProgress}+ elapsedSeconds={elapsedSeconds}+ mode="local"+ isOpen={dialogOpen}+ onClose={closeDialog}+ onViewReport={handleViewReport}+ startedByLabel={resolveStartedByLabel(installationProgress.startedBy, user?.email)}+ />+ </>+ )+}++/**+ * Gate for surfaces that don't already stream the run (the flow header): opens the session stream+ * only once the cheap detector poll says a self-driving run is in flight.+ */+export function InstallationTrackerGate(): JSX.Element | null {+ useMountedLogic(wizardActiveSessionDetectorLogic)+ const { shouldStream, activeWorkflowId } = useValues(wizardActiveSessionDetectorLogic)+ useEffect(() => watchWorkflowWhileMounted(SELF_DRIVING_WORKFLOW_ID), [])+ if (!shouldStream || activeWorkflowId !== SELF_DRIVING_WORKFLOW_ID) {+ return null+ }+ return <InstallationTracker variant="pill" />+}diff --git a/frontend/src/scenes/onboarding/self-driving/components/PlanChoice.tsx b/frontend/src/scenes/onboarding/self-driving/components/PlanChoice.tsxindex 163d5a1f7bea..8d4e98e59672 100644--- a/frontend/src/scenes/onboarding/self-driving/components/PlanChoice.tsx+++ b/frontend/src/scenes/onboarding/self-driving/components/PlanChoice.tsx@@ -31,7 +31,7 @@ export function PlanChoice({completing: boolean}): JSX.Element {const { startPaymentEntryFlow } = useActions(paymentEntryLogic)- const { reportSelfDrivingOnboardingPlanSelected } = useActions(onboardingEventUsageLogic)+ const { reportOnboardingPlanSelected } = 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)@@ -43,12 +43,12 @@ export function PlanChoice({// 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')+ reportOnboardingPlanSelected('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')+ reportOnboardingPlanSelected('free')onContinue()}diff --git a/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingInstallOptions.tsx b/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingInstallOptions.tsxindex 68ad8a5215e3..fb06d19af023 100644--- a/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingInstallOptions.tsx+++ b/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingInstallOptions.tsx@@ -1,19 +1,51 @@-import { useActions } from 'kea'+import { useActions, useValues } from 'kea'import { IconCheckCircle } from '@posthog/icons'-import { LemonButton } from '@posthog/lemon-ui'+import { LemonButton, Link } 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 { useLocalWizardRunActive } from 'scenes/onboarding/shared/wizard-sync/hooks'import { WizardCommandBlock } from 'scenes/onboarding/shared/wizard-sync/WizardCommandBlock'import { WizardInstallOptions } from 'scenes/onboarding/shared/wizard-sync/WizardInstallOptions'+import { SELF_DRIVING_WORKFLOW_ID } from 'scenes/onboarding/shared/wizard-sync/workflows'++import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'++import { DOCS_URL_BY_PRODUCT_PATH, ONBOARDING_TOOLS, resolveSetup, toolIconType } from '../../shared/useCases'+import { useCaseSelectionLogic } from '../useCaseSelectionLogic'+import { InstallationTracker } from './InstallationTracker'++/** A quiet reminder of what the install feeds: the use case's tools, as icons and names. */+function ProductsBeingInstalled(): JSX.Element {+ const { selectedUseCase } = useValues(useCaseSelectionLogic)+ const tools = resolveSetup(selectedUseCase).tools.map((key) => ONBOARDING_TOOLS[key])+ return (+ <div className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-xs text-muted">+ <span>Tools for your setup:</span>+ {tools.map((tool) => (+ <Link+ key={tool.productPath}+ to={DOCS_URL_BY_PRODUCT_PATH[tool.productPath]}+ target="_blank"+ className="flex items-center gap-1 text-muted hover:text-default"+ >+ <span className="flex text-sm group/colorful-product-icons colorful-product-icons-true">+ {iconForType(toolIconType(tool))}+ </span>+ {tool.displayName ?? tool.productPath}+ </Link>+ ))}+ </div>+ )+}/** 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',+ 'Connects GitHub so agents can open pull requests',+ 'Chooses signal sources and scouts to watch',+ 'Sends findings to the Inbox',]// The self-driving run is interactive: it asks about your issue tracker, walks you through the@@ -22,7 +54,10 @@ const WIZARD_SETS_UP = [// being left to the experiment flag.export function SelfDrivingInstallOptions({ onContinue }: { onContinue: () => void }): JSX.Element {const { isCloudOrDev } = useWizardCommand()- const { reportSelfDrivingOnboardingInstallModeSelected } = useActions(onboardingEventUsageLogic)+ const { reportOnboardingInstallModeSelected } = useActions(onboardingEventUsageLogic)+ // Once the CLI registers a run, the command block and its caption give way to the tracker -+ // the command has been run, so repeating it is noise.+ const isRunActive = useLocalWizardRunActive(SELF_DRIVING_WORKFLOW_ID)// 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.@@ -43,19 +78,27 @@ export function SelfDrivingInstallOptions({ onContinue }: { onContinue: () => voreturn (<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.+ Run this command in your project. The setup agent connects GitHub, chooses signal sources, and+ configures scouts.</p><WizardInstallOptionshideHogofferCloudRun={false}onQueued={onContinue}- onModeSelected={reportSelfDrivingOnboardingInstallModeSelected}+ onModeSelected={reportOnboardingInstallModeSelected}localBlock={- <WizardCommandBlock- hideHog- subcommand="self-driving"- description="Takes about ten minutes. It'll ask you a few things along the way."- />+ <div className="flex flex-col gap-2">+ {isRunActive ? (+ <InstallationTracker variant="card" />+ ) : (+ <WizardCommandBlock+ hideHog+ subcommand="self-driving"+ description="Takes about ten minutes. It'll ask you a few things along the way."+ />+ )}+ <ProductsBeingInstalled />+ </div>}/><CheckListdiff --git a/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingPricing.tsx b/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingPricing.tsxindex f459b8703643..cbc640ed07aa 100644--- a/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingPricing.tsx+++ b/frontend/src/scenes/onboarding/self-driving/components/SelfDrivingPricing.tsx@@ -18,7 +18,7 @@ export function SelfDrivingPricing({ product }: { product: BillingProductV2Typeconst perPr = pricePerPrUsd(product)return (- <div className="w-full flex flex-col gap-3 p-4 rounded-lg border border-accent bg-accent-highlight">+ <div className="OnboardingProductCard w-full flex flex-col gap-3 p-4 rounded-lg border"><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">diff --git a/frontend/src/scenes/onboarding/self-driving/components/SubscribedState.tsx b/frontend/src/scenes/onboarding/self-driving/components/SubscribedState.tsxindex e07aa83ce9f0..751958874e8e 100644--- a/frontend/src/scenes/onboarding/self-driving/components/SubscribedState.tsx+++ b/frontend/src/scenes/onboarding/self-driving/components/SubscribedState.tsx@@ -18,7 +18,7 @@ export function SubscribedState({</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+ Go to the Inbox</LemonButton></div>)diff --git a/frontend/src/scenes/onboarding/self-driving/onboardingLogic.test.ts b/frontend/src/scenes/onboarding/self-driving/onboardingLogic.test.tsnew file mode 100644index 000000000000..b9cb94954313--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/onboardingLogic.test.ts@@ -0,0 +1,209 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { teamLogic } from 'scenes/teamLogic'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { useMocks } from '~/mocks/jest'+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { onboardingLogic } from './onboardingLogic'+import { useCaseSelectionLogic } from './useCaseSelectionLogic'++describe('onboardingLogic', () => {+ let logic: ReturnType<typeof onboardingLogic.build>++ beforeEach(() => {+ localStorage.clear()+ useMocks({+ get: {+ '/api/environments/:team_id/user_product_list': async () => [200, { results: [], count: 0 }],+ },+ patch: {+ '/api/environments/:team_id/': async ({ request }) => [+ 200,+ { ...MOCK_DEFAULT_TEAM, ...((await request.json()) as Record<string, unknown>) },+ ],+ '/api/environments/:team_id/add_product_intent/': async () => [200, { product_intents: [] }],+ '/api/environments/:team_id/complete_product_onboarding': async () => [200, { product_intents: [] }],+ },+ })+ initKeaTests()+ logic = onboardingLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('persists both onboarding completion signals', async () => {+ await expectLogic(logic, () => {+ logic.actions.completeOnboarding()+ }).toDispatchActions([+ (action) => {+ if (action.type !== logic.actionTypes.updateCurrentTeam) {+ return false+ }+ if (!action.payload.completed_snippet_onboarding) {+ return false+ }+ expect(action.payload).toMatchObject({+ completed_snippet_onboarding: true,+ has_completed_onboarding_for: { [ProductKey.PRODUCT_ANALYTICS]: true },+ })+ return true+ },+ ])+ })++ it('short-circuits when a completion is already in flight', async () => {+ logic.actions.setIsCompleting(true)+ await expectLogic(logic, () => {+ logic.actions.completeOnboarding()+ }).toNotHaveDispatchedActions(['updateCurrentTeam'])+ })++ it('sets the selected tools required options before completing onboarding', async () => {+ const updates: Record<string, unknown>[] = []+ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ session_recording_masking_config: null,+ })+ useMocks({+ patch: {+ '/api/environments/:team_id/': async ({ request }) => {+ const update = (await request.json()) as Record<string, unknown>+ updates.push(update)+ return [200, { ...MOCK_DEFAULT_TEAM, ...update }]+ },+ },+ })++ await logic.asyncActions.completeOnboarding('find_problems')++ expect(updates).toEqual(+ expect.arrayContaining([+ {+ autocapture_exceptions_opt_in: true,+ },+ {+ session_recording_opt_in: true,+ session_recording_masking_config: { maskAllInputs: true },+ capture_console_log_opt_in: true,+ capture_performance_opt_in: true,+ },+ ])+ )+ })++ it('records each selected product once and persists completion last', async () => {+ let addIntentRequests = 0+ let customProductLoads = 0+ const intents: { intent_context: ProductIntentContext; product_type: ProductKey }[] = []+ const writes: string[] = []+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, surveys_opt_in: true })+ useMocks({+ get: {+ '/api/environments/:team_id/user_product_list': () => {+ customProductLoads+++ return [200, { results: [], count: 0 }]+ },+ },+ patch: {+ '/api/environments/:team_id/': async ({ request }) => {+ const update = (await request.json()) as Record<string, unknown>+ if (update.completed_snippet_onboarding) {+ writes.push('completion')+ }+ return [200, { ...MOCK_DEFAULT_TEAM, ...update }]+ },+ '/api/environments/:team_id/add_product_intent/': () => {+ addIntentRequests+++ return [200, { product_intents: [] }]+ },+ '/api/environments/:team_id/complete_product_onboarding': async ({ request }) => {+ const intent = (await request.json()) as {+ intent_context: ProductIntentContext+ product_type: ProductKey+ }+ intents.push(intent)+ writes.push(`intent:${intent.product_type}`)+ return [200, { ...MOCK_DEFAULT_TEAM, product_intents: [] }]+ },+ },+ })+ useCaseSelectionLogic.actions.selectUseCase('find_problems')++ await logic.asyncActions.completeOnboarding('find_problems')++ expect(addIntentRequests).toBe(0)+ expect(intents).toHaveLength(6)+ expect(new Set(intents.map(({ product_type }) => product_type)).size).toBe(6)+ expect(intents).not.toContainEqual(expect.objectContaining({ product_type: ProductKey.SURVEYS }))+ expect(intents).toEqual(+ expect.arrayContaining([+ {+ product_type: ProductKey.ERROR_TRACKING,+ intent_context: ProductIntentContext.ONBOARDING_PRODUCT_SELECTED_PRIMARY,+ },+ {+ product_type: ProductKey.SESSION_REPLAY,+ intent_context: ProductIntentContext.ONBOARDING_PRODUCT_SELECTED_SECONDARY,+ },+ {+ product_type: ProductKey.CONVERSATIONS,+ intent_context: ProductIntentContext.ONBOARDING_PRODUCT_SELECTED_SECONDARY,+ },+ ])+ )+ expect(customProductLoads).toBe(1)+ expect(writes.at(-1)).toBe('completion')+ expect(useCaseSelectionLogic.values.selectedUseCase).toBeNull()+ })++ it('reports onboarding completion once with the shared event schema', async () => {+ const capture = jest.spyOn(posthog, 'capture')++ await logic.asyncActions.completeOnboarding('find_problems')++ expect(capture.mock.calls.filter(([event]) => event === 'onboarding completed')).toEqual([+ [+ 'onboarding completed',+ {+ product_key: ProductKey.ERROR_TRACKING,+ version: 2,+ flow_variant: 'context_first',+ },+ ],+ ])+ capture.mockRestore()+ })++ it('does not persist completion when a product intent request fails', async () => {+ let completionUpdates = 0+ silenceKeaLoadersErrors()+ useMocks({+ patch: {+ '/api/environments/:team_id/': async ({ request }) => {+ const update = (await request.json()) as Record<string, unknown>+ if (update.completed_snippet_onboarding) {+ completionUpdates+++ }+ return [200, { ...MOCK_DEFAULT_TEAM, ...update }]+ },+ '/api/environments/:team_id/complete_product_onboarding': () => [500, {}],+ },+ })++ try {+ await logic.asyncActions.completeOnboarding('find_problems')+ expect(completionUpdates).toBe(0)+ } finally {+ resumeKeaLoadersErrors()+ }+ })+})diff --git a/frontend/src/scenes/onboarding/self-driving/onboardingLogic.ts b/frontend/src/scenes/onboarding/self-driving/onboardingLogic.tsnew file mode 100644index 000000000000..a12937962ccf--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/onboardingLogic.ts@@ -0,0 +1,190 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'+import { router } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import { eventUsageLogic, type OnboardingEventProperties } from 'lib/utils/eventUsageLogic'+import { completeProductOnboarding, teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { customProductsLogic } from '~/layout/panel-layout/ProjectTree/customProductsLogic'+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import type { TeamPublicType, TeamType } from '~/types'++import { SELF_DRIVING_ONBOARDING_EVENT_PROPS } from '../onboardingEventUsageLogic'+import { optionsForSetup, productKeysForSetup, resolveSetup } from '../shared/useCases'+import type { TeamOption } from '../shared/useCases'+import type { OnboardingUseCaseKey } from '../shared/useCases'+import { useCaseSelectionLogic } from './useCaseSelectionLogic'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface onboardingLogicValues {+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ isCompleting: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface onboardingLogicActions {+ loadCustomProducts: () => any // customProductsLogic+ reportOnboardingCompleted: (+ productKey: string,+ properties?: OnboardingEventProperties | undefined+ ) => {+ productKey: string+ properties: OnboardingEventProperties | undefined+ } // eventUsageLogic+ updateCurrentTeam: (payload: Partial<TeamType>) => Partial<TeamType> // teamLogic+ clearUseCase: () => {+ value: true+ } // useCaseSelectionLogic+ completeOnboarding: (useCase?: OnboardingUseCaseKey | null) => {+ useCase: OnboardingUseCaseKey | null+ }+ setIsCompleting: (isCompleting: boolean) => {+ isCompleting: boolean+ }+}++export type onboardingLogicType = MakeLogicType<onboardingLogicValues, onboardingLogicActions>++function completedOnboardingMap(+ team: TeamPublicType | TeamType | null,+ products: ProductKey[]+): Record<string, boolean> {+ const completedMap: Record<string, boolean> = { ...team?.has_completed_onboarding_for }+ for (const productKey of products) {+ completedMap[productKey] = true+ }+ return completedMap+}++function optionsPayload(team: TeamPublicType | TeamType | null, options: TeamOption[]): Partial<TeamType> {+ return {+ ...(options.includes('session_recording') ? { session_recording_opt_in: true } : {}),+ ...(options.includes('replay_masking_floor') && team?.session_recording_masking_config == null+ ? { session_recording_masking_config: { maskAllInputs: true } }+ : {}),+ ...(options.includes('exception_autocapture') ? { autocapture_exceptions_opt_in: true } : {}),+ ...(options.includes('web_vitals') ? { autocapture_web_vitals_opt_in: true } : {}),+ ...(options.includes('console_log_capture') ? { capture_console_log_opt_in: true } : {}),+ ...(options.includes('network_performance') ? { capture_performance_opt_in: true } : {}),+ ...(options.includes('heatmaps') ? { heatmaps_opt_in: true } : {}),+ ...(options.includes('dead_clicks') ? { capture_dead_clicks: true } : {}),+ }+}++export const onboardingLogic = kea<onboardingLogicType>([+ path(['scenes', 'onboarding', 'self-driving', 'onboardingLogic']),++ connect(() => ({+ values: [teamLogic, ['currentTeam']],+ actions: [+ teamLogic,+ ['updateCurrentTeam'],+ customProductsLogic,+ ['loadCustomProducts'],+ useCaseSelectionLogic,+ ['clearUseCase'],+ eventUsageLogic,+ ['reportOnboardingCompleted'],+ ],+ })),++ actions({+ completeOnboarding: (useCase?: OnboardingUseCaseKey | null) => ({ useCase: useCase ?? null }),+ setIsCompleting: (isCompleting: boolean) => ({ isCompleting }),+ }),++ reducers({+ isCompleting: [+ false,+ {+ setIsCompleting: (_, { isCompleting }) => isCompleting,+ },+ ],+ }),++ listeners(({ actions, values }) => ({+ completeOnboarding: async ({ useCase }) => {+ if (values.isCompleting) {+ return+ }+ actions.setIsCompleting(true)+ const team = values.currentTeam+ const setup = resolveSetup(useCase)+ const products = productKeysForSetup(setup)+ const options = optionsForSetup(setup)+ const needsReplayAdminSetup =+ options.includes('replay_masking_floor') && team?.session_recording_masking_config == null+ try {+ if (!team) {+ throw new Error('Current team is not loaded')+ }+ const {+ session_recording_opt_in,+ session_recording_masking_config,+ capture_console_log_opt_in,+ capture_performance_opt_in,+ heatmaps_opt_in,+ capture_dead_clicks,+ ...otherOptions+ } = optionsPayload(team, options)+ const memberOptions = needsReplayAdminSetup+ ? otherOptions+ : {+ ...otherOptions,+ ...(session_recording_opt_in ? { session_recording_opt_in } : {}),+ }+ if (Object.keys(memberOptions).length > 0) {+ await teamLogic.asyncActions.updateCurrentTeam(memberOptions)+ }+ const adminOptions = needsReplayAdminSetup+ ? {+ ...(session_recording_opt_in ? { session_recording_opt_in } : {}),+ session_recording_masking_config,+ capture_console_log_opt_in,+ capture_performance_opt_in,+ heatmaps_opt_in,+ capture_dead_clicks,+ }+ : {+ session_recording_masking_config,+ capture_console_log_opt_in,+ capture_performance_opt_in,+ heatmaps_opt_in,+ capture_dead_clicks,+ }+ if (Object.values(adminOptions).some(Boolean)) {+ try {+ await teamLogic.asyncActions.updateCurrentTeam(adminOptions)+ } catch {+ lemonToast.warning('Some settings could not be enabled. An admin can finish them later.')+ }+ }+ await Promise.all(+ products.map((productKey) =>+ completeProductOnboarding(team.id, {+ product_type: productKey,+ intent_context:+ productKey === setup.primaryProduct+ ? ProductIntentContext.ONBOARDING_PRODUCT_SELECTED_PRIMARY+ : ProductIntentContext.ONBOARDING_PRODUCT_SELECTED_SECONDARY,+ })+ )+ )+ actions.loadCustomProducts()+ await teamLogic.asyncActions.updateCurrentTeam({+ completed_snippet_onboarding: true,+ has_completed_onboarding_for: completedOnboardingMap(team, products),+ })+ actions.clearUseCase()+ actions.reportOnboardingCompleted(setup.primaryProduct, SELF_DRIVING_ONBOARDING_EVENT_PROPS)+ router.actions.push(urls.inbox())+ } catch {+ lemonToast.error("Couldn't finish onboarding. Please try again.")+ } finally {+ actions.setIsCompleting(false)+ }+ },+ })),+])diff --git a/frontend/src/scenes/onboarding/self-driving/steps/AIObservabilityStep.tsx b/frontend/src/scenes/onboarding/self-driving/steps/AIObservabilityStep.tsxnew file mode 100644index 000000000000..65a887ba166f--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/steps/AIObservabilityStep.tsx@@ -0,0 +1,56 @@+import { useState } from 'react'++import { LemonButton, LemonSelect } from '@posthog/lemon-ui'++import { AIObservabilitySDKInstructions } from 'scenes/onboarding/legacy/sdks/ai-observability/AIObservabilitySDKInstructions'+import { ALL_SDKS } from 'scenes/onboarding/legacy/sdks/allSDKs'++import { SDKKey } from '~/types'++const PROVIDER_OPTIONS = Object.keys(AIObservabilitySDKInstructions).map((key) => ({+ value: key as SDKKey,+ label: ALL_SDKS.find((sdk) => sdk.key === key)?.name ?? key,+}))++/**+ * Goal-conditional step for `maintain_ai`: the generic wizard install doesn't wire LLM instrumentation,+ * so this step carries the per-provider instructions. The goal's finish line is the first AI+ * traces coming in.+ */+export function AIObservabilityStep({+ onContinue,+ onSkip,+}: {+ onContinue: () => void+ onSkip: () => void+}): JSX.Element {+ const [provider, setProvider] = useState<SDKKey>(SDKKey.OPENAI)+ const Instructions = AIObservabilitySDKInstructions[provider]++ return (+ <div className="flex flex-col gap-5">+ <div className="flex items-center justify-center gap-2">+ <span className="text-secondary text-sm">My AI app uses</span>+ <LemonSelect+ size="small"+ value={provider}+ onChange={(value) => value && setProvider(value)}+ options={PROVIDER_OPTIONS}+ />+ </div>+ {Instructions && (+ <div className="border rounded p-4 text-left">+ <Instructions />+ </div>+ )}+ <div className="flex flex-col items-center gap-1 pt-2">+ <LemonButton type="primary" status="alt" onClick={onContinue}>+ Continue+ </LemonButton>+ <LemonButton type="tertiary" size="small" onClick={onSkip}>+ Skip for now+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/steps/AuthorizedUrlsStep.tsx b/frontend/src/scenes/onboarding/self-driving/steps/AuthorizedUrlsStep.tsxnew file mode 100644index 000000000000..e78d90a4765f--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/steps/AuthorizedUrlsStep.tsx@@ -0,0 +1,58 @@+import { useValues } from 'kea'++import { LemonBanner, LemonButton } from '@posthog/lemon-ui'++import { AuthorizedUrlList } from 'lib/components/AuthorizedUrlList/AuthorizedUrlList'+import { AuthorizedUrlListType, authorizedUrlListLogic } from 'lib/components/AuthorizedUrlList/authorizedUrlListLogic'++const AUTHORIZED_URL_LOGIC_PROPS = {+ actionId: null,+ experimentId: null,+ productTourId: null,+ type: AuthorizedUrlListType.WEB_ANALYTICS,+ allowWildCards: false,+} as const++/**+ * Goal-conditional step for `improve_experience`: web analytics breaks traffic down by authorized+ * URL, so the goal's finish line (a live dashboard) needs at least one. Wildcards are off - the+ * URL must be concrete so the toolbar and agents can open the site.+ */+export function AuthorizedUrlsStep({+ onContinue,+ onSkip,+}: {+ onContinue: () => void+ onSkip: () => void+}): JSX.Element {+ const { authorizedUrls } = useValues(authorizedUrlListLogic(AUTHORIZED_URL_LOGIC_PROPS))++ return (+ <div className="flex flex-col gap-5">+ <p className="text-secondary text-center m-0">+ Add each full URL where your site runs. Web analytics uses these URLs to show where your traffic comes+ from.+ </p>+ <LemonBanner type="info">Include https:// in each URL. Wildcards are not supported.</LemonBanner>+ <AuthorizedUrlList+ type={AuthorizedUrlListType.WEB_ANALYTICS}+ allowWildCards={false}+ hideEmptyState+ showLaunch={false}+ />+ <div className="flex flex-col items-center gap-1 pt-2">+ <LemonButton+ type="primary"+ status="alt"+ onClick={onContinue}+ disabledReason={authorizedUrls.length === 0 ? 'Add at least one URL' : null}+ >+ Continue+ </LemonButton>+ <LemonButton type="tertiary" size="small" onClick={onSkip}>+ Skip for now+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/steps/BillingStep.tsx b/frontend/src/scenes/onboarding/self-driving/steps/BillingStep.tsxindex 45c6cdda9af8..6b40943d744d 100644--- a/frontend/src/scenes/onboarding/self-driving/steps/BillingStep.tsx+++ b/frontend/src/scenes/onboarding/self-driving/steps/BillingStep.tsx@@ -46,7 +46,7 @@ export function BillingStep({ onContinue, completing }: { onContinue: () => voidSee pricing</LemonButton><LemonButton type="primary" status="alt" onClick={onContinue} loading={completing}>- Go to your inbox+ Go to the Inbox</LemonButton></div></div>diff --git a/frontend/src/scenes/onboarding/self-driving/steps/InstallStep.tsx b/frontend/src/scenes/onboarding/self-driving/steps/InstallStep.tsxindex 74236adcb017..7179a0c64e1a 100644--- a/frontend/src/scenes/onboarding/self-driving/steps/InstallStep.tsx+++ b/frontend/src/scenes/onboarding/self-driving/steps/InstallStep.tsx@@ -1,24 +1,10 @@-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.+ * 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. Once the CLI+ * registers a run, the install options swap the command block for the compact tracker.*/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} />- )+ return <SelfDrivingInstallOptions onContinue={onContinue} />}diff --git a/frontend/src/scenes/onboarding/self-driving/steps/ToolsStep.tsx b/frontend/src/scenes/onboarding/self-driving/steps/ToolsStep.tsxnew file mode 100644index 000000000000..ed0731ef8bb0--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/steps/ToolsStep.tsx@@ -0,0 +1,129 @@+import { useValues } from 'kea'++import { LemonButton, LemonTag, Link } from '@posthog/lemon-ui'++import { toSentenceCase } from 'scenes/onboarding/shared/utils'++import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'+import { getTreeItemsProducts } from '~/products'++import {+ ADDITIONAL_TOOL_DETAILS,+ DOCS_URL_BY_PRODUCT_PATH,+ ONBOARDING_TOOLS,+ resolveSetup,+ toolIconType,+} from '../../shared/useCases'+import { useCaseSelectionLogic } from '../useCaseSelectionLogic'++export function ToolsStep({ onContinue }: { onContinue: () => void }): JSX.Element {+ const { selectedUseCase } = useValues(useCaseSelectionLogic)++ const setup = resolveSetup(selectedUseCase)+ const setupTools = setup.tools.map((key) => ONBOARDING_TOOLS[key])+ const setupProductKeys = new Set(setupTools.map((tool) => tool.productKey))+ const tools = [+ ...setupTools.map((tool) => ({+ productKey: tool.productKey,+ name: tool.displayName ?? tool.productPath,+ description: tool.benefit,+ docsUrl: DOCS_URL_BY_PRODUCT_PATH[tool.productPath],+ iconType: toolIconType(tool),+ })),+ ...(setup.additionalTools ?? [])+ .filter((productKey) => !setupProductKeys.has(productKey))+ .map((productKey) => {+ const productItem = getTreeItemsProducts().find((item) => item.intents?.includes(productKey))+ const details = ADDITIONAL_TOOL_DETAILS[productKey]+ const tool = {+ name: productItem?.path ?? productKey,+ description: details?.description ?? '',+ }+ return {+ productKey,+ name: toSentenceCase(tool.name),+ description: tool.description,+ docsUrl: details?.docsUrl ?? DOCS_URL_BY_PRODUCT_PATH[tool.name],+ iconType: productItem?.iconType ?? 'product_analytics',+ }+ }),+ ]+ // The setup's sidebar extras, resolved the same way the backend populates the sidebar:+ // through the products registry's `intents`. Tools already shown above are excluded.+ const shownNames = new Set(tools.map((tool) => tool.name))+ const sidebarExtras = getTreeItemsProducts().filter(+ (item) =>+ item.intents?.some((intent) => setup.sidebarExtras.includes(intent)) &&+ typeof item.path === 'string' &&+ !shownNames.has(item.path)+ )++ return (+ <div className="flex flex-col gap-6 py-1">+ <p className="text-secondary text-center m-0">+ These tools will feed your agents after setup finishes. You can change them later in settings.+ </p>+ <div className="flex flex-col gap-3">+ {tools.map((tool) => {+ const iconType = tool.iconType+ const colorVar = `var(--color-product-${iconType.replace(/_/g, '-')}-light)`+ return (+ <div+ key={tool.productKey}+ className="OnboardingProductCard flex items-start gap-4 p-4 rounded-lg border"+ >+ <div+ className="size-12 shrink-0 rounded-lg flex items-center justify-center"+ style={{ background: `color-mix(in srgb, ${colorVar} 12%, transparent)` }}+ >+ <div className="flex *:text-2xl group/colorful-product-icons colorful-product-icons-true">+ {iconForType(iconType)}+ </div>+ </div>+ <div className="flex-1 flex flex-col gap-1 min-w-0">+ <div className="font-semibold text-base">{tool.name}</div>+ <div className="text-sm text-secondary text-balance">{tool.description}</div>+ <Link to={tool.docsUrl} target="_blank" className="text-sm w-fit">+ Read the docs+ </Link>+ </div>+ </div>+ )+ })}+ </div>+ {sidebarExtras.length > 0 && (+ <div className="flex flex-wrap items-center justify-center gap-2">+ <span className="text-xs text-muted">Also in your sidebar:</span>+ {sidebarExtras.map((item) => {+ const tag = (+ <LemonTag+ icon={+ item.iconType ? (+ <span className="flex group/colorful-product-icons colorful-product-icons-true">+ {iconForType(item.iconType)}+ </span>+ ) : undefined+ }+ >+ {item.path}+ </LemonTag>+ )+ const docsUrl = DOCS_URL_BY_PRODUCT_PATH[item.path]+ return docsUrl ? (+ <Link key={item.path} to={docsUrl} target="_blank">+ {tag}+ </Link>+ ) : (+ <span key={item.path}>{tag}</span>+ )+ })}+ </div>+ )}+ <div className="flex justify-center">+ <LemonButton type="primary" status="alt" onClick={onContinue}>+ Continue+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/steps/UseCasesStep.test.tsx b/frontend/src/scenes/onboarding/self-driving/steps/UseCasesStep.test.tsxnew file mode 100644index 000000000000..01f2a4bdf582--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/steps/UseCasesStep.test.tsx@@ -0,0 +1,53 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import posthog from 'posthog-js'++import { initKeaTests } from '~/test/init'++import { SELF_DRIVING_ONBOARDING_EVENT_PROPS } from '../../onboardingEventUsageLogic'+import { productKeysForSetup, resolveSetup } from '../../shared/useCases'+import { useCaseSelectionLogic } from '../useCaseSelectionLogic'+import { UseCasesStep } from './UseCasesStep'++describe('UseCasesStep', () => {+ let logic: ReturnType<typeof useCaseSelectionLogic.build>++ beforeEach(() => {+ localStorage.clear()+ initKeaTests(false)+ logic = useCaseSelectionLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ cleanup()+ })++ it('clears the previous use case before continuing without one', () => {+ logic.actions.selectUseCase('find_problems')+ const onSkip = jest.fn()++ render(<UseCasesStep onContinue={jest.fn()} onSkip={onSkip} />)+ fireEvent.click(screen.getByText('Continue without choosing a goal'))++ expect(logic.values.selectedUseCase).toBeNull()+ expect(onSkip).toHaveBeenCalledTimes(1)+ })++ it('reports the selected use case with the self-driving event schema', () => {+ const capture = jest.spyOn(posthog, 'capture')++ logic.actions.selectUseCase('find_problems')++ expect(capture.mock.calls).toContainEqual([+ 'onboarding use case selected',+ {+ use_case: 'find_problems',+ recommended_products: productKeysForSetup(resolveSetup('find_problems')),+ ...SELF_DRIVING_ONBOARDING_EVENT_PROPS,+ },+ ])++ capture.mockRestore()+ })+})diff --git a/frontend/src/scenes/onboarding/self-driving/steps/UseCasesStep.tsx b/frontend/src/scenes/onboarding/self-driving/steps/UseCasesStep.tsxnew file mode 100644index 000000000000..7977f2c65346--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/steps/UseCasesStep.tsx@@ -0,0 +1,63 @@+import { useActions } from 'kea'++import { LemonButton } from '@posthog/lemon-ui'++import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'++import { ONBOARDING_USE_CASES } from '../../shared/useCases'+import { useCaseSelectionLogic } from '../useCaseSelectionLogic'++export function UseCasesStep({ onContinue, onSkip }: { onContinue: () => void; onSkip: () => void }): JSX.Element {+ const { clearUseCase, selectUseCase } = useActions(useCaseSelectionLogic)++ return (+ <div className="flex flex-col gap-4 py-1">+ <div className="flex flex-col gap-3">+ {ONBOARDING_USE_CASES.map((useCase) => {+ const iconType = useCase.icon+ const colorVar = `var(--color-product-${iconType.replace(/_/g, '-')}-light)`+ return (+ <button+ key={useCase.key}+ type="button"+ onClick={() => {+ selectUseCase(useCase.key)+ onContinue()+ }}+ className="OnboardingProductCard group flex items-center gap-4 p-4 rounded-lg border text-left cursor-pointer transition-all hover:shadow-sm"+ // Tailwind can't parameterize the product color, so the hover border+ // tint rides on a CSS variable the class below reads.+ style={{ ['--goal-color' as string]: colorVar }}+ data-attr={`self-driving-goal-${useCase.key}`}+ >+ <div+ className="size-12 shrink-0 rounded-lg flex items-center justify-center"+ style={{ background: `color-mix(in srgb, ${colorVar} 12%, transparent)` }}+ >+ <div className="flex *:text-2xl group/colorful-product-icons colorful-product-icons-true">+ {iconForType(iconType)}+ </div>+ </div>+ <div className="flex-1 flex flex-col gap-1 min-w-0">+ <div className="font-semibold text-base">{useCase.title}</div>+ <div className="text-sm text-secondary text-balance">{useCase.description}</div>+ </div>+ </button>+ )+ })}+ </div>+ <div className="flex justify-center">+ <LemonButton+ type="tertiary"+ size="small"+ onClick={() => {+ clearUseCase()+ onSkip()+ }}+ >+ Continue without choosing a goal+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/onboarding/self-driving/steps/WelcomeStep.tsx b/frontend/src/scenes/onboarding/self-driving/steps/WelcomeStep.tsxindex baca838e5957..ed51469a0750 100644--- a/frontend/src/scenes/onboarding/self-driving/steps/WelcomeStep.tsx+++ b/frontend/src/scenes/onboarding/self-driving/steps/WelcomeStep.tsx@@ -1,15 +1,31 @@import selfDrivingHog from 'public/hedgehog/self-driving-hog.png'+import { RoughMark } from '../RoughMark'+/** 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>+ {/* Highlight treatments mirror posthog.com's hero: blue mark on the headline+ (Home/Test Headline, blue #2F80FA), amber rough-notation highlight in the body. */}+ <h1 className="text-2xl font-bold m-0">+ Let's make your product{' '}+ {/* A span, not <mark>: the app styles mark with an !important cream highlight. */}+ <span+ className="rounded-md px-1.5"+ style={{ backgroundColor: 'rgba(47, 128, 250, 0.1)', color: '#2F80FA' }}+ >+ self-driving+ </span>+ </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.+ PostHog runs on your product's context. One command gets it flowing, then agents can start{' '}+ <RoughMark type="highlight" color="rgba(247, 165, 1, 0.15)" strokeWidth={1} multiline delay={400}>+ finding and fixing things+ </RoughMark>+ , with you steering.</p></div></div>diff --git a/frontend/src/scenes/onboarding/self-driving/useCaseSelectionLogic.ts b/frontend/src/scenes/onboarding/self-driving/useCaseSelectionLogic.tsnew file mode 100644index 000000000000..034aac74b553--- /dev/null+++ b/frontend/src/scenes/onboarding/self-driving/useCaseSelectionLogic.ts@@ -0,0 +1,70 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'++import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'++import { onboardingEventUsageLogic, SELF_DRIVING_ONBOARDING_EVENT_PROPS } from '../onboardingEventUsageLogic'+import { productKeysForSetup, resolveSetup } from '../shared/useCases'+import type { OnboardingUseCaseKey } from '../shared/useCases'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface useCaseSelectionLogicValues {+ selectedUseCase: OnboardingUseCaseKey | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface useCaseSelectionLogicActions {+ reportOnboardingUseCaseSelected: (+ useCase: string,+ recommendedProducts: readonly string[],+ properties?: import('lib/utils/eventUsageLogic').OnboardingEventProperties | undefined+ ) => {+ properties: import('lib/utils/eventUsageLogic').OnboardingEventProperties | undefined+ recommendedProducts: readonly string[]+ useCase: string+ } // onboardingEventUsageLogic+ clearUseCase: () => {+ value: true+ }+ selectUseCase: (useCase: OnboardingUseCaseKey) => {+ useCase: OnboardingUseCaseKey+ }+}++export type useCaseSelectionLogicType = MakeLogicType<useCaseSelectionLogicValues, useCaseSelectionLogicActions>++/** Holds the use case declared on the onboarding's use-case step; the rest of the flow spins off it. */+export const useCaseSelectionLogic = kea<useCaseSelectionLogicType>([+ path(['scenes', 'onboarding', 'self-driving', 'useCaseSelectionLogic']),++ connect(() => ({+ actions: [onboardingEventUsageLogic, ['reportOnboardingUseCaseSelected']],+ })),++ actions({+ selectUseCase: (useCase: OnboardingUseCaseKey) => ({ useCase }),+ clearUseCase: true,+ }),++ reducers({+ selectedUseCase: [+ null as OnboardingUseCaseKey | null,+ // Persisted so a refresh (or the GitHub OAuth round-trip on the install step) keeps+ // the use-case-conditional steps in the flow.+ { persist: true, prefix: `${getCurrentTeamIdOrNone() ?? 'unknown'}__` },+ {+ clearUseCase: () => null,+ selectUseCase: (_, { useCase }) => useCase,+ },+ ],+ }),++ listeners(({ actions }) => ({+ selectUseCase: ({ useCase }) => {+ actions.reportOnboardingUseCaseSelected(+ useCase,+ productKeysForSetup(resolveSetup(useCase)),+ SELF_DRIVING_ONBOARDING_EVENT_PROPS+ )+ },+ })),+])diff --git a/frontend/src/scenes/onboarding/shared/components/CheckList.tsx b/frontend/src/scenes/onboarding/shared/components/CheckList.tsxindex e8f52f374aa7..88d05a881937 100644--- a/frontend/src/scenes/onboarding/shared/components/CheckList.tsx+++ b/frontend/src/scenes/onboarding/shared/components/CheckList.tsx@@ -28,11 +28,12 @@ export function CheckList({<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">+ {/* The icon box matches the text's first-line height (text-xs → h-4, text-sm → h-5)+ and centers the icon in it, so single- and multi-line rows align the same way. */}<spanclassName={cn(- 'shrink-0 text-success',- size === 'xs' ? '[&_svg]:size-3.5' : '[&_svg]:size-4',- 'mt-0.5'+ 'shrink-0 text-success flex items-center justify-center',+ size === 'xs' ? 'h-4 [&_svg]:size-3.5' : 'h-5 [&_svg]:size-4')}>{item.icon ?? <IconCheck />}diff --git a/frontend/src/scenes/onboarding/shared/useCases.test.ts b/frontend/src/scenes/onboarding/shared/useCases.test.tsnew file mode 100644index 000000000000..a2f1604068d5--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/useCases.test.ts@@ -0,0 +1,25 @@+import { getTreeItemsProducts } from '~/products'++import { DOCS_URL_BY_PRODUCT_PATH, ONBOARDING_TOOLS, ONBOARDING_USE_CASES, SUPPORTED_TOOL_PRODUCTS } from './useCases'++describe('onboarding use cases', () => {+ it('covers every supported tool with a visible use case', () => {+ const coveredProducts = new Set(+ ONBOARDING_USE_CASES.flatMap((useCase) => [+ ...useCase.tools.map((tool) => ONBOARDING_TOOLS[tool].productKey),+ ...(useCase.additionalTools ?? []),+ ])+ )++ expect(coveredProducts).toEqual(new Set(SUPPORTED_TOOL_PRODUCTS))+ })++ it('resolves every onboarding tool through the product registry', () => {+ const productPaths = new Set(getTreeItemsProducts().map((item) => item.path))++ for (const tool of Object.values(ONBOARDING_TOOLS)) {+ expect(productPaths).toContain(tool.productPath)+ expect(DOCS_URL_BY_PRODUCT_PATH[tool.productPath]).toEqual(expect.any(String))+ }+ })+})diff --git a/frontend/src/scenes/onboarding/shared/useCases.tsx b/frontend/src/scenes/onboarding/shared/useCases.tsxnew file mode 100644index 000000000000..232ffada1015--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/useCases.tsx@@ -0,0 +1,295 @@+/**+ * The declarative model the onboarding spins off from. A use case defines which tools it contains,+ * which extras go to the sidebar, and (through each tool's `options`) which team settings must be+ * on for self-driving to actually see data. Tool display (name, icon) resolves from the products+ * registry via `productPath`, so the flow can't drift from the sidebar.+ */+import { getTreeItemsProducts } from '~/products'+import { FileSystemIconType, ProductKey } from '~/queries/schema/schema-general'++export type OnboardingUseCaseKey =+ | 'find_problems'+ | 'improve_experience'+ | 'ship_changes'+ | 'maintain_ai'+ | 'connect_context'+ | 'ai_app'++/** A team setting a tool needs to produce data. Keys are ours; each maps to a `Team` field. */+export type TeamOption =+ | 'session_recording' // session_recording_opt_in+ | 'replay_masking_floor' // session_recording_masking_config, only if unset+ | 'console_log_capture' // capture_console_log_opt_in (admin-gated)+ | 'network_performance' // capture_performance_opt_in (admin-gated)+ | 'exception_autocapture' // autocapture_exceptions_opt_in+ | 'heatmaps' // heatmaps_opt_in (admin-gated)+ | 'dead_clicks' // capture_dead_clicks (admin-gated)+ | 'web_vitals' // autocapture_web_vitals_opt_in++export type OnboardingToolKey =+ | 'product_analytics'+ | 'session_replay'+ | 'error_tracking'+ | 'web_analytics'+ | 'ai_observability'++export interface OnboardingTool {+ productPath: string+ displayName?: string+ productKey: ProductKey+ /** One line: what the tool contributes to the self-driving loop. */+ benefit: string+ /** Everything that must be on for this tool to work. */+ options: TeamOption[]+}++export const ONBOARDING_TOOLS: Record<OnboardingToolKey, OnboardingTool> = {+ product_analytics: {+ productPath: 'Product analytics',+ productKey: ProductKey.PRODUCT_ANALYTICS,+ benefit: 'Events, trends, and funnels. Understand how users use your product.',+ options: ['heatmaps', 'dead_clicks'],+ },+ session_replay: {+ productPath: 'Session replay',+ productKey: ProductKey.SESSION_REPLAY,+ benefit: 'Real sessions recorded, so agents can watch what users did.',+ options: ['session_recording', 'replay_masking_floor', 'console_log_capture', 'network_performance'],+ },+ error_tracking: {+ productPath: 'Error tracking',+ productKey: ProductKey.ERROR_TRACKING,+ benefit: 'Exceptions grouped into issues that feed your agents.',+ options: ['exception_autocapture'],+ },+ web_analytics: {+ productPath: 'Web analytics',+ productKey: ProductKey.WEB_ANALYTICS,+ benefit: 'Traffic, sources, and conversion on a live dashboard.',+ options: ['web_vitals', 'heatmaps', 'network_performance'],+ },+ ai_observability: {+ productPath: 'LLM analytics',+ displayName: 'AI observability',+ productKey: ProductKey.AI_OBSERVABILITY,+ benefit: 'Traces, costs, and failures from your LLM features.',+ options: [],+ },+}++export const SUPPORTED_TOOL_PRODUCTS = [+ ...Object.values(ONBOARDING_TOOLS).map((tool) => tool.productKey),+ ProductKey.FEATURE_FLAGS,+ ProductKey.EXPERIMENTS,+ ProductKey.SURVEYS,+ ProductKey.LOGS,+ ProductKey.METRICS,+ ProductKey.DATA_WAREHOUSE,+ ProductKey.WORKFLOWS,+ ProductKey.MCP_ANALYTICS,+ ProductKey.CONVERSATIONS,+]++export const ADDITIONAL_TOOL_DETAILS: Partial<Record<ProductKey, { description: string; docsUrl: string }>> = {+ [ProductKey.FEATURE_FLAGS]: {+ description: 'Roll out changes gradually and safely.',+ docsUrl: 'https://posthog.com/docs/feature-flags',+ },+ [ProductKey.EXPERIMENTS]: {+ description: 'Measure whether a product change works.',+ docsUrl: 'https://posthog.com/docs/experiments',+ },+ [ProductKey.SURVEYS]: {+ description: 'Collect feedback from users in your product.',+ docsUrl: 'https://posthog.com/docs/surveys',+ },+ [ProductKey.LOGS]: {+ description: 'Search and investigate application logs.',+ docsUrl: 'https://posthog.com/docs/logs',+ },+ [ProductKey.METRICS]: {+ description: 'Monitor service metrics and alerts.',+ docsUrl: 'https://posthog.com/docs/metrics',+ },+ [ProductKey.DATA_WAREHOUSE]: {+ description: 'Query product and business data together.',+ docsUrl: 'https://posthog.com/docs/data-warehouse',+ },+ [ProductKey.WORKFLOWS]: {+ description: 'Automate work from product activity.',+ docsUrl: 'https://posthog.com/docs/workflows',+ },+ [ProductKey.MCP_ANALYTICS]: {+ description: 'Monitor MCP tool calls and failures.',+ docsUrl: 'https://posthog.com/docs/mcp-analytics',+ },+ [ProductKey.CONVERSATIONS]: {+ description: 'Manage support conversations with customers.',+ docsUrl: 'https://posthog.com/docs/support',+ },+}++/** Docs pages, keyed by products-registry path - covers tools and sidebar-only extras alike. */+export const DOCS_URL_BY_PRODUCT_PATH: Record<string, string> = {+ 'Product analytics': 'https://posthog.com/docs/product-analytics',+ 'Session replay': 'https://posthog.com/docs/session-replay',+ 'Error tracking': 'https://posthog.com/docs/error-tracking',+ 'Web analytics': 'https://posthog.com/docs/web-analytics',+ 'LLM analytics': 'https://posthog.com/docs/llm-analytics',+ 'Feature flags': 'https://posthog.com/docs/feature-flags',+ Experiments: 'https://posthog.com/docs/experiments',+ Surveys: 'https://posthog.com/docs/surveys',+ Logs: 'https://posthog.com/docs/logs',+ Metrics: 'https://posthog.com/docs/metrics',+ 'Data warehouse': 'https://posthog.com/docs/data-warehouse',+ Workflows: 'https://posthog.com/docs/workflows',+ 'MCP analytics': 'https://posthog.com/docs/mcp-analytics',+ Support: 'https://posthog.com/docs/support',+ Dashboards: 'https://posthog.com/docs/product-analytics/dashboards',+}++export function toolIconType(tool: OnboardingTool): FileSystemIconType {+ const item = getTreeItemsProducts().find((i) => i.path === tool.productPath)+ return item?.iconType ?? 'product_analytics'+}++/** A flow step only some use cases need; the flow maps each id to its step component. */+export type OnboardingExtraStepId = 'authorized-urls' | 'ai-observability'++/** What a selection sets up, shared by the use cases and the no-use-case default. */+export interface OnboardingSetup {+ /** Registered as the primary product intent. */+ primaryProduct: ProductKey+ /** Shown and configured on the tools step. */+ tools: OnboardingToolKey[]+ /** Intent-only ProductKeys shown on the tools step. */+ additionalTools?: ProductKey[]+ /** Intent-only ProductKeys: populate the sidebar (via the products registry's `intents`)+ * without appearing in the onboarding UI. */+ sidebarExtras: ProductKey[]+ /** Team settings needed beyond the tools' own options. */+ extraOptions?: TeamOption[]+ /** Steps after install that this setup can't reach its finish line without. */+ extraSteps?: OnboardingExtraStepId[]+}++export function productKeysForSetup(setup: OnboardingSetup): ProductKey[] {+ return Array.from(+ new Set([+ setup.primaryProduct,+ ...setup.tools.map((key) => ONBOARDING_TOOLS[key].productKey),+ ...(setup.additionalTools ?? []),+ ...setup.sidebarExtras,+ ])+ )+}++export interface OnboardingUseCase extends OnboardingSetup {+ key: OnboardingUseCaseKey+ icon: FileSystemIconType+ title: string+ /** One sentence: how agents get there, ending in the deliverable (the finish line). */+ description: string+ /** The achievement criterion (measurement spec, not rendered). */+ done: string+}++// Dashboards for everyone: it answers to the PRODUCT_ANALYTICS intent in the products registry.+const SHARED_SIDEBAR: ProductKey[] = [ProductKey.PRODUCT_ANALYTICS]++export const ONBOARDING_USE_CASES: OnboardingUseCase[] = [+ {+ key: 'improve_experience',+ icon: 'product_analytics',+ title: 'Improve the customer experience',+ description: 'Agents study behavior, feedback, traffic, and conversions. They identify where users get stuck.',+ done: 'first experience finding or report',+ primaryProduct: ProductKey.PRODUCT_ANALYTICS,+ tools: ['product_analytics', 'session_replay', 'web_analytics'],+ additionalTools: [ProductKey.SURVEYS],+ sidebarExtras: SHARED_SIDEBAR,+ extraSteps: ['authorized-urls'],+ },+ {+ key: 'find_problems',+ icon: 'error_tracking',+ title: 'Find product problems',+ description:+ 'Agents inspect errors, sessions, logs, and support context. They send findings and propose fixes.',+ done: 'first product problem finding or proposed fix',+ primaryProduct: ProductKey.ERROR_TRACKING,+ tools: ['error_tracking', 'session_replay'],+ additionalTools: [ProductKey.LOGS, ProductKey.METRICS, ProductKey.CONVERSATIONS],+ sidebarExtras: SHARED_SIDEBAR,+ },+ {+ key: 'ship_changes',+ icon: 'feature_flag',+ title: 'Ship changes with confidence',+ description: 'Agents monitor flags and experiments. They report results before you expand a rollout.',+ done: 'first rollout or experiment result',+ primaryProduct: ProductKey.FEATURE_FLAGS,+ tools: ['product_analytics'],+ additionalTools: [ProductKey.FEATURE_FLAGS, ProductKey.EXPERIMENTS],+ sidebarExtras: SHARED_SIDEBAR,+ },+ {+ key: 'maintain_ai',+ icon: 'llm_analytics',+ title: 'Maintain an AI product',+ description: 'Agents inspect AI traces, costs, failures, and MCP tool calls. They find issues in AI features.',+ done: 'first AI product finding or report',+ primaryProduct: ProductKey.AI_OBSERVABILITY,+ tools: ['ai_observability', 'product_analytics'],+ additionalTools: [ProductKey.MCP_ANALYTICS],+ sidebarExtras: SHARED_SIDEBAR,+ extraSteps: ['ai-observability'],+ },+ {+ key: 'connect_context',+ icon: 'data_warehouse',+ title: 'Connect context and automate work',+ description: 'Agents use warehouse data and workflows to act on signals across your systems.',+ done: 'first workflow or report using connected context',+ primaryProduct: ProductKey.DATA_WAREHOUSE,+ tools: ['product_analytics'],+ additionalTools: [ProductKey.DATA_WAREHOUSE, ProductKey.WORKFLOWS],+ sidebarExtras: SHARED_SIDEBAR,+ },+]++const DEFAULT_SETUP: OnboardingSetup = {+ primaryProduct: ProductKey.PRODUCT_ANALYTICS,+ tools: ['product_analytics', 'session_replay', 'error_tracking'],+ additionalTools: [+ ProductKey.FEATURE_FLAGS,+ ProductKey.EXPERIMENTS,+ ProductKey.SURVEYS,+ ProductKey.LOGS,+ ProductKey.METRICS,+ ProductKey.DATA_WAREHOUSE,+ ProductKey.WORKFLOWS,+ ProductKey.MCP_ANALYTICS,+ ProductKey.CONVERSATIONS,+ ProductKey.WEB_ANALYTICS,+ ProductKey.AI_OBSERVABILITY,+ ],+ sidebarExtras: SHARED_SIDEBAR,+}++export function resolveSetup(useCase: OnboardingUseCaseKey | null): OnboardingSetup {+ return ONBOARDING_USE_CASES.find((u) => u.key === useCase) ?? DEFAULT_SETUP+}++/** The setup's primary tool - the use-case card's icon derives from it. */+export function primaryTool(setup: OnboardingSetup): OnboardingTool {+ const key = setup.tools.find((k) => ONBOARDING_TOOLS[k].productKey === setup.primaryProduct) ?? setup.tools[0]+ return ONBOARDING_TOOLS[key]+}++/** Every team option the setup needs: the tools' union plus the setup's extras. */+export function optionsForSetup(setup: OnboardingSetup): TeamOption[] {+ return Array.from(+ new Set([...setup.tools.flatMap((key) => ONBOARDING_TOOLS[key].options), ...(setup.extraOptions ?? [])])+ )+}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.tsindex 06d36209a536..c830d0502f5a 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 {- reportSelfDrivingOnboardingCloudRunCompleted: (props: {+ reportOnboardingCloudRunCompleted: (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, ['reportSelfDrivingOnboardingCloudRunCompleted']],+ actions: [onboardingEventUsageLogic, ['reportOnboardingCloudRunCompleted']],})),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.reportSelfDrivingOnboardingCloudRunCompleted({+ actions.reportOnboardingCloudRunCompleted({taskId: props.taskId,runId: props.runId,...report,diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.tsindex 23e9ce9b2223..4e98d86e5b26 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- reportSelfDrivingOnboardingCloudRunQueued: (props: { repository: string; runId: string; taskId: string }) => {+ reportOnboardingCloudRunQueued: (props: { repository: string; runId: string; taskId: string }) => {repository: stringrunId: stringtaskId: string@@ -138,7 +138,7 @@ export const wizardCloudRunLogic = kea<wizardCloudRunLogicType>([activeCloudRunLogic,['setActiveCloudRun', 'clearActiveCloudRun'],onboardingEventUsageLogic,- ['reportSelfDrivingOnboardingCloudRunQueued'],+ ['reportOnboardingCloudRunQueued'],],})),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.reportSelfDrivingOnboardingCloudRunQueued({ taskId: task_id, runId: run_id, repository })+ actions.reportOnboardingCloudRunQueued({ taskId: task_id, runId: run_id, repository })actions.startCloudRunSuccess()} catch (e) {const detail = e instanceof ApiError ? e.detail : nulldiff --git a/frontend/src/scenes/teamLogic.test.ts b/frontend/src/scenes/teamLogic.test.tsindex e7e1726faa2a..45f0e7ca1998 100644--- a/frontend/src/scenes/teamLogic.test.ts+++ b/frontend/src/scenes/teamLogic.test.ts@@ -3,7 +3,7 @@ import { MOCK_DEFAULT_PROJECT, MOCK_DEFAULT_TEAM, MOCK_TEAM_ID } from 'lib/api.mimport { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'-import { ProductKey } from '~/queries/schema/schema-general'+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { AppContext, TeamType } from '~/types'@@ -136,6 +136,28 @@ describe('teamLogic', () => {expect(logic.values.currentTeam?.id).toBe(MOCK_TEAM_ID)expect((logic.values.currentTeam as TeamType)?.product_intents).toBeUndefined()})++ it('forwards the intent context', async () => {+ let requestBody: Record<string, unknown> | undefined+ useMocks({+ patch: {+ '/api/environments/:id/complete_product_onboarding': async ({ request }) => {+ requestBody = (await request.json()) as Record<string, unknown>+ return [200, { ...MOCK_DEFAULT_TEAM, product_intents: [] }]+ },+ },+ })++ await logic.asyncActions.recordProductIntentOnboardingComplete({+ product_type: ProductKey.ERROR_TRACKING,+ intent_context: ProductIntentContext.ONBOARDING_PRODUCT_SELECTED_PRIMARY,+ })++ expect(requestBody).toEqual({+ product_type: ProductKey.ERROR_TRACKING,+ intent_context: ProductIntentContext.ONBOARDING_PRODUCT_SELECTED_PRIMARY,+ })+ })})describe('before team is loaded', () => {diff --git a/frontend/src/scenes/teamLogic.tsx b/frontend/src/scenes/teamLogic.tsxindex fae14ac3807e..5963933897a1 100644--- a/frontend/src/scenes/teamLogic.tsx+++ b/frontend/src/scenes/teamLogic.tsx@@ -21,7 +21,12 @@ import {import { identifierToHuman } from 'lib/utils/strings'import { customProductsLogic } from '~/layout/panel-layout/ProjectTree/customProductsLogic'-import { CurrencyCode, CustomerAnalyticsConfig, ProductKey } from '~/queries/schema/schema-general'+import {+ CurrencyCode,+ CustomerAnalyticsConfig,+ type ProductIntentContext,+ ProductKey,+} from '~/queries/schema/schema-general'import { CorrelationConfigType, ProjectType, TeamPublicType, TeamType } from '~/types'import type { FeatureFlagsSet } from '../lib/logic/featureFlagLogic'@@ -79,6 +84,21 @@ export interface FrequentMistakeAdvice {fix: string}+export interface ProductOnboardingCompleteProperties {+ product_type: ProductKey+ intent_context?: ProductIntentContext+}++export async function completeProductOnboarding(+ teamId: TeamType['id'] | string,+ { product_type, intent_context }: ProductOnboardingCompleteProperties+): Promise<TeamType | null> {+ return await api.update(`api/environments/${teamId}/complete_product_onboarding`, {+ product_type,+ intent_context,+ })+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface teamLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic@@ -215,9 +235,9 @@ export interface teamLogicActions {currentTeam: TeamPublicType | nullpayload?: any}- recordProductIntentOnboardingComplete: ({ product_type }: { product_type: ProductKey }) => {- product_type: ProductKey- }+ recordProductIntentOnboardingComplete: (+ properties: ProductOnboardingCompleteProperties+ ) => ProductOnboardingCompletePropertiesrecordProductIntentOnboardingCompleteFailure: (error: string,errorObject?: any@@ -227,14 +247,10 @@ export interface teamLogicActions {}recordProductIntentOnboardingCompleteSuccess: (currentTeam: TeamPublicType | TeamType | null,- payload?: {- product_type: ProductKey- }+ payload?: ProductOnboardingCompleteProperties) => {currentTeam: TeamPublicType | TeamType | null- payload?: {- product_type: ProductKey- }+ payload?: ProductOnboardingCompleteProperties}resetToken: () => anyresetTokenFailure: (@@ -481,13 +497,8 @@ export const teamLogic = kea<teamLogicType>([return withProductIntentsFrom(values.currentTeam, result)},- recordProductIntentOnboardingComplete: async ({ product_type }: { product_type: ProductKey }) => {- const result = await api.update(- `api/environments/${values.currentTeamId}/complete_product_onboarding`,- {- product_type,- }- )+ recordProductIntentOnboardingComplete: async (properties: ProductOnboardingCompleteProperties) => {+ const result = await completeProductOnboarding(values.currentTeamIdStrict, properties)actions.loadCustomProducts()return withProductIntentsFrom(values.currentTeam, result)diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b42675722128..67493fac882b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1226,6 +1226,9 @@ importers:remark-gfm:specifier: ^4.0.0version: 4.0.1+ rough-notation:+ specifier: ^0.5.1+ version: 0.5.1rrule:specifier: ^2.8.1version: 2.8.1@@ -20603,6 +20606,9 @@ packages:resolution: {integrity: sha512-85aZYCxweiD5J8yTEbw+E6A27zSnLPNDL0WfPdw3YYodq7WjnTKo0q4dtyQ2gz23iPT8Q9CUyJtAaUNcTxRf5Q==}+ resolution: {integrity: sha512-ITHofTzm13cWFVfoGsh/4c/k2Mg8geKgBCwex71UZLnNuw403tCRjYPQ68jSAd37DMbZIePXPjDgY0XdZi9HPw==}+resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==}@@ -43124,6 +43130,8 @@ snapshots:+ [email protected]: {}+dependencies:hachure-fill: 0.5.2diff --git a/products/signals/frontend/inbox/components/config/AgentsRoster.tsx b/products/signals/frontend/inbox/components/config/AgentsRoster.tsxindex 6a7c65a230f1..0cc5fa95e9fa 100644--- a/products/signals/frontend/inbox/components/config/AgentsRoster.tsx+++ b/products/signals/frontend/inbox/components/config/AgentsRoster.tsx@@ -10,7 +10,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import type { SyncStatusEnumApi } from 'products/engineering_analytics/frontend/generated/api.schemas'import { signalSourcesLogic } from '../../signalSourcesLogic'-import type { SourceToolStatus } from '../../signalSourcesLogic'+import type { SourceToolDataStatus, SourceToolStatus } from '../../signalSourcesLogic'import { SignalSourceConfig, SignalSourceConfigStatus } from '../../types'import { getSourceProductMeta } from '../badges/sourceProductIcons'import { AGENT_ROSTER_GROUPS, AgentRosterDefinition, AgentRosterSource } from './agentRosterMeta'@@ -66,6 +66,75 @@ interface AgentCardProps {enablingTool: booleanonToggle: (source: AgentRosterSource) => voidonEnableTool: (tool: SourceToolStatus) => void+ onRetryData: () => void+}++function ToolDataStatus({+ agent,+ status,+ onRetry,+}: {+ agent: AgentRosterDefinition+ status: SourceToolDataStatus+ onRetry: () => void+}): JSX.Element | null {+ if (status === 'unavailable') {+ return null+ }++ if (status === 'loading') {+ return (+ <div className="flex items-center gap-1.5 mt-2 ml-11 text-xs text-muted">+ <Spinner className="text-xs" />+ Checking for recent data+ </div>+ )+ }++ if (status === 'error') {+ return (+ <div className="flex items-center gap-2 mt-2 ml-11 text-xs text-muted">+ <span>Couldn't check recent data.</span>+ <LemonButton+ type="tertiary"+ size="xsmall"+ onClick={(event) => {+ event.stopPropagation()+ onRetry()+ }}+ >+ Try again+ </LemonButton>+ </div>+ )+ }++ if (status === 'recent') {+ return (+ <div className="flex items-center gap-1.5 mt-2 ml-11 text-xs text-muted">+ <span className="size-1.5 rounded-full bg-success" />+ Data received in the last 30 days+ </div>+ )+ }++ return (+ <div className="flex items-center gap-2 mt-2 ml-11 text-xs text-muted">+ <span className="size-1.5 rounded-full bg-border-bold" />+ <span>No data received in the last 30 days.</span>+ {agent.docsUrl && (+ <Link+ to={agent.docsUrl}+ target="_blank"+ className="inline-flex items-center gap-1"+ onClick={(event) => event.stopPropagation()}+ >+ Check setup+ <IconArrowUpRight />+ </Link>+ )}+ </div>+ )}const AgentCard = memo(function AgentCard({@@ -75,11 +144,12 @@ const AgentCard = memo(function AgentCard({enablingTool,onToggle,onEnableTool,+ onRetryData,}: AgentCardProps): JSX.Element {const { armed, loading, requiresSetup, syncStatus } = stateconst status = resolveAgentStatus(armed, syncStatus)const statusTag = STATUS_TAG[status]- const toolOff = !!tool && !tool.enabled+ const toolOff = tool?.enabled === false// An off tool blocks arming (the source would watch nothing), never disarming.const armingBlocked = toolOff && !armedconst isInteractive = !loading && !armingBlocked@@ -176,11 +246,8 @@ const AgentCard = memo(function AgentCard({</LemonButton>)}</div>- ) : tool?.receivingData !== null && tool?.receivingData !== undefined ? (- <div className="flex items-center gap-1.5 mt-2 ml-11 text-xs text-muted">- <span className={`size-1.5 rounded-full ${tool.receivingData ? 'bg-success' : 'bg-border-bold'}`} />- {tool.receivingData ? 'Receiving data' : 'No data yet'}- </div>+ ) : tool ? (+ <ToolDataStatus agent={agent} status={tool.dataStatus} onRetry={onRetryData} />) : null}{armed && agent.source === 'session_replay' && status === 'syncing' && (@@ -232,6 +299,7 @@ export function AgentsRoster(): JSX.Element {toggleHealthChecks,initiateDataWarehouseSourceToggle,enableSourceTool,+ loadToolDataEvents,} = useActions(signalSourcesLogic)const { featureFlags } = useValues(featureFlagLogic)@@ -396,6 +464,7 @@ export function AgentsRoster(): JSX.Element {}onToggle={handleToggle}onEnableTool={(tool) => tool.enablement && enableSourceTool(tool.enablement)}+ onRetryData={loadToolDataEvents}/>))}</div>diff --git a/products/signals/frontend/inbox/components/config/AgentsTab.tsx b/products/signals/frontend/inbox/components/config/AgentsTab.tsxindex 9077ab62fe67..15a545e266ca 100644--- a/products/signals/frontend/inbox/components/config/AgentsTab.tsx+++ b/products/signals/frontend/inbox/components/config/AgentsTab.tsx@@ -58,6 +58,7 @@ export function AgentsTab(): JSX.Element {const {loadSources,loadSourceConfigs,+ loadToolDataEvents,closeSessionAnalysisSetup,closeDataSourceSetup,onDataSourceSetupComplete,@@ -66,6 +67,7 @@ export function AgentsTab(): JSX.Element {useEffect(() => {loadSources()loadSourceConfigs()+ loadToolDataEvents()}, []) // eslint-disable-line react-hooks/exhaustive-depslet agentsBody: JSX.Elementdiff --git a/products/signals/frontend/inbox/components/config/SignalSourcesPanel.stories.tsx b/products/signals/frontend/inbox/components/config/SignalSourcesPanel.stories.tsxindex e74695b353a1..a6bcbc621c42 100644--- a/products/signals/frontend/inbox/components/config/SignalSourcesPanel.stories.tsx+++ b/products/signals/frontend/inbox/components/config/SignalSourcesPanel.stories.tsx@@ -30,6 +30,7 @@ interface PanelState {hasExceptionEvents: booleanhasAiEvents: booleanhasAnalyticsEvents: boolean+ eventDefinitionsUnavailable: boolean}function sourceConfig(@@ -66,13 +67,13 @@ function sourceConfigsFor(state: PanelState): SignalSourceConfig[] {]}-function eventDefinitionsFor(state: PanelState): { name: string }[] {+function eventDefinitionsFor(state: PanelState): { name: string; last_seen_at: string }[] {const names = [...(state.hasExceptionEvents ? ['$exception'] : []),...(state.hasAiEvents ? ['$ai_generation', '$ai_trace'] : []),...(state.hasAnalyticsEvents ? ['$pageview', '$autocapture'] : []),]- return names.map((name) => ({ name }))+ return names.map((name) => ({ name, last_seen_at: new Date().toISOString() }))}function PanelHarness(state: PanelState): JSX.Element {@@ -88,15 +89,18 @@ function PanelHarness(state: PanelState): JSX.Element {},],'/api/projects/:team_id/signals/source_configs/': () => [200, { results: sourceConfigsFor(state) }],- '/api/projects/:team_id/event_definitions/': () => [- 200,- {- count: eventDefinitionsFor(state).length,- next: null,- previous: null,- results: eventDefinitionsFor(state),- },- ],+ '/api/projects/:team_id/event_definitions/': () =>+ state.eventDefinitionsUnavailable+ ? [500, { detail: "Couldn't check recent data." }]+ : [+ 200,+ {+ count: eventDefinitionsFor(state).length,+ next: null,+ previous: null,+ results: eventDefinitionsFor(state),+ },+ ],'/api/environments/:team_id/external_data_sources/': () => [200,{ count: 0, next: null, previous: null, results: [] },@@ -140,6 +144,7 @@ const meta: Meta<typeof PanelHarness> = {hasExceptionEvents: true,hasAiEvents: false,hasAnalyticsEvents: true,+ eventDefinitionsUnavailable: false,},}export default meta@@ -200,8 +205,8 @@ export const EverythingHealthy: Story = {},}-/** Tools on but no events yet: the usage lines read "No data yet". */-export const ToolsOnNoDataYet: Story = {+/** Tools on but no recent events show the setup link. */+export const ToolsOnNoRecentData: Story = {args: {errorTrackingArmed: true,sessionReplayArmed: true,@@ -217,6 +222,17 @@ export const ToolsOnNoDataYet: Story = {},}+/** A failed event-definition check shows the retry action without marking tools as off. */+export const EventDefinitionsUnavailable: Story = {+ args: {+ errorTrackingArmed: true,+ aiObservabilityArmed: true,+ productAnalyticsArmed: true,+ exceptionAutocaptureOn: false,+ eventDefinitionsUnavailable: true,+ },+}+/** Exceptions flow from a server SDK while the autocapture opt-in is off: still counts as on. */export const ServerSideExceptionsOnly: Story = {args: {diff --git a/products/signals/frontend/inbox/signalSourcesLogic.test.ts b/products/signals/frontend/inbox/signalSourcesLogic.test.tsindex cc3f7a4270cd..0e064b33966f 100644--- a/products/signals/frontend/inbox/signalSourcesLogic.test.ts+++ b/products/signals/frontend/inbox/signalSourcesLogic.test.ts@@ -1,6 +1,9 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'+import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { teamLogic } from 'scenes/teamLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -57,6 +60,14 @@ const githubIssuesConfig = {status: null,}+function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {+ let resolvePromise!: (value: T) => void+ const promise = new Promise<T>((resolve) => {+ resolvePromise = resolve+ })+ return { promise, resolve: resolvePromise }+}+describe('signalSourcesLogic', () => {let logic: ReturnType<typeof signalSourcesLogic.build>let warehouseSources: ExternalDataSource[]@@ -192,4 +203,121 @@ describe('signalSourcesLogic', () => {config: {},})})++ it.each([+ {+ name: 'while recent data is loading',+ arrange: (_mountedLogic: typeof logic) => undefined,+ enabled: null,+ dataStatus: 'loading',+ },+ {+ name: 'when the recent data check fails',+ arrange: (mountedLogic: typeof logic) => {+ mountedLogic.actions.loadToolDataEventsSuccess(new Set(['$exception']))+ mountedLogic.actions.loadToolDataEventsFailure('Failed')+ },+ enabled: null,+ dataStatus: 'error',+ },+ {+ name: 'when a successful check finds no recent exceptions',+ arrange: (mountedLogic: typeof logic) => mountedLogic.actions.loadToolDataEventsSuccess(new Set()),+ enabled: false,+ dataStatus: 'none',+ },+ {+ name: 'when a successful check finds recent exceptions',+ arrange: (mountedLogic: typeof logic) =>+ mountedLogic.actions.loadToolDataEventsSuccess(new Set(['$exception'])),+ enabled: true,+ dataStatus: 'recent',+ },+ ])('reports Error tracking as $dataStatus $name', ({ arrange, enabled, dataStatus }) => {+ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ autocapture_exceptions_opt_in: false,+ })++ arrange(logic)++ expect(logic.values.toolStatusBySource.error_tracking).toMatchObject({ enabled, dataStatus })+ })++ it('uses only recently seen event definitions as tool data', async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/event_definitions/': ({ request }) => {+ const excludeStale = new URL(request.url).searchParams.get('exclude_stale') === 'true'+ const results = excludeStale+ ? [+ { name: '$exception', last_seen_at: '2026-08-09T00:00:00Z' },+ { name: '$pageview', last_seen_at: null },+ ]+ : [+ { name: '$exception', last_seen_at: '2026-08-09T00:00:00Z' },+ { name: '$pageview', last_seen_at: null },+ { name: '$ai_trace', last_seen_at: '2026-01-01T00:00:00Z' },+ ]+ return [200, { count: results.length, next: null, previous: null, results }]+ },+ },+ })+ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ autocapture_exceptions_opt_in: false,+ })++ await expectLogic(logic, () => {+ logic.actions.loadToolDataEvents()+ }).toFinishAllListeners()++ expect(logic.values.toolDataEvents).toEqual(new Set(['$exception']))+ expect(logic.values.toolStatusBySource.error_tracking).toMatchObject({+ enabled: true,+ dataStatus: 'recent',+ })+ expect(logic.values.toolStatusBySource.analytics?.dataStatus).toBe('none')+ expect(logic.values.toolStatusBySource.llm_analytics?.dataStatus).toBe('none')+ })++ it('keeps tool enablement loading until the refreshed team is available', async () => {+ const enablementResponse = deferred<[number, { results: Record<string, string> }]>()+ const teamResponse = deferred<[number, typeof MOCK_DEFAULT_TEAM]>()+ const teamRequestStarted = deferred<void>()+ useMocks({+ post: {+ '/api/projects/:team_id/product_enablement/': () => enablementResponse.promise,+ },+ get: {+ '/api/environments/:team_id/': () => {+ teamRequestStarted.resolve()+ return teamResponse.promise+ },+ },+ })+ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ autocapture_exceptions_opt_in: false,+ })++ logic.actions.enableSourceTool('error_tracking')+ expect(logic.values.enablingTool).toBe('error_tracking')++ enablementResponse.resolve([200, { results: { error_tracking: 'enabled' } }])+ await teamRequestStarted.promise+ expect(logic.values.enablingTool).toBe('error_tracking')++ teamResponse.resolve([+ 200,+ {+ ...MOCK_DEFAULT_TEAM,+ autocapture_exceptions_opt_in: true,+ },+ ])+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.enablingTool).toBeNull()+ expect(logic.values.toolStatusBySource.error_tracking?.enabled).toBe(true)+ })})diff --git a/products/signals/frontend/inbox/signalSourcesLogic.ts b/products/signals/frontend/inbox/signalSourcesLogic.tsindex 4983a1ef5c67..272647d1a49d 100644--- a/products/signals/frontend/inbox/signalSourcesLogic.ts+++ b/products/signals/frontend/inbox/signalSourcesLogic.ts@@ -36,17 +36,16 @@ import { SignalSourceConfig, SignalSourceConfigStatus, ToggleSignalSourceParams/** product_enablement recipe names for tools that back a signal source. */export type SourceToolEnablement = 'session_replay' | 'error_tracking' | 'conversations'-/** The PostHog tool behind a signal source: whether it captures anything, and how to turn it on. */+export type SourceToolDataStatus = 'unavailable' | 'loading' | 'error' | 'recent' | 'none'+export interface SourceToolStatus {toolName: string- enabled: boolean- /** The product_enablement recipe that turns the tool on, when one exists. */+ enabled: boolean | nullenablement: SourceToolEnablement | null- /** Whether the tool's events exist in this project; null when there is no cheap event signal. */- receivingData: boolean | null+ dataStatus: SourceToolDataStatus}-/** Event definitions probed to tell whether each source's tool is receiving data. */+/** Event definitions probed to detect recent data for each source's tool. */const TOOL_USAGE_EVENTS = ['$exception', '$ai_generation', '$ai_trace', '$pageview', '$autocapture']/** Matches Cymbal `EmitSignalRequest.source_type` + `products.signals.backend.api.emit_signal` checks. */@@ -235,6 +234,7 @@ export interface signalSourcesLogicValues {sourcesModalOpen: booleantogglingSourceKeys: Set<string>toolDataEvents: Set<string> | null+ toolDataEventsFailed: booleantoolDataEventsLoading: booleantoolStatusBySource: Partial<Record<AgentRosterSource, SourceToolStatus>>zendeskTicketsConfig: SignalSourceConfig | null@@ -245,7 +245,6 @@ export interface signalSourcesLogicActions {loadSources: () => {value: true} // sourcesDataLogic- loadCurrentTeam: () => any // teamLogicclearSessionAnalysisFilters: () => {value: true}@@ -406,7 +405,9 @@ export interface signalSourcesLogicMeta {isAnomalyInvestigationToggling: (togglingSourceKeys: Set<string>) => booleantoolStatusBySource: (currentTeam: TeamPublicType | TeamType | null,- toolDataEvents: Set<string> | null+ toolDataEvents: Set<string> | null,+ toolDataEventsLoading: boolean,+ toolDataEventsFailed: boolean) => Partial<Record<AgentRosterSource, SourceToolStatus>>errorTrackingIsFullyEnabled: (sourceConfigs: SignalSourceConfig[] | null) => booleanciSignalsIsFullyEnabled: (ciSignalsConfig: CISignalsConfigApi | null) => boolean@@ -436,7 +437,7 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([teamLogic,['currentTeam'],],- actions: [sourcesDataLogic, ['loadSources'], teamLogic, ['loadCurrentTeam']],+ actions: [sourcesDataLogic, ['loadSources']],})),actions({@@ -491,10 +492,13 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([{loadToolDataEvents: async (): Promise<Set<string>> => {const response = await eventDefinitionsList(String(teamLogic.values.currentTeamId), {+ exclude_stale: true,names: TOOL_USAGE_EVENTS,limit: TOOL_USAGE_EVENTS.length,})- return new Set(response.results.map(({ name }) => name))+ return new Set(+ response.results.filter(({ last_seen_at }) => !!last_seen_at).map(({ name }) => name)+ )},},],@@ -531,6 +535,14 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([enableSourceToolComplete: () => null,},],+ toolDataEventsFailed: [+ false,+ {+ loadToolDataEvents: () => false,+ loadToolDataEventsSuccess: () => false,+ loadToolDataEventsFailure: () => true,+ },+ ],sourceConfigs: {toggleSessionAnalysis: (state: SignalSourceConfig[] | null) =>toggleSourceConfigState(@@ -734,47 +746,63 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([keys.has(`${SignalSourceProduct.Analytics}_${SignalSourceType.AnomalyInvestigation}`),],toolStatusBySource: [- (s) => [s.currentTeam, s.toolDataEvents],+ (s) => [s.currentTeam, s.toolDataEvents, s.toolDataEventsLoading, s.toolDataEventsFailed],(currentTeam: TeamPublicType | TeamType | null,- toolDataEvents: Set<string> | null+ toolDataEvents: Set<string> | null,+ toolDataEventsLoading: boolean,+ toolDataEventsFailed: boolean): Partial<Record<AgentRosterSource, SourceToolStatus>> => {const team = currentTeam as TeamType | null- const has = (...events: string[]): boolean | null =>- toolDataEvents ? events.some((event) => toolDataEvents.has(event)) : null+ const dataStatus = (...events: string[]): SourceToolDataStatus => {+ if (toolDataEventsLoading || (toolDataEvents === null && !toolDataEventsFailed)) {+ return 'loading'+ }+ if (toolDataEventsFailed) {+ return 'error'+ }+ return events.some((event) => toolDataEvents?.has(event)) ? 'recent' : 'none'+ }+ const errorTrackingDataStatus = dataStatus('$exception')+ const errorTrackingEnabled =+ team?.autocapture_exceptions_opt_in === true || errorTrackingDataStatus === 'recent'+ ? true+ : team && errorTrackingDataStatus === 'none'+ ? false+ : nullreturn {error_tracking: {toolName: 'Error tracking',- // Server SDKs capture exceptions without the autocapture opt-in, so- // flowing data counts as on.- enabled: !!team?.autocapture_exceptions_opt_in || has('$exception') === true,+ // Server SDKs capture exceptions without the autocapture opt-in, so recent+ // exception data counts as on.+ enabled: errorTrackingEnabled,enablement: 'error_tracking',- receivingData: has('$exception'),+ dataStatus: errorTrackingDataStatus,},session_replay: {toolName: 'Session replay',- enabled: !!team?.session_recording_opt_in,+ enabled: team ? !!team.session_recording_opt_in : null,enablement: 'session_replay',// Recordings never produce event definitions, so there is no cheap signal.- receivingData: null,+ dataStatus: 'unavailable',},conversations: {toolName: 'Support',- enabled: !!team?.conversations_enabled,+ enabled: team ? !!team.conversations_enabled : null,enablement: 'conversations',- receivingData: null,+ dataStatus: 'unavailable',},llm_analytics: {toolName: 'AI observability',enabled: true,enablement: null,- receivingData: has('$ai_generation', '$ai_trace'),+ dataStatus: dataStatus('$ai_generation', '$ai_trace'),},analytics: {toolName: 'Product analytics',enabled: true,enablement: null,- receivingData: has('$pageview', '$autocapture'),+ dataStatus: dataStatus('$pageview', '$autocapture'),},}},@@ -1138,11 +1166,12 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([products: [enablement],})// Refresh the cached team so the tool reads back as on.- actions.loadCurrentTeam()+ await teamLogic.asyncActions.loadCurrentTeam()} catch (error: any) {lemonToast.error(error?.detail || error?.message || "Couldn't turn this on. Please try again.")+ } finally {+ actions.enableSourceToolComplete()}- actions.enableSourceToolComplete()},setDataWarehouseSourceEnabled: ({ source, enabled }) => {const { completion } = WAREHOUSE_SOURCE_SETUP[source]