:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(onboarding): add versioned instrumentation for the context-first funnel (#68052)
Fernando Gomes10877bdcd753
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex c62278c5fb90..b9d8db8409d0 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -119,6 +119,12 @@ export enum GraphSeriesAddedSource {Duplicate = 'duplicate',}+// GROW-89: both onboarding flows fire the same funnel event names during the transition, told apart+// by `version` (1 = legacy, 2 = context-first redesign) and `flow_variant`. Stamping properties+// instead of renaming keeps every existing dashboard and alert on the v1 events working. The+// redesign's v2 events live in `scenes/onboarding/onboardingEventUsageLogic`.+const LEGACY_ONBOARDING_EVENT_PROPS = { version: 1, flow_variant: 'legacy' } as const+function retentionWindowDays(metric: ExperimentRetentionMetric): number | undefined {const unitToDays: Record<string, number> = { day: 1, week: 7, month: 30 }const multiplier = unitToDays[metric.retention_window_unit]@@ -2276,6 +2282,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([reportOnboardingStarted: ({ entrypoint }) => {posthog.capture('onboarding started', {entry_point: entrypoint,+ ...LEGACY_ONBOARDING_EVENT_PROPS,})},reportOnboardingStepCompleted: ({ stepKey, productKey }) => {@@ -2284,23 +2291,27 @@ export const eventUsageLogic = kea<eventUsageLogicType>([// Optional — only set when the caller knows which product owns the step.// Lets dashboards split step funnels by product without joining elsewhere....(productKey ? { product_key: productKey } : {}),+ ...LEGACY_ONBOARDING_EVENT_PROPS,})},reportOnboardingStepSkipped: ({ stepKey, productKey }) => {posthog.capture('onboarding step skipped', {step_key: stepKey,...(productKey ? { product_key: productKey } : {}),+ ...LEGACY_ONBOARDING_EVENT_PROPS,})},reportOnboardingCompleted: ({ productKey }) => {posthog.capture('onboarding completed', {product_key: productKey,+ ...LEGACY_ONBOARDING_EVENT_PROPS,})},reportOnboardingUseCaseSelected: ({ useCase, recommendedProducts }) => {posthog.capture('onboarding use case selected', {use_case: useCase,recommended_products: recommendedProducts,+ ...LEGACY_ONBOARDING_EVENT_PROPS,})},reportOnboardingUseCaseSkipped: () => {@@ -2336,6 +2347,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([product_key: productKey,selected,recommendation_source: recommendationSource,+ ...LEGACY_ONBOARDING_EVENT_PROPS,})},reportSDKSelected: ({ sdk }) => {diff --git a/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx b/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsxindex f0ca328f0c60..9aca1d2378b7 100644--- a/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx+++ b/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx@@ -25,6 +25,7 @@ import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePaneimport { ProductKey } from '~/queries/schema/schema-general'import { Breadcrumb, OnboardingProduct, OnboardingStepKey } from '~/types'+import { onboardingEventUsageLogic } from '../onboardingEventUsageLogic'import { arraysEqual, parseProductsParam, stepKeyToTitle } from './onboardingFlowUtils'import type { onboardingLogicType } from './onboardingLogicType'import { appendSharedTrailingSteps } from './sharedSteps'@@ -69,6 +70,8 @@ export const onboardingLogic = kea<onboardingLogicType>([['openSidePanel'],globalSetupLogic,['openGlobalSetup'],+ onboardingEventUsageLogic,+ ['reportContextOnboardingCompleted'],],})),actions({@@ -595,7 +598,9 @@ export const onboardingLogic = kea<onboardingLogicType>([products.push(ProductKey.SURVEYS)}for (const productKey of products) {- eventUsageLogic.actions.reportOnboardingCompleted(productKey)+ // Same `onboarding completed` event name as the legacy flow, stamped `version: 2`+ // so dashboards can split the flows without a rename (GROW-89).+ actions.reportContextOnboardingCompleted(productKey)actions.recordProductIntentOnboardingComplete({ product_type: productKey })}// Populating has_completed_onboarding_for flips teamLogic.hasOnboardedAnyProduct true, sodiff --git a/frontend/src/scenes/onboarding/onboardingEventUsageLogic.ts b/frontend/src/scenes/onboarding/onboardingEventUsageLogic.tsnew file mode 100644index 000000000000..e995c521d1f4--- /dev/null+++ b/frontend/src/scenes/onboarding/onboardingEventUsageLogic.ts@@ -0,0 +1,122 @@+import { actions, kea, listeners, path } from 'kea'+import posthog from 'posthog-js'++import type { onboardingEventUsageLogicType } from './onboardingEventUsageLogicType'++/** Steps of the context-first onboarding flow (`ContextOnboarding.tsx`), in order. */+export type ContextOnboardingStepId = 'welcome' | 'install' | 'sources' | 'warehouse' | 'billing' | 'invite'++// GROW-89: both onboarding flows fire the same funnel event names during the transition, told apart+// by `version` (1 = legacy, 2 = context-first redesign) and `flow_variant`. Reusing names keeps+// every existing dashboard and alert on the v1 events working; the legacy flow's events live in+// `eventUsageLogic`, stamped `{version: 1, flow_variant: 'legacy'}`.+const CONTEXT_ONBOARDING_EVENT_PROPS = { version: 2, flow_variant: 'context_first' } as const++/**+ * Funnel events for the context-first onboarding flow (v2) — a dedicated logic rather than more+ * surface on the giant `eventUsageLogic`, following `sessionRecordingEventUsageLogic`'s split.+ * Shared funnel signals (started, step completed/skipped, completed) reuse the legacy event names+ * with `version: 2`; signals the legacy flow doesn't have (step viewed, install mode, source+ * toggles, plan, cloud run) get their own names.+ */+export const onboardingEventUsageLogic = kea<onboardingEventUsageLogicType>([+ path(['scenes', 'onboarding', 'onboardingEventUsageLogic']),+ actions({+ reportContextOnboardingStarted: true,+ reportContextOnboardingStepViewed: (stepId: ContextOnboardingStepId) => ({ stepId }),+ reportContextOnboardingStepCompleted: (stepId: ContextOnboardingStepId) => ({ stepId }),+ reportContextOnboardingStepSkipped: (stepId: ContextOnboardingStepId) => ({ stepId }),+ reportContextOnboardingCompleted: (productKey: string) => ({ productKey }),+ reportContextOnboardingInstallModeSelected: (mode: 'cloud' | 'local') => ({ mode }),+ reportContextOnboardingSourceToggled: (productKey: string, toggle: string, enabled: boolean) => ({+ productKey,+ toggle,+ enabled,+ }),+ reportContextOnboardingPlanSelected: (plan: 'free' | 'pay_as_you_go') => ({ plan }),+ // Cloud-run funnel events mirror the backend `task_run_created` / `task_run_completed`+ // lifecycle events (products/tasks/backend/models.py) and reuse their property names.+ reportContextOnboardingCloudRunQueued: (props: { taskId: string; runId: string; repository: string }) => props,+ reportContextOnboardingCloudRunCompleted: (props: {+ taskId: string+ runId: string+ status: 'completed' | 'failed' | 'cancelled'+ durationSeconds: number | null+ prOpened: boolean+ prUrl: string | null+ }) => props,+ }),+ listeners({+ // The flow always enters at the welcome step, so `started` carries a fixed entry point+ // (legacy uses e.g. 'product_selection').+ reportContextOnboardingStarted: () => {+ posthog.capture('onboarding started', {+ entry_point: 'welcome',+ ...CONTEXT_ONBOARDING_EVENT_PROPS,+ })+ },+ reportContextOnboardingStepViewed: ({ stepId }) => {+ posthog.capture('onboarding step viewed', {+ step_key: stepId,+ ...CONTEXT_ONBOARDING_EVENT_PROPS,+ })+ },+ reportContextOnboardingStepCompleted: ({ stepId }) => {+ posthog.capture('onboarding step completed', {+ step_key: stepId,+ ...CONTEXT_ONBOARDING_EVENT_PROPS,+ })+ },+ reportContextOnboardingStepSkipped: ({ stepId }) => {+ posthog.capture('onboarding step skipped', {+ step_key: stepId,+ ...CONTEXT_ONBOARDING_EVENT_PROPS,+ })+ },+ reportContextOnboardingCompleted: ({ productKey }) => {+ posthog.capture('onboarding completed', {+ product_key: productKey,+ ...CONTEXT_ONBOARDING_EVENT_PROPS,+ })+ },+ reportContextOnboardingInstallModeSelected: ({ mode }) => {+ posthog.capture('onboarding install mode selected', {+ mode,+ ...CONTEXT_ONBOARDING_EVENT_PROPS,+ })+ },+ reportContextOnboardingSourceToggled: ({ productKey, toggle, enabled }) => {+ posthog.capture('onboarding context source toggled', {+ product_key: productKey,+ toggle,+ enabled,+ ...CONTEXT_ONBOARDING_EVENT_PROPS,+ })+ },+ reportContextOnboardingPlanSelected: ({ plan }) => {+ posthog.capture('onboarding plan selected', {+ plan,+ ...CONTEXT_ONBOARDING_EVENT_PROPS,+ })+ },+ reportContextOnboardingCloudRunQueued: ({ taskId, runId, repository }) => {+ posthog.capture('onboarding cloud run queued', {+ task_id: taskId,+ run_id: runId,+ repository,+ ...CONTEXT_ONBOARDING_EVENT_PROPS,+ })+ },+ reportContextOnboardingCloudRunCompleted: ({ taskId, runId, status, durationSeconds, prOpened, prUrl }) => {+ posthog.capture('onboarding cloud run completed', {+ task_id: taskId,+ run_id: runId,+ status,+ duration_seconds: durationSeconds,+ pr_opened: prOpened,+ pr_url: prUrl,+ ...CONTEXT_ONBOARDING_EVENT_PROPS,+ })+ },+ }),+])diff --git a/frontend/src/scenes/onboarding/self-driving/ContextBillingStep.tsx b/frontend/src/scenes/onboarding/self-driving/ContextBillingStep.tsxindex 8e826b463222..bb6c79c70d3a 100644--- a/frontend/src/scenes/onboarding/self-driving/ContextBillingStep.tsx+++ b/frontend/src/scenes/onboarding/self-driving/ContextBillingStep.tsx@@ -7,6 +7,7 @@ import { BillingUpgradeCTA } from 'lib/components/BillingUpgradeCTA'import { pluralize } from 'lib/utils/strings'import { billingLogic } from 'scenes/billing/billingLogic'import { paymentEntryLogic } from 'scenes/billing/paymentEntryLogic'+import { onboardingEventUsageLogic } from 'scenes/onboarding/onboardingEventUsageLogic'import { availableOnboardingProducts } from 'scenes/onboarding/shared/utils'import { ProductKey } from '~/queries/schema/schema-general'@@ -98,15 +99,23 @@ function PlanChoice({onContinue: () => void}): JSX.Element {const { startPaymentEntryFlow } = useActions(paymentEntryLogic)+ const { reportContextOnboardingPlanSelected } = useActions(onboardingEventUsageLogic)// Guard the subscribe button against double-submit: `isLoading` covers the returning-customer// activate call, `paymentEntryModalOpen` covers a new customer once the Stripe modal is up.const { isLoading, paymentEntryModalOpen } = useValues(paymentEntryLogic)const subscribing = isLoading || paymentEntryModalOpen+ // Reported at the pick, not at payment completion — whether payment then resolves is billing's+ // own funnel (GROW-89).const subscribe = (): void => {+ reportContextOnboardingPlanSelected('pay_as_you_go')// Returning the user to the same URL keeps them in the onboarding flow once payment resolves.startPaymentEntryFlow(platformProduct, window.location.pathname + window.location.search)}+ const continueFree = (): void => {+ reportContextOnboardingPlanSelected('free')+ onContinue()+ }return (<div className="flex flex-wrap gap-3">@@ -127,7 +136,7 @@ function PlanChoice({type="secondary"fullWidthcenter- onClick={onContinue}+ onClick={continueFree}className="mt-auto"data-attr="context-onboarding-free">diff --git a/frontend/src/scenes/onboarding/self-driving/ContextOnboarding.tsx b/frontend/src/scenes/onboarding/self-driving/ContextOnboarding.tsxindex 6dd3d3652353..3aefda7e24f1 100644--- a/frontend/src/scenes/onboarding/self-driving/ContextOnboarding.tsx+++ b/frontend/src/scenes/onboarding/self-driving/ContextOnboarding.tsx@@ -1,4 +1,4 @@-import { useActions, useValues } from 'kea'+import { useActions, useAsyncActions, useValues } from 'kea'import { router } from 'kea-router'import { type ReactNode, useEffect, useState } from 'react'@@ -9,11 +9,13 @@ import { AuthorizedUrlList } from 'lib/components/AuthorizedUrlList/AuthorizedUrimport { AuthorizedUrlListType } from 'lib/components/AuthorizedUrlList/authorizedUrlListLogic'import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { Spinner } from 'lib/lemon-ui/Spinner'import { cn } from 'lib/utils/css-classes'import { teamLogic } from 'scenes/teamLogic'import { ProductKey } from '~/queries/schema/schema-general'+import type { TeamType } from '~/types'import selfDrivingHog from 'public/hedgehog/self-driving-hog.png'@@ -22,6 +24,7 @@ import {useWizardTakeoverActive,WizardProgressTracker,} from '../legacy/sdks/OnboardingInstallStep/WizardProgressTracker'+import { type ContextOnboardingStepId, onboardingEventUsageLogic } from '../onboardingEventUsageLogic'import { useWizardCommand } from '../shared/SetupWizardBanner'import { availableOnboardingProducts, getProductIcon, toSentenceCase } from '../shared/utils'import { ContextBillingStep } from './ContextBillingStep'@@ -69,6 +72,7 @@ function InstallOptions({ onContinue }: { onContinue: () => void }): JSX.Elementconst { isCloudOrDev } = useWizardCommand()const { activeCloudRun } = useValues(activeCloudRunLogic)const { clearActiveCloudRun } = useActions(activeCloudRunLogic)+ const { reportContextOnboardingInstallModeSelected } = useActions(onboardingEventUsageLogic)const [mode, setMode] = useState<InstallMode>('cloud')const offerCloud = cloudRunEnabled && isCloudOrDev// GROW-95: once a cloud run is spawned you cannot also run it locally, so the local tab is blocked and@@ -122,7 +126,10 @@ function InstallOptions({ onContinue }: { onContinue: () => void }): JSX.Element<LemonSegmentedButtonfullWidthvalue={effectiveMode}- onChange={(value) => setMode(value)}+ onChange={(value) => {+ reportContextOnboardingInstallModeSelected(value)+ setMode(value)+ }}options={[{value: 'cloud',@@ -388,7 +395,8 @@ export function SourcesStepInner({codebase: CodebaseAccess}): JSX.Element {const { currentTeam } = useValues(teamLogic)- const { updateCurrentTeam } = useActions(teamLogic)+ const { updateCurrentTeam } = useAsyncActions(teamLogic)+ const { reportContextOnboardingSourceToggled } = useActions(onboardingEventUsageLogic)const autocaptureOn = !currentTeam?.autocapture_opt_outconst replayOn = !!currentTeam?.session_recording_opt_in@@ -398,6 +406,15 @@ export function SourcesStepInner({// installed and sending. Until then, turned-on sources read as "Needs install".const sdkInstalled = !!currentTeam?.ingested_event+ // Report to the v2 funnel (GROW-89) only after the PATCH lands: on failure the switch snaps back+ // to the team's real state, so a funnel event would record a toggle that never happened.+ // `toggle` names the switch — a card can carry several.+ const toggleSource = (productKey: ProductKey, toggle: string, enabled: boolean, patch: Partial<TeamType>): void => {+ void updateCurrentTeam(patch)+ .then(() => reportContextOnboardingSourceToggled(productKey, toggle, enabled))+ .catch(() => {}) // a failed write is not a toggle; the UI already reflects the revert+ }+const sources: ToolSource[] = [{productKey: ProductKey.PRODUCT_ANALYTICS,@@ -407,13 +424,17 @@ export function SourcesStepInner({label: 'Autocapture events',description: 'Clicks, pageviews, and inputs captured automatically.',checked: autocaptureOn,- onChange: (checked) => updateCurrentTeam({ autocapture_opt_out: !checked }),+ onChange: (checked) =>+ toggleSource(ProductKey.PRODUCT_ANALYTICS, 'autocapture', checked, {+ autocapture_opt_out: !checked,+ }),},{label: 'Heatmaps',description: 'Aggregate clicks, scrolls, and mouse movement.',checked: !!currentTeam?.heatmaps_opt_in,- onChange: (checked) => updateCurrentTeam({ heatmaps_opt_in: checked }),+ onChange: (checked) =>+ toggleSource(ProductKey.PRODUCT_ANALYTICS, 'heatmaps', checked, { heatmaps_opt_in: checked }),},],},@@ -424,18 +445,27 @@ export function SourcesStepInner({{label: 'Record sessions',checked: replayOn,- onChange: (checked) => updateCurrentTeam({ session_recording_opt_in: checked }),+ onChange: (checked) =>+ toggleSource(ProductKey.SESSION_REPLAY, 'session_recording', checked, {+ session_recording_opt_in: checked,+ }),},{label: 'Console logs',checked: !!currentTeam?.capture_console_log_opt_in,- onChange: (checked) => updateCurrentTeam({ capture_console_log_opt_in: checked }),+ onChange: (checked) =>+ toggleSource(ProductKey.SESSION_REPLAY, 'console_logs', checked, {+ capture_console_log_opt_in: checked,+ }),disabled: !replayOn,},{label: 'Network performance',checked: !!currentTeam?.capture_performance_opt_in,- onChange: (checked) => updateCurrentTeam({ capture_performance_opt_in: checked }),+ onChange: (checked) =>+ toggleSource(ProductKey.SESSION_REPLAY, 'network_performance', checked, {+ capture_performance_opt_in: checked,+ }),disabled: !replayOn,},],@@ -448,7 +478,10 @@ export function SourcesStepInner({label: 'Capture exceptions',description: 'Errors and stack traces as they happen.',checked: !!currentTeam?.autocapture_exceptions_opt_in,- onChange: (checked) => updateCurrentTeam({ autocapture_exceptions_opt_in: checked }),+ onChange: (checked) =>+ toggleSource(ProductKey.ERROR_TRACKING, 'exception_autocapture', checked, {+ autocapture_exceptions_opt_in: checked,+ }),},],},@@ -460,7 +493,10 @@ export function SourcesStepInner({label: 'Web vitals',description: 'Load times and layout shifts from real users.',checked: !!currentTeam?.autocapture_web_vitals_opt_in,- onChange: (checked) => updateCurrentTeam({ autocapture_web_vitals_opt_in: checked }),+ onChange: (checked) =>+ toggleSource(ProductKey.WEB_ANALYTICS, 'web_vitals', checked, {+ autocapture_web_vitals_opt_in: checked,+ }),},],extra: (@@ -512,7 +548,7 @@ export function SourcesStepInner({// ---- Shell ---------------------------------------------------------------------------------------interface StepDef {- id: string+ id: ContextOnboardingStepIdtitle: stringContent: (props: { onContinue: () => void }) => JSX.Elementskippable?: boolean@@ -546,6 +582,12 @@ const CARD_CLASSES =export function ContextOnboarding(): JSX.Element {const { completeContextOnboarding } = useActions(onboardingLogic)const { isCompleting } = useValues(onboardingLogic)+ const {+ reportContextOnboardingStarted,+ reportContextOnboardingStepViewed,+ reportContextOnboardingStepCompleted,+ reportContextOnboardingStepSkipped,+ } = useActions(onboardingEventUsageLogic)// Initialize from the URL so a refresh — or an OAuth callback that lands back on ?step=install// (e.g. the GitHub connect flow) — resumes where it left off instead of restarting at welcome.const [stepIndex, setStepIndex] = useState(() => {@@ -557,6 +599,18 @@ export function ContextOnboarding(): JSX.Element {const isFirst = stepIndex === 0const isLast = stepIndex === STEPS.length - 1+ // Funnel (GROW-89): `started` fires once per fresh entry — a ?step= resume (refresh, OAuth+ // callback) is a continuation, not a new start. `step viewed` fires for every step shown,+ // including the one this mounts on.+ useOnMountEffect(() => {+ if (stepIndex === 0) {+ reportContextOnboardingStarted()+ }+ })+ useEffect(() => {+ reportContextOnboardingStepViewed(STEPS[stepIndex].id)+ }, [stepIndex, reportContextOnboardingStepViewed])+// Keep ?step= in sync as the user moves so the URL stays resumable, preserving any other params// (like the integration ids the GitHub callback appends).const goToStep = (index: number): void => {@@ -567,7 +621,7 @@ export function ContextOnboarding(): JSX.Element {})}- const goNext = (): void => {+ const advance = (): void => {if (isLast) {// Marks onboarding complete (credits the sources turned on) and navigates out, so// sceneLogic doesn't bounce the user back into onboarding.@@ -576,6 +630,17 @@ export function ContextOnboarding(): JSX.Element {}goToStep(stepIndex + 1)}+ // Leaving a step forward is either completing it (Continue / the step's own primary action,+ // e.g. a queued cloud run or a plan pick) or skipping it — reported separately so the funnel+ // can tell drop-off from opt-out.+ const completeStep = (): void => {+ reportContextOnboardingStepCompleted(step.id)+ advance()+ }+ const skipStep = (): void => {+ reportContextOnboardingStepSkipped(step.id)+ advance()+ }const goBack = (): void => goToStep(Math.max(0, stepIndex - 1))return (@@ -614,7 +679,7 @@ export function ContextOnboarding(): JSX.Element {{/* Scrollable middle: fade edges + hover scrollbar so tall steps don't hard-crop. */}<ScrollableShadows direction="vertical" styledScrollbars className="flex-1 min-h-0" contentClassName="px-1">- <step.Content onContinue={goNext} />+ <step.Content onContinue={completeStep} /></ScrollableShadows>{/* Pinned footer — omitted when the step has neither Skip nor a footer Continue (it supplies@@ -622,7 +687,7 @@ export function ContextOnboarding(): JSX.Element {{(step.skippable || !step.hideContinue) && (<div className="shrink-0 flex items-center justify-between gap-2">{step.skippable ? (- <LemonButton type="tertiary" size="small" onClick={goNext}>+ <LemonButton type="tertiary" size="small" onClick={skipStep}>Skip for now</LemonButton>) : (@@ -633,7 +698,7 @@ export function ContextOnboarding(): JSX.Element {type="primary"status="alt"sideIcon={<IconArrowRight />}- onClick={goNext}+ onClick={completeStep}loading={isLast && isCompleting}>{isLast ? 'Finish' : isFirst ? 'Get started' : 'Continue'}diff --git a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/installationProgressLogic.ts b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/installationProgressLogic.tsindex 25b51695b254..9c7d2d714053 100644--- a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/installationProgressLogic.ts+++ b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/installationProgressLogic.ts@@ -4,7 +4,7 @@ import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/apiimport { wizardSessionStreamLogic } from 'products/wizard/frontend/wizardSessionStreamLogic'import type { installationProgressLogicType } from './installationProgressLogicType'-import { taskRunStreamLogic, TaskRunProgressStep, TaskRunStreamState } from './taskRunStreamLogic'+import { taskRunPrUrl, taskRunStreamLogic, TaskRunProgressStep, TaskRunStreamState } from './taskRunStreamLogic'// The wizard session stream the local CLI publishes to — and the channel a cloud wizard reports its// own sub-progress on. Matches wizardProgressTrackerLogic's WORKFLOW_ID.@@ -113,10 +113,7 @@ export function cloudProgress(}): null- // The agent opens the PR mid-run (while it keeps CI green), so the url arrives via the "pr" progress- // step before the run reaches a terminal output. Prefer the terminal output when present.- const prStepUrl = progressSteps.find((p) => p.step === 'pr')?.detail- const prUrl = taskRunState?.output?.pr_url ?? (prStepUrl && prStepUrl.startsWith('http') ? prStepUrl : null)+ const prUrl = taskRunPrUrl(taskRunState, progressSteps)return {phase,diff --git a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.test.ts b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.test.tsindex e44c1c7f1243..94078ea75bbd 100644--- a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.test.ts+++ b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.test.ts@@ -1,4 +1,11 @@-import { mergeProgressStep, parseTaskRunStreamMessage, TaskRunProgressStep } from './taskRunStreamLogic'+import {+ cloudRunCompletionReport,+ mergeProgressStep,+ parseTaskRunStreamMessage,+ TaskRunProgressStep,+ taskRunPrUrl,+ TaskRunStreamState,+} from './taskRunStreamLogic'function step(overrides: Partial<TaskRunProgressStep> = {}): TaskRunProgressStep {return {@@ -11,6 +18,19 @@ function step(overrides: Partial<TaskRunProgressStep> = {}): TaskRunProgressStep}}+function runState(overrides: Partial<TaskRunStreamState> = {}): TaskRunStreamState {+ return {+ status: 'in_progress',+ stage: 'wizard',+ output: null,+ branch: null,+ error_message: null,+ updated_at: '2026-01-01T00:05:00Z',+ completed_at: null,+ ...overrides,+ }+}+describe('taskRunStreamLogic helpers', () => {describe('mergeProgressStep', () => {it('appends a new step', () => {@@ -131,4 +151,103 @@ describe('taskRunStreamLogic helpers', () => {expect(() => parseTaskRunStreamMessage('not json')).toThrow(SyntaxError)})})++ describe('taskRunPrUrl', () => {+ it('prefers the terminal output url over the pr progress step', () => {+ const state = runState({ output: { pr_url: 'https://x/pull/2' } })+ const steps = [step({ step: 'pr', group: 'pr_create', detail: 'https://x/pull/1' })]+ expect(taskRunPrUrl(state, steps)).toBe('https://x/pull/2')+ })++ it('falls back to the pr progress step detail when the output has no url', () => {+ const steps = [step({ step: 'pr', group: 'pr_create', detail: 'https://x/pull/1' })]+ expect(taskRunPrUrl(runState(), steps)).toBe('https://x/pull/1')+ })++ it('ignores a pr step whose detail is not a url', () => {+ const steps = [step({ step: 'pr', group: 'pr_create', detail: 'Opening a pull request' })]+ expect(taskRunPrUrl(runState(), steps)).toBeNull()+ })++ it('returns null with no state and no pr step', () => {+ expect(taskRunPrUrl(null, [step()])).toBeNull()+ })+ })++ describe('cloudRunCompletionReport', () => {+ const startedAt = '2026-01-01T00:00:00Z'++ it('reports an observed transition into completed, with duration and the PR', () => {+ const report = cloudRunCompletionReport(+ runState({ status: 'in_progress' }),+ runState({+ status: 'completed',+ output: { pr_url: 'https://x/pull/1' },+ completed_at: '2026-01-01T00:04:30Z',+ }),+ [],+ startedAt+ )+ expect(report).toEqual({+ status: 'completed',+ durationSeconds: 270,+ prOpened: true,+ prUrl: 'https://x/pull/1',+ })+ })++ it('reports a failed run with no PR opened', () => {+ const report = cloudRunCompletionReport(+ runState({ status: 'in_progress' }),+ runState({ status: 'failed', error_message: 'boom', completed_at: '2026-01-01T00:04:30Z' }),+ [],+ startedAt+ )+ expect(report).toEqual({ status: 'failed', durationSeconds: 270, prOpened: false, prUrl: null })+ })++ it('takes the PR url from the pr progress step when the output lacks one', () => {+ const report = cloudRunCompletionReport(+ runState({ status: 'in_progress' }),+ runState({ status: 'completed', completed_at: '2026-01-01T00:04:30Z' }),+ [step({ step: 'pr', group: 'pr_create', detail: 'https://x/pull/1' })],+ startedAt+ )+ expect(report).toMatchObject({ prOpened: true, prUrl: 'https://x/pull/1' })+ })++ it('falls back to updated_at for the duration when completed_at is missing', () => {+ const report = cloudRunCompletionReport(+ runState({ status: 'in_progress' }),+ runState({ status: 'cancelled', updated_at: '2026-01-01T00:02:00Z' }),+ [],+ startedAt+ )+ expect(report).toMatchObject({ status: 'cancelled', durationSeconds: 120 })+ })++ it('reports a null duration without a kickoff timestamp', () => {+ const report = cloudRunCompletionReport(+ runState({ status: 'in_progress' }),+ runState({ status: 'completed', completed_at: '2026-01-01T00:04:30Z' }),+ [],+ undefined+ )+ expect(report).toMatchObject({ durationSeconds: null })+ })++ it.each([+ ['the update is not terminal', runState({ status: 'in_progress' }), runState({ status: 'queued' })],+ // A stream (re)connecting to a finished run replays the terminal state with no prior+ // observation — the backend task_run_* events cover unwatched completions.+ ['no previous state was observed', null, runState({ status: 'completed' })],+ [+ 'the previous state was already terminal',+ runState({ status: 'completed' }),+ runState({ status: 'completed' }),+ ],+ ])('returns null when %s', (_name, previous, state) => {+ expect(cloudRunCompletionReport(previous, state, [], startedAt)).toBeNull()+ })+ })})diff --git a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.ts b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.tsindex 2cfa7eba03e5..21b2b2764ff1 100644--- a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.ts+++ b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/taskRunStreamLogic.ts@@ -4,6 +4,8 @@ import { projectLogic } from 'scenes/projectLogic'import { getTasksRunsStreamRetrieveUrl } from 'products/tasks/frontend/generated/api'+import { onboardingEventUsageLogic } from '../../../onboardingEventUsageLogic'+import { activeCloudRunLogic } from './activeCloudRunLogic'import type { taskRunStreamLogicType } from './taskRunStreamLogicType'export type TaskRunConnectionStatus = 'idle' | 'connecting' | 'open' | 'closed' | 'error'@@ -94,6 +96,57 @@ export function parseTaskRunStreamMessage(rawData: string): TaskRunStreamMessagereturn null}+export const TERMINAL_TASK_RUN_STATUSES = ['completed', 'failed', 'cancelled'] as const+export type TerminalTaskRunStatus = (typeof TERMINAL_TASK_RUN_STATUSES)[number]++function isTerminalStatus(status: string): status is TerminalTaskRunStatus {+ return (TERMINAL_TASK_RUN_STATUSES as readonly string[]).includes(status)+}++// The agent opens the PR mid-run (while it keeps CI green), so the url arrives via the "pr" progress+// step before the run reaches a terminal output. Prefer the terminal output when present.+export function taskRunPrUrl(state: TaskRunStreamState | null, steps: TaskRunProgressStep[]): string | null {+ const prStepUrl = steps.find((s) => s.step === 'pr')?.detail+ return state?.output?.pr_url ?? (prStepUrl && prStepUrl.startsWith('http') ? prStepUrl : null)+}++export interface CloudRunCompletionReport {+ status: TerminalTaskRunStatus+ durationSeconds: number | null+ prOpened: boolean+ prUrl: string | null+}++/**+ * The v2 onboarding funnel's terminal cloud-run event (GROW-89), or null when this state update is+ * not one to report. Only an OBSERVED transition into a terminal status counts: a stream that+ * (re)connects to an already-finished run replays that state, and reporting it would double-count+ * the run — the backend `task_run_completed` / `task_run_failed` events already cover runs that+ * finish while nobody is watching.+ */+export function cloudRunCompletionReport(+ previous: TaskRunStreamState | null,+ state: TaskRunStreamState,+ progressSteps: TaskRunProgressStep[],+ startedAt: string | undefined+): CloudRunCompletionReport | null {+ if (!isTerminalStatus(state.status) || !previous || isTerminalStatus(previous.status)) {+ return null+ }+ // Duration since kickoff (the handle's startedAt) — the stream carries no started_at of its own.+ // The backend's `duration_seconds` (created_at → completed_at) stays the authoritative figure.+ const endedAt = state.completed_at ?? state.updated_at+ const elapsedMs = startedAt && endedAt ? new Date(endedAt).getTime() - new Date(startedAt).getTime() : NaN+ const durationSeconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.round(elapsedMs / 1000)) : null+ const prUrl = taskRunPrUrl(state, progressSteps)+ return { status: state.status, durationSeconds, prOpened: !!prUrl, prUrl }+}++// Terminal outcomes already reported this pageload, keyed by run id. Guards against a re-observed+// transition (e.g. the stream replaying history after a remount) double-counting a run. Mirrors the+// wizard tracker's once-per-session report guards.+const reportedTerminalRuns = new Set<string>()+/*** Raw SSE consumer for a single TaskRun (the cloud-run pipeline: provision → clone → wizard → agent →* PR). A private source for the Installation layer — `installationProgressLogic` merges this with the@@ -108,7 +161,8 @@ export const taskRunStreamLogic = kea<taskRunStreamLogicType>([key((props) => props.runId),path((key) => ['scenes', 'onboarding', 'taskRunStreamLogic', key]),connect(() => ({- values: [projectLogic, ['currentProjectId']],+ values: [projectLogic, ['currentProjectId'], activeCloudRunLogic, ['activeCloudRun']],+ actions: [onboardingEventUsageLogic, ['reportContextOnboardingCloudRunCompleted']],})),actions({connect: true,@@ -170,10 +224,25 @@ export const taskRunStreamLogic = kea<taskRunStreamLogicType>([},],}),- listeners(({ values, actions, props, cache }) => ({- // Arm a stall timer while the run reports `queued`; any other status disarms it. The timer- // rides disposables so unmount (and tab-hide) tears it down with everything else.- taskRunStateUpdated: ({ state }) => {+ listeners(({ values, actions, props, cache, selectors }) => ({+ taskRunStateUpdated: ({ state }, _breakpoint, _action, previousState) => {+ // The run's terminal state flows through here no matter which surface is watching (inline+ // install view, sources step, FAB, sidebar button), so this is where the funnel's cloud-run+ // outcome is reported (GROW-89) — the keyed logic dedupes concurrent surfaces to one listener.+ const previous = selectors.taskRunState(previousState)+ // startedAt travels on the persisted run handle; ignore it if the handle is a different run.+ const startedAt = values.activeCloudRun?.runId === props.runId ? values.activeCloudRun.startedAt : undefined+ const report = cloudRunCompletionReport(previous, state, values.progressSteps, startedAt)+ if (report && !reportedTerminalRuns.has(props.runId)) {+ reportedTerminalRuns.add(props.runId)+ actions.reportContextOnboardingCloudRunCompleted({+ taskId: props.taskId,+ runId: props.runId,+ ...report,+ })+ }+ // Arm a stall timer while the run reports `queued`; any other status disarms it. The timer+ // rides disposables so unmount (and tab-hide) tears it down with everything else.if (state.status !== 'queued') {cache.disposables.dispose('queued-stall')returndiff --git a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/wizardCloudRunLogic.ts b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/wizardCloudRunLogic.tsindex 6b0b6cd1dea7..3993cf94377f 100644--- a/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/wizardCloudRunLogic.ts+++ b/frontend/src/scenes/onboarding/self-driving/sdks/OnboardingInstallStep/wizardCloudRunLogic.ts@@ -11,6 +11,7 @@ import { IntegrationType, OnboardingStepKey } from '~/types'import { onboardingLogic } from '../../../legacy/onboardingLogic'import { sdksLogic } from '../../../legacy/sdks/sdksLogic'+import { onboardingEventUsageLogic } from '../../../onboardingEventUsageLogic'import { activeCloudRunLogic } from './activeCloudRunLogic'import type { wizardCloudRunLogicType } from './wizardCloudRunLogicType'@@ -51,7 +52,14 @@ export const wizardCloudRunLogic = kea<wizardCloudRunLogicType>([sdksLogic,['selectedSDK'],],- actions: [integrationsLogic, ['loadIntegrations'], activeCloudRunLogic, ['setActiveCloudRun']],+ actions: [+ integrationsLogic,+ ['loadIntegrations'],+ activeCloudRunLogic,+ ['setActiveCloudRun'],+ onboardingEventUsageLogic,+ ['reportContextOnboardingCloudRunQueued'],+ ],})),actions({setSelectedRepository: (repository: string | null) => ({ repository }),@@ -145,6 +153,8 @@ export const wizardCloudRunLogic = kea<wizardCloudRunLogicType>([// teamLogic's currentProjectId can be the '@current' placeholder pre-load; by kickoff// time the team is loaded, so this is a plain numeric coercion in practice.actions.setActiveCloudRun(task_id, run_id, new Date().toISOString(), Number(currentProjectId))+ // Frontend side of the kickoff, pairing with the backend `task_run_created` (GROW-89).+ actions.reportContextOnboardingCloudRunQueued({ taskId: task_id, runId: run_id, repository })actions.startCloudRunSuccess()} catch (e) {const detail = e instanceof ApiError ? e.detail : null