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.

39.9 KB
Raw Blame
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'

import { ApiConfig, ApiError } from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { urls } from 'scenes/urls'

import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { initKeaTests } from '~/test/init'

import {
    engineeringAnalyticsCiCards,
    engineeringAnalyticsPullRequests,
    engineeringAnalyticsQuarantine,
    engineeringAnalyticsSources,
    engineeringAnalyticsTrunkQuarantine,
    engineeringAnalyticsWorkflowHealth,
} from '../generated/api'
import type {
    CICardSummaryApi,
    GitHubSourceApi,
    PullRequestListItemApi,
    QuarantineFileApi,
    WorkflowHealthItemApi,
    WorkflowRunDetailApi,
} from '../generated/api.schemas'
import { ciStatusOf } from '../lib/ci'
import { workflowRuns } from '../lib/lifecycle'
import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import {
    DEFAULT_FILTERS,
    DEFAULT_WORKFLOW_FILTERS,
    PullRequestRow,
    WorkflowHealthRow,
    engineeringAnalyticsLogic,
    filterPullRequests,
    filterWorkflowHealth,
    workflowFailureSeries,
} from './engineeringAnalyticsLogic'
import { engineeringAnalyticsSceneLogic } from './engineeringAnalyticsSceneLogic'
import { groupRunsByCommit, sortRunsForTriage } from './pullRequestDetailLogic'
import { repoScopeLogic } from './repoScopeLogic'

jest.mock('../generated/api', () => ({
    engineeringAnalyticsCiCards: jest.fn(),
    engineeringAnalyticsPrLifecycle: jest.fn(),
    engineeringAnalyticsPullRequests: jest.fn(),
    engineeringAnalyticsQuarantine: jest.fn(),
    engineeringAnalyticsSources: jest.fn(),
    engineeringAnalyticsTrunkQuarantine: jest.fn(),
    engineeringAnalyticsWorkflowHealth: jest.fn(),
}))

const mockCiCards = engineeringAnalyticsCiCards as jest.MockedFunction<typeof engineeringAnalyticsCiCards>
const mockPullRequests = engineeringAnalyticsPullRequests as jest.MockedFunction<
    typeof engineeringAnalyticsPullRequests
>
const mockWorkflowHealth = engineeringAnalyticsWorkflowHealth as jest.MockedFunction<
    typeof engineeringAnalyticsWorkflowHealth
>
const mockQuarantine = engineeringAnalyticsQuarantine as jest.MockedFunction<typeof engineeringAnalyticsQuarantine>
const mockSources = engineeringAnalyticsSources as jest.MockedFunction<typeof engineeringAnalyticsSources>
const mockTrunkQuarantine = engineeringAnalyticsTrunkQuarantine as jest.MockedFunction<
    typeof engineeringAnalyticsTrunkQuarantine
>

const QUARANTINE: QuarantineFileApi = {
    available: true,
    entries: [],
    parse_errors: [],
    parse_warnings: [],
    repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },
    source_url: 'https://github.com/PostHog/posthog/blob/HEAD/.test_quarantine.json',
    generated_at: '2026-06-12T00:00:00Z',
}

function makePr(overrides: Partial<PullRequestRow> = {}): PullRequestRow {
    return {
        number: 1,
        title: 'feat: a thing',
        repoOwner: 'posthog',
        repoName: 'posthog',
        authorHandle: 'alice',
        authorAvatarUrl: '',
        isBot: false,
        state: 'open',
        isDraft: false,
        createdAt: '2026-05-01T00:00:00Z',
        mergedAt: null,
        openToMergeSeconds: null,
        labels: [],
        runs: 0,
        passing: 0,
        failing: 0,
        pending: 0,
        inconclusive: 0,
        failingWorkflows: [],
        pushes: 0,
        pushHistory: [],
        rerunCycles: 0,
        estimatedCostUsd: null,
        billableMinutes: null,
        ...overrides,
    }
}

function apiPr(overrides: Partial<PullRequestListItemApi> = {}): PullRequestListItemApi {
    return {
        author: { handle: 'alice', display_name: 'alice', avatar_url: 'https://a/avatar', is_bot: false },
        repo: { provider: 'github', owner: 'posthog', name: 'posthog' },
        ci: { runs: 0, passing: 0, failing: 0, pending: 0, inconclusive: 0 },
        number: 1,
        title: 'feat: x',
        state: 'open',
        is_draft: false,
        created_at: '2026-05-01T00:00:00Z',
        merged_at: null,
        open_to_merge_seconds: null,
        ready_to_merge_seconds: null,
        labels: [],
        pushes: 0,
        push_history: [],
        rerun_cycles: 0,
        estimated_cost_usd: null,
        ...overrides,
    }
}

