: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(posthog-ai): update saved insights from chat (#104641)
Matt Pua80fa7fee6be6
diff --git a/ee/hogai/core/runner.py b/ee/hogai/core/runner.pyindex da3a2010eda0..0122ad22d986 100644--- a/ee/hogai/core/runner.py+++ b/ee/hogai/core/runner.py@@ -495,6 +495,8 @@ class BaseAgentRunner(ABC):interrupt_messages: list[Any] = []should_not_update_state = Falsefor task in state.tasks:+ if task.result is not None:+ continuefor interrupt in task.interrupts:if interrupt.value is None:continue # Skip None interrupts@@ -587,6 +589,24 @@ class BaseAgentRunner(ABC):if message.id is not None:self._stream_processor.mark_id_as_streamed(message.id)+ resume_value = self._resume_payload+ if self._resume_payload and self._resume_payload.get("action") in ("approve", "reject"):+ proposal_id = self._resume_payload.get("proposal_id")+ approval_interrupt = next(+ (+ pending+ for task in snapshot.tasks+ if task.result is None+ for pending in task.interrupts+ if isinstance(pending.value, ApprovalRequest) and pending.value.proposal_id == proposal_id+ ),+ None,+ )+ if approval_interrupt is None:+ raise ValueError("Approval does not match a pending operation")+ # A scalar resume targets the next interrupt, which may belong to a different approval card.+ resume_value = {approval_interrupt.interrupt_id: self._resume_payload}+# If there are pending nodes (snapshot.next is non-empty), we need to resume.# This happens when:# 1. A tool called interrupt() for approval - snapshot.next will have pending nodes@@ -603,8 +623,8 @@ class BaseAgentRunner(ABC):# If there's a new message alongside the resume (user sent message while approval pending),# include it in the state update so the agent sees it as a proper HumanMessageif self._latest_message:- return Command(resume=self._resume_payload, update={"messages": [self._latest_message]})- return Command(resume=self._resume_payload)+ return Command(resume=resume_value, update={"messages": [self._latest_message]})+ return Command(resume=resume_value)elif saved_state.graph_status == "interrupted":# NodeInterrupt without approval flow - add the new message and resumeif self._latest_message:diff --git a/ee/hogai/core/test/test_runner.py b/ee/hogai/core/test/test_runner.pyindex fec924f7fea2..551f44b9f5f2 100644--- a/ee/hogai/core/test/test_runner.py+++ b/ee/hogai/core/test/test_runner.py@@ -1,6 +1,7 @@-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Callablefrom contextlib import asynccontextmanagerfrom typing import cast+from uuid import uuid4from posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, MagicMock, patch@@ -8,6 +9,9 @@ from unittest.mock import AsyncMock, MagicMock, patchimport httpximport openaiimport anthropic+from langgraph.checkpoint.memory import MemorySaver+from langgraph.graph import END, START, StateGraph+from langgraph.types import interruptfrom parameterized import parameterizedfrom posthog.schema import AssistantEventType, FailureMessage@@ -15,7 +19,7 @@ from posthog.schema import AssistantEventType, FailureMessagefrom products.posthog_ai.backend.models.assistant import Conversationfrom ee.hogai.core.base import BaseAssistantGraph-from ee.hogai.tool import ClientToolCallRequest+from ee.hogai.tool import ApprovalRequest, ClientToolCallRequestfrom ee.hogai.utils.types.base import AssistantState, ConversationTitleAction, PartialAssistantState@@ -767,7 +771,7 @@ class TestRunnerClientToolCallInterrupt(BaseTest):mock_state = MagicMock()mock_state.values = {}mock_state.next = ["pending_node"]- mock_state.tasks = [MagicMock(interrupts=[MagicMock(value=interrupt_value)])]+ mock_state.tasks = [MagicMock(result=None, interrupts=[MagicMock(value=interrupt_value)])]mock_graph.aget_state = AsyncMock(return_value=mock_state)mock_graph.aupdate_state = AsyncMock()@@ -823,3 +827,59 @@ class TestRunnerClientToolCallInterrupt(BaseTest):self.assertTrue(any(getattr(m, "content", None) == "Please clarify your request" for m in messages))mock_graph.aupdate_state.assert_called_once()++ @parameterized.expand([("approve",), ("reject",)])+ async def test_response_targets_selected_parallel_approval(self, action: str) -> None:+ executed: list[str] = []++ def operation(name: str) -> Callable[[AssistantState], dict[str, object]]:+ proposal_id = str(uuid4())++ def run(state: AssistantState) -> dict[str, object]:+ response = interrupt(+ ApprovalRequest(+ proposal_id=proposal_id, tool_name=name, preview=name, payload={}, original_tool_call_id=name+ )+ )+ if response["action"] == "approve":+ executed.append(name)+ return {}++ return run++ builder = StateGraph(AssistantState)+ for name in ("first", "second"):+ builder.add_node(name, operation(name))+ builder.add_edge(START, name)+ builder.add_edge(name, END)+ graph = builder.compile(checkpointer=MemorySaver())+ runner, _ = self._create_runner_with_interrupt(None)+ runner._graph = graph+ config = runner._get_config()+ config["callbacks"] = []+ await graph.ainvoke(AssistantState(messages=[]), config)+ snapshot = await graph.aget_state(config)+ approvals = {pending.value.tool_name: pending.value for task in snapshot.tasks for pending in task.interrupts}+ for approval in approvals.values():+ self.conversation.approval_decisions[approval.proposal_id] = {"decision_status": "pending"}+ runner._resume_payload = {"action": action, "proposal_id": approvals["second"].proposal_id}+ command = await runner._init_or_update_state()+ await graph.ainvoke(command, config)+ self.assertEqual(executed, ["second"] if action == "approve" else [])+ after = await graph.aget_state(config)+ remaining = [pending.value for task in after.tasks if task.result is None for pending in task.interrupts]+ self.assertEqual([request.proposal_id for request in remaining], [approvals["first"].proposal_id])+ await self.conversation.arefresh_from_db()+ self.assertEqual(+ self.conversation.approval_decisions[approvals["first"].proposal_id]["decision_status"], "pending"+ )+ self.assertEqual(+ self.conversation.approval_decisions[approvals["second"].proposal_id]["decision_status"],+ "approved" if action == "approve" else "rejected",+ )+ with self.assertRaisesMessage(ValueError, "Approval does not match a pending operation"):+ await runner._init_or_update_state()+ runner._resume_payload = {"action": "reject", "proposal_id": approvals["first"].proposal_id}+ await graph.ainvoke(await runner._init_or_update_state(), config)+ self.assertFalse((await graph.aget_state(config)).next)+ self.assertEqual(executed, ["second"] if action == "approve" else [])diff --git a/ee/hogai/test/test_tool.py b/ee/hogai/test/test_tool.pyindex 67a97b479d01..51e2fcc6e9c9 100644--- a/ee/hogai/test/test_tool.py+++ b/ee/hogai/test/test_tool.py@@ -529,3 +529,19 @@ class TestDangerousOperationBindsApprovedArguments(BaseTest):assert artifact["count"] == 5assert "5" in content++ def test_parallel_resumption_keeps_approval_identity(self) -> None:+ proposals = []+ for call_id in ("first", "second", "first"):+ tool = self._SpendingTool(+ team=self.team,+ user=self.user,+ node_path=(NodePath(name="root", tool_call_id=call_id),),+ config={"configurable": {"thread_id": "approval-test"}},+ )+ with patch("ee.hogai.tool.interrupt", side_effect=GraphInterrupt()) as mocked_interrupt:+ with self.assertRaises(GraphInterrupt):+ tool._handle_dangerous_operation({"count": 5}, preview="Change count")+ proposals.append(mocked_interrupt.call_args.args[0].proposal_id)+ self.assertEqual(proposals[0], proposals[2])+ self.assertNotEqual(proposals[0], proposals[1])diff --git a/ee/hogai/tool.py b/ee/hogai/tool.pyindex 9fa5dbeccb73..a5795192d980 100644--- a/ee/hogai/tool.py+++ b/ee/hogai/tool.py@@ -381,7 +381,12 @@ class MaxTool(AssistantContextMixin, AssistantDispatcherMixin, BaseTool):if preview is None:raise ValueError("preview must be provided for dangerous operations")- proposal_id = str(uuid.uuid4())+ # Other parallel approvals can resume while this tool stays interrupted.+ proposal_id = str(+ uuid.uuid5(uuid.NAMESPACE_URL, f"{self._get_conversation_id()}:{self._original_tool_call_id}")+ if self._original_tool_call_id+ else uuid.uuid4()+ )serialized_payload = self._serialize_kwargs_for_storage(kwargs)approval_request = ApprovalRequest(diff --git a/ee/hogai/tools/create_insight.py b/ee/hogai/tools/create_insight.pyindex 6dd4575c3417..b683c2fe2c38 100644--- a/ee/hogai/tools/create_insight.py+++ b/ee/hogai/tools/create_insight.py@@ -1,22 +1,42 @@-from typing import Literal, Self+import json+from typing import Any, Literal, Self, cast+import jsonpatch+from jsonpointer import JsonPointerExceptionfrom langchain_core.runnables import RunnableConfig-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, ValidationError-from posthog.schema import AssistantTool, AssistantToolCallMessage, VisualizationArtifactContent+from posthog.schema import (+ ArtifactContentType,+ ArtifactSource,+ AssistantTool,+ AssistantToolCallMessage,+ QuerySchemaRoot,+ VisualizationArtifactContent,+)from posthog.models import Team, User+from posthog.sync import database_sync_to_async++from products.product_analytics.backend.facade.api import save_saved_insight_query, saved_insight_for_update+from products.product_analytics.backend.facade.contracts import SavedInsightDefinitionfrom ee.hogai.artifacts.utils import is_visualization_artifact_messagefrom ee.hogai.chat_agent.insights_graph.graph import InsightsGraphfrom ee.hogai.chat_agent.schema_generator.nodes import SchemaGenerationExceptionfrom ee.hogai.context.context import AssistantContextManagerfrom ee.hogai.tool import MaxTool, ToolMessagesArtifact+from ee.hogai.tool_errors import MaxToolRetryableErrorfrom ee.hogai.utils.prompt import format_prompt_string-from ee.hogai.utils.types.base import AssistantNodeName, AssistantState, NodePath+from ee.hogai.utils.types.base import ArtifactRefMessage, AssistantNodeName, AssistantState, NodePathINSIGHT_TOOL_PROMPT = """-Use this tool to generate an insight from a structured plan. It will return a visualization that the user can analyze and a textual representation for your analysis. These visualizations are transient and only exist within the current conversation—they are not saved to the project. To save an insight permanently, users should click the open insight icon below the chart in the conversation.+Use this tool to generate an insight from a structured plan. It will return a visualization that the user can analyze and a textual representation for your analysis. Without `insight_id`, these visualizations are transient and are not saved to the project. To save an insight permanently, users should click the open insight icon below the chart in the conversation.++A chart generated in this conversation can have an artifact or visualization ID without being saved. Never pass those IDs as `insight_id`. To revise an unsaved chart, omit both `insight_id` and `query_patch`, and provide a revised structured plan based on that chart and the requested changes. Only use `insight_id` after confirming the saved insight in this project through search or read_data.++To update an existing saved insight, first read its saved query with read_data, then provide its short ID as `insight_id` and `query_patch` as a JSON-encoded array of JSON Patch operations against that full query. This saves the same insight and affects every dashboard referencing it. Use narrow paths for only the changes in the current request. Do not apply remembered preferences, defaults, or other improvements to unrelated settings. For example, [{"op":"replace","path":"/source/breakdownFilter/breakdown","value":"name"}] changes a legacy breakdown property; for a breakdowns list, use /source/breakdownFilter/breakdowns/0/property. Use add to set an optional field, remove to delete a field, and move with from/path to reorder a series without rebuilding it. Parent objects must exist. Never regenerate the whole query or replace a whole filter object to change one setting. Use the saved query, not dashboard overrides. Do not create a replacement insight or use upsert_dashboard for insight edits. The existing name and description are preserved. query_description and insight_type are used only for generation, not saved edits.+When editing the currently open insight editor, omit `insight_id` to apply a draft to the editor, including its unsaved changes. Supply `insight_id` only when the user asks to save directly to that insight.This tool can also be used to edit the visualization the user is currently viewing on the insight page. In that case, you need to generate a new plan based on the schema of the existing insight.@@ -516,6 +536,15 @@ InsightType = Literal["trends", "funnel", "retention", "sql"]class CreateInsightToolArgs(BaseModel):+ insight_id: str | None = Field(+ default=None,+ description="Short ID of a saved insight in this project, confirmed through search or read_data. Never use an unsaved chart's artifact or visualization ID. Omit to create or revise an unsaved chart, or edit the open editor's draft.",+ )+ query_patch: str | None = Field(+ default=None,+ description="Required for saved edits: JSON-encoded JSON Patch array against the full saved query. Use add, replace, remove, move or test with precise paths. Read the saved query first. Omit for generation.",+ )+ expected_query: dict[str, Any] | None = Field(default=None, exclude=True)query_description: str = Field(description="A plan of the query to generate based on the template.")insight_type: InsightType = Field(description="The type of insight to generate.")viz_title: str = Field(@@ -535,6 +564,91 @@ class CreateInsightTool(MaxTool):"""Creating an insight requires editor-level access to insights."""return [("insight", "editor")]+ async def _get_insight(self, insight_id: str) -> SavedInsightDefinition:+ insight = await database_sync_to_async(saved_insight_for_update)(+ team=self._team, user=self._user, short_id=insight_id+ )+ if insight is None:+ raise MaxToolRetryableError(+ "Insight not found. insight_id must be the short ID of a saved insight in this project. "+ "For an unsaved chart from this conversation, omit insight_id and query_patch and provide a revised "+ "structured plan. For a saved insight, use search or read_data to confirm its short ID before retrying."+ )+ return insight++ async def is_dangerous_operation(self, insight_id: str | None = None, **kwargs: Any) -> bool:+ return insight_id is not None++ async def format_dangerous_operation_preview(+ self, insight_id: str | None = None, query_patch: str | None = None, **kwargs: Any+ ) -> str:+ if insight_id is None:+ raise MaxToolRetryableError("Provide the short ID of the insight to update.")+ insight = await self._get_insight(insight_id)+ preview = f"Update insight **{insight.name or insight.short_id}**. This changes every dashboard that uses this insight."+ if query_patch is not None:+ self._updated_insight_query(insight, query_patch)+ preview += f"\n\nRequested query edits:\n```json\n{json.dumps(json.loads(query_patch), indent=2)}\n```"+ return preview++ async def _check_dangerous_operation(self, kwargs: dict[str, Any]) -> tuple[str, Any] | None:+ insight_id = kwargs.get("insight_id")+ if insight_id is None:+ return await super()._check_dangerous_operation(kwargs)++ insight = await self._get_insight(insight_id)+ if kwargs.get("expected_query") is None:+ kwargs["expected_query"] = insight.query+ preview = f"Update insight **{insight.name or insight.short_id}**. This changes every dashboard that uses this insight."+ if query_patch := kwargs.get("query_patch"):+ self._updated_insight_query(insight, query_patch)+ preview += f"\n\nRequested query edits:\n```json\n{json.dumps(json.loads(query_patch), indent=2)}\n```"+ return self._handle_dangerous_operation(kwargs, preview=preview)++ @staticmethod+ def _updated_insight_query(insight: SavedInsightDefinition, query_patch: str) -> dict[str, Any]:+ try:+ operations = json.loads(query_patch)+ if not isinstance(operations, list) or not operations:+ raise ValueError("Provide at least one query edit.")+ for operation in operations:+ if (+ not isinstance(operation, dict)+ or operation.get("op") not in {"add", "replace", "remove", "move", "test"}+ or not isinstance(operation.get("path"), str)+ or not operation["path"].startswith("/")+ ):+ raise ValueError("Use add, replace, remove, move or test with a nonempty JSON Pointer path.")+ original = insight.query or {}+ query = jsonpatch.apply_patch(original, operations)+ original_source = original.get("source", original)+ source = query.get("source", query)+ if query.get("kind") != original.get("kind") or source.get("kind") != original_source.get("kind"):+ raise ValueError("Editing an insight cannot change its query type.")+ query.pop("response", None)+ source.pop("response", None)+ QuerySchemaRoot.model_validate(query)+ return cast(dict[str, Any], query)+ except (+ ValueError,+ TypeError,+ KeyError,+ AttributeError,+ jsonpatch.JsonPatchException,+ JsonPointerException,+ ValidationError,+ ) as error:+ raise MaxToolRetryableError(+ f"Could not apply the query edits. Read the saved query and retry: {error}"+ ) from error++ async def _save_insight_query(self, insight: SavedInsightDefinition, query: dict[str, Any]) -> None:+ error = await database_sync_to_async(save_saved_insight_query)(+ team=self._team, user=self._user, insight_id=insight.id, expected_query=insight.query, query=query+ )+ if error:+ raise MaxToolRetryableError(error)+@classmethodasync def create_tool_class(cls,@@ -554,8 +668,39 @@ class CreateInsightTool(MaxTool):return cls(team=team, user=user, state=state, node_path=node_path, config=config, description=prompt)async def _arun_impl(- self, viz_title: str, viz_description: str, query_description: str, insight_type: InsightType+ self,+ viz_title: str,+ viz_description: str,+ query_description: str,+ insight_type: InsightType,+ insight_id: str | None = None,+ query_patch: str | None = None,+ expected_query: dict[str, Any] | None = None,) -> tuple[str, ToolMessagesArtifact | None]:+ if insight_id is not None:+ if query_patch is None:+ raise MaxToolRetryableError("Read the saved insight and provide query_patch with the requested edits.")+ insight = await self._get_insight(insight_id)+ if expected_query is not None and insight.query != expected_query:+ raise MaxToolRetryableError("This insight changed while awaiting approval. Read it again and retry.")+ await self._save_insight_query(insight, self._updated_insight_query(insight, query_patch))+ return "", ToolMessagesArtifact(+ messages=[+ ArtifactRefMessage(+ id=f"{self.tool_call_id}-saved-insight",+ content_type=ArtifactContentType.VISUALIZATION,+ source=ArtifactSource.INSIGHT,+ artifact_id=insight.short_id,+ ),+ AssistantToolCallMessage(+ content=f"Updated existing insight {insight.short_id}. All dashboards using it now use the updated query.",+ tool_call_id=self.tool_call_id,+ ui_payload={self.get_name(): {"saved_insight": {"short_id": insight.short_id}}},+ ),+ ]+ )+ if query_patch is not None:+ raise MaxToolRetryableError("Provide insight_id to edit a saved insight.")graph_builder = InsightsGraph(self._team, self._user)match insight_type:case "trends":diff --git a/ee/hogai/tools/test/test_create_insight.py b/ee/hogai/tools/test/test_create_insight.pyindex eb282b42ef82..53a8cb136c67 100644--- a/ee/hogai/tools/test/test_create_insight.py+++ b/ee/hogai/tools/test/test_create_insight.py@@ -1,9 +1,11 @@+import jsonfrom typing import Anyfrom posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTestfrom unittest.mock import AsyncMock, patchfrom langchain_core.runnables import RunnableConfig+from parameterized import parameterizedfrom posthog.schema import (ArtifactContentType,@@ -16,10 +18,19 @@ from posthog.schema import (VisualizationArtifactContent,)+from posthog.constants import AvailableFeature+from posthog.models import SharingConfiguration, Team, User+from posthog.sync import database_sync_to_async++from products.access_control.backend.models.access_control import AccessControl+from products.dashboards.backend.models.dashboard import Dashboard+from products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.posthog_ai.backend.models.assistant import AgentArtifact, Conversation+from products.product_analytics.backend.facade.models import Insightfrom ee.hogai.chat_agent.schema_generator.nodes import SchemaGenerationExceptionfrom ee.hogai.context.context import AssistantContextManager+from ee.hogai.tool_errors import MaxToolRetryableErrorfrom ee.hogai.tools.create_insight import INSIGHT_TOOL_FAILURE_SYSTEM_REMINDER_PROMPT, CreateInsightToolfrom ee.hogai.utils.types import AssistantStatefrom ee.hogai.utils.types.base import ArtifactRefMessage, AssistantNodeName, NodePath@@ -58,9 +69,7 @@ class TestCreateInsightTool(ClickhouseTestMixin, NonAtomicBaseTest):return toolasync def test_successful_trends_insight_creation_returns_messages(self):- """Test successful trends insight creation returns visualization and tool call messages."""tool = await self._create_tool()-query = AssistantTrendsQuery(series=[])artifact = await AgentArtifact.objects.acreate(team=self.team,@@ -76,7 +85,6 @@ class TestCreateInsightTool(ClickhouseTestMixin, NonAtomicBaseTest):id="123",)tool_call_message = AssistantToolCallMessage(content="Results are here", tool_call_id=self.tool_call_id)-mock_state = AssistantState(messages=[artifact_message, tool_call_message])with patch("ee.hogai.tools.create_insight.InsightsGraph") as mock_graph_class:@@ -84,12 +92,10 @@ class TestCreateInsightTool(ClickhouseTestMixin, NonAtomicBaseTest):mock_graph_builder.add_trends_generator.return_value = mock_graph_buildermock_graph_builder.add_edge.return_value = mock_graph_buildermock_graph_builder.add_query_executor.return_value = mock_graph_builder-mock_compiled_graph = AsyncMock()mock_compiled_graph.ainvoke = AsyncMock(return_value=mock_state.model_dump())mock_graph_builder.compile.return_value = mock_compiled_graph-- result_text, artifact = await tool._arun_impl(+ result_text, result_artifact = await tool._arun_impl(viz_title="Test Chart",viz_description="Test description",query_description="test trends description",@@ -97,15 +103,200 @@ class TestCreateInsightTool(ClickhouseTestMixin, NonAtomicBaseTest):)self.assertEqual(result_text, "")- self.assertIsNotNone(artifact)- self.assertEqual(len(artifact.messages), 2)- self.assertIsInstance(artifact.messages[0], ArtifactRefMessage)- self.assertIsInstance(artifact.messages[1], AssistantToolCallMessage)-- # Verify correct graph nodes were added+ self.assertIsNotNone(result_artifact)+ self.assertEqual(len(result_artifact.messages), 2)mock_graph_builder.add_trends_generator.assert_called_once()mock_graph_builder.add_edge.assert_called_with(AssistantNodeName.START, AssistantNodeName.TRENDS_GENERATOR)+ async def test_saved_update_requires_approval_and_rejects_concurrent_changes(self):+ tool = await self._create_tool()+ insight = await Insight.objects.acreate(+ team=self.team, name="Existing chart", query={"kind": "TrendsQuery", "series": []}+ )+ self.assertFalse(await tool.is_dangerous_operation())+ self.assertTrue(await tool.is_dangerous_operation(insight_id=insight.short_id))+ self.assertIn("Existing chart", await tool.format_dangerous_operation_preview(insight_id=insight.short_id))+ concurrent_query = {"kind": "TrendsQuery", "series": [], "interval": "week"}+ await Insight.objects.filter(pk=insight.pk).aupdate(query=concurrent_query)+ with self.assertRaisesRegex(MaxToolRetryableError, "changed while generating"):+ await tool._save_insight_query(insight, {"kind": "TrendsQuery", "series": [], "interval": "month"})+ await insight.arefresh_from_db()+ self.assertEqual(insight.query, concurrent_query)++ async def test_saved_update_rejects_changes_after_approval_preview(self):+ tool = await self._create_tool()+ original_query = {"kind": "TrendsQuery", "series": []}+ insight = await Insight.objects.acreate(team=self.team, query=original_query)+ concurrent_query = {"kind": "TrendsQuery", "series": [], "interval": "week"}+ await Insight.objects.filter(pk=insight.pk).aupdate(query=concurrent_query)++ with self.assertRaisesRegex(MaxToolRetryableError, "changed while awaiting approval"):+ await tool._arun_impl(+ viz_title="Chart",+ viz_description="",+ query_description="Edit chart",+ insight_type="trends",+ insight_id=insight.short_id,+ query_patch=json.dumps([{"op": "replace", "path": "/interval", "value": "month"}]),+ expected_query=original_query,+ )++ await insight.arefresh_from_db()+ self.assertEqual(insight.query, concurrent_query)++ @parameterized.expand([("deleted",), ("other_project",)])+ async def test_update_rejects_unavailable_insight(self, reason: str):+ tool = await self._create_tool()+ insight = await Insight.objects.acreate(team=self.team, deleted=reason == "deleted")+ if reason == "other_project":+ other_team = await database_sync_to_async(Team.objects.create_with_data)(+ organization=self.organization, initiating_user=self.user+ )+ await Insight.objects.filter(pk=insight.pk).aupdate(team=other_team)+ with self.assertRaisesRegex(MaxToolRetryableError, "Insight not found"):+ await tool._get_insight(insight.short_id)++ @parameterized.expand(+ [+ (+ [+ {"op": "replace", "path": "/source/interval", "value": "week"},+ {"op": "remove", "path": "/source/missing"},+ ],+ ),+ ([{"op": "replace", "path": "/source/interval", "value": "invalid"}],),+ ([{"op": "replace", "path": "/source/kind", "value": "FunnelsQuery"}],),+ (+ [+ {"op": "test", "path": "/source/interval", "value": "month"},+ {"op": "replace", "path": "/source/interval", "value": "week"},+ ],+ ),+ ]+ )+ async def test_invalid_saved_edit_leaves_query_unchanged(self, operations):+ tool = await self._create_tool()+ original = {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": [], "interval": "day"}}+ insight = await Insight.objects.acreate(team=self.team, query=original)+ with self.assertRaises(MaxToolRetryableError):+ await tool._arun_impl(+ viz_title="Chart",+ viz_description="",+ query_description="Edit chart",+ insight_type="trends",+ insight_id=insight.short_id,+ query_patch=json.dumps(operations),+ )+ await insight.arefresh_from_db()+ self.assertEqual(insight.query, original)++ async def test_saved_update_requires_object_edit_permission(self):+ tool = await self._create_tool()+ insight = await Insight.objects.acreate(team=self.team, query={"kind": "TrendsQuery", "series": []})+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": "Access control"}+ ]+ await self.organization.asave()+ self.team.organization = self.organization+ self.user = await database_sync_to_async(User.objects.create_and_join)(+ self.organization, "[email protected]", "test-password"+ )+ tool = await self._create_tool()+ await tool._get_insight(insight.short_id)+ await AccessControl.objects.acreate(+ team=self.team, resource="insight", resource_id=str(insight.pk), access_level="viewer"+ )+ with self.assertRaisesRegex(MaxToolRetryableError, "Insight not found"):+ await tool._get_insight(insight.short_id)+ with self.assertRaisesRegex(MaxToolRetryableError, "permission to edit"):+ await tool._save_insight_query(insight, {"kind": "TrendsQuery", "series": [], "interval": "week"})+ await insight.arefresh_from_db()+ self.assertEqual(insight.query, {"kind": "TrendsQuery", "series": []})++ async def test_saved_update_blocks_restricted_query_on_public_share(self):+ tool = await self._create_tool()+ original_query = {"kind": "TrendsQuery", "series": []}+ insight = await Insight.objects.acreate(team=self.team, query=original_query)+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": "Access control"}+ ]+ await self.organization.asave()+ self.team.organization = self.organization+ self.user = await database_sync_to_async(User.objects.create_and_join)(+ self.organization, "[email protected]", "test-password"+ )+ tool = await self._create_tool()+ await SharingConfiguration.objects.acreate(team=self.team, insight=insight, enabled=True)++ with patch("posthog.api.sharing_publish_gate.blocked_access_for_user", return_value=["restricted table"]):+ with self.assertRaisesRegex(MaxToolRetryableError, "publicly shared"):+ await tool._save_insight_query(insight, {"kind": "TrendsQuery", "series": [], "interval": "week"})++ await insight.arefresh_from_db()+ self.assertEqual(insight.query, original_query)++ async def test_saved_update_preserves_query_settings_and_dashboard_tiles(self):+ tool = await self._create_tool()+ original_query = {+ "kind": "InsightVizNode",+ "showTable": True,+ "source": {+ "kind": "TrendsQuery",+ "series": [],+ "dataColorTheme": 7,+ "dateRange": {"date_from": "-7d"},+ "breakdownFilter": {+ "breakdown": "email",+ "breakdown_type": "person",+ "breakdown_limit": 10,+ "breakdown_hide_other_aggregation": True,+ },+ "trendsFilter": {"hideWeekends": True},+ "modifiers": {"personsOnEventsMode": "person_id_override_properties_joined"},+ },+ }+ insight = await Insight.objects.acreate(+ team=self.team, name="Existing name", description="Existing description", saved=False, query=original_query+ )+ for name in ["First dashboard", "Second dashboard"]:+ dashboard = await Dashboard.objects.acreate(team=self.team, name=name)+ await DashboardTile.objects.acreate(+ dashboard=dashboard, insight=insight, layouts={"sm": {"x": 0, "y": 0}}, color="blue"+ )+ result_text, artifact = await tool._arun_impl(+ viz_title="Ignored for saved updates",+ viz_description="Ignored for saved updates",+ query_description="Change the breakdown",+ insight_type="trends",+ insight_id=insight.short_id,+ query_patch=json.dumps([{"op": "replace", "path": "/source/breakdownFilter/breakdown", "value": "name"}]),+ )+ self.assertEqual(result_text, "")+ self.assertIsNotNone(artifact)+ self.assertEqual(len(artifact.messages), 2)+ await insight.arefresh_from_db()+ saved_query = insight.query+ assert isinstance(saved_query, dict)+ self.assertEqual(saved_query["source"]["breakdownFilter"]["breakdown"], "name")+ self.assertEqual(saved_query["source"]["trendsFilter"], {"hideWeekends": True})+ self.assertEqual(+ saved_query["source"]["modifiers"], {"personsOnEventsMode": "person_id_override_properties_joined"}+ )+ self.assertEqual(insight.name, "Existing name")+ self.assertEqual(insight.description, "Existing description")+ self.assertEqual(await Insight.objects.filter(team=self.team).acount(), 1)+ self.assertEqual(+ await DashboardTile.objects.filter(+ insight=insight, color="blue", layouts={"sm": {"x": 0, "y": 0}}+ ).acount(),+ 2,+ )+ self.assertEqual(artifact.messages[0].artifact_id, insight.short_id)+ self.assertEqual(+ artifact.messages[1].ui_payload,+ {"create_insight": {"saved_insight": {"short_id": insight.short_id}}},+ )+async def test_successful_funnel_insight_creation_returns_messages(self):"""Test successful funnel insight creation uses correct generator node."""tool = await self._create_tool()@@ -211,6 +402,7 @@ class TestCreateInsightTool(ClickhouseTestMixin, NonAtomicBaseTest):with patch("ee.hogai.tools.create_insight.InsightsGraph") as mock_graph_class:mock_graph_builder = mock_graph_class.return_valuemock_graph_builder.add_sql_generator.return_value = mock_graph_builder+ mock_graph_builder.add_retention_generator.return_value = mock_graph_buildermock_graph_builder.add_edge.return_value = mock_graph_buildermock_graph_builder.add_query_executor.return_value = mock_graph_builderdiff --git a/frontend/src/models/insightsModel.tsx b/frontend/src/models/insightsModel.tsxindex 744d8bda9be8..cb11468ab65c 100644--- a/frontend/src/models/insightsModel.tsx+++ b/frontend/src/models/insightsModel.tsx@@ -7,7 +7,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { insightsApi } from 'scenes/insights/utils/api'import { teamLogic } from 'scenes/teamLogic'-import { InsightModel } from '~/types'+import { InsightModel, InsightShortId } from '~/types'import type { Node } from '../queries/schema/schema-general'@@ -19,6 +19,9 @@ export interface insightsModelActions {duplicateInsightSuccess: (item: InsightModel) => {item: InsightModel<Node<Record<string, any>>>}+ insightSaved: (shortId: InsightShortId) => {+ shortId: InsightShortId+ }insightsAddedToDashboard: ({ dashboardId, insightIds }: { dashboardId: number; insightIds: number[] }) => {dashboardId: numberinsightIds: number[]@@ -44,6 +47,7 @@ export const insightsModel = kea<insightsModelType>([path(['models', 'insightsModel']),connect(() => ({ logic: [teamLogic] })),actions(() => ({+ insightSaved: (shortId: InsightShortId) => ({ shortId }),renameInsight: (item: InsightModel) => ({ item }),updateInsightDirect: (item: InsightModel, updates: Partial<InsightModel>) => ({item,diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.tsindex 9d1caa1256d3..657b63b65ae9 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts@@ -3427,29 +3427,40 @@ describe('dashboardLogic', () => {autoPreviewLimit.restore()})- it('uses visible SQL variable values when refreshing one tile before Preview', async () => {- const autoPreviewLimit = jest.replaceProperty(dashboardUtils, 'AUTO_PREVIEW_TILE_LIMIT', 0)- await mountDashboardWithVariable({})- const getInsightWithRetrySpy = jest- .spyOn(dashboardUtils, 'getInsightWithRetry')- .mockImplementation(async (_teamId, insight) => insight)+ it.each(['manual', 'saved insight'])(+ 'uses dashboard context for a %s tile refresh before Preview',+ async (trigger) => {+ const autoPreviewLimit = jest.replaceProperty(dashboardUtils, 'AUTO_PREVIEW_TILE_LIMIT', 0)+ await mountDashboardWithVariable({})+ const getInsightWithRetrySpy = jest+ .spyOn(dashboardUtils, 'getInsightWithRetry')+ .mockImplementation(async (_teamId, insight) => insight)- try {- await expectLogic(logic, () => {- logic.actions.overrideVariableValue(variableId, 'draft value', false)- }).toFinishAllListeners()+ try {+ await expectLogic(logic, () => {+ logic.actions.overrideVariableValue(variableId, 'draft value', false)+ }).toFinishAllListeners()- await expectLogic(logic, () => {- logic.actions.refreshDashboardItem({ tile: logic.values.insightTiles[0] })- }).toFinishAllListeners()+ await expectLogic(logic, () => {+ if (trigger === 'saved insight') {+ insightsModel.actions.insightSaved(logic.values.insightTiles[0].insight!.short_id)+ } else {+ logic.actions.refreshDashboardItem({ tile: logic.values.insightTiles[0] })+ }+ }).toFinishAllListeners()- expect(getInsightWithRetrySpy).toHaveBeenCalledTimes(1)- expect(getInsightWithRetrySpy.mock.calls[0][7]).toEqual({})- } finally {- getInsightWithRetrySpy.mockRestore()- autoPreviewLimit.restore()+ expect(getInsightWithRetrySpy).toHaveBeenCalledTimes(1)+ expect(getInsightWithRetrySpy.mock.calls[0][6]).toEqual(logic.values.effectiveRefreshFilters)+ expect(getInsightWithRetrySpy.mock.calls[0][7]).toEqual({})+ expect(getInsightWithRetrySpy.mock.calls[0][8]).toEqual(+ logic.values.insightTiles[0].filters_overrides+ )+ } finally {+ getInsightWithRetrySpy.mockRestore()+ autoPreviewLimit.restore()+ }}- })+ )it('makes Preview available when a SQL variable changes during an older preview', async () => {const autoPreviewLimit = jest.replaceProperty(dashboardUtils, 'AUTO_PREVIEW_TILE_LIMIT', 0)diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex 41410e981dee..8011d6f96ca9 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -3523,6 +3523,13 @@ export const dashboardLogic = kea<dashboardLogicType>([}},+ [insightsModel.actionTypes.insightSaved]: ({ shortId }: { shortId: InsightShortId }) => {+ for (const tile of values.insightTiles) {+ if (tile.insight?.short_id === shortId) {+ actions.refreshDashboardItem({ tile })+ }+ }+ },[insightsModel.actionTypes.duplicateInsightSuccess]: () => {// TODO this is a bit hacky, but we need to reload the dashboard to get the new insight// TODO when duplicated from a dashboard we should carry the context so only one logic needs to reloaddiff --git a/frontend/src/scenes/insights/insightLogic.test.ts b/frontend/src/scenes/insights/insightLogic.test.tsindex dcc1cbc0bd3a..1fb221044958 100644--- a/frontend/src/scenes/insights/insightLogic.test.ts+++ b/frontend/src/scenes/insights/insightLogic.test.ts@@ -40,6 +40,7 @@ import {import { insightDataLogic } from './insightDataLogic'import { createEmptyInsight, insightLogic } from './insightLogic'import { insightVizDataLogic } from './insightVizDataLogic'+import { insightsApi } from './utils/api'const API_FILTERS: Partial<FilterType> = {insight: InsightType.TRENDS as InsightType,@@ -835,6 +836,33 @@ describe('insightLogic', () => {})})+ it.each(['clean', 'draft', 'draft during refresh'])('handles an external save with a %s editor', async (state) => {+ logic = insightLogic({ dashboardItemId: Insight42 })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const original = logic.values.insight+ const updated = { ...original, name: 'Externally saved name' } as InsightModel+ let resolveRefresh!: (value: InsightModel) => void+ const refresh = new Promise<InsightModel>((resolve) => {+ resolveRefresh = resolve+ })+ const fetchInsight = jest.spyOn(insightsApi, 'getByShortId').mockReturnValue(refresh)+ if (state === 'draft') {+ logic.actions.setInsightMetadataLocal({ name: 'Unsaved name' })+ }+ insightsModel.actions.insightSaved(Insight42)+ if (state === 'draft during refresh') {+ logic.actions.setInsightMetadataLocal({ name: 'Unsaved name' })+ }+ resolveRefresh(updated)+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.insight.name).toEqual(state === 'clean' ? 'Externally saved name' : 'Unsaved name')+ if (state === 'draft') {+ expect(fetchInsight).not.toHaveBeenCalled()+ }+ fetchInsight.mockRestore()+ })+describe('setInsight name preservation', () => {it('preserves user-edited name when loading new data for the same insight', async () => {logic = insightLogic({ dashboardItemId: Insight42 })diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsxindex d7aff910849e..68f54a677492 100644--- a/frontend/src/scenes/insights/insightLogic.tsx+++ b/frontend/src/scenes/insights/insightLogic.tsx@@ -1069,6 +1069,34 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType],}),listeners(({ actions, values, props }) => ({+ [insightsModel.actionTypes.insightSaved]: async ({ shortId }: { shortId: InsightShortId }, breakpoint) => {+ if ((props.dashboardId && !isInsightSceneInstance(props)) || values.insight.short_id !== shortId) {+ return+ }+ const hasDraft = (): boolean =>+ values.insightChanged || !!insightDataLogic.findMounted(props)?.values.queryChanged+ if (hasDraft()) {+ lemonToast.info('The saved insight changed. Your unsaved edits have been kept.')+ return+ }+ try {+ const insight = await insightsApi.getByShortId(+ shortId,+ undefined,+ values.hasOverrides ? 'async_except_on_cache_miss' : 'async',+ props.filtersOverride,+ props.variablesOverride,+ props.tileFiltersOverride+ )+ breakpoint()+ if (insight && !hasDraft()) {+ actions.setInsight(insight, { overrideQuery: true, fromPersistentApi: true })+ }+ } catch {+ breakpoint()+ lemonToast.error('Could not refresh the insight. Reload it to see the saved changes.')+ }+ },saveInsight: async ({ redirectToViewMode, folder }) => {const insightNumericId =values.insight.id || (values.insight.short_id ? await getInsightId(values.insight.short_id) : undefined)diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsxindex e9484f82ee58..3198051ee9fe 100644--- a/frontend/src/scenes/max/max-constants.tsx+++ b/frontend/src/scenes/max/max-constants.tsx@@ -22,6 +22,7 @@ import { isObject } from 'lib/utils/guards'import { Scene } from 'scenes/sceneTypes'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'+import { insightsModel } from '~/models/insightsModel'import {AgentMode,AssistantTool,@@ -29,7 +30,7 @@ import {AssistantToolCallMessage,TaskExecutionStatus,} from '~/queries/schema/schema-assistant-messages'-import { RecordingUniversalFilters } from '~/types'+import { InsightShortId, RecordingUniversalFilters } from '~/types'export interface EnhancedToolCall extends AssistantToolCall {status: TaskExecutionStatus@@ -82,6 +83,7 @@ export interface ToolDefinition<N extends string = string> {toolCall: EnhancedToolCall,{ registeredToolMap }: DisplayFormatterContext) => string | [text: string, widgetDef: RecordingsWidgetDef | ReplayVisionScanWidgetDef | null]+ onResult?: (result: any) => void/*** If only available in a specific product, specify it here.* We're using Scene instead of ProductKey, because that's more flexible (specifically for SQL editor there@@ -592,7 +594,15 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {icon: iconForType('product_analytics'),product: Scene.Insight,modes: [AgentMode.ProductAnalytics],+ onResult: (result) => {+ if (result?.saved_insight?.short_id) {+ insightsModel.actions.insightSaved(result.saved_insight.short_id as InsightShortId)+ }+ },displayFormatter: (toolCall, { registeredToolMap }) => {+ if (toolCall.args?.insight_id) {+ return toolCall.status === 'completed' ? 'Updated insight' : 'Updating insight...'+ }const isEditing = registeredToolMap.create_insightif (isEditing) {return toolCall.status === 'completed'diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.tsindex 966ad0beefd0..b6741b0561ce 100644--- a/frontend/src/scenes/max/maxThreadLogic.test.ts+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts@@ -20,6 +20,7 @@ import { urls } from 'scenes/urls'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { useMocks } from '~/mocks/jest'+import { insightsModel } from '~/models/insightsModel'import * as notebooksModel from '~/models/notebooksModel'import {AgentMode,@@ -30,7 +31,14 @@ import {SlashCommandName,} from '~/queries/schema/schema-assistant-messages'import { initKeaTests } from '~/test/init'-import { Conversation, ConversationDetail, ConversationStatus, ConversationType, OrganizationType } from '~/types'+import {+ Conversation,+ ConversationDetail,+ ConversationStatus,+ ConversationType,+ OrganizationType,+ InsightShortId,+} from '~/types'import { attachedContextLogic, runStreamLogic } from 'products/posthog_ai/frontend/api/logics'import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'@@ -2210,6 +2218,33 @@ describe('maxThreadLogic', () => {logic.mount()})+ it('dispatches a saved insight refresh from a create insight result', async () => {+ const { onEventImplementation } = await import('./maxThreadLogic')+ const dashboardModel = insightsModel()+ dashboardModel.mount()+ const cache = {}+ const emit = async (message: object): Promise<void> =>+ onEventImplementation(AssistantEventType.Message, JSON.stringify(message), {+ actions: logic.actions,+ values: logic.values,+ props: logic.props,+ agentMode: null,+ cache,+ })+ const saved = {+ id: 'save-result',+ type: AssistantMessageType.ToolCall,+ content: 'Updated insight',+ tool_call_id: 'save-tool',+ ui_payload: { create_insight: { saved_insight: { short_id: 'saved-chart' } } },+ }+ await expectLogic(dashboardModel, () => emit(saved)).toDispatchActions([+ dashboardModel.actionCreators.insightSaved('saved-chart' as InsightShortId),+ ])+ await expectLogic(dashboardModel, () => emit(saved)).toNotHaveDispatchedActions(['insightSaved'])+ dashboardModel.unmount()+ })+it('handles streaming message with temp- ID by adding it first time', async () => {const { onEventImplementation } = await import('./maxThreadLogic')diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex 8ef735afb231..bfc3da21ed40 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -88,6 +88,7 @@ import {MODE_DEFINITIONS,TOOL_DEFINITIONS,ToolRegistration,+ getToolDefinition,getModeDisplayName,messageLength,} from './max-constants'@@ -3295,6 +3296,12 @@ export async function onEventImplementation(} else if (isAssistantToolCallMessage(parsedResponse)) {if (parsedResponse.ui_payload != null) {for (const [toolName, toolResult] of Object.entries(parsedResponse.ui_payload)) {+ const alreadyProcessed = parsedResponse.id+ ? cache.processedToolResultIds?.has(parsedResponse.id)+ : false+ if (!alreadyProcessed) {+ getToolDefinition(toolName)?.onResult?.(toolResult)+ }if (values.availableStaticTools.some((tool) => tool.identifier === toolName)) {continue // Static tools (mode-level) don't operate via ui_payload}@@ -3305,6 +3312,10 @@ export async function onEventImplementation(}await values.toolMap[toolName]?.callback?.(toolResult, props.conversationId)}+ if (parsedResponse.id) {+ cache.processedToolResultIds ??= new Set()+ cache.processedToolResultIds.add(parsedResponse.id)+ }}actions.addMessage({...parsedResponse,diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.pyindex 80f28ae78ca7..7ccb1de72c38 100644--- a/products/product_analytics/backend/facade/api.py+++ b/products/product_analytics/backend/facade/api.py@@ -16,10 +16,15 @@ from datetime import datetimefrom typing import TYPE_CHECKING, Anyfrom uuid import UUID+from django.db import transactionfrom django.db.models import QuerySet+from posthog.constants import AvailableFeature+from posthog.models import Team, User++from products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.product_analytics.backend import logic-from products.product_analytics.backend.facade.contracts import InsightVariableDefinition+from products.product_analytics.backend.facade.contracts import InsightVariableDefinition, SavedInsightDefinitionfrom products.product_analytics.backend.models.insight import Insightfrom products.product_analytics.backend.models.insight_variable import InsightVariable@@ -146,3 +151,49 @@ def get_or_create_saved_insight(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)+++def saved_insight_for_update(*, team: Team, user: User, short_id: str) -> SavedInsightDefinition | None:+ access_control = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))+ if not access_control.check_access_level_for_resource("insight", "editor"):+ return None+ insight = Insight.objects.filter(team=team, short_id=short_id, deleted=False).first()+ if insight is None:+ return None+ if not access_control.check_access_level_for_object(insight, "editor"):+ return None+ return SavedInsightDefinition(+ id=insight.pk, short_id=insight.short_id, name=insight.name, query=insight.query or {}+ )+++def save_saved_insight_query(+ *, team: Team, user: User, insight_id: int, expected_query: dict[str, Any], query: dict[str, Any]+) -> str | None:+ from posthog.api.sharing_publish_gate import blocked_access_for_user, is_publicly_shared # noqa: PLC0415, I001 — avoids HogQL import cycle++ with transaction.atomic():+ insight = Insight.objects.select_for_update().filter(team=team, pk=insight_id, deleted=False).first()+ if insight is None:+ return "Insight not found. Read it again and retry."+ if insight.query != expected_query:+ return "This insight changed while generating the update. Read it again and retry."+ access_control = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))+ if not access_control.check_access_level_for_resource(+ "insight", "editor"+ ) or not access_control.check_access_level_for_object(insight, "editor"):+ return "You no longer have permission to edit this insight."+ if (+ insight.team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL)+ and not access_control.is_organization_admin+ and is_publicly_shared(insight)+ ):+ blocked = blocked_access_for_user(user, insight.team, [query])+ if blocked:+ blocked_list = ", ".join(f"`{name}`" for name in blocked)+ return f"Can't save this query: you don't have access to {blocked_list}, and this insight is publicly shared."+ insight.query = query+ insight.saved = True+ insight.last_modified_by = user+ insight.save(update_fields=["query", "saved", "last_modified_by", "updated_at"])+ return Nonediff --git a/products/product_analytics/backend/facade/contracts.py b/products/product_analytics/backend/facade/contracts.pyindex 851f483521c4..e4049c0573c3 100644--- a/products/product_analytics/backend/facade/contracts.py+++ b/products/product_analytics/backend/facade/contracts.py@@ -42,3 +42,11 @@ class TrendsQueryRunResult:results: list[dict[str, Any]]last_refresh: datetime | None = None+++@dataclass(frozen=True)+class SavedInsightDefinition:+ id: int+ short_id: str+ name: str | None+ query: dict[str, Any]diff --git a/pyproject.toml b/pyproject.tomlindex 72f25f06ac1a..85fb8b4fad8d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -76,6 +76,7 @@ dependencies = ["jsonref==1.1.0","kafka-python==2.3.0","kombu==5.6.2",+ "jsonpatch~=1.33","langchain~=0.3.27","langchain-community~=0.3.31","langchain-core~=0.3.81",diff --git a/uv.lock b/uv.lockindex f01d3f6a30e5..09263de2f81b 100644--- a/uv.lock+++ b/uv.lock@@ -5694,6 +5694,7 @@ dependencies = [{ name = "hogql-parser-rs" },{ name = "humanize" },{ name = "infi-clickhouse-orm" },+ { name = "jsonpatch" },{ name = "jsonref" },{ name = "kafka-python" },{ name = "kombu" },@@ -5981,6 +5982,7 @@ requires-dist = [{ name = "hogql-parser-rs", specifier = "==1.3.109" },{ name = "humanize", specifier = "~=4.12.3" },{ name = "infi-clickhouse-orm", git = "https://github.com/PostHog/infi.clickhouse_orm?rev=4e3996becf66bf5c26580aff12a80425d9d56fe5" },+ { name = "jsonpatch", specifier = "~=1.33" },{ name = "jsonref", specifier = "==1.1.0" },{ name = "kafka-python", specifier = "==2.3.0" },{ name = "kombu", specifier = "==5.6.2" },