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.

33.4 KB
Raw Blame
import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'

/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */
import { waitFor } from '@testing-library/react'
import { combineUrl, router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
import type { CaptureOptions } from 'posthog-js'

import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'

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

import { OriginProduct, Task, TaskRun, TaskRunStatus } from 'products/posthog_ai/frontend/types/taskTypes'
import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'

import { myClaim } from './__mocks__/inboxMocks'
import { inboxSceneLogic, mergeSignalRuns } from './inboxSceneLogic'
import { inboxBulkActionsLogic } from './logics/inboxBulkActionsLogic'
import { reportListLogic, sectionListLogicProps } from './logics/reportListLogic'
import { SignalReport, SignalReportStatus, SignalScoutRunSummary } from './types'

function openedCalls(spy: jest.SpyInstance): any[][] {
    return spy.mock.calls.filter((call) => call[0] === 'Inbox report opened')
}

function openedEvents(spy: jest.SpyInstance): Record<string, any>[] {
    return openedCalls(spy).map((call) => call[1] as Record<string, any>)
}

function waitForOpenRankRetry(): Promise<void> {
    return new Promise((resolve) => setTimeout(resolve, 400))
}

function scoutRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRunSummary {
    return {
        run_id: 'run-1',
        total_spend: null,
        skill_name: 'signals-scout-error-tracking',
        skill_version: 1,
        status: 'completed',
        metadata: {},
        created_at: '2026-06-11T10:00:00Z',
        started_at: '2026-06-11T10:00:00Z',
        completed_at: null,
        task_id: 'task-scout',
        summary: '',
        emitted_count: 0,
        emitted_finding_ids: [],
        emitted_report_ids: [],
        edited_report_ids: [],
        ...overrides,
    }
}

function signalTask(overrides: Partial<Task> = {}): Task {
    return {
        id: 'task-signal',
        task_number: null,
        slug: '',
        title: 'Crash on login',
        description: '',
        origin_product: OriginProduct.SIGNAL_REPORT,
        runtime: TaskRuntimeEnumApi.Acp,
        repository: null,
        github_integration: null,
        signal_report: 'report-1',
        json_schema: null,
        internal: false,
        latest_run: null,
        created_at: '2026-06-11T09:00:00Z',
        updated_at: '2026-06-11T09:00:00Z',
        created_by: null,
        ...overrides,
    }
}

describe('mergeSignalRuns', () => {
    it('drops scout runs without a backing task_id (they cannot deep-link to a task)', () => {
        const merged = mergeSignalRuns([scoutRun({ task_id: null }), scoutRun({ task_id: 'task-ok' })], [])
        expect(merged.map((r) => r.task_id)).toEqual(['task-ok'])
    })

    it('drops signal tasks with no report link (the scout-authoring CTA threads share the origin)', () => {
        const merged = mergeSignalRuns(
            [],
            [signalTask({ id: 'scout-authoring-chat', title: 'Suggest a scout', signal_report: null })]
        )
        expect(merged).toEqual([])
    })

    it('interleaves scout and signal rows newest-first by created_at', () => {
        const merged = mergeSignalRuns(
            [scoutRun({ task_id: 'scout-old', created_at: '2026-06-10T00:00:00Z' })],
            [signalTask({ id: 'signal-new', created_at: '2026-06-12T00:00:00Z' })]
        )
        expect(merged.map((r) => r.task_id)).toEqual(['signal-new', 'scout-old'])
    })

    it('tags kind and title per source (scout → skill_name, signal → report title)', () => {
        const [scoutRow, signalRow] = mergeSignalRuns(
            [
                scoutRun({
                    task_id: 'scout',
                    skill_name: 'signals-scout-surveys',
                    created_at: '2026-06-11T11:00:00Z',
                    total_spend: 125.25,
                    status: 'in_progress',
                }),
            ],
            [signalTask({ id: 'signal', title: 'Slow query', created_at: '2026-06-11T08:00:00Z' })]
        )
        expect(scoutRow).toMatchObject({
            kind: 'scout',
            title: 'signals-scout-surveys',
            report_id: null,
            total_spend: 125.25,
        })
        expect(signalRow).toMatchObject({ kind: 'signal', title: 'Slow query', report_id: 'report-1' })
    })

    it('falls back to the task timestamp and a null status when a signal task has no run', () => {
        const [row] = mergeSignalRuns([], [signalTask({ latest_run: null, created_at: '2026-06-11T07:00:00Z' })])
        expect(row).toMatchObject({ status: null, created_at: '2026-06-11T07:00:00Z' })
    })

    it("maps the latest run's task status to the scout status string, and uses the run's timestamp", () => {
        const latest_run = {
            status: TaskRunStatus.IN_PROGRESS,
            created_at: '2026-06-11T12:00:00Z',
        } as TaskRun
        const [row] = mergeSignalRuns([], [signalTask({ latest_run, created_at: '2026-06-11T07:00:00Z' })])
        // The `TaskRunStatus` enum is bridged to the equivalent `SignalScoutRunStatus` string the row
        // field holds (here 'in_progress'), and the run's own timestamp wins over the task's.
        expect(row).toMatchObject({ status: 'in_progress', created_at: '2026-06-11T12:00:00Z' })
    })
})

// Slack links, bookmarks, and other products carry `/inbox/<tab>` segments from either layout, so
// each layout has to land the other's segments on its own surface instead of dropping them.
describe('inboxSceneLogic routing', () => {
    let logic: ReturnType<typeof inboxSceneLogic.build>

    beforeEach(() => {
        useMocks({
            get: {
                '/api/projects/:team_id/signals/reports/available_reviewers': {},
                '/api/projects/:team_id/signals/reports/': { results: [], count: 0, next: null, previous: null },
                '/api/projects/:team_id/signals/source_configs/': { results: [] },
                '/api/projects/:team_id/signals/scout/configs/': [],
            },
        })
        // The list-visited flag lives in session storage, so it outlives a test.
        window.sessionStorage.clear()
        initKeaTests()
        featureFlagLogic.mount()
    })

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

    function mountLogic(): void {
        logic = inboxSceneLogic()
        logic.mount()
    }

    it.each<[string, string, string]>([
        ['/inbox/pulls', urls.inbox('reports'), 'reports'],
        ['/inbox/archived', urls.inbox('reports'), 'reports'],
        ['/inbox/config', urls.inbox('settings'), 'settings'],
        ['/inbox/runs', urls.inboxRuns(), 'scouts'],
        ['/inbox/pulls/report-1', urls.inboxReport('reports', 'report-1'), 'reports'],
    ])('old-layout link %s lands on %s', (path, expectedPath, expectedTab) => {
        mountLogic()
        router.actions.push(path)
        expect(router.values.location.pathname.endsWith(expectedPath)).toBe(true)
        expect(logic.values.activeTab).toBe(expectedTab)
    })

    it('a bare /inbox lands on the reports tab', () => {
        mountLogic()
        router.actions.push(urls.inbox())
        expect(logic.values.activeTab).toBe('reports')
    })

    it.each([null, 'report', 'scout'] as const)('opens sources from %s without selecting a report', (surface) => {
        mountLogic()
        if (surface === 'report') {
            router.actions.push(urls.inboxReport('reports', 'report-1'))
        } else if (surface === 'scout') {
            router.actions.push(urls.inboxScout('signals-scout-web-vitals'))
        }
        router.actions.push(urls.inbox('sources'))

        expect(router.values.location.pathname.endsWith('/inbox/sources')).toBe(true)
        expect(logic.values.activeTab).toBe('sources')
        expect(logic.values.selectedReportId).toBeNull()
        expect(logic.values.selectedScoutSkillName).toBeNull()
    })

    it.each(['/inbox', '/inbox/config', '/inbox/settings', '/inbox/sources'])(
        'preserves source setup parameters when returning to %s',
        (path) => {
            mountLogic()
            const searchParams = {
                setup: 'signal-sources',
                signal_source: 'intercom',
                integration_id: '7',
                source: 'saved-filter',
            }
            const hashParams = { tab: 'details' }
            router.actions.push(path, searchParams, hashParams)

            expect(router.values.location.pathname.endsWith('/inbox/sources')).toBe(true)
            expect(logic.values.activeTab).toBe('sources')
            expect(logic.values.selectedReportId).toBeNull()
            expect(router.values.searchParams).toEqual(searchParams)
            expect(router.values.hashParams).toEqual(hashParams)
        }
    )

    // The scout page's tabs live in the URL, so a link to a scout's runs has to survive a reload.
    // Selecting a scout resets the tab, so the URL's tab had to be applied after that reset.
    describe('the scout page tab in the URL', () => {
        it('keeps trials separate from an existing scout named trials', () => {
            mountLogic()
            router.actions.push(urls.inboxScoutTrials())
            expect(logic.values.selectedScoutSkillName).toBeNull()
            expect(router.values.location.pathname.endsWith('/inbox/scout-trials')).toBe(true)
            router.actions.push(urls.inboxScout('trials'))
            expect(logic.values.selectedScoutSkillName).toBe('trials')
            router.actions.push(urls.inboxScout('trials', 'finding-1'))
            expect(logic.values.selectedScoutSkillName).toBe('trials')
            expect(logic.values.selectedScoutFindingId).toBe('finding-1')
        })

        it.each(['runs', 'trials'] as const)('opens the %s tab a reloaded URL names', (tab) => {
            mountLogic()
            router.actions.push(urls.inboxScout('signals-scout-web-vitals'), { tab })
            expect(logic.values.selectedScoutSkillName).toBe('signals-scout-web-vitals')
            expect(logic.values.scoutDetailTab).toBe(tab)
        })

        it('leaves the tab on its default for a bare scout URL', () => {
            mountLogic()
            router.actions.push(urls.inboxScout('signals-scout-web-vitals'))
            expect(logic.values.scoutDetailTab).toBeNull()
        })

        it('ignores a tab the page has no pane for', () => {
            mountLogic()
            router.actions.push(urls.inboxScout('signals-scout-web-vitals'), { tab: 'nonsense' })
            expect(logic.values.scoutDetailTab).toBeNull()
        })

        it.each(['learned', 'trials'] as const)(
            'writes the chosen %s tab to the URL and drops it on the default',
            (tab) => {
                mountLogic()
                router.actions.push(urls.inboxScout('signals-scout-web-vitals'))
                logic.actions.setScoutDetailTab(tab)
                expect(router.values.searchParams.tab).toBe(tab)
                logic.actions.setScoutDetailTab(null)
                expect(router.values.searchParams.tab).toBeUndefined()
            }
        )

        // Hydrating a deep link must not add a history entry, or the first Back press lands on the
        // same page with the same tab and reads as a dead control.
        it.each<[string, string, Record<string, string> | undefined]>([
            ['a tab deep link', urls.inboxScout('signals-scout-web-vitals'), { tab: 'runs' }],
            ['a trials deep link', urls.inboxScout('signals-scout-web-vitals'), { tab: 'trials' }],
            ['a finding deep link', urls.inboxScout('signals-scout-web-vitals', 'finding-1'), undefined],
            [
                'a finding link on another pane',
                urls.inboxScout('signals-scout-web-vitals', 'finding-1'),
                { tab: 'runs' },
            ],
        ])('opens %s with one history entry', (_name, path, searchParams) => {
            mountLogic()
            const push = jest.spyOn(router.actions, 'push')
            router.actions.push(path, searchParams)
            expect(push).toHaveBeenCalledTimes(1)
            push.mockRestore()
        })

        it('opens Signals for a finding deep-link, which is what the link is asking for', () => {
            mountLogic()
            router.actions.push(urls.inboxScout('signals-scout-web-vitals', 'finding-1'))
            expect(logic.values.scoutDetailTab).toBe('signals')
        })

        // A finding opens on Signals, but the reader can move to another pane and share that URL.
        it('opens the pane a finding URL names instead of resetting to Signals', () => {
            mountLogic()
            router.actions.push(urls.inboxScout('signals-scout-web-vitals', 'finding-1'), { tab: 'runs' })
            expect(logic.values.scoutDetailTab).toBe('runs')
            expect(logic.values.selectedScoutFindingId).toBe('finding-1')
        })

        it('records a pane move on a finding page, and drops the param back on Signals', () => {
            mountLogic()
            router.actions.push(urls.inboxScout('signals-scout-web-vitals', 'finding-1'))
            logic.actions.setScoutDetailTab('runs')
            expect(router.values.location.pathname.endsWith('/finding-1')).toBe(true)
            expect(router.values.searchParams.tab).toBe('runs')
            logic.actions.setScoutDetailTab('signals')
            expect(router.values.searchParams.tab).toBeUndefined()
        })
    })

    // The triage card's "Full report" link opens the report by URL (with a triage `back`), not through
    // `openCurrent`, so the open-method must be recovered from that `back` or triage opens split between
    // the `triage` and `click` analytics values.
    it.each<[string, boolean, string]>([
        ['a triage back link records the triage open method', true, 'triage'],
        ['a plain report deep-link is not attributed to triage', false, 'deeplink'],
    ])('%s', async (_name, withTriageBack, expectedMethod) => {
        mountLogic()
        const url = withTriageBack
            ? combineUrl(urls.inboxReport('reports', 'r1'), {
                  back: combineUrl(urls.inboxTriage(), { report: 'r1', at: 0 }).url,
              }).url
            : urls.inboxReport('reports', 'r1')

        let openMethod: string | undefined
        await expectLogic(logic, () => router.actions.push(url)).toDispatchActions([
            (action: any) => {
                if (action.type !== logic.actionTypes.setSelectedReportId) {
                    return false
                }
                openMethod = action.payload.openMethod
                return true
            },
        ])
        expect(openMethod).toBe(expectedMethod)
    })

    // A reload, a new tab, and a bundle update each start a fresh logic. Switching project is a
    // same-tab page load as well, and it keeps session storage, so the marker is per project.
    it.each([
        { where: 'the same project', team: MOCK_DEFAULT_TEAM, expected: 'click' },
        {
            where: 'another project',
            team: { ...MOCK_DEFAULT_TEAM, id: MOCK_DEFAULT_TEAM.id + 1 },
            expected: 'deeplink',
        },
    ])('a report URL loaded fresh in $where after the list was visited reads $expected', async ({ team, expected }) => {
        mountLogic()
        router.actions.push(urls.inbox('reports'))
        logic.unmount()

        initKeaTests(true, team)
        featureFlagLogic.mount()
        mountLogic()

        let openMethod: string | undefined
        await expectLogic(logic, () => router.actions.push(urls.inboxReport('reports', 'r1'))).toDispatchActions([
            (action: any) => {
                if (action.type !== logic.actionTypes.setSelectedReportId) {
                    return false
                }
                openMethod = action.payload.openMethod
                return true
            },
        ])
        expect(openMethod).toBe(expected)
    })

    // A link PostHog wrote names its surface in `link_source`. The product filter keeps `source`. A tab that already saw the list can still
    // open one, and the param leaves the address bar so a copied URL does not pass it on. `link_action` leaves it the same way.
    it.each([
        { name: 'no param', source: undefined, visitedList: false, method: 'deeplink', linkSource: null },
        { name: 'a known source', source: 'slack', visitedList: false, method: 'deeplink', linkSource: 'slack' },
        {
            name: 'the first report email',
            source: 'first_report_email',
            visitedList: false,
            method: 'deeplink',
            linkSource: 'first_report_email',
        },
        {
            name: 'an unknown source',
            source: 'carrier-pigeon',
            visitedList: false,
            method: 'deeplink',
            linkSource: 'other',
        },
        { name: 'a source after the list', source: 'mcp', visitedList: true, method: 'deeplink', linkSource: 'mcp' },
        { name: 'no param after the list', source: undefined, visitedList: true, method: 'click', linkSource: null },
        {
            name: 'the implement action',
            source: 'slack',
            linkAction: 'implement',
            visitedList: false,
            method: 'deeplink',
            linkSource: 'slack',
        },
    ])(
        'a report link with $name opens as $method with link source $linkSource',
        async ({ source, linkAction, visitedList, method, linkSource }) => {
            mountLogic()
            if (visitedList) {
                router.actions.push(urls.inbox('reports'))
            }
            const url = combineUrl(urls.inboxReport('reports', 'r1'), {
                source: 'github',
                ...(source ? { link_source: source } : {}),
                ...(linkAction ? { link_action: linkAction } : {}),
            }).url

            let payload: { openMethod?: string; linkSource?: string | null } = {}
            await expectLogic(logic, () => router.actions.push(url)).toDispatchActions([
                (action: any) => {
                    if (action.type !== logic.actionTypes.setSelectedReportId) {
                        return false
                    }
                    payload = action.payload
                    return true
                },
            ])
            expect(payload).toMatchObject({ openMethod: method, linkSource })
            expect(router.values.searchParams).toEqual({ source: 'github' })
            expect(logic.values.linkImplementReportId).toBe(linkAction ? 'r1' : null)
        }
    )

    // A rank read at open time is null on a cold load, and joins to no impression row. The event is
    // then captured after the wait, so it also has to carry the moment the report opened: a scroll
    // or an action taken during the wait would otherwise read earlier than the open.
    // The detail pane reads the selected report. A claim from its list row must reach it, or the open report
    // keeps offering a claim the user already holds.
    it('shows a claim made from a list row on the open report', () => {
        mountLogic()
        logic.actions.loadSelectedReportSuccess({ id: 'r1', title: 'Crash on login', assignee: null } as SignalReport)

        inboxBulkActionsLogic.actions.reportClaimChanged('r1', myClaim)

        expect(logic.values.selectedReport?.assignee).toEqual(myClaim)
    })

    it('holds `Inbox report opened` until the list answers, then reports the rank and the open time', async () => {
        const report = { id: 'r1', title: 'Crash on login' } as SignalReport
        useMocks({
            get: {
                '/api/projects/:team_id/signals/reports/': {
                    results: [report],
                    count: 1,
                    next: null,
                    previous: null,
                },
            },
        })
        const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
        mountLogic()
        const listLogic = reportListLogic(sectionListLogicProps('needs-decision'))
        listLogic.mount()
        listLogic.actions.loadReports()

        logic.actions.setSelectedReportId('r1', 'deeplink', 'slack')
        const beforeOpen = Date.now()
        logic.actions.loadSelectedReportSuccess(report)
        const afterOpen = Date.now()
        expect(openedEvents(captureSpy)).toHaveLength(0)
        // kea-disposables runs the poll setup again on a resume, and one without a pause leaves the
        // first interval running. That leftover interval must not send the open again on each tick.
        document.dispatchEvent(new Event('visibilitychange'))

        await waitForOpenRankRetry()
        await waitForOpenRankRetry()

        expect(openedEvents(captureSpy)).toHaveLength(1)
        expect(openedEvents(captureSpy)[0]).toMatchObject({
            rank: 1,
            list_size: 1,
            open_method: 'deeplink',
            link_source: 'slack',
        })
        const stampedAt = (openedCalls(captureSpy)[0][2] as CaptureOptions | undefined)?.timestamp?.getTime()
        expect(stampedAt).toBeGreaterThanOrEqual(beforeOpen)
        expect(stampedAt).toBeLessThanOrEqual(afterOpen)
        captureSpy.mockRestore()
        listLogic.unmount()
    })

    // The flat list merges every selected state, so a state that answers late can add rows that sort
    // above the report. Ranking on the first state to answer records a rank that is too small, and
    // the impression side (which waits for all of them) then records a different one.
    it('under the flat list the rank waits for the slower state, not the first one to answer', async () => {
        const opened = { id: 'r1', title: 'Crash on login', priority: 'P2' } as SignalReport
        const higher = { id: 'r2', title: 'Checkout times out', priority: 'P0' } as SignalReport
        let releaseMonitoring = (): void => {}
        const monitoringAnswered = new Promise<void>((resolve) => {
            releaseMonitoring = resolve
        })
        useMocks({
            get: {
                '/api/projects/:team_id/signals/reports/': async ({ request }) => {
                    // Only the monitoring state filters on an open implementation PR.
                    if (new URL(request.url).searchParams.get('has_implementation_pr') === 'true') {
                        await monitoringAnswered
                        return [200, { results: [higher], count: 1, next: null, previous: null }]
                    }
                    return [200, { results: [opened], count: 1, next: null, previous: null }]
                },
            },
        })
        const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
        mountLogic()
        const needsDecision = reportListLogic(sectionListLogicProps('needs-decision'))
        const monitoring = reportListLogic(sectionListLogicProps('monitoring'))
        needsDecision.mount()
        monitoring.mount()
        needsDecision.actions.loadReports()
        monitoring.actions.loadReports()

        logic.actions.setSelectedReportId('r1')
        logic.actions.loadSelectedReportSuccess(opened)

        await waitForOpenRankRetry()
        expect(needsDecision.values.reports).toHaveLength(1)
        expect(openedEvents(captureSpy)).toHaveLength(0)

        releaseMonitoring()
        await waitForOpenRankRetry()

        expect(openedEvents(captureSpy)[0]).toMatchObject({ rank: 2, list_size: 2 })
        captureSpy.mockRestore()
        needsDecision.unmount()
        monitoring.unmount()
    })

    // posthog-js drains its batch queue from its own `pagehide` handler, which is registered before
    // this scene's. An open left to normal batching is enqueued after that drain and never leaves.
    it('a page unload while an open is still waiting sends the open instantly, ahead of the close', () => {
        const report = { id: 'r1', title: 'Crash on login' } as SignalReport
        const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
        mountLogic()

        // No list is mounted, so the rank never resolves and the open stays pending.
        logic.actions.setSelectedReportId('r1')
        logic.actions.loadSelectedReportSuccess(report)
        expect(openedEvents(captureSpy)).toHaveLength(0)

        window.dispatchEvent(new Event('pagehide'))

        const inboxCalls = captureSpy.mock.calls.filter(([name]) =>
            ['Inbox report opened', 'Inbox report closed'].includes(name as string)
        )
        expect(inboxCalls.map(([name]) => name)).toEqual(['Inbox report opened', 'Inbox report closed'])
        // The open also carries its own `timestamp`, so match the option that bypasses the queue.
        expect(inboxCalls[0][2]).toMatchObject({ send_instantly: true })
        expect(inboxCalls[1][2]).toEqual({ send_instantly: true })
        captureSpy.mockRestore()
    })

    it('stops the runs poll when opening another surface closes the panel', () => {
        // Opening a report flips `isRunsOpen` false through a mutual-exclusion reducer, not
        // `setRunsOpen(false)`, so the poll teardown cannot hang off the `setRunsOpen` listener alone
        // or it leaks two requests every few seconds for the rest of the visit.
        mountLogic()
        const clearSpy = jest.spyOn(global, 'clearInterval')

        logic.actions.setRunsOpen(true)
        const clearedBeforeReport = clearSpy.mock.calls.length

        logic.actions.setSelectedReportId('report-1')

        expect(logic.values.isRunsOpen).toBe(false)
        expect(clearSpy.mock.calls.length).toBeGreaterThan(clearedBeforeReport)

        clearSpy.mockRestore()
    })

    describe('keeping the open report current', () => {
        const originalVisibilityState = document.visibilityState

        function setTabVisibility(state: 'visible' | 'hidden'): void {
            Object.defineProperty(document, 'visibilityState', { value: state, configurable: true })
            document.dispatchEvent(new Event('visibilitychange'))
        }

        // The first fetch always answers `ready`; later fetches answer `refreshedStatus`, so a test can
        // move the report's state server-side between the initial load and the visibility refresh.
        function mockReportGet(refreshedStatus: SignalReportStatus = SignalReportStatus.READY): jest.Mock {
            let fetches = 0
            const reportGet = jest.fn(() => [
                200,
                {
                    id: 'report-1',
                    title: 'Crash on login',
                    status: fetches++ === 0 ? SignalReportStatus.READY : refreshedStatus,
                },
            ])
            // Pinned to the report's own path: a `:id` pattern would also swallow `available_reviewers/`.
            useMocks({
                get: { '/api/projects/:team_id/signals/reports/report-1/': reportGet },
                post: { '/api/projects/:team_id/signals/reports/:id/viewed/': [204, null] },
            })
            return reportGet
        }

        afterEach(() => {
            Object.defineProperty(document, 'visibilityState', {
                value: originalVisibilityState,
                configurable: true,
            })
        })

        it('re-fetches the open report when the tab becomes visible again', async () => {
            const reportGet = mockReportGet()
            mountLogic()
            logic.actions.setSelectedReportId('report-1')
            await expectLogic(logic).toDispatchActions(['loadSelectedReportSuccess'])
            expect(reportGet).toHaveBeenCalledTimes(1)

            setTabVisibility('visible')

            await expectLogic(logic).toDispatchActions(['loadSelectedReport', 'loadSelectedReportSuccess'])
            expect(reportGet).toHaveBeenCalledTimes(2)
        })

        it('does not re-fetch while the tab is hidden, nor with no report open', async () => {
            const reportGet = mockReportGet()
            mountLogic()
            logic.actions.setSelectedReportId('report-1')
            await expectLogic(logic).toDispatchActions(['loadSelectedReportSuccess'])

            setTabVisibility('hidden')
            logic.actions.setSelectedReportId(null)
            setTabVisibility('visible')

            await expectLogic(logic).toNotHaveDispatchedActions(['loadSelectedReport'])
            expect(reportGet).toHaveBeenCalledTimes(1)
        })

        it('ignores a visibility callback captured before the scene unmounts', async () => {
            const reportGet = mockReportGet()
            const addEventListenerSpy = jest.spyOn(document, 'addEventListener')
            const removeEventListenerSpy = jest.spyOn(document, 'removeEventListener')
            try {
                mountLogic()
                logic.actions.setSelectedReportId('report-1')
                await expectLogic(logic).toDispatchActions(['loadSelectedReportSuccess'])

                const onVisibilityChange = addEventListenerSpy.mock.calls.find(
                    ([eventName]) => eventName === 'visibilitychange'
                )?.[1]
                if (typeof onVisibilityChange !== 'function') {
                    throw new Error('Expected the report refresh visibility listener to be registered')
                }

                logic.unmount()
                expect(removeEventListenerSpy).toHaveBeenCalledWith('visibilitychange', onVisibilityChange)
                expect(() => onVisibilityChange(new Event('visibilitychange'))).not.toThrow()
                await expectLogic(logic).toNotHaveDispatchedActions(['loadSelectedReport'])
                expect(reportGet).toHaveBeenCalledTimes(1)
            } finally {
                addEventListenerSpy.mockRestore()
                removeEventListenerSpy.mockRestore()
            }
        })

        // A write that timed out or lost its response can still have saved, so the open report must not keep its
        // local copy. A failure on another report must not refetch this one.
        test.each([
            { failedReportId: 'report-1', fetches: 2 },
            { failedReportId: 'report-2', fetches: 1 },
        ])(
            'a failed write on $failedReportId fetches the open report $fetches times',
            async ({ failedReportId, fetches }) => {
                const reportGet = mockReportGet()
                mountLogic()
                logic.actions.setSelectedReportId('report-1')
                await expectLogic(logic).toDispatchActions(['loadSelectedReportSuccess'])

                inboxBulkActionsLogic.actions.reportWriteFailed([failedReportId])
                await expectLogic(logic).toFinishAllListeners()

                expect(reportGet).toHaveBeenCalledTimes(fetches)
            }
        )

        it('keeps a claim made while a refresh is in flight, and takes the other fields from the refresh', async () => {
            let releaseRefresh: () => void = () => {}
            const heldRefresh = new Promise<void>((resolve) => {
                releaseRefresh = resolve
            })
            let fetches = 0
            const reportGet = jest.fn(async () => {
                if (fetches++ === 0) {
                    return [200, { id: 'report-1', title: 'Crash on login', status: SignalReportStatus.READY }]
                }
                await heldRefresh
                return [
                    200,
                    { id: 'report-1', title: 'Crash on login after refresh', status: SignalReportStatus.READY },
                ]
            })
            useMocks({
                get: { '/api/projects/:team_id/signals/reports/report-1/': reportGet },
                post: { '/api/projects/:team_id/signals/reports/:id/viewed/': [204, null] },
            })
            mountLogic()
            logic.actions.setSelectedReportId('report-1')
            await expectLogic(logic).toDispatchActions(['loadSelectedReportSuccess'])

            setTabVisibility('visible')
            await waitFor(() => expect(reportGet).toHaveBeenCalledTimes(2))
            inboxBulkActionsLogic.actions.reportClaimChanged('report-1', myClaim)
            releaseRefresh()
            await expectLogic(logic).toDispatchActions(['loadSelectedReportSuccess'])

            expect(logic.values.selectedReport).toMatchObject({
                title: 'Crash on login after refresh',
                assignee: myClaim,
            })
        })

        // The lists behind the detail pane reconcile only on `reportStateChanged`, so a refresh that
        // lands a new status has to broadcast it. An unconditional broadcast is just as wrong: every
        // tab return would refresh every mounted section and the refund summary.
        test.each([
            {
                case: 'broadcasts when the refresh lands a new status',
                refreshedStatus: SignalReportStatus.SUPPRESSED,
                broadcasts: true,
            },
            {
                case: 'stays quiet when the refresh lands the same status',
                refreshedStatus: SignalReportStatus.READY,
                broadcasts: false,
            },
        ])('$case', async ({ refreshedStatus, broadcasts }) => {
            mockReportGet(refreshedStatus)
            mountLogic()
            logic.actions.setSelectedReportId('report-1')
            await expectLogic(logic).toDispatchActions(['loadSelectedReportSuccess'])

            setTabVisibility('visible')

            await expectLogic(logic).toDispatchActions(['loadSelectedReportSuccess'])
            expect(logic.values.selectedReport?.status).toBe(refreshedStatus)
            const broadcast = [inboxBulkActionsLogic.actionTypes.reportStateChanged]
            await (broadcasts
                ? expectLogic(logic).toDispatchActions(broadcast)
                : expectLogic(logic).toNotHaveDispatchedActions(broadcast))
        })
    })
})