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.

feat(dashboards): control/tree dashboards-list A/B experiment (#65447)

Vasco de Krijger789732741897
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts
index 15604d7cf986..7d8540cb4e59 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts
@@ -1,6 +1,8 @@
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import api from 'lib/api'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { initKeaTests } from '~/test/init'
@@ -66,4 +68,55 @@ describe('projectTreeDataLogic', () => {
offset: 0,
})
})
+
+ it('emits the dashboard-move primary-metric event for dashboards but not for other item types', async () => {
+ const eventUsage = eventUsageLogic()
+ eventUsage.mount()
+ const capture = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
+ const move = jest.spyOn(api.fileSystem, 'move')
+ move.mockResolvedValueOnce({ id: 'fs-1', type: 'dashboard', path: 'Product/A' } as any)
+ move.mockResolvedValueOnce({ id: 'fs-2', type: 'insight', path: 'Product/B' } as any)
+
+ // A dashboard move fires the experiment's primary-metric event after the API move succeeds.
+ await expectLogic(eventUsage, () => {
+ logic.actions.moveItem(
+ { id: 'fs-1', type: 'dashboard', path: 'Unfiled/Dashboards/A', ref: '1' } as any,
+ 'Product/A',
+ true,
+ 'test'
+ )
+ }).toDispatchActions(['reportDashboardMovedToFolder'])
+ // Coarse fields only — never the folder/dashboard names (Unfiled/Dashboards/A -> Product/A).
+ expect(capture).toHaveBeenCalledWith(
+ 'dashboard moved to folder',
+ expect.objectContaining({
+ from_depth: 3,
+ to_depth: 2,
+ moved_from_unfiled: true,
+ moved_to_unfiled: false,
+ })
+ )
+
+ // A non-dashboard move still processes (movedItem) but must NOT fire the dashboard event.
+ capture.mockClear()
+ await expectLogic(logic, () => {
+ logic.actions.moveItem(
+ { id: 'fs-2', type: 'insight', path: 'Unfiled/Insights/B', ref: '2' } as any,
+ 'Product/B',
+ true,
+ 'test'
+ )
+ }).toDispatchActions(['movedItem'])
+ expect(capture.mock.calls.find((call) => call[0] === 'dashboard moved to folder')).toBeUndefined()
+
+ eventUsage.unmount()
+ })
+
+ it('deleteSavedItem does not crash when the parent folder is not loaded (lazy store)', () => {
+ // Folders load lazily; deleting an item whose parent folder was never loaded must not throw on
+ // state[folder].filter (previously "Cannot read properties of undefined (reading 'filter')").
+ expect(() =>
+ logic.actions.deleteSavedItem({ id: 'fs-x', type: 'dashboard', path: 'Marketing/Q1/X', ref: '9' } as any)
+ ).not.toThrow()
+ })
})
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
index 0a766d05b6c8..7e7e0213f9a3 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
@@ -210,6 +210,8 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
projectTreeLogicKey,
}),
movedItem: (item: FileSystemEntry, oldPath: string, newPath: string) => ({ item, oldPath, newPath }),
+ // Emitted after an undo-delete restores items, so consumers (e.g. the dashboards tree) can refetch.
+ restoredItems: true,
queueAction: (action: ProjectTreeAction, projectTreeLogicKey: string) => ({ action, projectTreeLogicKey }),
removeQueuedAction: (action: ProjectTreeAction) => ({ action }),
@@ -282,6 +284,21 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
await api.fileSystem.move(action.item.id, newPath)
actions.removeQueuedAction(action)
actions.movedItem(action.item, oldPath, newPath)
+ if (action.item.type === 'dashboard') {
+ // EXPERIMENT CLEANUP (flag dashboards-list-view · experiment 379125): a
+ // dashboard-specific event in the generic move path — a deliberate altitude
+ // compromise. It lives here, not in dashboardsFileSystemLogic, because that logic
+ // mounts only in the tree arm, so emitting there would miss control-arm moves and
+ // break the arm-agnostic primary metric. Remove or relocate (e.g. behind a generic
+ // post-move analytics hook) once we agree on a solution / the experiment ends.
+ // method/count + undo net-out deferred.
+ eventUsageLogic.actions.reportDashboardMovedToFolder({
+ fromDepth: splitPath(oldPath).length,
+ toDepth: splitPath(newPath).length,
+ fromUnfiled: oldPath.startsWith('Unfiled/'),
+ toUnfiled: newPath.startsWith('Unfiled/'),
+ })
+ }
lemonToast.success('Item moved successfully', {
button: {
label: 'Undo',
@@ -426,6 +443,8 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
?.actions.expandProjectFolder(folder)
}
}
+ // Signal non-sidebar consumers (the dashboards tree) to refetch.
+ actions.restoredItems()
const restoreCountsByType = new Map<string, number>()
for (const entry of undoableEntries) {
restoreCountsByType.set(
@@ -567,9 +586,11 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
},
deleteSavedItem: (state, { savedItem }) => {
const folder = joinPath(splitPath(savedItem.path).slice(0, -1))
- const newState = {
- ...state,
- [folder]: state[folder].filter((item) => item.id !== savedItem.id),
+ const newState = { ...state }
+ // The parent folder may not be loaded into the store yet (folders load lazily); only
+ // prune it when it's present — otherwise state[folder] is undefined and .filter throws.
+ if (newState[folder]) {
+ newState[folder] = newState[folder].filter((item) => item.id !== savedItem.id)
}
if (savedItem.type === 'folder') {
for (const folder of Object.keys(newState)) {
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 0c60f88497f7..735436150ab6 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -276,6 +276,7 @@ export const FEATURE_FLAGS = {
DASHBOARD_QUICK_FILTERS_EXPERIMENT: 'dashboard-quick-filters-experiment', // owner: @vdekrijger #team-product-analytics multivariate=control,test
DASHBOARD_TEMPLATE_CHOOSER_EXPERIMENT: 'dashboard-template-chooser-experiment', // owner: @mattp #team-analytics-platform multivariate=control,simple,new
DASHBOARD_WIDGETS: 'dashboard-widgets', // owner: @mattp #team-analytics-platform
+ DASHBOARDS_LIST_VIEW: 'dashboards-list-view', // owner: @vdekrijger #team-product-analytics multivariate=control,tree
DATA_MODELING_BACKEND_V2: 'data-modeling-backend-v2', // owner: #team-data-modeling
DATA_MODELING_MULTI_DAG: 'data-modeling-multi-dag', // owner: #team-data-modeling
DATA_MODELING_TAB: 'data-modeling-tab', // owner: #team-data-modeling
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index ce94f5e105f4..0176a361aec3 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -529,6 +529,15 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
pinned,
source,
}),
+ reportDashboardMovedToFolder: (props: {
+ fromDepth: number
+ toDepth: number
+ fromUnfiled: boolean
+ toUnfiled: boolean
+ }) => props,
+ reportDashboardListSearched: (searchLength: number, resultsCount: number) => ({ searchLength, resultsCount }),
+ reportDashboardsTreeFolderNavigated: (depth: number, hasSubfolders: boolean) => ({ depth, hasSubfolders }),
+ reportDashboardMoveInitiated: (method: 'single' | 'bulk', count: number) => ({ method, count }),
reportDashboardFrontEndUpdate: (
dashboardId: number | undefined,
attribute: 'name' | 'description' | 'tags',
@@ -1522,6 +1531,28 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
source,
})
},
+ reportDashboardMovedToFolder: async ({ fromDepth, toDepth, fromUnfiled, toUnfiled }) => {
+ // Coarse fields only — never folder/dashboard names (customer-controlled).
+ posthog.capture('dashboard moved to folder', {
+ from_depth: fromDepth,
+ to_depth: toDepth,
+ moved_from_unfiled: fromUnfiled,
+ moved_to_unfiled: toUnfiled,
+ })
+ },
+ reportDashboardListSearched: async ({ searchLength, resultsCount }) => {
+ // Length + count only, never the query text (can contain sensitive names).
+ posthog.capture('dashboard list searched', {
+ search_length: searchLength,
+ results_count: resultsCount,
+ })
+ },
+ reportDashboardsTreeFolderNavigated: async ({ depth, hasSubfolders }) => {
+ posthog.capture('dashboards tree folder navigated', { depth, has_subfolders: hasSubfolders })
+ },
+ reportDashboardMoveInitiated: async ({ method, count }) => {
+ posthog.capture('dashboard move initiated', { method, count })
+ },
reportDashboardFrontEndUpdate: async ({ dashboardId, attribute, originalLength, newLength }) => {
posthog.capture(`dashboard frontend updated`, {
dashboard_id: dashboardId,
diff --git a/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx b/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
index 3d088bc525e4..2788de86c830 100644
--- a/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
@@ -9,7 +9,6 @@ import { Shortcut } from 'lib/components/Shortcuts/Shortcut'
import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { DashboardsTab, dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
-import { DashboardsTableContainer } from 'scenes/dashboard/dashboards/DashboardsTable'
import { DashboardTemplateModal } from 'scenes/dashboard/dashboards/templates/DashboardTemplateModal'
import { DashboardTemplatesTable } from 'scenes/dashboard/dashboards/templates/DashboardTemplatesTable'
import { DashboardTemplateEditor } from 'scenes/dashboard/DashboardTemplateEditor'
@@ -26,6 +25,8 @@ import { dashboardsModel } from '~/models/dashboardsModel'
import { ProductKey } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { DashboardsContent } from 'products/dashboards/frontend/components/DashboardsContent'
+
import { FeaturedTemplatesChooser } from './templates/FeaturedTemplatesChooser'
const DASHBOARD_DOCS_URL = 'https://posthog.com/docs/product-analytics/dashboards'
@@ -106,7 +107,7 @@ export function Dashboards(): JSX.Element {
{currentTab === DashboardsTab.Templates ? (
<DashboardTemplatesTable />
) : dashboardsLoading || dashboards.length > 0 || isFiltering ? (
- <DashboardsTableContainer />
+ <DashboardsContent />
) : (
<ProductIntroduction
productName="Dashboards"
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx
new file mode 100644
index 000000000000..43396c4e4b72
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx
@@ -0,0 +1,93 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { useActions, useValues } from 'kea'
+
+import { DashboardsTable } from './DashboardsTable'
+
+jest.mock('kea', () => ({ ...jest.requireActual('kea'), useValues: jest.fn(), useActions: jest.fn() }))
+// BulkUpdateTagsButton pulls its own logic/deps that are irrelevant to the bulk-move button under test.
+jest.mock('lib/components/BulkActions/BulkUpdateTagsButton', () => ({ BulkUpdateTagsButton: () => null }))
+// The filters bar reads tag state from dashboardsLogic that this test doesn't mock; it's not under test.
+jest.mock('./DashboardsFiltersBar', () => ({ DashboardsFiltersBar: () => null }))
+
+// Stub LemonTable to render only the bulk-action bar, driven by a controllable selection context. The
+// per-row column renders never run (no rows), so the test stays focused on the bulk Move affordance.
+let mockCtx: { selectedKeys: number[]; clearSelection: jest.Mock }
+jest.mock('lib/lemon-ui/LemonTable', () => ({
+ LemonTable: ({ bulkSelection }: any) => (bulkSelection ? <div>{bulkSelection.renderActions(mockCtx)}</div> : null),
+}))
+
+describe('DashboardsTable bulk move', () => {
+ const openMoveToModal = jest.fn()
+ const reportDashboardMoveInitiated = jest.fn()
+ const clearSelection = jest.fn()
+
+ afterEach(cleanup)
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ ;(useActions as jest.Mock).mockReturnValue({
+ unpinDashboard: jest.fn(),
+ pinDashboard: jest.fn(),
+ tableSortingChanged: jest.fn(),
+ showDuplicateDashboardModal: jest.fn(),
+ showDeleteDashboardModal: jest.fn(),
+ openMoveToModal,
+ reportDashboardMoveInitiated,
+ })
+ ;(useValues as jest.Mock).mockReturnValue({
+ tableSorting: null,
+ filters: { search: '' },
+ currentTeam: { id: 1 },
+ itemsByRef: {},
+ })
+ })
+
+ // resolvable maps a dashboard id -> whether the tree arm's entry source resolves it (the rest fall through
+ // to the empty itemsByRef and are therefore unmovable).
+ const renderTable = (selectedKeys: number[], resolvable: Record<number, boolean>): void => {
+ mockCtx = { selectedKeys, clearSelection }
+ render(
+ <DashboardsTable
+ dashboards={[] as any}
+ dashboardsLoading={false}
+ dashboardFsEntry={(id) =>
+ resolvable[id]
+ ? ({ id: `fs-${id}`, type: 'dashboard', ref: String(id), path: 'Marketing' } as any)
+ : undefined
+ }
+ />
+ )
+ }
+
+ it('does not move anything when no selected dashboard resolves to an entry', () => {
+ renderTable([1, 2], {})
+ // The button still renders (labelled plainly), but the disabled state means a click is a no-op.
+ fireEvent.click(screen.getByText('Move to folder').closest('button')!)
+ expect(openMoveToModal).not.toHaveBeenCalled()
+ expect(reportDashboardMoveInitiated).not.toHaveBeenCalled()
+ })
+
+ it('reflects the resolvable count in the label when only some selected dashboards can be moved', () => {
+ renderTable([1, 2, 3], { 1: true })
+ expect(screen.getByText('Move 1 to folder')).toBeInTheDocument()
+ })
+
+ it('moves every resolvable entry and reports the bulk event on click', () => {
+ renderTable([1, 2], { 1: true, 2: true })
+ fireEvent.click(screen.getByText('Move to folder').closest('button')!)
+ expect(reportDashboardMoveInitiated).toHaveBeenCalledWith('bulk', 2)
+ expect(openMoveToModal).toHaveBeenCalledTimes(1)
+ expect(openMoveToModal.mock.calls[0][0]).toHaveLength(2)
+ expect(clearSelection).toHaveBeenCalled()
+ })
+
+ it('does not render the bulk move button in the control arm (no entry source)', () => {
+ // Control passes no dashboardFsEntry, so the bulk "Move to folder" button must not appear — its
+ // entry source is the mostly-empty sidebar store and it would render perpetually disabled.
+ mockCtx = { selectedKeys: [1, 2], clearSelection }
+ render(<DashboardsTable dashboards={[] as any} dashboardsLoading={false} />)
+ expect(screen.queryByText('Move to folder')).not.toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
index ba9aa1c360f0..c22d28fc663b 100644
--- a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
@@ -16,7 +16,7 @@ import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { Link } from 'lib/lemon-ui/Link'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
-import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
+import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
import { deleteDashboardLogic } from 'scenes/dashboard/deleteDashboardLogic'
@@ -26,6 +26,7 @@ import { urls } from 'scenes/urls'
import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { dashboardsModel, nameCompareFunction } from '~/models/dashboardsModel'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
import {
AccessControlLevel,
AccessControlResourceType,
@@ -50,6 +51,10 @@ interface DashboardsTableProps {
dashboardsLoading: boolean
extraActions?: JSX.Element | JSX.Element[]
hideActions?: boolean
+ // Tree arm: resolves a dashboard's FileSystem entry for "Move to another folder". The sidebar-backed
+ // itemsByRef only holds lazily-loaded folders, so it's missing for most dashboards (the Move action then
+ // never appears). The tree arm passes its complete entryByRef so every dashboard is movable.
+ dashboardFsEntry?: (id: number) => FileSystemEntry | undefined
}
export function DashboardsTable({
@@ -57,6 +62,7 @@ export function DashboardsTable({
dashboardsLoading,
extraActions,
hideActions,
+ dashboardFsEntry,
}: DashboardsTableProps): JSX.Element {
const { unpinDashboard, pinDashboard } = useActions(dashboardsModel)
const { tableSortingChanged, setFilters } = useActions(dashboardsLogic)
@@ -69,8 +75,19 @@ export function DashboardsTable({
const { showDuplicateDashboardModal } = useActions(duplicateDashboardLogic)
const { showDeleteDashboardModal } = useActions(deleteDashboardLogic)
const { openMoveToModal } = useActions(moveToLogic)
+ const { reportDashboardMoveInitiated } = useActions(eventUsageLogic)
const { itemsByRef } = useValues(projectTreeDataLogic)
+ // Prefer the tree arm's complete entryByRef over the sidebar's lazily-loaded itemsByRef, so every
+ // dashboard is movable even before the sidebar has populated.
+ const fsEntryFor = (id: number): FileSystemEntry | undefined =>
+ dashboardFsEntry?.(id) ?? itemsByRef[`dashboard::${id}`]
+
+ // The tree arm is the only caller that supplies a complete entry source. Control falls back to the
+ // sidebar's lazily-loaded itemsByRef, which is mostly empty here — so the bulk "Move to folder" button
+ // would render perpetually disabled. Gate it on the tree arm so control's bulk bar is unchanged.
+ const isTreeArm = !!dashboardFsEntry
+
const columns: LemonTableColumns<DashboardType> = [
{
width: 0,
@@ -169,7 +186,9 @@ export function DashboardsTable({
? {}
: {
width: 0,
- render: function RenderActions(_, { id, name, user_access_level }: DashboardType) {
+ render: function RenderActions(_, dashboard: DashboardType) {
+ const { id, name, user_access_level } = dashboard
+ const moveEntry = fsEntryFor(id)
return (
<More
overlay={
@@ -217,7 +236,7 @@ export function DashboardsTable({
Duplicate
</LemonButton>
- {itemsByRef[`dashboard::${id}`] && (
+ {moveEntry && (
<AccessControlAction
resourceType={AccessControlResourceType.Dashboard}
minAccessLevel={AccessControlLevel.Editor}
@@ -225,8 +244,8 @@ export function DashboardsTable({
>
<LemonButton
onClick={() => {
- const entry = itemsByRef[`dashboard::${id}`]
- openMoveToModal([entry as any])
+ reportDashboardMoveInitiated('single', 1)
+ openMoveToModal([moveEntry as any])
}}
fullWidth
data-attr="dashboard-move-to-folder"
@@ -301,16 +320,54 @@ export function DashboardsTable({
: { disabledReason: DASHBOARD_CANNOT_EDIT_MESSAGE },
rowAriaLabel: (dashboard: DashboardType) => `Select dashboard ${dashboard.name}`,
headerAriaLabel: 'Select all dashboards on this page',
- renderActions: (ctx) => (
- <BulkUpdateTagsButton
- resource="dashboards"
- selectedIds={ctx.selectedKeys}
- onSuccess={() => {
- ctx.clearSelection()
- dashboardsModel.actions.loadDashboards()
- }}
- />
- ),
+ renderActions: (ctx) => {
+ // Move the whole selection at once, resolving each id's entry the same way the per-row
+ // Move does. Some rows may not resolve (e.g. unfiled dashboards the sidebar hasn't
+ // loaded) — surface that count rather than silently dropping them from the move.
+ // Tree arm only: in control the entry source is mostly empty, so the button would be
+ // perpetually disabled — leave control's bulk bar exactly as it was.
+ const moveEntries = isTreeArm
+ ? ctx.selectedKeys.map(fsEntryFor).filter((entry): entry is FileSystemEntry => !!entry)
+ : []
+ const unmovable = ctx.selectedKeys.length - moveEntries.length
+ const partial = unmovable > 0 && moveEntries.length > 0
+ return (
+ <>
+ {isTreeArm && (
+ <LemonButton
+ size="small"
+ type="secondary"
+ onClick={() => {
+ reportDashboardMoveInitiated('bulk', moveEntries.length)
+ openMoveToModal(moveEntries)
+ ctx.clearSelection()
+ }}
+ disabledReason={
+ moveEntries.length === 0
+ ? 'None of the selected dashboards can be moved to a folder'
+ : undefined
+ }
+ tooltip={
+ partial
+ ? `Only ${moveEntries.length} of ${ctx.selectedKeys.length} selected can be moved to a folder`
+ : undefined
+ }
+ data-attr="dashboards-bulk-move-to-folder"
+ >
+ {partial ? `Move ${moveEntries.length} to folder` : 'Move to folder'}
+ </LemonButton>
+ )}
+ <BulkUpdateTagsButton
+ resource="dashboards"
+ selectedIds={ctx.selectedKeys}
+ onSuccess={() => {
+ ctx.clearSelection()
+ dashboardsModel.actions.loadDashboards()
+ }}
+ />
+ </>
+ )
+ },
}}
/>
</>
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
index 9e0b6c81b3cd..87a465d4b0f6 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
@@ -3,6 +3,7 @@ import { MOCK_DEFAULT_USER } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic, truth } from 'kea-test-utils'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { DashboardsFilters, DashboardsTab, dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
@@ -211,12 +212,16 @@ describe('dashboardsLogic', () => {
},
})
+ const reportSearched = jest.spyOn(eventUsageLogic.actions, 'reportDashboardListSearched')
await expectLogic(logic, () => {
logic.actions.setSearch('needl')
}).toDispatchActions(['loadSearchedDashboardsSuccess'])
expect(logic.values.dashboards).toHaveLength(1)
expect(logic.values.dashboards[0].name).toBe('needle')
+ // Findability signal fires once per settled search: term length + result count, never the query text.
+ // Covers the dashboards-list-view experiment instrumentation (flag: dashboards-list-view · experiment 379125).
+ expect(reportSearched).toHaveBeenCalledWith(5, 1)
})
it('does not refetch when only pinned / shared / createdBy change', async () => {
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
index 4f66f3e7a837..fbc10ff41465 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
@@ -6,6 +6,7 @@ import api, { PaginatedResponse } from 'lib/api'
import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { objectClean, objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
@@ -152,6 +153,10 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
`api/environments/${teamId}/dashboards/?${params.toString()}`
)
breakpoint()
+ // Findability signal for the dashboards-list-view experiment (flag: dashboards-list-view ·
+ // experiment: 379125) — fires once per settled search (the 250ms breakpoint + the post-fetch
+ // breakpoint() drop keystrokes and superseded queries). Remove with the experiment cleanup.
+ eventUsageLogic.actions.reportDashboardListSearched(term.length, response.results?.length ?? 0)
return response.results ?? []
},
},
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4259e70151ef..3a95952e25c5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2985,6 +2985,9 @@ importers:
jest:
specifier: ^29.7.0
+ kea-test-utils:
+ specifier: 'catalog:'
products/data_modeling:
dependencies:
diff --git a/products/dashboards/frontend/components/DashboardsContent.test.tsx b/products/dashboards/frontend/components/DashboardsContent.test.tsx
new file mode 100644
index 000000000000..80e6b53a49cd
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardsContent.test.tsx
@@ -0,0 +1,40 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { useValues } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { DashboardsContent } from './DashboardsContent'
+
+jest.mock('scenes/dashboard/dashboards/DashboardsTable', () => ({
+ DashboardsTableContainer: () => <div>table-arm</div>,
+}))
+jest.mock('./DashboardsTree', () => ({ DashboardsTree: () => <div>tree-arm</div> }))
+jest.mock('kea', () => ({ ...jest.requireActual('kea'), useValues: jest.fn() }))
+
+function renderWithFlag(value: string | undefined): void {
+ ;(useValues as jest.Mock).mockReturnValue({
+ featureFlags: value === undefined ? {} : { [FEATURE_FLAGS.DASHBOARDS_LIST_VIEW]: value },
+ })
+ render(<DashboardsContent />)
+}
+
+describe('DashboardsContent', () => {
+ afterEach(cleanup)
+
+ it.each([undefined, 'control', 'bogus', 'grid', 'finder', 'explorer'])(
+ 'renders the table for variant %p',
+ (value) => {
+ renderWithFlag(value)
+ expect(screen.getByText('table-arm')).toBeInTheDocument()
+ expect(screen.queryByText('tree-arm')).not.toBeInTheDocument()
+ }
+ )
+
+ it('renders the tree for the tree variant', () => {
+ renderWithFlag('tree')
+ expect(screen.getByText('tree-arm')).toBeInTheDocument()
+ expect(screen.queryByText('table-arm')).not.toBeInTheDocument()
+ })
+})
diff --git a/products/dashboards/frontend/components/DashboardsContent.tsx b/products/dashboards/frontend/components/DashboardsContent.tsx
new file mode 100644
index 000000000000..ca4d94966962
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardsContent.tsx
@@ -0,0 +1,20 @@
+import { useValues } from 'kea'
+
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { DashboardsTableContainer } from 'scenes/dashboard/dashboards/DashboardsTable'
+
+import { resolveDashboardsListViewVariant } from '../logics/dashboardsListViewVariants'
+import { DashboardsTree } from './DashboardsTree'
+
+// Routes the dashboards list body to the arm selected by the dashboards-list-view experiment flag.
+// Control (and any unknown value) renders today's table unchanged; the tree treatment arm shows a
+// persistent folder-tree panel beside the table.
+export function DashboardsContent(): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const variant = resolveDashboardsListViewVariant(featureFlags)
+
+ if (variant === 'tree') {
+ return <DashboardsTree />
+ }
+ return <DashboardsTableContainer />
+}
diff --git a/products/dashboards/frontend/components/DashboardsTree.test.tsx b/products/dashboards/frontend/components/DashboardsTree.test.tsx
new file mode 100644
index 000000000000..d041a3d01e79
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardsTree.test.tsx
@@ -0,0 +1,194 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { useActions, useValues } from 'kea'
+
+import { DashboardsTree } from './DashboardsTree'
+
+// Captured so a test can invoke the tree's onFolderClick directly with undefined — no click path produces that.
+let mockLastOnFolderClick: ((folder: unknown) => void) | undefined
+
+jest.mock('kea', () => ({ ...jest.requireActual('kea'), useValues: jest.fn(), useActions: jest.fn() }))
+jest.mock('scenes/dashboard/dashboards/DashboardsTable', () => ({
+ DashboardsTable: ({ dashboards }: any) => (
+ <div>
+ {dashboards.map((dashboard: { id: number; name: string }) => (
+ <span key={dashboard.id}>{dashboard.name}</span>
+ ))}
+ </div>
+ ),
+}))
+// Stub LemonTree: render each node (recursively) via renderItem, clickable to fire onFolderClick.
+jest.mock('lib/lemon-ui/LemonTree/LemonTree', () => {
+ const renderNodes = (items: any[], onFolderClick: any, renderItem: any): any =>
+ items.map((item: any) => (
+ <div key={item.id}>
+ <div onClick={() => onFolderClick(item)}>{renderItem ? renderItem(item, item.name) : item.name}</div>
+ {item.children ? renderNodes(item.children, onFolderClick, renderItem) : null}
+ </div>
+ ))
+ return {
+ LemonTree: ({ data, onFolderClick, renderItem }: any) => {
+ mockLastOnFolderClick = onFolderClick
+ return <div>{renderNodes(data, onFolderClick, renderItem)}</div>
+ },
+ }
+})
+
+describe('DashboardsTree', () => {
+ const navigateToFolder = jest.fn()
+ const toggleFolder = jest.fn()
+ const setExpandedFolders = jest.fn()
+ const reportDashboardsTreeFolderNavigated = jest.fn()
+
+ afterEach(cleanup)
+
+ beforeEach(() => {
+ navigateToFolder.mockClear()
+ toggleFolder.mockClear()
+ setExpandedFolders.mockClear()
+ reportDashboardsTreeFolderNavigated.mockClear()
+ ;(useActions as jest.Mock).mockReturnValue({
+ navigateToFolder,
+ toggleFolder,
+ setExpandedFolders,
+ createFolder: jest.fn(),
+ reportDashboardsTreeFolderNavigated,
+ })
+ })
+
+ function mockValues(overrides: Record<string, any>): void {
+ ;(useValues as jest.Mock).mockReturnValue({
+ folderTree: [],
+ currentFolder: '',
+ currentSubtreeDashboards: [],
+ entryByRef: {},
+ expandedFolders: {},
+ folderEntryByPath: {},
+ folderDashboardCounts: {},
+ dashboardFileSystemEntriesLoading: false,
+ folderEntriesLoading: false,
+ dashboardsLoading: false,
+ ...overrides,
+ })
+ }
+
+ it('renders All dashboards as the root with folders nested under it, and the scoped table', () => {
+ mockValues({
+ folderTree: [
+ {
+ path: 'Marketing',
+ label: 'Marketing',
+ children: [{ path: 'Marketing/Q1', label: 'Q1', children: [] }],
+ },
+ ],
+ currentSubtreeDashboards: [{ id: 1, name: 'Revenue' }],
+ })
+ render(<DashboardsTree />)
+ // "All dashboards" is the tree root; folders nest under it.
+ expect(screen.getByText('All dashboards')).toBeInTheDocument()
+ expect(screen.getByText('Marketing')).toBeInTheDocument()
+ expect(screen.getByText('Q1')).toBeInTheDocument()
+ expect(screen.getByText(/Revenue/)).toBeInTheDocument()
+ })
+
+ it('navigates to a childless folder without toggling it (it never expands)', () => {
+ mockValues({ folderTree: [{ path: 'Marketing', label: 'Marketing', children: [] }] })
+ render(<DashboardsTree />)
+ fireEvent.click(screen.getByText('Marketing'))
+ expect(navigateToFolder).toHaveBeenCalledWith('Marketing')
+ expect(toggleFolder).not.toHaveBeenCalled()
+ // Adoption signal fires with the folder's depth and whether it has subfolders.
+ expect(reportDashboardsTreeFolderNavigated).toHaveBeenCalledWith(1, false)
+ })
+
+ it('navigates to a folder with subfolders and toggles its expansion', () => {
+ mockValues({
+ folderTree: [
+ {
+ path: 'Marketing',
+ label: 'Marketing',
+ children: [{ path: 'Marketing/Q1', label: 'Q1', children: [] }],
+ },
+ ],
+ })
+ render(<DashboardsTree />)
+ fireEvent.click(screen.getByText('Marketing'))
+ expect(navigateToFolder).toHaveBeenCalledWith('Marketing')
+ expect(toggleFolder).toHaveBeenCalledWith('Marketing')
+ expect(reportDashboardsTreeFolderNavigated).toHaveBeenCalledWith(1, true)
+ })
+
+ it('navigates to the root when the All dashboards node is clicked', () => {
+ mockValues({ folderTree: [{ path: 'Marketing', label: 'Marketing', children: [] }] })
+ render(<DashboardsTree />)
+ fireEvent.click(screen.getByText('All dashboards'))
+ expect(navigateToFolder).toHaveBeenCalledWith('')
+ // Root is depth 0 and (here) has subfolders.
+ expect(reportDashboardsTreeFolderNavigated).toHaveBeenCalledWith(0, true)
+ })
+
+ const clickExpandToggle = (container: HTMLElement): void => {
+ fireEvent.click(container.querySelector('[data-attr="dashboards-tree-expand-toggle"]') as HTMLElement)
+ }
+
+ it('the expand toggle expands only folders that have subfolders (childless ones are skipped)', () => {
+ mockValues({
+ folderTree: [
+ {
+ path: 'Marketing',
+ label: 'Marketing',
+ // Q1 is childless, so it isn't expandable and must not appear in the expanded map.
+ children: [{ path: 'Marketing/Q1', label: 'Q1', children: [] }],
+ },
+ ],
+ })
+ const { container } = render(<DashboardsTree />)
+ clickExpandToggle(container)
+ expect(setExpandedFolders).toHaveBeenCalledWith({ Marketing: true })
+ })
+
+ it('the toggle collapses everything when all folders are currently expanded', () => {
+ mockValues({
+ folderTree: [
+ {
+ path: 'Marketing',
+ label: 'Marketing',
+ children: [{ path: 'Marketing/Q1', label: 'Q1', children: [] }],
+ },
+ ],
+ expandedFolders: { Marketing: true },
+ })
+ const { container } = render(<DashboardsTree />)
+ clickExpandToggle(container)
+ expect(setExpandedFolders).toHaveBeenCalledWith({})
+ })
+
+ it('the expand toggle cancels the row-link nav (no bounce to home) and does not select the root', () => {
+ mockValues({
+ folderTree: [
+ {
+ path: 'Marketing',
+ label: 'Marketing',
+ children: [{ path: 'Marketing/Q1', label: 'Q1', children: [] }],
+ },
+ ],
+ })
+ const { container } = render(<DashboardsTree />)
+ const toggle = container.querySelector('[data-attr="dashboards-tree-expand-toggle"]') as HTMLElement
+ // The row is a Link (to='#' for folders); fireEvent returns false only when the handler called
+ // preventDefault — the guard that stops the toggle bouncing to home. stopPropagation keeps it from
+ // also selecting the root folder.
+ expect(fireEvent.click(toggle)).toBe(false)
+ expect(navigateToFolder).not.toHaveBeenCalled()
+ expect(setExpandedFolders).toHaveBeenCalled()
+ })
+
+ it('onFolderClick ignores an undefined folder — the null guard never throws or navigates', () => {
+ mockValues({ folderTree: [] })
+ render(<DashboardsTree />)
+ // No click path produces undefined, but LemonTree's type allows it; the guard must hold.
+ expect(() => mockLastOnFolderClick?.(undefined)).not.toThrow()
+ expect(navigateToFolder).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/dashboards/frontend/components/DashboardsTree.tsx b/products/dashboards/frontend/components/DashboardsTree.tsx
new file mode 100644
index 000000000000..57ec45d9a8fa
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardsTree.tsx
@@ -0,0 +1,195 @@
+import { useActions, useValues } from 'kea'
+
+import { IconCollapse, IconExpand } from '@posthog/icons'
+import { LemonButton, Spinner } from '@posthog/lemon-ui'
+
+import { LemonTree, TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
+import { DropdownMenuGroup } from 'lib/ui/DropdownMenu/DropdownMenu'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { DashboardsTable } from 'scenes/dashboard/dashboards/DashboardsTable'
+
+import { splitPath } from '~/layout/panel-layout/ProjectTree/utils'
+import { dashboardsModel } from '~/models/dashboardsModel'
+
+import { dashboardsFileSystemLogic } from '../logics/dashboardsFileSystemLogic'
+import { FolderTreeNode } from '../logics/dashboardsFileSystemUtils'
+import { DashboardsTreeFolderMenu } from './DashboardsTreeFolderMenu'
+
+// "All dashboards" is the single tree root; every folder nests under it. record.type 'folder' makes even
+// childless folders behave as folders. The folder path doubles as the id; the root uses a sentinel id.
+const ROOT_ID = '__all_dashboards__'
+
+function toTreeData(nodes: FolderTreeNode[]): TreeDataItem[] {
+ return nodes.map((node) => ({
+ id: node.path,
+ name: node.label,
+ record: { type: 'folder', path: node.path },
+ children: node.children.length > 0 ? toTreeData(node.children) : undefined,
+ }))
+}
+
+// Only folders that actually contain subfolders are "expandable". A childless folder is a terminal node:
+// expanding it would reveal nothing in the tree (its dashboards live in the right-hand table), so it never
+// gets the open-folder icon or a chevron — you just click it to scope the table.
+function collectExpandablePaths(nodes: FolderTreeNode[], acc: string[] = []): string[] {
+ for (const node of nodes) {
+ if (node.children.length > 0) {
+ acc.push(node.path)
+ collectExpandablePaths(node.children, acc)
+ }
+ }
+ return acc
+}
+
+// Tree arm (variant=tree): the sidebar's LemonTree as a persistent folder panel on the left, beside the
+// familiar dashboards table on the right scoped to everything at or below the selected folder (root = all).
+// Expansion is controlled: the tree opens collapsed except for the root (so you see the top-level folders),
+// and clicking a folder expands it — both the chevron and a folder-row click mirror the toggle into the
+// expandedFolders reducer so collapsing sticks and the open/close animation plays. The table's Folder column
+// reads the same entryByRef the scoping uses, so the displayed folder always matches where the dashboard is.
+export function DashboardsTree(): JSX.Element {
+ const {
+ folderTree,
+ currentFolder,
+ currentSubtreeDashboards,
+ entryByRef,
+ expandedFolders,
+ folderEntryByPath,
+ folderDashboardCounts,
+ dashboardFileSystemEntriesLoading,
+ folderEntriesLoading,
+ } = useValues(dashboardsFileSystemLogic)
+ const { navigateToFolder, toggleFolder, setExpandedFolders } = useActions(dashboardsFileSystemLogic)
+ const { reportDashboardsTreeFolderNavigated } = useActions(eventUsageLogic)
+ const { dashboardsLoading } = useValues(dashboardsModel)
+
+ const treeData: TreeDataItem[] = [
+ {
+ id: ROOT_ID,
+ name: 'All dashboards',
+ record: { type: 'folder', path: '' },
+ children: toTreeData(folderTree),
+ },
+ ]
+
+ // The root is always open; folders with subfolders are closed until expanded. Childless folders are never
+ // expandable, so they stay closed-icon terminal nodes.
+ const expandablePaths = collectExpandablePaths(folderTree)
+ const expandedItemIds = [ROOT_ID, ...expandablePaths.filter((id) => expandedFolders[id])]
+ const allExpanded = expandablePaths.length > 0 && expandablePaths.every((id) => expandedFolders[id])
+
+ return (
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-[260px_1fr]" data-attr="dashboards-tree">
+ <div
+ className="flex flex-col border-b border-border pb-2 md:border-b-0 md:border-r md:pb-0 md:pr-2"
+ aria-label="Folder tree"
+ >
+ {/* LemonTree drops its own className, so the override lives on this wrapper instead. Every
+ open/expanded accordion trigger is shaded with the tertiary-active fill, which made all
+ expanded folders look selected; null that fill out via the CSS variable (cascades to all
+ rows) and re-apply it only to the actively-selected folder. */}
+ {/* On mobile the tree stacks above the table, so cap its height and let it scroll — otherwise a
+ project with many folders pushes the dashboards list far below the fold. Reset at md+ where the
+ panel sits beside the table. */}
+ <div className="dashboards-tree-panel flex-1 min-h-0 max-h-[40vh] overflow-y-auto md:max-h-none md:overflow-visible [--color-bg-fill-button-tertiary-active:transparent] [&_.button-primitive--active]:!bg-[var(--color-bg-fill-highlight-50)]">
+ <LemonTree
+ data={treeData}
+ expandedItemIds={expandedItemIds}
+ // Highlight only the folder you're in; navigating moves it (and clears the rest).
+ isItemActive={(item) => item.record?.path === currentFolder}
+ renderItem={(item, children) => {
+ if (item.record?.type !== 'folder') {
+ return children
+ }
+ // The root carries the expand/collapse-all toggle as a hover button (frees the
+ // panel header); every other folder shows a trailing subtree dashboard count.
+ if (item.id === ROOT_ID && expandablePaths.length > 0) {
+ return (
+ <span className="flex items-center gap-1 w-full min-w-0">
+ <span className="truncate">{children}</span>
+ <LemonButton
+ size="small"
+ icon={allExpanded ? <IconCollapse /> : <IconExpand />}
+ tooltip={allExpanded ? 'Collapse all folders' : 'Expand all folders'}
+ onClick={(e) => {
+ // The row is a Link (to='#' since folders carry no href); preventDefault
+ // stops the toggle from triggering that nav (which bounces to home),
+ // stopPropagation stops it from also selecting the root folder.
+ e.preventDefault()
+ e.stopPropagation()
+ setExpandedFolders(
+ allExpanded
+ ? {}
+ : Object.fromEntries(expandablePaths.map((id) => [id, true]))
+ )
+ }}
+ className="ml-auto shrink-0 opacity-0 group-hover/lemon-tree-button:opacity-100"
+ data-attr="dashboards-tree-expand-toggle"
+ />
+ </span>
+ )
+ }
+ const count = folderDashboardCounts[(item.record?.path as string) ?? ''] ?? 0
+ return (
+ <span className="flex items-center gap-1 w-full min-w-0">
+ <span className="truncate">{children}</span>
+ {count > 0 && (
+ <span className="ml-auto shrink-0 text-xxs text-tertiary tabular-nums">
+ {count}
+ </span>
+ )}
+ </span>
+ )
+ }}
+ onSetExpandedItemIds={(newIds) => {
+ // Sync the whole expandable set to LemonTree's new state. (Find-first missed batch
+ // keyboard collapses where a parent and its expanded children change at once;
+ // rebuilding from the live set also drops stale paths of since-deleted folders.)
+ const expanded = new Set(newIds)
+ setExpandedFolders(Object.fromEntries(expandablePaths.map((id) => [id, expanded.has(id)])))
+ }}
+ onFolderClick={(folder) => {
+ if (!folder) {
+ return
+ }
+ // A folder click selects it (scopes the table); a folder that has subfolders also
+ // toggles expansion. The root stays open; childless folders don't expand at all.
+ const path = (folder.record?.path as string) ?? ''
+ const hasSubfolders = !!folder.children && folder.children.length > 0
+ reportDashboardsTreeFolderNavigated(splitPath(path).length, hasSubfolders)
+ navigateToFolder(path)
+ if (folder.id !== ROOT_ID && hasSubfolders) {
+ toggleFolder(folder.id)
+ }
+ }}
+ itemSideAction={(item) => {
+ // Hover ellipsis on every folder (root included). Root → New folder; a real folder
+ // → New subfolder / Rename / Move to / Delete (the last three need its FileSystem row).
+ if (item.record?.type !== 'folder') {
+ return undefined
+ }
+ const path = (item.record?.path as string) ?? ''
+ return (
+ <DropdownMenuGroup>
+ <DashboardsTreeFolderMenu path={path} entry={folderEntryByPath[path]} />
+ </DropdownMenuGroup>
+ )
+ }}
+ />
+ {(dashboardFileSystemEntriesLoading || folderEntriesLoading) && folderTree.length === 0 && (
+ <div className="flex items-center justify-center p-3">
+ <Spinner className="text-lg" />
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="min-w-0" data-attr="dashboards-tree-content">
+ <DashboardsTable
+ dashboards={currentSubtreeDashboards}
+ dashboardsLoading={dashboardsLoading}
+ dashboardFsEntry={(id) => entryByRef[String(id)]}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/products/dashboards/frontend/components/DashboardsTreeFolderMenu.test.tsx b/products/dashboards/frontend/components/DashboardsTreeFolderMenu.test.tsx
new file mode 100644
index 000000000000..99e05487b42e
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardsTreeFolderMenu.test.tsx
@@ -0,0 +1,79 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { useActions } from 'kea'
+
+import { LemonDialog } from '@posthog/lemon-ui'
+
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+
+import { DashboardsTreeFolderMenu } from './DashboardsTreeFolderMenu'
+
+jest.mock('kea', () => ({ ...jest.requireActual('kea'), useActions: jest.fn() }))
+jest.mock('@posthog/lemon-ui', () => ({
+ ...jest.requireActual('@posthog/lemon-ui'),
+ LemonDialog: { openForm: jest.fn() },
+}))
+// Render each menu item as a plain clickable element so we don't need the Radix DropdownMenu context.
+jest.mock('lib/ui/DropdownMenu/DropdownMenu', () => ({
+ DropdownMenuItem: ({ children, onClick }: any) => <div onClick={onClick}>{children}</div>,
+}))
+
+const folderEntry = (path: string): FileSystemEntry => ({ id: `fs-${path}`, type: 'folder', path }) as FileSystemEntry
+
+describe('DashboardsTreeFolderMenu', () => {
+ const createFolder = jest.fn()
+ const renameFolder = jest.fn()
+ const deleteFolder = jest.fn()
+ const openMoveToModal = jest.fn()
+ const openForm = LemonDialog.openForm as jest.Mock
+
+ afterEach(cleanup)
+
+ beforeEach(() => {
+ ;[createFolder, renameFolder, deleteFolder, openMoveToModal, openForm].forEach((m) => m.mockClear())
+ ;(useActions as jest.Mock).mockReturnValue({ createFolder, renameFolder, deleteFolder, openMoveToModal })
+ })
+
+ it('shows the full menu for a real folder', () => {
+ render(<DashboardsTreeFolderMenu path="Marketing" entry={folderEntry('Marketing')} />)
+ expect(screen.getByText('New subfolder')).toBeInTheDocument()
+ expect(screen.getByText('Rename')).toBeInTheDocument()
+ expect(screen.getByText('Move to...')).toBeInTheDocument()
+ expect(screen.getByText('Delete')).toBeInTheDocument()
+ })
+
+ it('shows only New folder for the root (no entry)', () => {
+ render(<DashboardsTreeFolderMenu path="" />)
+ expect(screen.getByText('New folder')).toBeInTheDocument()
+ expect(screen.queryByText('Rename')).not.toBeInTheDocument()
+ expect(screen.queryByText('Move to...')).not.toBeInTheDocument()
+ expect(screen.queryByText('Delete')).not.toBeInTheDocument()
+ })
+
+ it('creates a subfolder under the clicked folder', () => {
+ render(<DashboardsTreeFolderMenu path="Marketing" entry={folderEntry('Marketing')} />)
+ fireEvent.click(screen.getByText('New subfolder'))
+ openForm.mock.calls[0][0].onSubmit({ folderName: 'Q1' })
+ expect(createFolder).toHaveBeenCalledWith('Q1', 'Marketing')
+ })
+
+ it('renames the folder to the submitted name', () => {
+ const entry = folderEntry('Marketing/Q1')
+ render(<DashboardsTreeFolderMenu path="Marketing/Q1" entry={entry} />)
+ fireEvent.click(screen.getByText('Rename'))
+ // The rename dialog pre-fills the last path segment.
+ expect(openForm.mock.calls[0][0].initialValues).toEqual({ folderName: 'Q1' })
+ openForm.mock.calls[0][0].onSubmit({ folderName: 'Q2' })
+ expect(renameFolder).toHaveBeenCalledWith(entry, 'Q2')
+ })
+
+ it('moves and deletes via the folder entry', () => {
+ const entry = folderEntry('Marketing')
+ render(<DashboardsTreeFolderMenu path="Marketing" entry={entry} />)
+ fireEvent.click(screen.getByText('Move to...'))
+ expect(openMoveToModal).toHaveBeenCalledWith([entry])
+ fireEvent.click(screen.getByText('Delete'))
+ expect(deleteFolder).toHaveBeenCalledWith(entry)
+ })
+})
diff --git a/products/dashboards/frontend/components/DashboardsTreeFolderMenu.tsx b/products/dashboards/frontend/components/DashboardsTreeFolderMenu.tsx
new file mode 100644
index 000000000000..c12813364721
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardsTreeFolderMenu.tsx
@@ -0,0 +1,117 @@
+import { useActions } from 'kea'
+
+import { IconArrowRight, IconPencil, IconPlus, IconTrash } from '@posthog/icons'
+import { LemonDialog } from '@posthog/lemon-ui'
+
+import { moveToLogic } from 'lib/components/FileSystem/MoveTo/moveToLogic'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
+import { DropdownMenuItem } from 'lib/ui/DropdownMenu/DropdownMenu'
+
+import { splitPath } from '~/layout/panel-layout/ProjectTree/utils'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+
+import { dashboardsFileSystemLogic } from '../logics/dashboardsFileSystemLogic'
+
+interface DashboardsTreeFolderMenuProps {
+ // The folder this menu acts on; '' is the tree root ("All dashboards"), which only offers New folder.
+ path: string
+ // The folder's FileSystem row. Absent for folders inferred purely from a dashboard's path (no row, no
+ // id) — those can't be moved/renamed/deleted, so only New subfolder is shown.
+ entry?: FileSystemEntry
+}
+
+function openNameDialog(title: string, initialName: string, onSubmit: (name: string) => void): void {
+ // Guard against a fast double-click submitting twice before the dialog closes — the create/rename
+ // actions are fire-and-forget, so without this a double-click yields a duplicate folder / repeated rename.
+ let submitted = false
+ LemonDialog.openForm({
+ title,
+ initialValues: { folderName: initialName },
+ content: (
+ <LemonField name="folderName">
+ <LemonInput placeholder="Enter a folder name" autoFocus />
+ </LemonField>
+ ),
+ errors: { folderName: (name) => (!name?.trim() ? 'You must enter a folder name' : undefined) },
+ onSubmit: ({ folderName }) => {
+ if (submitted) {
+ return
+ }
+ submitted = true
+ onSubmit(folderName)
+ },
+ })
+}
+
+// Folder context menu for the tree arm — reuses the same move/rename/delete/create operations the sidebar
+// tree uses (via dashboardsFileSystemLogic, which delegates to projectTreeDataLogic), but renders a scoped
+// surface instead of the sidebar's full menu. Rendered through LemonTree's itemSideAction (hover ellipsis).
+export function DashboardsTreeFolderMenu({ path, entry }: DashboardsTreeFolderMenuProps): JSX.Element {
+ const { createFolder, renameFolder, deleteFolder } = useActions(dashboardsFileSystemLogic)
+ const { openMoveToModal } = useActions(moveToLogic)
+ const isRoot = path === ''
+ const label = splitPath(path).at(-1) ?? path
+
+ return (
+ <>
+ <DropdownMenuItem
+ asChild
+ onClick={(e) => {
+ e.stopPropagation()
+ openNameDialog(isRoot ? 'New folder' : 'New subfolder', '', (name) => createFolder(name, path))
+ }}
+ data-attr="dashboards-tree-new-folder"
+ >
+ <ButtonPrimitive menuItem>
+ <IconPlus className="size-4 text-tertiary" />
+ {isRoot ? 'New folder' : 'New subfolder'}
+ </ButtonPrimitive>
+ </DropdownMenuItem>
+ {entry && (
+ <>
+ <DropdownMenuItem
+ asChild
+ onClick={(e) => {
+ e.stopPropagation()
+ openNameDialog('Rename folder', label, (name) => renameFolder(entry, name))
+ }}
+ data-attr="dashboards-tree-rename-folder"
+ >
+ <ButtonPrimitive menuItem>
+ <IconPencil className="size-4 text-tertiary" />
+ Rename
+ </ButtonPrimitive>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ asChild
+ onClick={(e) => {
+ e.stopPropagation()
+ openMoveToModal([entry])
+ }}
+ data-attr="dashboards-tree-move-folder"
+ >
+ <ButtonPrimitive menuItem>
+ <IconArrowRight className="size-4 text-tertiary" />
+ Move to...
+ </ButtonPrimitive>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ asChild
+ onClick={(e) => {
+ e.stopPropagation()
+ deleteFolder(entry)
+ }}
+ data-attr="dashboards-tree-delete-folder"
+ >
+ <ButtonPrimitive menuItem>
+ <IconTrash className="size-4 text-danger" />
+ Delete
+ </ButtonPrimitive>
+ </DropdownMenuItem>
+ </>
+ )}
+ </>
+ )
+}
diff --git a/products/dashboards/frontend/logics/dashboardsFileSystemLogic.test.ts b/products/dashboards/frontend/logics/dashboardsFileSystemLogic.test.ts
new file mode 100644
index 000000000000..c3a4d3b8bc87
--- /dev/null
+++ b/products/dashboards/frontend/logics/dashboardsFileSystemLogic.test.ts
@@ -0,0 +1,246 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
+import { useMocks } from '~/mocks/jest'
+import { dashboardsModel } from '~/models/dashboardsModel'
+import { initKeaTests } from '~/test/init'
+
+import { dashboardsFileSystemLogic } from './dashboardsFileSystemLogic'
+
+describe('dashboardsFileSystemLogic', () => {
+ let logic: ReturnType<typeof dashboardsFileSystemLogic.build>
+
+ useMocks({
+ get: {
+ '/api/environments/:team_id/dashboards/': () => [200, { count: 0, results: [], next: null }],
+ '/api/projects/:team_id/dashboards/': () => [200, { count: 0, results: [], next: null }],
+ },
+ })
+
+ beforeEach(() => {
+ jest.spyOn(api.fileSystem, 'list').mockImplementation(
+ async ({ type }: { type?: string } = {}) =>
+ (type === 'folder'
+ ? { count: 0, results: [], users: [] }
+ : {
+ count: 1,
+ results: [{ id: 'fs-1', type: 'dashboard', ref: '1', path: 'Marketing/A' }],
+ users: [],
+ }) as any
+ )
+ jest.spyOn(api.fileSystem, 'unfiled').mockResolvedValue(null as any)
+ jest.spyOn(api.fileSystemShortcuts, 'list').mockResolvedValue({ count: 0, results: [] } as any)
+ jest.spyOn(api.fileSystem, 'create').mockResolvedValue({ id: 'fs-new', type: 'folder', path: 'x' } as any)
+ initKeaTests()
+ logic = dashboardsFileSystemLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ jest.restoreAllMocks()
+ })
+
+ it('loads dashboard file-system entries indexed by ref', async () => {
+ await expectLogic(logic).toDispatchActions(['loadDashboardFileSystemEntriesSuccess'])
+ expect(logic.values.entryByRef['1']?.path).toEqual('Marketing/A')
+ })
+
+ it('pages through every dashboard entry instead of truncating at one page', async () => {
+ await expectLogic(logic).toDispatchActions([
+ 'loadDashboardFileSystemEntriesSuccess',
+ 'loadFolderEntriesSuccess',
+ ])
+ const entry = (n: number): any => ({ id: `fs-${n}`, type: 'dashboard', ref: String(n), path: `Folder/${n}` })
+ const fullPage = Array.from({ length: 500 }, (_, i) => entry(i))
+ ;(api.fileSystem.list as jest.Mock).mockImplementation(async ({ type, offset = 0 }: any) =>
+ type !== 'dashboard'
+ ? { count: 0, results: [], users: [] }
+ : offset === 0
+ ? { count: 501, results: fullPage, users: [] }
+ : { count: 501, results: [entry(500)], users: [] }
+ )
+ logic.unmount()
+ logic = dashboardsFileSystemLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadDashboardFileSystemEntriesSuccess'])
+ // 500 (page 1) + 1 (page 2): the 501st entry is loaded, not dropped past the old single-page cap.
+ expect(logic.values.entryByRef['500']?.path).toEqual('Folder/500')
+ expect(Object.keys(logic.values.entryByRef)).toHaveLength(501)
+ })
+
+ it('exposes empty folder rows in the folder tree', async () => {
+ // Drain the beforeEach mount's loaders so their (uncancelled) results don't race the re-mock below.
+ await expectLogic(logic).toDispatchActions([
+ 'loadDashboardFileSystemEntriesSuccess',
+ 'loadFolderEntriesSuccess',
+ ])
+ ;(api.fileSystem.list as jest.Mock).mockImplementation(
+ async ({ type }: { type?: string } = {}) =>
+ (type === 'folder'
+ ? { count: 1, results: [{ id: 'fld', type: 'folder', path: 'Ideas' }], users: [] }
+ : { count: 0, results: [], users: [] }) as any
+ )
+ logic.unmount()
+ logic = dashboardsFileSystemLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions([
+ 'loadDashboardFileSystemEntriesSuccess',
+ 'loadFolderEntriesSuccess',
+ ])
+ // The folder rows feed the tree even with no dashboards beneath them (empty folders appear).
+ expect(logic.values.folderTree.map((node) => node.path)).toEqual(['Ideas'])
+ })
+
+ it('navigates folders', async () => {
+ await expectLogic(logic, () => logic.actions.navigateToFolder('Marketing')).toMatchValues({
+ currentFolder: 'Marketing',
+ })
+ await expectLogic(logic, () => logic.actions.navigateToFolder('')).toMatchValues({ currentFolder: '' })
+ })
+
+ it('refetches entries when a dashboard move lands so the subtree reflects the new path', async () => {
+ await expectLogic(logic).toDispatchActions(['loadDashboardFileSystemEntriesSuccess'])
+ expect(logic.values.entryByRef['1']?.path).toEqual('Marketing/A')
+ ;(api.fileSystem.list as jest.Mock).mockImplementation(
+ async ({ type }: { type?: string } = {}) =>
+ (type === 'folder'
+ ? { count: 0, results: [], users: [] }
+ : {
+ count: 1,
+ results: [{ id: 'fs-1', type: 'dashboard', ref: '1', path: 'Product/A' }],
+ users: [],
+ }) as any
+ )
+ await expectLogic(logic, () => {
+ projectTreeDataLogic.actions.movedItem(
+ { id: 'fs-1', type: 'dashboard', ref: '1', path: 'Marketing/A' } as any,
+ 'Marketing/A',
+ 'Product/A'
+ )
+ }).toDispatchActions(['loadDashboardFileSystemEntries', 'loadDashboardFileSystemEntriesSuccess'])
+ expect(logic.values.entryByRef['1']?.path).toEqual('Product/A')
+ })
+
+ it('ignores moves of non-dashboard, non-folder items (no wasted refetch)', async () => {
+ await expectLogic(logic).toDispatchActions([
+ 'loadDashboardFileSystemEntriesSuccess',
+ 'loadFolderEntriesSuccess',
+ ])
+ ;(api.fileSystem.list as jest.Mock).mockClear()
+ projectTreeDataLogic.actions.movedItem({ id: 'i-1', type: 'insight', path: 'a' } as any, 'a', 'b')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(api.fileSystem.list).not.toHaveBeenCalled()
+ })
+
+ it('refetches the subtree after a duplicate lands', async () => {
+ await expectLogic(logic).toDispatchActions(['loadDashboardFileSystemEntriesSuccess'])
+ await expectLogic(logic, () => {
+ dashboardsModel.actions.duplicateDashboardSuccess({ id: 2, name: 'A (Copy)' } as any)
+ }).toDispatchActions(['loadDashboardFileSystemEntries'])
+ })
+
+ it('createFolder creates a folder under the current folder, syncs the sidebar, refetches, and selects it', async () => {
+ await expectLogic(logic).toDispatchActions(['loadDashboardFileSystemEntriesSuccess'])
+ logic.actions.navigateToFolder('Marketing')
+ ;(api.fileSystem.create as jest.Mock).mockClear()
+ await expectLogic(logic, () => logic.actions.createFolder('Ideas')).toDispatchActions([
+ 'createFolder',
+ // Syncs the sidebar's shared store, then refreshes our own folder rows.
+ 'createSavedItem',
+ 'loadFolderEntries',
+ ])
+ expect(api.fileSystem.create).toHaveBeenCalledWith({ type: 'folder', path: 'Marketing/Ideas' })
+ expect(logic.values.currentFolder).toEqual('Marketing/Ideas')
+ })
+
+ it('createFolder ignores a blank name', async () => {
+ ;(api.fileSystem.create as jest.Mock).mockClear()
+ logic.actions.createFolder(' ')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(api.fileSystem.create).not.toHaveBeenCalled()
+ })
+
+ it('toasts an error when loading dashboard folders fails', async () => {
+ await expectLogic(logic).toDispatchActions(['loadDashboardFileSystemEntriesSuccess'])
+ const error = jest.spyOn(lemonToast, 'error').mockReturnValue('' as any)
+ ;(api.fileSystem.list as jest.Mock).mockRejectedValueOnce(new Error('boom'))
+ await expectLogic(logic, () => {
+ logic.actions.loadDashboardFileSystemEntries()
+ }).toDispatchActions(['loadDashboardFileSystemEntriesFailure'])
+ expect(error).toHaveBeenCalled()
+ })
+
+ it('toasts an error when loading folder rows fails', async () => {
+ await expectLogic(logic).toDispatchActions(['loadFolderEntriesSuccess'])
+ const error = jest.spyOn(lemonToast, 'error').mockReturnValue('' as any)
+ ;(api.fileSystem.list as jest.Mock).mockRejectedValueOnce(new Error('boom'))
+ await expectLogic(logic, () => {
+ logic.actions.loadFolderEntries()
+ }).toDispatchActions(['loadFolderEntriesFailure'])
+ expect(error).toHaveBeenCalled()
+ })
+
+ it('renameFolder moves the folder to the renamed sibling path and re-points the current scope', async () => {
+ const move = jest.spyOn(api.fileSystem, 'move').mockResolvedValue({} as any)
+ await expectLogic(logic).toDispatchActions(['loadFolderEntriesSuccess'])
+ logic.actions.navigateToFolder('Marketing')
+ logic.actions.renameFolder({ id: 'fld', type: 'folder', path: 'Marketing' } as any, 'Growth')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(move).toHaveBeenCalledWith('fld', 'Growth')
+ expect(logic.values.currentFolder).toEqual('Growth')
+ })
+
+ it('renameFolder ignores a blank name and an unsaved (id-less) folder', async () => {
+ const move = jest.spyOn(api.fileSystem, 'move').mockResolvedValue({} as any)
+ logic.actions.renameFolder({ id: 'fld', type: 'folder', path: 'Marketing' } as any, ' ')
+ logic.actions.renameFolder({ type: 'folder', path: 'Marketing' } as any, 'Growth')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(move).not.toHaveBeenCalled()
+ })
+
+ it('deleteFolder delegates to the shared delete path (projectTreeDataLogic.deleteItem)', async () => {
+ jest.spyOn(api.fileSystem, 'count').mockResolvedValue({ count: 0 } as any)
+ jest.spyOn(api.fileSystem, 'delete').mockResolvedValue({ deleted: [] } as any)
+ await expectLogic(logic, () => {
+ logic.actions.deleteFolder({ id: 'fld', type: 'folder', path: 'Marketing' } as any)
+ }).toDispatchActions([projectTreeDataLogic.actionTypes.deleteItem])
+ })
+
+ it('on delete, refetches and falls back to root when the current folder OR an ancestor is gone', async () => {
+ await expectLogic(logic).toDispatchActions(['loadFolderEntriesSuccess'])
+ logic.actions.navigateToFolder('Marketing/Q1')
+ await expectLogic(logic, () => {
+ // Deleting the ancestor 'Marketing' while scoped to 'Marketing/Q1' must reset to root.
+ projectTreeDataLogic.actions.deleteSavedItem({ id: 'fld', type: 'folder', path: 'Marketing' } as any)
+ }).toDispatchActions(['loadFolderEntries', 'loadDashboardFileSystemEntries'])
+ expect(logic.values.currentFolder).toEqual('')
+ })
+
+ it('on delete of an unrelated folder, keeps the current scope', async () => {
+ logic.actions.navigateToFolder('Marketing')
+ projectTreeDataLogic.actions.deleteSavedItem({ id: 'fld', type: 'folder', path: 'Finance' } as any)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.currentFolder).toEqual('Marketing')
+ })
+
+ it('refetches on undo (restoredItems) so restored items reappear without a reload', async () => {
+ await expectLogic(logic).toDispatchActions(['loadFolderEntriesSuccess'])
+ await expectLogic(logic, () => {
+ projectTreeDataLogic.actions.restoredItems()
+ }).toDispatchActions(['loadFolderEntries', 'loadDashboardFileSystemEntries'])
+ })
+
+ it('renameFolder re-points a descendant scope onto the renamed path', async () => {
+ jest.spyOn(api.fileSystem, 'move').mockResolvedValue({} as any)
+ await expectLogic(logic).toDispatchActions(['loadFolderEntriesSuccess'])
+ logic.actions.navigateToFolder('Marketing/Q1')
+ logic.actions.renameFolder({ id: 'fld', type: 'folder', path: 'Marketing' } as any, 'Growth')
+ await expectLogic(logic).toFinishAllListeners()
+ // Renaming the ancestor 'Marketing' → 'Growth' moves the descendant scope to 'Growth/Q1'.
+ expect(logic.values.currentFolder).toEqual('Growth/Q1')
+ })
+})
diff --git a/products/dashboards/frontend/logics/dashboardsFileSystemLogic.ts b/products/dashboards/frontend/logics/dashboardsFileSystemLogic.ts
new file mode 100644
index 000000000000..4296e3d96ebb
--- /dev/null
+++ b/products/dashboards/frontend/logics/dashboardsFileSystemLogic.ts
@@ -0,0 +1,276 @@
+import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { withTimeout } from 'lib/utils/async'
+import { dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
+
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
+import { joinPath, splitPath } from '~/layout/panel-layout/ProjectTree/utils'
+import { dashboardsModel } from '~/models/dashboardsModel'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+import { DashboardBasicType } from '~/types'
+
+import type { dashboardsFileSystemLogicType } from './dashboardsFileSystemLogicType'
+import {
+ buildEntryByRef,
+ buildFolderDashboardCounts,
+ buildFolderTree,
+ FolderTreeNode,
+ subtreeDashboards,
+} from './dashboardsFileSystemUtils'
+
+const FILE_SYSTEM_PAGE_SIZE = 500
+// Safety ceiling so a misbehaving endpoint can't loop forever — 10 pages = 5k entries, well above any realistic
+// single project (and far cheaper to load than the old 40-page cap).
+const MAX_FILE_SYSTEM_PAGES = 10
+// Per-page timeout so one hung request can't leave the tree loader pending forever (mirrors the sidebar's
+// shortcuts loader); the abort signal cancels the in-flight request on timeout.
+const FILE_SYSTEM_PAGE_TIMEOUT_MS = 10000
+// Scopes projectTreeDataLogic's optional post-processing (selection clear, undo re-expand) for our reused delete
+// path; safely no-ops for our unmounted instance.
+const DASHBOARDS_TREE_PROJECT_LOGIC_KEY = 'dashboards-tree'
+
+// Page through every dashboard/folder FileSystem entry so large projects render their full tree instead of
+// being silently truncated to the first page — the experiment measures navigation, and big projects are
+// exactly the ones the tree is meant to help.
+async function fetchAllFileSystemEntries(type: 'dashboard' | 'folder'): Promise<FileSystemEntry[]> {
+ const entries: FileSystemEntry[] = []
+ for (let page = 0; page < MAX_FILE_SYSTEM_PAGES; page++) {
+ const response = await withTimeout(
+ (signal) =>
+ api.fileSystem.list({
+ type,
+ limit: FILE_SYSTEM_PAGE_SIZE,
+ offset: page * FILE_SYSTEM_PAGE_SIZE,
+ signal,
+ }),
+ FILE_SYSTEM_PAGE_TIMEOUT_MS,
+ `dashboardsFileSystemLogic: ${type} page ${page} timed out`
+ )
+ entries.push(...response.results)
+ if (response.results.length < FILE_SYSTEM_PAGE_SIZE) {
+ return entries
+ }
+ }
+ // Hitting the ceiling means a project's tree is truncated — emit a signal (not just a console.warn) so we can
+ // spot affected projects and raise the cap if real usage demands it.
+ posthog.capture('dashboards tree pagination ceiling hit', {
+ entry_type: type,
+ entries_loaded: entries.length,
+ ceiling: MAX_FILE_SYSTEM_PAGES * FILE_SYSTEM_PAGE_SIZE,
+ })
+ return entries
+}
+
+// View state for the tree arm: a folder tree built from the same FileSystem rows that back the sidebar
+// (both dashboard and folder rows, so empty folders appear), the selected folder, its expand state, and the
+// dashboards at or below it. Folder creation calls api.fileSystem.create then
+// projectTreeDataLogic.createSavedItem so the sidebar's in-memory store stays consistent. Per-dashboard
+// organizing (move / rename / delete) is handled by the reused DashboardsTable's own row actions, which go
+// through the shared move path — there is no second folder model to sync.
+export const dashboardsFileSystemLogic = kea<dashboardsFileSystemLogicType>([
+ path(['products', 'dashboards', 'dashboardsFileSystemLogic']),
+ connect(() => ({
+ values: [dashboardsLogic, ['dashboards']],
+ actions: [projectTreeDataLogic, ['createSavedItem', 'movedItem', 'deleteItem']],
+ })),
+ actions({
+ // Tree arm: select a folder ('' = the dashboards root).
+ navigateToFolder: (folder: string) => ({ folder }),
+ // Toggle a folder's expand/collapse state in the panel (folders start collapsed — see expandedFolders).
+ toggleFolder: (folder: string) => ({ folder }),
+ // Replace the whole expanded-folders map at once (Expand all / Collapse all).
+ setExpandedFolders: (folders: Record<string, boolean>) => ({ folders }),
+ // Create a folder inside `parentPath` ('' = root; defaults to the selected folder when omitted).
+ createFolder: (name: string, parentPath?: string) => ({ name, parentPath }),
+ // Rename a folder — moves it to a sibling path carrying the new name (descendants re-path server-side).
+ renameFolder: (entry: FileSystemEntry, newName: string) => ({ entry, newName }),
+ // Delete a folder via the shared delete path (its confirmation + undo + store sync live there).
+ deleteFolder: (entry: FileSystemEntry) => ({ entry }),
+ }),
+ loaders({
+ dashboardFileSystemEntries: [
+ [] as FileSystemEntry[],
+ {
+ loadDashboardFileSystemEntries: async (): Promise<FileSystemEntry[]> =>
+ await fetchAllFileSystemEntries('dashboard'),
+ },
+ ],
+ // Real folder rows, so empty folders (and ones the user creates) show up in the tree — not just
+ // folders inferred from dashboard paths.
+ folderEntries: [
+ [] as FileSystemEntry[],
+ {
+ loadFolderEntries: async (): Promise<FileSystemEntry[]> => await fetchAllFileSystemEntries('folder'),
+ },
+ ],
+ }),
+ reducers({
+ currentFolder: [
+ '',
+ {
+ navigateToFolder: (_, { folder }) => folder,
+ },
+ ],
+ // Folders the user has explicitly expanded. The tree starts collapsed except for the root, so it
+ // opens with just the top-level folders; clicking a folder expands it. Persisted to localStorage
+ // (like the sidebar tree) so an accidental reload keeps your folders open; stale paths from since-
+ // deleted folders are harmless — they're filtered against the live tree before use.
+ expandedFolders: [
+ {} as Record<string, boolean>,
+ { persist: true },
+ {
+ toggleFolder: (state, { folder }) => ({ ...state, [folder]: !state[folder] }),
+ setExpandedFolders: (_, { folders }) => folders,
+ },
+ ],
+ }),
+ selectors({
+ entryByRef: [
+ (s) => [s.dashboardFileSystemEntries],
+ (entries): Record<string, FileSystemEntry> => buildEntryByRef(entries),
+ ],
+ folderPaths: [(s) => [s.folderEntries], (folderEntries): string[] => folderEntries.map((entry) => entry.path)],
+ // Real folder rows keyed by path, so the folder menu can act on a folder's FileSystemEntry (needs its
+ // id). Folders that exist only because a dashboard references them (no row) are absent — the menu hides
+ // move/rename/delete for those and offers only "New subfolder".
+ folderEntryByPath: [
+ (s) => [s.folderEntries],
+ (folderEntries): Record<string, FileSystemEntry> =>
+ Object.fromEntries(folderEntries.map((entry) => [entry.path, entry])),
+ ],
+ folderTree: [
+ (s) => [s.dashboards, s.entryByRef, s.folderPaths],
+ (dashboards, entryByRef, folderPaths): FolderTreeNode[] =>
+ buildFolderTree(dashboards, entryByRef, folderPaths),
+ ],
+ // Tree arm: every dashboard at or below the selected folder, recursively (root = all). The tree is a
+ // scope selector; the content pane (DashboardsTable) shows everything in scope.
+ currentSubtreeDashboards: [
+ (s) => [s.dashboards, s.entryByRef, s.currentFolder],
+ (dashboards, entryByRef, currentFolder): DashboardBasicType[] =>
+ subtreeDashboards(dashboards, entryByRef, currentFolder),
+ ],
+ // Dashboard count per folder path (subtree), for the tree's trailing count badges.
+ folderDashboardCounts: [
+ (s) => [s.dashboards, s.entryByRef],
+ (dashboards, entryByRef): Record<string, number> => buildFolderDashboardCounts(dashboards, entryByRef),
+ ],
+ }),
+ listeners(({ values, actions }) => ({
+ // A duplicate (via the table) creates a dashboard server-side; refetch so the subtree reflects it
+ // (the new dashboard syncs its own FileSystem entry via FileSystemSyncMixin).
+ [dashboardsModel.actionTypes.duplicateDashboardSuccess]: () => {
+ actions.loadDashboardFileSystemEntries()
+ },
+ // A move lands as movedItem AFTER the server commit (the table's "Move to" action goes through the
+ // shared move path). A dashboard move changes its own path; a folder move re-parents the dashboards
+ // beneath it (and the folder rows). Other item types (insights, notebooks) don't affect this view,
+ // so skip the refetch for them.
+ [projectTreeDataLogic.actionTypes.movedItem]: ({ item }) => {
+ if (item.type === 'dashboard' || item.type === 'folder') {
+ actions.loadDashboardFileSystemEntries()
+ }
+ if (item.type === 'folder') {
+ actions.loadFolderEntries()
+ }
+ },
+ loadDashboardFileSystemEntriesFailure: () => {
+ // Without this the folder structure silently collapses to Unfiled (kea-loaders only
+ // console.errors), so the degraded state would look like a genuinely flat project.
+ lemonToast.error('Could not load dashboard folders — they may appear unorganized. Refresh to retry.')
+ },
+ loadFolderEntriesFailure: () => {
+ // Mirror the dashboard-entries failure toast: without it, empty folders silently disappear and
+ // the degraded structure looks like a genuinely flat project.
+ lemonToast.error('Could not load folders — empty folders may not appear. Refresh to retry.')
+ },
+ createFolder: async ({ name, parentPath }) => {
+ const trimmed = name.trim()
+ if (!trimmed) {
+ return
+ }
+ const parent = parentPath ?? values.currentFolder
+ const path = joinPath([...(parent ? splitPath(parent) : []), trimmed])
+ try {
+ const created = await api.fileSystem.create({ type: 'folder', path } as FileSystemEntry)
+ // Sync the sidebar's shared store the same way the project-tree create path does, then
+ // refresh our own folder rows and select the new folder.
+ actions.createSavedItem(created)
+ actions.loadFolderEntries()
+ actions.navigateToFolder(path)
+ lemonToast.success(`Created folder "${trimmed}"`)
+ } catch (error) {
+ console.error('Error creating folder:', error)
+ // Runs in an async listener, not a kea-loader, so initKea's global onFailure never sees it —
+ // capture here or we're blind to folder-create error rates (a key adoption-metric operation).
+ posthog.captureException(error)
+ lemonToast.error('Could not create the folder.')
+ }
+ },
+ renameFolder: async ({ entry, newName }) => {
+ const trimmed = newName.trim()
+ if (!trimmed || !entry.id) {
+ return
+ }
+ const newPath = joinPath([...splitPath(entry.path).slice(0, -1), trimmed])
+ if (newPath === entry.path) {
+ return
+ }
+ try {
+ await api.fileSystem.move(entry.id, newPath)
+ // movedItem syncs the sidebar's store and (via our own listener below) refetches this tree.
+ actions.movedItem(entry, entry.path, newPath)
+ // Re-point the scope if we were inside the renamed folder — or a descendant of it, which moves
+ // with it. (deleteSavedItem falls back to root because the folder is gone; rename keeps it.)
+ if (values.currentFolder === entry.path) {
+ actions.navigateToFolder(newPath)
+ } else if (values.currentFolder.startsWith(`${entry.path}/`)) {
+ actions.navigateToFolder(newPath + values.currentFolder.slice(entry.path.length))
+ }
+ lemonToast.success(`Renamed to "${trimmed}"`)
+ } catch (error) {
+ console.error('Error renaming folder:', error)
+ // Async listener, not a kea-loader — capture so folder-rename failures surface in error tracking.
+ posthog.captureException(error)
+ lemonToast.error('Could not rename the folder.')
+ }
+ },
+ deleteFolder: ({ entry }) => {
+ // Reuse the shared delete: large-folder confirmation, undo toast, and store sync all live there.
+ // The follow-up refetch happens in the deleteSavedItem listener below.
+ actions.deleteItem(entry, DASHBOARDS_TREE_PROJECT_LOGIC_KEY)
+ },
+ [projectTreeDataLogic.actionTypes.deleteSavedItem]: ({ savedItem }) => {
+ // Only dashboards/folders affect this view — ignore unrelated sidebar deletes (insights, notebooks),
+ // matching the movedItem listener's type-gate.
+ if (savedItem.type !== 'dashboard' && savedItem.type !== 'folder') {
+ return
+ }
+ // Deleting a folder cascades to its dashboards (soft-deleted server-side, undoable). Refetch our
+ // FileSystem rows AND the dashboards list itself — without the latter the soft-deleted dashboards
+ // linger in dashboardsModel and the folder looks like it didn't delete.
+ actions.loadFolderEntries()
+ actions.loadDashboardFileSystemEntries()
+ dashboardsModel.actions.loadDashboards()
+ // If the folder we were scoped to — or an ancestor of it — is gone, fall back to the root
+ // rather than leaving the table pointed at a now-deleted subtree.
+ if (values.currentFolder === savedItem.path || values.currentFolder.startsWith(`${savedItem.path}/`)) {
+ actions.navigateToFolder('')
+ }
+ },
+ [projectTreeDataLogic.actionTypes.restoredItems]: () => {
+ // An undo-delete restored items server-side; refetch so they reappear without a page reload.
+ actions.loadFolderEntries()
+ actions.loadDashboardFileSystemEntries()
+ dashboardsModel.actions.loadDashboards()
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadDashboardFileSystemEntries()
+ actions.loadFolderEntries()
+ }),
+])
diff --git a/products/dashboards/frontend/logics/dashboardsFileSystemUtils.test.ts b/products/dashboards/frontend/logics/dashboardsFileSystemUtils.test.ts
new file mode 100644
index 000000000000..25d5e01b5c7b
--- /dev/null
+++ b/products/dashboards/frontend/logics/dashboardsFileSystemUtils.test.ts
@@ -0,0 +1,90 @@
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+import { DashboardBasicType } from '~/types'
+
+import {
+ buildEntryByRef,
+ buildFolderDashboardCounts,
+ buildFolderTree,
+ subtreeDashboards,
+} from './dashboardsFileSystemUtils'
+
+const dash = (id: number, name: string): DashboardBasicType => ({ id, name }) as DashboardBasicType
+const entry = (ref: string, path: string): FileSystemEntry =>
+ ({ id: `fs-${ref}`, type: 'dashboard', ref, path }) as FileSystemEntry
+
+describe('dashboardsFileSystemUtils', () => {
+ it('indexes only dashboard entries by ref', () => {
+ const byRef = buildEntryByRef([
+ entry('1', 'Marketing/A'),
+ { id: 'fld', type: 'folder', path: 'Marketing' } as FileSystemEntry,
+ ])
+ expect(Object.keys(byRef)).toEqual(['1'])
+ })
+
+ it('builds a nested folder tree from dashboard paths, with ancestors and Unfiled, sorted', () => {
+ const dashboards = [dash(1, 'A'), dash(2, 'B'), dash(3, 'C')]
+ const byRef = buildEntryByRef([entry('1', 'Marketing/A'), entry('2', 'Marketing/Q1/B')])
+ expect(buildFolderTree(dashboards, byRef)).toEqual([
+ { path: 'Marketing', label: 'Marketing', children: [{ path: 'Marketing/Q1', label: 'Q1', children: [] }] },
+ {
+ path: 'Unfiled',
+ label: 'Unfiled',
+ children: [{ path: 'Unfiled/Dashboards', label: 'Dashboards', children: [] }],
+ },
+ ])
+ })
+
+ it('returns an empty tree when there are no dashboards', () => {
+ expect(buildFolderTree([], {})).toEqual([])
+ })
+
+ it('tolerates an undefined dashboards list (transient during a cascading delete) without throwing', () => {
+ expect(buildFolderTree(undefined, {})).toEqual([])
+ expect(buildFolderDashboardCounts(undefined, {})).toEqual({})
+ expect(subtreeDashboards(undefined, {}, 'Marketing')).toEqual([])
+ })
+
+ it('buildFolderTree includes empty folder rows (no dashboards beneath) and their ancestors', () => {
+ const byRef = buildEntryByRef([entry('1', 'Marketing/A')])
+ const tree = buildFolderTree([dash(1, 'A')], byRef, ['Ideas', 'Archive/2024'])
+ expect(tree.map((node) => node.path)).toEqual(['Archive', 'Ideas', 'Marketing'])
+ expect(tree.find((node) => node.path === 'Archive')?.children.map((c) => c.path)).toEqual(['Archive/2024'])
+ })
+
+ it('subtreeDashboards returns every dashboard at or below a folder (root = all)', () => {
+ const byRef = buildEntryByRef([
+ entry('1', 'Marketing/A'),
+ entry('2', 'Marketing/Q1/B'),
+ entry('3', 'Product/C'),
+ ])
+ const dashboards = [dash(1, 'A'), dash(2, 'B'), dash(3, 'C')]
+ expect(subtreeDashboards(dashboards, byRef, 'Marketing')).toEqual([dash(1, 'A'), dash(2, 'B')])
+ expect(subtreeDashboards(dashboards, byRef, '').map((d) => d.id)).toEqual([1, 2, 3])
+ })
+
+ it('counts dashboards per folder subtree, with ancestors, Unfiled, and the root total', () => {
+ const byRef = buildEntryByRef([
+ entry('1', 'Marketing/A'),
+ entry('2', 'Marketing/Q1/B'),
+ entry('3', 'Product/C'),
+ ])
+ // id 4 has no entry → Unfiled.
+ const dashboards = [dash(1, 'A'), dash(2, 'B'), dash(3, 'C'), dash(4, 'D')]
+ expect(buildFolderDashboardCounts(dashboards, byRef)).toEqual({
+ '': 4,
+ Marketing: 2,
+ 'Marketing/Q1': 1,
+ Product: 1,
+ Unfiled: 1,
+ 'Unfiled/Dashboards': 1,
+ })
+ })
+
+ it('subtreeDashboards treats dashboards with no folder entry as Unfiled', () => {
+ const byRef = buildEntryByRef([entry('1', 'Marketing/A')])
+ const dashboards = [dash(1, 'A'), dash(2, 'B')]
+ // id 2 has no entry → Unfiled/Dashboards; only matches the Unfiled subtree, not Marketing.
+ expect(subtreeDashboards(dashboards, byRef, 'Marketing').map((d) => d.id)).toEqual([1])
+ expect(subtreeDashboards(dashboards, byRef, 'Unfiled').map((d) => d.id)).toEqual([2])
+ })
+})
diff --git a/products/dashboards/frontend/logics/dashboardsFileSystemUtils.ts b/products/dashboards/frontend/logics/dashboardsFileSystemUtils.ts
new file mode 100644
index 000000000000..19bc8079defe
--- /dev/null
+++ b/products/dashboards/frontend/logics/dashboardsFileSystemUtils.ts
@@ -0,0 +1,113 @@
+import { UNFILED_DASHBOARDS_FOLDER } from 'scenes/dashboard/dashboardConstants'
+
+import { joinPath, splitPath } from '~/layout/panel-layout/ProjectTree/utils'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+import { DashboardBasicType } from '~/types'
+
+const UNFILED_SEGMENTS = splitPath(UNFILED_DASHBOARDS_FOLDER)
+
+// The path segments of a dashboard's containing folder (its FileSystem entry's path minus the last
+// segment); empty when the dashboard has no entry. Callers decide how to treat the empty case (the tree
+// groups those under Unfiled; the Folder column labels them "Unfiled").
+export function dashboardParentSegments(entry: FileSystemEntry | undefined): string[] {
+ return entry?.path ? splitPath(entry.path).slice(0, -1) : []
+}
+
+export interface FolderTreeNode {
+ // Full folder path, e.g. 'Marketing/Q1'.
+ path: string
+ // Last path segment, for display.
+ label: string
+ children: FolderTreeNode[]
+}
+
+// Index dashboard FileSystem rows by their `ref` (the dashboard id as a string) for O(1) lookup.
+export function buildEntryByRef(entries: FileSystemEntry[]): Record<string, FileSystemEntry> {
+ const byRef: Record<string, FileSystemEntry> = {}
+ for (const entry of entries) {
+ if (entry.type === 'dashboard' && entry.ref) {
+ byRef[entry.ref] = entry
+ }
+ }
+ return byRef
+}
+
+// Build the nested folder tree the tree arm renders in its LemonTree panel: every folder that contains a
+// dashboard (plus all its ancestors), unioned with the explicit `folderPaths` (real folder rows) so empty
+// folders also appear. Unfiled dashboards contribute the Unfiled subtree.
+export function buildFolderTree(
+ // `dashboards` is connected from dashboardsLogic and can be momentarily undefined while a mutation
+ // (e.g. a cascading folder delete) reloads the model — tolerate it rather than crash the recompute.
+ dashboards: DashboardBasicType[] | undefined,
+ entryByRef: Record<string, FileSystemEntry>,
+ folderPaths: string[] = []
+): FolderTreeNode[] {
+ const allFolderPaths = new Set<string>()
+ const addWithAncestors = (segments: string[]): void => {
+ for (let i = 1; i <= segments.length; i++) {
+ allFolderPaths.add(joinPath(segments.slice(0, i)))
+ }
+ }
+ for (const dashboard of dashboards ?? []) {
+ const parentSegments = dashboardParentSegments(entryByRef[String(dashboard.id)])
+ addWithAncestors(parentSegments.length > 0 ? parentSegments : UNFILED_SEGMENTS)
+ }
+ for (const folderPath of folderPaths) {
+ addWithAncestors(splitPath(folderPath))
+ }
+
+ const byPath = new Map<string, FolderTreeNode>()
+ const roots: FolderTreeNode[] = []
+ // Split each path once, then shallowest-first so a node's parent always exists before it's attached.
+ const sorted = [...allFolderPaths]
+ .map((path) => ({ path, segments: splitPath(path) }))
+ .sort((a, b) => a.segments.length - b.segments.length || a.path.localeCompare(b.path))
+ for (const { path, segments } of sorted) {
+ const node: FolderTreeNode = { path, label: segments.at(-1) ?? path, children: [] }
+ byPath.set(path, node)
+ const parent = segments.length > 1 ? byPath.get(joinPath(segments.slice(0, -1))) : undefined
+ ;(parent ? parent.children : roots).push(node)
+ }
+
+ const sortChildren = (nodes: FolderTreeNode[]): void => {
+ nodes.sort((a, b) => a.label.localeCompare(b.label))
+ nodes.forEach((node) => sortChildren(node.children))
+ }
+ sortChildren(roots)
+ return roots
+}
+
+// Dashboards at or below each folder path, so a folder's badge matches the subtree the table shows when
+// you select it. Each dashboard contributes to its containing folder, every ancestor, and the root ('').
+// Mirrors buildFolderTree's Unfiled handling so the counts line up with the rendered tree.
+export function buildFolderDashboardCounts(
+ dashboards: DashboardBasicType[] | undefined,
+ entryByRef: Record<string, FileSystemEntry>
+): Record<string, number> {
+ const counts: Record<string, number> = {}
+ for (const dashboard of dashboards ?? []) {
+ const parentSegments = dashboardParentSegments(entryByRef[String(dashboard.id)])
+ const segments = parentSegments.length > 0 ? parentSegments : UNFILED_SEGMENTS
+ counts[''] = (counts[''] ?? 0) + 1
+ for (let i = 1; i <= segments.length; i++) {
+ const path = joinPath(segments.slice(0, i))
+ counts[path] = (counts[path] ?? 0) + 1
+ }
+ }
+ return counts
+}
+
+// Every dashboard at or below `currentFolder`, recursively. Root ('') returns all dashboards. The tree
+// arm feeds these to the dashboards table, scoped to the selected folder's subtree.
+export function subtreeDashboards(
+ dashboards: DashboardBasicType[] | undefined,
+ entryByRef: Record<string, FileSystemEntry>,
+ currentFolder: string
+): DashboardBasicType[] {
+ const prefix = currentFolder ? splitPath(currentFolder) : []
+ return (dashboards ?? []).filter((dashboard) => {
+ const entry = entryByRef[String(dashboard.id)]
+ const segments = entry?.path ? splitPath(entry.path).slice(0, -1) : UNFILED_SEGMENTS
+ return prefix.every((segment, index) => segments[index] === segment)
+ })
+}
diff --git a/products/dashboards/frontend/logics/dashboardsListViewVariants.test.ts b/products/dashboards/frontend/logics/dashboardsListViewVariants.test.ts
new file mode 100644
index 000000000000..669300f3601a
--- /dev/null
+++ b/products/dashboards/frontend/logics/dashboardsListViewVariants.test.ts
@@ -0,0 +1,25 @@
+import { FEATURE_FLAGS } from 'lib/constants'
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+
+import { DashboardsListViewVariant, resolveDashboardsListViewVariant } from './dashboardsListViewVariants'
+
+// Experiment cleanup: flag `dashboards-list-view` · experiment 379125 — remove with the tree arm.
+describe('resolveDashboardsListViewVariant', () => {
+ const cases: [string | boolean | undefined, DashboardsListViewVariant][] = [
+ [undefined, 'control'],
+ ['', 'control'],
+ ['unknown', 'control'],
+ [true, 'control'],
+ ['control', 'control'],
+ ['tree', 'tree'],
+ // Retired arm names now fall back to control rather than enrolling a treatment arm.
+ ['explorer', 'control'],
+ ['grid', 'control'],
+ ['finder', 'control'],
+ ]
+
+ it.each(cases)('flag value %p resolves to %p', (value, expected) => {
+ const featureFlags: FeatureFlagsSet = value === undefined ? {} : { [FEATURE_FLAGS.DASHBOARDS_LIST_VIEW]: value }
+ expect(resolveDashboardsListViewVariant(featureFlags)).toBe(expected)
+ })
+})
diff --git a/products/dashboards/frontend/logics/dashboardsListViewVariants.ts b/products/dashboards/frontend/logics/dashboardsListViewVariants.ts
new file mode 100644
index 000000000000..03e7ba3ebc49
--- /dev/null
+++ b/products/dashboards/frontend/logics/dashboardsListViewVariants.ts
@@ -0,0 +1,21 @@
+import { FEATURE_FLAGS } from 'lib/constants'
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+
+// One folder-navigation paradigm tested against today's flat list: `tree` (a persistent folder-tree panel
+// beside the table). The `grid` and `explorer` arms were both dropped before launch — see the design spec.
+// Experiment cleanup: flag `dashboards-list-view` · experiment 379125 — remove this resolver and the tree arm
+// when the experiment concludes.
+export type DashboardsListViewVariant = 'control' | 'tree'
+
+const DEFAULT_VARIANT: DashboardsListViewVariant = 'control'
+
+export const DASHBOARDS_LIST_VIEW_VARIANTS: DashboardsListViewVariant[] = ['control', 'tree']
+
+// Resolves the `dashboards-list-view` multivariate flag to a known arm, defaulting to control
+// so a missing, unknown, boolean, or empty flag value never silently enrolls a project in a treatment arm.
+export function resolveDashboardsListViewVariant(featureFlags: FeatureFlagsSet): DashboardsListViewVariant {
+ const variant = featureFlags[FEATURE_FLAGS.DASHBOARDS_LIST_VIEW]
+ return typeof variant === 'string' && (DASHBOARDS_LIST_VIEW_VARIANTS as string[]).includes(variant)
+ ? (variant as DashboardsListViewVariant)
+ : DEFAULT_VARIANT
+}
diff --git a/products/dashboards/package.json b/products/dashboards/package.json
index 3daf91c43e92..22283b76693d 100644
--- a/products/dashboards/package.json
+++ b/products/dashboards/package.json
@@ -15,7 +15,8 @@
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^14.3.1",
"@testing-library/user-event": "^14.6.1",
- "jest": "^29.7.0"
+ "jest": "^29.7.0",
+ "kea-test-utils": "catalog:"
},
"peerDependencies": {
"@posthog/brand": "catalog:",