: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
fix(navigation): show insight type icons in files (#111033)
Marius Andrac937a152a88d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1935249580c4..4a575a2ca8bc 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4168,6 +4168,10 @@ snapshots:hash: v1.k794b7964.b569dafdb063a1002e9e88a5bdef5e6b3741cf1fb4ec5de3e339a92ac8f8be4e.3Ae1BykRVFxMYDXV_JdDul_Tjkc35U40oPM5xcm1sUclayout-products-and-files--files-filtered--light:hash: v1.k794b7964.37018760b9d9f87c394b082adc837cf5d3e442e68acb6f982b18eec23b02599d.VCrpPImVdZ75KDL4-O0kmHObtLu8KS4JZJO4gMUNeJU+ layout-products-and-files--files-insight-types--dark:+ hash: v1.k794b7964.4b66d2c48e9ec9aa3a9c6569ef582f55baea39c5cec3ddeb6f21875dad355884.RmGY5Tvyvw1QcuM2VSNiHAtaf1Qu-qEwHn_P2UFeMAc+ layout-products-and-files--files-insight-types--light:+ hash: v1.k794b7964.65b1a0aa425b7eeb7a25b9370944ae02fcf90609395bd36b83e5cea2dd1e3e1d.UeeLuhDGnuckYVH1y5SwRK8TRFtstIeJYuWgX5nqIP4layout-products-and-files--files-long-tree--dark:hash: v1.k794b7964.ff398682f2ad0164bc9f7d69ea1165101184e64f428b1df031397c195f86c217.lc3k6kNIbY6DRQBhg6WGA_7hYPWRRsZVAEIBH7KZ8X4layout-products-and-files--files-long-tree--light:diff --git a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsxindex 45f0189c07d4..36b426e7cd38 100644--- a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx@@ -539,6 +539,16 @@ export const ProductIconWrapper = ({ type, children, colorOverride }: ProductIco)}+export function getFileSystemIconType(item: Pick<FileSystemEntry, 'type' | 'meta'>): FileSystemIconType | undefined {+ if (item.type === 'insight' && typeof item.meta?.insight_type === 'string') {+ const insightIconType = `insight/${item.meta.insight_type}` as FileSystemIconType+ if (insightIconType in iconTypes) {+ return insightIconType+ }+ }+ return item.type as FileSystemIconType+}+export function iconForType(type?: FileSystemIconType, colorOverride?: FileSystemIconColor): JSX.Element {if (!type) {return (diff --git a/frontend/src/layout/panel-layout/ProjectTree/utils.test.ts b/frontend/src/layout/panel-layout/ProjectTree/utils.test.tsindex 5ed2154c8a6e..7cc841b50ed0 100644--- a/frontend/src/layout/panel-layout/ProjectTree/utils.test.ts+++ b/frontend/src/layout/panel-layout/ProjectTree/utils.test.ts@@ -2,7 +2,7 @@ import { renderToStaticMarkup } from 'react-dom/server'import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'-import { FileSystemEntry } from '~/queries/schema/schema-general'+import { FileSystemEntry, FileSystemIconType } from '~/queries/schema/schema-general'import { ProjectTreeRef } from '~/types'import { productsItemName } from '../navbar/tabs/productsCatalog'@@ -204,6 +204,22 @@ describe('project tree utils', () => {})})+ it.each(['trends', 'funnels', 'retention', 'paths', 'lifecycle', 'stickiness', 'hog', undefined, 'unknown'])(+ 'renders a saved insight with type %s using its insight icon',+ (insightType) => {+ const [node] = convertFileSystemEntryToTreeDataItem({+ imports: [{ id: 'report', path: 'Report', type: 'insight', meta: { insight_type: insightType } }],+ folderStates: {},+ checkedItems: {},+ root: 'project://',+ })+ const expectedType = insightType && insightType !== 'unknown' ? `insight/${insightType}` : 'insight'+ expect(renderToStaticMarkup(node.icon as JSX.Element)).toEqual(+ renderToStaticMarkup(iconForType(expectedType as FileSystemIconType))+ )+ }+ )+describe('starred products', () => {it.each(catalogProducts.map((item) => [item.path, item]))('renders a starred %s with the name, tags, icon and color it has in the product list',diff --git a/frontend/src/layout/panel-layout/ProjectTree/utils.tsx b/frontend/src/layout/panel-layout/ProjectTree/utils.tsxindex 4d53e7bc1cd3..8a01a3c6080b 100644--- a/frontend/src/layout/panel-layout/ProjectTree/utils.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/utils.tsx@@ -5,11 +5,11 @@ import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'import { SearchHighlightMultiple } from '~/layout/navigation-3000/components/SearchHighlight'import { RecentResults, SearchResults } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'-import { FileSystemEntry, FileSystemIconType, FileSystemImport } from '~/queries/schema/schema-general'+import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'import { ProjectTreeRef, UserBasicType } from '~/types'import { getCustomIcon } from './customIconRegistry'-import { ProductIconWrapper, getSidebarProduct, iconForType } from './defaultTree'+import { ProductIconWrapper, getFileSystemIconType, getSidebarProduct, iconForType } from './defaultTree'import { FolderState } from './types'// Hardcoded category order - categories not in this list will be sorted alphabetically after these@@ -198,9 +198,7 @@ export function convertFileSystemEntryToTreeDataItem({// A link to a sidebar product, such as a starred one, shows that product's icon and color.// Shortcuts store only a type, which can predate the product's current icon.const iconType =- sidebarProduct?.iconType ||- ('iconType' in item ? item.iconType : undefined) ||- (item.type as FileSystemIconType)+ sidebarProduct?.iconType || ('iconType' in item ? item.iconType : undefined) || getFileSystemIconType(item)const iconColor = sidebarProduct?.iconColor ?? ('iconColor' in item ? item.iconColor : undefined)// Check for custom icon component first (e.g., badges), then fall back to static iconconst CustomIcon = getCustomIcon(item.type, item.href)diff --git a/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsx b/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsxindex dc423d4ba91a..e915283f37bd 100644--- a/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsx+++ b/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsx@@ -450,3 +450,34 @@ export const FlagOffFlatNav: Story = {args: { tab: 'files', recentsCollapsed: true },parameters: { featureFlags: [FEATURE_FLAGS.FLAT_NAV] },}++export const FilesInsightTypes: Story = {+ args: { tab: 'files', recentsCollapsed: false },+ decorators: [+ mswDecorator({+ get: {+ '/api/environments/:team_id/file_system': [+ 200,+ {+ results: ['hog', 'trends', 'funnels', 'retention', 'paths', 'lifecycle', 'stickiness'].map(+ (type) => ({+ id: `insight-${type}`,+ path:+ type === 'hog'+ ? 'SQL insight'+ : `${type.charAt(0).toUpperCase()}${type.slice(1)} insight`,+ type: 'insight',+ ref: `example-${type}`,+ href: `/insights/example-${type}`,+ meta: { insight_type: type },+ })+ ),+ count: 7,+ next: null,+ has_more: false,+ },+ ],+ },+ }),+ ],+}diff --git a/frontend/src/layout/panel-layout/navbar/tabs/NavRecentItems.tsx b/frontend/src/layout/panel-layout/navbar/tabs/NavRecentItems.tsxindex 94f31d5bc324..34955e905012 100644--- a/frontend/src/layout/panel-layout/navbar/tabs/NavRecentItems.tsx+++ b/frontend/src/layout/panel-layout/navbar/tabs/NavRecentItems.tsx@@ -3,9 +3,9 @@ import { useActions, useValues } from 'kea'import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'-import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'+import { getFileSystemIconType, iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { splitPath, unescapePath } from '~/layout/panel-layout/ProjectTree/utils'-import { FileSystemEntry, FileSystemIconType } from '~/queries/schema/schema-general'+import { FileSystemEntry } from '~/queries/schema/schema-general'import { NavLink } from '../NavLink'import { navRecentsLogic } from './navRecentsLogic'@@ -33,7 +33,7 @@ export function NavRecentItems(): JSX.Element {key={item.id}to={item.href ?? ''}label={getItemName(item)}- icon={iconForType(item.type as FileSystemIconType)}+ icon={iconForType(getFileSystemIconType(item))}isCollapsed={false}data-attr={`nav-recent-item-${item.id}`}onClick={() => reportNavItemClicked('recent', 'recents', item.type)}diff --git a/posthog/api/file_system/file_system.py b/posthog/api/file_system/file_system.pyindex da0556f22e91..c5f60fc33adb 100644--- a/posthog/api/file_system/file_system.py+++ b/posthog/api/file_system/file_system.py@@ -77,6 +77,11 @@ MAX_META_BYTES = 1_000_000RECENTS_SEARCH_SCAN_LIMIT = 200+def get_file_system_insight_type(query_kind: str | None, legacy_type: str | None) -> str:+ insight_type = str(query_kind).removesuffix("Query").lower() if query_kind else str(legacy_type or "TRENDS").lower()+ return {"hogql": "hog", "pathsv2": "paths", "journeys": "paths"}.get(insight_type, insight_type)++def validate_file_system_path(path: Any) -> str:"""Bound a caller-supplied path before it reaches the per-segment folder creation loop, whichcosts one existence check plus one insert per segment and autocommits each one."""@@ -560,12 +565,13 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return queryset- def _add_content_types(self, results: builtins.list[dict[str, object]]) -> None:+ def _add_object_types(self, results: builtins.list[dict[str, object]], *, include_content_type: bool) -> None:+ entry_types = ("notebook", "insight") if include_content_type else ("insight",)entry_teams = {str(entry_id): team_idfor entry_id, team_id in FileSystem.objects.filter(team__project_id=self.team.project_id,- id__in=[item["id"] for item in results if item.get("type") in ("notebook", "insight")],+ id__in=[item["id"] for item in results if item.get("type") in entry_types],).values_list("id", "team_id")}denied: set[tuple[str, str, int]] = set()@@ -582,10 +588,13 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):))content_types: dict[tuple[str, int, str], str] = {}+ insight_types: dict[tuple[int, str], str] = {}for entry_type, app_label, model_name in (("notebook", "notebooks", "Notebook"),("insight", "product_analytics", "Insight"),):+ if entry_type == "notebook" and not include_content_type:+ continuerefs = {item["ref"]for item in results@@ -610,23 +619,37 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):_markdown_type="string",)content_type = "text/markdown"+ for team_id, ref in queryset.values_list("team_id", "short_id"):+ if (entry_type, ref, team_id) not in denied:+ content_types[(entry_type, team_id, ref)] = content_typeelse:- queryset = queryset.filter(query__source__kind="HogQLQuery")- content_type = "application/sql"- for team_id, ref in queryset.values_list("team_id", "short_id"):- if (entry_type, ref, team_id) not in denied:- content_types[(entry_type, team_id, ref)] = content_type+ for team_id, ref, kind, source_kind, nested_kind, legacy_type in queryset.values_list(+ "team_id",+ "short_id",+ "query__kind",+ "query__source__kind",+ "query__source__source__kind",+ "filters__insight",+ ):+ if (entry_type, ref, team_id) in denied:+ continue+ insight_types[(team_id, ref)] = get_file_system_insight_type(+ nested_kind or source_kind or kind, legacy_type+ )+ if source_kind == "HogQLQuery":+ content_types[(entry_type, team_id, ref)] = "application/sql"for item in results:- if item.get("type") not in ("notebook", "insight"):+ if item.get("type") not in entry_types:continuemeta = item.get("meta")- item["meta"] = {- **(meta if isinstance(meta, dict) else {}),- "content_type": content_types.get(- (str(item["type"]), entry_teams.get(str(item["id"]), -1), str(item.get("ref"))),- "application/json",- ),- }+ metadata = {**(meta if isinstance(meta, dict) else {})}+ team_id = entry_teams.get(str(item["id"]), -1)+ ref = str(item.get("ref"))+ if item.get("type") == "insight":+ metadata["insight_type"] = insight_types.get((team_id, ref))+ if include_content_type:+ metadata["content_type"] = content_types.get((str(item["type"]), team_id, ref), "application/json")+ item["meta"] = metadata@extend_schema(parameters=[FileSystemListQuerySerializer])def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:@@ -640,8 +663,10 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):else:response = super().list(request, *args, **kwargs)response.data["users"] = self._created_by_users(response.data.get("results", []))- if query_serializer.validated_data["include_content_type"]:- self._add_content_types(response.data.get("results", []))+ self._add_object_types(+ response.data.get("results", []),+ include_content_type=query_serializer.validated_data["include_content_type"],+ )return responsedef _created_by_users(self, results: builtins.list[dict[str, Any]]) -> builtins.list[dict[str, Any]]:diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.pyindex 627b9da152a1..26c82cdfbeb7 100644--- a/posthog/api/file_system/test/test_file_system.py+++ b/posthog/api/file_system/test/test_file_system.py@@ -24,6 +24,7 @@ from posthog.api.file_system.file_system import (MAX_PATH_SEGMENTS,FileSystemSerializer,UndoDeleteItemSerializer,+ get_file_system_insight_type,)from posthog.models import OrganizationMembership, Project, Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLog@@ -119,8 +120,10 @@ class TestFileSystemAPI(APIBaseTest):set(results),{f"Reports/{name}" for name, _, _, _ in entries} | {"Reports/Other notebook", "Reports/Other insight"},)- for name, _, _, content_type in entries:+ for name, entry_type, _, content_type in entries:expected_meta = {"label": "example"}+ if entry_type == "insight":+ expected_meta["insight_type"] = "hog" if name == "SQL" else "trends"if include_content_type:expected_meta["content_type"] = content_typeself.assertEqual(results[f"Reports/{name}"]["meta"], expected_meta)@@ -129,7 +132,10 @@ class TestFileSystemAPI(APIBaseTest):for name in ("Other notebook", "Other insight"):self.assertEqual(results[f"Reports/{name}"]["meta"],- {"content_type": "application/json"} if include_content_type else {},+ {+ **({"insight_type": "trends"} if name == "Other insight" else {}),+ **({"content_type": "application/json"} if include_content_type else {}),+ },)if include_content_type:markdown.content = legacy.content@@ -140,6 +146,19 @@ class TestFileSystemAPI(APIBaseTest):)self.assertEqual(refreshed.json()["results"][0]["meta"]["content_type"], "application/json")+ def test_list_insight_type_tracks_query_changes(self) -> None:+ insight = Insight.objects.create(team=self.team, saved=True, name="Report")+ queries = [+ {"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery", "query": "select 1"}},+ {"kind": "InsightVizNode", "source": {"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery"}}},+ None,+ ]+ for query, expected_type in zip(queries, ["hog", "hog", "paths"]):+ Insight.objects.filter(team=self.team, pk=insight.pk).update(query=query, filters={"insight": "JOURNEYS"})+ response = self.client.get(f"/api/projects/{self.team.id}/file_system/", {"type": "insight"})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["results"][0]["meta"]["insight_type"], expected_type)+def test_list_rejects_invalid_content_type_parameter(self) -> None:response = self.client.get(f"/api/projects/{self.team.id}/file_system/", {"include_content_type": "invalid"})self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)@@ -1662,12 +1681,16 @@ class TestFileSystemAPIAdvancedPermissions(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["results"][0]["meta"]["content_type"], "application/json")+ if entry_type == "insight":+ self.assertIsNone(response.json()["results"][0]["meta"]["insight_type"])self._grant_to_user(entry_type, str(obj.pk), "viewer")response = self.client.get(f"/api/projects/{self.team.id}/file_system/", {"path": entry.path, "include_content_type": "true"})self.assertEqual(response.json()["results"][0]["meta"]["content_type"], content_type)+ if entry_type == "insight":+ self.assertEqual(response.json()["results"][0]["meta"]["insight_type"], "hog")def test_undo_delete_refuses_an_object_that_is_not_deleted(self):flag = FeatureFlag.objects.create(@@ -2634,3 +2657,25 @@ class TestFileSystemInputValidationAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual([row["path"] for row in response.json()["results"]], ["!"])+++class TestFileSystemInsightType(SimpleTestCase):+ @parameterized.expand(+ [+ ("TrendsQuery", None, "trends"),+ ("FunnelsQuery", None, "funnels"),+ ("RetentionQuery", None, "retention"),+ ("PathsQuery", None, "paths"),+ ("PathsV2Query", None, "paths"),+ ("LifecycleQuery", None, "lifecycle"),+ ("StickinessQuery", None, "stickiness"),+ ("HogQLQuery", None, "hog"),+ ("HogQuery", None, "hog"),+ (None, "RETENTION", "retention"),+ (None, "JOURNEYS", "paths"),+ (None, None, "trends"),+ ("HogQLQuery", "TRENDS", "hog"),+ ]+ )+ def test_insight_type(self, query_kind: str | None, legacy_type: str | None, expected: str) -> None:+ self.assertEqual(get_file_system_insight_type(query_kind, legacy_type), expected)