: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): improve dashboard event instrumentation coverage (#62713)
Mike Warrenc0027c0fc908
diff --git a/ee/hogai/tools/upsert_dashboard/test/test_tool.py b/ee/hogai/tools/upsert_dashboard/test/test_tool.pyindex e3219455adca..0bb011cadd88 100644--- a/ee/hogai/tools/upsert_dashboard/test/test_tool.py+++ b/ee/hogai/tools/upsert_dashboard/test/test_tool.py@@ -1672,7 +1672,13 @@ class TestUpsertDashboardTool(BaseTest):dashboard_created_calls = [c for c in mock_report.call_args_list if c[0][1] == "dashboard created"]self.assertEqual(len(dashboard_created_calls), 1)self.assertEqual(dashboard_created_calls[0][0][0], self.user)- self.assertEqual(dashboard_created_calls[0][0][2]["source"], "posthog_ai")+ created_props = dashboard_created_calls[0][0][2]+ self.assertEqual(created_props["source"], "posthog_ai")+ self.assertEqual(created_props["creation_mode"], "default")+ self.assertEqual(created_props["from_template"], False)+ self.assertEqual(created_props["template_key"], None)+ self.assertEqual(created_props["duplicated"], False)+ self.assertEqual(created_props["duplicated_from_dashboard_id"], None)@patch("ee.hogai.tools.upsert_dashboard.tool.report_user_action")async def test_update_dashboard_reports_dashboard_updated(self, mock_report):diff --git a/ee/hogai/tools/upsert_dashboard/tool.py b/ee/hogai/tools/upsert_dashboard/tool.pyindex 7455045dd378..90c2cb65f6f6 100644--- a/ee/hogai/tools/upsert_dashboard/tool.py+++ b/ee/hogai/tools/upsert_dashboard/tool.py@@ -170,7 +170,18 @@ class UpsertDashboardTool(MaxTool):return CREATE_NO_INSIGHTS_PROMPT, Nonedashboard = await self._create_dashboard_with_tiles(action.name, action.description, insights)- await self._report_dashboard_action(dashboard, "dashboard created")+ # AI dashboards are always built from scratch (no template, no duplicate); set the same provenance+ # props the serializer create() path emits so `from_template`/`duplicated` filters include AI traffic.+ await self._report_dashboard_action(+ dashboard,+ "dashboard created",+ {+ "from_template": False,+ "template_key": None,+ "duplicated": False,+ "duplicated_from_dashboard_id": None,+ },+ )await self._report_new_insights(validated_artifacts, insights)output = await self._format_dashboard_output(dashboard, insights)@@ -244,13 +255,16 @@ class UpsertDashboardTool(MaxTool):return resolved- async def _report_dashboard_action(self, dashboard: Dashboard, event: str) -> None:+ async def _report_dashboard_action(+ self, dashboard: Dashboard, event: str, extra_properties: dict[str, Any] | None = None+ ) -> None:await database_sync_to_async(report_user_action)(self._user,event,{**await database_sync_to_async(dashboard.get_analytics_metadata)(),"source": EventSource.POSTHOG_AI,+ **(extra_properties or {}),},team=self._team,)diff --git a/frontend/src/lib/components/Sharing/sharingLogic.ts b/frontend/src/lib/components/Sharing/sharingLogic.tsindex c143ac945d00..ab61ffa993b7 100644--- a/frontend/src/lib/components/Sharing/sharingLogic.ts+++ b/frontend/src/lib/components/Sharing/sharingLogic.ts@@ -106,7 +106,7 @@ export const sharingLogic = kea<sharingLogicType>([listeners(({ props, values, actions }) => ({setIsEnabled: (enabled) => {if (props.dashboardId) {- eventUsageLogic.actions.reportDashboardShareToggled(enabled)+ eventUsageLogic.actions.reportDashboardShareToggled(props.dashboardId, enabled)}},setIsEnabledSuccess: () => {@@ -116,7 +116,7 @@ export const sharingLogic = kea<sharingLogicType>([},setSharingSettingsValue: ({ name, value }) => {if (name === 'whitelabel' && props.dashboardId) {- eventUsageLogic.actions.reportDashboardWhitelabelToggled(value)+ eventUsageLogic.actions.reportDashboardWhitelabelToggled(props.dashboardId, value)}if (name === 'whitelabel' && props.insightShortId) {eventUsageLogic.actions.reportInsightWhitelabelToggled(value)diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex ef1c9dede057..033ef33fff91 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -519,17 +519,25 @@ export const eventUsageLogic = kea<eventUsageLogicType>([dateTo,}),reportDashboardPropertiesChanged: (dashboard: DashboardType<QueryBasedInsightModel> | null) => ({ dashboard }),- reportDashboardPinToggled: (pinned: boolean, source: DashboardEventSource) => ({+ reportDashboardPinToggled: (dashboardId: number, pinned: boolean, source: DashboardEventSource) => ({+ dashboardId,pinned,source,}),reportDashboardFrontEndUpdate: (+ dashboardId: number | undefined,attribute: 'name' | 'description' | 'tags',originalLength: number,newLength: number- ) => ({ attribute, originalLength, newLength }),- reportDashboardShareToggled: (isShared: boolean) => ({ isShared }),- reportDashboardWhitelabelToggled: (isWhiteLabelled: boolean) => ({ isWhiteLabelled }),+ ) => ({ dashboardId, attribute, originalLength, newLength }),+ reportDashboardShareToggled: (dashboardId: number | undefined, isShared: boolean) => ({+ dashboardId,+ isShared,+ }),+ reportDashboardWhitelabelToggled: (dashboardId: number | undefined, isWhiteLabelled: boolean) => ({+ dashboardId,+ isWhiteLabelled,+ }),reportDashboardTileRepositioned: (dashboardId: number, action: 'moved' | 'resized', layoutZoom: number) => ({dashboardId,action,@@ -1430,21 +1438,29 @@ export const eventUsageLogic = kea<eventUsageLogicType>([dashboard: sanitizeDashboard(dashboard),})},- reportDashboardPinToggled: async (payload) => {- posthog.capture(`dashboard pin toggled`, payload)+ reportDashboardPinToggled: async ({ dashboardId, pinned, source }) => {+ posthog.capture(`dashboard pin toggled`, {+ dashboard_id: dashboardId,+ pinned,+ source,+ })},- reportDashboardFrontEndUpdate: async ({ attribute, originalLength, newLength }) => {+ reportDashboardFrontEndUpdate: async ({ dashboardId, attribute, originalLength, newLength }) => {posthog.capture(`dashboard frontend updated`, {+ dashboard_id: dashboardId,attribute,original_length: originalLength,new_length: newLength,})},- reportDashboardShareToggled: async ({ isShared }) => {- posthog.capture(`dashboard share toggled`, { is_shared: isShared })+ reportDashboardShareToggled: async ({ dashboardId, isShared }) => {+ posthog.capture(`dashboard share toggled`, { dashboard_id: dashboardId, is_shared: isShared })},- reportDashboardWhitelabelToggled: async ({ isWhiteLabelled }) => {- posthog.capture(`dashboard whitelabel toggled`, { is_whitelabelled: isWhiteLabelled })+ reportDashboardWhitelabelToggled: async ({ dashboardId, isWhiteLabelled }) => {+ posthog.capture(`dashboard whitelabel toggled`, {+ dashboard_id: dashboardId,+ is_whitelabelled: isWhiteLabelled,+ })},reportDashboardTileRepositioned: async ({ dashboardId, action, layoutZoom }) => {posthog.capture('dashboard tile repositioned', {diff --git a/frontend/src/models/dashboardsModel.tsx b/frontend/src/models/dashboardsModel.tsxindex 85e33d376883..bc3bdb9ce7ac 100644--- a/frontend/src/models/dashboardsModel.tsx+++ b/frontend/src/models/dashboardsModel.tsx@@ -186,6 +186,7 @@ export const dashboardsModel = kea<dashboardsModelType>([const updatedAttribute = Object.keys(payload)[0]if (updatedAttribute === 'name' || updatedAttribute === 'description' || updatedAttribute === 'tags') {eventUsageLogic.actions.reportDashboardFrontEndUpdate(+ id,updatedAttribute,values.rawDashboards[id]?.[updatedAttribute]?.length || 0,payload[updatedAttribute].length@@ -247,7 +248,7 @@ export const dashboardsModel = kea<dashboardsModelType>([pinned: true,})- eventUsageLogic.actions.reportDashboardPinToggled(true, source)+ eventUsageLogic.actions.reportDashboardPinToggled(id, true, source)return getQueryBasedDashboard(response)!},unpinDashboard: async ({ id, source }) => {@@ -257,7 +258,7 @@ export const dashboardsModel = kea<dashboardsModelType>([pinned: false,})- eventUsageLogic.actions.reportDashboardPinToggled(false, source)+ eventUsageLogic.actions.reportDashboardPinToggled(id, false, source)return getQueryBasedDashboard(response)!},duplicateDashboard: async ({ id, name, show, duplicateTiles }) => {diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex 999afeb65d45..af53054a84a7 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -1412,6 +1412,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):"dashboard created",{"created_at": mock.ANY,+ "creation_mode": "template","dashboard_id": response["id"],"duplicated": False,"duplicated_from_dashboard_id": None,@@ -1427,6 +1428,59 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):request=ANY,)+ @patch("products.dashboards.backend.api.dashboard.report_user_action")+ def test_soft_delete_reports_dashboard_deleted(self, mock_report_user_action):+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "to delete"})+ self.dashboard_api.create_insight({"dashboards": [dashboard_id]})+ self.dashboard_api.create_text_tile(dashboard_id)+ mock_report_user_action.reset_mock()++ self.dashboard_api.soft_delete(dashboard_id, "dashboards")++ # item_count (insight tiles) and tile_count (all tiles) are snapshotted pre-delete, so they survive+ # _delete_related_tiles: 1 insight tile, 2 tiles total (insight + text).+ mock_report_user_action.assert_called_once_with(+ self.user,+ "dashboard deleted",+ {+ "created_at": mock.ANY,+ "creation_mode": "default",+ "dashboard_id": dashboard_id,+ "has_description": False,+ "is_shared": False,+ "item_count": 1,+ "pinned": False,+ "tags_count": 0,+ "tile_count": 2,+ },+ team=ANY,+ request=ANY,+ )++ @patch("products.dashboards.backend.api.dashboard.report_user_action")+ def test_update_reports_dashboard_updated_with_creation_mode(self, mock_report_user_action):+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "to rename"})+ mock_report_user_action.reset_mock()++ self.dashboard_api.update_dashboard(dashboard_id, {"name": "renamed"})++ mock_report_user_action.assert_called_once_with(+ self.user,+ "dashboard updated",+ {+ "created_at": mock.ANY,+ "creation_mode": "default",+ "dashboard_id": dashboard_id,+ "has_description": False,+ "is_shared": False,+ "item_count": 0,+ "pinned": False,+ "tags_count": 0,+ },+ team=ANY,+ request=ANY,+ )+def test_invalid_template_key_returns_400(self):_, response = self.dashboard_api.create_dashboard({"name": "bad template", "use_template": "NONEXISTENT_KEY_abc123"},@@ -2430,6 +2484,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):{"created_at": mock.ANY,"creation_context": "onboarding",+ "creation_mode": "default","dashboard_id": dashboard["id"],"duplicated": False,"from_template": True,diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 201666547bbc..cea8cc3ab17c 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -1289,6 +1289,13 @@ class DashboardSerializer(DashboardMetadataSerializer):if being_undeleted:self._undo_delete_related_tiles(instance)+ # Soft-delete transition (false -> true). All channels (web/MCP/API) delete via this PATCH path,+ # so this is the single place to capture deletes. Snapshot tile counts before _delete_related_tiles+ # runs below — otherwise get_analytics_metadata()'s item_count would read 0 post-deletion.+ being_deleted = not instance.deleted and validated_data.get("deleted", False)+ tile_count_at_deletion = instance.tiles.count() if being_deleted else None+ item_count_at_deletion = instance.tiles.exclude(insight=None).count() if being_deleted else None+initial_data = dict(self.initial_data)if validated_data.get("deleted", False):@@ -1346,13 +1353,26 @@ class DashboardSerializer(DashboardMetadataSerializer):self._deep_duplicate_tiles(instance, existing_tile)if "request" in self.context:- report_user_action(- user,- "dashboard updated",- instance.get_analytics_metadata(),- team=instance.team,- request=self.context["request"],- )+ if being_deleted:+ report_user_action(+ user,+ "dashboard deleted",+ {+ **instance.get_analytics_metadata(),+ "item_count": item_count_at_deletion, # override post-delete 0 with pre-delete snapshot+ "tile_count": tile_count_at_deletion,+ },+ team=instance.team,+ request=self.context["request"],+ )+ else:+ report_user_action(+ user,+ "dashboard updated",+ instance.get_analytics_metadata(),+ team=instance.team,+ request=self.context["request"],+ )self.user_permissions.reset_insights_dashboard_cached_results()return instancediff --git a/products/dashboards/backend/models/dashboard.py b/products/dashboards/backend/models/dashboard.pyindex d5ffd83cebba..e942fb51ab8b 100644--- a/products/dashboards/backend/models/dashboard.py+++ b/products/dashboards/backend/models/dashboard.py@@ -162,4 +162,5 @@ class Dashboard(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.M"created_at": self.created_at,"has_description": self.description != "","tags_count": self.tagged_items.count(),+ "creation_mode": self.creation_mode,}