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.

30.4 KB
Raw Blame
import { MOCK_DEFAULT_USER } from 'lib/api.mock'

import { router } from 'kea-router'
import { expectLogic, truth } from 'kea-test-utils'

import { moveToLogic } from 'lib/components/FileSystem/MoveTo/moveToLogic'
import {
    DashboardsFilters,
    DashboardsTab,
    DEFAULT_FILTERS,
    dashboardsLogic,
} from 'scenes/dashboard/dashboards/dashboardsLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'

import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { useMocks } from '~/mocks/jest'
import { dashboardsModel } from '~/models/dashboardsModel'
import { initKeaTests } from '~/test/init'
import { AppContext, DashboardType, UserBasicType } from '~/types'

import dashboardJson from 'products/dashboards/frontend/__mocks__/dashboard.json'
import * as generatedApi from 'products/dashboards/frontend/generated/api'
import type { DashboardBulkDeleteResponseApi } from 'products/dashboards/frontend/generated/api.schemas'

let dashboardId = 1234
const dashboard = (extras: Partial<DashboardType>): DashboardType => {
    dashboardId = dashboardId + 1
    return {
        ...dashboardJson,
        id: dashboardId,
        name: 'Test dashboard: ' + dashboardId,
        ...extras,
    } as any as DashboardType
}

