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.

feat(wizard): add telemetry for setup wizard sync sessions (#63097)

Fernando Gomes6d94683547f0
diff --git a/frontend/src/lib/utils/datetime.ts b/frontend/src/lib/utils/datetime.ts
index 394a37a02a43..e262c8fbb76d 100644
--- a/frontend/src/lib/utils/datetime.ts
+++ b/frontend/src/lib/utils/datetime.ts
@@ -286,3 +286,14 @@ export function parseDateInTimezone(dateStr: string, timezone: string): dayjs.Da
return dayjs(null)
}
}
+
+/** Whole seconds elapsed from an ISO start timestamp to a reference `now` (ms epoch).
+ * Returns 0 for an unparseable start or a `now` that precedes it, so callers never
+ * surface a negative or NaN duration. */
+export function elapsedSecondsFrom(startedAt: string, now: number): number {
+ const started = new Date(startedAt).getTime()
+ if (Number.isNaN(started)) {
+ return 0
+ }
+ return Math.max(0, Math.floor((now - started) / 1000))
+}
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 31dc0fe2102d..13f69be5d6b0 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -983,6 +983,34 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
reportBillingUsageInteraction: (properties: BillingUsageInteractionProps) => ({ properties }),
reportBillingSpendInteraction: (properties: BillingUsageInteractionProps) => ({ properties }),
reportSDKSelected: (sdk: SDK) => ({ sdk }),
+ // Setup wizard sync (CLI ↔ app) funnel. Fired from the onboarding install step's
+ // progress tracker; guards for "once per session" live in that logic.
+ reportWizardSyncSessionDetected: (props: {
+ workflowId: string
+ skillId: string
+ runPhase: string
+ taskCount: number
+ }) => props,
+ reportWizardSyncSessionFinished: (props: {
+ workflowId: string
+ skillId: string
+ outcome: string
+ taskCount: number
+ completedTaskCount: number
+ elapsedSeconds: number
+ }) => props,
+ reportWizardSyncDismissed: (props: {
+ workflowId: string
+ skillId?: string
+ outcome: string
+ elapsedSeconds: number
+ }) => props,
+ reportWizardSyncProgressExpanded: (props: {
+ workflowId?: string
+ skillId?: string
+ displayState: string
+ progressPct: number
+ }) => props,
reportAccountOwnerClicked: ({ name, email }: { name: string; email: string }) => ({ name, email }),
// revenue analytics
reportRevenueAnalyticsViewed: (delay?: number) => ({ delay }),
@@ -2301,6 +2329,47 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
sdk: sdk.key,
})
},
+ reportWizardSyncSessionDetected: ({ workflowId, skillId, runPhase, taskCount }) => {
+ posthog.capture('setup wizard sync session detected', {
+ workflow_id: workflowId,
+ skill_id: skillId,
+ run_phase: runPhase,
+ task_count: taskCount,
+ })
+ },
+ reportWizardSyncSessionFinished: ({
+ workflowId,
+ skillId,
+ outcome,
+ taskCount,
+ completedTaskCount,
+ elapsedSeconds,
+ }) => {
+ posthog.capture('setup wizard sync session finished', {
+ workflow_id: workflowId,
+ skill_id: skillId,
+ outcome,
+ task_count: taskCount,
+ completed_task_count: completedTaskCount,
+ elapsed_seconds: elapsedSeconds,
+ })
+ },
+ reportWizardSyncDismissed: ({ workflowId, skillId, outcome, elapsedSeconds }) => {
+ posthog.capture('setup wizard sync dismissed', {
+ workflow_id: workflowId,
+ skill_id: skillId,
+ outcome,
+ elapsed_seconds: elapsedSeconds,
+ })
+ },
+ reportWizardSyncProgressExpanded: ({ workflowId, skillId, displayState, progressPct }) => {
+ posthog.capture('setup wizard sync progress expanded', {
+ workflow_id: workflowId,
+ skill_id: skillId,
+ display_state: displayState,
+ progress_pct: progressPct,
+ })
+ },
// command bar
reportCommandBarStatusChanged: ({ status }) => {
posthog.capture('command bar status changed', { status })
diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardProgressFab/index.tsx b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardProgressFab/index.tsx
index bf0891b8802b..e74580429565 100644
--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardProgressFab/index.tsx
+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardProgressFab/index.tsx
@@ -6,6 +6,7 @@ import { useState } from 'react'
import { IconChevronDown, IconX } from '@posthog/icons'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { wizardActiveSessionDetectorLogic } from '../wizardActiveSessionDetectorLogic'
import { wizardProgressTrackerLogic } from '../wizardProgressTrackerLogic'
@@ -45,6 +46,7 @@ function WizardProgressFabInner(): JSX.Element | null {
now,
} = useValues(wizardProgressTrackerLogic)
const { dismiss } = useActions(wizardProgressTrackerLogic)
+ const { reportWizardSyncProgressExpanded } = useActions(eventUsageLogic)
const [expanded, setExpanded] = useState(false)
@@ -72,7 +74,20 @@ function WizardProgressFabInner(): JSX.Element | null {
>
<button
type="button"
- onClick={() => setExpanded((v) => !v)}
+ onClick={() => {
+ const next = !expanded
+ setExpanded(next)
+ // Only the expand direction is an intentful "show me the details"
+ // signal worth tracking; collapsing is just tidying up.
+ if (next) {
+ reportWizardSyncProgressExpanded({
+ workflowId: latestSession?.workflow_id,
+ skillId: latestSession?.skill_id,
+ displayState,
+ progressPct,
+ })
+ }
+ }}
className="w-full text-left flex items-center gap-3 px-3 py-3 hover:bg-bg-3000 transition-colors cursor-pointer"
aria-label={expanded ? 'Collapse wizard details' : 'Expand wizard details'}
aria-expanded={expanded}
diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardProgressTrackerLogic.test.ts b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardProgressTrackerLogic.test.ts
index 1a16600e40ab..1dd23ea44aff 100644
--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardProgressTrackerLogic.test.ts
+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardProgressTrackerLogic.test.ts
@@ -1,4 +1,5 @@
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { initKeaTests } from '~/test/init'
@@ -6,7 +7,7 @@ import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api
import { wizardSessionStreamLogic } from 'products/wizard/frontend/wizardSessionStreamLogic'
import { wizardActiveSessionDetectorLogic } from './wizardActiveSessionDetectorLogic'
-import { wizardProgressTrackerLogic } from './wizardProgressTrackerLogic'
+import { resetWizardSyncTelemetryForTests, wizardProgressTrackerLogic } from './wizardProgressTrackerLogic'
// The detector polls a REST endpoint from afterMount and the stream logic builds an SSE
// URL on connect; stub both so mounting the tracker (which connects them) never hits the
@@ -60,12 +61,17 @@ describe('wizardProgressTrackerLogic', () => {
beforeEach(() => {
initKeaTests()
+ ;(posthog.capture as jest.Mock).mockClear()
+ resetWizardSyncTelemetryForTests()
streamLogic = wizardSessionStreamLogic({ workflowId: WORKFLOW_ID })
detector = wizardActiveSessionDetectorLogic()
logic = wizardProgressTrackerLogic()
logic.mount()
})
+ const capturedEvents = (name: string): any[][] =>
+ (posthog.capture as jest.Mock).mock.calls.filter((call) => call[0] === name)
+
afterEach(() => {
logic?.unmount()
})
@@ -107,4 +113,115 @@ describe('wizardProgressTrackerLogic', () => {
}).toNotHaveDispatchedActions(['markActive'])
await expectLogic(detector).toMatchValues({ hasActiveSession: false, shouldStream: false })
})
+
+ it('captures "session detected" once per session_id for a fresh session', async () => {
+ streamLogic.actions.sessionUpdated(makeSession({ run_phase: 'running' }))
+ await expectLogic(logic).toMatchValues({ sessionIsCurrent: true })
+
+ expect(posthog.capture).toHaveBeenCalledWith('setup wizard sync session detected', {
+ workflow_id: WORKFLOW_ID,
+ skill_id: 'nextjs',
+ run_phase: 'running',
+ task_count: 0,
+ })
+
+ // A later update for the same session must not re-fire the reach metric.
+ streamLogic.actions.sessionUpdated(makeSession({ run_phase: 'running' }))
+ expect(capturedEvents('setup wizard sync session detected')).toHaveLength(1)
+ })
+
+ it('does not re-fire "session detected" after a full unmount/remount of the same session', async () => {
+ const session = makeSession({ session_id: 'sess-remount', run_phase: 'running' })
+ streamLogic.actions.sessionUpdated(session)
+ await expectLogic(logic).toMatchValues({ sessionIsCurrent: true })
+ expect(capturedEvents('setup wizard sync session detected')).toHaveLength(1)
+
+ // A remount wipes the kea cache; the module-level guard must still suppress the
+ // re-delivered (still in-flight) session so reach isn't double-counted.
+ logic.unmount()
+ logic = wizardProgressTrackerLogic()
+ logic.mount()
+ streamLogic.actions.sessionUpdated(makeSession({ session_id: 'sess-remount', run_phase: 'running' }))
+
+ expect(capturedEvents('setup wizard sync session detected')).toHaveLength(1)
+ })
+
+ it('does not capture "session detected" for a stale session', async () => {
+ const stale = makeSession({
+ run_phase: 'completed',
+ updated_at: new Date(Date.now() - 20 * 60 * 1000).toISOString(),
+ })
+ streamLogic.actions.sessionUpdated(stale)
+ expect(capturedEvents('setup wizard sync session detected')).toHaveLength(0)
+ })
+
+ it.each(['completed', 'error'] as const)(
+ 'captures "session finished" once when a running session transitions to %s',
+ async (outcome) => {
+ streamLogic.actions.sessionUpdated(
+ makeSession({
+ run_phase: 'running',
+ tasks: [
+ { id: 't1', title: 'Install SDK', status: 'completed' },
+ { id: 't2', title: 'Capture events', status: 'in_progress' },
+ ],
+ })
+ )
+ streamLogic.actions.sessionUpdated(
+ makeSession({
+ run_phase: outcome,
+ tasks: [
+ { id: 't1', title: 'Install SDK', status: 'completed' },
+ { id: 't2', title: 'Capture events', status: 'completed' },
+ ],
+ })
+ )
+
+ expect(posthog.capture).toHaveBeenCalledWith('setup wizard sync session finished', {
+ workflow_id: WORKFLOW_ID,
+ skill_id: 'nextjs',
+ outcome,
+ task_count: 2,
+ completed_task_count: 2,
+ elapsed_seconds: expect.any(Number),
+ })
+
+ // Re-delivering the terminal state must not double-count the outcome.
+ streamLogic.actions.sessionUpdated(makeSession({ run_phase: outcome }))
+ expect(capturedEvents('setup wizard sync session finished')).toHaveLength(1)
+ }
+ )
+
+ it('captures "session dismissed" with the terminal outcome', async () => {
+ streamLogic.actions.sessionUpdated(makeSession({ run_phase: 'completed' }))
+ ;(posthog.capture as jest.Mock).mockClear()
+
+ logic.actions.dismiss()
+
+ expect(posthog.capture).toHaveBeenCalledWith('setup wizard sync dismissed', {
+ workflow_id: WORKFLOW_ID,
+ skill_id: 'nextjs',
+ outcome: 'completed',
+ elapsed_seconds: expect.any(Number),
+ })
+ })
+
+ it('captures "session dismissed" only once when dismiss fires twice', async () => {
+ streamLogic.actions.sessionUpdated(makeSession({ run_phase: 'completed' }))
+ ;(posthog.capture as jest.Mock).mockClear()
+
+ logic.actions.dismiss()
+ logic.actions.dismiss()
+
+ expect(capturedEvents('setup wizard sync dismissed')).toHaveLength(1)
+ })
+
+ it('does not capture "session dismissed" when there is no current session', async () => {
+ // No session_id means the once-per-session guard can't hold, so the listener
+ // must bail rather than fire an unguarded event on every dispatch.
+ logic.actions.dismiss()
+ logic.actions.dismiss()
+
+ expect(capturedEvents('setup wizard sync dismissed')).toHaveLength(0)
+ })
})
diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardProgressTrackerLogic.ts b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardProgressTrackerLogic.ts
index 6a29dd6af69e..71513928d958 100644
--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardProgressTrackerLogic.ts
+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardProgressTrackerLogic.ts
@@ -1,6 +1,9 @@
-import { actions, afterMount, beforeUnmount, connect, kea, path, reducers, selectors } from 'kea'
+import { actions, afterMount, beforeUnmount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { subscriptions } from 'kea-subscriptions'
+import { elapsedSecondsFrom } from 'lib/utils/datetime'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+
import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'
import { wizardSessionStreamLogic } from 'products/wizard/frontend/wizardSessionStreamLogic'
@@ -34,6 +37,24 @@ const SESSION_CURRENT_THRESHOLD_MS = 10 * 60 * 1000
const WORKFLOW_ID = 'posthog-integration'
+// Per-session telemetry guards, deliberately module-scoped rather than on the kea
+// `cache`. The tracker logic unmounts whenever the FAB's `shouldStream` flips false
+// and the install step isn't mounted, and a remount wipes `cache` — so a cache-based
+// guard would let the SSE redeliver a still-in-flight session and re-fire these
+// events. Keying by session_id at module scope makes "once per session" hold across
+// remounts for the whole page load. (A hard reload starts a fresh page session; the
+// reach funnel is read on unique users, so that boundary is acceptable.)
+const reportedDetectedSessions = new Set<string>()
+const reportedFinishedSessions = new Set<string>()
+const reportedDismissedSessions = new Set<string>()
+
+// Test-only: clear the module-level guards so each case starts from a clean slate.
+export function resetWizardSyncTelemetryForTests(): void {
+ reportedDetectedSessions.clear()
+ reportedFinishedSessions.clear()
+ reportedDismissedSessions.clear()
+}
+
function runPhaseMessage(phase: string): string {
if (phase === 'completed') {
return 'wizard finished'
@@ -84,6 +105,8 @@ export const wizardProgressTrackerLogic = kea<wizardProgressTrackerLogicType>([
['connect', 'disconnect'],
wizardActiveSessionDetectorLogic,
['markActive', 'scheduleMarkInactive'],
+ eventUsageLogic,
+ ['reportWizardSyncSessionDetected', 'reportWizardSyncSessionFinished', 'reportWizardSyncDismissed'],
],
})),
actions({
@@ -168,16 +191,7 @@ export const wizardProgressTrackerLogic = kea<wizardProgressTrackerLogicType>([
],
elapsedSeconds: [
(s) => [s.latestSession, s.now],
- (latestSession, now): number => {
- if (!latestSession) {
- return 0
- }
- const startedAt = new Date(latestSession.started_at).getTime()
- if (Number.isNaN(startedAt)) {
- return 0
- }
- return Math.max(0, Math.floor((now - startedAt) / 1000))
- },
+ (latestSession, now): number => (latestSession ? elapsedSecondsFrom(latestSession.started_at, now) : 0),
],
}),
subscriptions(({ actions }) => ({
@@ -206,6 +220,18 @@ export const wizardProgressTrackerLogic = kea<wizardProgressTrackerLogicType>([
const isFresh = !Number.isNaN(updatedAt) && now - updatedAt < SESSION_CURRENT_THRESHOLD_MS
if (isFresh) {
actions.markSessionCurrent()
+ // Reach metric: count each live wizard session the sync surfaces, once per
+ // session_id. Gated on freshness so stale terminal rows sitting in the DB —
+ // which never reach the user — don't inflate the funnel.
+ if (!reportedDetectedSessions.has(session.session_id)) {
+ reportedDetectedSessions.add(session.session_id)
+ actions.reportWizardSyncSessionDetected({
+ workflowId: WORKFLOW_ID,
+ skillId: session.skill_id,
+ runPhase: session.run_phase,
+ taskCount: session.tasks.length,
+ })
+ }
}
// Keep the global detector in sync so the FAB survives a navigation
// away from the install step. Gate on the detector's shared
@@ -235,6 +261,21 @@ export const wizardProgressTrackerLogic = kea<wizardProgressTrackerLogicType>([
}
if (session.run_phase !== prev.run_phase) {
actions.appendActivity(runPhaseMessage(session.run_phase))
+ const isTerminal = session.run_phase === 'completed' || session.run_phase === 'error'
+ // Outcome metric: fire once when a run the user watched live reaches a
+ // terminal phase. Terminal phases are sticky, so this transition is observed
+ // at most once per session — the id guard covers any SSE redelivery.
+ if (isTerminal && !reportedFinishedSessions.has(session.session_id)) {
+ reportedFinishedSessions.add(session.session_id)
+ actions.reportWizardSyncSessionFinished({
+ workflowId: WORKFLOW_ID,
+ skillId: session.skill_id,
+ outcome: session.run_phase,
+ taskCount: session.tasks.length,
+ completedTaskCount: session.tasks.filter((t) => t.status === 'completed').length,
+ elapsedSeconds: elapsedSecondsFrom(session.started_at, now),
+ })
+ }
}
const prevTaskKeys = new Set(prev.tasks.map((t) => `${t.id}::${t.status}`))
for (const task of session.tasks) {
@@ -248,6 +289,29 @@ export const wizardProgressTrackerLogic = kea<wizardProgressTrackerLogicType>([
}
},
})),
+ listeners(({ values, actions }) => ({
+ dismiss: () => {
+ const sessionId = values.latestSession?.session_id
+ // No session means nothing to attribute the dismissal to, and without a
+ // session_id the once-per-session guard can't hold — bail rather than fire
+ // an unguarded event on every dispatch.
+ if (!sessionId) {
+ return
+ }
+ // Guard against a double-click landing two `dismiss` dispatches before the
+ // FAB re-renders itself away: capture at most once per session.
+ if (reportedDismissedSessions.has(sessionId)) {
+ return
+ }
+ reportedDismissedSessions.add(sessionId)
+ actions.reportWizardSyncDismissed({
+ workflowId: WORKFLOW_ID,
+ skillId: values.latestSession?.skill_id,
+ outcome: values.displayState,
+ elapsedSeconds: values.elapsedSeconds,
+ })
+ },
+ })),
afterMount(({ actions, cache, values }) => {
actions.connect()
actions.appendActivity('opening wizard session stream…')