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.

12.0 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { ApiConfig } from 'lib/api'

import type { ActivityRun } from '../components/RunActivityChart'
import {
    engineeringAnalyticsAttentionPullRequests,
    engineeringAnalyticsRepoOverview,
    engineeringAnalyticsRepoRunActivity,
} from '../generated/api'
import type { RepoOverviewApi, WorkflowRunActivityApi } from '../generated/api.schemas'
import { HUB_PREVIEW_MAX, HUB_PREVIEW_ROWS, HUB_PREVIEW_STEP } from '../lib/preview'
import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import {
    PullRequestRow,
    awaitsRepoForward,
    engineeringAnalyticsLogic,
    loaderStatusFromError,
    toPullRequestRow,
} from './engineeringAnalyticsLogic'
import type { WorkflowHealthRow } from './engineeringAnalyticsLogic'

const projectId = (): string => String(ApiConfig.getCurrentProjectId())

const TOP_COST_WORKFLOWS = 5

export interface AttentionPullRequests {
    rows: PullRequestRow[]
    total: number
}

export interface CostShareRow {
    workflowName: string | null
    costUsd: number
    share: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface repoOverviewLogicValues {
    dateFrom: string | null // engineeringAnalyticsFiltersLogic
    dateTo: string | null // engineeringAnalyticsFiltersLogic
    notConnected: boolean // engineeringAnalyticsLogic
    scopeRepo: string | null // engineeringAnalyticsLogic
    sourceId: string | null // engineeringAnalyticsLogic
    workflowHealth: WorkflowHealthRow[] // engineeringAnalyticsLogic
    workflowHealthLoading: boolean // engineeringAnalyticsLogic
    activityRuns: ActivityRun[]
    activityTruncated: boolean
    attention: AttentionPullRequests
    attentionFailed: boolean
    attentionLoading: boolean
    costByWorkflow: CostShareRow[]
    jobsAvailable: boolean
    otherCostWorkflowCount: number
    overview: RepoOverviewApi | null
    overviewDefaultBranch: string
    overviewFailed: boolean
    overviewLoading: boolean
    prPreviewCount: number
    repoActivity: WorkflowRunActivityApi
    repoActivityFailed: boolean
    repoActivityLoading: boolean
    workflowPreviewCount: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface repoOverviewLogicActions {
    loadAttention: (_: void) => void
    loadAttentionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAttentionSuccess: (
        attention: AttentionPullRequests,
        payload?: void
    ) => {
        attention: AttentionPullRequests
        payload?: void
    }
    loadOverview: () => any
    loadOverviewFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadOverviewSuccess: (
        overview: RepoOverviewApi,
        payload?: any
    ) => {
        overview: RepoOverviewApi
        payload?: any
    }
    loadRepoActivity: () => any
    loadRepoActivityFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRepoActivitySuccess: (
        repoActivity: WorkflowRunActivityApi,
        payload?: any
    ) => {
        repoActivity: WorkflowRunActivityApi
        payload?: any
    }
    showMorePrs: () => {
        value: true
    }
    showMoreWorkflows: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface repoOverviewLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        jobsAvailable: (overview: RepoOverviewApi | null) => boolean
        overviewDefaultBranch: (overview: RepoOverviewApi | null) => string
        activityRuns: (repoActivity: WorkflowRunActivityApi) => ActivityRun[]
        activityTruncated: (repoActivity: WorkflowRunActivityApi) => boolean
        costByWorkflow: (workflowHealth: WorkflowHealthRow[]) => CostShareRow[]
        otherCostWorkflowCount: (workflowHealth: WorkflowHealthRow[]) => number
    }
}

export type repoOverviewLogicType = MakeLogicType<
    repoOverviewLogicValues,
    repoOverviewLogicActions,
    Record<string, any>,
    repoOverviewLogicMeta
>

export const repoOverviewLogic = kea<repoOverviewLogicType>([
    path(['products', 'engineering_analytics', 'frontend', 'scenes', 'repoOverviewLogic']),

    connect(() => ({
        values: [
            engineeringAnalyticsFiltersLogic,
            ['dateFrom', 'dateTo'],
            engineeringAnalyticsLogic,
            ['sourceId', 'scopeRepo', 'workflowHealth', 'workflowHealthLoading', 'notConnected'],
        ],
    })),

    actions({
        showMorePrs: true,
        showMoreWorkflows: true,
    }),

    loaders(({ values }) => ({
        attention: [
            { rows: [], total: 0 } as AttentionPullRequests,
            {
                loadAttention: async (_: void, breakpoint): Promise<AttentionPullRequests> => {
                    const response = await engineeringAnalyticsAttentionPullRequests(projectId(), {
                        source_id: values.sourceId ?? undefined,
                        repo: values.scopeRepo ?? undefined,
                    })
                    breakpoint()
                    return { rows: response.items.map(toPullRequestRow), total: response.total }
                },
            },
        ],
        overview: [
            null as RepoOverviewApi | null,
            {
                loadOverview: async (): Promise<RepoOverviewApi> =>
                    await engineeringAnalyticsRepoOverview(projectId(), {
                        date_from: values.dateFrom ?? undefined,
                        date_to: values.dateTo ?? undefined,
                        // The hub renders window-vs-previous comparisons from the headline
                        // aggregates; skipping the chart series skips their query cost too.
                        include_series: false,
                        source_id: values.sourceId ?? undefined,
                        repo: values.scopeRepo ?? undefined,
                    }),
            },
        ],
        // One collapsed point per default-branch commit (all its workflows folded together) for the
        // master-health strip — the backend owns the collapse, so the UI just plots the points.
        repoActivity: [
            { points: [], truncated: false, limit: 0 } as WorkflowRunActivityApi,
            {
                loadRepoActivity: async (): Promise<WorkflowRunActivityApi> =>
                    await engineeringAnalyticsRepoRunActivity(projectId(), {
                        date_from: values.dateFrom ?? undefined,
                        date_to: values.dateTo ?? undefined,
                        source_id: values.sourceId ?? undefined,
                        repo: values.scopeRepo ?? undefined,
                    }),
            },
        ],
    })),

    reducers({
        // Non-400 failure only; the shared 400 "not connected" state comes from engineeringAnalyticsLogic.
        attentionFailed: [
            false,
            {
                loadAttention: () => false,
                loadAttentionSuccess: () => false,
                loadAttentionFailure: (_, { errorObject }) => loaderStatusFromError(errorObject) === 'error',
            },
        ],
        overviewFailed: [
            false,
            {
                loadOverview: () => false,
                loadOverviewSuccess: () => false,
                loadOverviewFailure: () => true,
            },
        ],
        // Without this, a failed activity fetch is indistinguishable from a quiet branch — the scene
        // would show the "no runs" empty state over a real error.
        repoActivityFailed: [
            false,
            {
                loadRepoActivity: () => false,
                loadRepoActivitySuccess: () => false,
                loadRepoActivityFailure: () => true,
            },
        ],
        // How many rows the hub's preview tables show. Start short (HUB_PREVIEW_ROWS), grow by a fixed
        // step on "Show more", capped so the hub stays a preview — the full tables live on the dedicated
        // pages. No reset on reload: slicing tolerates any list length, and keeping the user's expansion
        // across a window change is less surprising than snapping back.
        prPreviewCount: [
            HUB_PREVIEW_ROWS,
            { showMorePrs: (count) => Math.min(HUB_PREVIEW_MAX, count + HUB_PREVIEW_STEP) },
        ],
        workflowPreviewCount: [
            HUB_PREVIEW_ROWS,
            { showMoreWorkflows: (count) => Math.min(HUB_PREVIEW_MAX, count + HUB_PREVIEW_STEP) },
        ],
    }),

    selectors({
        jobsAvailable: [
            (s) => [s.overview],
            (overview: RepoOverviewApi | null): boolean => overview?.jobs_available ?? false,
        ],
        overviewDefaultBranch: [
            (s) => [s.overview],
            (overview: RepoOverviewApi | null): string => overview?.default_branch ?? 'master',
        ],
        // Backend-collapsed commit points, mapped to the shared chart shape (one bar per default-branch
        // commit: start time, wall-clock CI duration, overall verdict).
        activityRuns: [
            (s) => [s.repoActivity],
            (repoActivity: WorkflowRunActivityApi): ActivityRun[] =>
                repoActivity.points.map((point) => ({
                    runId: point.run_id,
                    conclusion: point.conclusion,
                    startedAt: point.run_started_at,
                    durationSeconds: point.duration_seconds,
                    headBranch: point.head_branch,
                    prNumber: point.pr_number,
                    headSha: point.head_sha,
                })),
        ],
        activityTruncated: [
            (s) => [s.repoActivity],
            (repoActivity: WorkflowRunActivityApi): boolean => repoActivity.truncated,
        ],
        costByWorkflow: [
            (s) => [s.workflowHealth],
            (workflowHealth: import('./engineeringAnalyticsLogic').WorkflowHealthRow[]): CostShareRow[] => {
                const costed = workflowHealth.filter((row) => (row.estimatedCostUsd ?? 0) > 0)
                if (!costed.length) {
                    return []
                }
                const total = costed.reduce((sum, row) => sum + (row.estimatedCostUsd ?? 0), 0)
                const top = [...costed]
                    .sort((a, b) => (b.estimatedCostUsd ?? 0) - (a.estimatedCostUsd ?? 0))
                    .slice(0, TOP_COST_WORKFLOWS)
                const rows: CostShareRow[] = top.map((row) => ({
                    workflowName: row.workflowName,
                    costUsd: row.estimatedCostUsd ?? 0,
                    share: (row.estimatedCostUsd ?? 0) / total,
                }))
                const otherCost = total - rows.reduce((sum, row) => sum + row.costUsd, 0)
                if (costed.length > TOP_COST_WORKFLOWS && otherCost > 0) {
                    rows.push({ workflowName: null, costUsd: otherCost, share: otherCost / total })
                }
                return rows
            },
        ],
        otherCostWorkflowCount: [
            (s) => [s.workflowHealth],
            (workflowHealth: import('./engineeringAnalyticsLogic').WorkflowHealthRow[]): number =>
                Math.max(
                    0,
                    workflowHealth.filter((row) => (row.estimatedCostUsd ?? 0) > 0).length - TOP_COST_WORKFLOWS
                ),
        ],
    }),

    listeners(({ actions }) => ({
        [engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
            actions.loadOverview()
            actions.loadRepoActivity()
        },
        [engineeringAnalyticsLogic.actionTypes.refresh]: () => {
            actions.loadAttention()
            actions.loadOverview()
            actions.loadRepoActivity()
        },
    })),

    afterMount(({ actions }) => {
        if (awaitsRepoForward()) {
            return
        }
        actions.loadAttention()
        actions.loadOverview()
        actions.loadRepoActivity()
    }),
])