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.

9.2 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, path, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'

import { teamLogic } from 'scenes/teamLogic'

import { isSharedView } from '~/exporter/exporterViewLogic'

import { tasksList, tasksRunsList } from 'products/tasks/frontend/generated/api'
import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'

export interface SetupPullRequest {
    url: string
    merged: boolean
}

/** Where the onboarding wizard's setup run is at, coarse enough for any surface to render. */
export type SetupWizardStatus =
    /** The wizard opened a pull request - surface it so the user merges it. */
    | { kind: 'pull_request'; pullRequest: SetupPullRequest }
    /** The wizard is still working on the integration and ends with a pull request. */
    | { kind: 'installing' }

const RUNNING_STATUSES = ['not_started', 'queued', 'in_progress']
const STATUS_POLL_INTERVAL_MS = 10_000
// Lost access or a deleted resource does not recover on retry, unlike a network or server error.
const PERMANENT_ERROR_STATUSES = [401, 403, 404]

const byCreatedAtDesc = (a: { created_at?: string | null }, b: { created_at?: string | null }): number =>
    (b.created_at ?? '').localeCompare(a.created_at ?? '')

type LatestRunDetail = Pick<TaskRunDetailDTOApi, 'id' | 'status' | 'output' | 'created_at'>

/**
 * The tasks list endpoint nests the full run detail in `latest_run`, but the generated type
 * collapses it to the bare run id (OpenAPI schema-name collision with the conversation envelope
 * variant), so the nested shape has to be recovered with a cast.
 */
function asLatestRunDetail(latestRun: unknown): Partial<LatestRunDetail> | null {
    return latestRun && typeof latestRun === 'object' ? (latestRun as Partial<LatestRunDetail>) : null
}

export function pullRequestFromRunOutput(output: Record<string, unknown> | null | undefined): SetupPullRequest | null {
    const url = output?.pr_url
    if (typeof url !== 'string' || !url) {
        return null
    }
    return { url, merged: output?.pr_merged === true }
}

export function isRunRunning(run: Partial<LatestRunDetail> | null): boolean {
    return typeof run?.status === 'string' && RUNNING_STATUSES.includes(run.status)
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface setupWizardStatusLogicValues {
    currentTeamId: number | null // teamLogic
    discoveredRun: SetupWizardStatus | null
    discoveredRunLoading: boolean
    setupStatus: SetupWizardStatus | null
    setupStatusLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface setupWizardStatusLogicActions {
    loadDiscoveredRun: () => any
    loadDiscoveredRunFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadDiscoveredRunSuccess: (
        discoveredRun: SetupWizardStatus | null,
        payload?: any
    ) => {
        discoveredRun: SetupWizardStatus | null
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface setupWizardStatusLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        setupStatus: (discoveredRun: SetupWizardStatus | null) => SetupWizardStatus | null
        setupStatusLoading: (discoveredRunLoading: boolean) => boolean
    }
}

export type setupWizardStatusLogicType = MakeLogicType<
    setupWizardStatusLogicValues,
    setupWizardStatusLogicActions,
    Record<string, any>,
    setupWizardStatusLogicMeta
>

/**
 * Status of the onboarding wizard's setup task run (the cloud run that installs PostHog in the
 * user's codebase and opens a pull request). It finds the newest onboarding task through the tasks
 * API, so runs started elsewhere (another browser, a server-side drop flow) are found too, and it is
 * the only source that knows whether the PR got merged.
 *
 * Mount it from surfaces that actually need setup state rather than app-wide (INC-886).
 */
export const setupWizardStatusLogic = kea<setupWizardStatusLogicType>([
    path(['scenes', 'onboarding', 'shared', 'setupWizardStatusLogic']),
    connect(() => ({
        values: [teamLogic, ['currentTeamId']],
    })),
    loaders(({ values }) => ({
        discoveredRun: [
            null as SetupWizardStatus | null,
            {
                loadDiscoveredRun: async (): Promise<SetupWizardStatus | null> => {
                    // The onboarding wizard is meaningless to a logged-out viewer, and the tasks API
                    // it hits is team-scoped, so it 403s in a shared/exported view. Skip it entirely.
                    if (isSharedView()) {
                        return null
                    }
                    // Mounted before the team loaded: the currentTeamId subscription below retries
                    if (values.currentTeamId === null) {
                        return null
                    }
                    try {
                        const projectId = String(values.currentTeamId)
                        const tasks = await tasksList(projectId, { origin_product: 'onboarding', limit: 10 })
                        const newestFirst = [...tasks.results].sort(byCreatedAtDesc)
                        for (const task of newestFirst) {
                            const run = asLatestRunDetail(task.latest_run)
                            const pullRequest = pullRequestFromRunOutput(run?.output)
                            if (pullRequest) {
                                return { kind: 'pull_request', pullRequest }
                            }
                        }
                        // Fallback for when `latest_run` really is a bare run id: check the newest task's runs
                        const newestTask = newestFirst[0]
                        if (newestTask && typeof newestTask.latest_run === 'string') {
                            const runs = await tasksRunsList(projectId, newestTask.id)
                            const runsNewestFirst = [...runs.results].sort(byCreatedAtDesc)
                            for (const run of runsNewestFirst) {
                                const pullRequest = pullRequestFromRunOutput(run.output)
                                if (pullRequest) {
                                    return { kind: 'pull_request', pullRequest }
                                }
                            }
                            if (runsNewestFirst.some((run) => isRunRunning(run))) {
                                return { kind: 'installing' }
                            }
                        }
                        // No PR anywhere: the wizard may still be working on it
                        for (const task of newestFirst) {
                            const run = asLatestRunDetail(task.latest_run)
                            if (isRunRunning(run)) {
                                return { kind: 'installing' }
                            }
                        }
                        return null
                    } catch (error) {
                        // A null status stops the poll, so permanent errors clear it. Transient
                        // errors keep the last status so the poll continues.
                        const status = (error as { status?: unknown } | null)?.status
                        if (typeof status === 'number' && PERMANENT_ERROR_STATUSES.includes(status)) {
                            return null
                        }
                        return values.discoveredRun
                    }
                },
            },
        ],
    })),
    selectors({
        setupStatus: [
            (s) => [s.discoveredRun],
            (discoveredRun: SetupWizardStatus | null): SetupWizardStatus | null => discoveredRun,
        ],
        setupStatusLoading: [
            (s) => [s.discoveredRunLoading],
            (discoveredRunLoading: boolean): boolean => discoveredRunLoading,
        ],
    }),
    subscriptions(({ actions }) => ({
        // The afterMount load no-ops when the logic mounts before the team is known; (re)load once
        // the team id arrives or changes. kea-subscriptions' initial mount call (prev undefined) is
        // skipped since afterMount already covers it.
        currentTeamId: (teamId: number | null, prevTeamId: number | null | undefined) => {
            if (prevTeamId !== undefined && teamId !== prevTeamId) {
                actions.loadDiscoveredRunSuccess(null)
                if (teamId !== null) {
                    actions.loadDiscoveredRun()
                }
            }
        },
    })),
    afterMount(({ actions, cache, values }) => {
        actions.loadDiscoveredRun()
        cache.disposables.add(() => {
            const timer = window.setInterval(() => {
                const status = values.setupStatus
                if (
                    !values.discoveredRunLoading &&
                    status &&
                    (status.kind === 'installing' || !status.pullRequest.merged)
                ) {
                    actions.loadDiscoveredRun()
                }
            }, STATUS_POLL_INTERVAL_MS)
            return () => window.clearInterval(timer)
        }, 'setup-status-poll')
    }),
])