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.

7.2 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, isBreakpoint, kea, listeners, path } from 'kea'

import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { runWhenIdle } from 'lib/utils/async'
import { teamLogic } from 'scenes/teamLogic'

import { productSetupProbes } from '~/products'

import * as api from 'products/event_definitions/frontend/generated/api'

import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'
import { productSetupStatusLogic } from './productSetupStatusLogic'
import { ProbeEventDefinition, ProductSetupProbe, statusFromProbeDefinitions } from './setupProbes'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productSetupPreloadLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    currentTeamId: number | null // teamLogic
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productSetupPreloadLogicActions {
    preloadAgainIfAsked: () => {
        value: true
    }
    preloadStatuses: () => {
        value: true
    }
}

export type productSetupPreloadLogicType = MakeLogicType<
    productSetupPreloadLogicValues,
    productSetupPreloadLogicActions
>

/**
 * Resolves every registered product's setup status as early as possible with one
 * event-definition request after the team loads and seeds
 * `productSetupStatusLogic` with the results. By the time a user first opens a
 * gated product scene, the status is usually already known, so the gate renders
 * the empty state (or the scene) directly instead of a loading spinner.
 *
 * The product's own detection logic remains the in-scene source of truth: it
 * re-checks with a fresh (uncached) query and keeps polling. The preload only
 * seeds instances still in `loading`, so it can never override a fresher answer.
 *
 * Best-effort by design: a failed run marks nothing as done, so the next trigger
 * (team load, flags arriving, idle) retries, and a probe is only skipped once it
 * has actually been seeded for the current team.
 */
export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([
    path(['lib', 'components', 'ProductEmptyState', 'productSetupPreloadLogic']),
    connect(() => ({
        values: [teamLogic, ['currentTeamId'], featureFlagLogic, ['featureFlags']],
    })),
    actions({
        preloadStatuses: true,
        preloadAgainIfAsked: true,
    }),
    listeners(({ actions, values, cache }) => ({
        preloadStatuses: async (_, breakpoint) => {
            const teamId = values.currentTeamId
            if (!teamId) {
                return
            }
            // Keyed by team AND probe: a project switch re-seeds for the new team, and a
            // flag-gated probe whose flag arrives late still gets its turn.
            const seeded: Set<string> = (cache.seeded ??= new Set())
            const probes = productSetupProbes.filter(
                (probe) =>
                    (!probe.featureFlag || values.featureFlags[probe.featureFlag]) &&
                    !seeded.has(`${teamId}:${probe.productKey}`)
            )
            if (!probes.length) {
                return
            }

            const eventNames = [
                ...new Set(probes.flatMap((probe) => [...probe.hasDataEvents, ...(probe.waitingEvents ?? [])])),
            ]

            let existingDefinitions: ProbeEventDefinition[]
            cache.requestsInFlight = (cache.requestsInFlight ?? 0) + 1
            try {
                const response = await api.eventDefinitionsList(String(teamId), {
                    names: eventNames,
                    limit: eventNames.length,
                })
                existingDefinitions = response.results.map(({ name, last_seen_at }) => ({ name, last_seen_at }))
            } catch (error) {
                if (error instanceof Error && isBreakpoint(error)) {
                    throw error
                }
                // Nothing was marked seeded, so the next trigger retries; until then the
                // in-scene detection logic answers on its own.
                actions.preloadAgainIfAsked()
                return
            } finally {
                cache.requestsInFlight -= 1
            }
            breakpoint()
            if (values.currentTeamId !== teamId) {
                return
            }

            for (const probe of probes) {
                seeded.add(`${teamId}:${probe.productKey}`)
                seedProbeStatus(probe, existingDefinitions, cache)
            }
            actions.preloadAgainIfAsked()
        },
        preloadAgainIfAsked: () => {
            if (cache.preloadAgain) {
                cache.preloadAgain = false
                actions.preloadStatuses()
            }
        },
        // Covers login and project switches that happen after mount.
        [teamLogic.actionTypes.loadCurrentTeamSuccess]: ({ currentTeam }) => {
            if (currentTeam) {
                actions.preloadStatuses()
            }
        },
        // Flags resolve asynchronously (posthog-js `onFeatureFlags`), possibly after
        // the boot triggers have already run - re-check so flag-gated probes aren't
        // silently skipped for the whole session.
        [featureFlagLogic.actionTypes.setFeatureFlags]: () => {
            // A second run would send the same request and cancel the one in flight, so it waits for that one.
            if (cache.requestsInFlight) {
                cache.preloadAgain = true
            } else {
                actions.preloadStatuses()
            }
        },
    })),
    afterMount(({ actions, cache }) => {
        // The authenticated shell mounts after the team has loaded, so the team listener has already fired.
        actions.preloadStatuses()
        // Defer to idle so boot-critical work (scene chunk, first queries) wins.
        cache.disposables.add(() => {
            // A retry for a failed mount run. A second request while one is running would cancel it.
            const run = (): void => {
                if (!cache.requestsInFlight) {
                    actions.preloadStatuses()
                }
            }
            return runWhenIdle(run)
        }, 'idle-preload')
    }),
])

function seedProbeStatus(
    probe: ProductSetupProbe,
    definitions: ProbeEventDefinition[],
    cache: Record<string, any>
): void {
    const instance = productSetupStatusLogic.build({ productKey: probe.productKey })
    if (!instance.isMounted()) {
        // Keep the instance alive for the app's lifetime so the seeded status is
        // still there when the scene finally opens. Mounting inside the disposable's
        // setup (with hidden-tab pausing off) is what keeps it alive across tab
        // switches - pausing would unmount it and silently discard the seed.
        cache.disposables.add(
            () => {
                instance.mount()
                return () => instance.unmount()
            },
            `status-${probe.productKey}`,
            { pauseOnPageHidden: false }
        )
    }
    // Seed only unknown statuses - a product logic that already answered
    // (fresh, uncached) always beats this cached approximation.
    if (instance.values.status === 'loading') {
        instance.actions.setDetectedStatus(statusFromProbeDefinitions(probe, definitions))
    }
}