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.

4.1 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'
import { loaders } from 'kea-loaders'

import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
import type { ProductSetupStatus } from 'lib/components/ProductEmptyState/types'
import { teamLogic } from 'scenes/teamLogic'

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

import { visionScannersStatsRetrieve } from './generated/api'
import type { ScannerStatsResponseApi } from './generated/api.schemas'

// The wizard's self-driving run creates scanners from the terminal, so keep polling
// while the empty state is up and flip to the real scene as soon as one lands.
const POLL_INTERVAL_MS = 20000

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface replayVisionSetupLogicValues {
    setupStatus: ProductSetupStatus // productSetupStatusLogic
    setupStats: ScannerStatsResponseApi | null
    setupStatsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface replayVisionSetupLogicActions {
    setDetectedStatus: (status: ProductSetupStatus) => {
        status: ProductSetupStatus
    } // productSetupStatusLogic
    loadSetupStats: (_: void) => void
    loadSetupStatsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSetupStatsSuccess: (
        setupStats: ScannerStatsResponseApi,
        payload?: void
    ) => {
        setupStats: ScannerStatsResponseApi
        payload?: void
    }
}

export type replayVisionSetupLogicType = MakeLogicType<replayVisionSetupLogicValues, replayVisionSetupLogicActions>

/**
 * Setup detection for the Replay vision empty-state gate: a scanner is the unit of
 * setup, so any scanner on the team means the product is in use. Pushes the
 * normalized status into `productSetupStatusLogic({ productKey: REPLAY_VISION })`.
 */
export const replayVisionSetupLogic = kea<replayVisionSetupLogicType>([
    path(['products', 'replay_vision', 'frontend', 'replayVisionSetupLogic']),
    connect(() => ({
        actions: [productSetupStatusLogic({ productKey: ProductKey.REPLAY_VISION }), ['setDetectedStatus']],
        values: [productSetupStatusLogic({ productKey: ProductKey.REPLAY_VISION }), ['status as setupStatus']],
    })),
    loaders({
        setupStats: {
            __default: null as ScannerStatsResponseApi | null,
            loadSetupStats: async (_: void, breakpoint): Promise<ScannerStatsResponseApi> => {
                const teamId = teamLogic.values.currentTeamId
                if (!teamId) {
                    // Routed to loadSetupStatsFailure, which fails open like any other unanswerable probe.
                    throw new Error('no current team')
                }
                const response = await visionScannersStatsRetrieve(String(teamId))
                breakpoint()
                return response
            },
        },
    }),
    listeners(({ actions, values, cache }) => ({
        loadSetupStatsSuccess: ({ setupStats }) => {
            const detected = setupStats && setupStats.total > 0 ? 'has-data' : 'needs-setup'
            // Poll ticks mostly re-detect the same status; don't re-render the gate subtree for those.
            if (detected !== values.setupStatus) {
                actions.setDetectedStatus(detected)
            }
            if (detected === 'has-data') {
                cache.disposables.dispose('poll')
            }
        },
        loadSetupStatsFailure: () => {
            // Never strand the gate on its spinner: if nothing has answered yet, fail
            // open to the real scene. Don't downgrade an existing answer on a poll blip.
            if (values.setupStatus === 'loading') {
                actions.setDetectedStatus('unknown')
            }
        },
    })),
    afterMount(({ actions, cache }) => {
        actions.loadSetupStats()
        cache.disposables.add(() => {
            const id = window.setInterval(() => actions.loadSetupStats(), POLL_INTERVAL_MS)
            return () => clearInterval(id)
        }, 'poll')
    }),
])