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.

13.1 KB
Raw Blame
import { expectLogic } from 'kea-test-utils'

import api from 'lib/api'

import { initKeaTests } from '~/test/init'
import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'

import { type DailyToolStat, buildDailyChartData, mcpAnalyticsToolDetailLogic } from './mcpAnalyticsToolDetailLogic'

jest.mock('lib/api')

const mockApi = api as jest.Mocked<typeof api>

function stat(overrides: Partial<DailyToolStat> & { day: string }): DailyToolStat {
    return {
        calls: 0,
        errors: 0,
        p50: 0,
        p95: 0,
        users: 0,
        sessions: 0,
        ...overrides,
    }
}

describe('buildDailyChartData', () => {
    it('returns empty series for no rows, so the empty state shows', () => {
        expect(buildDailyChartData([], ['2026-06-01 00:00:00'])).toEqual({
            labels: [],
            calls: [],
            errors: [],
            p50: [],
            p95: [],
            users: [],
            sessions: [],
        })
    })

    // Guards the "sparklines lose their line" regression: with one active day, projecting onto the
    // full window's day keys pads the axis out (counts→0, latency→NaN) so the line still renders.
    it('projects rows onto day bucket keys, padding empty days', () => {
        const rows = [stat({ day: '2026-06-03', calls: 5, errors: 0, p50: 50, p95: 150, users: 1, sessions: 1 })]
        const keys = ['2026-06-01 00:00:00', '2026-06-02 00:00:00', '2026-06-03 00:00:00', '2026-06-04 00:00:00']
        expect(buildDailyChartData(rows, keys)).toEqual({
            labels: keys,
            calls: [0, 0, 5, 0],
            errors: [0, 0, 0, 0],
            p50: [NaN, NaN, 50, NaN],
            p95: [NaN, NaN, 150, NaN],
            users: [0, 0, 1, 0],
            sessions: [0, 0, 1, 0],
        })
    })

    // Sub-day windows bucket by hour: hourly rows must line up with hourly keys, so "12 hours
    // collapses to a single point" can't come back.
    it('lines up hourly rows with hourly bucket keys', () => {
        const rows = [
            stat({ day: '2026-06-03 10:00:00', calls: 12, errors: 2, p50: 80, p95: 200, users: 4, sessions: 5 }),
        ]
        const keys = ['2026-06-03 09:00:00', '2026-06-03 10:00:00', '2026-06-03 11:00:00']
        const data = buildDailyChartData(rows, keys)
        expect(data.calls).toEqual([0, 12, 0])
        expect(data.p95).toEqual([NaN, 200, NaN])
        expect(data.sessions).toEqual([0, 5, 0])
    })
})

describe('incompleteTail', () => {
    beforeEach(() => {
        jest.clearAllMocks()
        initKeaTests()
        jest.spyOn(mockApi, 'query').mockResolvedValue({ results: [] })
    })

    // An open-ended relative window always ends in the bucket that is still collecting, and a window
    // that closed in the past never does, so this holds whenever the suite runs.
    it.each([
        ['an open-ended window', '-30d', null, true],
        ['a window that already closed', '2026-06-01', '2026-06-10', false],
    ])('is %s: %s', async (_label, dateFrom, dateTo, expected) => {
        const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })
        logic.mount()
        await expectLogic(logic, () => {
            logic.actions.setDateFilter(dateFrom, dateTo)
        }).toFinishAllListeners()
        // Seeded directly: with no rows the chart data short-circuits to empty, and an empty axis
        // has no tail to dash either way.
        logic.actions.loadDailyStatsSuccess([stat({ day: '2026-06-02 00:00:00', calls: 1 })])

        expect(logic.values.incompleteTail).toBe(expected)
    })
})