const CARDS: CICardSummaryApi = { open_prs: 18, repos: 10, stuck: 6, failing_ci: 4 }
const PRS: PullRequestListItemApi[] = [
    apiPr({
        number: 101,
        ci: { runs: 3, passing: 2, failing: 1, pending: 0, inconclusive: 0 },
        pushes: 7,
        rerun_cycles: 2,
    }),
    apiPr({
        number: 102,
        title: 'fix: y',
        author: { handle: 'bob', display_name: 'bob', avatar_url: 'https://b/avatar', is_bot: false },
        repo: { provider: 'github', owner: 'posthog', name: 'posthog-js' },
        ci: { runs: 5, passing: 5, failing: 0, pending: 0, inconclusive: 0 },
        state: 'merged',
        created_at: '2026-05-20T00:00:00Z',
        merged_at: '2026-05-21T00:00:00Z',
        open_to_merge_seconds: 86400,
    }),
]
const WORKFLOWS: WorkflowHealthItemApi[] = [
    {
        repo: { provider: 'github', owner: 'posthog', name: 'posthog' },
        granularity: 'day',
        buckets: [{ bucket_start: '2026-05-30T00:00:00Z', run_count: 100, completed: 95, successes: 90, failures: 4 }],
        workflow_name: 'CI',
        run_count: 100,
        successful_run_count: 90,
        conclusive_run_count: 94,
        success_rate: 0.95,
        p50_seconds: 120,
        p95_seconds: 600,
        last_failure_at: '2026-05-30T00:00:00Z',
        latest_run_failed: false,
        latest_run_conclusion: 'success',
        latest_run_id: 123456,
        latest_run_attempt: 1,
    },
]
function makeWorkflow(overrides: Partial<WorkflowHealthRow> = {}): WorkflowHealthRow {
    return {
        repoOwner: 'posthog',
        repoName: 'posthog',
        workflowName: 'CI',
        runCount: 10,
        successRate: 1,
        p50Seconds: 60,
        p95Seconds: 120,
        lastFailureAt: null,
        latestRunFailed: false,
        latestRunConclusion: 'success',
        granularity: 'day',
        buckets: [],
        mergeQueueRunCount: 0,
        ...overrides,
    }
}

const SOURCES: GitHubSourceApi[] = [
    { id: 'src-older', repo: 'posthog/posthog', prefix: 'older', synced: true },
    { id: 'src-newer', repo: 'posthog/posthog.com', prefix: 'website', synced: true },
]

