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, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, urlToAction } from 'kea-router'

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

import { stamphogRepoConfigsList, stamphogReviewRunsList } from '../../generated/api'
import type {
    PaginatedReviewRunListApi,
    ReviewRunApi,
    StamphogRepoConfigApi,
    StamphogReviewRunsListTrigger,
} from '../../generated/api.schemas'

export const RUNS_PAGE_SIZE = 50

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface stamphogRunsSceneLogicValues {
    currentProjectId: number | string // teamLogic
    page: number
    repoConfigs: StamphogRepoConfigApi[]
    repoConfigsLoading: boolean
    repository: string | null
    repositoryOptions: {
        label: string
        value: string
    }[]
    runCount: number
    runs: ReviewRunApi[]
    runsFailed: boolean
    runsResponse: PaginatedReviewRunListApi | null
    runsResponseLoading: boolean
    trigger: StamphogReviewRunsListTrigger | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface stamphogRunsSceneLogicActions {
    loadRepoConfigs: () => any
    loadRepoConfigsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRepoConfigsSuccess: (
        repoConfigs: StamphogRepoConfigApi[],
        payload?: any
    ) => {
        repoConfigs: StamphogRepoConfigApi[]
        payload?: any
    }
    loadRuns: () => {
        value: true
    }
    loadRunsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRunsSuccess: (
        runsResponse: PaginatedReviewRunListApi,
        payload?: {
            value: true
        }
    ) => {
        runsResponse: PaginatedReviewRunListApi
        payload?: {
            value: true
        }
    }
    setPage: (page: number) => {
        page: number
    }
    setRepository: (repository: string | null) => {
        repository: string | null
    }
    setTrigger: (trigger: StamphogReviewRunsListTrigger | null) => {
        trigger: StamphogReviewRunsListTrigger | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface stamphogRunsSceneLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        runs: (runsResponse: PaginatedReviewRunListApi | null) => ReviewRunApi[]
        runCount: (runsResponse: PaginatedReviewRunListApi | null) => number
        repositoryOptions: (repoConfigs: StamphogRepoConfigApi[]) => {
            label: string
            value: string
        }[]
    }
}

export type stamphogRunsSceneLogicType = MakeLogicType<
    stamphogRunsSceneLogicValues,
    stamphogRunsSceneLogicActions,
    Record<string, any>,
    stamphogRunsSceneLogicMeta
>

export const stamphogRunsSceneLogic = kea<stamphogRunsSceneLogicType>([
    path(['products', 'stamphog', 'frontend', 'scenes', 'StamphogRunsScene', 'stamphogRunsSceneLogic']),

    connect(() => ({
        values: [teamLogic, ['currentProjectId']],
    })),

    actions({
        // Declared explicitly rather than left to the loaders builder: the loader takes a breakpoint,
        // so typegen would otherwise infer a required payload from its first parameter and every
        // `loadRuns()` call site would stop compiling.
        loadRuns: true,
        setRepository: (repository: string | null) => ({ repository }),
        setTrigger: (trigger: StamphogReviewRunsListTrigger | null) => ({ trigger }),
        setPage: (page: number) => ({ page }),
    }),

    reducers({
        repository: [null as string | null, { setRepository: (_, { repository }) => repository }],
        trigger: [null as StamphogReviewRunsListTrigger | null, { setTrigger: (_, { trigger }) => trigger }],
        // Every filter change resets the page: page 4 of the unfiltered list is rarely a page at all
        // once a filter narrows the result set, and the reader would land on an empty table.
        page: [
            1,
            {
                setPage: (_, { page }) => page,
                setRepository: () => 1,
                setTrigger: () => 1,
            },
        ],
        // A failed request resolves the loader with a null response, which the runs selector turns into
        // an empty list. Without this the table would claim there are no runs when it simply could not
        // ask. Loading, empty and error are three different screens.
        runsFailed: [
            false,
            {
                loadRuns: () => false,
                loadRunsSuccess: () => false,
                loadRunsFailure: () => true,
            },
        ],
    }),

    loaders(({ values }) => ({
        runsResponse: [
            null as PaginatedReviewRunListApi | null,
            {
                loadRuns: async (_, breakpoint) => {
                    // urlToAction replays on mount, so a deep link sets repository, trigger and page
                    // in turn, each with its own listener. Debounce so only the settled filters load.
                    await breakpoint(1)
                    return stamphogReviewRunsList(String(values.currentProjectId), {
                        limit: RUNS_PAGE_SIZE,
                        offset: (values.page - 1) * RUNS_PAGE_SIZE,
                        ...(values.repository ? { repository: values.repository } : {}),
                        ...(values.trigger ? { trigger: values.trigger } : {}),
                    })
                },
            },
        ],
        // Populates the repository filter. Read-only here — the toggles that own these rows live on
        // the repositories scene, so this list is never written back.
        repoConfigs: [
            [] as StamphogRepoConfigApi[],
            {
                loadRepoConfigs: async () => {
                    // An installation can surface hundreds of repos, so follow LimitOffset pagination and
                    // fetch every page. A truncated first page would leave repos out of the filter while
                    // their runs still show up in the table.
                    const pageSize = 100
                    const all: StamphogRepoConfigApi[] = []
                    for (let offset = 0; ; offset += pageSize) {
                        const response = await stamphogRepoConfigsList(String(values.currentProjectId), {
                            limit: pageSize,
                            offset,
                        })
                        all.push(...response.results)
                        if (all.length >= response.count || response.results.length === 0) {
                            break
                        }
                    }
                    return all
                },
            },
        ],
    })),

    selectors({
        runs: [
            (s) => [s.runsResponse],
            (runsResponse: PaginatedReviewRunListApi | null): ReviewRunApi[] => runsResponse?.results ?? [],
        ],
        runCount: [
            (s) => [s.runsResponse],
            (runsResponse: PaginatedReviewRunListApi | null): number => runsResponse?.count ?? 0,
        ],
        // Only repositories stamphog is configured for — filtering by one it never reviewed would be
        // an empty table with no explanation for why.
        repositoryOptions: [
            (s) => [s.repoConfigs],
            (repoConfigs: StamphogRepoConfigApi[]): { value: string; label: string }[] =>
                repoConfigs.map((repo) => ({ value: repo.repository, label: repo.repository })),
        ],
    }),

    listeners(({ actions }) => ({
        setRepository: () => actions.loadRuns(),
        setTrigger: () => actions.loadRuns(),
        setPage: () => actions.loadRuns(),
    })),

    actionToUrl(({ values }) => {
        const toUrl = (): [string, Record<string, string>] => [
            urls.stamphogRuns(),
            {
                ...(values.repository ? { repository: values.repository } : {}),
                ...(values.trigger ? { trigger: values.trigger } : {}),
                ...(values.page > 1 ? { page: String(values.page) } : {}),
            },
        ]
        return { setRepository: toUrl, setTrigger: toUrl, setPage: toUrl }
    }),

    urlToAction(({ actions, values }) => ({
        [urls.stamphogRuns()]: (_: any, searchParams: Record<string, any>) => {
            const repository = (searchParams.repository as string | undefined) ?? null
            const trigger = (searchParams.trigger as StamphogReviewRunsListTrigger | undefined) ?? null
            const page = Number(searchParams.page ?? 1) || 1
            // Guard each against its current value: setRepository resets the page, so replaying an
            // unchanged filter on a deep link would knock the reader back to page 1.
            if (repository !== values.repository) {
                actions.setRepository(repository)
            }
            if (trigger !== values.trigger) {
                actions.setTrigger(trigger)
            }
            if (page !== values.page) {
                actions.setPage(page)
            }
        },
    })),

    afterMount(({ actions }) => {
        actions.loadRuns()
        actions.loadRepoConfigs()
    }),
])