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.

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

import { ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'

import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { ActivityScope } from '~/types'

import { getChangeSql, getQueryChange, insightHistoryLogic } from './insightHistoryLogic'

const queryChangeItem = {
    id: 'activity-1',
    user: { first_name: 'Jane', last_name: 'Doe', email: '[email protected]' },
    activity: 'updated',
    scope: ActivityScope.INSIGHT,
    item_id: '42',
    detail: {
        name: 'revenue',
        changes: [
            {
                type: 'Insight',
                field: 'query',
                action: 'changed',
                before: { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'SELECT 1' } },
                after: { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'SELECT 2' } },
            },
        ],
    },
    created_at: '2026-07-01T10:00:00Z',
} as unknown as ActivityLogItem

const nameChangeItem = {
    ...queryChangeItem,
    detail: {
        name: 'revenue',
        changes: [{ type: 'Insight', field: 'name', action: 'changed', before: 'old', after: 'revenue' }],
    },
} as unknown as ActivityLogItem

// Chart settings edits touch the query JSON but leave the SQL text untouched
const settingsOnlyChangeItem = {
    ...queryChangeItem,
    detail: {
        name: 'revenue',
        changes: [
            {
                type: 'Insight',
                field: 'query',
                action: 'changed',
                before: {
                    kind: 'DataVisualizationNode',
                    source: { kind: 'HogQLQuery', query: 'SELECT 2' },
                    display: 'ActionsTable',
                },
                after: {
                    kind: 'DataVisualizationNode',
                    source: { kind: 'HogQLQuery', query: 'SELECT 2' },
                    display: 'BoldNumber',
                },
            },
        ],
    },
} as unknown as ActivityLogItem

describe('insightHistoryLogic', () => {
    describe('getChangeSql', () => {
        it.each([
            [{ kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'SELECT 1' } }, 'SELECT 1'],
            [{ source: { query: '   ' } }, null],
            [{ source: {} }, null],
            [{}, null],
            [null, null],
            ['SELECT 1', null],
        ])('extracts SQL from %p as %p', (changeSide, expected) => {
            expect(getChangeSql(changeSide as any)).toEqual(expected)
        })
    })

    describe('getQueryChange', () => {
        it('finds the query change on an item and ignores non-query changes', () => {
            expect(getQueryChange(queryChangeItem)?.field).toEqual('query')
            expect(getQueryChange(nameChangeItem)).toBeNull()
        })

        it('ignores query changes where the SQL text is unchanged (settings-only edits)', () => {
            expect(getQueryChange(settingsOnlyChangeItem)).toBeNull()
        })
    })

    describe('loading', () => {
        let logic: ReturnType<typeof insightHistoryLogic.build>

        beforeEach(() => {
            useMocks({
                get: {
                    '/api/projects/:team_id/activity_log/': () => [
                        200,
                        { results: [settingsOnlyChangeItem, queryChangeItem, nameChangeItem], count: 3, next: null },
                    ],
                },
            })
            initKeaTests()
        })

        afterEach(() => {
            logic?.unmount()
        })

        it('loads activity on mount and only surfaces query-change versions', async () => {
            logic = insightHistoryLogic({ insightId: 42 })
            logic.mount()

            await expectLogic(logic).toDispatchActions(['loadActivity', 'loadActivitySuccess'])

            expect(logic.values.activity).toHaveLength(3)
            expect(logic.values.historyComplete).toBe(true)
            expect(logic.values.versions).toEqual([
                {
                    id: 'activity-1',
                    createdAt: '2026-07-01T10:00:00Z',
                    authorName: 'Jane Doe',
                    email: '[email protected]',
                    isSystem: false,
                    beforeSql: 'SELECT 1',
                    afterSql: 'SELECT 2',
                },
            ])
        })

        it('pages through the full activity log and concatenates results', async () => {
            const fullPage = Array.from({ length: 100 }, () => queryChangeItem)
            useMocks({
                get: {
                    '/api/projects/:team_id/activity_log/': ({ request }) => {
                        const page = Number(new URL(request.url).searchParams.get('page') || '1')
                        return [
                            200,
                            page === 1
                                ? { results: fullPage, count: 101, next: '/api/activity_log/?page=2' }
                                : { results: [nameChangeItem], count: 101, next: null },
                        ]
                    },
                },
            })

            logic = insightHistoryLogic({ insightId: 42 })
            logic.mount()

            await expectLogic(logic).toDispatchActions(['loadActivity', 'loadActivitySuccess'])

            expect(logic.values.activity).toHaveLength(101)
            expect(logic.values.historyComplete).toBe(true)
        })

        it('treats a log ending on an exactly full page as complete', async () => {
            const fullPage = Array.from({ length: 100 }, () => queryChangeItem)
            useMocks({
                get: {
                    '/api/projects/:team_id/activity_log/': ({ request }) => {
                        const page = Number(new URL(request.url).searchParams.get('page') || '1')
                        if (page > 2) {
                            // DRF's paginator 404s past the last page — a length-based
                            // completeness check would request page 3 and blow up here
                            return [404, { detail: 'Invalid page.' }]
                        }
                        return [
                            200,
                            {
                                results: fullPage,
                                count: 200,
                                next: page === 1 ? '/api/activity_log/?page=2' : null,
                            },
                        ]
                    },
                },
            })

            logic = insightHistoryLogic({ insightId: 42 })
            logic.mount()

            await expectLogic(logic).toDispatchActions(['loadActivity', 'loadActivitySuccess'])

            expect(logic.values.activity).toHaveLength(200)
            expect(logic.values.historyComplete).toBe(true)
        })

        it('marks history incomplete when the page cap is hit', async () => {
            const fullPage = Array.from({ length: 100 }, () => queryChangeItem)
            useMocks({
                get: {
                    '/api/projects/:team_id/activity_log/': () => [
                        200,
                        { results: fullPage, count: 5000, next: '/api/activity_log/?page=next' },
                    ],
                },
            })

            logic = insightHistoryLogic({ insightId: 42 })
            logic.mount()

            await expectLogic(logic).toDispatchActions(['loadActivity', 'loadActivitySuccess'])

            expect(logic.values.activity).toHaveLength(1000)
            expect(logic.values.historyComplete).toBe(false)
        })
    })
})