Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(onboarding): compose flow from per-product step providers (#57579)

Fernando Gomes706db7c3d5ee
diff --git a/frontend/package.json b/frontend/package.json
index 810260156cab..3228749c426a 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -103,6 +103,7 @@
"@posthog/products-replay": "workspace:*",
"@posthog/products-replay-vision": "workspace:*",
"@posthog/products-revenue-analytics": "workspace:*",
+ "@posthog/products-session-replay": "workspace:*",
"@posthog/products-session-summaries": "workspace:*",
"@posthog/products-surveys": "workspace:*",
"@posthog/products-tasks": "workspace:*",
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ede58a345f70..86cfc47896fe 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1429,7 +1429,7 @@ snapshots:
exporter-funnels--funnel-left-to-right-breakdown-insight--light:
hash: v1.k794b7964.356f222b7bb0e751fb97c31194cfa581c2f8e2a20fa082c547919e4be56bd467.v_ydIqgDEzUkU7qXHZA86gtNMDzG5tKOuLVBmE92hwQ
exporter-funnels--funnel-left-to-right-insight--dark:
- hash: v1.k794b7964.cef23b57da6622305304db51e2440e1197443fc75c08cf85074bb6d9d6a21efb.s_VidsIoKt2ldoOeBXySOUIvsE4kXHhjG9WzN_wxttw
+ hash: v1.k794b7964.77f4bbfacf05973cfa74be85dabf52dddc6bf7ee0e166938fd11a61d790007bf.MNcgTyREi7N9PTllc2pVkibKrSlF03e5ry7Gi2i5Azc
exporter-funnels--funnel-left-to-right-insight--light:
hash: v1.k794b7964.557c7929127d2ff2d13bea0843d557abdac43752101e625a7e55783767b4d4e9.x_dm0hlgOTogGEUOAXd3-0QUcU7O5yCdrw3cA_3bYlI
exporter-funnels--funnel-left-to-right-insight-no-results--dark:
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index e103427c4eae..902933cee3eb 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -899,8 +899,14 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
reportProductUnsubscribed: (product: string) => ({ product }),
reportSubscribedDuringOnboarding: (productKey: string) => ({ productKey }),
reportOnboardingStarted: (entrypoint: string) => ({ entrypoint }),
- reportOnboardingStepCompleted: (stepKey: OnboardingStepKey) => ({ stepKey }),
- reportOnboardingStepSkipped: (stepKey: OnboardingStepKey) => ({ stepKey }),
+ reportOnboardingStepCompleted: (stepKey: OnboardingStepKey, productKey?: string) => ({
+ stepKey,
+ productKey,
+ }),
+ reportOnboardingStepSkipped: (stepKey: OnboardingStepKey, productKey?: string) => ({
+ stepKey,
+ productKey,
+ }),
reportOnboardingCompleted: (productKey: string) => ({ productKey }),
reportOnboardingUseCaseSelected: (useCase: string, recommendedProducts: readonly string[]) => ({
useCase,
@@ -2123,14 +2129,18 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
entry_point: entrypoint,
})
},
- reportOnboardingStepCompleted: ({ stepKey }) => {
+ reportOnboardingStepCompleted: ({ stepKey, productKey }) => {
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 } : {}),
})
},
- reportOnboardingStepSkipped: ({ stepKey }) => {
+ reportOnboardingStepSkipped: ({ stepKey, productKey }) => {
posthog.capture('onboarding step skipped', {
step_key: stepKey,
+ ...(productKey ? { product_key: productKey } : {}),
})
},
reportOnboardingCompleted: ({ productKey }) => {
diff --git a/frontend/src/scenes/authentication/signup/verify-email/verifyEmailLogic.ts b/frontend/src/scenes/authentication/signup/verify-email/verifyEmailLogic.ts
index 57c0814c21c2..b66dc2bfe120 100644
--- a/frontend/src/scenes/authentication/signup/verify-email/verifyEmailLogic.ts
+++ b/frontend/src/scenes/authentication/signup/verify-email/verifyEmailLogic.ts
@@ -10,10 +10,20 @@ import { userLogic } from 'scenes/userLogic'
import type { verifyEmailLogicType } from './verifyEmailLogicType'
-/** Delay between a successful verification and redirecting to the app.
- * Must stay in sync with the `VerifyEmail__Progress` animation duration in VerifyEmail.scss. */
+// Must stay in sync with the `VerifyEmail__Progress` animation duration in VerifyEmail.scss.
export const VERIFY_EMAIL_REDIRECT_DELAY_MS = 2000
+const resolvePostVerifyDefault = (values: {
+ user?: { team?: { has_completed_onboarding_for?: Record<string, boolean> } | null } | null
+}): string => {
+ if (!values.user) {
+ return urls.default()
+ }
+ const completedMap = values.user.team?.has_completed_onboarding_for ?? {}
+ const hasCompletedSomething = Object.values(completedMap).some(Boolean)
+ return hasCompletedSomething ? urls.default() : urls.onboarding()
+}
+
export interface ResponseType {
success: boolean
errorCode?: string
@@ -58,11 +68,9 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([
// this url is validated in getRelativeNextPath as either being relative or on the same origin
// this url is also secret and so we can trust it's not attacker controlled
// nosemgrep: javascript.browser.security.open-redirect.js-open-redirect
- location.href = nextUrl || '/'
+ location.href = nextUrl || resolvePostVerifyDefault(values)
return { success: true, token, uuid }
} catch (e: any) {
- // If the token is invalid but the user is already logged in and verified,
- // treat this as success (likely a page refresh after the first successful POST)
const user = (values as any).user
if (user?.is_email_verified) {
actions.setView('success')
@@ -73,7 +81,7 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([
)
// this url is validated in getRelativeNextPath as either being relative or on the same origin
// nosemgrep: javascript.browser.security.open-redirect.js-open-redirect
- location.href = nextUrl || '/'
+ location.href = nextUrl || resolvePostVerifyDefault(values)
return { success: true, token, uuid }
}
actions.setView('invalid')
diff --git a/frontend/src/scenes/onboarding/Onboarding.stories.tsx b/frontend/src/scenes/onboarding/Onboarding.stories.tsx
index a63fcd8d5fa1..6baeace2a087 100644
--- a/frontend/src/scenes/onboarding/Onboarding.stories.tsx
+++ b/frontend/src/scenes/onboarding/Onboarding.stories.tsx
@@ -322,12 +322,14 @@ export const BillingPlans: Story = {
},
})
- const { setProduct } = useActions(onboardingLogic)
-
useDelayedOnMountEffect(() => {
- setProduct(availableOnboardingProducts[ProductKey.PRODUCT_ANALYTICS])
router.actions.push(
- urls.onboarding({ productKey: ProductKey.PRODUCT_ANALYTICS, stepKey: OnboardingStepKey.PLANS })
+ urls.onboarding({
+ productKey: ProductKey.PRODUCT_ANALYTICS,
+ // Use the namespaced id so currentFlowStep resolves via exact match
+ // (loose-match by bare stepKey races with the billing-gated flow rebuild).
+ step: `${OnboardingStepKey.PLANS}:${ProductKey.PRODUCT_ANALYTICS}`,
+ })
)
})
diff --git a/frontend/src/scenes/onboarding/Onboarding.tsx b/frontend/src/scenes/onboarding/Onboarding.tsx
index fa21fd716d49..9ad6bce95cf0 100644
--- a/frontend/src/scenes/onboarding/Onboarding.tsx
+++ b/frontend/src/scenes/onboarding/Onboarding.tsx
@@ -1,52 +1,10 @@
-import { useActions, useValues } from 'kea'
-import { useEffect } from 'react'
+import { useValues } from 'kea'
-import { LemonBanner, Link, Spinner } from '@posthog/lemon-ui'
-
-import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
-import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
-import { OrganizationMembershipLevel, SESSION_REPLAY_MINIMUM_DURATION_OPTIONS } from 'lib/constants'
-import { billingLogic } from 'scenes/billing/billingLogic'
-import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'
import { ProductSelection } from 'scenes/onboarding/productSelection/ProductSelection'
-import { productSelectionLogic } from 'scenes/onboarding/productSelection/productSelectionLogic'
-import { useWizardCommand } from 'scenes/onboarding/sdks/sdk-install-instructions/components/SetupWizardBanner'
-import { WebAnalyticsSDKInstructions } from 'scenes/onboarding/sdks/web-analytics/WebAnalyticsSDKInstructions'
-import { organizationLogic } from 'scenes/organizationLogic'
import { SceneExport } from 'scenes/sceneTypes'
-import { getMaskingConfigFromLevel, getMaskingLevelFromConfig } from 'scenes/session-recordings/utils'
-import { teamLogic } from 'scenes/teamLogic'
-import { userLogic } from 'scenes/userLogic'
-
-import { ProductKey } from '~/queries/schema/schema-general'
-import { AvailableFeature, type SessionRecordingMaskingLevel, TeamPublicType, TeamType } from '~/types'
-import { OnboardingUpgradeStep } from './billing/OnboardingUpgradeStep'
-import { OnboardingDataWarehouseSourcesStep } from './data-warehouse/OnboardingDataWarehouseSourcesStep'
-import { OnboardingErrorTrackingAlertsStep } from './error-tracking/OnboardingErrorTrackingAlertsStep'
-import { OnboardingErrorTrackingSourceMapsStep } from './error-tracking/OnboardingErrorTrackingSourceMapsStep'
-import { OnboardingInviteTeammates } from './OnboardingInviteTeammates'
-import { OnboardingLogicProps, OnboardingStepElement, onboardingLogic } from './onboardingLogic'
-import { OnboardingProductConfiguration } from './OnboardingProductConfiguration'
-import { ProductConfigOption } from './onboardingProductConfigurationLogic'
-import { OnboardingSessionReplayConfiguration } from './OnboardingSessionReplayConfiguration'
-import { ErrorTrackingSDKInstructions } from './sdks/error-tracking/ErrorTrackingSDKInstructions'
-import { ExperimentsSDKInstructions } from './sdks/experiments/ExperimentsSDKInstructions'
-import { FeatureFlagsSDKInstructions } from './sdks/feature-flags/FeatureFlagsSDKInstructions'
-import {
- LLMAnalyticsSDKInstructions,
- LLMAnalyticsSDKTagOverrides,
-} from './sdks/llm-analytics/LLMAnalyticsSDKInstructions'
-import { LogsSDKInstructions } from './sdks/logs/LogsSDKInstructions'
-import { OnboardingInstallStep } from './sdks/OnboardingInstallStep'
-import {
- ProductAnalyticsSDKInstructions,
- ProductAnalyticsSDKTagOverrides,
-} from './sdks/product-analytics/ProductAnalyticsSDKInstructions'
-import { SessionReplaySDKInstructions } from './sdks/session-replay/SessionReplaySDKInstructions'
-import { SurveysSDKInstructions } from './sdks/surveys/SurveysSDKInstructions'
-import { WorkflowsSDKInstructions, WorkflowsSDKTagOverrides } from './sdks/workflows/WorkflowsSDKInstructions'
-import { OnboardingWebAnalyticsAuthorizedDomainsStep } from './web-analytics/OnboardingWebAnalyticsAuthorizedDomainsStep'
+import { OnboardingFlowHost } from './OnboardingFlowHost'
+import { onboardingLogic } from './onboardingLogic'
export const scene: SceneExport = {
component: Onboarding,
@@ -54,451 +12,22 @@ export const scene: SceneExport = {
}
/**
- * Wrapper for custom onboarding content. This automatically includes billing, other products, and invite steps.
+ * Onboarding scene shell.
+ *
+ * - No `productKey` in the URL → render the product-selection landing page.
+ * - With a `productKey` → hand off to {@link OnboardingFlowHost}, which renders the
+ * current step out of the data-driven flow built by `onboardingLogic.flow`.
*/
-const OnboardingWrapper = ({
- children,
- ...logicProps
-}: { children: React.ReactNode } & OnboardingLogicProps): JSX.Element => {
- const logic = onboardingLogic(logicProps)
- const {
- currentOnboardingStep,
- shouldShowBillingStep,
- shouldShowDataWarehouseStep,
- product,
- billingProduct,
- waitForBilling,
- } = useValues(logic)
- const { setAllOnboardingSteps } = useActions(logic)
- const { billingLoading } = useValues(billingLogic)
- const { currentOrganization } = useValues(organizationLogic)
-
- const minAdminRestrictionReason = useRestrictedArea({
- minimumAccessLevel: OrganizationMembershipLevel.Admin,
- scope: RestrictionScope.Organization,
- })
-
- useEffect(() => {
- if (billingLoading && waitForBilling) {
- return
- }
-
- let steps: OnboardingStepElement[] = []
- if (Array.isArray(children)) {
- steps = [...children]
- } else {
- steps = [children as OnboardingStepElement]
- }
-
- if (shouldShowDataWarehouseStep) {
- const DataWarehouseStep = <OnboardingDataWarehouseSourcesStep />
- steps = [...steps, DataWarehouseStep]
- }
-
- if (shouldShowBillingStep && billingProduct) {
- const BillingStep = <OnboardingUpgradeStep product={billingProduct} />
-
- steps = [...steps, BillingStep]
- }
-
- const userCannotInvite = Boolean(minAdminRestrictionReason) && !currentOrganization?.members_can_invite
- if (!userCannotInvite) {
- const inviteTeammatesStep = <OnboardingInviteTeammates />
- steps = [...steps, inviteTeammatesStep]
- }
-
- setAllOnboardingSteps(steps.filter(Boolean))
- }, [children, billingLoading, waitForBilling, minAdminRestrictionReason, currentOrganization]) // oxlint-disable-line react-hooks/exhaustive-deps
-
- if (!product || !children) {
- return <></>
- }
-
- if (!currentOnboardingStep) {
- return (
- <div className="flex items-center justify-center my-20">
- <Spinner className="text-2xl text-secondary w-10 h-10" />
- </div>
- )
- }
-
- return currentOnboardingStep
-}
-
-const sessionReplayOnboardingToggle = (
- currentTeam: TeamType | TeamPublicType | null,
- selectedProducts: ProductKey[]
-): ProductConfigOption => {
- const userDecision =
- currentTeam?.session_recording_opt_in ||
- selectedProducts.includes(ProductKey.SESSION_REPLAY) ||
- currentTeam?.product_intents?.some((intent) => intent.product_type === ProductKey.SESSION_REPLAY)
-
- return {
- title: 'Enable session recordings',
- description: `Turn on session recordings and watch how users experience your app. We will also turn on console log and network performance recording. You can change these settings any time in the settings panel.`,
- teamProperty: 'session_recording_opt_in',
- // TRICKY: if someone has shown secondary (or tertiary or...) product intent for replay we want to include it as enabled
- // particularly while we're not taking people through every product onboarding they showed interest in
- value: userDecision ?? false,
- type: 'toggle',
- visible: true,
- }
-}
-const ProductAnalyticsOnboarding = (): JSX.Element => {
- const { currentTeam } = useValues(teamLogic)
- const { selectedProducts } = useValues(productSelectionLogic)
-
- // mount the logic here so that it stays mounted for the entire onboarding flow
- // not sure if there is a better way to do this
- useValues(newDashboardLogic)
-
- const options: ProductConfigOption[] = [
- {
- title: 'Autocapture frontend interactions',
- description: `If you use our JavaScript, React Native or iOS libraries, we'll automagically
- capture frontend interactions like clicks, submits, and more. Fine-tune what you
- capture directly in your code snippet.`,
- teamProperty: 'autocapture_opt_out',
- value: !currentTeam?.autocapture_opt_out,
- type: 'toggle',
- inverseToggle: true,
- visible: true,
- },
- {
- title: 'Enable heatmaps',
- description: `If you use our JavaScript libraries, we can capture general clicks, mouse movements,
- and scrolling to create heatmaps.
- No additional events are created, and you can disable this at any time.`,
- teamProperty: 'heatmaps_opt_in',
- value: currentTeam?.heatmaps_opt_in ?? true,
- type: 'toggle',
- visible: true,
- },
- {
- title: 'Enable web vitals autocapture',
- description: `Uses Google's web vitals library to automagically capture performance information.`,
- teamProperty: 'autocapture_web_vitals_opt_in',
- value: currentTeam?.autocapture_web_vitals_opt_in ?? true,
- type: 'toggle',
- visible: true,
- },
- sessionReplayOnboardingToggle(currentTeam, selectedProducts),
- {
- title: 'Capture console logs',
- description: `Automatically enable console log capture`,
- teamProperty: 'capture_console_log_opt_in',
- value: true,
- type: 'toggle',
- visible: false,
- },
- {
- title: 'Capture network performance',
- description: `Automatically enable network performance capture`,
- teamProperty: 'capture_performance_opt_in',
- value: true,
- type: 'toggle',
- visible: false,
- },
- ]
-
- const filteredOptions = options.filter((option) => option.teamProperty !== 'session_recording_opt_in')
-
- return (
- <OnboardingWrapper>
- <OnboardingInstallStep
- sdkInstructionMap={ProductAnalyticsSDKInstructions}
- sdkTagOverrides={ProductAnalyticsSDKTagOverrides}
- />
- <OnboardingProductConfiguration options={filteredOptions} />
-
- <OnboardingSessionReplayConfiguration />
- </OnboardingWrapper>
- )
-}
-
-const WebAnalyticsOnboarding = (): JSX.Element => {
- const { currentTeam } = useValues(teamLogic)
- const { selectedProducts } = useValues(productSelectionLogic)
-
- const options: ProductConfigOption[] = [
- {
- title: 'Autocapture frontend interactions',
- description: `If you use our JavaScript, React Native or iOS libraries, we'll automagically
- capture frontend interactions like clicks, submits, and more. Fine-tune what you
- capture directly in your code snippet.`,
- teamProperty: 'autocapture_opt_out',
- value: !currentTeam?.autocapture_opt_out,
- type: 'toggle',
- inverseToggle: true,
- visible: true,
- },
- {
- title: 'Enable heatmaps',
- description: `If you use our JavaScript libraries, we can capture general clicks, mouse movements,
- and scrolling to create heatmaps.
- No additional events are created, and you can disable this at any time.`,
- teamProperty: 'heatmaps_opt_in',
- value: currentTeam?.heatmaps_opt_in ?? true,
- type: 'toggle',
- visible: true,
- },
- {
- title: 'Enable web vitals autocapture',
- description: `Uses Google's web vitals library to automagically capture performance information.`,
- teamProperty: 'autocapture_web_vitals_opt_in',
- value: currentTeam?.autocapture_web_vitals_opt_in ?? true,
- type: 'toggle',
- visible: true,
- },
- sessionReplayOnboardingToggle(currentTeam, selectedProducts),
- {
- title: 'Capture network performance',
- description: `Automatically enable network performance capture`,
- teamProperty: 'capture_performance_opt_in',
- value: true,
- type: 'toggle',
- visible: false,
- },
- ]
-
- return (
- <OnboardingWrapper>
- <OnboardingInstallStep sdkInstructionMap={WebAnalyticsSDKInstructions} />
- <OnboardingWebAnalyticsAuthorizedDomainsStep />
- <OnboardingProductConfiguration options={options} />
- </OnboardingWrapper>
- )
-}
-
-const SessionReplayOnboarding = (): JSX.Element => {
- const { hasAvailableFeature } = useValues(userLogic)
- const { currentTeam } = useValues(teamLogic)
-
- const configOptions: ProductConfigOption[] = [
- {
- type: 'toggle',
- title: 'Capture console logs',
- description: `Capture console logs as a part of user session recordings.
- Use the console logs alongside recordings to debug any issues with your app.`,
- teamProperty: 'capture_console_log_opt_in',
- value: currentTeam?.capture_console_log_opt_in ?? true,
- visible: true,
- },
- {
- type: 'toggle',
- title: 'Capture network performance',
- description: `Capture performance and network information alongside recordings. Use the
- network requests and timings in the recording player to help you debug issues with your app.`,
- teamProperty: 'capture_performance_opt_in',
- value: currentTeam?.capture_performance_opt_in ?? true,
- visible: true,
- },
- {
- type: 'toggle',
- title: 'Record user sessions',
- description: 'Watch recordings of how users interact with your web app to see what can be improved.',
- teamProperty: 'session_recording_opt_in',
- value: true,
- visible: false,
- },
- {
- type: 'select',
- title: 'Masking',
- description: 'Choose the level of masking for your recordings.',
- value: getMaskingLevelFromConfig(currentTeam?.session_recording_masking_config ?? {}),
- teamProperty: 'session_recording_masking_config',
- onChange: (value: string | number | null) => {
- return {
- session_recording_masking_config: getMaskingConfigFromLevel(value as SessionRecordingMaskingLevel),
- }
- },
- selectOptions: [
- { value: 'total-privacy', label: 'Total privacy (mask all text/images)' },
- { value: 'normal', label: 'Normal (mask inputs but not text/images)' },
- { value: 'free-love', label: 'Free love (mask only passwords)' },
- ],
- visible: true,
- },
- ]
-
- if (hasAvailableFeature(AvailableFeature.REPLAY_RECORDING_DURATION_MINIMUM)) {
- configOptions.push({
- type: 'select',
- title: 'Minimum session duration (seconds)',
- description: `Only record sessions that are longer than the specified duration.
- Start with it low and increase it later if you're getting too many short sessions.`,
- teamProperty: 'session_recording_minimum_duration_milliseconds',
- value: currentTeam?.session_recording_minimum_duration_milliseconds || null,
- selectOptions: SESSION_REPLAY_MINIMUM_DURATION_OPTIONS,
- visible: true,
- })
- }
-
- return (
- <OnboardingWrapper>
- <OnboardingInstallStep sdkInstructionMap={SessionReplaySDKInstructions} />
- <OnboardingProductConfiguration options={configOptions} />
- </OnboardingWrapper>
- )
-}
-
-const FeatureFlagsOnboarding = (): JSX.Element => {
- return (
- <OnboardingWrapper>
- <OnboardingInstallStep sdkInstructionMap={FeatureFlagsSDKInstructions} />
- </OnboardingWrapper>
- )
-}
-
-const ExperimentsOnboarding = (): JSX.Element => {
- return (
- <OnboardingWrapper>
- <OnboardingInstallStep sdkInstructionMap={ExperimentsSDKInstructions} />
- </OnboardingWrapper>
- )
-}
-
-const SurveysOnboarding = (): JSX.Element => {
- return (
- <OnboardingWrapper>
- <OnboardingInstallStep sdkInstructionMap={SurveysSDKInstructions} />
- </OnboardingWrapper>
- )
-}
-
-const DataWarehouseOnboarding = (): JSX.Element => {
- return (
- <OnboardingWrapper>
- <OnboardingDataWarehouseSourcesStep />
- </OnboardingWrapper>
- )
-}
-
-const ErrorTrackingOnboarding = (): JSX.Element => {
- const { updateCurrentTeam } = useActions(teamLogic)
-
- return (
- <OnboardingWrapper
- onCompleteOnboarding={(productKey) => {
- if (productKey === ProductKey.ERROR_TRACKING) {
- updateCurrentTeam({ autocapture_exceptions_opt_in: true })
- }
- }}
- >
- <OnboardingInstallStep sdkInstructionMap={ErrorTrackingSDKInstructions} />
- <OnboardingErrorTrackingSourceMapsStep />
- <OnboardingErrorTrackingAlertsStep />
- </OnboardingWrapper>
- )
-}
-
-const LLMAnalyticsOnboarding = (): JSX.Element => {
- return (
- <OnboardingWrapper>
- <OnboardingInstallStep
- sdkInstructionMap={LLMAnalyticsSDKInstructions}
- sdkTagOverrides={LLMAnalyticsSDKTagOverrides}
- listeningForName="LLM generation"
- />
- </OnboardingWrapper>
- )
-}
-
-const WorkflowsOnboarding = (): JSX.Element => {
- return (
- <OnboardingWrapper>
- <OnboardingInstallStep
- sdkInstructionMap={WorkflowsSDKInstructions}
- sdkTagOverrides={WorkflowsSDKTagOverrides}
- header={<WorkflowsInstallHeader />}
- />
- </OnboardingWrapper>
- )
-}
-
-const LogsOnboarding = (): JSX.Element => {
- return (
- <OnboardingWrapper>
- <OnboardingInstallStep sdkInstructionMap={LogsSDKInstructions} hideInstallationCheck />
- </OnboardingWrapper>
- )
-}
-
-const WorkflowsInstallHeader = (): JSX.Element => {
- const { wizardCommand, isCloudOrDev } = useWizardCommand()
-
- return (
- <div className="mt-2 space-y-4">
- <p className="text-sm">
- Workflows is a no-code product - installing an SDK is optional. However, with an SDK installed, any
- captured or custom event can be used as a{' '}
- <Link
- to="https://posthog.com/docs/workflows/workflow-builder#triggers"
- target="_blank"
- targetBlankIcon={false}
- >
- workflow trigger
- </Link>
- . Without an SDK, you're limited to webhook and manual triggers.
- </p>
- {isCloudOrDev && (
- <>
- <LemonBanner type="info" hideIcon>
- <h3 className="pb-1">AI setup wizard</h3>
- <div className="flex flex-col p-2">
- <p className="font-normal pb-1">
- The fastest way to get started. Run this command from your project root — it
- automatically detects your framework, installs PostHog, and sets up event capture.
- </p>
- <CodeSnippet language={Language.Bash}>{wizardCommand}</CodeSnippet>
- </div>
- </LemonBanner>
- <p className="text-sm">
- After the wizard finishes, <Link to="/workflows/channels">configure a channel</Link> then head
- to the <Link to="/workflows">workflow builder</Link> to create your first automation.
- </p>
- <div className="flex items-center gap-3">
- <div className="flex-1 border-t border-border" />
- <span className="text-muted font-semibold text-xs uppercase">Or, set up manually</span>
- <div className="flex-1 border-t border-border" />
- </div>
- </>
- )}
- </div>
- )
-}
-
-export const onboardingViews = {
- [ProductKey.PRODUCT_ANALYTICS]: ProductAnalyticsOnboarding,
- [ProductKey.WEB_ANALYTICS]: WebAnalyticsOnboarding,
- [ProductKey.SESSION_REPLAY]: SessionReplayOnboarding,
- [ProductKey.FEATURE_FLAGS]: FeatureFlagsOnboarding,
- [ProductKey.EXPERIMENTS]: ExperimentsOnboarding,
- [ProductKey.SURVEYS]: SurveysOnboarding,
- [ProductKey.DATA_WAREHOUSE]: DataWarehouseOnboarding,
- [ProductKey.ERROR_TRACKING]: ErrorTrackingOnboarding,
- [ProductKey.LLM_ANALYTICS]: LLMAnalyticsOnboarding,
- [ProductKey.WORKFLOWS]: WorkflowsOnboarding,
- [ProductKey.LOGS]: LogsOnboarding,
-}
-
export function Onboarding(): JSX.Element | null {
- const { product, productKey } = useValues(onboardingLogic)
+ const { productKey } = useValues(onboardingLogic)
if (!productKey) {
return <ProductSelection />
}
- if (!product) {
- return <></>
- }
-
- const OnboardingView = onboardingViews[productKey as keyof typeof onboardingViews]
-
return (
<div className="pt-4 pb-10">
- <OnboardingView />
+ <OnboardingFlowHost />
</div>
)
}
diff --git a/frontend/src/scenes/onboarding/OnboardingBreadcrumbs.tsx b/frontend/src/scenes/onboarding/OnboardingBreadcrumbs.tsx
index 7f090c33c396..02f5addea8eb 100644
--- a/frontend/src/scenes/onboarding/OnboardingBreadcrumbs.tsx
+++ b/frontend/src/scenes/onboarding/OnboardingBreadcrumbs.tsx
@@ -9,45 +9,73 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { OnboardingStepKey } from '~/types'
-import { onboardingLogic, stepKeyToTitle } from './onboardingLogic'
+import { stepKeyToTitle } from './onboardingFlowUtils'
+import { onboardingLogic } from './onboardingLogic'
+import { INSTALL_DEDUP_KEYS } from './types'
+import { availableOnboardingProducts } from './utils'
-interface OnboardingBreadcrumbsProps {
- stepKey: OnboardingStepKey
- breadcrumbHighlightName?: OnboardingStepKey
-}
-
-export function OnboardingBreadcrumbs({
- stepKey,
- breadcrumbHighlightName,
-}: OnboardingBreadcrumbsProps): JSX.Element | null {
- const { onboardingStepKeys } = useValues(onboardingLogic)
- const { setStepKey } = useActions(onboardingLogic)
+export function OnboardingBreadcrumbs(): JSX.Element | null {
+ const { flow, currentFlowStep } = useValues(onboardingLogic)
+ const { setStepId } = useActions(onboardingLogic)
const hideBreadcrumbs = useFeatureFlag('ONBOARDING_HIDE_BREADCRUMBS', 'test')
if (hideBreadcrumbs) {
return null
}
- const stepCount = onboardingStepKeys.length
+ const stepCount = flow.length
+ const activeId = currentFlowStep?.id
+
+ // Disambiguate duplicate step types by appending the product name. This keeps a
+ // flow like `Install (PA) → Install (SR) → Install (WA)` readable instead of three
+ // identical "Install" labels.
+ const stepKeyCounts = flow.reduce<Record<string, number>>((acc, step) => {
+ acc[step.stepKey] = (acc[step.stepKey] ?? 0) + 1
+ return acc
+ }, {})
+ const labelForStep = (step: (typeof flow)[number]): string => {
+ if (step.label) {
+ return step.label
+ }
+ // The posthog-js install step is shared across products via dedup, so it gets
+ // a generic "Install" label rather than being titled after whichever product
+ // happens to be the dedup survivor (which would be misleading when it
+ // actually installs the SDK for several products at once).
+ if (step.stepKey === OnboardingStepKey.INSTALL && step.dedupKey === INSTALL_DEDUP_KEYS.POSTHOG_JS) {
+ return 'Install'
+ }
+ const base = stepKeyToTitle(step.stepKey) ?? step.stepKey
+ if (stepKeyCounts[step.stepKey] > 1) {
+ const productName =
+ availableOnboardingProducts[step.productKey as keyof typeof availableOnboardingProducts]?.name
+ if (productName) {
+ // Middle dot scopes the product name as a qualifier rather than reading
+ // as one phrase ("Install · Web Analytics" instead of "Install Web Analytics").
+ // Product names use the registry's Title Case ("Product Analytics",
+ // "LLM Analytics") as-is — these are proper-noun product names.
+ return `${base} · ${productName}`
+ }
+ }
+ return base
+ }
return (
<div
className="flex items-center justify-start gap-x-3 px-4 sm:px-2 w-full overflow-x-auto [mask-image:linear-gradient(to_right,black_calc(100%-24px),transparent)] sm:[mask-image:none]"
data-attr="onboarding-breadcrumbs"
>
- {onboardingStepKeys.map((stepName, idx) => {
- const highlightStep = [stepKey, breadcrumbHighlightName].includes(stepName)
+ {flow.map((step, idx) => {
+ const highlightStep = step.id === activeId
+ const label = labelForStep(step)
return (
- <React.Fragment key={`stepKey-${idx}`}>
+ <React.Fragment key={`stepId-${step.id}-${idx}`}>
<Link
className={clsx('text-sm shrink-0 whitespace-nowrap', highlightStep && 'font-bold')}
- data-text={stepKeyToTitle(stepName)}
- key={stepName}
- onClick={() => setStepKey(stepName)}
+ data-text={label}
+ key={step.id}
+ onClick={() => setStepId(step.id)}
>
- <span className={clsx('text-sm', !highlightStep && 'text-muted')}>
- {stepKeyToTitle(stepName)}
- </span>
+ <span className={clsx('text-sm', !highlightStep && 'text-muted')}>{label}</span>
</Link>
{stepCount > 1 && idx !== stepCount - 1 && <IconChevronRight className="text-xl shrink-0" />}
</React.Fragment>
diff --git a/frontend/src/scenes/onboarding/OnboardingFlowHost.tsx b/frontend/src/scenes/onboarding/OnboardingFlowHost.tsx
new file mode 100644
index 000000000000..c98c4ea9166b
--- /dev/null
+++ b/frontend/src/scenes/onboarding/OnboardingFlowHost.tsx
@@ -0,0 +1,49 @@
+import { useValues } from 'kea'
+import posthog from 'posthog-js'
+import { useEffect } from 'react'
+
+import { LemonBanner, Link, Spinner } from '@posthog/lemon-ui'
+
+import { billingLogic } from 'scenes/billing/billingLogic'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { onboardingLogic } from './onboardingLogic'
+
+export function OnboardingFlowHost(): JSX.Element {
+ const { product, productKey, currentFlowStep, flow, waitForBilling } = useValues(onboardingLogic)
+ const { billingLoading } = useValues(billingLogic)
+ const { currentTeam } = useValues(teamLogic)
+
+ const isMisconfigured = productKey && product && !billingLoading && currentTeam !== null && flow.length === 0
+ const isLoading = !isMisconfigured && ((billingLoading && waitForBilling) || !product || !currentFlowStep)
+
+ useEffect(() => {
+ if (isMisconfigured) {
+ posthog.captureException(new Error('Onboarding flow misconfigured: product registered but no flow steps'), {
+ productKey,
+ })
+ }
+ }, [isMisconfigured, productKey])
+
+ if (isMisconfigured) {
+ return (
+ <div className="max-w-screen-md mx-auto px-4 py-2">
+ <LemonBanner type="error">
+ We couldn't load the onboarding flow for this product. Try{' '}
+ <Link to={urls.onboarding()}>going back to product selection</Link>.
+ </LemonBanner>
+ </div>
+ )
+ }
+
+ if (isLoading || !currentFlowStep) {
+ return (
+ <div className="flex items-center justify-center my-20" role="status" aria-label="Loading onboarding">
+ <Spinner className="text-2xl text-secondary w-10 h-10" />
+ </div>
+ )
+ }
+
+ return currentFlowStep.render()
+}
diff --git a/frontend/src/scenes/onboarding/OnboardingStep.tsx b/frontend/src/scenes/onboarding/OnboardingStep.tsx
index 6859903579c1..bef974bb770e 100644
--- a/frontend/src/scenes/onboarding/OnboardingStep.tsx
+++ b/frontend/src/scenes/onboarding/OnboardingStep.tsx
@@ -10,7 +10,8 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { OnboardingStepKey } from '~/types'
import { OnboardingBreadcrumbs } from './OnboardingBreadcrumbs'
-import { onboardingLogic, stepKeyToTitle } from './onboardingLogic'
+import { stepKeyToTitle } from './onboardingFlowUtils'
+import { onboardingLogic } from './onboardingLogic'
export const OnboardingStep = ({
stepKey,
@@ -25,7 +26,6 @@ export const OnboardingStep = ({
continueText,
continueDisabledReason,
hideHeader,
- breadcrumbHighlightName,
fullWidth = false,
actions,
}: {
@@ -41,11 +41,10 @@ export const OnboardingStep = ({
continueText?: string
continueDisabledReason?: string
hideHeader?: boolean
- breadcrumbHighlightName?: OnboardingStepKey
fullWidth?: boolean
actions?: JSX.Element
}): JSX.Element => {
- const { hasNextStep } = useValues(onboardingLogic)
+ const { hasNextStep, currentStepProductKey } = useValues(onboardingLogic)
const { completeOnboarding, goToNextStep } = useActions(onboardingLogic)
const { reportOnboardingStepCompleted, reportOnboardingStepSkipped } = useActions(eventUsageLogic)
@@ -54,13 +53,13 @@ export const OnboardingStep = ({
const advance: () => void = !hasNextStep ? completeOnboarding : goToNextStep
const skip = (): void => {
- reportOnboardingStepSkipped(stepKey)
+ reportOnboardingStepSkipped(stepKey, currentStepProductKey ?? undefined)
onSkip?.()
advance()
}
const next = (): void => {
- reportOnboardingStepCompleted(stepKey)
+ reportOnboardingStepCompleted(stepKey, currentStepProductKey ?? undefined)
onContinue?.()
advance()
}
@@ -69,7 +68,7 @@ export const OnboardingStep = ({
<>
<div className="pb-2">
<div className={`text-secondary max-w-screen-md mx-auto ${hideHeader && 'hidden'}`}>
- <OnboardingBreadcrumbs stepKey={stepKey} breadcrumbHighlightName={breadcrumbHighlightName} />
+ <OnboardingBreadcrumbs />
<div className="flex flex-col sm:flex-row sm:justify-between sm:items-center items-start gap-2 mt-3 px-4 sm:px-0">
<h1 className={clsx('font-bold m-0 px-0 sm:px-2', fullWidth && 'text-center')}>
{title || stepKeyToTitle(stepKey)}
diff --git a/frontend/src/scenes/onboarding/exit/onboardingExitLogic.ts b/frontend/src/scenes/onboarding/exit/onboardingExitLogic.ts
index fcc65264c253..81a6fb7b734b 100644
--- a/frontend/src/scenes/onboarding/exit/onboardingExitLogic.ts
+++ b/frontend/src/scenes/onboarding/exit/onboardingExitLogic.ts
@@ -62,7 +62,7 @@ export const onboardingExitLogic = kea<onboardingExitLogicType>([
connect(() => ({
values: [
onboardingLogic,
- ['stepKey', 'onCompleteOnboardingRedirectUrl'],
+ ['currentStepKey', 'onCompleteOnboardingRedirectUrl'],
organizationLogic,
['currentOrganizationId'],
],
@@ -122,7 +122,7 @@ export const onboardingExitLogic = kea<onboardingExitLogicType>([
listeners(({ actions, values }) => ({
openExitModal: () => {
// Frontend-only event (no backend counterpart); the delegation success event is fired from the backend.
- posthog.capture('onboarding exit modal opened', { step_at_open: values.stepKey || null })
+ posthog.capture('onboarding exit modal opened', { step_at_open: values.currentStepKey || null })
// Snapshot the org so a mid-modal org switch in another tab can't redirect the
// submission to the wrong org.
actions.captureOrgIdAtOpen(values.currentOrganizationId ?? null)
@@ -161,7 +161,7 @@ export const onboardingExitLogic = kea<onboardingExitLogicType>([
await invitesDelegateCreate(orgId, {
target_email: values.targetEmail.trim(),
message: values.message.trim(),
- step_at_delegation: values.stepKey || '',
+ step_at_delegation: values.currentStepKey || '',
})
delegationCommitted = true
lemonToast.success(`Invitation sent to ${values.targetEmail.trim()}`)
diff --git a/frontend/src/scenes/onboarding/onboardingFlowUtils.ts b/frontend/src/scenes/onboarding/onboardingFlowUtils.ts
new file mode 100644
index 000000000000..cab593530704
--- /dev/null
+++ b/frontend/src/scenes/onboarding/onboardingFlowUtils.ts
@@ -0,0 +1,48 @@
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey } from '~/types'
+
+import { availableOnboardingProducts } from './utils'
+
+const STEP_KEY_TITLE_OVERRIDES: Partial<Record<OnboardingStepKey, string>> = {
+ [OnboardingStepKey.LINK_DATA]: 'Import data',
+}
+
+export const stepKeyToTitle = (stepKey?: OnboardingStepKey): undefined | string => {
+ if (!stepKey) {
+ return undefined
+ }
+ if (STEP_KEY_TITLE_OVERRIDES[stepKey]) {
+ return STEP_KEY_TITLE_OVERRIDES[stepKey]
+ }
+ return stepKey
+ .split('_')
+ .map((part, i) => (i == 0 ? part[0].toUpperCase() + part.substring(1) : part))
+ .join(' ')
+}
+
+export const MAX_WITH_PRODUCTS = 16
+const MAX_RAW_PRODUCT_TOKENS = 64
+
+// Dedupe before truncating so duplicate-stuffing can't push valid keys out of the result.
+export const parseProductsParam = (raw: unknown): ProductKey[] => {
+ const value = typeof raw === 'string' ? raw : ''
+ if (!value) {
+ return []
+ }
+ const unique = Array.from(new Set(value.split(',').slice(0, MAX_RAW_PRODUCT_TOKENS)))
+ return unique
+ .filter((k: string) => Object.hasOwn(availableOnboardingProducts, k))
+ .slice(0, MAX_WITH_PRODUCTS) as ProductKey[]
+}
+
+export const arraysEqual = <T>(a: readonly T[], b: readonly T[]): boolean => {
+ if (a.length !== b.length) {
+ return false
+ }
+ for (let i = 0; i < a.length; i++) {
+ if (a[i] !== b[i]) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/frontend/src/scenes/onboarding/onboardingLogic.test.ts b/frontend/src/scenes/onboarding/onboardingLogic.test.ts
new file mode 100644
index 000000000000..733a6b799174
--- /dev/null
+++ b/frontend/src/scenes/onboarding/onboardingLogic.test.ts
@@ -0,0 +1,586 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { SetupTaskId } from 'lib/components/ProductSetup'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { OnboardingStepKey } from '~/types'
+
+import { onboardingLogic } from './onboardingLogic'
+import { INSTALL_DEDUP_KEYS } from './types'
+
+/**
+ * Comprehensive coverage of the onboarding flow composition system. The flow selector
+ * is the central piece of the refactor and the place where regressions are most costly
+ * (wrong steps, missed dedup, mis-ordered installs, lost completion bookkeeping).
+ *
+ * Test focus:
+ * 1. Flow shape per single product and representative multi-product combos
+ * 2. Install-step dedup behaviour (POSTHOG_JS, OPENTELEMETRY, no-dedup)
+ * 3. Bucket sort: all installs first, posthog-js install first among them
+ * 4. URL parsing defenses (cap, dedupe, filter)
+ * 5. Navigation correctness (next/prev, bad stepId reconciliation)
+ * 6. Completion: visited-product credit, idempotency, additionalProductKeys merge
+ */
+describe('onboardingLogic — flow composition', () => {
+ let logic: ReturnType<typeof onboardingLogic.build>
+
+ beforeEach(() => {
+ localStorage.clear()
+ initKeaTests()
+ logic = onboardingLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ /** Convenience: list step ids for the active flow. */
+ const flowIds = (): string[] => logic.values.flow.map((s) => s.id)
+ /** Convenience: list step keys for the active flow. */
+ const flowStepKeys = (): OnboardingStepKey[] => logic.values.flow.map((s) => s.stepKey)
+
+ describe('single-product flows', () => {
+ // Each entry: [primaryProduct, expected step ids in order].
+ // Default test environment has the user as Admin (canInviteTeammates=true) and
+ // billing not loaded (shouldShowBillingStep=false), so flows include the invite
+ // step but not the plans step. Bucket sort puts the install step first.
+ const cases: Array<[ProductKey, string[]]> = [
+ [
+ ProductKey.PRODUCT_ANALYTICS,
+ [
+ 'install:product_analytics',
+ 'configure:product_analytics',
+ 'session_replay:product_analytics',
+ 'link_data:product_analytics',
+ 'invite_teammates:product_analytics',
+ ],
+ ],
+ [
+ ProductKey.WEB_ANALYTICS,
+ [
+ 'install:web_analytics',
+ 'authorized_domains:web_analytics',
+ 'configure:web_analytics',
+ 'invite_teammates:web_analytics',
+ ],
+ ],
+ [
+ ProductKey.SESSION_REPLAY,
+ ['install:session_replay', 'configure:session_replay', 'invite_teammates:session_replay'],
+ ],
+ [ProductKey.FEATURE_FLAGS, ['install:feature_flags', 'invite_teammates:feature_flags']],
+ [ProductKey.EXPERIMENTS, ['install:experiments', 'invite_teammates:experiments']],
+ [ProductKey.SURVEYS, ['install:surveys', 'invite_teammates:surveys']],
+ [
+ ProductKey.ERROR_TRACKING,
+ [
+ 'install:error_tracking',
+ 'source_maps:error_tracking',
+ 'alerts:error_tracking',
+ 'invite_teammates:error_tracking',
+ ],
+ ],
+ [ProductKey.LLM_ANALYTICS, ['install:llm_analytics', 'invite_teammates:llm_analytics']],
+ [ProductKey.WORKFLOWS, ['install:workflows', 'invite_teammates:workflows']],
+ [ProductKey.LOGS, ['install:logs', 'invite_teammates:logs']],
+ // Data Warehouse has no install step — the link_data step is the entry point.
+ [ProductKey.DATA_WAREHOUSE, ['link_data:data_warehouse', 'invite_teammates:data_warehouse']],
+ ]
+
+ it.each(cases)('builds the expected flow when only %s is selected', (product, expected) => {
+ logic.actions.setProductKey(product)
+ expect(flowIds()).toEqual(expected)
+ })
+
+ it('returns an empty flow when no product is selected', () => {
+ expect(logic.values.flow).toEqual([])
+ expect(logic.values.currentFlowStep).toBeNull()
+ })
+ })
+
+ describe('install-step dedup — POSTHOG_JS', () => {
+ it('collapses two posthog-js installs into one survivor (PA primary + WA secondary)', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setSecondaryProductKeys([ProductKey.WEB_ANALYTICS])
+
+ const installs = logic.values.flow.filter((s) => s.stepKey === OnboardingStepKey.INSTALL)
+ expect(installs).toHaveLength(1)
+ expect(installs[0].id).toBe('install:product_analytics')
+ expect(installs[0].dedupKey).toBe(INSTALL_DEDUP_KEYS.POSTHOG_JS)
+ })
+
+ it('credits dropped products via additionalProductKeys', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setSecondaryProductKeys([
+ ProductKey.WEB_ANALYTICS,
+ ProductKey.SESSION_REPLAY,
+ ProductKey.FEATURE_FLAGS,
+ ])
+
+ const survivor = logic.values.flow.find((s) => s.id === 'install:product_analytics')!
+ expect(survivor.additionalProductKeys).toEqual(
+ expect.arrayContaining([
+ ProductKey.PRODUCT_ANALYTICS,
+ ProductKey.WEB_ANALYTICS,
+ ProductKey.SESSION_REPLAY,
+ ProductKey.FEATURE_FLAGS,
+ ])
+ )
+ })
+
+ it('merges dropped setup task ids that differ from the survivor (SR.SetupSessionRecordings, ET.EnableErrorTracking)', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setSecondaryProductKeys([ProductKey.SESSION_REPLAY, ProductKey.ERROR_TRACKING])
+
+ const survivor = logic.values.flow.find((s) => s.id === 'install:product_analytics')!
+ // Survivor's own setupTaskId is `IngestFirstEvent`; dropped descriptors contribute
+ // their own task ids, which may include `IngestFirstEvent` from sibling posthog-js
+ // products (deduped against the survivor's own). The exact set depends on which
+ // products are picked — we assert the distinctive ones.
+ expect(survivor.additionalSetupTaskIds).toEqual(
+ expect.arrayContaining([SetupTaskId.SetupSessionRecordings, SetupTaskId.EnableErrorTracking])
+ )
+ })
+
+ it('all 7 posthog-js products yield exactly one install step', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setSecondaryProductKeys([
+ ProductKey.WEB_ANALYTICS,
+ ProductKey.SESSION_REPLAY,
+ ProductKey.FEATURE_FLAGS,
+ ProductKey.EXPERIMENTS,
+ ProductKey.SURVEYS,
+ ProductKey.ERROR_TRACKING,
+ ])
+
+ const installs = logic.values.flow.filter((s) => s.stepKey === OnboardingStepKey.INSTALL)
+ expect(installs).toHaveLength(1)
+ expect(installs[0].dedupKey).toBe(INSTALL_DEDUP_KEYS.POSTHOG_JS)
+ })
+
+ it('does not attach extras when only the primary contributes (no other products in dedup group)', () => {
+ // PA alone has dedupKey POSTHOG_JS but no other posthog-js product to merge with.
+ // Survivor should NOT carry additionalProductKeys / additionalSetupTaskIds since
+ // there's nothing to add (productKeys.length === 1, setupTaskIds.length === 0).
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ const survivor = logic.values.flow.find((s) => s.id === 'install:product_analytics')!
+ expect(survivor.additionalProductKeys).toBeUndefined()
+ expect(survivor.additionalSetupTaskIds).toBeUndefined()
+ })
+ })
+
+ describe('install-step dedup — OPENTELEMETRY', () => {
+ it('Logs install uses the OTEL dedup key (separate group from posthog-js)', () => {
+ logic.actions.setProductKey(ProductKey.LOGS)
+ const install = logic.values.flow.find((s) => s.stepKey === OnboardingStepKey.INSTALL)!
+ expect(install.dedupKey).toBe(INSTALL_DEDUP_KEYS.OPENTELEMETRY)
+ })
+
+ it('PA primary + Logs secondary keeps both install steps (different dedup groups)', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setSecondaryProductKeys([ProductKey.LOGS])
+
+ const installs = logic.values.flow.filter((s) => s.stepKey === OnboardingStepKey.INSTALL)
+ expect(installs).toHaveLength(2)
+ expect(installs.map((s) => s.dedupKey)).toEqual([
+ INSTALL_DEDUP_KEYS.POSTHOG_JS,
+ INSTALL_DEDUP_KEYS.OPENTELEMETRY,
+ ])
+ })
+ })
+
+ describe('install-step — no dedup', () => {
+ it('LLM Analytics + Workflows produce two install steps (neither has a dedupKey)', () => {
+ logic.actions.setProductKey(ProductKey.LLM_ANALYTICS)
+ logic.actions.setSecondaryProductKeys([ProductKey.WORKFLOWS])
+
+ const installs = logic.values.flow.filter((s) => s.stepKey === OnboardingStepKey.INSTALL)
+ expect(installs).toHaveLength(2)
+ expect(installs.every((s) => s.dedupKey === undefined)).toBe(true)
+ })
+
+ it('PA + LLM + Workflows + Logs yields four install steps (PA dedup, LLM, WF, LOGS dedup)', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setSecondaryProductKeys([ProductKey.LLM_ANALYTICS, ProductKey.WORKFLOWS, ProductKey.LOGS])
+
+ const installs = logic.values.flow.filter((s) => s.stepKey === OnboardingStepKey.INSTALL)
+ expect(installs.map((s) => s.id)).toEqual([
+ 'install:product_analytics',
+ 'install:llm_analytics',
+ 'install:workflows',
+ 'install:logs',
+ ])
+ })
+ })
+
+ describe('step ordering (bucket sort)', () => {
+ it('puts the posthog-js install first (bucket 0) for a multi-step PA primary flow', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ // PA emits: install, product_configuration, session_replay (configure)
+ // sharedSteps appends: link_data, invite_teammates
+ // After bucket sort: install (bucket 0) MUST be first.
+ expect(logic.values.flow[0].id).toBe('install:product_analytics')
+ })
+
+ it('all install steps come before any non-install step', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setSecondaryProductKeys([ProductKey.LLM_ANALYTICS, ProductKey.WORKFLOWS, ProductKey.LOGS])
+
+ const lastInstallIdx = logic.values.flow
+ .map((s, i) => (s.stepKey === OnboardingStepKey.INSTALL ? i : -1))
+ .filter((i) => i >= 0)
+ .pop()
+ const firstNonInstallIdx = logic.values.flow.findIndex((s) => s.stepKey !== OnboardingStepKey.INSTALL)
+ expect(lastInstallIdx!).toBeLessThan(firstNonInstallIdx)
+ })
+
+ it('non-install steps preserve their relative order after bucket sort (stable)', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ // PA's intra-product order is: install → product_configuration → session_replay.
+ // sharedSteps appends link_data, invite_teammates AFTER. Bucket sort moves
+ // install to position 0; the rest must keep their relative order.
+ const nonInstall = logic.values.flow.filter((s) => s.stepKey !== OnboardingStepKey.INSTALL)
+ expect(nonInstall.map((s) => s.stepKey)).toEqual([
+ OnboardingStepKey.PRODUCT_CONFIGURATION, // 'configure'
+ OnboardingStepKey.SESSION_REPLAY,
+ OnboardingStepKey.LINK_DATA,
+ OnboardingStepKey.INVITE_TEAMMATES,
+ ])
+ })
+
+ it('non-posthog-js install steps land in bucket 1 (after posthog-js install, before non-installs)', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setSecondaryProductKeys([ProductKey.LOGS])
+
+ const ids = flowIds()
+ const paInstallIdx = ids.indexOf('install:product_analytics')
+ const logsInstallIdx = ids.indexOf('install:logs')
+ const firstNonInstall = logic.values.flow.findIndex((s) => s.stepKey !== OnboardingStepKey.INSTALL)
+ expect(paInstallIdx).toBe(0)
+ expect(logsInstallIdx).toBe(1)
+ expect(firstNonInstall).toBeGreaterThan(logsInstallIdx)
+ })
+ })
+
+ describe('shared trailing steps', () => {
+ it('appends data-warehouse step for PA primary when DW is not in secondaries', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ const linkDataSteps = logic.values.flow.filter((s) => s.stepKey === OnboardingStepKey.LINK_DATA)
+ expect(linkDataSteps).toHaveLength(1)
+ expect(linkDataSteps[0].productKey).toBe(ProductKey.PRODUCT_ANALYTICS)
+ })
+
+ it('does NOT duplicate data-warehouse step when DW is also in secondaries', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setSecondaryProductKeys([ProductKey.DATA_WAREHOUSE])
+ const linkDataSteps = logic.values.flow.filter((s) => s.stepKey === OnboardingStepKey.LINK_DATA)
+ // DW provider's link_data emits once; sharedSteps' append is suppressed by the
+ // `secondaries.includes(DATA_WAREHOUSE)` check. Without that guard the user would
+ // walk through Import data twice.
+ expect(linkDataSteps).toHaveLength(1)
+ expect(linkDataSteps[0].productKey).toBe(ProductKey.DATA_WAREHOUSE)
+ })
+
+ it('does NOT append data-warehouse step for non-PA primaries', () => {
+ logic.actions.setProductKey(ProductKey.WEB_ANALYTICS)
+ const linkDataSteps = logic.values.flow.filter((s) => s.stepKey === OnboardingStepKey.LINK_DATA)
+ expect(linkDataSteps).toHaveLength(0)
+ })
+
+ it('appends invite-teammates step when canInviteTeammates is true (default Admin user)', () => {
+ logic.actions.setProductKey(ProductKey.WEB_ANALYTICS)
+ const invite = logic.values.flow.find((s) => s.stepKey === OnboardingStepKey.INVITE_TEAMMATES)
+ expect(invite).not.toBeUndefined()
+ expect(invite!.productKey).toBe(ProductKey.WEB_ANALYTICS)
+ })
+ })
+
+ describe('currentFlowStep selector', () => {
+ it('falls through to flow[0] when stepId is empty', () => {
+ logic.actions.setProductKey(ProductKey.WEB_ANALYTICS)
+ expect(logic.values.currentFlowStep?.id).toBe('install:web_analytics')
+ })
+
+ it('resolves an exact namespaced id', () => {
+ logic.actions.setProductKey(ProductKey.WEB_ANALYTICS)
+ logic.actions.setStepId('authorized_domains:web_analytics')
+ expect(logic.values.currentFlowStep?.id).toBe('authorized_domains:web_analytics')
+ })
+
+ it('resolves a bare stepKey via loose match (legacy URL support)', () => {
+ logic.actions.setProductKey(ProductKey.WEB_ANALYTICS)
+ logic.actions.setStepId('authorized_domains')
+ // First descriptor matching stepKey === 'authorized_domains'.
+ expect(logic.values.currentFlowStep?.stepKey).toBe(OnboardingStepKey.AUTHORIZED_DOMAINS)
+ })
+
+ it('returns null and self-corrects to flow[0] for an unresolvable stepId', async () => {
+ logic.actions.setProductKey(ProductKey.WEB_ANALYTICS)
+ // The setStepId listener detects the bad id and dispatches setStepId('') as
+ // self-correction once flow.length > 0. We assert the end state rather than
+ // the intermediate dispatches — the contract is "user lands on flow[0],
+ // URL doesn't keep a stale stepId" regardless of how many setStepId calls
+ // it takes to get there.
+ logic.actions.setStepId('totally-bogus-step')
+ // Flush microtasks so the self-correcting setStepId('') has a chance to run.
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect(logic.values.stepId).toBe('')
+ expect(logic.values.currentFlowStep?.id).toBe('install:web_analytics')
+ })
+ })
+
+ describe('navigation', () => {
+ it('goToNextStep advances to the next descriptor by id', async () => {
+ logic.actions.setProductKey(ProductKey.WEB_ANALYTICS)
+ await expectLogic(logic, () => {
+ logic.actions.goToNextStep()
+ }).toDispatchActions([
+ { type: logic.actionTypes.setStepId, payload: { stepId: 'authorized_domains:web_analytics' } },
+ ])
+ })
+
+ it('goToNextStep on the last step calls completeOnboarding', async () => {
+ logic.actions.setProductKey(ProductKey.SURVEYS)
+ const lastId = logic.values.flow[logic.values.flow.length - 1].id
+ logic.actions.setStepId(lastId)
+ await expectLogic(logic, () => {
+ logic.actions.goToNextStep()
+ }).toDispatchActions(['completeOnboarding'])
+ })
+
+ it('goToPreviousStep at index 0 is a no-op', async () => {
+ logic.actions.setProductKey(ProductKey.WEB_ANALYTICS)
+ // setStepId('') resolves to flow[0] via currentFlowStep fallback.
+ await expectLogic(logic, () => {
+ logic.actions.goToPreviousStep()
+ }).toNotHaveDispatchedActions(['setStepId'])
+ })
+
+ it('goToNextStep is a no-op when no product is selected (empty flow)', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.goToNextStep()
+ }).toNotHaveDispatchedActions(['completeOnboarding'])
+ })
+ })
+
+ describe('visited-step tracking', () => {
+ it('forward jump via setStepId marks every traversed step as visited', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setStepId('install:product_analytics')
+ logic.actions.setStepId('link_data:product_analytics')
+ // PA flow after bucket sort: install, product_configuration, session_replay,
+ // link_data, invite_teammates. Forward jump install → link_data should mark
+ // every step from install up to link_data inclusive.
+ expect(logic.values.visitedStepIds).toEqual(
+ expect.arrayContaining([
+ 'install:product_analytics',
+ 'configure:product_analytics',
+ 'session_replay:product_analytics',
+ 'link_data:product_analytics',
+ ])
+ )
+ })
+
+ it('backward jump does not unmark already-visited steps', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setStepId('install:product_analytics')
+ logic.actions.setStepId('link_data:product_analytics')
+ const afterForward = [...logic.values.visitedStepIds]
+ logic.actions.setStepId('install:product_analytics')
+ // Set semantics: visitedStepIds is monotonic — backward navigation never removes.
+ expect(logic.values.visitedStepIds).toEqual(expect.arrayContaining(afterForward))
+ })
+ })
+
+ describe('completeOnboarding — visited-product credit', () => {
+ it('credits the primary product even when only its first step was visited (deep-link backfill at completion)', async () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ await expectLogic(logic, () => {
+ logic.actions.completeOnboarding()
+ }).toDispatchActions([
+ {
+ type: logic.actionTypes.recordProductIntentOnboardingComplete,
+ payload: { product_type: ProductKey.PRODUCT_ANALYTICS } as any,
+ },
+ ])
+ })
+
+ it('credits dedup-collapsed secondaries via additionalProductKeys at completion', async () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setSecondaryProductKeys([ProductKey.WEB_ANALYTICS, ProductKey.SESSION_REPLAY])
+ // Survivor descriptor carries additionalProductKeys=[PA, WA, SR]; the
+ // completion listener iterates them and dispatches
+ // `recordProductIntentOnboardingComplete` for each. We collect every
+ // dispatched product_type and assert the full set, since the iteration
+ // order is `Set` insertion order (primary first, then per-step adds).
+ logic.actions.setStepId('install:product_analytics')
+ const dispatched: ProductKey[] = []
+ await expectLogic(logic, () => {
+ logic.actions.completeOnboarding()
+ }).toDispatchActions([
+ 'completeOnboarding',
+ (action) => {
+ if (action.type === logic.actionTypes.recordProductIntentOnboardingComplete) {
+ dispatched.push((action.payload as any).product_type)
+ }
+ // Stop matching once we've seen the team update — that's the tail
+ // of the synchronous completion path.
+ return action.type === logic.actionTypes.updateCurrentTeam
+ },
+ ])
+ expect(dispatched).toEqual(
+ expect.arrayContaining([
+ ProductKey.PRODUCT_ANALYTICS,
+ ProductKey.WEB_ANALYTICS,
+ ProductKey.SESSION_REPLAY,
+ ])
+ )
+ })
+
+ it('is idempotent — short-circuits when isCompleting is already true (isCompleting guard)', async () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ // Set the guard directly to test the guard's effect deterministically. (Going
+ // through a real first `completeOnboarding()` then checking the second is
+ // racy: the team-patch failure in jsdom resets `isCompleting` async, which
+ // can flip back to false before the second call lands.)
+ logic.actions.setIsCompleting(true)
+
+ await expectLogic(logic, () => {
+ logic.actions.completeOnboarding()
+ }).toNotHaveDispatchedActions(['recordProductIntentOnboardingComplete'])
+ })
+
+ it('returns early when no productKey is set', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.completeOnboarding()
+ }).toNotHaveDispatchedActions(['recordProductIntentOnboardingComplete', 'setIsCompleting'])
+ })
+ })
+
+ describe('URL → state', () => {
+ it('parses /onboarding/<productKey> and sets primary', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/onboarding/web_analytics')
+ }).toDispatchActions([
+ { type: logic.actionTypes.setProductKey, payload: { productKey: ProductKey.WEB_ANALYTICS } as any },
+ ])
+ expect(logic.values.productKey).toBe(ProductKey.WEB_ANALYTICS)
+ })
+
+ it('parses ?with= as a CSV of secondary products', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/onboarding/web_analytics?with=logs,product_analytics')
+ }).toDispatchActions(['setSecondaryProductKeys'])
+ expect(logic.values.secondaryProductKeys).toEqual([ProductKey.LOGS, ProductKey.PRODUCT_ANALYTICS])
+ })
+
+ it('filters the primary product out of ?with= (avoids self-secondary)', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/onboarding/web_analytics?with=web_analytics,logs')
+ }).toDispatchActions(['setSecondaryProductKeys'])
+ expect(logic.values.secondaryProductKeys).toEqual([ProductKey.LOGS])
+ })
+
+ it('drops unknown product keys from ?with=', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/onboarding/web_analytics?with=invalid_product,logs,another_invalid')
+ }).toDispatchActions(['setSecondaryProductKeys'])
+ expect(logic.values.secondaryProductKeys).toEqual([ProductKey.LOGS])
+ })
+
+ it('dedupes ?with= and caps the result at MAX_WITH_PRODUCTS (16)', async () => {
+ // Stuff the head with duplicates plus extra valid keys; only one of each survives,
+ // and the total is capped at 16. We use 8 valid keys + 16 duplicates of the first.
+ const valid = [
+ ProductKey.LOGS,
+ ProductKey.PRODUCT_ANALYTICS,
+ ProductKey.SESSION_REPLAY,
+ ProductKey.FEATURE_FLAGS,
+ ProductKey.EXPERIMENTS,
+ ProductKey.SURVEYS,
+ ProductKey.ERROR_TRACKING,
+ ProductKey.LLM_ANALYTICS,
+ ]
+ const stuffed = [...Array(16).fill(ProductKey.LOGS), ...valid].join(',')
+ await expectLogic(logic, () => {
+ router.actions.push(`/onboarding/web_analytics?with=${stuffed}`)
+ }).toDispatchActions(['setSecondaryProductKeys'])
+ expect(logic.values.secondaryProductKeys.length).toBeLessThanOrEqual(16)
+ // Each valid key survives the dedupe-before-truncate.
+ for (const key of valid) {
+ expect(logic.values.secondaryProductKeys).toContain(key)
+ }
+ })
+
+ it('parses ?step= as the namespaced step id', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/onboarding/web_analytics?step=authorized_domains:web_analytics')
+ }).toDispatchActions(['setStepId'])
+ expect(logic.values.stepId).toBe('authorized_domains:web_analytics')
+ })
+
+ it('sets subscribedDuringOnboarding when ?success=true is present', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/onboarding/web_analytics?success=true')
+ }).toDispatchActions([
+ {
+ type: logic.actionTypes.setSubscribedDuringOnboarding,
+ payload: { subscribedDuringOnboarding: true } as any,
+ },
+ ])
+ })
+ })
+
+ describe('completion redirect URL', () => {
+ // Each entry: [primary, expected redirect path-substring].
+ // Verifies that each per-product provider's `completeRedirectUrl` is wired up.
+ // Two products (DATA_WAREHOUSE and EXPERIMENTS) intentionally fall through to
+ // urls.default() — same behaviour as the original central switch.
+ const cases: Array<[ProductKey, RegExp]> = [
+ [ProductKey.PRODUCT_ANALYTICS, /quickstart|insight/i],
+ [ProductKey.WEB_ANALYTICS, /web/i],
+ [ProductKey.SESSION_REPLAY, /replay/i],
+ [ProductKey.FEATURE_FLAGS, /feature_flag/i],
+ [ProductKey.SURVEYS, /survey/i],
+ [ProductKey.ERROR_TRACKING, /error_tracking/i],
+ [ProductKey.LLM_ANALYTICS, /llm/i],
+ [ProductKey.WORKFLOWS, /workflow/i],
+ [ProductKey.LOGS, /log/i],
+ ]
+
+ it.each(cases)('%s lands on a product-specific page', (product, pattern) => {
+ logic.actions.setProductKey(product)
+ expect(logic.values.onCompleteOnboardingRedirectUrl).toMatch(pattern)
+ })
+
+ it('experiments and data warehouse fall through to urls.default()', () => {
+ logic.actions.setProductKey(ProductKey.EXPERIMENTS)
+ expect(logic.values.onCompleteOnboardingRedirectUrl).toBe('/')
+ logic.actions.setProductKey(ProductKey.DATA_WAREHOUSE)
+ expect(logic.values.onCompleteOnboardingRedirectUrl).toBe('/')
+ })
+
+ it('redirect override takes precedence over the per-product URL', () => {
+ logic.actions.setProductKey(ProductKey.WEB_ANALYTICS)
+ logic.actions.setOnCompleteOnboardingRedirectUrl('/custom-target')
+ expect(logic.values.onCompleteOnboardingRedirectUrl).toBe('/custom-target')
+ })
+ })
+
+ describe('flow stays consistent across product changes', () => {
+ it('switching primary resets the secondary list and rebuilds the flow', () => {
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+ logic.actions.setSecondaryProductKeys([ProductKey.LOGS])
+ expect(flowIds()).toContain('install:logs')
+
+ logic.actions.setProductKey(ProductKey.WEB_ANALYTICS)
+ // Switching primary triggers resetOnboardingFlowState which clears secondaries.
+ // The flow now reflects just WA.
+ expect(logic.values.secondaryProductKeys).toEqual([])
+ expect(flowStepKeys()).not.toContain(OnboardingStepKey.LINK_DATA)
+ })
+ })
+})
diff --git a/frontend/src/scenes/onboarding/onboardingLogic.tsx b/frontend/src/scenes/onboarding/onboardingLogic.tsx
index 7d3460d6a252..f55abdd60e0e 100644
--- a/frontend/src/scenes/onboarding/onboardingLogic.tsx
+++ b/frontend/src/scenes/onboarding/onboardingLogic.tsx
@@ -1,12 +1,16 @@
import { actions, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'
+import { type SetupTaskId } from 'lib/components/ProductSetup'
import { globalSetupLogic } from 'lib/components/ProductSetup/globalSetupLogic'
-import { FEATURE_FLAGS } from 'lib/constants'
+import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { isKeyOf } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
import { billingLogic } from 'scenes/billing/billingLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
@@ -17,76 +21,26 @@ import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePane
import { ProductKey } from '~/queries/schema/schema-general'
import { Breadcrumb, OnboardingProduct, OnboardingStepKey } from '~/types'
+import { arraysEqual, parseProductsParam, stepKeyToTitle } from './onboardingFlowUtils'
import type { onboardingLogicType } from './onboardingLogicType'
import { postOnboardingModalLogic } from './postOnboardingModalLogic'
+import { appendSharedTrailingSteps } from './sharedSteps'
+import { onboardingProviderRegistry } from './stepProviderRegistry'
+import { INSTALL_DEDUP_KEYS, type OnboardingFlowContext, type OnboardingStepDescriptor } from './types'
import { availableOnboardingProducts } from './utils'
-/** Interface for onboarding step components that have a static stepKey property */
+/** Interface kept for callers that import it (legacy step components). */
export interface OnboardingStepComponentType<P = object> extends React.FC<P> {
stepKey: OnboardingStepKey
}
-/** A JSX element whose component type is an OnboardingStepComponentType */
-export type OnboardingStepElement = React.ReactElement<unknown, OnboardingStepComponentType>
-
-/** Helper to extract stepKey from a step element's component type */
-const getStepKey = (step: OnboardingStepElement): OnboardingStepKey => {
- return step.type.stepKey
-}
-
export interface OnboardingLogicProps {
onCompleteOnboarding?: (key: ProductKey) => void
}
-const STEP_KEY_TITLE_OVERRIDES: Partial<Record<OnboardingStepKey, string>> = {
- [OnboardingStepKey.LINK_DATA]: 'Import data',
-}
-
-export const stepKeyToTitle = (stepKey?: OnboardingStepKey): undefined | string => {
- if (!stepKey) {
- return undefined
- }
- if (STEP_KEY_TITLE_OVERRIDES[stepKey]) {
- return STEP_KEY_TITLE_OVERRIDES[stepKey]
- }
- return stepKey
- .split('_')
- .map((part, i) => (i == 0 ? part[0].toUpperCase() + part.substring(1) : part))
- .join(' ')
-}
-
-// These types have to be set like this, so that kea typegen is happy
-export type OnboardingStepType = OnboardingStepElement
-
-export const getOnboardingCompleteRedirectUri = (productKey: ProductKey): string => {
- switch (productKey) {
- case ProductKey.PRODUCT_ANALYTICS:
- return urls.insightQuickStart()
- case ProductKey.WEB_ANALYTICS:
- return urls.webAnalytics()
- case ProductKey.SESSION_REPLAY:
- return urls.replay()
- case ProductKey.FEATURE_FLAGS:
- return urls.featureFlags()
- case ProductKey.SURVEYS:
- return urls.surveyWizard()
- case ProductKey.ERROR_TRACKING:
- return urls.errorTracking()
- case ProductKey.LLM_ANALYTICS:
- return urls.llmAnalyticsDashboard()
- case ProductKey.WORKFLOWS:
- return urls.workflows()
- case ProductKey.LOGS:
- return urls.logs()
- default:
- return urls.default()
- }
-}
-
export const onboardingLogic = kea<onboardingLogicType>([
props({} as OnboardingLogicProps),
path(['scenes', 'onboarding', 'onboardingLogic']),
- // connect this so we start collecting live events the whole time during onboarding
connect(() => ({
values: [
billingLogic,
@@ -97,6 +51,8 @@ export const onboardingLogic = kea<onboardingLogicType>([
['user'],
preflightLogic,
['isCloudOrDev', 'preflight'],
+ organizationLogic,
+ ['currentOrganization'],
sidePanelStateLogic,
['modalMode'],
featureFlagLogic,
@@ -120,35 +76,49 @@ export const onboardingLogic = kea<onboardingLogicType>([
actions({
setProduct: (product: OnboardingProduct | null) => ({ product }),
setProductKey: (productKey: ProductKey | null) => ({ productKey }),
+ setSecondaryProductKeys: (keys: ProductKey[]) => ({ keys }),
+ setStepId: (stepId: string) => ({ stepId }),
+ markStepsVisited: (stepIds: string[]) => ({ stepIds }),
+ resetOnboardingFlowState: true,
completeOnboarding: (options?: { redirectUrlOverride?: string }) => ({
redirectUrlOverride: options?.redirectUrlOverride,
}),
- setAllOnboardingSteps: (allOnboardingSteps: OnboardingStepElement[]) => ({ allOnboardingSteps }),
- setStepKey: (stepKey: OnboardingStepKey) => ({ stepKey }),
setSubscribedDuringOnboarding: (subscribedDuringOnboarding: boolean) => ({ subscribedDuringOnboarding }),
setTeamPropertiesForProduct: (productKey: ProductKey) => ({ productKey }),
setWaitForBilling: (waitForBilling: boolean) => ({ waitForBilling }),
- goToNextStep: (numStepsToAdvance?: number) => ({ numStepsToAdvance }),
+ goToNextStep: true,
goToPreviousStep: true,
- resetStepKey: true,
setOnCompleteOnboardingRedirectUrl: (url: string | null) => ({ url }),
skipOnboarding: true,
setAwaitingPostOnboardingModal: (awaiting: boolean) => ({ awaiting }),
- setSessionSecondaryProductKeys: (keys: ProductKey[]) => ({ keys }),
- setFromProductKey: (key: ProductKey | null) => ({ key }),
- setResumeStep: (step: OnboardingStepKey | null) => ({ step }),
+ // Distinct from `setProductKey(null)`: navigating to `/onboarding` (the product
+ // selection page) should not trigger the invalid-key redirect-to-home path.
+ clearProductKey: true,
+ setIsCompleting: (isCompleting: boolean) => ({ isCompleting }),
}),
reducers(() => ({
isAwaitingPostOnboardingModal: [
false,
{
setAwaitingPostOnboardingModal: (_, { awaiting }) => awaiting,
+ resetOnboardingFlowState: () => false,
+ },
+ ],
+ // True between dispatching `completeOnboarding` and the resulting team PATCH
+ // settling. Guards against double-fires from button double-clicks, re-renders,
+ // and the post-billing `?success=true` round-trip.
+ isCompleting: [
+ false,
+ {
+ setIsCompleting: (_, { isCompleting }) => isCompleting,
+ resetOnboardingFlowState: () => false,
},
],
productKey: [
null as ProductKey | null,
{
setProductKey: (_, { productKey }) => productKey,
+ clearProductKey: () => null,
},
],
product: [
@@ -157,59 +127,271 @@ export const onboardingLogic = kea<onboardingLogicType>([
setProduct: (_, { product }) => product ?? null,
},
],
- allOnboardingSteps: [
- [] as OnboardingStepElement[],
+ secondaryProductKeys: [
+ [] as ProductKey[],
{
- setAllOnboardingSteps: (_, { allOnboardingSteps }) => allOnboardingSteps,
+ setSecondaryProductKeys: (_, { keys }) => keys,
+ resetOnboardingFlowState: () => [],
},
],
- stepKey: [
- '' as OnboardingStepKey,
+ stepId: [
+ '' as string,
{
- setStepKey: (_, { stepKey }) => stepKey,
+ setStepId: (_, { stepId }) => stepId,
+ resetOnboardingFlowState: () => '',
+ },
+ ],
+ // Tracks which step ids the user has actually visited during this onboarding session.
+ // Used to (a) tick `setupTaskId`s for steps the user reached even when they skipped
+ // ahead via a breadcrumb, and (b) only mark a product as completed when the user
+ // actually saw at least one of its steps.
+ visitedStepIds: [
+ [] as string[],
+ {
+ markStepsVisited: (state, { stepIds }) => {
+ const next = new Set(state)
+ stepIds.forEach((id) => next.add(id))
+ return Array.from(next)
+ },
+ resetOnboardingFlowState: () => [],
},
],
subscribedDuringOnboarding: [
false,
{
setSubscribedDuringOnboarding: (_, { subscribedDuringOnboarding }) => subscribedDuringOnboarding,
+ resetOnboardingFlowState: () => false,
},
],
waitForBilling: [
false,
{
setWaitForBilling: (_, { waitForBilling }) => waitForBilling,
+ resetOnboardingFlowState: () => false,
},
],
onCompleteOnboardingRedirectUrlOverride: [
null as string | null,
{
setOnCompleteOnboardingRedirectUrl: (_, { url }) => url,
+ resetOnboardingFlowState: () => null,
},
],
- sessionSecondaryProductKeys: [
- [] as ProductKey[],
- {
- setSessionSecondaryProductKeys: (_, { keys }) => keys,
+ })),
+ selectors({
+ canInviteTeammates: [
+ (s) => [s.currentOrganization, s.user],
+ (currentOrganization, user): boolean => {
+ if (currentOrganization?.members_can_invite) {
+ return true
+ }
+ const level = user?.organization?.membership_level
+ return typeof level === 'number' && level >= OrganizationMembershipLevel.Admin
},
],
- fromProductKey: [
- null as ProductKey | null,
- {
- setFromProductKey: (_, { key }) => key,
+ billingProduct: [
+ (s) => [s.billing, s.productKey],
+ (billing, productKey) => billing?.products?.find((p) => p.type === productKey) ?? null,
+ ],
+ shouldShowBillingStep: [
+ (s) => [s.product, s.subscribedDuringOnboarding, s.isCloudOrDev, s.billing, s.billingProduct],
+ (_product, subscribedDuringOnboarding, isCloudOrDev, billing, billingProduct): boolean => {
+ if (!isCloudOrDev || !billing?.products || !billingProduct) {
+ return false
+ }
+ return !billingProduct?.subscribed || subscribedDuringOnboarding
},
],
- resumeStep: [
- null as OnboardingStepKey | null,
- {
- setResumeStep: (_, { step }) => step,
+ flow: [
+ // Note: depend on `currentTeam` directly (rather than projecting a slim shape)
+ // because providers read varied fields and a kea-style shallow projection still
+ // re-fires on object identity. The cost is small: descriptor allocation is
+ // microseconds and React's reconciler keeps the rendered subtree stable as
+ // long as `currentFlowStep.id` is unchanged.
+ (s) => [
+ s.productKey,
+ s.secondaryProductKeys,
+ s.currentTeam,
+ s.billing,
+ s.billingProduct,
+ s.shouldShowBillingStep,
+ s.isCloudOrDev,
+ s.subscribedDuringOnboarding,
+ s.canInviteTeammates,
+ ],
+ (
+ primary,
+ secondaries,
+ currentTeam,
+ billing,
+ billingProduct,
+ shouldShowBilling,
+ isCloudOrDev,
+ subscribedDuringOnboarding,
+ canInviteTeammates
+ ): OnboardingStepDescriptor[] => {
+ if (!primary) {
+ return []
+ }
+ const orderedProducts: ProductKey[] = [primary, ...secondaries]
+ const baseCtx: Omit<OnboardingFlowContext, 'role'> = {
+ primary,
+ secondaries,
+ currentTeam,
+ billing,
+ isCloudOrDev: Boolean(isCloudOrDev),
+ subscribedDuringOnboarding,
+ canInviteTeammates,
+ }
+ const productSteps = orderedProducts.flatMap((p, i) => {
+ const provider = onboardingProviderRegistry[p]
+ if (!provider) {
+ return []
+ }
+ return provider.steps({ ...baseCtx, role: i === 0 ? 'primary' : 'secondary' })
+ })
+ const allSteps = appendSharedTrailingSteps(
+ productSteps,
+ { ...baseCtx, role: 'primary' },
+ billingProduct,
+ shouldShowBilling
+ )
+ // Collapse functionally-identical steps (e.g. multiple posthog-js install
+ // steps when the user picks several products that share the SDK). First
+ // occurrence wins so the primary product's install step — which carries
+ // the most configuration — survives. When a descriptor is dropped, we
+ // accumulate its `setupTaskId` and `productKey` for the survivor so:
+ // (1) advancing past the kept step still ticks every dropped product's
+ // setup-checklist task, and
+ // (2) `completeOnboarding` can credit the dropped products' visit even
+ // though no surviving descriptor carries their productKey.
+ // Two-pass build: first accumulate into per-survivor scratch records, then
+ // emit fully-frozen descriptors. Avoids mutating descriptors after they've
+ // been pushed to the result array (selector purity).
+ interface AccumulatedExtras {
+ setupTaskIds: SetupTaskId[]
+ productKeys: ProductKey[]
+ }
+ const extras = new Map<string, AccumulatedExtras>()
+ for (const step of allSteps) {
+ if (!step.dedupKey) {
+ continue
+ }
+ let entry = extras.get(step.dedupKey)
+ if (!entry) {
+ entry = { setupTaskIds: [], productKeys: [step.productKey] }
+ extras.set(step.dedupKey, entry)
+ continue
+ }
+ if (step.setupTaskId && !entry.setupTaskIds.includes(step.setupTaskId)) {
+ entry.setupTaskIds.push(step.setupTaskId)
+ }
+ if (!entry.productKeys.includes(step.productKey)) {
+ entry.productKeys.push(step.productKey)
+ }
+ }
+ const emittedDedup = new Set<string>()
+ const result: OnboardingStepDescriptor[] = []
+ for (const step of allSteps) {
+ if (!step.dedupKey) {
+ result.push(step)
+ continue
+ }
+ if (emittedDedup.has(step.dedupKey)) {
+ continue
+ }
+ emittedDedup.add(step.dedupKey)
+ const entry = extras.get(step.dedupKey)
+ if (!entry || (entry.setupTaskIds.length === 0 && entry.productKeys.length <= 1)) {
+ result.push(step)
+ continue
+ }
+ result.push(
+ Object.freeze({
+ ...step,
+ additionalSetupTaskIds: entry.setupTaskIds.slice(),
+ additionalProductKeys: entry.productKeys.slice(),
+ })
+ )
+ }
+ // Reorder: all install steps to the front, with the SDK install (the
+ // posthog-js-deduped survivor) first among them. Stable sort preserves
+ // each provider's intra-group order — non-install steps (configure,
+ // link_data, plans, invite) keep their relative positions, just appear
+ // after the installs. Buckets:
+ // 0 — Install + posthog-js dedup survivor (the canonical "SDK install")
+ // 1 — Install (any other dedupKey or none — Logs/OTel, Workflows, etc.)
+ // 2 — everything else (configure, plans, invite, link_data, …)
+ const sortBucket = (step: OnboardingStepDescriptor): number => {
+ if (step.stepKey !== OnboardingStepKey.INSTALL) {
+ return 2
+ }
+ return step.dedupKey === INSTALL_DEDUP_KEYS.POSTHOG_JS ? 0 : 1
+ }
+ return result.slice().sort((a, b) => sortBucket(a) - sortBucket(b))
},
],
- })),
- selectors({
+ onboardingStepKeys: [
+ (s) => [s.flow],
+ (flow: OnboardingStepDescriptor[]): OnboardingStepKey[] => flow.map((step) => step.stepKey),
+ ],
+ currentFlowStep: [
+ (s) => [s.flow, s.stepId],
+ (flow: OnboardingStepDescriptor[], stepId): OnboardingStepDescriptor | null => {
+ if (!flow.length) {
+ // If the user explicitly asked for a step (URL has `?step=...`) but the
+ // flow hasn't been built yet (billing/team still loading), we MUST NOT
+ // fall through to `flow[0]` — that would render a different product's
+ // step than the URL indicates and fire analytics for the wrong step.
+ // Returning null lets `OnboardingFlowHost` show a spinner until the
+ // flow rebuilds and the requested step resolves.
+ return null
+ }
+ if (!stepId) {
+ return flow[0]
+ }
+ const exact = flow.find((step) => step.id === stepId)
+ if (exact) {
+ return exact
+ }
+ // Backwards-compat: bare step keys (no namespace) resolve to the first
+ // matching descriptor — covers older bookmarks and inbound links from
+ // setup-task `getUrl` callsites that pre-date the namespaced ids.
+ const looseMatch = flow.find((step) => step.stepKey === stepId)
+ if (looseMatch) {
+ return looseMatch
+ }
+ // Bad step id — neither exact nor loose match. Return null so
+ // `OnboardingFlowHost` shows a loading state instead of silently
+ // rendering `flow[0]` while the URL keeps a stale stepId. The
+ // urlToAction handler reconciles this by calling `setStepId('')`
+ // when the parsed stepValue can't be resolved.
+ return null
+ },
+ ],
+ flowIndex: [
+ (s) => [s.flow, s.currentFlowStep],
+ (flow, currentFlowStep): number =>
+ currentFlowStep ? flow.findIndex((step) => step.id === currentFlowStep.id) : -1,
+ ],
+ currentStepKey: [
+ (s) => [s.currentFlowStep],
+ (currentFlowStep): OnboardingStepKey | null => currentFlowStep?.stepKey ?? null,
+ ],
+ currentStepProductKey: [
+ (s) => [s.currentFlowStep, s.productKey],
+ (currentFlowStep, productKey): ProductKey | null => currentFlowStep?.productKey ?? productKey,
+ ],
+ totalOnboardingSteps: [(s) => [s.flow], (flow) => flow.length],
+ hasNextStep: [
+ (s) => [s.flow, s.flowIndex],
+ (flow, flowIndex): boolean => flowIndex >= 0 && flowIndex < flow.length - 1,
+ ],
+ hasPreviousStep: [(s) => [s.flowIndex], (flowIndex): boolean => flowIndex > 0],
breadcrumbs: [
- (s) => [s.productKey, s.stepKey],
- (productKey, stepKey): Breadcrumb[] => {
+ (s) => [s.productKey, s.currentFlowStep, s.secondaryProductKeys],
+ (productKey, currentFlowStep, secondaryProductKeys): Breadcrumb[] => {
+ const stepName = stepKeyToTitle(currentFlowStep?.stepKey ?? undefined)
return [
{
key: Scene.Onboarding,
@@ -222,8 +404,15 @@ export const onboardingLogic = kea<onboardingLogicType>([
},
{
key: availableOnboardingProducts[productKey as keyof typeof availableOnboardingProducts]?.scene,
- name: stepKeyToTitle(stepKey),
- path: urls.onboarding({ productKey: productKey ?? undefined, stepKey }),
+ name: stepName,
+ // Preserve `withProducts` and use the namespaced step id so the URL
+ // round-trips through `urlToAction` without collapsing the flow's
+ // secondary products or losing the active step's product attribution.
+ path: urls.onboarding({
+ productKey: productKey ?? undefined,
+ step: currentFlowStep?.id,
+ withProducts: secondaryProductKeys.length ? secondaryProductKeys : undefined,
+ }),
iconType: 'action',
},
]
@@ -231,81 +420,21 @@ export const onboardingLogic = kea<onboardingLogicType>([
],
onCompleteOnboardingRedirectUrl: [
(s) => [s.productKey, s.onCompleteOnboardingRedirectUrlOverride],
- (productKey: string | null, onCompleteOnboardingRedirectUrlOverride) => {
+ (productKey: ProductKey | null, onCompleteOnboardingRedirectUrlOverride: string | null): string => {
if (onCompleteOnboardingRedirectUrlOverride) {
return onCompleteOnboardingRedirectUrlOverride
}
- return productKey ? getOnboardingCompleteRedirectUri(productKey as ProductKey) : urls.default()
- },
- ],
- totalOnboardingSteps: [
- (s) => [s.allOnboardingSteps],
- (allOnboardingSteps: OnboardingStepElement[]) => allOnboardingSteps.length,
- ],
- onboardingStepKeys: [
- (s) => [s.allOnboardingSteps],
- (allOnboardingSteps: OnboardingStepElement[]) => {
- return allOnboardingSteps.map(getStepKey)
- },
- ],
- currentOnboardingStep: [
- (s) => [s.allOnboardingSteps, s.stepKey],
- (allOnboardingSteps: OnboardingStepElement[], stepKey: OnboardingStepKey): OnboardingStepType | null =>
- allOnboardingSteps.find((step) => getStepKey(step) === stepKey) || null,
- ],
- hasNextStep: [
- (s) => [s.allOnboardingSteps, s.stepKey],
- (allOnboardingSteps: OnboardingStepElement[], stepKey: OnboardingStepKey) => {
- const currentStepIndex = allOnboardingSteps.findIndex((step) => getStepKey(step) === stepKey)
- return currentStepIndex < allOnboardingSteps.length - 1
- },
- ],
- hasPreviousStep: [
- (s) => [s.allOnboardingSteps, s.stepKey],
- (allOnboardingSteps: OnboardingStepElement[], stepKey: OnboardingStepKey) => {
- const currentStepIndex = allOnboardingSteps.findIndex((step) => getStepKey(step) === stepKey)
- return currentStepIndex > 0
- },
- ],
- shouldShowBillingStep: [
- (s) => [s.product, s.subscribedDuringOnboarding, s.isCloudOrDev, s.billing, s.billingProduct],
- (_product, subscribedDuringOnboarding: boolean, isCloudOrDev: boolean, billing, billingProduct) => {
- if (!isCloudOrDev || !billing?.products || !billingProduct) {
- return false
+ if (!productKey) {
+ return urls.default()
}
-
- return !billingProduct?.subscribed || subscribedDuringOnboarding
- },
- ],
- shouldShowDataWarehouseStep: [
- (s) => [s.productKey],
- (productKey) => {
- return productKey === ProductKey.PRODUCT_ANALYTICS
- },
- ],
- isStepKeyInvalid: [
- (s) => [s.stepKey, s.allOnboardingSteps, s.currentOnboardingStep],
- (
- stepKey: string,
- allOnboardingSteps: OnboardingStepElement[],
- currentOnboardingStep: React.ReactNode | null
- ) =>
- (stepKey && allOnboardingSteps.length > 0 && !currentOnboardingStep) ||
- (!stepKey && allOnboardingSteps.length > 0),
- ],
- billingProduct: [
- (s) => [s.product, s.productKey, s.billing],
- (_product, productKey, billing) => {
- return billing?.products?.find((p) => p.type === productKey)
+ return onboardingProviderRegistry[productKey]?.completeRedirectUrl?.() ?? urls.default()
},
],
}),
- listeners(({ actions, values, props }) => ({
+ listeners(({ actions, values, props, selectors }) => ({
setProduct: ({ product }) => {
if (!product) {
window.location.href = urls.default()
- } else {
- actions.resetStepKey()
}
},
setTeamPropertiesForProduct: ({ productKey }) => {
@@ -313,7 +442,7 @@ export const onboardingLogic = kea<onboardingLogicType>([
case ProductKey.PRODUCT_ANALYTICS:
return
case ProductKey.SESSION_REPLAY:
- actions.updateCurrentTeam({
+ teamLogic.actions.updateCurrentTeam({
session_recording_opt_in: true,
capture_console_log_opt_in: true,
capture_performance_opt_in: true,
@@ -327,40 +456,122 @@ export const onboardingLogic = kea<onboardingLogicType>([
return
}
},
- setProductKey: ({ productKey }) => {
+ setProductKey: ({ productKey }, _, __, previousState) => {
if (!productKey || !isKeyOf(productKey, availableOnboardingProducts)) {
window.location.href = urls.default()
return
}
+ // Reset per-flow state when transitioning into a new product. Without this,
+ // a redirect override / `subscribedDuringOnboarding` / `waitForBilling` set
+ // during a previous onboarding in the same SPA tab would carry over and
+ // hijack the new flow's behaviour.
+ const previousKey = selectors.productKey(previousState)
+ if (previousKey && previousKey !== productKey) {
+ actions.resetOnboardingFlowState()
+ }
actions.setProduct(availableOnboardingProducts[productKey])
},
setSubscribedDuringOnboarding: ({ subscribedDuringOnboarding }) => {
- if (subscribedDuringOnboarding) {
- // we might not have the product key yet
- // if not we'll just use the current url to determine the product key
- const productKey = values.productKey || (window.location.pathname.split('/')[2] as ProductKey)
- eventUsageLogic.actions.reportSubscribedDuringOnboarding(productKey)
+ if (!subscribedDuringOnboarding) {
+ return
}
+ // Strip /project/<id>/ prefix before splitting, otherwise the path index
+ // points at the project id instead of the product key.
+ const fallbackKey = removeProjectIdIfPresent(window.location.pathname).split('/')[2] as
+ | ProductKey
+ | undefined
+ const productKey = values.productKey || fallbackKey
+ // Don't fire the analytics event without a valid productKey — would record
+ // `productKey: undefined` rows which dirty downstream dashboards.
+ if (!productKey || !isKeyOf(productKey, availableOnboardingProducts)) {
+ return
+ }
+ eventUsageLogic.actions.reportSubscribedDuringOnboarding(productKey)
},
-
completeOnboarding: ({ redirectUrlOverride }) => {
+ // Idempotency guard. Without this, a double-click on Finish, a re-render
+ // calling advance() twice, or back-then-forward into the last step plus
+ // pressing Finish again all fire duplicate product-intent writes,
+ // analytics events, and team PATCHes.
+ if (values.isCompleting) {
+ return
+ }
+ const primary = values.productKey
+ if (!primary) {
+ return
+ }
+ actions.setIsCompleting(true)
if (redirectUrlOverride) {
actions.setOnCompleteOnboardingRedirectUrl(redirectUrlOverride)
}
- if (values.productKey) {
- const productKey = values.productKey
- eventUsageLogic.actions.reportOnboardingCompleted(productKey)
- props.onCompleteOnboarding?.(productKey)
+ // Analytics: keep the existing single event for the primary product to avoid
+ // changing dashboards. Secondary products are still recorded via
+ // `recordProductIntentOnboardingComplete` and `has_completed_onboarding_for`,
+ // but don't fire an additional `onboarding completed` analytics event.
+ eventUsageLogic.actions.reportOnboardingCompleted(primary)
+ props.onCompleteOnboarding?.(primary)
+ // Error Tracking has a side-effect tied to onboarding completion (set up in the
+ // legacy view): turn on autocapture_exceptions_opt_in. Preserved here.
+ if (primary === ProductKey.ERROR_TRACKING) {
+ teamLogic.actions.updateCurrentTeam({ autocapture_exceptions_opt_in: true })
+ }
+ // Only mark a product as fully onboarded when the user actually visited at
+ // least one of its steps. Without this guard, a hand-crafted URL with an
+ // arbitrary `?with=...` list would silently flip every secondary's flag on
+ // the first "Continue" — even ones the user never saw.
+ //
+ // Two extra signals beyond `visitedStepIds`:
+ // - The user is, by definition, looking at the current step right now.
+ // Include `currentFlowStep` even if `setStepId` never fired for it
+ // (deep-link entry, or final step reached by goToNextStep).
+ // - Walk every step from the start of the flow up to the current step:
+ // a deep link past the start of a multi-product flow implies the user
+ // committed to seeing the preceding steps' products.
+ // - For each visited step, also credit `additionalProductKeys` from the
+ // dedup pass so collapsed-into-survivor secondaries get marked.
+ const visited = new Set(values.visitedStepIds)
+ const currentStep = values.currentFlowStep
+ if (currentStep) {
+ visited.add(currentStep.id)
+ }
+ const currentIndex = values.flowIndex
+ if (currentIndex >= 0) {
+ for (let i = 0; i <= currentIndex; i++) {
+ visited.add(values.flow[i].id)
+ }
+ }
+ const visitedProducts = new Set<ProductKey>([primary])
+ // Tick every reached step's setupTaskId — including the final step's, which
+ // would otherwise never fire because `setStepId` doesn't tick the destination.
+ const setup = globalSetupLogic.findMounted()
+ const tickedTaskIds = new Set<SetupTaskId>()
+ for (const step of values.flow) {
+ if (!visited.has(step.id)) {
+ continue
+ }
+ visitedProducts.add(step.productKey)
+ for (const productKey of step.additionalProductKeys ?? []) {
+ visitedProducts.add(productKey)
+ }
+ if (step.setupTaskId) {
+ tickedTaskIds.add(step.setupTaskId)
+ }
+ for (const id of step.additionalSetupTaskIds ?? []) {
+ tickedTaskIds.add(id)
+ }
+ }
+ if (setup && tickedTaskIds.size > 0) {
+ setup.actions.markTaskAsCompleted(Array.from(tickedTaskIds))
+ }
+ for (const productKey of visitedProducts) {
actions.recordProductIntentOnboardingComplete({ product_type: productKey as ProductKey })
- // Signal that the next updateCurrentTeamSuccess should show the modal
- actions.setAwaitingPostOnboardingModal(true)
- teamLogic.actions.updateCurrentTeam({
- has_completed_onboarding_for: {
- ...values.currentTeam?.has_completed_onboarding_for,
- [productKey]: true,
- },
- })
}
+ actions.setAwaitingPostOnboardingModal(true)
+ const completedMap: Record<string, boolean> = { ...values.currentTeam?.has_completed_onboarding_for }
+ for (const productKey of visitedProducts) {
+ completedMap[productKey] = true
+ }
+ teamLogic.actions.updateCurrentTeam({ has_completed_onboarding_for: completedMap })
},
skipOnboarding: () => {
// Quick Start does not auto-open here. The button remains in the scene title
@@ -369,13 +580,18 @@ export const onboardingLogic = kea<onboardingLogicType>([
// creating two competing "what to do next" surfaces.
router.actions.push(values.onCompleteOnboardingRedirectUrl)
},
- updateCurrentTeamSuccess: () => {
- // See `skipOnboarding`: Quick Start no longer auto-opens after onboarding completes.
+ updateCurrentTeamSuccess: (val) => {
+ // Only react to the completion PATCH. Without this the listener would fire
+ // for *any* `updateCurrentTeam` (e.g. `setTeamPropertiesForProduct` toggles)
+ // while `isAwaitingPostOnboardingModal` happened to be true, mis-attributing
+ // unrelated success to onboarding completion.
+ const isCompletionPatch =
+ values.productKey && val.payload?.has_completed_onboarding_for?.[values.productKey]
+ if (!isCompletionPatch) {
+ return
+ }
if (values.isAwaitingPostOnboardingModal && values.productKey) {
actions.setAwaitingPostOnboardingModal(false)
- // Experiment variant still shows its modal (it's gated by `modalShown` so it
- // only fires once per user), but the control branch no longer auto-opens
- // Quick Start.
const isVariant =
values.receivedFeatureFlags &&
values.featureFlags[FEATURE_FLAGS.POST_ONBOARDING_MODAL_EXPERIMENT] === 'test'
@@ -384,165 +600,229 @@ export const onboardingLogic = kea<onboardingLogicType>([
actions.openPostOnboardingModal(values.productKey)
}
}
+ actions.setIsCompleting(false)
},
- setAllOnboardingSteps: () => {
- if (values.isStepKeyInvalid) {
- actions.resetStepKey()
- }
- },
- setStepKey: () => {
- if (values.isStepKeyInvalid) {
- actions.resetStepKey()
- }
- },
- resetStepKey: () => {
- if (values.allOnboardingSteps.length > 0) {
- actions.setStepKey(getStepKey(values.allOnboardingSteps[0]))
+ updateCurrentTeamFailure: (val) => {
+ // Same scoping as the success listener: only react to the completion PATCH,
+ // not to unrelated team updates that happen to fail while the user is on
+ // the last step.
+ const isCompletionPatch =
+ values.productKey && val.payload?.has_completed_onboarding_for?.[values.productKey]
+ if (!isCompletionPatch) {
+ return
}
- },
- })),
- actionToUrl(({ actions, values }) => ({
- setStepKey: ({ stepKey }) => {
- if (stepKey) {
- return [`/onboarding/${values.productKey}`, { ...router.values.searchParams, step: stepKey }]
+ if (values.isAwaitingPostOnboardingModal) {
+ actions.setAwaitingPostOnboardingModal(false)
+ lemonToast.error(
+ "We couldn't finish onboarding. Click Finish to try again, or contact support if the problem persists."
+ )
}
- return [`/onboarding/${values.productKey}`, router.values.searchParams]
+ actions.setIsCompleting(false)
},
- goToNextStep: ({ numStepsToAdvance }) => {
- const currentStepIndex = values.allOnboardingSteps.findIndex((step) => getStepKey(step) === values.stepKey)
- const nextStep = values.allOnboardingSteps[currentStepIndex + (numStepsToAdvance || 1)]
- const baseParams = { ...router.values.searchParams }
+ setStepId: ({ stepId }, _, __, previousState) => {
+ // kea listeners receive (payload, breakpoint, action, previousState). We need
+ // the 4th arg here, not the 2nd — that was the breakpoint function.
+ const previousStepId = selectors.stepId(previousState)
- // Divert into Logs install when leaving the primary product's Install step with
- // Logs selected as a secondary intent. Strip LOGS from `secondary` so that if the
- // user later returns to this step, the divert won't fire again (no ping-pong).
- // The primary's next-step key is captured as `resumeStep` so completion of the
- // Logs install can return the user to the correct point in the primary flow.
- if (
- values.stepKey === OnboardingStepKey.INSTALL &&
- values.productKey !== ProductKey.LOGS &&
- values.sessionSecondaryProductKeys.includes(ProductKey.LOGS)
- ) {
- const remainingSecondary = values.sessionSecondaryProductKeys.filter((k) => k !== ProductKey.LOGS)
- const resumeStepKey = nextStep ? getStepKey(nextStep) : null
- return [
- urls.onboarding({
- productKey: ProductKey.LOGS,
- stepKey: OnboardingStepKey.INSTALL,
- secondary: remainingSecondary.length ? remainingSecondary : undefined,
- from: values.productKey ?? undefined,
- resumeStep: resumeStepKey ?? undefined,
- }),
- {},
- ]
+ // URL self-correction: if the user navigated to a stepId we can't resolve
+ // (typo'd bookmark, deprecated step name, secondary product not in `?with=`),
+ // `currentFlowStep` returns null and the host shows a spinner forever.
+ // Reconcile by falling through to flow[0].
+ //
+ // Important: only self-correct when the stepId is genuinely unknown — NOT when
+ // it's a valid OnboardingStepKey that simply hasn't been emitted into the flow
+ // yet. Steps like `plans` are appended async (after billing loads) by
+ // `appendSharedTrailingSteps`; self-correcting too eagerly here would clobber
+ // the URL before the flow settles, leaving the user on `flow[0]` even after
+ // billing arrives.
+ const isKnownStepKey = (id: string): boolean =>
+ Object.values(OnboardingStepKey).includes(id as OnboardingStepKey) || id.includes(':')
+ if (stepId && values.flow.length > 0 && !isKnownStepKey(stepId)) {
+ const exact = values.flow.find((step) => step.id === stepId)
+ const loose = exact ? null : values.flow.find((step) => step.stepKey === stepId)
+ if (!exact && !loose) {
+ actions.setStepId('')
+ return
+ }
}
- // Returning from a Logs divert: route to the original product at its captured
- // resume step. If no resume step was captured, the primary had no further steps
- // and completion is handled by the install step's NextButton (completeOnboarding).
- if (values.productKey === ProductKey.LOGS && values.fromProductKey && values.resumeStep && !nextStep) {
- return [
- urls.onboarding({
- productKey: values.fromProductKey,
- stepKey: values.resumeStep,
- secondary: values.sessionSecondaryProductKeys.length
- ? values.sessionSecondaryProductKeys
- : undefined,
- }),
- {},
- ]
+ if (!previousStepId || previousStepId === stepId) {
+ if (stepId) {
+ actions.markStepsVisited([stepId])
+ }
+ return
}
- if (nextStep) {
- return [`/onboarding/${values.productKey}`, { ...baseParams, step: getStepKey(nextStep) }]
+ const flow = values.flow
+ const previousIndex = flow.findIndex((step) => step.id === previousStepId)
+ const nextIndex = flow.findIndex((step) => step.id === stepId)
+
+ // Mark every step from previous → next as visited (forward jumps via
+ // breadcrumb included). Backward jumps don't add new visits — already-marked
+ // steps stay marked thanks to the Set semantics in the reducer.
+ if (previousIndex >= 0 && nextIndex > previousIndex) {
+ const traversed = flow.slice(previousIndex, nextIndex + 1).map((step) => step.id)
+ actions.markStepsVisited(traversed)
+ // Tick setupTaskId for every step the user traversed away from, plus
+ // any additionalSetupTaskIds inherited from descriptors that were
+ // collapsed via the dedup pass. Single batched call — looping per id
+ // would have each call read the same stale `currentTeam.onboarding_tasks`
+ // snapshot and clobber prior writes (only the last id would survive).
+ const setup = globalSetupLogic.findMounted()
+ if (setup) {
+ const ticked = new Set<SetupTaskId>()
+ for (const step of flow.slice(previousIndex, nextIndex)) {
+ if (step.setupTaskId) {
+ ticked.add(step.setupTaskId)
+ }
+ for (const id of step.additionalSetupTaskIds ?? []) {
+ ticked.add(id)
+ }
+ }
+ if (ticked.size > 0) {
+ setup.actions.markTaskAsCompleted(Array.from(ticked))
+ }
+ }
+ } else if (stepId) {
+ // Backward / lateral / outside-flow movement: still record the new step as visited.
+ actions.markStepsVisited([stepId])
+ }
+ },
+ goToNextStep: () => {
+ // Empty / not-yet-built flow: do nothing. Without this guard, a misconfigured
+ // product (registered in availableOnboardingProducts but not in
+ // stepProviderRegistry) would cascade through completeOnboarding the first
+ // time anything triggered goToNextStep.
+ if (!values.flow.length) {
+ return
}
- return [`/onboarding/${values.productKey}`, baseParams]
+ const next = values.flow[values.flowIndex + 1]
+ if (next) {
+ actions.setStepId(next.id)
+ return
+ }
+ actions.completeOnboarding()
},
goToPreviousStep: () => {
- const currentStepIndex = values.allOnboardingSteps.findIndex((step) => getStepKey(step) === values.stepKey)
- const previousStep = values.allOnboardingSteps[currentStepIndex - 1]
- const baseParams = { ...router.values.searchParams }
- if (previousStep) {
- return [`/onboarding/${values.productKey}`, { ...baseParams, step: getStepKey(previousStep) }]
- }
- // No previous step within this product: if we were diverted here from another
- // product's install step, navigate back to it. Strip LOGS from secondary so the
- // primary's "Continue" doesn't re-divert (back implies "I don't want this divert");
- // other secondary selections are preserved.
- if (values.fromProductKey) {
- const remainingSecondary = values.sessionSecondaryProductKeys.filter((k) => k !== ProductKey.LOGS)
- return [
- urls.onboarding({
- productKey: values.fromProductKey,
- stepKey: OnboardingStepKey.INSTALL,
- secondary: remainingSecondary.length ? remainingSecondary : undefined,
- }),
- {},
- ]
+ const prev = values.flow[values.flowIndex - 1]
+ if (prev) {
+ actions.setStepId(prev.id)
}
- return [`/onboarding/${values.productKey}`, baseParams]
+ },
+ })),
+ actionToUrl(({ values, actions }) => ({
+ setStepId: ({ stepId }) => {
+ // `success`/`upgraded` are billing-callback signals consumed once; keeping them in
+ // the URL re-fires the `subscribed during onboarding` event on every step nav.
+ const existingParams = router.values.searchParams ?? {}
+ const {
+ step: _step,
+ with: _with,
+ productKey: _productKey,
+ success: _success,
+ upgraded: _upgraded,
+ ...passthrough
+ } = existingParams
+ void _step
+ void _with
+ void _productKey
+ void _success
+ void _upgraded
+ // Drop the stepId from the URL if it's not resolvable in the current flow.
+ // Without this, the self-correcting `setStepId('')` from the listener races
+ // with the OUTER `actionToUrl` for the bogus stepId — kea fires the outer
+ // actionToUrl AFTER the listener completes, which re-pushes the bogus URL
+ // through urlToAction and re-dispatches setStepId(bogus), looping
+ // indefinitely. Stripping unresolvable stepIds here keeps the URL
+ // self-consistent with the reducer state.
+ // Mirror the `setStepId` listener's `isKnownStepKey` heuristic. Billing-gated
+ // steps (plans, invite_teammates, link_data) are appended async after billing
+ // loads, so they may not be in `flow` when the URL push lands. Stripping them
+ // from the URL would re-fire `setStepId('')` and permanently lose the request.
+ const isKnownStepKey =
+ Object.values(OnboardingStepKey).includes(stepId as OnboardingStepKey) || stepId.includes(':')
+ const stepResolves =
+ !stepId ||
+ values.flow.length === 0 ||
+ isKnownStepKey ||
+ !!values.flow.find((s) => s.id === stepId || s.stepKey === stepId)
+ const url = urls.onboarding({
+ productKey: values.productKey ?? undefined,
+ step: stepResolves ? stepId || undefined : undefined,
+ withProducts: values.secondaryProductKeys.length ? values.secondaryProductKeys : undefined,
+ })
+ // Use `replace` so the user doesn't accumulate one history entry per onboarding
+ // step — otherwise pressing browser Back after onboarding requires N presses to
+ // escape, where N is the number of steps the user advanced.
+ return [url, passthrough, undefined, { replace: true }]
},
updateCurrentTeamSuccess(val) {
if (values.productKey && val.payload?.has_completed_onboarding_for?.[values.productKey]) {
const redirectUrl = values.onCompleteOnboardingRedirectUrl
- actions.setOnCompleteOnboardingRedirectUrl(null)
-
+ // Reset the override after consuming it so a subsequent onboarding session
+ // in the same tab doesn't reuse a stale redirect target.
+ if (values.onCompleteOnboardingRedirectUrlOverride) {
+ actions.setOnCompleteOnboardingRedirectUrl(null)
+ }
return [redirectUrl]
}
},
})),
urlToAction(({ actions, values }) => ({
- '/onboarding/:productKey': ({ productKey }, { success, upgraded, step, secondary, from, resumeStep }) => {
+ '/onboarding/:productKey': ({ productKey }, params: Record<string, unknown>) => {
if (!productKey || !Object.hasOwn(availableOnboardingProducts, productKey)) {
return
}
- if (success || upgraded) {
- actions.setSubscribedDuringOnboarding(true)
- }
+ const success = params.success
+ const upgraded = params.upgraded
+ const step = params.step
+ const withRaw = params.with
+
+ // Order matters: `setProductKey` may dispatch `resetOnboardingFlowState`
+ // (which resets `subscribedDuringOnboarding` to false) when transitioning
+ // between products. Set the product first, THEN apply the post-payment
+ // subscription flag, so the reset doesn't clobber it.
if (productKey !== values.productKey) {
actions.setProductKey(productKey as ProductKey)
- // Reset onboarding steps so they can be populated upon render in the component.
- actions.setAllOnboardingSteps([])
}
- // `secondary`/`from`/`resumeStep` are always sourced from the URL on every
- // route hit so navigating away from a URL without these params clears the
- // state — preventing leakage across separate onboardings in the same tab.
- // Defensive coercion: kea-router auto-coerces "true"/"42" to bool/number,
- // so we must guard against non-string values before splitting.
- const secondaryStr = typeof secondary === 'string' ? secondary : ''
- const secondaryKeys = secondaryStr
- ? (secondaryStr
- .split(',', 32)
- .filter((k: string) => Object.hasOwn(availableOnboardingProducts, k)) as ProductKey[])
- : []
- actions.setSessionSecondaryProductKeys(Array.from(new Set(secondaryKeys)))
+ if (success || upgraded) {
+ actions.setSubscribedDuringOnboarding(true)
+ }
- const fromValid =
- typeof from === 'string' && Object.hasOwn(availableOnboardingProducts, from) && from !== productKey
- actions.setFromProductKey(fromValid ? (from as ProductKey) : null)
+ const parsedSecondaries = parseProductsParam(withRaw).filter((k) => k !== productKey)
+ // Skip the dispatch when nothing changed — kea reducers compare by reference,
+ // so re-emitting an identical-but-fresh array still triggers downstream
+ // selector recomputes (notably `flow`, which is the most expensive selector
+ // in this logic).
+ if (!arraysEqual(parsedSecondaries, values.secondaryProductKeys)) {
+ actions.setSecondaryProductKeys(parsedSecondaries)
+ }
- actions.setResumeStep(
- typeof resumeStep === 'string' && resumeStep ? (resumeStep as OnboardingStepKey) : null
- )
+ const stepValue = typeof step === 'string' ? step : ''
+ // Wait-for-billing gating: same intent as before, just keyed off the step value
+ // (namespaced or bare). Plans-step bookmarks should not advance until billing
+ // has loaded so the upgrade UI has data to render.
+ const isPlansStep =
+ stepValue === OnboardingStepKey.PLANS || stepValue.startsWith(`${OnboardingStepKey.PLANS}:`)
+ if (isPlansStep) {
+ actions.setWaitForBilling(true)
+ }
- if (step) {
- // when loading specific steps, like plans, we need to make sure we have a billing response before we can continue
- const stepsToWaitForBilling = [OnboardingStepKey.PLANS]
- if (stepsToWaitForBilling.includes(step as OnboardingStepKey)) {
- actions.setWaitForBilling(true)
- }
- actions.setStepKey(step)
- } else {
- actions.resetStepKey()
+ if (stepValue !== values.stepId) {
+ actions.setStepId(stepValue)
}
},
'/onboarding': () => {
- // Clear productKey when on the product selection page
+ // Land on the product-selection page. We can't dispatch `setProductKey(null)`
+ // because that listener treats null as "invalid product" and hard-redirects
+ // to the home page — preventing users from returning here from inside an
+ // existing flow.
if (values.productKey !== null) {
- actions.setProductKey(null)
+ actions.clearProductKey()
}
+ actions.resetOnboardingFlowState()
},
})),
])
diff --git a/frontend/src/scenes/onboarding/productSelection/productSelectionLogic.ts b/frontend/src/scenes/onboarding/productSelection/productSelectionLogic.ts
index 6f47af669aa9..f3639c10727c 100644
--- a/frontend/src/scenes/onboarding/productSelection/productSelectionLogic.ts
+++ b/frontend/src/scenes/onboarding/productSelection/productSelectionLogic.ts
@@ -275,7 +275,11 @@ export const productSelectionLogic = kea<productSelectionLogicType>([
(k) => k !== values.firstProductOnboarding
) as string[]
router.actions.push(
- urls.onboarding({ productKey: values.firstProductOnboarding, stepKey, secondary: secondaryProducts })
+ urls.onboarding({
+ productKey: values.firstProductOnboarding,
+ stepKey,
+ withProducts: secondaryProducts,
+ })
)
values.selectedProducts.forEach((productKey) => {
diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/NextButton.tsx b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/NextButton.tsx
index 774c60c6ffc0..a6c3ea9bba26 100644
--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/NextButton.tsx
+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/NextButton.tsx
@@ -15,18 +15,18 @@ interface NextButtonProps {
}
export const NextButton = ({ installationComplete, size = 'medium' }: NextButtonProps): JSX.Element => {
- const { hasNextStep } = useValues(onboardingLogic)
+ const { hasNextStep, currentStepProductKey } = useValues(onboardingLogic)
const { completeOnboarding, goToNextStep } = useActions(onboardingLogic)
const { reportOnboardingStepCompleted, reportOnboardingStepSkipped } = useActions(eventUsageLogic)
const advance = !hasNextStep ? completeOnboarding : goToNextStep
const skipInstallation = (): void => {
- reportOnboardingStepSkipped(OnboardingStepKey.INSTALL)
+ reportOnboardingStepSkipped(OnboardingStepKey.INSTALL, currentStepProductKey ?? undefined)
advance()
}
const continueInstallation = (): void => {
- reportOnboardingStepCompleted(OnboardingStepKey.INSTALL)
+ reportOnboardingStepCompleted(OnboardingStepKey.INSTALL, currentStepProductKey ?? undefined)
advance()
}
diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/index.tsx b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/index.tsx
index a5ee3ca8285e..87d52d2f4dc1 100644
--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/index.tsx
+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/index.tsx
@@ -11,6 +11,7 @@ import { OnboardingStepKey, type SDK, SDKInstructionsMap, SDKTagOverrides } from
import { onboardingLogic, OnboardingStepComponentType } from '../../onboardingLogic'
import { OnboardingStep } from '../../OnboardingStep'
+import { INSTALL_DEDUP_KEYS } from '../../types'
import { availableOnboardingProducts } from '../../utils'
import { useAdblockDetection } from '../hooks/useAdblockDetection'
import { useInstallationComplete } from '../hooks/useInstallationComplete'
@@ -77,11 +78,18 @@ export const OnboardingInstallStep: OnboardingStepComponentType<OnboardingInstal
const [mobileHandoffDismissed, setMobileHandoffDismissed] = useState(false)
const linkOpenedCapturedRef = useRef(false)
const { currentTeam } = useValues(teamLogic)
- const { productKey } = useValues(onboardingLogic)
- const productName = productKey
- ? availableOnboardingProducts[productKey as keyof typeof availableOnboardingProducts]?.name
+ const { currentStepProductKey, currentFlowStep } = useValues(onboardingLogic)
+ const productName = currentStepProductKey
+ ? availableOnboardingProducts[currentStepProductKey as keyof typeof availableOnboardingProducts]?.name
: undefined
- const installTitle = productName ? `Install ${productName}` : 'Install your SDK'
+ // The posthog-js install step is shared across many products via dedup, so it
+ // gets a generic "Install" title rather than tying it to whichever product
+ // happens to be the dedup survivor (which would mislead users picking PA + WA +
+ // SR into thinking the step only installs Product Analytics, etc.).
+ // Product-specific install steps (LLM Analytics, Workflows, Logs) keep their
+ // product-titled label since they really are product-specific.
+ const isSdkInstallStep = currentFlowStep?.dedupKey === INSTALL_DEDUP_KEYS.POSTHOG_JS
+ const installTitle = isSdkInstallStep ? 'Install' : productName ? `Install ${productName}` : 'Install your SDK'
const installationCompleteFromTeam = useInstallationComplete(teamPropertyToVerify)
const installationComplete = hideInstallationCheck || installationCompleteFromTeam
@@ -93,9 +101,9 @@ export const OnboardingInstallStep: OnboardingStepComponentType<OnboardingInstal
const isWizardOnly = useFeatureFlag('ONBOARDING_WIZARD_PROMINENCE', 'wizard-only')
// Logs uses OpenTelemetry, not the PostHog JS wizard. When the Logs install step is
- // shown (either directly or after diversion from another product's wizard step),
- // skip all wizard variants and fall through to the control SDK-grid layout.
- const isLogsProduct = productKey === ProductKey.LOGS
+ // shown (either directly or as a secondary product within another flow), skip all
+ // wizard variants and fall through to the control SDK-grid layout.
+ const isLogsProduct = currentStepProductKey === ProductKey.LOGS
// Double-gated: both the feature flag AND the client-side mobile check must
// be true. The flag controls experiment enrollment (targeted to mobile
diff --git a/frontend/src/scenes/onboarding/sdks/session-replay/AdvertiseMobileReplay.tsx b/frontend/src/scenes/onboarding/sdks/session-replay/AdvertiseMobileReplay.tsx
new file mode 100644
index 000000000000..d4147d37926a
--- /dev/null
+++ b/frontend/src/scenes/onboarding/sdks/session-replay/AdvertiseMobileReplay.tsx
@@ -0,0 +1,61 @@
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
+import { LemonTag } from 'lib/lemon-ui/LemonTag'
+import { Link } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+import { OnboardingStepKey, SDKKey } from '~/types'
+
+export type AdvertiseMobileReplayContext =
+ | 'product-analytics-onboarding'
+ | 'flags-onboarding'
+ | 'experiments-onboarding'
+
+export function AdvertiseMobileReplay({
+ context,
+ sdkKey,
+}: {
+ context: AdvertiseMobileReplayContext
+ sdkKey: SDKKey
+}): JSX.Element {
+ let platform = 'Mobile'
+ switch (sdkKey) {
+ case SDKKey.ANDROID:
+ platform = 'Android'
+ break
+ case SDKKey.IOS:
+ platform = 'iOS'
+ break
+ case SDKKey.REACT_NATIVE:
+ platform = 'React Native'
+ break
+ case SDKKey.FLUTTER:
+ platform = 'Flutter'
+ break
+ }
+ const dataAttrPlatform = platform.toLowerCase().replace(/\s+/g, '-')
+
+ return (
+ <div>
+ <LemonDivider className="my-8" />
+ <LemonBanner type="info">
+ <h3>
+ Session Replay for {platform} <LemonTag type="highlight">NEW</LemonTag>
+ </h3>
+ <div>
+ Session replay is now in general availability for {platform}.{' '}
+ <Link
+ to={urls.onboarding({
+ productKey: 'session_replay',
+ stepKey: OnboardingStepKey.INSTALL,
+ sdk: sdkKey,
+ })}
+ data-attr={`${context}-${dataAttrPlatform}-replay-cta`}
+ >
+ Learn how to set it up
+ </Link>
+ </div>
+ </LemonBanner>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/onboarding/sdks/session-replay/SessionReplaySDKInstructions.tsx b/frontend/src/scenes/onboarding/sdks/session-replay/SessionReplaySDKInstructions.tsx
index e24cb4c8c3c3..ddd9de28f14f 100644
--- a/frontend/src/scenes/onboarding/sdks/session-replay/SessionReplaySDKInstructions.tsx
+++ b/frontend/src/scenes/onboarding/sdks/session-replay/SessionReplaySDKInstructions.tsx
@@ -19,17 +19,14 @@ import {
WebInstallation,
} from '@posthog/shared-onboarding/session-replay'
-import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
-import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
-import { LemonTag } from 'lib/lemon-ui/LemonTag'
-import { Link } from 'lib/lemon-ui/Link'
-import { urls } from 'scenes/urls'
-
-import { OnboardingStepKey, SDKInstructionsMap, SDKKey } from '~/types'
+import { SDKInstructionsMap, SDKKey } from '~/types'
import { JS_WEB_SNIPPETS } from '../shared/jsWebSnippets'
import { withOnboardingDocsWrapper } from '../shared/onboardingWrappers'
+// Re-exported for back-compat: callers used to import these from this file.
+export { AdvertiseMobileReplay, type AdvertiseMobileReplayContext } from './AdvertiseMobileReplay'
+
const SNIPPETS = {
...JS_WEB_SNIPPETS,
SessionReplayFinalSteps,
@@ -144,56 +141,3 @@ export const SessionReplaySDKInstructions: SDKInstructionsMap = {
[SDKKey.REACT_NATIVE]: SessionReplayRNInstructionsWrapper,
[SDKKey.FLUTTER]: SessionReplayFlutterInstructionsWrapper,
}
-
-export type AdvertiseMobileReplayContext =
- | 'product-analytics-onboarding'
- | 'flags-onboarding'
- | 'experiments-onboarding'
-
-export function AdvertiseMobileReplay({
- context,
- sdkKey,
-}: {
- context: AdvertiseMobileReplayContext
- sdkKey: SDKKey
-}): JSX.Element {
- let platform = 'Mobile'
- switch (sdkKey) {
- case SDKKey.ANDROID:
- platform = 'Android'
- break
- case SDKKey.IOS:
- platform = 'iOS'
- break
- case SDKKey.REACT_NATIVE:
- platform = 'React-Native'
- break
- case SDKKey.FLUTTER:
- platform = 'Flutter'
- break
- }
-
- return (
- <div>
- <LemonDivider className="my-8" />
- <LemonBanner type="info">
- <h3>
- Session Replay for {platform} <LemonTag type="highlight">NEW</LemonTag>
- </h3>
- <div>
- Session replay is now in general availability for {platform}.{' '}
- <Link
- to={urls.onboarding({
- productKey: 'session_replay',
- stepKey: OnboardingStepKey.INSTALL,
- sdk: sdkKey,
- })}
- data-attr={`${context}-${platform.toLowerCase()}-replay-cta`}
- >
- Learn how to set it up
- </Link>
- </div>
- </LemonBanner>
- </div>
- )
-}
diff --git a/frontend/src/scenes/onboarding/sdks/shared/onboardingWrappers.tsx b/frontend/src/scenes/onboarding/sdks/shared/onboardingWrappers.tsx
index 85382370e02a..52d0427ca6dc 100644
--- a/frontend/src/scenes/onboarding/sdks/shared/onboardingWrappers.tsx
+++ b/frontend/src/scenes/onboarding/sdks/shared/onboardingWrappers.tsx
@@ -7,7 +7,7 @@ import { OnboardingDocsContentWrapper } from 'scenes/onboarding/OnboardingDocsCo
import { SDKKey } from '~/types'
import SetupWizardBanner from '../sdk-install-instructions/components/SetupWizardBanner'
-import { AdvertiseMobileReplay, AdvertiseMobileReplayContext } from '../session-replay/SessionReplaySDKInstructions'
+import { AdvertiseMobileReplay, type AdvertiseMobileReplayContext } from '../session-replay/AdvertiseMobileReplay'
interface OnboardingDocsWrapperOptions {
Installation: React.ComponentType<any>
diff --git a/frontend/src/scenes/onboarding/sharedSteps.tsx b/frontend/src/scenes/onboarding/sharedSteps.tsx
new file mode 100644
index 000000000000..a7b2b9dd4448
--- /dev/null
+++ b/frontend/src/scenes/onboarding/sharedSteps.tsx
@@ -0,0 +1,50 @@
+import { ProductKey } from '~/queries/schema/schema-general'
+import { type BillingProductV2Type } from '~/types'
+import { OnboardingStepKey } from '~/types'
+
+import { OnboardingUpgradeStep } from './billing/OnboardingUpgradeStep'
+import { OnboardingDataWarehouseSourcesStep } from './data-warehouse/OnboardingDataWarehouseSourcesStep'
+import { OnboardingInviteTeammates } from './OnboardingInviteTeammates'
+import { OnboardingFlowContext, OnboardingStepDescriptor } from './types'
+
+export function appendSharedTrailingSteps(
+ steps: OnboardingStepDescriptor[],
+ ctx: OnboardingFlowContext,
+ billingProduct: BillingProductV2Type | null,
+ shouldShowBilling: boolean
+): OnboardingStepDescriptor[] {
+ const result = [...steps]
+
+ // Skip when DATA_WAREHOUSE is a secondary — its provider already emits the Import data step.
+ if (ctx.primary === ProductKey.PRODUCT_ANALYTICS && !ctx.secondaries.includes(ProductKey.DATA_WAREHOUSE)) {
+ result.push({
+ id: `${OnboardingStepKey.LINK_DATA}:${ctx.primary}`,
+ productKey: ctx.primary,
+ stepKey: OnboardingStepKey.LINK_DATA,
+ role: 'primary',
+ render: () => <OnboardingDataWarehouseSourcesStep />,
+ })
+ }
+
+ if (shouldShowBilling && billingProduct) {
+ result.push({
+ id: `${OnboardingStepKey.PLANS}:${ctx.primary}`,
+ productKey: ctx.primary,
+ stepKey: OnboardingStepKey.PLANS,
+ role: 'primary',
+ render: () => <OnboardingUpgradeStep product={billingProduct} />,
+ })
+ }
+
+ if (ctx.canInviteTeammates) {
+ result.push({
+ id: `${OnboardingStepKey.INVITE_TEAMMATES}:${ctx.primary}`,
+ productKey: ctx.primary,
+ stepKey: OnboardingStepKey.INVITE_TEAMMATES,
+ role: 'primary',
+ render: () => <OnboardingInviteTeammates />,
+ })
+ }
+
+ return result
+}
diff --git a/frontend/src/scenes/onboarding/stepProviderRegistry.ts b/frontend/src/scenes/onboarding/stepProviderRegistry.ts
new file mode 100644
index 000000000000..8325a6623010
--- /dev/null
+++ b/frontend/src/scenes/onboarding/stepProviderRegistry.ts
@@ -0,0 +1,39 @@
+import { ProductKey } from '~/queries/schema/schema-general'
+
+import { dataWarehouseOnboarding } from 'products/data_warehouse/frontend/onboarding/steps'
+import { errorTrackingOnboarding } from 'products/error_tracking/frontend/onboarding/steps'
+import { experimentsOnboarding } from 'products/experiments/frontend/onboarding/steps'
+import { featureFlagsOnboarding } from 'products/feature_flags/frontend/onboarding/steps'
+import { llmAnalyticsOnboarding } from 'products/llm_analytics/frontend/onboarding/steps'
+import { logsOnboarding } from 'products/logs/frontend/onboarding/steps'
+import { productAnalyticsOnboarding } from 'products/product_analytics/frontend/onboarding/steps'
+import { sessionReplayOnboarding } from 'products/session_replay/frontend/onboarding/steps'
+import { surveysOnboarding } from 'products/surveys/frontend/onboarding/steps'
+import { webAnalyticsOnboarding } from 'products/web_analytics/frontend/onboarding/steps'
+import { workflowsOnboarding } from 'products/workflows/frontend/onboarding/steps'
+
+import { type ProductOnboardingProvider } from './types'
+
+/**
+ * Registry of per-product onboarding providers. The flow selector iterates
+ * `selectedProducts` in order and concatenates each provider's `steps(ctx)`
+ * into a single flat flow. The primary product's `completeRedirectUrl()` is
+ * used as the post-onboarding landing target.
+ *
+ * Adding a product to the onboarding system: write a provider in
+ * `products/<name>/frontend/onboarding/steps.tsx`, register it here, and add
+ * the product to `availableOnboardingProducts` in `utils.tsx`.
+ */
+export const onboardingProviderRegistry: Partial<Record<ProductKey, ProductOnboardingProvider>> = {
+ [ProductKey.PRODUCT_ANALYTICS]: productAnalyticsOnboarding,
+ [ProductKey.WEB_ANALYTICS]: webAnalyticsOnboarding,
+ [ProductKey.SESSION_REPLAY]: sessionReplayOnboarding,
+ [ProductKey.FEATURE_FLAGS]: featureFlagsOnboarding,
+ [ProductKey.EXPERIMENTS]: experimentsOnboarding,
+ [ProductKey.SURVEYS]: surveysOnboarding,
+ [ProductKey.DATA_WAREHOUSE]: dataWarehouseOnboarding,
+ [ProductKey.ERROR_TRACKING]: errorTrackingOnboarding,
+ [ProductKey.LLM_ANALYTICS]: llmAnalyticsOnboarding,
+ [ProductKey.WORKFLOWS]: workflowsOnboarding,
+ [ProductKey.LOGS]: logsOnboarding,
+}
diff --git a/frontend/src/scenes/onboarding/types.ts b/frontend/src/scenes/onboarding/types.ts
new file mode 100644
index 000000000000..60d0ebcf561d
--- /dev/null
+++ b/frontend/src/scenes/onboarding/types.ts
@@ -0,0 +1,108 @@
+import { type SetupTaskId } from 'lib/components/ProductSetup'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { type BillingType, OnboardingStepKey, type TeamPublicType, type TeamType } from '~/types'
+
+/**
+ * A unit of work in an onboarding flow. Pure data — composes deterministically from
+ * (selectedProducts, currentTeam, billing, ...) into a flat list rendered one at a
+ * time. Replaces the old "JSX children of a per-product *Onboarding view" pattern.
+ */
+export interface OnboardingStepDescriptor {
+ /** Unique within a flow. Format: `<stepKey>:<productKey>`. e.g. `install:web_analytics`. */
+ id: string
+ /** Which product this step belongs to (drives completion bookkeeping + breadcrumb attribution). */
+ productKey: ProductKey
+ /** Type of step, used for analytics events (`reportOnboardingStepCompleted`) and the default label. */
+ stepKey: OnboardingStepKey
+ /** Override for the breadcrumb/title label. Defaults to `stepKeyToTitle(stepKey)`. */
+ label?: string
+ /** Whether this step belongs to the primary product the user is onboarding into, or a secondary one. */
+ role: 'primary' | 'secondary'
+ /** Returns the React element to render for this step. */
+ render: () => React.ReactElement
+ /**
+ * If set, advancing past this step ticks the matching task in PRODUCT_SETUP_REGISTRY
+ * (via globalSetupLogic). Bridges onboarding completion into the post-onboarding setup checklist.
+ */
+ setupTaskId?: SetupTaskId
+ /**
+ * Optional flow-level dedup key. When two descriptors in the same flow share a
+ * `dedupKey`, only the first occurrence is kept. Use it to collapse install steps
+ * that are functionally identical — e.g. every posthog-js-based product's install
+ * step uses `dedupKey: "install:posthog-js"`, so picking Product Analytics + Web
+ * Analytics + Session Replay shows one Install step, not three.
+ */
+ dedupKey?: string
+ /**
+ * Auto-populated by the flow selector during the dedup pass: setup task ids from
+ * descriptors that were dropped because they shared a `dedupKey` with this one.
+ * The setStepId listener ticks all of them when the user advances past this step,
+ * so dropped products still get their setup-checklist task marked complete.
+ * Providers should NOT set this directly.
+ */
+ additionalSetupTaskIds?: SetupTaskId[]
+ /**
+ * Auto-populated by the flow selector during the dedup pass: product keys from
+ * descriptors that were dropped because they shared a `dedupKey` with this one.
+ * `completeOnboarding` credits these products as visited when the user advances
+ * past this step, so dropped secondaries still flip `has_completed_onboarding_for`.
+ * Providers should NOT set this directly.
+ */
+ additionalProductKeys?: ProductKey[]
+}
+
+export interface OnboardingFlowContext {
+ primary: ProductKey
+ secondaries: ProductKey[]
+ /** Set per-product as the registry iterates. Each provider call sees its own role. */
+ role: 'primary' | 'secondary'
+ currentTeam: TeamType | TeamPublicType | null
+ billing: BillingType | null
+ isCloudOrDev: boolean
+ subscribedDuringOnboarding: boolean
+ /** Members can invite teammates — drives the trailing invite step. */
+ canInviteTeammates: boolean
+}
+
+export type StepProvider = (ctx: OnboardingFlowContext) => OnboardingStepDescriptor[]
+
+/**
+ * Per-product registration unit for the onboarding system. Wires a product into
+ * the flow with everything the central machinery needs to know:
+ *
+ * - `steps`: how to build the product's contribution to the flow.
+ * - `completeRedirectUrl`: where to send the user after their onboarding for
+ * this product completes (was previously a central switch in onboardingLogic).
+ *
+ * Co-locating both here means adding a product is a single-file change inside
+ * `products/<name>/frontend/onboarding/steps.tsx` plus a registry entry — no
+ * scattered switches to keep in sync.
+ */
+export interface ProductOnboardingProvider {
+ steps: StepProvider
+ /**
+ * Where to redirect when this product's onboarding completes (used when this
+ * product is the primary). Falls back to `urls.default()` if not provided.
+ */
+ completeRedirectUrl?: () => string
+}
+
+/**
+ * Standard dedup keys for install steps. Products that share an SDK should use the
+ * same key on their install descriptor so the user only has to install once.
+ *
+ * - `INSTALL_POSTHOG_JS`: every product backed by `posthog-js` (the JS web SDK + its
+ * server/mobile counterparts in the same SDKInstructionsMap shape).
+ * - `INSTALL_OPENTELEMETRY`: products that send data via OTel collectors (currently
+ * Logs; expand as we add more).
+ *
+ * Products with a meaningfully-different install experience (different verification
+ * target, custom install header) intentionally don't share these keys — e.g. LLM
+ * Analytics waits for an "LLM generation" event, which is a stricter signal than
+ * "any event ingested." Workflows ships a custom AI-wizard install header.
+ */
+export const INSTALL_DEDUP_KEYS = {
+ POSTHOG_JS: 'install:posthog-js',
+ OPENTELEMETRY: 'install:opentelemetry',
+} as const
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index f622ba22348b..0c63edfff2f9 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -170,41 +170,34 @@ export const urls = {
campaign,
productKey,
stepKey,
+ step,
sdk,
- secondary,
- from,
- resumeStep,
+ withProducts,
}: {
campaign?: string
productKey?: string
stepKey?: OnboardingStepKey
+ // Namespaced step ID (e.g. `install:logs`). Takes precedence over `stepKey` when both are passed.
+ step?: string
sdk?: SDKKey
- /** Secondary product keys selected in this onboarding session (comma-joined in URL) */
- secondary?: string[]
- /** Product key the user navigated from (used for back navigation when diverted) */
- from?: string
- /** Step on the from-product to resume after a divert completes */
- resumeStep?: OnboardingStepKey
+ /** Other products to include in the flow alongside the primary (comma-joined in the URL). */
+ withProducts?: string[]
} = {}): string => {
if (campaign) {
return `/onboarding/coupons/${campaign}`
}
const params = new URLSearchParams()
- if (stepKey) {
+ if (step) {
+ params.set('step', step)
+ } else if (stepKey) {
params.set('step', stepKey)
}
if (sdk) {
params.set('sdk', sdk)
}
- if (secondary?.length) {
- params.set('secondary', secondary.join(','))
- }
- if (from) {
- params.set('from', from)
- }
- if (resumeStep) {
- params.set('resumeStep', resumeStep)
+ if (withProducts?.length) {
+ params.set('with', withProducts.join(','))
}
const base = `/onboarding${productKey ? `/${productKey}` : ''}`
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 65a8cd5b3dbb..cd1983b56060 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -700,6 +700,9 @@ importers:
'@posthog/products-revenue-analytics':
specifier: workspace:*
version: link:../products/revenue_analytics
+ '@posthog/products-session-replay':
+ specifier: workspace:*
+ version: link:../products/session_replay
'@posthog/products-session-summaries':
specifier: workspace:*
version: link:../products/session_summaries
@@ -3192,6 +3195,18 @@ importers:
specifier: 18.3.1
version: 18.3.1
+ products/session_replay:
+ dependencies:
+ '@types/react':
+ specifier: 18.3.27
+ version: 18.3.27
+ kea:
+ specifier: 'catalog:'
+ version: 4.0.0-pre.5([email protected])
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
+
products/session_summaries:
dependencies:
'@posthog/icons':
diff --git a/products/data_warehouse/frontend/onboarding/steps.tsx b/products/data_warehouse/frontend/onboarding/steps.tsx
new file mode 100644
index 000000000000..d7473bc02001
--- /dev/null
+++ b/products/data_warehouse/frontend/onboarding/steps.tsx
@@ -0,0 +1,19 @@
+import { OnboardingDataWarehouseSourcesStep } from 'scenes/onboarding/data-warehouse/OnboardingDataWarehouseSourcesStep'
+import { type ProductOnboardingProvider } from 'scenes/onboarding/types'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey } from '~/types'
+
+// `completeRedirectUrl` intentionally omitted: data warehouse falls through to
+// urls.default() — same behaviour as the original central switch.
+export const dataWarehouseOnboarding: ProductOnboardingProvider = {
+ steps: (ctx) => [
+ {
+ id: `${OnboardingStepKey.LINK_DATA}:${ProductKey.DATA_WAREHOUSE}`,
+ productKey: ProductKey.DATA_WAREHOUSE,
+ stepKey: OnboardingStepKey.LINK_DATA,
+ role: ctx.role,
+ render: () => <OnboardingDataWarehouseSourcesStep />,
+ },
+ ],
+}
diff --git a/products/error_tracking/frontend/onboarding/steps.tsx b/products/error_tracking/frontend/onboarding/steps.tsx
new file mode 100644
index 000000000000..523c71a12049
--- /dev/null
+++ b/products/error_tracking/frontend/onboarding/steps.tsx
@@ -0,0 +1,50 @@
+import { SetupTaskId } from 'lib/components/ProductSetup'
+import { OnboardingErrorTrackingAlertsStep } from 'scenes/onboarding/error-tracking/OnboardingErrorTrackingAlertsStep'
+import { OnboardingErrorTrackingSourceMapsStep } from 'scenes/onboarding/error-tracking/OnboardingErrorTrackingSourceMapsStep'
+import { ErrorTrackingSDKInstructions } from 'scenes/onboarding/sdks/error-tracking/ErrorTrackingSDKInstructions'
+import { OnboardingInstallStep } from 'scenes/onboarding/sdks/OnboardingInstallStep'
+import { INSTALL_DEDUP_KEYS, type ProductOnboardingProvider } from 'scenes/onboarding/types'
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey } from '~/types'
+
+export const errorTrackingOnboarding: ProductOnboardingProvider = {
+ steps: (ctx) => {
+ const installStep = {
+ id: `${OnboardingStepKey.INSTALL}:${ProductKey.ERROR_TRACKING}`,
+ productKey: ProductKey.ERROR_TRACKING,
+ stepKey: OnboardingStepKey.INSTALL,
+ role: ctx.role,
+ setupTaskId: SetupTaskId.EnableErrorTracking,
+ // Same posthog-js install as Product Analytics / Web Analytics / etc. When
+ // those products are also picked, only one install step is shown — but the
+ // `EnableErrorTracking` task still gets ticked because the dedup pass merges
+ // setupTaskIds from dropped descriptors into the survivor.
+ dedupKey: INSTALL_DEDUP_KEYS.POSTHOG_JS,
+ render: () => <OnboardingInstallStep sdkInstructionMap={ErrorTrackingSDKInstructions} />,
+ }
+ if (ctx.role === 'secondary') {
+ return [installStep]
+ }
+ return [
+ installStep,
+ {
+ id: `${OnboardingStepKey.SOURCE_MAPS}:${ProductKey.ERROR_TRACKING}`,
+ productKey: ProductKey.ERROR_TRACKING,
+ stepKey: OnboardingStepKey.SOURCE_MAPS,
+ role: ctx.role,
+ setupTaskId: SetupTaskId.UploadSourceMaps,
+ render: () => <OnboardingErrorTrackingSourceMapsStep />,
+ },
+ {
+ id: `${OnboardingStepKey.ALERTS}:${ProductKey.ERROR_TRACKING}`,
+ productKey: ProductKey.ERROR_TRACKING,
+ stepKey: OnboardingStepKey.ALERTS,
+ role: ctx.role,
+ render: () => <OnboardingErrorTrackingAlertsStep />,
+ },
+ ]
+ },
+ completeRedirectUrl: () => urls.errorTracking(),
+}
diff --git a/products/experiments/frontend/onboarding/steps.tsx b/products/experiments/frontend/onboarding/steps.tsx
new file mode 100644
index 000000000000..b9db50215d3d
--- /dev/null
+++ b/products/experiments/frontend/onboarding/steps.tsx
@@ -0,0 +1,21 @@
+import { ExperimentsSDKInstructions } from 'scenes/onboarding/sdks/experiments/ExperimentsSDKInstructions'
+import { OnboardingInstallStep } from 'scenes/onboarding/sdks/OnboardingInstallStep'
+import { INSTALL_DEDUP_KEYS, type ProductOnboardingProvider } from 'scenes/onboarding/types'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey } from '~/types'
+
+// `completeRedirectUrl` intentionally omitted: experiments falls through to
+// urls.default() (no curated post-onboarding landing page yet).
+export const experimentsOnboarding: ProductOnboardingProvider = {
+ steps: (ctx) => [
+ {
+ id: `${OnboardingStepKey.INSTALL}:${ProductKey.EXPERIMENTS}`,
+ productKey: ProductKey.EXPERIMENTS,
+ stepKey: OnboardingStepKey.INSTALL,
+ role: ctx.role,
+ dedupKey: INSTALL_DEDUP_KEYS.POSTHOG_JS,
+ render: () => <OnboardingInstallStep sdkInstructionMap={ExperimentsSDKInstructions} />,
+ },
+ ],
+}
diff --git a/products/feature_flags/frontend/onboarding/steps.tsx b/products/feature_flags/frontend/onboarding/steps.tsx
new file mode 100644
index 000000000000..89284ec7d821
--- /dev/null
+++ b/products/feature_flags/frontend/onboarding/steps.tsx
@@ -0,0 +1,21 @@
+import { FeatureFlagsSDKInstructions } from 'scenes/onboarding/sdks/feature-flags/FeatureFlagsSDKInstructions'
+import { OnboardingInstallStep } from 'scenes/onboarding/sdks/OnboardingInstallStep'
+import { INSTALL_DEDUP_KEYS, type ProductOnboardingProvider } from 'scenes/onboarding/types'
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey } from '~/types'
+
+export const featureFlagsOnboarding: ProductOnboardingProvider = {
+ steps: (ctx) => [
+ {
+ id: `${OnboardingStepKey.INSTALL}:${ProductKey.FEATURE_FLAGS}`,
+ productKey: ProductKey.FEATURE_FLAGS,
+ stepKey: OnboardingStepKey.INSTALL,
+ role: ctx.role,
+ dedupKey: INSTALL_DEDUP_KEYS.POSTHOG_JS,
+ render: () => <OnboardingInstallStep sdkInstructionMap={FeatureFlagsSDKInstructions} />,
+ },
+ ],
+ completeRedirectUrl: () => urls.featureFlags(),
+}
diff --git a/products/llm_analytics/frontend/onboarding/steps.tsx b/products/llm_analytics/frontend/onboarding/steps.tsx
new file mode 100644
index 000000000000..edb04d8254c9
--- /dev/null
+++ b/products/llm_analytics/frontend/onboarding/steps.tsx
@@ -0,0 +1,31 @@
+import { SetupTaskId } from 'lib/components/ProductSetup'
+import {
+ LLMAnalyticsSDKInstructions,
+ LLMAnalyticsSDKTagOverrides,
+} from 'scenes/onboarding/sdks/llm-analytics/LLMAnalyticsSDKInstructions'
+import { OnboardingInstallStep } from 'scenes/onboarding/sdks/OnboardingInstallStep'
+import { type ProductOnboardingProvider } from 'scenes/onboarding/types'
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey } from '~/types'
+
+export const llmAnalyticsOnboarding: ProductOnboardingProvider = {
+ steps: (ctx) => [
+ {
+ id: `${OnboardingStepKey.INSTALL}:${ProductKey.LLM_ANALYTICS}`,
+ productKey: ProductKey.LLM_ANALYTICS,
+ stepKey: OnboardingStepKey.INSTALL,
+ role: ctx.role,
+ setupTaskId: SetupTaskId.IngestFirstLlmEvent,
+ render: () => (
+ <OnboardingInstallStep
+ sdkInstructionMap={LLMAnalyticsSDKInstructions}
+ sdkTagOverrides={LLMAnalyticsSDKTagOverrides}
+ listeningForName="LLM generation"
+ />
+ ),
+ },
+ ],
+ completeRedirectUrl: () => urls.llmAnalyticsDashboard(),
+}
diff --git a/products/logs/frontend/onboarding/steps.tsx b/products/logs/frontend/onboarding/steps.tsx
new file mode 100644
index 000000000000..4ccd0475fd81
--- /dev/null
+++ b/products/logs/frontend/onboarding/steps.tsx
@@ -0,0 +1,25 @@
+import { SetupTaskId } from 'lib/components/ProductSetup'
+import { LogsSDKInstructions } from 'scenes/onboarding/sdks/logs/LogsSDKInstructions'
+import { OnboardingInstallStep } from 'scenes/onboarding/sdks/OnboardingInstallStep'
+import { INSTALL_DEDUP_KEYS, type ProductOnboardingProvider } from 'scenes/onboarding/types'
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey } from '~/types'
+
+export const logsOnboarding: ProductOnboardingProvider = {
+ steps: (ctx) => [
+ {
+ id: `${OnboardingStepKey.INSTALL}:${ProductKey.LOGS}`,
+ productKey: ProductKey.LOGS,
+ stepKey: OnboardingStepKey.INSTALL,
+ role: ctx.role,
+ setupTaskId: SetupTaskId.EnableLogCapture,
+ // Logs uses OpenTelemetry, not posthog-js — no dedup with the analytics products.
+ // Future OTel-based products would set the same dedupKey to share this step.
+ dedupKey: INSTALL_DEDUP_KEYS.OPENTELEMETRY,
+ render: () => <OnboardingInstallStep sdkInstructionMap={LogsSDKInstructions} hideInstallationCheck />,
+ },
+ ],
+ completeRedirectUrl: () => urls.logs(),
+}
diff --git a/products/product_analytics/frontend/onboarding/steps.tsx b/products/product_analytics/frontend/onboarding/steps.tsx
new file mode 100644
index 000000000000..97e7d3f7f12b
--- /dev/null
+++ b/products/product_analytics/frontend/onboarding/steps.tsx
@@ -0,0 +1,154 @@
+import { useValues } from 'kea'
+
+import { SetupTaskId } from 'lib/components/ProductSetup'
+import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'
+import { OnboardingProductConfiguration } from 'scenes/onboarding/OnboardingProductConfiguration'
+import { type ProductConfigOption } from 'scenes/onboarding/onboardingProductConfigurationLogic'
+import { OnboardingSessionReplayConfiguration } from 'scenes/onboarding/OnboardingSessionReplayConfiguration'
+import { OnboardingInstallStep } from 'scenes/onboarding/sdks/OnboardingInstallStep'
+import {
+ ProductAnalyticsSDKInstructions,
+ ProductAnalyticsSDKTagOverrides,
+} from 'scenes/onboarding/sdks/product-analytics/ProductAnalyticsSDKInstructions'
+import { INSTALL_DEDUP_KEYS, type ProductOnboardingProvider } from 'scenes/onboarding/types'
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey, type TeamPublicType, type TeamType } from '~/types'
+
+const sessionReplayOnboardingToggle = (
+ currentTeam: TeamType | TeamPublicType | null,
+ selectedProducts: ProductKey[]
+): ProductConfigOption => {
+ const userDecision =
+ currentTeam?.session_recording_opt_in ||
+ selectedProducts.includes(ProductKey.SESSION_REPLAY) ||
+ currentTeam?.product_intents?.some((intent) => intent.product_type === ProductKey.SESSION_REPLAY)
+
+ return {
+ title: 'Enable session recordings',
+ description: `Turn on session recordings and watch how users experience your app. We will also turn on console log and network performance recording. You can change these settings any time in the settings panel.`,
+ teamProperty: 'session_recording_opt_in',
+ // TRICKY: if someone has shown secondary (or tertiary or...) product intent for replay we want to include it as enabled
+ // particularly while we're not taking people through every product onboarding they showed interest in
+ value: userDecision ?? false,
+ type: 'toggle',
+ visible: true,
+ }
+}
+
+const ProductAnalyticsConfigStep = ({ options }: { options: ProductConfigOption[] }): JSX.Element => {
+ // mount newDashboardLogic for the entire onboarding flow — same intent as the legacy view
+ useValues(newDashboardLogic)
+ return <OnboardingProductConfiguration options={options} />
+}
+
+export const productAnalyticsOnboarding: ProductOnboardingProvider = {
+ steps: (ctx) => {
+ if (ctx.role === 'secondary') {
+ return [
+ {
+ id: `${OnboardingStepKey.INSTALL}:${ProductKey.PRODUCT_ANALYTICS}`,
+ productKey: ProductKey.PRODUCT_ANALYTICS,
+ stepKey: OnboardingStepKey.INSTALL,
+ role: ctx.role,
+ setupTaskId: SetupTaskId.IngestFirstEvent,
+ dedupKey: INSTALL_DEDUP_KEYS.POSTHOG_JS,
+ render: () => (
+ <OnboardingInstallStep
+ sdkInstructionMap={ProductAnalyticsSDKInstructions}
+ sdkTagOverrides={ProductAnalyticsSDKTagOverrides}
+ />
+ ),
+ },
+ ]
+ }
+
+ const selectedProducts = [ctx.primary, ...ctx.secondaries]
+ const options: ProductConfigOption[] = [
+ {
+ title: 'Autocapture frontend interactions',
+ description: `If you use our JavaScript, React Native or iOS libraries, we'll automagically
+ capture frontend interactions like clicks, submits, and more. Fine-tune what you
+ capture directly in your code snippet.`,
+ teamProperty: 'autocapture_opt_out',
+ value: !ctx.currentTeam?.autocapture_opt_out,
+ type: 'toggle',
+ inverseToggle: true,
+ visible: true,
+ },
+ {
+ title: 'Enable heatmaps',
+ description: `If you use our JavaScript libraries, we can capture general clicks, mouse movements,
+ and scrolling to create heatmaps.
+ No additional events are created, and you can disable this at any time.`,
+ teamProperty: 'heatmaps_opt_in',
+ value: ctx.currentTeam?.heatmaps_opt_in ?? true,
+ type: 'toggle',
+ visible: true,
+ },
+ {
+ title: 'Enable web vitals autocapture',
+ description: `Uses Google's web vitals library to automagically capture performance information.`,
+ teamProperty: 'autocapture_web_vitals_opt_in',
+ value: ctx.currentTeam?.autocapture_web_vitals_opt_in ?? true,
+ type: 'toggle',
+ visible: true,
+ },
+ sessionReplayOnboardingToggle(ctx.currentTeam, selectedProducts),
+ {
+ title: 'Capture console logs',
+ description: `Automatically enable console log capture`,
+ teamProperty: 'capture_console_log_opt_in',
+ value: true,
+ type: 'toggle',
+ visible: false,
+ },
+ {
+ title: 'Capture network performance',
+ description: `Automatically enable network performance capture`,
+ teamProperty: 'capture_performance_opt_in',
+ value: true,
+ type: 'toggle',
+ visible: false,
+ },
+ ]
+ const filteredOptions = options.filter((option) => option.teamProperty !== 'session_recording_opt_in')
+
+ return [
+ {
+ id: `${OnboardingStepKey.INSTALL}:${ProductKey.PRODUCT_ANALYTICS}`,
+ productKey: ProductKey.PRODUCT_ANALYTICS,
+ stepKey: OnboardingStepKey.INSTALL,
+ role: ctx.role,
+ setupTaskId: SetupTaskId.IngestFirstEvent,
+ // Same dedupKey as the secondary branch above — without this on the
+ // primary install step, picking Product Analytics + Session Replay (or
+ // any other posthog-js product) would render two install steps because
+ // the survivor here would carry no dedupKey for the secondary to match.
+ dedupKey: INSTALL_DEDUP_KEYS.POSTHOG_JS,
+ render: () => (
+ <OnboardingInstallStep
+ sdkInstructionMap={ProductAnalyticsSDKInstructions}
+ sdkTagOverrides={ProductAnalyticsSDKTagOverrides}
+ />
+ ),
+ },
+ {
+ id: `${OnboardingStepKey.PRODUCT_CONFIGURATION}:${ProductKey.PRODUCT_ANALYTICS}`,
+ productKey: ProductKey.PRODUCT_ANALYTICS,
+ stepKey: OnboardingStepKey.PRODUCT_CONFIGURATION,
+ role: ctx.role,
+ render: () => <ProductAnalyticsConfigStep options={filteredOptions} />,
+ },
+ {
+ id: `${OnboardingStepKey.SESSION_REPLAY}:${ProductKey.PRODUCT_ANALYTICS}`,
+ productKey: ProductKey.PRODUCT_ANALYTICS,
+ stepKey: OnboardingStepKey.SESSION_REPLAY,
+ role: ctx.role,
+ render: () => <OnboardingSessionReplayConfiguration />,
+ },
+ ]
+ },
+ completeRedirectUrl: () => urls.insightQuickStart(),
+}
diff --git a/products/session_replay/frontend/onboarding/steps.tsx b/products/session_replay/frontend/onboarding/steps.tsx
new file mode 100644
index 000000000000..88d14cac534b
--- /dev/null
+++ b/products/session_replay/frontend/onboarding/steps.tsx
@@ -0,0 +1,114 @@
+import { useValues } from 'kea'
+
+import { SetupTaskId } from 'lib/components/ProductSetup'
+import { SESSION_REPLAY_MINIMUM_DURATION_OPTIONS } from 'lib/constants'
+import { OnboardingProductConfiguration } from 'scenes/onboarding/OnboardingProductConfiguration'
+import { type ProductConfigOption } from 'scenes/onboarding/onboardingProductConfigurationLogic'
+import { OnboardingInstallStep } from 'scenes/onboarding/sdks/OnboardingInstallStep'
+import { SessionReplaySDKInstructions } from 'scenes/onboarding/sdks/session-replay/SessionReplaySDKInstructions'
+import { INSTALL_DEDUP_KEYS, type ProductOnboardingProvider } from 'scenes/onboarding/types'
+import { getMaskingConfigFromLevel, getMaskingLevelFromConfig } from 'scenes/session-recordings/utils'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { AvailableFeature, OnboardingStepKey, type SessionRecordingMaskingLevel } from '~/types'
+
+const SessionReplayConfigStep = (): JSX.Element => {
+ const { hasAvailableFeature } = useValues(userLogic)
+ const { currentTeam } = useValues(teamLogic)
+
+ const configOptions: ProductConfigOption[] = [
+ {
+ type: 'toggle',
+ title: 'Capture console logs',
+ description: `Capture console logs as a part of user session recordings.
+ Use the console logs alongside recordings to debug any issues with your app.`,
+ teamProperty: 'capture_console_log_opt_in',
+ value: currentTeam?.capture_console_log_opt_in ?? true,
+ visible: true,
+ },
+ {
+ type: 'toggle',
+ title: 'Capture network performance',
+ description: `Capture performance and network information alongside recordings. Use the
+ network requests and timings in the recording player to help you debug issues with your app.`,
+ teamProperty: 'capture_performance_opt_in',
+ value: currentTeam?.capture_performance_opt_in ?? true,
+ visible: true,
+ },
+ {
+ type: 'toggle',
+ title: 'Record user sessions',
+ description: 'Watch recordings of how users interact with your web app to see what can be improved.',
+ teamProperty: 'session_recording_opt_in',
+ value: true,
+ visible: false,
+ },
+ {
+ type: 'select',
+ title: 'Masking',
+ description: 'Choose the level of masking for your recordings.',
+ value: getMaskingLevelFromConfig(currentTeam?.session_recording_masking_config ?? {}),
+ teamProperty: 'session_recording_masking_config',
+ onChange: (value: string | number | null) => {
+ return {
+ session_recording_masking_config: getMaskingConfigFromLevel(value as SessionRecordingMaskingLevel),
+ }
+ },
+ selectOptions: [
+ { value: 'total-privacy', label: 'Total privacy (mask all text/images)' },
+ { value: 'normal', label: 'Normal (mask inputs but not text/images)' },
+ { value: 'free-love', label: 'Free love (mask only passwords)' },
+ ],
+ visible: true,
+ },
+ ]
+
+ if (hasAvailableFeature(AvailableFeature.REPLAY_RECORDING_DURATION_MINIMUM)) {
+ configOptions.push({
+ type: 'select',
+ title: 'Minimum session duration (seconds)',
+ description: `Only record sessions that are longer than the specified duration.
+ Start with it low and increase it later if you're getting too many short sessions.`,
+ teamProperty: 'session_recording_minimum_duration_milliseconds',
+ value: currentTeam?.session_recording_minimum_duration_milliseconds || null,
+ selectOptions: SESSION_REPLAY_MINIMUM_DURATION_OPTIONS,
+ visible: true,
+ })
+ }
+
+ return <OnboardingProductConfiguration options={configOptions} />
+}
+
+export const sessionReplayOnboarding: ProductOnboardingProvider = {
+ steps: (ctx) => {
+ const installStep = {
+ id: `${OnboardingStepKey.INSTALL}:${ProductKey.SESSION_REPLAY}`,
+ productKey: ProductKey.SESSION_REPLAY,
+ stepKey: OnboardingStepKey.INSTALL,
+ role: ctx.role,
+ setupTaskId: SetupTaskId.SetupSessionRecordings,
+ dedupKey: INSTALL_DEDUP_KEYS.POSTHOG_JS,
+ render: () => <OnboardingInstallStep sdkInstructionMap={SessionReplaySDKInstructions} />,
+ }
+
+ if (ctx.role === 'secondary') {
+ return [installStep]
+ }
+
+ return [
+ installStep,
+ {
+ id: `${OnboardingStepKey.PRODUCT_CONFIGURATION}:${ProductKey.SESSION_REPLAY}`,
+ productKey: ProductKey.SESSION_REPLAY,
+ stepKey: OnboardingStepKey.PRODUCT_CONFIGURATION,
+ role: ctx.role,
+ setupTaskId: SetupTaskId.ConfigureRecordingSettings,
+ render: () => <SessionReplayConfigStep />,
+ },
+ ]
+ },
+ completeRedirectUrl: () => urls.replay(),
+}
diff --git a/products/session_replay/package.json b/products/session_replay/package.json
new file mode 100644
index 000000000000..fd29c7116aaf
--- /dev/null
+++ b/products/session_replay/package.json
@@ -0,0 +1,10 @@
+{
+ "name": "@posthog/products-session-replay",
+ "dependencies": {
+ "kea": "catalog:"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "*"
+ }
+}
diff --git a/products/surveys/frontend/onboarding/steps.tsx b/products/surveys/frontend/onboarding/steps.tsx
new file mode 100644
index 000000000000..d72bae6cdb0c
--- /dev/null
+++ b/products/surveys/frontend/onboarding/steps.tsx
@@ -0,0 +1,21 @@
+import { OnboardingInstallStep } from 'scenes/onboarding/sdks/OnboardingInstallStep'
+import { SurveysSDKInstructions } from 'scenes/onboarding/sdks/surveys/SurveysSDKInstructions'
+import { INSTALL_DEDUP_KEYS, type ProductOnboardingProvider } from 'scenes/onboarding/types'
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey } from '~/types'
+
+export const surveysOnboarding: ProductOnboardingProvider = {
+ steps: (ctx) => [
+ {
+ id: `${OnboardingStepKey.INSTALL}:${ProductKey.SURVEYS}`,
+ productKey: ProductKey.SURVEYS,
+ stepKey: OnboardingStepKey.INSTALL,
+ role: ctx.role,
+ dedupKey: INSTALL_DEDUP_KEYS.POSTHOG_JS,
+ render: () => <OnboardingInstallStep sdkInstructionMap={SurveysSDKInstructions} />,
+ },
+ ],
+ completeRedirectUrl: () => urls.surveyWizard(),
+}
diff --git a/products/web_analytics/frontend/onboarding/steps.tsx b/products/web_analytics/frontend/onboarding/steps.tsx
new file mode 100644
index 000000000000..4ecb7e7c4831
--- /dev/null
+++ b/products/web_analytics/frontend/onboarding/steps.tsx
@@ -0,0 +1,115 @@
+import { SetupTaskId } from 'lib/components/ProductSetup'
+import { OnboardingProductConfiguration } from 'scenes/onboarding/OnboardingProductConfiguration'
+import { type ProductConfigOption } from 'scenes/onboarding/onboardingProductConfigurationLogic'
+import { OnboardingInstallStep } from 'scenes/onboarding/sdks/OnboardingInstallStep'
+import { WebAnalyticsSDKInstructions } from 'scenes/onboarding/sdks/web-analytics/WebAnalyticsSDKInstructions'
+import { INSTALL_DEDUP_KEYS, type ProductOnboardingProvider } from 'scenes/onboarding/types'
+import { OnboardingWebAnalyticsAuthorizedDomainsStep } from 'scenes/onboarding/web-analytics/OnboardingWebAnalyticsAuthorizedDomainsStep'
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey, type TeamPublicType, type TeamType } from '~/types'
+
+// Helper preserved from Onboarding.tsx — lives here because only Web Analytics + Product
+// Analytics use it as part of their config; productAnalytics will import it from there.
+export const sessionReplayOnboardingToggle = (
+ currentTeam: TeamType | TeamPublicType | null,
+ selectedProducts: ProductKey[]
+): ProductConfigOption => {
+ const userDecision =
+ currentTeam?.session_recording_opt_in ||
+ selectedProducts.includes(ProductKey.SESSION_REPLAY) ||
+ currentTeam?.product_intents?.some((intent) => intent.product_type === ProductKey.SESSION_REPLAY)
+
+ return {
+ title: 'Enable session recordings',
+ description: `Turn on session recordings and watch how users experience your app. We will also turn on console log and network performance recording. You can change these settings any time in the settings panel.`,
+ teamProperty: 'session_recording_opt_in',
+ // TRICKY: if someone has shown secondary (or tertiary or...) product intent for replay we want to include it as enabled
+ // particularly while we're not taking people through every product onboarding they showed interest in
+ value: userDecision ?? false,
+ type: 'toggle',
+ visible: true,
+ }
+}
+
+export const webAnalyticsOnboarding: ProductOnboardingProvider = {
+ steps: (ctx) => {
+ const installStep = {
+ id: `${OnboardingStepKey.INSTALL}:${ProductKey.WEB_ANALYTICS}`,
+ productKey: ProductKey.WEB_ANALYTICS,
+ stepKey: OnboardingStepKey.INSTALL,
+ role: ctx.role,
+ setupTaskId: SetupTaskId.IngestFirstEvent,
+ dedupKey: INSTALL_DEDUP_KEYS.POSTHOG_JS,
+ render: () => <OnboardingInstallStep sdkInstructionMap={WebAnalyticsSDKInstructions} />,
+ }
+
+ if (ctx.role === 'secondary') {
+ return [installStep]
+ }
+
+ const selectedProducts = [ctx.primary, ...ctx.secondaries]
+
+ const options: ProductConfigOption[] = [
+ {
+ title: 'Autocapture frontend interactions',
+ description: `If you use our JavaScript, React Native or iOS libraries, we'll automagically
+ capture frontend interactions like clicks, submits, and more. Fine-tune what you
+ capture directly in your code snippet.`,
+ teamProperty: 'autocapture_opt_out',
+ value: !ctx.currentTeam?.autocapture_opt_out,
+ type: 'toggle',
+ inverseToggle: true,
+ visible: true,
+ },
+ {
+ title: 'Enable heatmaps',
+ description: `If you use our JavaScript libraries, we can capture general clicks, mouse movements,
+ and scrolling to create heatmaps.
+ No additional events are created, and you can disable this at any time.`,
+ teamProperty: 'heatmaps_opt_in',
+ value: ctx.currentTeam?.heatmaps_opt_in ?? true,
+ type: 'toggle',
+ visible: true,
+ },
+ {
+ title: 'Enable web vitals autocapture',
+ description: `Uses Google's web vitals library to automagically capture performance information.`,
+ teamProperty: 'autocapture_web_vitals_opt_in',
+ value: ctx.currentTeam?.autocapture_web_vitals_opt_in ?? true,
+ type: 'toggle',
+ visible: true,
+ },
+ sessionReplayOnboardingToggle(ctx.currentTeam, selectedProducts),
+ {
+ title: 'Capture network performance',
+ description: `Automatically enable network performance capture`,
+ teamProperty: 'capture_performance_opt_in',
+ value: true,
+ type: 'toggle',
+ visible: false,
+ },
+ ]
+
+ return [
+ installStep,
+ {
+ id: `${OnboardingStepKey.AUTHORIZED_DOMAINS}:${ProductKey.WEB_ANALYTICS}`,
+ productKey: ProductKey.WEB_ANALYTICS,
+ stepKey: OnboardingStepKey.AUTHORIZED_DOMAINS,
+ role: ctx.role,
+ setupTaskId: SetupTaskId.AddAuthorizedDomain,
+ render: () => <OnboardingWebAnalyticsAuthorizedDomainsStep />,
+ },
+ {
+ id: `${OnboardingStepKey.PRODUCT_CONFIGURATION}:${ProductKey.WEB_ANALYTICS}`,
+ productKey: ProductKey.WEB_ANALYTICS,
+ stepKey: OnboardingStepKey.PRODUCT_CONFIGURATION,
+ role: ctx.role,
+ render: () => <OnboardingProductConfiguration options={options} />,
+ },
+ ]
+ },
+ completeRedirectUrl: () => urls.webAnalytics(),
+}
diff --git a/products/workflows/frontend/onboarding/steps.tsx b/products/workflows/frontend/onboarding/steps.tsx
new file mode 100644
index 000000000000..931216a9abcf
--- /dev/null
+++ b/products/workflows/frontend/onboarding/steps.tsx
@@ -0,0 +1,77 @@
+import { LemonBanner, Link } from '@posthog/lemon-ui'
+
+import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
+import { OnboardingInstallStep } from 'scenes/onboarding/sdks/OnboardingInstallStep'
+import { useWizardCommand } from 'scenes/onboarding/sdks/sdk-install-instructions/components/SetupWizardBanner'
+import {
+ WorkflowsSDKInstructions,
+ WorkflowsSDKTagOverrides,
+} from 'scenes/onboarding/sdks/workflows/WorkflowsSDKInstructions'
+import { type ProductOnboardingProvider } from 'scenes/onboarding/types'
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey } from '~/types'
+
+const WorkflowsInstallHeader = (): JSX.Element => {
+ const { wizardCommand, isCloudOrDev } = useWizardCommand()
+
+ return (
+ <div className="mt-2 space-y-4">
+ <p className="text-sm">
+ Workflows is a no-code product — installing an SDK is optional. However, with an SDK installed, any
+ captured or custom event can be used as a{' '}
+ <Link
+ to="https://posthog.com/docs/workflows/workflow-builder#triggers"
+ target="_blank"
+ targetBlankIcon={false}
+ >
+ workflow trigger
+ </Link>
+ . Without an SDK, you're limited to webhook and manual triggers.
+ </p>
+ {isCloudOrDev && (
+ <>
+ <LemonBanner type="info" hideIcon>
+ <h3 className="pb-1">AI setup wizard</h3>
+ <div className="flex flex-col p-2">
+ <p className="font-normal pb-1">
+ The fastest way to get started. Run this command from your project root — it
+ automatically detects your framework, installs PostHog, and sets up event capture.
+ </p>
+ <CodeSnippet language={Language.Bash}>{wizardCommand}</CodeSnippet>
+ </div>
+ </LemonBanner>
+ <p className="text-sm">
+ After the wizard finishes, <Link to="/workflows/channels">configure a channel</Link> then head
+ to the <Link to="/workflows">workflow builder</Link> to create your first automation.
+ </p>
+ <div className="flex items-center gap-3">
+ <div className="flex-1 border-t border-border" />
+ <span className="text-muted font-semibold text-xs uppercase">Or, set up manually</span>
+ <div className="flex-1 border-t border-border" />
+ </div>
+ </>
+ )}
+ </div>
+ )
+}
+
+export const workflowsOnboarding: ProductOnboardingProvider = {
+ steps: (ctx) => [
+ {
+ id: `${OnboardingStepKey.INSTALL}:${ProductKey.WORKFLOWS}`,
+ productKey: ProductKey.WORKFLOWS,
+ stepKey: OnboardingStepKey.INSTALL,
+ role: ctx.role,
+ render: () => (
+ <OnboardingInstallStep
+ sdkInstructionMap={WorkflowsSDKInstructions}
+ sdkTagOverrides={WorkflowsSDKTagOverrides}
+ header={<WorkflowsInstallHeader />}
+ />
+ ),
+ },
+ ],
+ completeRedirectUrl: () => urls.workflows(),
+}