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.

11.9 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import posthog from 'posthog-js'
import { v4 as uuid } from 'uuid'

import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'

import type { ProductKey } from '~/queries/schema/schema-general'
import type { TeamType } from '~/types'

import type { TeamPublicType } from '../../../types'
import type { ProductEmptyStateMode, ProductSetupStatus } from './types'

export interface ProductSetupStatusLogicProps {
    productKey: ProductKey
}

interface DetectedStatus {
    status: ProductSetupStatus
    teamId: number | null
}

export type ProductSetupRoute = 'wizard' | 'agent' | 'manual'

interface SetupAttempt {
    id: string
    initialRoute: ProductSetupRoute | null
    route: ProductSetupRoute | null
    completed: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productSetupStatusLogicValues {
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    currentTeamId: number | null // teamLogic
    detected: DetectedStatus
    mode: ProductEmptyStateMode
    setupAttempt: SetupAttempt | null
    setupAttemptsByProject: Record<string, SetupAttempt>
    setupProjectKey: string | null
    skipped: boolean
    skippedByTeam: Record<number, boolean>
    status: ProductSetupStatus
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productSetupStatusLogicActions {
    applyDetectedStatus: (
        status: ProductSetupStatus,
        teamId: number | null
    ) => {
        status: ProductSetupStatus
        teamId: number | null
    }
    reportSetupInteraction: (
        action: string,
        mode: ProductEmptyStateMode,
        route?: ProductSetupRoute | null,
        preview?: boolean,
        wizardSession?: {
            phase: string
            session_id: string
        }
    ) => {
        action: string
        mode: ProductEmptyStateMode
        preview: boolean
        route: ProductSetupRoute | null
        wizardSession:
            | {
                  phase: string
                  session_id: string
              }
            | undefined
    }
    reportSetupShown: (
        mode: ProductEmptyStateMode,
        preview?: boolean
    ) => {
        mode: ProductEmptyStateMode
        preview: boolean
    }
    setDetectedStatus: (status: ProductSetupStatus) => {
        status: ProductSetupStatus
    }
    setSetupAttempt: (
        projectKey: string,
        attempt: SetupAttempt
    ) => {
        attempt: SetupAttempt
        projectKey: string
    }
    setSkippedForTeam: (
        teamId: number,
        skipped: boolean
    ) => {
        skipped: boolean
        teamId: number
    }
    skipEmptyState: () => {
        value: true
    }
    unskipEmptyState: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productSetupStatusLogicMeta {
    key: ProductKey
    __keaTypeGenInternalSelectorTypes: {
        setupProjectKey: (currentTeam: TeamPublicType | TeamType | null) => string | null
        setupAttempt: (
            setupAttemptsByProject: Record<string, SetupAttempt>,
            setupProjectKey: string | null
        ) => SetupAttempt | null
        status: (detected: DetectedStatus, currentTeamId: number | null) => ProductSetupStatus
        skipped: (skippedByTeam: Record<number, boolean>, currentTeamId: number | null) => boolean
        mode: (status: ProductSetupStatus) => ProductEmptyStateMode
    }
}

export type productSetupStatusLogicType = MakeLogicType<
    productSetupStatusLogicValues,
    productSetupStatusLogicActions,
    ProductSetupStatusLogicProps,
    productSetupStatusLogicMeta
>

/**
 * The single read point for "is product X set up?".
 *
 * Detection stays with each product (they know their own events/APIs), but every
 * product pushes its normalized `ProductSetupStatus` here via `setDetectedStatus`,
 * so any surface — the scene-level empty-state gate, nav, activation — can ask one
 * place instead of reaching into per-product logics.
 *
 * Detection must be a real signal: data existence (HogQL count / exists API), the
 * product's opt-in flag, or entity count for creation-first products. Never a
 * dismissal flag — `has_completed_onboarding_for` is routing metadata, not evidence
 * of data.
 *
 * Skip is local-only (per browser, keyed by team): it bypasses the empty-state
 * screen without writing anything to the backend, and detection keeps running so
 * the real product appears as soon as data lands.
 */
export const productSetupStatusLogic = kea<productSetupStatusLogicType>([
    props({} as ProductSetupStatusLogicProps),
    key((props) => {
        if (!props.productKey) {
            throw new Error('productSetupStatusLogic must be initialized with a productKey')
        }
        return props.productKey
    }),
    path((key) => ['lib', 'components', 'ProductEmptyState', 'productSetupStatusLogic', key]),
    connect(() => ({ values: [teamLogic, ['currentTeamId', 'currentTeam']] })),
    actions({
        setDetectedStatus: (status: ProductSetupStatus) => ({ status }),
        applyDetectedStatus: (status: ProductSetupStatus, teamId: number | null) => ({ status, teamId }),
        skipEmptyState: true,
        unskipEmptyState: true,
        setSkippedForTeam: (teamId: number, skipped: boolean) => ({ teamId, skipped }),
        setSetupAttempt: (projectKey: string, attempt: SetupAttempt) => ({ projectKey, attempt }),
        reportSetupShown: (mode: ProductEmptyStateMode, preview: boolean = false) => ({ mode, preview }),
        reportSetupInteraction: (
            action: string,
            mode: ProductEmptyStateMode,
            route: ProductSetupRoute | null = null,
            preview: boolean = false,
            wizardSession?: { session_id: string; phase: string }
        ) => ({ action, mode, route, preview, wizardSession }),
    }),
    reducers({
        setupAttemptsByProject: [
            {} as Record<string, SetupAttempt>,
            { persist: true },
            { setSetupAttempt: (state, { projectKey, attempt }) => ({ ...state, [projectKey]: attempt }) },
        ],
        // Stamped with the team the detection ran against, so a stale answer is
        // never served across a project switch (see the `status` selector).
        detected: [
            { status: 'loading', teamId: null } as DetectedStatus,
            {
                applyDetectedStatus: (_, { status, teamId }) => ({ status, teamId }),
            },
        ],
        // Keyed by team so switching projects never leaks a skip across tenants.
        skippedByTeam: [
            {} as Record<number, boolean>,
            { persist: true },
            {
                setSkippedForTeam: (state, { teamId, skipped }) => ({ ...state, [teamId]: skipped }),
            },
        ],
    }),
    selectors({
        setupProjectKey: [(s) => [s.currentTeam], (team: TeamType | null): string | null => team?.uuid ?? null],
        setupAttempt: [
            (s) => [s.setupAttemptsByProject, s.setupProjectKey],
            (attempts: Record<string, SetupAttempt>, projectKey: string | null): SetupAttempt | null =>
                projectKey ? (attempts[projectKey] ?? null) : null,
        ],
        // A detected status only counts for the team it was detected for; after a
        // project switch we're back to `loading` until a detection (or the preload)
        // answers for the new team.
        status: [
            (s) => [s.detected, s.currentTeamId],
            (detected: DetectedStatus, currentTeamId: number | null): ProductSetupStatus =>
                detected.teamId === currentTeamId ? detected.status : 'loading',
        ],
        skipped: [
            (s) => [s.skippedByTeam, s.currentTeamId],
            (skippedByTeam: Record<number, boolean>, currentTeamId: number | null): boolean =>
                !!(currentTeamId && skippedByTeam[currentTeamId]),
        ],
        mode: [
            (s) => [s.status],
            (status: ProductSetupStatus): ProductEmptyStateMode =>
                status === 'waiting-for-data' ? 'waiting-for-data' : 'needs-setup',
        ],
    }),
    listeners(({ actions, values, props }) => ({
        reportSetupShown: ({ mode, preview }) => {
            actions.reportSetupInteraction('shown', mode, null, preview)
        },
        reportSetupInteraction: ({ action, mode, route, preview, wizardSession }) => {
            if (
                preview ||
                !values.setupProjectKey ||
                !values.currentTeamId ||
                userLogic.findMounted()?.values.user?.is_impersonated
            ) {
                return
            }
            const attempt = values.setupAttempt ?? { id: uuid(), initialRoute: null, route: null, completed: false }
            const updated = { ...attempt, initialRoute: attempt.initialRoute ?? route, route: route ?? attempt.route }
            actions.setSetupAttempt(values.setupProjectKey, updated)
            posthog.capture(`product empty state ${action}`, {
                product_key: props.productKey,
                project_id: values.currentTeamId,
                project_uuid: values.setupProjectKey,
                mode,
                setup_attempt_id: updated.id,
                initial_setup_route: updated.initialRoute,
                setup_route: updated.route,
                ...(wizardSession
                    ? { wizard_session_id: wizardSession.session_id, wizard_phase: wizardSession.phase }
                    : {}),
            })
        },
        applyDetectedStatus: ({ status, teamId }) => {
            const attempt = values.setupAttempt
            if (
                status === 'has-data' &&
                teamId &&
                teamId === values.currentTeamId &&
                values.setupProjectKey &&
                attempt &&
                !attempt.completed &&
                !userLogic.findMounted()?.values.user?.is_impersonated
            ) {
                actions.setSetupAttempt(values.setupProjectKey, { ...attempt, completed: true })
                posthog.capture('product empty state data detected', {
                    product_key: props.productKey,
                    project_id: teamId,
                    project_uuid: values.setupProjectKey,
                    setup_attempt_id: attempt.id,
                    initial_setup_route: attempt.initialRoute,
                    setup_route: attempt.route,
                })
            }
        },
        setDetectedStatus: ({ status }) => {
            // Detection answers more than once per session: several products poll while their
            // scene is mounted. Once a status has put the real scene on screen, a later
            // `needs-setup` must not replace it, because that swaps a mounted scene for the
            // setup screen under the user, losing whatever they had typed into it, and a
            // product with `skippable: false` leaves no way back. `unknown` means detection
            // failed and we deliberately failed open; `has-data` means real data was seen.
            // A project switch resets `status` to `loading`, so the new team can still land on
            // `needs-setup`, and `waiting-for-data` stays free to move either way.
            if (status === 'needs-setup' && (values.status === 'unknown' || values.status === 'has-data')) {
                return
            }
            actions.applyDetectedStatus(status, values.currentTeamId)
        },
        skipEmptyState: () => {
            posthog.capture('product empty state skipped', { product_key: props.productKey })
            if (values.currentTeamId) {
                actions.setSkippedForTeam(values.currentTeamId, true)
            }
        },
        unskipEmptyState: () => {
            posthog.capture('product empty state setup resumed', { product_key: props.productKey })
            if (values.currentTeamId) {
                actions.setSkippedForTeam(values.currentTeamId, false)
            }
        },
    })),
])