: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(ai): add insights without replacing dashboard tiles (#104039)
Matt Pua5ee777dae2d2
diff --git a/ee/hogai/tools/upsert_dashboard/prompts.py b/ee/hogai/tools/upsert_dashboard/prompts.pyindex 6eb1fe1064a7..5c2002352373 100644--- a/ee/hogai/tools/upsert_dashboard/prompts.py+++ b/ee/hogai/tools/upsert_dashboard/prompts.py@@ -21,10 +21,16 @@ Treat templates as examples, not instructions: take inspiration from the insight## FinalizeCall this tool when you have enough information to create or update the dashboard.-# Understanding dashboard update with insight_ids+# Choose the dashboard action from the requested state change++Use `add_insights` when the user wants to keep the current dashboard and include new insights. This includes requests to add, include, expand, or put a metric on a dashboard. Send only the new insight IDs. This action never removes existing insight tiles.++Use `update` only when the user defines the complete intended set of dashboard insights, asks to remove or replace insights, or asks to change dashboard metadata.++# Understanding full dashboard update with insight_idsWhen `insight_ids` is provided, it replaces all dashboard insights with the provided insights.-You can use insight_ids to add, replace, or remove insights.+Use insight_ids to replace or remove insights.By default, keep existing insight tile layouts unchanged (`layout_mode="preserve_existing"`).Use `layout_mode="reflow_all"` whenever the user explicitly asks to change placement/order, including phrases like:- reorder/rearrange/reflow the dashboard@@ -52,7 +58,7 @@ Assistant: I'll create a new dashboard for file activity metrics.User: I want a dashboard of how my business is doingAssistant: I'll search for existing dashboards. I found a relevant dashboard. Do you want me to summarize it or update it?User: I want you to add MRR to that dashboard.-<reasoning>The user's request was ambiguous. The assistant needed to ask for more details. The user wanted to modify it with specific insights. To add MRR, include all existing insights plus the new MRR insight in insight_ids.</reasoning>+<reasoning>The user wants to retain the current dashboard and add MRR. Use add_insights with the new MRR insight ID.</reasoning></example><example>diff --git a/ee/hogai/tools/upsert_dashboard/test/test_tool.py b/ee/hogai/tools/upsert_dashboard/test/test_tool.pyindex 449312b1acd4..95b8a186efa9 100644--- a/ee/hogai/tools/upsert_dashboard/test/test_tool.py+++ b/ee/hogai/tools/upsert_dashboard/test/test_tool.py@@ -24,6 +24,10 @@ from posthog.schema import (VisualizationMessage,)+from posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership+from posthog.models.sharing_configuration import SharingConfiguration+from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Textfrom products.posthog_ai.backend.models.assistant import AgentArtifact, Conversation@@ -199,6 +203,116 @@ class TestUpsertDashboardTool(BaseTest):soft_deleted_tiles = [t for t in all_tiles if t.deleted]self.assertEqual(len(soft_deleted_tiles), 2)+ @parameterized.expand([("saved",), ("state",), ("artifact",)])+ @patch("ee.hogai.tools.upsert_dashboard.tool.report_user_action")+ async def test_add_insights_preserves_existing_dashboard_tiles(self, source: str, mock_report: MagicMock) -> None:+ dashboard = await Dashboard.objects.acreate(team=self.team, name="Dashboard", created_by=self.user)+ existing_insight = await self._create_insight("Existing insight")+ layouts = {"sm": {"x": 0, "y": 0, "w": 6, "h": 5}}+ existing_tile = await DashboardTile.objects.acreate(+ dashboard=dashboard, insight=existing_insight, layouts=layouts, color="blue"+ )+ state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))+ if source == "saved":+ new_insight = await self._create_insight("New insight")+ insight_id = new_insight.short_id+ elif source == "state":+ insight_id = str(uuid4())+ state.messages = [VisualizationMessage(id=insight_id, answer=DEFAULT_TRENDS_QUERY)]+ else:+ conversation = await Conversation.objects.acreate(team=self.team, user=self.user)+ artifact = await AgentArtifact.objects.acreate(+ team=self.team,+ conversation=conversation,+ name="New insight",+ type=AgentArtifact.Type.VISUALIZATION,+ data={"query": DEFAULT_TRENDS_QUERY.model_dump(), "name": "New insight"},+ )+ insight_id = artifact.short_id++ action = {+ "action": {"action": "add_insights", "dashboard_id": str(dashboard.id), "insight_ids": [insight_id] * 2}+ }+ first_tile_ids = None+ for _ in range(2):+ tool = UpsertDashboardTool(team=self.team, user=self.user, state=state)+ await tool.ainvoke(action)+ tile_ids = [+ tile_id+ async for tile_id in DashboardTile.objects.filter(dashboard=dashboard)+ .order_by("id")+ .values_list("id", flat=True)+ ]+ self.assertEqual(len(tile_ids), 2)+ if first_tile_ids is not None:+ self.assertEqual(tile_ids, first_tile_ids)+ first_tile_ids = tile_ids++ await existing_tile.arefresh_from_db()+ self.assertEqual(existing_tile.layouts, layouts)+ self.assertEqual(existing_tile.color, "blue")+ self.assertEqual(await Insight.objects.filter(team=self.team).acount(), 2)+ insight_created_events = [call for call in mock_report.call_args_list if call.args[1] == "insight created"]+ self.assertEqual(len(insight_created_events), 0 if source == "saved" else 1)++ @parameterized.expand([("saved", True), ("restored", True), ("generated", True), ("saved", False)])+ @patch("posthog.api.sharing_publish_gate.blocked_access_for_user", return_value=["restricted_table"])+ async def test_add_insights_enforces_shared_dashboard_access(+ self, source: str, shared: bool, _mock_blocked: MagicMock+ ) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ await self.organization.asave()+ await OrganizationMembership.objects.filter(user=self.user, organization=self.organization).aupdate(+ level=OrganizationMembership.Level.MEMBER+ )+ dashboard = await Dashboard.objects.acreate(team=self.team, name="Dashboard", created_by=self.user)+ if shared:+ await SharingConfiguration.objects.acreate(team=self.team, dashboard=dashboard, enabled=True)+ existing = await self._create_insight("Existing")+ existing_tile = await DashboardTile.objects.acreate(dashboard=dashboard, insight=existing)+ allowed = await self._create_insight("Allowed addition")+ state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))+ deleted_tile = None+ if source == "generated":+ insight_id = str(uuid4())+ state.messages = [VisualizationMessage(id=insight_id, answer=DEFAULT_TRENDS_QUERY)]+ else:+ restricted = await self._create_insight("Restricted")+ insight_id = restricted.short_id+ if source == "restored":+ deleted_tile = await DashboardTile.objects.acreate(+ dashboard=dashboard, insight=restricted, deleted=True+ )+ count_before = await Insight.objects.filter(team=self.team).acount()+ tool = UpsertDashboardTool(team=self.team, user=self.user, state=state)+ action = {+ "action": {+ "action": "add_insights",+ "dashboard_id": str(dashboard.id),+ "insight_ids": [allowed.short_id, insight_id],+ }+ }+ _mock_blocked.side_effect = [[], ["restricted_table"]]+ if shared:+ with self.assertRaisesRegex(MaxToolRetryableError, "publicly shared"):+ await tool.ainvoke(action)+ self.assertEqual(+ [+ tile_id+ async for tile_id in DashboardTile.objects.filter(dashboard=dashboard).values_list("id", flat=True)+ ],+ [existing_tile.id],+ )+ self.assertEqual(await Insight.objects.filter(team=self.team).acount(), count_before)+ if deleted_tile:+ await deleted_tile.arefresh_from_db()+ self.assertTrue(deleted_tile.deleted)+ else:+ await tool.ainvoke(action)+ self.assertEqual(await DashboardTile.objects.filter(dashboard=dashboard).acount(), 3)+@parameterized.expand([("trends", TrendsQuery(series=[EventsNode(name="$pageview")])),diff --git a/ee/hogai/tools/upsert_dashboard/tool.py b/ee/hogai/tools/upsert_dashboard/tool.pyindex 12d814031e20..40a88f491da1 100644--- a/ee/hogai/tools/upsert_dashboard/tool.py+++ b/ee/hogai/tools/upsert_dashboard/tool.py@@ -1,18 +1,26 @@+import hashlib+from base64 import urlsafe_b64encodefrom typing import Any, Literal, TypedDict, castfrom django.db import transactionimport structlogfrom pydantic import BaseModel, Field+from rest_framework.exceptions import ValidationErrorfrom posthog.schema import DataTableNode, DataVisualizationNode, HogQLQuery, InsightVizNode, QuerySchemaRoot+from posthog.api.sharing_publish_gate import check_can_add_insight_to_shared_dashboardfrom posthog.event_usage import EventSource, report_user_actionfrom posthog.sync import database_sync_to_asyncfrom posthog.utils import pluralizefrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.facade.api import (+ get_or_create_saved_insight,+ insights_including_soft_deleted_for_team,+)from products.product_analytics.backend.facade.models import Insightfrom ee.hogai.artifacts.types import ModelArtifactResult, VisualizationWithSourceResult@@ -70,7 +78,15 @@ class UpdateDashboardToolArgs(BaseModel):)-UpsertDashboardAction = CreateDashboardToolArgs | UpdateDashboardToolArgs+class AddDashboardInsightsToolArgs(BaseModel):+ """Schema to add insights to an existing dashboard without removing its tiles."""++ action: Literal["add_insights"] = "add_insights"+ dashboard_id: str = Field(description="Provide the ID of the dashboard to add insights to.")+ insight_ids: list[str] = Field(description="The IDs of the insights to add to the dashboard.")+++UpsertDashboardAction = CreateDashboardToolArgs | UpdateDashboardToolArgs | AddDashboardInsightsToolArgsclass UpsertDashboardToolArgs(BaseModel):@@ -119,8 +135,8 @@ class UpsertDashboardTool(MaxTool):"""Build a rich preview showing dashboard details and what will be modified."""- if isinstance(action, CreateDashboardToolArgs):- raise MaxToolFatalError("Create dashboard operation is not dangerous.")+ if not isinstance(action, UpdateDashboardToolArgs):+ raise MaxToolFatalError("Only dashboard updates can require a dangerous operation preview.")dashboard = await self._get_dashboard(action.dashboard_id)sorted_tiles = await self._get_dashboard_sorted_tiles(dashboard)@@ -152,8 +168,9 @@ class UpsertDashboardTool(MaxTool):async def _arun_impl(self, action: UpsertDashboardAction) -> tuple[str, dict | None]:if isinstance(action, CreateDashboardToolArgs):return await self._handle_create(action)- else:+ if isinstance(action, UpdateDashboardToolArgs):return await self._handle_update(action)+ return await self._handle_add_insights(action)async def _handle_create(self, action: CreateDashboardToolArgs) -> tuple[str, dict | None]:"""Handle CREATE action: create a new dashboard with insights."""@@ -218,6 +235,25 @@ class UpsertDashboardTool(MaxTool):return output, {"dashboard_id": dashboard.id}+ async def _handle_add_insights(self, action: AddDashboardInsightsToolArgs) -> tuple[str, dict | None]:+ """Add insights to an existing dashboard while preserving current tiles."""+ dashboard = await self._get_dashboard(action.dashboard_id)+ insight_ids = list(dict.fromkeys(action.insight_ids))+ artifacts = await self._get_visualization_artifacts(insight_ids)+ try:+ created_insights = await self._add_dashboard_insights(dashboard, insight_ids, artifacts)+ except ValidationError as error:+ raise MaxToolRetryableError(str(error.detail)) from error+ await self._report_dashboard_action(dashboard, "dashboard updated", {"operation": "add_insights"})+ for artifact, insight in created_insights:+ await self._report_new_insights([artifact], [insight])++ sorted_tiles = await self._get_dashboard_sorted_tiles(dashboard)+ insights = [tile.insight for tile in sorted_tiles if tile.insight is not None]+ output = await self._format_dashboard_output(dashboard, insights)++ return output, {"dashboard_id": dashboard.id}+def _resolve_insights(self, artifacts: list[VisualizationWithSourceResult]) -> list[Insight]:"""Resolve insight_ids using VisualizationHandler.@@ -315,6 +351,43 @@ class UpsertDashboardTool(MaxTool):)return dashboard+ @database_sync_to_async+ @transaction.atomic+ def _add_dashboard_insights(+ self, dashboard: Dashboard, insight_ids: list[str], artifacts: list[VisualizationWithSourceResult]+ ) -> list[tuple[VisualizationWithSourceResult, Insight]]:+ """Add or restore insight tiles without changing any other dashboard tiles."""+ created_insights: list[tuple[VisualizationWithSourceResult, Insight]] = []+ for artifact_id, artifact, insight in zip(insight_ids, artifacts, self._resolve_insights(artifacts)):+ if not isinstance(artifact, ModelArtifactResult):+ # Stable IDs let the database deduplicate artifact retries, including concurrent calls.+ identity = f"dashboard:{dashboard.id}:{artifact.source.value}:{artifact_id}"+ short_id = urlsafe_b64encode(hashlib.sha256(identity.encode()).digest()[:9]).decode()+ insight_pk, created = get_or_create_saved_insight(+ team_id=self._team.id,+ user_id=self._user.id,+ short_id=short_id,+ name=insight.name,+ description=insight.description,+ query=insight.query,+ )+ insight = insights_including_soft_deleted_for_team(team_id=self._team.id, insight_ids=[insight_pk])[0]+ if created:+ created_insights.append((artifact, insight))++ check_can_add_insight_to_shared_dashboard(self._user, dashboard, insight.query, self.user_access_control)++ tile, created = DashboardTile.objects_including_soft_deleted.get_or_create(+ dashboard=dashboard,+ insight=insight,+ defaults={"team_id": dashboard.team_id, "layouts": {}},+ )+ if not created and tile.deleted:+ tile.deleted = False+ tile.save(update_fields=["deleted"])++ return created_insights+@database_sync_to_async@transaction.atomicdef _update_dashboard_with_tiles(diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.pyindex b907845a0177..80f28ae78ca7 100644--- a/products/product_analytics/backend/facade/api.py+++ b/products/product_analytics/backend/facade/api.py@@ -132,3 +132,17 @@ def map_stale_to_latest(stale_variables: dict, latest_variables: list[InsightVardef get_query_specific_instructions(kind: str) -> str:"""Analysis guidance for a query kind, used by LLM insight and subscription summaries."""return logic.get_query_specific_instructions(kind)+++def get_or_create_saved_insight(+ *,+ team_id: int,+ user_id: int,+ short_id: str,+ name: str | None,+ description: str | None,+ query: dict[str, object] | None,+) -> tuple[int, bool]:+ return logic.get_or_create_saved_insight(+ team_id=team_id, user_id=user_id, short_id=short_id, name=name, description=description, query=query+ )diff --git a/products/product_analytics/backend/logic.py b/products/product_analytics/backend/logic.pyindex 5a5181302cda..d70351cf5cf8 100644--- a/products/product_analytics/backend/logic.py+++ b/products/product_analytics/backend/logic.py@@ -156,3 +156,23 @@ def get_query_specific_instructions(kind: str) -> str:return "Focus on the balance between new, returning, resurrecting, and dormant users. Identify which group is dominating the total count."return "Focus on the most significant patterns and anomalies in the data."+++def get_or_create_saved_insight(+ *,+ team_id: int,+ user_id: int,+ short_id: str,+ name: str | None,+ description: str | None,+ query: dict[str, object] | None,+) -> tuple[int, bool]:+ insight, created = Insight.objects_including_soft_deleted.get_or_create(+ team_id=team_id,+ short_id=short_id,+ defaults={"created_by_id": user_id, "name": name, "description": description, "query": query, "saved": True},+ )+ if insight.deleted:+ insight.deleted = False+ insight.save(update_fields=["deleted"])+ return insight.id, created