describe('failure drill-down', () => {
    beforeEach(() => {
        jest.clearAllMocks()
        initKeaTests()
        jest.spyOn(mockApi, 'query').mockResolvedValue({ results: [] })
    })

    // The occurrences query must receive the bucket's RAW parts (not the composed display
    // label), and the no-status bucket must omit errorStatus so the backend's
    // "only events without a status" branch applies.
    it.each([
        ['statused bucket', '500', '500'],
        ['no-status bucket', '', undefined],
    ])(
        'selecting a %s queries occurrences with raw bucket params and stores the results',
        async (_label, bucketStatus, expectedStatus) => {
            const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })
            logic.mount()
            const occurrence = {
                timestamp: '2026-07-15 00:00:00',
                distinct_id: 'd1',
                session_id: 's1',
                harness: 'Claude Code',
                intent: '',
                error_message: 'boom: table not found',
                error_status: bucketStatus,
            }
            mockApi.query.mockClear()
            jest.spyOn(mockApi, 'query').mockResolvedValue({ results: [occurrence] })

            await expectLogic(logic, () => {
                logic.actions.selectFailure({
                    message: 'api_5xx (HTTP 500)',
                    error_type: 'api_5xx',
                    error_status: bucketStatus,
                    occurrences: 2,
                    last_seen: '2026-07-15 00:00:00',
                    harnesses: [],
                })
            }).toDispatchActions(['loadFailureOccurrences', 'loadFailureOccurrencesSuccess'])

            expect(mockApi.query).toHaveBeenCalledWith(
                expect.objectContaining({
                    kind: 'MCPToolFailureOccurrencesQuery',
                    toolName: 'query_run',
                    errorType: 'api_5xx',
                    errorStatus: expectedStatus,
                })
            )
            expect(logic.values.failureOccurrences).toEqual([occurrence])
        }
    )

    // Guards the stale-response race: bucket A selected, then bucket B before A resolves.
    // Without the loader breakpoint, A's late response would overwrite B's occurrences
    // while the modal header still shows B.
    it.each(['select another bucket', 'deselect'])('discards a pending failure load on %s', async (change) => {
        const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })
        logic.mount()
        const occurrenceFor = (id: string): Record<string, string> => ({
            timestamp: '2026-07-15 00:00:00',
            distinct_id: id,
            session_id: 's1',
            harness: 'Claude Code',
            intent: '',
            error_message: `boom from ${id}`,
            error_status: '',
        })
        let resolveSlowA: (value: unknown) => void = () => {}
        const slowA = new Promise((resolve) => {
            resolveSlowA = resolve
        })
        jest.spyOn(mockApi, 'query')
            .mockImplementationOnce(() => slowA as any)
            .mockImplementationOnce(() => Promise.resolve({ results: [occurrenceFor('bucketB')] }))

        const bucket = (errorType: string): any => ({
            message: errorType,
            error_type: errorType,
            error_status: '',
            occurrences: 1,
            last_seen: '2026-07-15 00:00:00',
            harnesses: [],
        })
        await expectLogic(logic, () => {
            logic.actions.selectFailure(bucket('api_5xx'))
            if (change === 'select another bucket') {
                logic.actions.selectFailure(bucket('internal'))
            } else {
                logic.actions.selectFailure(null)
            }
        }).toMatchValues({ selectedFailure: change === 'deselect' ? null : bucket('internal') })
        const expected = change === 'deselect' ? [] : [occurrenceFor('bucketB')]
        if (change === 'select another bucket') {
            await expectLogic(logic).toMatchValues({ failureOccurrences: expected })
        }

        // Bucket A's request resolves late — its stale result must be discarded.
        await expectLogic(logic, () => {
            resolveSlowA({ results: [occurrenceFor('bucketA')] })
        }).toFinishAllListeners()
        expect(logic.values.failureOccurrences).toEqual(expected)
    })

    it.each(['deselect', 'properties', 'test accounts'])('clears the open failure on %s', async (change) => {
        const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })
        logic.mount()
        jest.spyOn(mockApi, 'query').mockResolvedValue({
            results: [
                {
                    timestamp: '2026-07-15 00:00:00',
                    distinct_id: 'd1',
                    session_id: 's1',
                    harness: 'Claude Code',
                    intent: '',
                    error_message: 'boom',
                    error_status: '',
                },
            ],
        })

        await expectLogic(logic, () => {
            logic.actions.selectFailure({
                message: 'internal',
                error_type: 'internal',
                error_status: '',
                occurrences: 1,
                last_seen: '2026-07-15 00:00:00',
                harnesses: [],
            })
        }).toDispatchActions(['loadFailureOccurrencesSuccess'])

        await expectLogic(logic, () => {
            if (change === 'properties') {
                logic.actions.setPropertyFilters([
                    {
                        key: '$mcp_tool_name',
                        value: ['query_run'],
                        operator: PropertyOperator.Exact,
                        type: PropertyFilterType.Event,
                    },
                ])
            } else if (change === 'test accounts') {
                logic.actions.setFilterTestAccounts(true)
            } else {
                logic.actions.selectFailure(null)
            }
        }).toMatchValues({ selectedFailure: null, failureOccurrences: [] })
    })
})

