: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(dashboards): show and filter by folder in dashboards list (#64391)
Matt Pua9fd4e4127483
diff --git a/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx b/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsxindex 9eb696bd323f..bb5b45986083 100644--- a/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx+++ b/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx@@ -148,6 +148,7 @@ const dashboardActionsMapping: Record<breakdown_colors: () => null,data_color_theme_id: () => null,last_accessed_at: () => null,+ folder: () => null,is_shared: () => null,creation_mode: () => null,user_access_level: () => null,diff --git a/frontend/src/scenes/dashboard/dashboardConstants.ts b/frontend/src/scenes/dashboard/dashboardConstants.tsindex 14a595767b89..45aba9c24756 100644--- a/frontend/src/scenes/dashboard/dashboardConstants.ts+++ b/frontend/src/scenes/dashboard/dashboardConstants.ts@@ -8,3 +8,6 @@ export const AUTO_REFRESH_INITIAL_INTERVAL_SECONDS = DashboardAutoRefreshInterva* backend throttle (`SHARED_FORCE_BLOCKING_MIN_AGE`).*/export const SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES = AUTO_REFRESH_INITIAL_INTERVAL_SECONDS / 60++/** Default project-tree folder for dashboards that haven't been filed anywhere (mirrors the backend's `base_folder`). */+export const UNFILED_DASHBOARDS_FOLDER = 'Unfiled/Dashboards'diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsxindex 404493f3d88f..36eb9c268d01 100644--- a/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { useDebouncedCallback } from 'use-debounce'-import { IconChevronDown, IconPin, IconPinFilled, IconShare } from '@posthog/icons'+import { IconChevronDown, IconFolder, IconPin, IconPinFilled, IconShare, IconX } from '@posthog/icons'import { LemonInput, Popover } from '@posthog/lemon-ui'import { MemberSelect } from 'lib/components/MemberSelect'@@ -42,7 +42,7 @@ export function DashboardsFiltersBar({ extraActions }: DashboardsFiltersBarPropsvalue={filters.search}/><div className="flex items-center gap-2 flex-wrap">- <div className="flex items-center gap-2">+ <div className="flex items-center gap-2 flex-wrap"><span>Filter to:</span>{currentTab !== DashboardsTab.Pinned && (<div className="flex items-center gap-2">@@ -144,6 +144,20 @@ export function DashboardsFiltersBar({ extraActions }: DashboardsFiltersBarPropsShared</LemonButton></div>+ {filters.folder != null && (+ <LemonButton+ active+ type="secondary"+ size="small"+ className="max-w-full"+ icon={<IconFolder />}+ sideIcon={<IconX />}+ onClick={() => setFilters({ folder: null })}+ tooltip="Clear folder filter"+ >+ <span className="truncate">{filters.folder || 'Project root'}</span>+ </LemonButton>+ )}</div>{currentTab !== DashboardsTab.Yours && (<div className="flex items-center gap-2">diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsxindex 0d2027ad8ed1..ba9aa1c360f0 100644--- a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { IconHome, IconLock, IconPin, IconPinFilled, IconShare } from '@posthog/icons'+import { IconFolder, IconHome, IconLock, IconPin, IconPinFilled, IconShare } from '@posthog/icons'import { AccessControlAction } from 'lib/components/AccessControlAction'import { BulkUpdateTagsButton } from 'lib/components/BulkActions/BulkUpdateTagsButton'@@ -34,6 +34,7 @@ import {DashboardType,} from '~/types'+import { UNFILED_DASHBOARDS_FOLDER } from '../dashboardConstants'import { DASHBOARD_CANNOT_EDIT_MESSAGE } from '../DashboardHeader'import { DashboardsFiltersBar } from './DashboardsFiltersBar'@@ -58,7 +59,7 @@ export function DashboardsTable({hideActions,}: DashboardsTableProps): JSX.Element {const { unpinDashboard, pinDashboard } = useActions(dashboardsModel)- const { tableSortingChanged } = useActions(dashboardsLogic)+ const { tableSortingChanged, setFilters } = useActions(dashboardsLogic)const { tableSorting, filters } = useValues(dashboardsLogic)// Server-side fuzzy search ranks results by relevance; re-sorting alphabetically by name// would push the exact match below partial matches. Suppress the persisted column sort@@ -138,6 +139,26 @@ export function DashboardsTable({return tags ? <ObjectTags tags={[...tags].sort()} staticOnly /> : null},} as LemonTableColumn<DashboardType, keyof DashboardType | undefined>,+ {+ title: 'Folder',+ dataIndex: 'folder' as keyof DashboardType,+ render: function Render(folder: DashboardType['folder']) {+ // Unfiled dashboards live in the default `Unfiled/Dashboards` folder — that's not a folder+ // the user chose, so show nothing rather than a filter affordance.+ if (folder === null || folder === undefined || folder === UNFILED_DASHBOARDS_FOLDER) {+ return <span className="text-secondary">—</span>+ }+ const label = folder || 'Project root'+ return (+ <Tooltip title={`Filter to dashboards in ${label}`}>+ <Link className="flex items-center gap-1 text-secondary" onClick={() => setFilters({ folder })}>+ <IconFolder className="shrink-0" />+ <span className="truncate">{label}</span>+ </Link>+ </Tooltip>+ )+ },+ } as LemonTableColumn<DashboardType, keyof DashboardType | undefined>,createdByColumn<DashboardType>() as LemonTableColumn<DashboardType, keyof DashboardType | undefined>,createdAtColumn<DashboardType>() as LemonTableColumn<DashboardType, keyof DashboardType | undefined>,atColumn<DashboardType>('last_accessed_at', 'Last accessed at') as LemonTableColumn<@@ -268,6 +289,7 @@ export function DashboardsTable({emptyState="No dashboards matching your filters!"nouns={['dashboard', 'dashboards']}bulkSelection={{+ barClassName: 'mb-2',getKey: (dashboard: DashboardType): number => dashboard.id,isRowSelectable: (dashboard: DashboardType) =>accessLevelSatisfied(diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.tsindex 7f7a79d72bfb..4f6fd6fbbd64 100644--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts@@ -43,8 +43,14 @@ describe('dashboardsLogic', () => {pinned: true,}),},- { ...dashboard({ created_by: { uuid: 'USER_UUID' } as UserBasicType }) },- { ...dashboard({ created_by: { uuid: 'user2' } as UserBasicType, name: 'needle' }) },+ { ...dashboard({ created_by: { uuid: 'USER_UUID' } as UserBasicType, folder: 'Marketing/Website' }) },+ {+ ...dashboard({+ created_by: { uuid: 'user2' } as UserBasicType,+ name: 'needle',+ folder: 'Marketing/Website',+ }),+ },{...dashboard({created_by: { uuid: 'USER_UUID' } as UserBasicType,@@ -118,6 +124,18 @@ describe('dashboardsLogic', () => {})})+ 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 correct dashboards when filtering by name and shared', async () => {expectLogic(logic, () => {logic.actions.setFilters({ createdBy: 'user2', shared: true })diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.tsindex cc1266623fb1..06c52ea53720 100644--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts@@ -32,6 +32,8 @@ export interface DashboardsFilters {pinned: booleanshared: booleantags?: string[]+ /** Folder path to filter to, e.g. 'Unfiled/Dashboards' (empty string = project root). null means no folder filter. */+ folder?: string | null}export const DEFAULT_FILTERS: DashboardsFilters = {@@ -40,6 +42,7 @@ export const DEFAULT_FILTERS: DashboardsFilters = {pinned: false,shared: false,tags: [],+ folder: null,}/** Router may coerce numeric-looking query values to numbers; search text must stay a string. */@@ -117,7 +120,10 @@ export const dashboardsLogic = kea<dashboardsLogicType>([* The 250ms `breakpoint` runs before the empty-term short-circuit so a stale* in-flight request can't clobber a freshly cleared search.*/- loadSearchedDashboards: async ({ search, tags }: { search: string; tags: string[] }, breakpoint) => {+ loadSearchedDashboards: async (+ { search, tags, folder }: { search: string; tags: string[]; folder: string | null },+ breakpoint+ ) => {await breakpoint(250)const term = search.trim()if (!term) {@@ -132,12 +138,16 @@ export const dashboardsLogic = kea<dashboardsLogicType>([limit: '200',exclude_generated: 'true',})- // Push tag filtering to the server so MCP and API clients see the same- // result shape as the UI (and so the limit:200 cap operates on the right- // population — pre-tag-filtered, not post).+ // Push tag/folder filtering to the server so MCP and API clients see the same+ // result shape as the UI, and so the limit:200 cap operates on the right+ // population — filtered first, not after. Without this, a folder filter combined+ // with search would only narrow the top-200 global matches and silently drop the rest.for (const tag of tags) {params.append('tags', tag)}+ if (folder != null) {+ params.append('folder', folder)+ }const response: PaginatedResponse<DashboardBasicType> = await api.get(`api/environments/${teamId}/dashboards/?${params.toString()}`)@@ -206,6 +216,9 @@ export const dashboardsLogic = kea<dashboardsLogicType>([if (filters.tags && filters.tags.length > 0) {haystack = haystack.filter((d) => filters.tags?.some((tag) => d.tags?.includes(tag)))}+ if (filters.folder != null) {+ haystack = haystack.filter((d) => d.folder === filters.folder)+ }return haystack},],@@ -257,6 +270,29 @@ export const dashboardsLogic = kea<dashboardsLogicType>([delete searchParams['search']}+ return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]+ },+ setFilters: () => {+ // Persist the folder filter so it survives reloads/sharing. `null` means no filter (param absent);+ // an empty string is a valid value (project root), so we key off the param's presence, not its value.+ const folder = values.filters.folder ?? null+ const hadFolder = 'folder' in router.values.searchParams+ const currentFolder = hadFolder ? urlSearchParamToString(router.values.searchParams['folder']) : null++ if (folder === currentFolder) {+ return+ }++ const searchParams: Record<string, any> = {+ ...router.values.searchParams,+ }++ if (folder === null) {+ delete searchParams['folder']+ } else {+ searchParams['folder'] = folder+ }+return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]},})),@@ -267,20 +303,28 @@ export const dashboardsLogic = kea<dashboardsLogicType>([const search = urlSearchParamToString(searchParams['search'])actions.setSearch(search)++ const folder = 'folder' in searchParams ? urlSearchParamToString(searchParams['folder']) : null+ actions.setFilters({ folder })},})),listeners(({ actions, values }) => ({setSearch: ({ search }) => {- actions.loadSearchedDashboards({ search, tags: values.filters.tags ?? [] })+ actions.loadSearchedDashboards({+ search,+ tags: values.filters.tags ?? [],+ folder: values.filters.folder ?? null,+ })},setFilters: ({ filters }) => {- // Tag changes refetch when a search is active so server-side filtering stays+ // Tag/folder changes refetch when a search is active so server-side filtering stays// accurate. Other filter keys (pinned/shared/createdBy/currentTab) are still// applied client-side over the in-memory list so they don't refetch.- if ('tags' in filters && values.filters.search) {+ if (('tags' in filters || 'folder' in filters) && values.filters.search) {actions.loadSearchedDashboards({search: values.filters.search,tags: values.filters.tags ?? [],+ folder: values.filters.folder ?? null,})}},diff --git a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateCreationFlows.ts b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateCreationFlows.tsindex db5b4b6ab77a..3d2431dfd827 100644--- a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateCreationFlows.ts+++ b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateCreationFlows.ts@@ -1,3 +1,4 @@+import { UNFILED_DASHBOARDS_FOLDER } from 'scenes/dashboard/dashboardConstants'import type { NewDashboardForm } from 'scenes/dashboard/newDashboardLogic'import type { DashboardTemplateType, DashboardTemplateVariableType } from '~/types'@@ -53,6 +54,6 @@ export function runBlankDashboardFlow(ctx: { isLoading: boolean } & BlankDashboactx.addDashboard({name: 'New Dashboard',show: true,- _create_in_folder: 'Unfiled/Dashboards',+ _create_in_folder: UNFILED_DASHBOARDS_FOLDER,})}diff --git a/frontend/src/scenes/dashboard/newDashboardLogic.ts b/frontend/src/scenes/dashboard/newDashboardLogic.tsindex faab4f88e902..3937248cd968 100644--- a/frontend/src/scenes/dashboard/newDashboardLogic.ts+++ b/frontend/src/scenes/dashboard/newDashboardLogic.ts@@ -25,6 +25,7 @@ import {JsonType,} from '~/types'+import { UNFILED_DASHBOARDS_FOLDER } from './dashboardConstants'import type { newDashboardLogicType } from './newDashboardLogicType'export interface NewDashboardForm {@@ -262,7 +263,7 @@ export const newDashboardLogic = kea<newDashboardLogicType>([{template: dashboardJSON,creation_context: creationContext,- _create_in_folder: 'Unfiled/Dashboards',+ _create_in_folder: UNFILED_DASHBOARDS_FOLDER,})diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 449159ad3c13..8b714e8083af 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -2537,6 +2537,8 @@ export interface DashboardBasicType extends WithAccessControl {deleted: booleancreation_mode: 'default' | 'template' | 'duplicate' | 'unlisted'tags?: string[]+ /** Project-tree folder the dashboard is filed under, e.g. 'Unfiled/Dashboards'. Empty string is the project root; null means no file system entry. */+ folder?: string | null/** Purely local value to determine whether the dashboard should be highlighted, e.g. as a fresh duplicate. */_highlight?: boolean/**diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambrindex 49d0d7c028bf..3bf79c317057 100644--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr@@ -1917,6 +1917,19 @@"posthog_dashboard"."share_token","posthog_dashboard"."is_shared",recent_dashboard_views."viewed_at" AS "last_viewed_at",+ ("posthog_dashboard"."id")::varchar AS "_ref_id",++ (SELECT U0."path" AS "path"+ FROM "posthog_filesystem" U0+ WHERE ((U0."surface" IS NULL+ OR U0."surface" = 'web')+ AND U0."ref" = ("posthog_dashboard"."id")::varchar+ AND U0."team_id" = ("posthog_dashboard"."team_id")+ AND U0."type" = 'dashboard'+ AND NOT (U0."shortcut"+ AND U0."shortcut" IS NOT NULL))+ ORDER BY U0."id" ASC+ LIMIT 1) AS "_folder_path",T6."id",T6."password",T6."last_login",@@ -5677,6 +5690,19 @@"posthog_dashboard"."share_token","posthog_dashboard"."is_shared",recent_dashboard_views."viewed_at" AS "last_viewed_at",+ ("posthog_dashboard"."id")::varchar AS "_ref_id",++ (SELECT U0."path" AS "path"+ FROM "posthog_filesystem" U0+ WHERE ((U0."surface" IS NULL+ OR U0."surface" = 'web')+ AND U0."ref" = ("posthog_dashboard"."id")::varchar+ AND U0."team_id" = ("posthog_dashboard"."team_id")+ AND U0."type" = 'dashboard'+ AND NOT (U0."shortcut"+ AND U0."shortcut" IS NOT NULL))+ ORDER BY U0."id" ASC+ LIMIT 1) AS "_folder_path",T6."id",T6."password",T6."last_login",@@ -11316,6 +11342,19 @@"posthog_dashboard"."share_token","posthog_dashboard"."is_shared",recent_dashboard_views."viewed_at" AS "last_viewed_at",+ ("posthog_dashboard"."id")::varchar AS "_ref_id",++ (SELECT U0."path" AS "path"+ FROM "posthog_filesystem" U0+ WHERE ((U0."surface" IS NULL+ OR U0."surface" = 'web')+ AND U0."ref" = ("posthog_dashboard"."id")::varchar+ AND U0."team_id" = ("posthog_dashboard"."team_id")+ AND U0."type" = 'dashboard'+ AND NOT (U0."shortcut"+ AND U0."shortcut" IS NOT NULL))+ ORDER BY U0."id" ASC+ LIMIT 1) AS "_folder_path",T6."id",T6."password",T6."last_login",@@ -18480,6 +18519,19 @@"posthog_dashboard"."share_token","posthog_dashboard"."is_shared",recent_dashboard_views."viewed_at" AS "last_viewed_at",+ ("posthog_dashboard"."id")::varchar AS "_ref_id",++ (SELECT U0."path" AS "path"+ FROM "posthog_filesystem" U0+ WHERE ((U0."surface" IS NULL+ OR U0."surface" = 'web')+ AND U0."ref" = ("posthog_dashboard"."id")::varchar+ AND U0."team_id" = ("posthog_dashboard"."team_id")+ AND U0."type" = 'dashboard'+ AND NOT (U0."shortcut"+ AND U0."shortcut" IS NOT NULL))+ ORDER BY U0."id" ASC+ LIMIT 1) AS "_folder_path",T6."id",T6."password",T6."last_login",@@ -22334,6 +22386,19 @@"posthog_dashboard"."share_token","posthog_dashboard"."is_shared",recent_dashboard_views."viewed_at" AS "last_viewed_at",+ ("posthog_dashboard"."id")::varchar AS "_ref_id",++ (SELECT U0."path" AS "path"+ FROM "posthog_filesystem" U0+ WHERE ((U0."surface" IS NULL+ OR U0."surface" = 'web')+ AND U0."ref" = ("posthog_dashboard"."id")::varchar+ AND U0."team_id" = ("posthog_dashboard"."team_id")+ AND U0."type" = 'dashboard'+ AND NOT (U0."shortcut"+ AND U0."shortcut" IS NOT NULL))+ ORDER BY U0."id" ASC+ LIMIT 1) AS "_folder_path",T6."id",T6."password",T6."last_login",diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex cf194115a3ee..9926b922b9d0 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -432,6 +432,46 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):assert isoparse(results_by_id[dashboard_recent_id]["last_viewed_at"]) == isoparse("2024-01-01T12:00:00+00:00")assert results_by_id[dashboard_unseen_id]["last_viewed_at"] is None+ def test_list_includes_folder_from_filesystem(self):+ filed_id, _ = self.dashboard_api.create_dashboard(+ {"name": "Filed dashboard", "_create_in_folder": "Marketing/Website"}+ )+ unfiled_id, _ = self.dashboard_api.create_dashboard({"name": "Unfiled dashboard"})++ response = self.dashboard_api.list_dashboards(parent="environment")+ results_by_id = {dashboard["id"]: dashboard for dashboard in response["results"]}++ # The folder is the file system path without the dashboard's own name+ assert results_by_id[filed_id]["folder"] == "Marketing/Website"+ # Dashboards created without an explicit folder land in the default unfiled folder+ assert results_by_id[unfiled_id]["folder"] == "Unfiled/Dashboards"++ @parameterized.expand(+ [+ # The named folder matches only the dashboard filed directly in it — nested sub-folders excluded+ ("named_folder", "Marketing/Website", "in_folder"),+ # The empty string is the project root (the `depth=1`, no-prefix branch of _apply_folder_filter)+ ("project_root", "", "root"),+ ]+ )+ def test_list_filters_by_folder(self, _name: str, folder: str, expected_key: str):+ ids = {+ "in_folder": self.dashboard_api.create_dashboard(+ {"name": "In folder", "_create_in_folder": "Marketing/Website"}+ )[0],+ "nested": self.dashboard_api.create_dashboard(+ {"name": "Nested deeper", "_create_in_folder": "Marketing/Website/Landing"}+ )[0],+ "other": self.dashboard_api.create_dashboard({"name": "Other folder", "_create_in_folder": "Product"})[0],+ "root": self.dashboard_api.create_dashboard({"name": "Root dashboard", "_create_in_folder": ""})[0],+ }++ response = self.dashboard_api.list_dashboards(parent="environment", query_params={"folder": folder})+ result_ids = {dashboard["id"] for dashboard in response["results"]}++ # Set equality asserts the match is exact — every other dashboard (nested, other folder, root/named) is excluded+ assert result_ids == {ids[expected_key]}+@snapshot_postgres_queriesdef test_retrieve_dashboard(self):dashboard = Dashboard.objects.create(team=self.team, name="private dashboard", created_by=self.user)diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 3c18f0538f5f..230396254a54 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -14,7 +14,20 @@ from django.conf import settingsfrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.core.validators import URLValidatorfrom django.db import IntegrityError, transaction-from django.db.models import CharField, Count, DateTimeField, F, FilteredRelation, Prefetch, Q, QuerySet, Value+from django.db.models import (+ CharField,+ Count,+ DateTimeField,+ Exists,+ F,+ FilteredRelation,+ OuterRef,+ Prefetch,+ Q,+ QuerySet,+ Subquery,+ Value,+)from django.db.models.functions import Castfrom django.http import StreamingHttpResponsefrom django.shortcuts import get_object_or_404@@ -25,7 +38,7 @@ import pydantic_coreimport posthoganalyticsfrom asgiref.sync import sync_to_asyncfrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_viewfrom opentelemetry import tracefrom rest_framework import exceptions, serializers, status, viewsetsfrom rest_framework.permissions import SAFE_METHODS, BasePermission@@ -50,7 +63,8 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.helpers import create_dashboard_from_templatefrom posthog.helpers.dashboard_templates import create_from_template, dashboard_template_from_creation_payloadfrom posthog.helpers.trigram_search import DESCRIPTION_FIELD, MAX_SEARCH_LENGTH, NAME_FIELD, apply_trigram_search-from posthog.models.file_system.file_system import create_or_update_file, delete_file+from posthog.models.file_system.constants import DEFAULT_SURFACE, surface_q+from posthog.models.file_system.file_system import FileSystem, create_or_update_file, delete_file, join_path, split_pathfrom posthog.models.quick_filter import QuickFilterfrom posthog.models.tagged_item import TaggedItemfrom posthog.models.team import Team@@ -126,6 +140,7 @@ DASHBOARD_SHARED_FIELDS = ["created_by","last_accessed_at","last_viewed_at",+ "folder","is_shared","deleted","creation_mode",@@ -825,6 +840,13 @@ class DashboardBasicSerializer(access_control_version = serializers.SerializerMethodField()is_shared = serializers.BooleanField(source="is_sharing_enabled", read_only=True, required=False)last_viewed_at = serializers.DateTimeField(read_only=True, required=False, allow_null=True)+ folder = serializers.SerializerMethodField(+ help_text=(+ "Path of the project-tree folder this dashboard is filed under in the file system, "+ "e.g. 'Unfiled/Dashboards'. An empty string means the project root; null means the "+ "dashboard has no file system entry. The dashboard's own name is not part of the path."+ ),+ )class Meta:model = Dashboard@@ -837,6 +859,7 @@ class DashboardBasicSerializer("created_by","last_accessed_at","last_viewed_at",+ "folder","is_shared","deleted","creation_mode",@@ -874,6 +897,19 @@ class DashboardBasicSerializer(return "v1"return "v2"+ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_folder(self, dashboard: Dashboard) -> str | None:+ # Don't expose the project-tree location to anonymous viewers of a publicly shared dashboard —+ # the folder name can encode internal organisational structure.+ if self.context.get("is_shared"):+ return None+ # `_folder_path` is annotated on DashboardsViewSet.dangerously_get_queryset (all actions).+ # The file system path's last segment is the dashboard's own name; the folder is everything above it.+ path = getattr(dashboard, "_folder_path", None)+ if not path:+ return None+ return join_path(split_path(path)[:-1])+class DashboardMetadataSerializer(DashboardBasicSerializer):filters = serializers.SerializerMethodField()@@ -1901,6 +1937,16 @@ class DashboardSerializer(DashboardMetadataSerializer):"400 error."),),+ OpenApiParameter(+ "folder",+ OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ description=(+ "Optional. Return only dashboards filed directly in this project-tree folder, e.g. "+ "'Unfiled/Dashboards'. An empty string matches dashboards at the project root. Nested "+ "sub-folders are not included."+ ),+ ),],),partial_update=extend_schema(request=PatchedDashboardOpenApiSerializer),@@ -1947,8 +1993,29 @@ class DashboardsViewSet(if tags:queryset = queryset.filter(tagged_items__tag__name__in=tags).distinct()+ folder = self.request.query_params.get("folder")+ if folder is not None:+ queryset = self._apply_folder_filter(queryset, folder)+return queryset+ @staticmethod+ def _apply_folder_filter(queryset: QuerySet, folder: str) -> QuerySet:+ # Keep dashboards whose default-surface, non-shortcut file system entry sits *directly* in `folder`+ # (an empty string means the project root). `depth` pins it to direct children so dashboards nested in+ # sub-folders don't leak in, and lets the filter ride the posthog_fs_team_s_typeref index via the+ # correlated ref lookup. Stored paths are already escaped, so the prefix comparison stays segment-safe.+ entries = FileSystem.objects.filter(+ surface_q(DEFAULT_SURFACE),+ team_id=OuterRef("team_id"),+ type="dashboard",+ ref=Cast(OuterRef("id"), output_field=CharField()),+ depth=len(split_path(folder)) + 1 if folder else 1,+ ).exclude(shortcut=True)+ if folder:+ entries = entries.filter(path__startswith=f"{folder}/")+ return queryset.filter(Exists(entries))+@tracer.start_as_current_span("DashboardViewSet.list")def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:response = super().list(request, *args, **kwargs)@@ -1995,6 +2062,27 @@ class DashboardsViewSet(else:queryset = queryset.annotate(last_viewed_at=Value(None, output_field=DateTimeField()))+ # Annotate the project-tree folder each dashboard is filed under, so responses can expose it+ # without an extra round-trip. A single-valued correlated subquery against the file system —+ # backed by the posthog_fs_team_s_typeref index on (team_id, surface, type, ref) — keeps this cheap+ # and avoids the row multiplication a join could cause when shortcuts/multiple surfaces exist.+ # The default surface matches both NULL and "web" rows, so order by id to keep the picked path+ # stable when more than one non-shortcut entry exists for the same dashboard.+ queryset = queryset.annotate(_ref_id=Cast(F("id"), output_field=CharField())).annotate(+ _folder_path=Subquery(+ FileSystem.objects.filter(+ surface_q(DEFAULT_SURFACE),+ team_id=OuterRef("team_id"),+ type="dashboard",+ ref=OuterRef("_ref_id"),+ )+ .exclude(shortcut=True)+ .order_by("id")+ .values("path")[:1],+ output_field=CharField(),+ )+ )+include_deleted = Falseif self.action in ("partial_update", "update") and hasattr(self, "request"):deleted_value = self.request.data.get("deleted")diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 465f1e245415..76776790f605 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -235,6 +235,11 @@ export interface DashboardBasicApi {readonly last_accessed_at: string | null/** @nullable */readonly last_viewed_at: string | null+ /**+ * Path of the project-tree folder this dashboard is filed under in the file system, e.g. 'Unfiled/Dashboards'. An empty string means the project root; null means the dashboard has no file system entry. The dashboard's own name is not part of the path.+ * @nullable+ */+ readonly folder: string | nullreadonly is_shared: booleanreadonly deleted: booleanreadonly creation_mode: CreationModeEnumApi@@ -305,6 +310,11 @@ export interface DashboardApi {last_accessed_at?: string | null/** @nullable */readonly last_viewed_at: string | null+ /**+ * Path of the project-tree folder this dashboard is filed under in the file system, e.g. 'Unfiled/Dashboards'. An empty string means the project root; null means the dashboard has no file system entry. The dashboard's own name is not part of the path.+ * @nullable+ */+ readonly folder: string | nullreadonly is_shared: booleandeleted?: booleanreadonly creation_mode: CreationModeEnumApi@@ -8408,6 +8418,10 @@ export const DashboardTemplatesListScope = {} as constexport type DashboardsListParams = {+ /**+ * Optional. Return only dashboards filed directly in this project-tree folder, e.g. 'Unfiled/Dashboards'. An empty string matches dashboards at the project root. Nested sub-folders are not included.+ */+ folder?: stringformat?: DashboardsListFormat/*** Number of results to return per page.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 050c338ae4b9..d48b2a603881 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13795,6 +13795,11 @@ export namespace Schemas {last_accessed_at?: string | null;/** @nullable */readonly last_viewed_at: string | null;+ /**+ * Path of the project-tree folder this dashboard is filed under in the file system, e.g. 'Unfiled/Dashboards'. An empty string means the project root; null means the dashboard has no file system entry. The dashboard's own name is not part of the path.+ * @nullable+ */+ readonly folder: string | null;readonly is_shared: boolean;deleted?: boolean;readonly creation_mode: CreationModeEnum;@@ -13864,6 +13869,11 @@ export namespace Schemas {readonly last_accessed_at: string | null;/** @nullable */readonly last_viewed_at: string | null;+ /**+ * Path of the project-tree folder this dashboard is filed under in the file system, e.g. 'Unfiled/Dashboards'. An empty string means the project root; null means the dashboard has no file system entry. The dashboard's own name is not part of the path.+ * @nullable+ */+ readonly folder: string | null;readonly is_shared: boolean;readonly deleted: boolean;readonly creation_mode: CreationModeEnum;@@ -50210,6 +50220,10 @@ export namespace Schemas {};export type EnvironmentsDashboardsListParams = {+ /**+ * Optional. Return only dashboards filed directly in this project-tree folder, e.g. 'Unfiled/Dashboards'. An empty string matches dashboards at the project root. Nested sub-folders are not included.+ */+ folder?: string;format?: EnvironmentsDashboardsListFormat;/*** Number of results to return per page.@@ -55916,6 +55930,10 @@ export namespace Schemas {} as const;export type DashboardsListParams = {+ /**+ * Optional. Return only dashboards filed directly in this project-tree folder, e.g. 'Unfiled/Dashboards'. An empty string matches dashboards at the project root. Nested sub-folders are not included.+ */+ folder?: string;format?: DashboardsListFormat;/*** Number of results to return per page.diff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.tsindex 4a2796158556..c4f3701fd44f 100644--- a/services/mcp/src/generated/dashboards/api.ts+++ b/services/mcp/src/generated/dashboards/api.ts@@ -17,6 +17,12 @@ export const DashboardsListParams = /* @__PURE__ */ zod.object({})export const DashboardsListQueryParams = /* @__PURE__ */ zod.object({+ folder: zod+ .string()+ .optional()+ .describe(+ "Optional. Return only dashboards filed directly in this project-tree folder, e.g. 'Unfiled/Dashboards'. An empty string matches dashboards at the project root. Nested sub-folders are not included."+ ),format: zod.enum(['json', 'txt']).optional(),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),diff --git a/services/mcp/src/tools/generated/dashboards.ts b/services/mcp/src/tools/generated/dashboards.tsindex 4ee59c7549ec..a27c7052e45a 100644--- a/services/mcp/src/tools/generated/dashboards.ts+++ b/services/mcp/src/tools/generated/dashboards.ts@@ -565,6 +565,7 @@ const dashboardsGetAll = (): ToolBase<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/dashboards/`,query: {+ folder: params.folder,limit: params.limit,offset: params.offset,search: params.search,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboards-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboards-get-all.jsonindex 1eb7b62a21e6..7d67cdcf45cc 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboards-get-all.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboards-get-all.json@@ -1,6 +1,10 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "folder": {+ "description": "Optional. Return only dashboards filed directly in this project-tree folder, e.g. 'Unfiled/Dashboards'. An empty string matches dashboards at the project root. Nested sub-folders are not included.",+ "type": "string"+ },"limit": {"description": "Number of results to return per page.","type": "number"