: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(phai): keep variables and formatting when copying a dashboard (#116590)
posthog[bot]3d9187406f3f
diff --git a/ee/hogai/tools/upsert_dashboard/prompts.py b/ee/hogai/tools/upsert_dashboard/prompts.pyindex 5c2002352373..23a2d694f428 100644--- a/ee/hogai/tools/upsert_dashboard/prompts.py+++ b/ee/hogai/tools/upsert_dashboard/prompts.py@@ -25,6 +25,8 @@ Call this tool when you have enough information to create or update the dashboarUse `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 `duplicate` when the user wants a copy of an existing dashboard, for example the same dashboard for another customer, subscription, or date range. It keeps the dashboard variables, filters, tiles, layouts, and the chart settings of each insight (number formatting, prefixes, and suffixes). Do not rebuild the insights with SQL for a copy. Use `variable_values` to change only the variable values that differ, keyed by the variable code name. Never hardcode a value in SQL when the source dashboard has a variable for it.+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_ids@@ -44,7 +46,7 @@ Example: Dashboard has [A, B, C] (in layout order). Use `insight_ids=[A, C]` (saResult: A and C keep their existing tile layouts, B's tile is soft-deleted, and no new tiles are created.# When to use this tool-- The user asks to create or update a dashboard.+- The user asks to create, copy, or update a dashboard.- The user asks for multiple metrics or dimensions, so it might be better to visualize them in a dashboard.- The user wants to modify insights on an existing dashboard (add, remove, or replace).@@ -131,3 +133,8 @@ PERMISSION_REQUEST_PROMPT = """MISSING_INSIGHT_IDS_PROMPT = """Some insights were not found in the conversation artifacts: {{{missing_ids}}}. You should check if the provided insight_ids are correct.""".strip()+++UNKNOWN_VARIABLES_PROMPT = """+These variables do not exist in this project: {{{unknown_variables}}}. Use the code names of existing variables: {{{available_variables}}}.+""".strip()diff --git a/ee/hogai/tools/upsert_dashboard/test/test_tool.py b/ee/hogai/tools/upsert_dashboard/test/test_tool.pyindex 14555b2f9636..1ed6de16b545 100644--- a/ee/hogai/tools/upsert_dashboard/test/test_tool.py+++ b/ee/hogai/tools/upsert_dashboard/test/test_tool.py@@ -29,17 +29,23 @@ from posthog.models import OrganizationMembershipfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.sync import database_sync_to_async+from products.access_control.backend.models.access_control import AccessControlfrom 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-from products.product_analytics.backend.facade.models import Insight+from products.product_analytics.backend.facade.models import Insight, InsightVariablefrom products.subscriptions.backend.facade.testing import create_subscriptionfrom ee.hogai.artifacts.types import ModelArtifactResult, StateArtifactResult, VisualizationWithSourceResultfrom ee.hogai.context.context import AssistantContextManagerfrom ee.hogai.context.insight.context import InsightContextfrom ee.hogai.tool_errors import MaxToolAccessDeniedError, MaxToolFatalError, MaxToolRetryableError-from ee.hogai.tools.upsert_dashboard.tool import CreateDashboardToolArgs, UpdateDashboardToolArgs, UpsertDashboardTool+from ee.hogai.tools.upsert_dashboard.tool import (+ CreateDashboardToolArgs,+ DuplicateDashboardToolArgs,+ UpdateDashboardToolArgs,+ UpsertDashboardTool,+)from ee.hogai.utils.types import AssistantStateDEFAULT_TRENDS_QUERY = TrendsQuery(series=[EventsNode(name="$pageview")])@@ -1823,6 +1829,162 @@ class TestUpsertDashboardTool(BaseTest):self.assertEqual(created_props["duplicated"], False)self.assertEqual(created_props["duplicated_from_dashboard_id"], None)+ async def _create_variable_dashboard(self) -> tuple[Dashboard, Insight, InsightVariable, InsightVariable]:+ subscription = await InsightVariable.objects.acreate(+ team=self.team, name="Subscription", code_name="subscription_id", type=InsightVariable.Type.STRING+ )+ rate = await InsightVariable.objects.acreate(+ team=self.team, name="Rate", code_name="rate", type=InsightVariable.Type.NUMBER+ )+ insight = await Insight.objects.acreate(+ team=self.team,+ created_by=self.user,+ name="Spend",+ query={+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT sum(amount) * {variables.rate} FROM events WHERE id = {variables.subscription_id}",+ },+ "chartSettings": {"yAxis": [{"column": "spend", "settings": {"formatting": {"prefix": "$"}}}]},+ },+ saved=True,+ )+ dashboard = await Dashboard.objects.acreate(+ team=self.team,+ name="Subscription usage",+ description="Usage for one subscription",+ created_by=self.user,+ filters={"date_from": "-30d"},+ variables={+ str(subscription.id): {+ "code_name": "subscription_id",+ "variableId": str(subscription.id),+ "value": "sub_a",+ },+ str(rate.id): {"code_name": "rate", "variableId": str(rate.id), "value": 2},+ },+ )+ layouts = {"sm": {"x": 0, "y": 0, "w": 6, "h": 5}}+ await DashboardTile.objects.acreate(dashboard=dashboard, insight=insight, layouts=layouts)+ text = await Text.objects.acreate(team=self.team, body="Notes")+ await DashboardTile.objects.acreate(dashboard=dashboard, text=text, layouts={})+ return dashboard, insight, subscription, rate++ @parameterized.expand([False, True])+ @patch("posthog.event_usage.posthoganalytics.capture")+ async def test_duplicate_dashboard_keeps_variables_and_chart_settings(+ self, enforce_2fa: bool, mock_capture: MagicMock+ ) -> None:+ self.organization.enforce_2fa = enforce_2fa+ await self.organization.asave(update_fields=["enforce_2fa"])+ source, source_insight, subscription, rate = await self._create_variable_dashboard()++ _, artifact = await self._create_tool()._arun_impl(+ DuplicateDashboardToolArgs(+ dashboard_id=str(source.id),+ name="Subscription B usage",+ variable_values={"subscription_id": "sub_b"},+ )+ )++ assert artifact is not None+ copy = await Dashboard.objects.aget(id=artifact["dashboard_id"])+ self.assertEqual(copy.description, "Usage for one subscription")+ self.assertEqual(copy.filters, {"date_from": "-30d"})+ assert copy.variables is not None+ self.assertEqual(copy.variables[str(subscription.id)]["value"], "sub_b")+ self.assertEqual(copy.variables[str(rate.id)]["value"], 2)+ source_variables = (await Dashboard.objects.aget(id=source.id)).variables+ assert source_variables is not None+ self.assertEqual(source_variables[str(subscription.id)]["value"], "sub_a")++ tiles = [t async for t in DashboardTile.objects.filter(dashboard=copy).select_related("insight")]+ insight_tiles = [t for t in tiles if t.insight is not None]+ self.assertEqual(len(tiles), 2)+ self.assertEqual(len(insight_tiles), 1)+ assert insight_tiles[0].insight is not None+ self.assertNotEqual(insight_tiles[0].insight.id, source_insight.id)+ self.assertEqual(insight_tiles[0].insight.query, source_insight.query)+ self.assertEqual(insight_tiles[0].layouts, {"sm": {"x": 0, "y": 0, "w": 6, "h": 5}})++ copied_insight = insight_tiles[0].insight+ copied_insight.query = DEFAULT_TRENDS_QUERY.model_dump()+ await copied_insight.asave(update_fields=["query"])+ await source_insight.arefresh_from_db()+ assert source_insight.query is not None+ self.assertEqual(source_insight.query["kind"], "DataVisualizationNode")++ creation_events = [+ call for call in mock_capture.call_args_list if call.kwargs.get("event") == "dashboard created"+ ]+ self.assertEqual(len(creation_events), 1)+ created_props = creation_events[0].kwargs["properties"]+ self.assertEqual(created_props["source"], "posthog_ai")+ self.assertEqual(created_props["duplicated"], True)+ self.assertEqual(created_props["duplicated_from_dashboard_id"], source.id)++ async def test_duplicate_dashboard_rejects_unknown_variable(self):+ source, *_ = await self._create_variable_dashboard()++ with self.assertRaises(MaxToolRetryableError) as error:+ await self._create_tool()._arun_impl(+ DuplicateDashboardToolArgs(+ dashboard_id=str(source.id), name="Copy", variable_values={"customer_id": "sub_b"}+ )+ )++ self.assertIn("customer_id", str(error.exception))+ self.assertIn("subscription_id", str(error.exception))+ self.assertEqual(await Dashboard.objects.filter(team=self.team).acount(), 1)++ @parameterized.expand(["validation", "permission"])+ @patch("posthog.event_usage.posthoganalytics.capture")+ async def test_duplicate_dashboard_rolls_back_failed_copy(self, failure: str, mock_capture: MagicMock) -> None:+ source, source_insight, *_ = await self._create_variable_dashboard()+ expected_error: type[MaxToolRetryableError | MaxToolAccessDeniedError] = MaxToolRetryableError+ error_message = "copy the insight"+ if failure == "validation":+ invalid_insight = await self._create_insight("x" * 400)+ else:+ expected_error = MaxToolAccessDeniedError+ error_message = "viewer access"+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ await self.organization.asave()+ membership = await OrganizationMembership.objects.aget(user=self.user, organization=self.organization)+ membership.level = OrganizationMembership.Level.MEMBER+ await membership.asave()+ invalid_insight = await self._create_insight("Restricted insight")+ await Insight.objects.filter(id=invalid_insight.id).aupdate(created_by=None)+ await AccessControl.objects.acreate(+ team=self.team,+ resource="insight",+ resource_id=str(invalid_insight.id),+ access_level="none",+ organization_member=membership,+ )+ await DashboardTile.objects.acreate(dashboard=source, insight=invalid_insight)+ dashboard_count = await Dashboard.objects.filter(team=self.team).acount()+ insight_count = await Insight.objects.filter(team=self.team).acount()+ tile_count = await DashboardTile.objects.filter(dashboard__team=self.team).acount()+ text_count = await Text.objects.filter(team=self.team).acount()++ with self.assertRaisesRegex(expected_error, error_message):+ await self._create_tool()._arun_impl(+ DuplicateDashboardToolArgs(dashboard_id=str(source.id), name="Invalid copy")+ )++ self.assertEqual(await Dashboard.objects.filter(team=self.team).acount(), dashboard_count)+ self.assertEqual(await Insight.objects.filter(team=self.team).acount(), insight_count)+ self.assertEqual(await DashboardTile.objects.filter(dashboard__team=self.team).acount(), tile_count)+ self.assertEqual(await Text.objects.filter(team=self.team).acount(), text_count)+ await source_insight.arefresh_from_db()+ assert source_insight.query is not None+ self.assertEqual(source_insight.query["kind"], "DataVisualizationNode")+ self.assertFalse(any(call.kwargs.get("event") == "dashboard created" for call in mock_capture.call_args_list))+@patch("ee.hogai.tools.upsert_dashboard.tool.report_user_action")async def test_update_dashboard_reports_dashboard_updated(self, mock_report):dashboard = await Dashboard.objects.acreate(team=self.team, name="Existing", created_by=self.user)diff --git a/ee/hogai/tools/upsert_dashboard/tool.py b/ee/hogai/tools/upsert_dashboard/tool.pyindex cbf5af1318fc..8c15538b9cf8 100644--- a/ee/hogai/tools/upsert_dashboard/tool.py+++ b/ee/hogai/tools/upsert_dashboard/tool.py@@ -3,22 +3,33 @@ from base64 import urlsafe_b64encodefrom typing import Any, Literal, TypedDict, castfrom django.db import transaction+from django.http import HttpRequestimport structlogfrom pydantic import BaseModel, Field-from rest_framework.exceptions import ValidationError--from posthog.schema import DataTableNode, DataVisualizationNode, HogQLQuery, InsightVizNode, QuerySchemaRoot+from rest_framework.exceptions import PermissionDenied, ValidationError+from rest_framework.request import Request++from posthog.schema import (+ DataTableNode,+ DataVisualizationNode,+ HogQLQuery,+ HogQLVariable,+ InsightVizNode,+ QuerySchemaRoot,+)from posthog.api.sharing_publish_gate import check_can_add_insight_to_dashboardfrom posthog.event_usage import EventSource, report_user_actionfrom posthog.sync import database_sync_to_asyncfrom posthog.utils import pluralize+from products.dashboards.backend.api.dashboard import DashboardSerializerfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.product_analytics.backend.facade.api import (get_or_create_saved_insight,+ insight_variables_for_team,insights_including_soft_deleted_for_team,)from products.product_analytics.backend.facade.models import Insight@@ -27,12 +38,13 @@ from ee.hogai.artifacts.types import ModelArtifactResult, VisualizationWithSourcfrom ee.hogai.context.dashboard.context import DashboardContext, DashboardInsightContextfrom ee.hogai.context.insight.context import InsightContextfrom ee.hogai.tool import MaxTool-from ee.hogai.tool_errors import MaxToolFatalError, MaxToolRetryableError+from ee.hogai.tool_errors import MaxToolAccessDeniedError, MaxToolFatalError, MaxToolRetryableErrorfrom ee.hogai.tools.upsert_dashboard.prompts import (CREATE_NO_INSIGHTS_PROMPT,DASHBOARD_NOT_FOUND_PROMPT,MISSING_INSIGHT_IDS_PROMPT,PERMISSION_REQUEST_PROMPT,+ UNKNOWN_VARIABLES_PROMPT,UPDATE_NO_CHANGES_PROMPT,UPSERT_DASHBOARD_CONTEXT_PROMPT_TEMPLATE,UPSERT_DASHBOARD_TOOL_PROMPT,@@ -86,7 +98,28 @@ class AddDashboardInsightsToolArgs(BaseModel):insight_ids: list[str] = Field(description="The IDs of the insights to add to the dashboard.")-UpsertDashboardAction = CreateDashboardToolArgs | UpdateDashboardToolArgs | AddDashboardInsightsToolArgs+class DuplicateDashboardToolArgs(BaseModel):+ """Schema to copy an existing dashboard with its variables, filters, tiles, and insight display settings."""++ action: Literal["duplicate"] = "duplicate"+ dashboard_id: str = Field(description="The ID of the dashboard to copy.")+ name: str = Field(description="A short and concise (3-7 words) name of the new dashboard.")+ description: str | None = Field(+ description="A short description of the new dashboard. If not provided, the source description is kept.",+ default=None,+ )+ variable_values: dict[str, Any] | None = Field(+ description=(+ "New values for SQL variables on the copy, keyed by the variable code name, "+ 'for example {"subscription_id": "sub_123"}. Variables that are not listed keep the source values.'+ ),+ default=None,+ )+++UpsertDashboardAction = (+ CreateDashboardToolArgs | UpdateDashboardToolArgs | AddDashboardInsightsToolArgs | DuplicateDashboardToolArgs+)class UpsertDashboardToolArgs(BaseModel):@@ -170,6 +203,8 @@ class UpsertDashboardTool(MaxTool):return await self._handle_create(action)if isinstance(action, UpdateDashboardToolArgs):return await self._handle_update(action)+ if isinstance(action, DuplicateDashboardToolArgs):+ return await self._handle_duplicate(action)return await self._handle_add_insights(action)async def _handle_create(self, action: CreateDashboardToolArgs) -> tuple[str, dict | None]:@@ -257,6 +292,89 @@ class UpsertDashboardTool(MaxTool):return output, {"dashboard_id": dashboard.id}+ async def _handle_duplicate(self, action: DuplicateDashboardToolArgs) -> tuple[str, dict | None]:+ """Copy a dashboard as it is, so SQL variables and insight chart settings survive the copy."""+ source = await self._get_dashboard(action.dashboard_id, required_level="viewer")+ variables = await database_sync_to_async(self._resolve_duplicate_variables)(+ source.variables or {}, action.variable_values or {}+ )+ dashboard = await self._duplicate_dashboard(+ source,+ action.name,+ source.description if action.description is None else action.description,+ variables,+ )++ 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_duplicate_variables(+ self, source_variables: dict[str, Any], variable_values: dict[str, Any]+ ) -> dict[str, Any]:+ variables = {key: dict(value) for key, value in source_variables.items() if isinstance(value, dict)}+ if not variable_values:+ return variables++ team_variables = {+ variable.code_name: variable for variable in insight_variables_for_team(self._team.id) if variable.code_name+ }+ unknown = [code_name for code_name in variable_values if code_name not in team_variables]+ if unknown:+ raise MaxToolRetryableError(+ format_prompt_string(+ UNKNOWN_VARIABLES_PROMPT,+ unknown_variables=", ".join(unknown),+ available_variables=", ".join(sorted(team_variables)) or "none",+ )+ )++ for code_name, value in variable_values.items():+ variable_id = str(team_variables[code_name].id)+ variables[variable_id] = HogQLVariable(+ variableId=variable_id, code_name=code_name, value=value, isNull=value is None+ ).model_dump(exclude_none=True)+ return variables++ @database_sync_to_async+ @transaction.atomic+ def _duplicate_dashboard(+ self, source: Dashboard, name: str, description: str, variables: dict[str, Any]+ ) -> Dashboard:+ http_request = HttpRequest()+ http_request.method = "GET"+ request = Request(http_request)+ request.user = self._user+ request.auth = None+ cast(Any, request)._authenticator = None+ serializer = DashboardSerializer(+ data={+ "use_dashboard": source.id,+ "duplicate_tiles": True,+ "name": name,+ "description": description,+ },+ context={+ "request": request,+ "team_id": self._team.id,+ "get_team": lambda: self._team,+ "insight_variables": insight_variables_for_team(self._team.id),+ "creation_event_properties": {"source": EventSource.POSTHOG_AI},+ },+ )+ try:+ serializer.is_valid(raise_exception=True)+ dashboard = serializer.save()+ except PermissionDenied as error:+ raise MaxToolAccessDeniedError("insight", "viewer", action="read") from error+ except ValidationError as error:+ raise MaxToolRetryableError(str(error.detail)) from error+ dashboard.variables = variables+ dashboard.save(update_fields=["variables"])+ return dashboard+def _resolve_insights(self, artifacts: list[VisualizationWithSourceResult]) -> list[Insight]:"""Resolve insight_ids using VisualizationHandler.@@ -654,7 +772,9 @@ class UpsertDashboardTool(MaxTool):return await context.format_schema()- async def _get_dashboard(self, dashboard_id: Any) -> Dashboard:+ async def _get_dashboard(+ self, dashboard_id: Any, required_level: Literal["viewer", "editor"] = "editor"+ ) -> Dashboard:"""Get the dashboard and sorted tiles for the given dashboard ID."""# LLMs sometimes output IDs as floats (e.g., "642161.0"), so we parse to inttry:@@ -666,7 +786,9 @@ class UpsertDashboardTool(MaxTool):except Dashboard.DoesNotExist:raise MaxToolFatalError(DASHBOARD_NOT_FOUND_PROMPT.format(dashboard_id=dashboard_id))- await self.check_object_access(dashboard, "editor", action="edit")+ await self.check_object_access(+ dashboard, required_level, action="edit" if required_level == "editor" else "read"+ )return dashboarddiff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 57a17e997e6d..a3f77699fcf7 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -2015,6 +2015,7 @@ class DashboardSerializer(DashboardMetadataSerializer):"template_key": use_template,"duplicated": bool(use_dashboard),"duplicated_from_dashboard_id": use_dashboard,+ **self.context.get("creation_event_properties", {}),},team=dashboard.team,request=request,