describe('engineeringAnalyticsLogic', () => {
    let logic: ReturnType<typeof engineeringAnalyticsLogic.build>
    let extraUnmounts: (() => void)[] = []

    beforeEach(() => {
        // The last repository used persists, so one test's pick must not steer the next test's forward.
        localStorage.clear()
        initKeaTests()
        ApiConfig.setCurrentProjectId(1)
        jest.clearAllMocks()
        // Happy-path defaults; individual tests override before mounting where needed.
        mockCiCards.mockResolvedValue(CARDS)
        mockPullRequests.mockResolvedValue({ items: PRS, truncated: false, limit: PRS.length })
        mockWorkflowHealth.mockResolvedValue(WORKFLOWS)
        mockQuarantine.mockResolvedValue(QUARANTINE)
        // Most tests are single- or no-source; the picker tests override with SOURCES.
        mockSources.mockResolvedValue([])
        mockTrunkQuarantine.mockResolvedValue({
            available: true,
            owners_resolved: true,
            ttl_days: 15,
            truncated: false,
            limit: 5000,
            repository: 'PostHog/posthog',
            trunk_url: null,
            teams: [],
            tests: [],
        })
    })

    afterEach(() => {
        // Unmount everything so a still-pending loader can't reject into a later, unsilenced test.
        extraUnmounts.forEach((unmount) => unmount())
        extraUnmounts = []
        if (logic?.isMounted()) {
            logic.unmount()
        }
        jest.restoreAllMocks()
        resumeKeaLoadersErrors()
    })

    it('filters by state, author, repo, ci status, and search', () => {
        const rows = [
            makePr({ number: 1, state: 'open', authorHandle: 'alice', runs: 2, failing: 1 }),
            makePr({ number: 2, state: 'merged', authorHandle: 'bob', repoName: 'posthog-js' }),
            makePr({ number: 3, state: 'open', authorHandle: 'bob', title: 'chore: bump' }),
            makePr({ number: 4, state: 'open', isDraft: true }),
            makePr({ number: 5, state: 'closed' }),
        ]
        // The open lens includes drafts; Draft and Closed are narrower cuts.
        expect(filterPullRequests(rows, DEFAULT_FILTERS)).toHaveLength(3)
        expect(filterPullRequests(rows, { ...DEFAULT_FILTERS, state: 'merged' })).toHaveLength(1)
        expect(filterPullRequests(rows, { ...DEFAULT_FILTERS, state: 'draft' }).map((row) => row.number)).toEqual([4])
        expect(filterPullRequests(rows, { ...DEFAULT_FILTERS, state: 'closed' }).map((row) => row.number)).toEqual([5])
        expect(filterPullRequests(rows, { ...DEFAULT_FILTERS, state: 'all', author: 'bob' })).toHaveLength(2)
        expect(filterPullRequests(rows, { ...DEFAULT_FILTERS, state: 'all', repo: 'posthog/posthog-js' })).toHaveLength(
            1
        )
        expect(filterPullRequests(rows, { ...DEFAULT_FILTERS, state: 'all', ciStatus: 'failing' })).toHaveLength(1)
        expect(filterPullRequests(rows, { ...DEFAULT_FILTERS, state: 'all', search: 'bump' })).toHaveLength(1)
        expect(filterPullRequests(rows, { ...DEFAULT_FILTERS, state: 'all', search: '#2' })).toHaveLength(1)
    })

    it('stuckOnly keeps open, non-draft, non-bot PRs older than 7 days', () => {
        const now = dayjs('2026-06-11T00:00:00Z')
        const rows = [
            makePr({ number: 1, createdAt: '2026-06-01T00:00:00Z' }),
            makePr({ number: 2, createdAt: '2026-06-09T00:00:00Z' }),
            makePr({ number: 3, createdAt: '2026-06-01T00:00:00Z', isDraft: true }),
            makePr({ number: 4, createdAt: '2026-06-01T00:00:00Z', isBot: true }),
            makePr({ number: 5, createdAt: '2026-05-01T00:00:00Z', state: 'merged', mergedAt: '2026-06-10T00:00:00Z' }),
        ]
        const stuck = filterPullRequests(rows, { ...DEFAULT_FILTERS, stuckOnly: true }, now)
        expect(stuck.map((row) => row.number)).toEqual([1])
    })

    it('card filters toggle the matching view and back', async () => {
        logic = engineeringAnalyticsLogic()
        logic.mount()
        expect(logic.values.activeCard).toBe('open')

        logic.actions.applyCardFilter('failing')
        expect(logic.values.activeCard).toBe('failing')
        expect(logic.values.ciStatusFilter).toBe('failing')

        logic.actions.applyCardFilter('stuck')
        expect(logic.values.activeCard).toBe('stuck')
        expect(logic.values.stuckOnly).toBe(true)
        expect(logic.values.ciStatusFilter).toBe('all')
        // The stuck lens is an active filter — a filtered-to-zero table must offer "Clear filters".
        expect(logic.values.hasActiveFilters).toBe(true)

        // Clicking the active card returns to the plain open view.
        logic.actions.applyCardFilter('stuck')
        expect(logic.values.activeCard).toBe('open')
        expect(logic.values.stuckOnly).toBe(false)

        // Leaving the open backlog deactivates every card.
        logic.actions.applyCardFilter('failing')
        logic.actions.setStateFilter('merged')
        expect(logic.values.activeCard).toBeNull()
    })

    it('scene logic mounts without a tabId so /engineering-analytics resolves instead of 404ing', () => {
        // #62051 collapsed sceneLogic to single-scene state and stopped threading a tabId into
        // scene logics. A tab-aware scene logic then throws "must have a tabId prop" on mount,
        // sceneLogic's catch falls back to Error404, and every visit to the scene 404s.
        expect(() => extraUnmounts.push(engineeringAnalyticsSceneLogic().mount())).not.toThrow()
    })

    it('maps the three endpoints into typed rows and defaults to the open filter', async () => {
        logic = engineeringAnalyticsLogic()
        logic.mount()
        await expectLogic(logic).toDispatchActions([
            'loadCardsSuccess',
            'loadPullRequestsSuccess',
            'loadWorkflowHealthSuccess',
        ])

        expect(logic.values.cards).toEqual({ openPrs: 18, repos: 10, stuck: 6, failingCi: 4 })
        expect(logic.values.pullRequests).toHaveLength(2)
        expect(logic.values.pullRequests[0].authorHandle).toBe('alice')
        expect(ciStatusOf(logic.values.pullRequests[0])).toBe('failing')
        expect(logic.values.pullRequests[0].pushes).toBe(7)
        expect(logic.values.pullRequests[0].rerunCycles).toBe(2)
        expect(logic.values.pullRequests[0].estimatedCostUsd).toBeNull()
        expect(logic.values.pullRequests[1].openToMergeSeconds).toBe(86400)
        expect(logic.values.workflowHealth).toHaveLength(1)
        expect(logic.values.workflowHealth[0].successRate).toBe(0.95)
        expect(logic.values.workflowHealth[0].latestRunFailed).toBe(false)
        expect(logic.values.workflowHealth[0].granularity).toBe('day')
        expect(logic.values.workflowHealth[0].buckets).toEqual([
            { bucketStart: '2026-05-30T00:00:00Z', runCount: 100, completed: 95, successes: 90, failures: 4 },
        ])
        // Default state filter is "open", so only the open PR survives.
        expect(logic.values.filteredPullRequests).toHaveLength(1)
        expect(logic.values.notConnected).toBe(false)
        expect(logic.values.pullRequestsLoadError).toBe(false)
        expect(logic.values.workflowHealthLoadError).toBe(false)
    })

    it('reloads workflow health when the shared date range changes', async () => {
        logic = engineeringAnalyticsLogic()
        logic.mount()
        const filters = engineeringAnalyticsFiltersLogic()
        extraUnmounts.push(filters.mount())
        await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
        expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d' })

        filters.actions.setDateRange('-90d', null)
        await expectLogic(logic).toDispatchActions(['loadWorkflowHealth', 'loadWorkflowHealthSuccess'])
        expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-90d' })

        filters.actions.setDateRange('2026-01-01', '2026-03-01')
        await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
        expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '2026-01-01', date_to: '2026-03-01' })
    })

    it('scopes workflow health to the shared run group', async () => {
        logic = engineeringAnalyticsLogic()
        logic.mount()
        const filters = engineeringAnalyticsFiltersLogic()
        extraUnmounts.push(filters.mount())
        await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
        // All runs is the default, and the backend already reports every run when the param is absent.
        expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d' })

        filters.actions.setRunScope('pull_request')
        await expectLogic(logic).toDispatchActions(['loadWorkflowHealth', 'loadWorkflowHealthSuccess'])
        expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d', run_scope: 'pull_request' })

        filters.actions.setDateRange('-90d', null)
        await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
        expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-90d', run_scope: 'pull_request' })

        filters.actions.setRunScope('all')
        await expectLogic(logic).toDispatchActions(['loadWorkflowHealth', 'loadWorkflowHealthSuccess'])
        expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-90d' })
    })

    it('lists one option per (source, repo) pair and switches to the picked repo', async () => {
        // The option value encodes (source, repo) so a multi-repo source's repos stay distinct;
        // two distinct sources and one source syncing two repos produce the same option shape.
        mockSources.mockResolvedValue([
            { id: 'src-multi', repo: 'posthog/posthog', prefix: 'multi', synced: true },
            { id: 'src-multi', repo: 'posthog/posthog.com', prefix: 'multi', synced: true },
            { id: 'src-other', repo: 'posthog/posthog.js', prefix: 'js', synced: true },
        ])
        logic = engineeringAnalyticsLogic()
        logic.mount()
        const scope = repoScopeLogic()
        await expectLogic(scope).toDispatchActions(['loadGithubSourcesSuccess'])
        await expectLogic(logic).toDispatchActions(['loadCardsSuccess'])

        expect(scope.values.hasMultipleSources).toBe(true)
        expect(scope.values.sourceOptions).toEqual([
            { value: 'src-multi::posthog/posthog', label: 'posthog/posthog' },
            { value: 'src-multi::posthog/posthog.com', label: 'posthog/posthog.com' },
            { value: 'src-other::posthog/posthog.js', label: 'posthog/posthog.js' },
        ])

        // One source syncs that repository, so the path alone names it and no `?source` rides along.
        scope.actions.switchRepo('src-multi::posthog/posthog.com')
        await expectLogic(logic).toDispatchActions(['setScope', 'loadCardsSuccess'])
        expect(routedPath()).toBe(urls.engineeringAnalytics('posthog/posthog.com'))
        expect(router.values.searchParams).toEqual({})
        expect(scope.values.selectedScope).toBe('src-multi::posthog/posthog.com')
        expect(mockCiCards).toHaveBeenLastCalledWith('1', { source_id: undefined, repo: 'posthog/posthog.com' })
    })

    it.each([
        [
            'another source of the repository on screen keeps the page and sets ?source',
            'src-mirror::PostHog/PostHog',
            urls.engineeringAnalyticsPullRequest('posthog', 'posthog', 42),
            { source: 'src-mirror' },
        ],
        [
            'a legacy source with no repository opens the repo-less list tab with ?source',
            'src-legacy::',
            urls.engineeringAnalyticsPullRequestList(),
            { source: 'src-legacy' },
        ],
    ])('switching repository: %s', async (_label, pick, pathname, searchParams) => {
        mockSources.mockResolvedValue([
            { id: 'src-main', repo: 'posthog/posthog', prefix: 'main', synced: true },
            { id: 'src-mirror', repo: 'PostHog/PostHog', prefix: 'mirror', synced: true },
            { id: 'src-legacy', repo: '', prefix: 'legacy', synced: true },
        ])
        router.actions.push(urls.engineeringAnalyticsPullRequest('posthog', 'posthog', 42))
        const scope = repoScopeLogic()
        scope.mount()
        extraUnmounts.push(() => scope.unmount())
        await expectLogic(scope).toDispatchActions(['loadGithubSourcesSuccess'])

        scope.actions.switchRepo(pick)

        expect(routedPath()).toBe(pathname)
        expect(router.values.searchParams).toEqual(searchParams)
        expect(scope.values.selectedScope).toBe(pick)
    })

    it('hides the picker when the team has a single source', async () => {
        mockSources.mockResolvedValue([SOURCES[0]])
        const scope = repoScopeLogic()
        scope.mount()
        await expectLogic(scope).toDispatchActions(['loadGithubSourcesSuccess'])

        expect(scope.values.hasMultipleSources).toBe(false)
    })

    it('defaults to no source, then scopes every endpoint to the picked one and reloads', async () => {
        logic = engineeringAnalyticsLogic()
        logic.mount()
        await expectLogic(logic).toDispatchActions([
            'loadCardsSuccess',
            'loadPullRequestsSuccess',
            'loadWorkflowHealthSuccess',
        ])
        // No source picked → omit source_id/repo so the backend resolves its default.
        expect(mockCiCards).toHaveBeenLastCalledWith('1', { source_id: undefined, repo: undefined })

        logic.actions.setSourceId('src-newer')
        await expectLogic(logic).toDispatchActions([
            'setSourceId',
            'loadCards',
            'loadPullRequests',
            'loadWorkflowHealth',
            'loadCardsSuccess',
        ])

        expect(logic.values.sourceId).toBe('src-newer')
        expect(mockCiCards).toHaveBeenLastCalledWith('1', { source_id: 'src-newer', repo: undefined })
        expect(mockPullRequests).toHaveBeenLastCalledWith('1', { source_id: 'src-newer', repo: undefined })
        expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', {
            date_from: '-7d',
            source_id: 'src-newer',
            repo: undefined,
        })
    })

    it.each([
        // 'failing'/'passing' key off the latest settled run; a row with nothing completed
        // (latestRunFailed null) must show only under 'all' — it is neither green nor red.
        ['failing keeps only rows whose latest run failed', { status: 'failing' as const }, ['E2E']],
        ['passing keeps only settled green rows', { status: 'passing' as const }, ['CI']],
        ['unsettled rows show only under all', {}, ['CI', 'E2E', 'Nightly']],
        ['search is case-insensitive over the name', { search: 'NIGHT' }, ['Nightly']],
    ])('filterWorkflowHealth: %s', (_label, overrides, expected) => {
        const rows = [
            makeWorkflow({ workflowName: 'CI', latestRunFailed: false }),
            makeWorkflow({ workflowName: 'E2E', latestRunFailed: true }),
            makeWorkflow({ workflowName: 'Nightly', latestRunFailed: null, latestRunConclusion: null }),
        ]
        expect(
            filterWorkflowHealth(rows, { ...DEFAULT_WORKFLOW_FILTERS, ...overrides }).map((row) => row.workflowName)
        ).toEqual(expected)
    })

    it('workflowCostAvailable flips on once any row carries cost data', async () => {
        logic = engineeringAnalyticsLogic()
        logic.mount()
        await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
        expect(logic.values.workflowCostAvailable).toBe(false)

        mockWorkflowHealth.mockResolvedValue([{ ...WORKFLOWS[0], billable_minutes: 12, estimated_cost_usd: 0.5 }])
        logic.actions.loadWorkflowHealth()
        await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
        expect(logic.values.workflowCostAvailable).toBe(true)
    })

    it.each([
        ['workflows', () => urls.engineeringAnalyticsWorkflows('posthog/posthog.com')],
        ['tests', () => urls.engineeringAnalyticsTests('posthog/posthog.com')],
        ['teams', () => urls.engineeringAnalyticsTeams('posthog/posthog.com')],
        ['authors', () => urls.engineeringAnalyticsAuthors('posthog/posthog.com')],
        ['team detail', () => urls.engineeringAnalyticsTeam('team-replay', 'posthog/posthog.com')],
        ['deploys', () => urls.engineeringAnalyticsDeploys('posthog/posthog.com')],
    ])('the %s route takes the repository from its path and the source from ?source', async (_label, url) => {
        logic = engineeringAnalyticsLogic()
        logic.mount()

        router.actions.push(url(), { source: 'src-newer' })
        await expectLogic(logic).toDispatchActions(['setScope'])
        expect(logic.values.sourceId).toBe('src-newer')
        expect(logic.values.scopeRepo).toBe('posthog/posthog.com')
    })

    it('requests the hub once on a scoped direct load', async () => {
        router.actions.push(urls.engineeringAnalyticsTeam('team-replay', 'posthog/posthog.com'), {
            source: 'src-newer',
        })
        logic = engineeringAnalyticsLogic()
        logic.mount()

        await expectLogic(logic).toDispatchActions(['loadCardsSuccess'])
        expect(mockCiCards).toHaveBeenCalledTimes(1)
        expect(mockCiCards.mock.calls[0][1]).toMatchObject({ source_id: 'src-newer', repo: 'posthog/posthog.com' })
    })

    it.each([
        ['the repository it names', { repo: 'posthog/posthog.com' }, 'posthog/posthog.com'],
        ['the first synced repository of the source it names', { source: 'src-newer' }, 'posthog/posthog.com'],
        ['the default repository when it names none', {}, 'posthog/posthog'],
    ])('an old repo-less link forwards to %s, then loads once', async (_label, searchParams, repo) => {
        mockSources.mockResolvedValue(SOURCES)
        router.actions.push(urls.engineeringAnalyticsPullRequestList(), { ...searchParams, date_from: '-30d' })
        logic = engineeringAnalyticsLogic()
        logic.mount()

        await expectLogic(logic).toDispatchActions(['loadCardsSuccess'])
        expect(routedPath()).toBe(urls.engineeringAnalyticsPullRequestList(repo))
        expect(router.values.searchParams).not.toHaveProperty('repo')
        expect(mockCiCards).toHaveBeenCalledTimes(1)
        expect(mockCiCards.mock.calls[0][1]).toMatchObject({ repo })
    })

    it('an old repo-less link to a legacy source stays repo-less and reads that source', async () => {
        mockSources.mockResolvedValue([...SOURCES, { id: 'src-legacy', repo: '', prefix: 'legacy', synced: true }])
        router.actions.push(urls.engineeringAnalyticsPullRequestList(), { source: 'src-legacy' })
        logic = engineeringAnalyticsLogic()
        logic.mount()

        await expectLogic(logic).toDispatchActions(['noRepoToForward', 'loadCardsSuccess'])
        expect(routedPath()).toBe(urls.engineeringAnalyticsPullRequestList())
        expect(mockCiCards).toHaveBeenCalledTimes(1)
        expect(mockCiCards.mock.calls[0][1]).toMatchObject({ source_id: 'src-legacy' })
    })

    const openPullRequestList = async (
        searchParams: Record<string, string>,
        sources: GitHubSourceApi[] = SOURCES
    ): Promise<jest.SpyInstance> => {
        mockSources.mockResolvedValue(sources)
        const { repo, ...rest } = searchParams
        router.actions.push(urls.engineeringAnalyticsPullRequestList(repo), rest)
        logic = engineeringAnalyticsLogic()
        logic.mount()
        await expectLogic(repoScopeLogic).toDispatchActions(['loadGithubSourcesSuccess'])
        return jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
    }
    const jumpEvents = (capture: jest.SpyInstance): unknown[] =>
        capture.mock.calls
            .filter(([event]) => event === 'pull request jump submitted')
            .map(([, properties]) => properties)
    const routedPath = (): string => removeProjectIdIfPresent(router.values.location.pathname)

    const PICKED = { source: 'src-older', repo: 'posthog/posthog', date_from: '-30d' }

    it.each<[string, Record<string, string>, string, string, Record<string, string>, string]>([
        [
            'a link to the repository in scope with no source when none is picked',
            {},
            'https://github.com/PostHog/posthog/pull/42',
            urls.engineeringAnalyticsCIExplorer('posthog', 'posthog', 42),
            {},
            'link',
        ],
        [
            'a link to another repository without the source and repo of this one',
            PICKED,
            'https://github.com/PostHog/posthog.com/pull/42/files',
            urls.engineeringAnalyticsCIExplorer('PostHog', 'posthog.com', 42),
            { date_from: '-30d' },
            'link',
        ],
        [
            'a bare number in the picked repository',
            PICKED,
            '#42',
            urls.engineeringAnalyticsCIExplorer('posthog', 'posthog', 42),
            { source: 'src-older', date_from: '-30d' },
            'number',
        ],
    ])('the pull request jump opens %s once', async (_label, opened, text, pathname, searchParams, inputKind) => {
        const capture = await openPullRequestList(opened)

        logic.actions.setPullRequestJumpText(text)
        logic.actions.submitPullRequestJump()
        logic.actions.submitPullRequestJump()

        expect(routedPath()).toBe(pathname)
        expect(router.values.searchParams).toEqual(searchParams)
        expect(jumpEvents(capture)).toEqual([{ outcome: 'opened', input_kind: inputKind }])
        expect(logic.values.pullRequestJumpFailure).toBeNull()
    })

    it('the pull request jump says why it cannot open, until the cause is fixed', async () => {
        const capture = await openPullRequestList({}, [{ ...SOURCES[0], repo: '' }])

        logic.actions.setPullRequestJumpText('not a pr')
        logic.actions.submitPullRequestJump()
        expect(logic.values.pullRequestJumpFailure).toBe('invalid')

        logic.actions.setPullRequestJumpText('42')
        expect(logic.values.pullRequestJumpFailure).toBeNull()
        logic.actions.submitPullRequestJump()
        expect(logic.values.pullRequestJumpFailure).toBe('needs_repository')
        expect(routedPath()).toBe(urls.engineeringAnalyticsPullRequestList())
        expect(jumpEvents(capture)).toEqual([
            { outcome: 'invalid', input_kind: null },
            { outcome: 'needs_repository', input_kind: 'number' },
        ])

        logic.actions.setPullRequestJumpText('PostHog/posthog#42')
        expect(logic.values.pullRequestJumpFailure).toBeNull()
        logic.actions.submitPullRequestJump()
        expect(routedPath()).toBe(urls.engineeringAnalyticsCIExplorer('PostHog', 'posthog', 42))
    })

    it.each([
        [
            'pull request',
            [
                ['setStateFilter', 'all'],
                ['setAuthor', 'alice'],
                ['setRepo', 'posthog/posthog'],
                ['setCiStatusFilter', 'failing'],
                ['setSearch', 'fix'],
            ],
            'resetFilters',
            'hasActiveFilters',
            'filters',
            DEFAULT_FILTERS,
        ],
        [
            'workflow',
            [
                ['setWorkflowSearch', 'e2e'],
                ['setWorkflowStatusFilter', 'failing'],
            ],
            'resetWorkflowFilters',
            'hasActiveWorkflowFilters',
            'workflowFilters',
            DEFAULT_WORKFLOW_FILTERS,
        ],
    ] as [string, [string, string][], string, string, string, object][])(
        'the %s reset returns filters to defaults and clears the active flag',
        (_label, dirtyCalls, resetAction, activeKey, filtersKey, defaults) => {
            logic = engineeringAnalyticsLogic()
            logic.mount()
            const actions = logic.actions as unknown as Record<string, (value: string) => void>
            const values = logic.values as unknown as Record<string, unknown>
            expect(values[activeKey]).toBe(false)

            dirtyCalls.forEach(([action, value]) => actions[action](value))
            expect(values[activeKey]).toBe(true)

            ;(actions[resetAction] as unknown as () => void)()
            expect(values[filtersKey]).toEqual(defaults)
            expect(values[activeKey]).toBe(false)
        }
    )

    it.each([
        // Stacked bar: total height is completed (volume), the red portion is failures, so the red
        // fraction reads as the rate. Skipped/cancelled/action_required are completed but not failures.
        [
            'a bad day stacks failures over completed',
            { completed: 25, successes: 22, failures: 3 },
            25,
            3,
            'Jun 5 · 3 of 25 failed',
        ],
        ['an all-green day has no red', { completed: 25, successes: 25, failures: 0 }, 25, 0, 'Jun 5 · 0 of 25 failed'],
        [
            'skipped/cancelled runs are not failures',
            { completed: 25, successes: 20, failures: 0 },
            25,
            0,
            'Jun 5 · 0 of 25 failed',
        ],
        [
            'a bucket with nothing completed is empty',
            { completed: 0, successes: 0, failures: 0 },
            0,
            0,
            'Jun 5 · no completed runs',
        ],
    ])('workflowFailureSeries: %s', (_label, counts, completed, failures, label) => {
        const series = workflowFailureSeries([{ bucketStart: '2026-06-05', runCount: 30, ...counts }], 'day')
        expect(series).toEqual({ completed: [completed], failures: [failures], labels: [label] })
    })

    it('workflowRuns pairs starts and finishes into per-workflow runs with durations', () => {
        const runs = workflowRuns([
            { kind: 'opened', at: '2026-06-01T00:00:00Z' },
            { kind: 'ci_started', at: '2026-06-01T00:01:00Z', detail: 'Backend CI', run_id: 9001 },
            { kind: 'ci_started', at: '2026-06-01T00:01:30Z', detail: 'Frontend CI' },
            { kind: 'ci_started', at: '2026-06-01T01:00:00Z', detail: 'Backend CI', run_id: 9002 },
            { kind: 'ci_finished', at: '2026-06-01T00:31:00Z', detail: 'Backend CI: failure', run_id: 9001 },
            { kind: 'ci_finished', at: '2026-06-01T01:20:00Z', detail: 'Backend CI: success', run_id: 9002 },
            { kind: 'ci_finished', at: '2026-06-01T00:10:00Z', detail: 'Orphan CI: success', run_id: 9003 },
        ])
        expect(runs).toEqual([
            // First Backend CI start pairs with the first Backend CI finish (FIFO across re-runs).
            {
                workflow: 'Backend CI',
                conclusion: 'failure',
                startedAt: '2026-06-01T00:01:00Z',
                finishedAt: '2026-06-01T00:31:00Z',
                durationSeconds: 1800,
                runId: 9001,
                runAttempt: null,
            },
            {
                workflow: 'Frontend CI',
                conclusion: null,
                startedAt: '2026-06-01T00:01:30Z',
                finishedAt: null,
                durationSeconds: null,
                runId: null,
                runAttempt: null,
            },
            {
                workflow: 'Backend CI',
                conclusion: 'success',
                startedAt: '2026-06-01T01:00:00Z',
                finishedAt: '2026-06-01T01:20:00Z',
                durationSeconds: 1200,
                runId: 9002,
                runAttempt: null,
            },
            // A finish without a matching start (outside the window) still yields a row.
            {
                workflow: 'Orphan CI',
                conclusion: 'success',
                startedAt: null,
                finishedAt: '2026-06-01T00:10:00Z',
                durationSeconds: null,
                runId: 9003,
                runAttempt: null,
            },
        ])
        // The detail page triages: failures first, then still-running, then passes.
        expect(sortRunsForTriage(runs).map((run) => run.conclusion)).toEqual(['failure', null, 'success', 'success'])
    })

    it('groupRunsByCommit groups by head SHA, newest push first', () => {
        const apiRun = (overrides: Partial<WorkflowRunDetailApi>): WorkflowRunDetailApi => ({
            repo: { provider: 'github', owner: 'posthog', name: 'posthog' },
            id: 1,
            workflow_name: 'CI',
            head_sha: 'sha',
            head_branch: 'main',
            status: 'completed',
            conclusion: 'success',
            run_started_at: '2026-06-01T00:00:00Z',
            updated_at: '2026-06-01T00:05:00Z',
            duration_seconds: 300,
            run_attempt: 1,
            pr_number: 10,
            commit_pr_number: null,
            is_merge_queue: false,
            ...overrides,
        })
        const groups = groupRunsByCommit([
            apiRun({ id: 1, head_sha: 'old', run_started_at: '2026-06-01T00:00:00Z' }),
            apiRun({ id: 2, head_sha: 'old', run_started_at: '2026-06-01T00:01:00Z' }),
            apiRun({ id: 3, head_sha: 'new', run_started_at: '2026-06-02T00:00:00Z' }),
        ])
        // Newest push (latest start) first; runs map into WorkflowRun shape under their commit.
        expect(groups.map((g) => g.headSha)).toEqual(['new', 'old'])
        expect(groups[1].runs.map((r) => r.runId)).toEqual([1, 2])
    })

    it.each([
        // A 400 means "connect a source" and must flag notConnected from any loader, else the
        // Workflows scene (which renders no cards) misses the connect prompt. A 500 errors only
        // its own scene, so the other keeps rendering.
        ['cards', 400, { notConnected: true, pullRequestsLoadError: false, workflowHealthLoadError: false }],
        ['workflow health', 400, { notConnected: true, pullRequestsLoadError: false, workflowHealthLoadError: false }],
        ['cards', 500, { notConnected: false, pullRequestsLoadError: true, workflowHealthLoadError: false }],
        ['workflow health', 500, { notConnected: false, pullRequestsLoadError: false, workflowHealthLoadError: true }],
    ])('a %s loader %i sets exactly the right error flags', async (loader, statusCode, expected) => {
        silenceKeaLoadersErrors() // the loader failure is the scenario under test
        const failingMock = loader === 'cards' ? mockCiCards : mockWorkflowHealth
        const failureAction = loader === 'cards' ? 'loadCardsFailure' : 'loadWorkflowHealthFailure'
        failingMock.mockRejectedValue(new ApiError('Connect a GitHub data warehouse source.', statusCode))
        logic = engineeringAnalyticsLogic()
        logic.mount()
        await expectLogic(logic).toDispatchActions([failureAction])

        expect({
            notConnected: logic.values.notConnected,
            pullRequestsLoadError: logic.values.pullRequestsLoadError,
            workflowHealthLoadError: logic.values.workflowHealthLoadError,
        }).toEqual(expected)
    })

    it('maps the trunk quarantine endpoint and filters the tests by team', async () => {
        mockTrunkQuarantine.mockResolvedValue({
            available: true,
            owners_resolved: true,
            ttl_days: 15,
            truncated: true,
            limit: 5000,
            repository: 'PostHog/posthog',
            trunk_url: 'https://app.trunk.io/posthog-inc/flaky-tests?repo=PostHog/posthog',
            teams: [{ owner_team: 'team-replay', test_count: 1, overdue_count: 1, oldest_age_days: 44 }],
            tests: [
                {
                    runner: 'pytest',
                    nodeid: 'a.py::TestA::test_a',
                    file: 'a.py',
                    owner_team: 'team-replay',
                    status: 'flaky',
                    quarantined_at: '2026-05-19T08:00:00Z',
                    age_days: 44,
                    overdue: true,
                    trunk_url: 'https://app.trunk.io/posthog-inc/flaky-tests/test/t-1?repo=PostHog/posthog',
                },
                {
                    runner: 'jest',
                    nodeid: 'b.test.tsx::renders',
                    file: 'b.test.tsx',
                    owner_team: 'unowned',
                    status: 'flaky',
                    quarantined_at: '2026-06-23T08:00:00Z',
                    age_days: 9,
                    overdue: false,
                    trunk_url: null,
                },
            ],
        })
        logic = engineeringAnalyticsLogic()
        logic.mount()
        await expectLogic(logic).toDispatchActions(['loadTrunkQuarantineSuccess'])

        expect(logic.values.trunkQuarantine?.ttlDays).toBe(15)
        expect(logic.values.trunkQuarantine?.truncated).toBe(true)
        expect(logic.values.trunkQuarantine?.limit).toBe(5000)
        expect(logic.values.trunkQuarantine?.repository).toBe('PostHog/posthog')
        expect(logic.values.trunkQuarantine?.trunkUrl).toBe(
            'https://app.trunk.io/posthog-inc/flaky-tests?repo=PostHog/posthog'
        )
        expect(logic.values.trunkQuarantine?.tests[0]).toEqual({
            runner: 'pytest',
            nodeid: 'a.py::TestA::test_a',
            file: 'a.py',
            ownerTeam: 'team-replay',
            status: 'flaky',
            quarantinedAt: '2026-05-19T08:00:00Z',
            ageDays: 44,
            overdue: true,
            trunkUrl: 'https://app.trunk.io/posthog-inc/flaky-tests/test/t-1?repo=PostHog/posthog',
        })
        expect(Object.keys(logic.values.trunkQuarantineTestsByTeam)).toEqual(['team-replay', 'unowned'])
        expect(logic.values.trunkQuarantineTestsByTeam['team-replay'].map((test) => test.nodeid)).toEqual([
            'a.py::TestA::test_a',
        ])
    })

    it.each([
        [400, 'notConnected'],
        [500, 'error'],
    ])('maps a quarantine %i response to %s', async (statusCode, expectedStatus) => {
        silenceKeaLoadersErrors()
        mockTrunkQuarantine.mockRejectedValue(new ApiError('Quarantine request failed.', statusCode))

        logic = engineeringAnalyticsLogic()
        logic.mount()
        await expectLogic(logic).toDispatchActions(['loadTrunkQuarantineFailure'])

        expect(logic.values.trunkQuarantineStatus).toBe(expectedStatus)
    })
})