const blankScene = (): any => ({ scene: { component: () => null, logic: null } })
const scenes: any = { [Scene.Dashboards]: blankScene }

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

    it('removes deleted dashboards from the list and keeps skipped dashboards selected', async () => {
        const [first, second] = allDashboards
        useMocks({
            post: {
                '/api/projects/:team_id/dashboards/bulk_delete/': {
                    deleted: [first.id],
                    skipped: [{ id: second.id, reason: 'No permission' }],
                },
            },
        })
        const onStillSelected = jest.fn()
        await expectLogic(logic, () =>
            logic.actions.bulkDeleteDashboards({ ids: [first.id, second.id], onStillSelected })
        ).toDispatchActions(['bulkDeleteDashboardsSuccess'])
        expect(onStillSelected).toHaveBeenCalledWith([second.id])
        expect(logic.values.dashboards.map(({ id }) => id)).not.toContain(first.id)
        expect(logic.values.dashboards.map(({ id }) => id)).toContain(second.id)
    })

    it('reconciles bulk deletion after the dashboard scene unmounts', async () => {
        const [first, second] = allDashboards
        let finishRequest: (response: DashboardBulkDeleteResponseApi) => void
        const request = new Promise<DashboardBulkDeleteResponseApi>((resolve) => {
            finishRequest = resolve
        })
        const deleteSpy = jest.spyOn(generatedApi, 'dashboardsBulkDeleteCreate').mockReturnValueOnce(request)
        try {
            logic.actions.bulkDeleteDashboards({ ids: [first.id], onStillSelected: jest.fn() })
            logic.unmount()
            await expectLogic(dashboardsModel, () =>
                finishRequest!({ deleted: [first.id], skipped: [] })
            ).toDispatchActions(['bulkDeleteDashboardsSuccess', 'removeDashboardsFromCache'])
            logic.mount()
            expect(logic.values.dashboards.map(({ id }) => id)).not.toContain(first.id)
            expect(logic.values.dashboards.map(({ id }) => id)).toContain(second.id)
        } finally {
            deleteSpy.mockRestore()
        }
    })

    it.each([false, true])('removes stale search rows when refresh fails (bulk failure: %s)', async (bulkFails) => {
        const [first, second] = allDashboards
        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': { count: 2, results: [first, second], next: null },
            },
        })
        await expectLogic(logic, () => logic.actions.setSearch('Test')).toDispatchActions([
            'loadSearchedDashboardsSuccess',
        ])
        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': ({ request }) => {
                    if (new URL(request.url).searchParams.get('search')) {
                        return [500, { detail: 'Search unavailable' }]
                    }
                    return [200, { count: 1, results: [second], next: null, previous: null }]
                },
            },
            post: {
                '/api/projects/:team_id/dashboards/bulk_delete/': () =>
                    bulkFails
                        ? [500, { detail: 'Response unavailable' }]
                        : [200, { deleted: [first.id], skipped: [{ id: second.id, reason: 'No permission' }] }],
            },
        })
        const onStillSelected = jest.fn()
        await expectLogic(logic, () =>
            logic.actions.bulkDeleteDashboards({ ids: [first.id, second.id], onStillSelected })
        ).toDispatchActions(['loadSearchedDashboardsFailure'])
        expect(logic.values.searchedDashboards?.map(({ id }) => id)).toEqual([second.id])
        expect(logic.values.dashboards.map(({ id }) => id)).toEqual([second.id])
        expect(onStillSelected).toHaveBeenCalledWith([second.id])
    })

    const CURRENT_USER = { id: 178, uuid: 'USER_UUID' } as UserBasicType
    const OTHER_USER = { id: 2, uuid: 'user2' } as UserBasicType

    const allDashboards = [
        { ...dashboard({ created_by: CURRENT_USER, is_shared: true }) },
        { ...dashboard({ created_by: CURRENT_USER, pinned: true }) },
        { ...dashboard({ created_by: OTHER_USER, pinned: true }) },
        {
            ...dashboard({
                created_by: CURRENT_USER,
                is_shared: true,
                pinned: true,
            }),
        },
        {
            ...dashboard({
                created_by: CURRENT_USER,
                folder: 'Marketing/Website',
                file_system_id: 'fs-filed',
                file_system_path: 'Marketing/Website/Filed',
            }),
        },
        {
            ...dashboard({
                created_by: OTHER_USER,
                name: 'needle',
                folder: 'Marketing/Website',
                file_system_id: 'fs-needle',
                file_system_path: 'Marketing/Website/needle',
            }),
        },
        {
            ...dashboard({
                created_by: CURRENT_USER,
                name: 'VMS Feature - History Browser - Nova',
            }),
        },
    ]

    beforeEach(async () => {
        jest.clearAllMocks()
        localStorage.clear()
        window.POSTHOG_APP_CONTEXT = { current_user: MOCK_DEFAULT_USER } as unknown as AppContext

        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': {
                    count: 7,
                    next: null,
                    previous: null,
                    results: allDashboards,
                },
            },
        })

        initKeaTests()

        dashboardsModel.mount()
        await expectLogic(dashboardsModel, () => dashboardsModel.actions.loadDashboardsIfNeeded()).toDispatchActions([
            'loadDashboardsSuccess',
        ])
        sceneLogic({ scenes }).mount()

        logic = dashboardsLogic({ tabId: '1' })
        logic.mount()
    })

    it('restores list filters after navigating away and returning', async () => {
        await expectLogic(logic, () => {
            logic.actions.setFilters({ createdBy: [OTHER_USER.id], pinned: true, shared: true, tags: ['finance'] })
        }).toFinishAllListeners()

        logic.unmount()
        router.actions.push('/settings')
        router.actions.push('/dashboard')

        logic = dashboardsLogic({ tabId: '1' })
        logic.mount()

        await expectLogic(logic).toFinishAllListeners()

        expect(logic.values.filters).toEqual(
            expect.objectContaining({ createdBy: [OTHER_USER.id], pinned: true, shared: true, tags: ['finance'] })
        )
        expect(router.values.searchParams).toEqual(
            expect.objectContaining({ created_by: [OTHER_USER.id], pinned: true, shared: true, tags: ['finance'] })
        )
    })

    it('does not restore filters saved by another user', async () => {
        await expectLogic(logic, () => {
            logic.actions.setFilters({ pinned: true })
        }).toFinishAllListeners()

        logic.unmount()
        window.POSTHOG_APP_CONTEXT = {
            ...window.POSTHOG_APP_CONTEXT,
            current_user: { ...MOCK_DEFAULT_USER, uuid: 'ANOTHER_USER_UUID' },
        } as unknown as AppContext
        router.actions.push('/settings')
        router.actions.push('/dashboard')

        logic = dashboardsLogic({ tabId: '1' })
        logic.mount()

        await expectLogic(logic).toFinishAllListeners()

        expect(logic.values.filters).toEqual(DEFAULT_FILTERS)
    })

    it('clears the created by filter when switching to my dashboards', async () => {
        await expectLogic(logic, () => {
            logic.actions.setFilters({ createdBy: [OTHER_USER.id] })
        }).toFinishAllListeners()

        await expectLogic(logic, () => {
            logic.actions.setCurrentTab(DashboardsTab.Yours)
        }).toFinishAllListeners()

        expect(logic.values.filters.createdBy).toBe('All users')
        expect(router.values.searchParams.created_by).toBeUndefined()
    })

    it('replaces tag results for a new search and appends the next page', async () => {
        await expectLogic(logic, () => {
            logic.actions.loadTagResultsSuccess(
                { next: 'next-page', previous: null, results: ['alpha', 'beta'] },
                { search: '', offset: 0 }
            )
        }).toMatchValues({ hasMoreTagResults: true, tagResults: ['alpha', 'beta'] })

        await expectLogic(logic, () => {
            logic.actions.loadTagResultsSuccess(
                { next: null, previous: 'previous-page', results: ['gamma'] },
                { search: '', offset: 2 }
            )
        }).toMatchValues({ hasMoreTagResults: false, tagResults: ['alpha', 'beta', 'gamma'] })
    })

    describe('reflecting a completed move', () => {
        it('updates the moved dashboard to its new folder', async () => {
            await expectLogic(logic, () => {
                projectTreeDataLogic.actions.movedItem(
                    { id: 'fs-1', type: 'dashboard', ref: String(dashboardId), path: 'Marketing/A' } as any,
                    'Marketing/A',
                    'Revenue/Q3/A'
                )
            }).toDispatchActions([
                dashboardsModel.actionCreators.patchDashboardFolders({ [dashboardId]: 'Revenue/Q3/A' }),
            ])
        })

        it('moves a dashboard to the project root', async () => {
            await expectLogic(logic, () => {
                projectTreeDataLogic.actions.movedItem(
                    { id: 'fs-1', type: 'dashboard', ref: String(dashboardId), path: 'Marketing/A' } as any,
                    'Marketing/A',
                    'A'
                )
            }).toDispatchActions([dashboardsModel.actionCreators.patchDashboardFolders({ [dashboardId]: 'A' })])
        })

        it('hands a moved folder to the model to re-parent', async () => {
            await expectLogic(logic, () => {
                projectTreeDataLogic.actions.movedItem(
                    { id: 'fs-3', type: 'folder', path: 'Marketing' } as any,
                    'Marketing',
                    'Revenue/Marketing'
                )
            }).toDispatchActions([
                dashboardsModel.actionCreators.reparentDashboardFolders('Marketing', 'Revenue/Marketing'),
            ])
        })

        it('ignores a moved shortcut, which only points at the dashboard', async () => {
            const before = dashboardsModel.values.rawDashboards
            projectTreeDataLogic.actions.movedItem(
                {
                    id: 'fs-4',
                    type: 'dashboard',
                    ref: String(dashboardId),
                    path: 'Marketing/A',
                    shortcut: true,
                } as any,
                'Marketing/A',
                'Revenue/A'
            )
            expect(dashboardsModel.values.rawDashboards).toBe(before)
        })

        it('ignores moves of other item types', async () => {
            const before = dashboardsModel.values.rawDashboards
            projectTreeDataLogic.actions.movedItem(
                { id: 'fs-2', type: 'insight', ref: String(dashboardId), path: 'Marketing/An insight' } as any,
                'Marketing/An insight',
                'Revenue/An insight'
            )
            expect(dashboardsModel.values.rawDashboards).toBe(before)
        })
    })

    it('shows all dashboards when no filters', async () => {
        expect(logic.values.dashboards).toHaveLength(allDashboards.length)
    })

    it('shows correct dashboards when on pinned tab', async () => {
        expectLogic(logic, () => {
            logic.actions.setCurrentTab(DashboardsTab.Pinned)
        }).toMatchValues({
            dashboards: truth((dashboards: DashboardType[]) => {
                return dashboards.length === 3 && dashboards.every((d) => d.pinned)
            }),
        })
    })

    it('shows correct dashboards when on my tab', async () => {
        expectLogic(logic, () => {
            logic.actions.setCurrentTab(DashboardsTab.Yours)
        }).toMatchValues({
            dashboards: truth((dashboards: DashboardType[]) => {
                return dashboards.length === 5 && dashboards.every((d) => d.created_by?.uuid === 'USER_UUID')
            }),
        })
    })

    it('shows correct dashboards when filtering by name', async () => {
        expectLogic(logic, () => {
            logic.actions.setFilters({ createdBy: [OTHER_USER.id] })
        }).toMatchValues({
            dashboards: truth((dashboards: DashboardType[]) => {
                return (
                    dashboards.length === 2 &&
                    dashboards[0].created_by?.uuid === 'user2' &&
                    dashboards[1].created_by?.uuid === 'user2'
                )
            }),
        })
    })

    it('filters client-side by folder when no search is active', async () => {
        const inFolder = allDashboards.filter((d) => (d as DashboardType).folder === 'Marketing/Website')
        expectLogic(logic, () => {
            logic.actions.setFilters({ folder: 'Marketing/Website' })
        }).toMatchValues({
            dashboards: truth(
                (dashboards: DashboardType[]) =>
                    dashboards.length === inFolder.length && dashboards.every((d) => d.folder === 'Marketing/Website')
            ),
        })
    })

    it('shows dashboards from all selected creators when multiple are chosen', async () => {
        // Multi-select is a union: selecting both users returns every dashboard, since each was
        // created by one of them.
        expectLogic(logic, () => {
            logic.actions.setFilters({ createdBy: [CURRENT_USER.id, OTHER_USER.id] })
        }).toMatchValues({
            dashboards: truth((dashboards: DashboardType[]) => dashboards.length === allDashboards.length),
        })
    })

    it('shows correct dashboards when filtering by name and shared', async () => {
        expectLogic(logic, () => {
            logic.actions.setFilters({ createdBy: [OTHER_USER.id], shared: true })
        }).toMatchValues({
            dashboards: [],
        })
    })

    it('shows correct dashboards when filtering by name and on pinned tab', async () => {
        expectLogic(logic, () => {
            logic.actions.setCurrentTab(DashboardsTab.Pinned)
            logic.actions.setFilters({ createdBy: [OTHER_USER.id] })
        }).toMatchValues({
            dashboards: truth((dashboards: DashboardType[]) => {
                return dashboards.length === 1 && dashboards[0].pinned
            }),
        })
    })

    it('shows correct dashboards filtering by shared and on pinned tab', async () => {
        expectLogic(logic, () => {
            logic.actions.setCurrentTab(DashboardsTab.Pinned)
            logic.actions.setFilters({ shared: true })
        }).toMatchValues({
            dashboards: truth((dashboards: DashboardType[]) => {
                return (
                    dashboards.length === 1 &&
                    dashboards.every((d) => d.pinned && d.is_shared) &&
                    dashboards[0].created_by?.uuid === 'USER_UUID'
                )
            }),
        })
    })

    it('shows correct dashboards when searching by name', async () => {
        expectLogic(logic, () => {
            logic.actions.setCurrentTab(DashboardsTab.Pinned)
            logic.actions.setFilters({ shared: true })
        }).toMatchValues({
            dashboards: truth((dashboards: DashboardType[]) => {
                return (
                    dashboards.length === 1 &&
                    dashboards.every((d) => d.pinned && d.is_shared) &&
                    dashboards[0].created_by?.uuid === 'USER_UUID'
                )
            }),
        })
    })

    it('uses server-side search results when a search term is set', async () => {
        // Search is executed server-side (Postgres trigram word similarity); the logic
        // delegates ranking to the API and uses the returned list as-is. We mock the search
        // endpoint and assert the selector swaps the in-memory list for the response.
        const needleDashboard = allDashboards.find((d) => d.name === 'needle')!
        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': ({ request }) => {
                    if (new URL(request.url).searchParams.get('search')) {
                        return [200, { count: 1, next: null, previous: null, results: [needleDashboard] }]
                    }
                    return [200, { count: 7, next: null, previous: null, results: allDashboards }]
                },
            },
        })

        await expectLogic(logic, () => {
            logic.actions.setSearch('needl')
        }).toDispatchActions(['loadSearchedDashboardsSuccess'])

        expect(logic.values.dashboards).toHaveLength(1)
        expect(logic.values.dashboards[0].name).toBe('needle')
    })

    it('does not refetch when only pinned / shared / createdBy change', async () => {
        // Pinned/shared/createdBy stay client-side over the in-memory list — only search
        // and tags drive the server fetch. (Tag changes only refetch when a search is
        // active; that's covered by a separate test below.)
        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': () => {
                    return [200, { count: 0, next: null, previous: null, results: [] }]
                },
            },
        })

        await expectLogic(logic, () => {
            logic.actions.setFilters({ pinned: true })
            logic.actions.setFilters({ shared: true })
            logic.actions.setFilters({ createdBy: [999] })
        }).toNotHaveDispatchedActions(['loadSearchedDashboards'])
    })

    it('sends tag filters to the server alongside search', async () => {
        // Server-side tag filtering keeps MCP/API clients in sync with the UI and ensures
        // the limit:200 cap operates on the right population (pre-tag-filtered, not post).
        let lastRequestUrl: URL | null = null
        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': ({ request }) => {
                    lastRequestUrl = new URL(request.url)
                    return [200, { count: 0, next: null, previous: null, results: [] }]
                },
            },
        })

        await expectLogic(logic, () => {
            logic.actions.setFilters({ tags: ['finance', 'q4'] })
            logic.actions.setSearch('sales')
        }).toDispatchActions(['loadSearchedDashboardsSuccess'])

        expect(lastRequestUrl).not.toBeNull()
        expect(lastRequestUrl!.searchParams.get('search')).toBe('sales')
        expect(lastRequestUrl!.searchParams.getAll('tags')).toEqual(['finance', 'q4'])
    })

    it('refetches when tags change while a search is active', async () => {
        let requestCount = 0
        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': () => {
                    requestCount += 1
                    return [200, { count: 0, next: null, previous: null, results: [] }]
                },
            },
        })

        await expectLogic(logic, () => {
            logic.actions.setSearch('sales')
        }).toDispatchActions(['loadSearchedDashboardsSuccess'])
        const afterSearch = requestCount

        await expectLogic(logic, () => {
            logic.actions.setFilters({ tags: ['finance'] })
        }).toDispatchActions(['loadSearchedDashboardsSuccess'])

        expect(requestCount).toBe(afterSearch + 1)
    })

    it('syncs search to URL when setSearch is called', async () => {
        await expectLogic(logic, () => {
            logic.actions.setSearch('needle')
        })

        expect(router.values.searchParams.search).toBe('needle')
    })

    it('removes search param from URL when search is cleared', async () => {
        await expectLogic(logic, () => {
            logic.actions.setSearch('needle')
        })

        await expectLogic(logic, () => {
            logic.actions.setSearch('')
        })

        expect(router.values.searchParams.search).toBeUndefined()
    })

    it('loads search from URL into filters on mount', async () => {
        // Recreate logic with URL containing a search param
        logic.unmount()
        router.actions.push(urls.dashboards(), { search: 'needle' })
        logic = dashboardsLogic({ tabId: '1' })
        logic.mount()

        await expectLogic(logic).toMatchValues({
            filters: expect.objectContaining({ search: 'needle' }),
        })
    })

    it('loads search from URL when the router coerces it to a number', async () => {
        logic.unmount()
        router.actions.push(urls.dashboards(), { search: 33333333 as unknown as string })
        logic = dashboardsLogic({ tabId: '1' })
        logic.mount()

        await expectLogic(logic).toMatchValues({
            filters: expect.objectContaining({ search: '33333333' }),
        })
    })

    const urlWriteCases: Array<{
        name: string
        set: Partial<DashboardsFilters>
        reset: Partial<DashboardsFilters>
        param: string
        expected: unknown
    }> = [
        {
            name: 'created_by',
            set: { createdBy: [2] },
            reset: { createdBy: 'All users' },
            param: 'created_by',
            expected: [2],
        },
        { name: 'pinned', set: { pinned: true }, reset: { pinned: false }, param: 'pinned', expected: true },
        { name: 'shared', set: { shared: true }, reset: { shared: false }, param: 'shared', expected: true },
        { name: 'tags', set: { tags: ['finance'] }, reset: { tags: [] }, param: 'tags', expected: ['finance'] },
    ]

    it.each(urlWriteCases)(
        'syncs $name to the URL and removes it on reset',
        async ({ set, reset, param, expected }) => {
            await expectLogic(logic, () => {
                logic.actions.setFilters(set)
            })
            expect(router.values.searchParams[param]).toEqual(expected)

            await expectLogic(logic, () => {
                logic.actions.setFilters(reset)
            })
            expect(router.values.searchParams[param]).toBeUndefined()
        }
    )

    const urlReadCases: Array<{
        name: string
        params: Record<string, unknown>
        expected: Partial<DashboardsFilters>
    }> = [
        { name: 'created_by', params: { created_by: [2] }, expected: { createdBy: [2] } },
        { name: 'pinned', params: { pinned: true }, expected: { pinned: true } },
        { name: 'shared', params: { shared: true }, expected: { shared: true } },
        { name: 'tags', params: { tags: ['finance', 'q4'] }, expected: { tags: ['finance', 'q4'] } },
    ]

    it.each(urlReadCases)('loads $name from the URL into filters on mount', async ({ params, expected }) => {
        logic.unmount()
        router.actions.push(urls.dashboards(), params)
        logic = dashboardsLogic({ tabId: '1' })
        logic.mount()

        await expectLogic(logic).toMatchValues({
            filters: expect.objectContaining(expected),
        })
    })

    it('normalizes the legacy pinned tab while preserving its filter', async () => {
        logic.unmount()
        router.actions.push(urls.dashboards(), { tab: DashboardsTab.Pinned })
        logic = dashboardsLogic({ tabId: '1' })
        logic.mount()

        await expectLogic(logic).toMatchValues({
            currentTab: DashboardsTab.All,
            filters: expect.objectContaining({ pinned: true }),
        })
        expect(router.values.searchParams['tab']).toBeUndefined()
    })

    it('keeps the cross-project tab selected from the URL', async () => {
        logic.unmount()
        router.actions.push(urls.dashboards(), { tab: DashboardsTab.CrossProject })
        logic = dashboardsLogic({ tabId: '1' })
        logic.mount()

        await expectLogic(logic).toMatchValues({ currentTab: DashboardsTab.CrossProject })
    })

    it('restores both search and tags from the URL and fetches with the restored tags', async () => {
        let lastRequestUrl: URL | null = null
        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': ({ request }) => {
                    lastRequestUrl = new URL(request.url)
                    return [200, { count: 0, next: null, previous: null, results: [] }]
                },
            },
        })

        logic.unmount()
        router.actions.push(urls.dashboards(), { search: 'sales', tags: ['finance'] })
        logic = dashboardsLogic({ tabId: '1' })
        logic.mount()

        await expectLogic(logic).toDispatchActions(['loadSearchedDashboardsSuccess'])

        expect(logic.values.filters).toEqual(expect.objectContaining({ search: 'sales', tags: ['finance'] }))
        expect(lastRequestUrl).not.toBeNull()
        expect(lastRequestUrl!.searchParams.get('search')).toBe('sales')
        expect(lastRequestUrl!.searchParams.getAll('tags')).toEqual(['finance'])
    })

    it('opens the move modal with the entry the list already carries', async () => {
        moveToLogic.mount()
        const filed = logic.values.dashboards.find((d) => d.file_system_id)!

        logic.actions.moveDashboardsToFolder([filed.id], 'single')

        expect(moveToLogic.values.movingItems).toEqual([
            expect.objectContaining({ id: filed.file_system_id, path: filed.file_system_path }),
        ])
        expect(moveToLogic.values.isOpen).toBe(true)
    })

    it('moves a dashboard the search returned that the model never loaded', async () => {
        moveToLogic.mount()
        const filed = logic.values.dashboards.find((d) => d.file_system_id)!
        // A dashboard created after this page loaded is reachable through search but absent from the model
        delete (dashboardsModel.values.rawDashboards as Record<string, unknown>)[filed.id]

        logic.actions.moveDashboardsToFolder([filed.id], 'single')

        expect(moveToLogic.values.isOpen).toBe(true)
    })

    it('carries the href the project tree needs to keep the moved row clickable', async () => {
        moveToLogic.mount()
        const filed = logic.values.dashboards.find((d) => d.file_system_id)!

        logic.actions.moveDashboardsToFolder([filed.id], 'single')

        expect(moveToLogic.values.movingItems[0]).toEqual(expect.objectContaining({ href: urls.dashboard(filed.id) }))
    })

    it('does nothing for a dashboard that is not filed anywhere', async () => {
        moveToLogic.mount()
        const unfiled = logic.values.dashboards.find((d) => !d.file_system_id)!

        logic.actions.moveDashboardsToFolder([unfiled.id], 'single')

        expect(moveToLogic.values.isOpen).toBe(false)
    })

    it('deselects a dashboard only once its move lands, leaving the rest ticked', async () => {
        moveToLogic.mount()
        const [first, second] = logic.values.dashboards.filter((d) => d.file_system_id)
        const onStillSelected = jest.fn()

        logic.actions.moveDashboardsToFolder([first.id, second.id], 'bulk', onStillSelected)

        // The modal is open; nothing has moved yet, so nothing is deselected.
        expect(onStillSelected).not.toHaveBeenCalled()

        projectTreeDataLogic.actions.movedItem(
            { id: first.file_system_id, type: 'dashboard', ref: String(first.id), path: first.file_system_path } as any,
            first.file_system_path!,
            'Revenue/Filed'
        )

        expect(onStillSelected).toHaveBeenCalledWith([second.id])
    })

    it('stops tracking a move once the modal is dismissed', async () => {
        moveToLogic.mount()
        const [first, second] = logic.values.dashboards.filter((d) => d.file_system_id)
        const onStillSelected = jest.fn()

        logic.actions.moveDashboardsToFolder([first.id, second.id], 'bulk', onStillSelected)
        moveToLogic.actions.closeMoveToModal()

        // movedItem fires for moves made anywhere in the project tree. Once the modal is gone, one of those
        // must not rewrite the table's selection from the abandoned bulk action.
        projectTreeDataLogic.actions.movedItem(
            { id: first.file_system_id, type: 'dashboard', ref: String(first.id), path: first.file_system_path } as any,
            first.file_system_path!,
            'Revenue/Filed'
        )

        expect(onStillSelected).not.toHaveBeenCalled()
    })

    it('does not refetch when toggling pinned while a search is active on the /dashboard URL', async () => {
        // Toggling pinned writes ?pinned=true to the URL, which round-trips back through
        // urlToAction. The guard there must not re-dispatch setSearch and trigger a redundant
        // server search. (The earlier regression test runs on pathname '/' so it never matches
        // urlToAction — this one mounts on /dashboard to exercise that round trip.)
        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': () => {
                    return [200, { count: 0, next: null, previous: null, results: [] }]
                },
            },
        })

        logic.unmount()
        router.actions.push(urls.dashboards())
        logic = dashboardsLogic({ tabId: '1' })
        logic.mount()

        await expectLogic(logic, () => {
            logic.actions.setSearch('sales')
        }).toDispatchActions(['loadSearchedDashboardsSuccess'])

        await expectLogic(logic, () => {
            logic.actions.setFilters({ pinned: true })
        }).toNotHaveDispatchedActions(['loadSearchedDashboards'])
    })
})