describe('shared filter wiring', () => {
    beforeEach(() => {
        jest.clearAllMocks()
        initKeaTests()
        jest.spyOn(mockApi, 'query').mockResolvedValue({ results: [] })
    })

    function queryCallsSince(callIndex: number): Record<string, any>[] {
        return mockApi.query.mock.calls.slice(callIndex).map((call) => call[0] as any)
    }

    const EVENT_FILTER: AnyPropertyFilter = {
        key: '$mcp_tool_name',
        value: ['query_run'],
        operator: PropertyOperator.Exact,
        type: PropertyFilterType.Event,
    }

    it('spreads the shared property filters into every section query and reloads on change', async () => {
        const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })
        logic.mount()
        await expectLogic(logic, () => {
            logic.actions.loadAllSections()
        }).toFinishAllListeners()
        const callsBefore = mockApi.query.mock.calls.length

        await expectLogic(logic, () => {
            logic.actions.setPropertyFilters([EVENT_FILTER])
        }).toFinishAllListeners()

        const reloads = queryCallsSince(callsBefore)
        expect(reloads.length).toBe(10)
        expect(reloads.every((call) => JSON.stringify(call.properties) === JSON.stringify([EVENT_FILTER]))).toBe(true)
    })

    it('spreads filterTestAccounts into every section query and reloads on change', async () => {
        const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })
        logic.mount()
        await expectLogic(logic, () => {
            logic.actions.loadAllSections()
        }).toFinishAllListeners()
        const callsBefore = mockApi.query.mock.calls.length

        await expectLogic(logic, () => {
            logic.actions.setFilterTestAccounts(true)
        }).toFinishAllListeners()

        const reloads = queryCallsSince(callsBefore)
        expect(reloads.length).toBe(10)
        expect(reloads.every((call) => call.filterTestAccounts === true)).toBe(true)
    })

    it('reloads sections once when both shared filters hydrate from the URL', async () => {
        const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })
        logic.mount()
        await expectLogic(logic, () => logic.actions.loadAllSections()).toFinishAllListeners()
        const callsBefore = mockApi.query.mock.calls.length

        await expectLogic(logic, () => logic.actions.hydrateFilters(true, [EVENT_FILTER])).toFinishAllListeners()

        const reloads = queryCallsSince(callsBefore)
        expect(reloads).toHaveLength(10)
        expect(reloads.every((call) => call.filterTestAccounts === true)).toBe(true)
        expect(reloads.every((call) => JSON.stringify(call.properties) === JSON.stringify([EVENT_FILTER]))).toBe(true)
    })

    it('discards a superseded summary response so a slow earlier request cannot overwrite it', async () => {
        const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })
        logic.mount()

        let resolveSlow: (value: unknown) => void = () => {}
        const slow = new Promise((resolve) => {
            resolveSlow = resolve
        })
        jest.spyOn(mockApi, 'query')
            .mockImplementationOnce(() => slow as any)
            .mockImplementationOnce(() => Promise.resolve({ results: [{ calls: 42 }] }))

        await expectLogic(logic, () => {
            logic.actions.loadSummary()
            logic.actions.loadSummary()
        }).toDispatchActions(['loadSummarySuccess'])

        expect(logic.values.summary?.calls).toBe(42)

        resolveSlow({ results: [{ calls: 1 }] })
        await new Promise((resolve) => setTimeout(resolve, 0))
        expect(logic.values.summary?.calls).toBe(42)
    })
})