Skip to content

: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.

fix: resolve state-only viz when saving AI notebooks (#60865)

Alex Liderd7c138060411
diff --git a/ee/hogai/tools/create_notebook/helpers.py b/ee/hogai/tools/create_notebook/helpers.py
index 79ea6c4ebece..bc182ae41498 100644
--- a/ee/hogai/tools/create_notebook/helpers.py
+++ b/ee/hogai/tools/create_notebook/helpers.py
@@ -6,10 +6,12 @@ from posthog.models import Team, User
from products.notebooks.backend.models import Notebook
from products.posthog_ai.backend.models.assistant import AgentArtifact
+from ee.hogai.artifacts.handlers.visualization import VisualizationHandler
from ee.hogai.artifacts.manager import ArtifactManager
from ee.hogai.artifacts.types import StoredBlock, StoredNotebookArtifactContent, VisualizationRefBlock
from ee.hogai.tools.create_notebook.parsing import parse_notebook_content_for_storage
from ee.hogai.tools.create_notebook.tiptap import blocks_to_tiptap_doc
+from ee.hogai.utils.types.base import AssistantMessageUnion
class ArtifactStatus(Enum):
@@ -57,6 +59,7 @@ async def save_notebook_to_db(
artifact: AgentArtifact,
blocks: Sequence[StoredBlock],
title: str,
+ state_messages: Sequence[AssistantMessageUnion],
) -> Notebook:
"""
Save or update a real Notebook record with the same short_id as the artifact.
@@ -64,19 +67,17 @@ async def save_notebook_to_db(
If a Notebook with the artifact's short_id already exists, update its content.
Otherwise, create a new Notebook.
"""
- # Pre-fetch all referenced visualization artifacts to avoid sync ORM calls in the closure
+ # Resolve viz refs through the unified handler (state → AgentArtifact → Insight),
+ # matching the chat preview. A direct AgentArtifact query misses state-only charts.
ref_ids = [block.artifact_id for block in blocks if isinstance(block, VisualizationRefBlock)]
viz_lookup: dict[str, dict] = {}
if ref_ids:
- viz_artifacts = AgentArtifact.objects.filter(short_id__in=ref_ids, team=team)
- async for viz_artifact in viz_artifacts:
- data = viz_artifact.data
- if data.get("content_type") != "visualization":
- continue
- query = data.get("query")
- name = data.get("name")
- if not query:
+ viz_handler = VisualizationHandler()
+ results = await viz_handler.alist(team, ref_ids, state_messages)
+ for ref_id, result in zip(ref_ids, results):
+ if result is None or result.content.query is None:
continue
+ query = result.content.query.model_dump(mode="json", exclude_none=True)
kind = query.get("kind", "")
if kind == "DataVisualizationNode":
# Already a top-level SQL chart node, do not double-wrap.
@@ -85,7 +86,7 @@ async def save_notebook_to_db(
notebook_query = {"kind": "DataVisualizationNode", "source": query}
else:
notebook_query = {"kind": "InsightVizNode", "source": query}
- viz_lookup[viz_artifact.short_id] = {"query": notebook_query, "name": name}
+ viz_lookup[ref_id] = {"query": notebook_query, "name": result.content.name}
def resolve_visualization(artifact_id: str) -> dict | None:
return viz_lookup.get(artifact_id)
diff --git a/ee/hogai/tools/create_notebook/test/test_helpers.py b/ee/hogai/tools/create_notebook/test/test_helpers.py
index 8cb960cbca33..ba2a511a9437 100644
--- a/ee/hogai/tools/create_notebook/test/test_helpers.py
+++ b/ee/hogai/tools/create_notebook/test/test_helpers.py
@@ -3,6 +3,8 @@ from posthog.test.base import BaseTest
from asgiref.sync import async_to_sync
from parameterized import parameterized
+from posthog.schema import TrendsQuery, VisualizationMessage
+
from products.notebooks.backend.models import Notebook
from products.posthog_ai.backend.models.assistant import AgentArtifact, Conversation
@@ -49,7 +51,12 @@ class TestSaveNotebookToDb(BaseTest):
data={"content_type": "notebook", "blocks": [], "title": "Notebook"},
)
- def _save_and_get_notebook(self, viz_short_id: str, parent_short_id: str) -> Notebook:
+ def _save_and_get_notebook(
+ self,
+ viz_short_id: str,
+ parent_short_id: str,
+ state_messages: list | None = None,
+ ) -> Notebook:
parent = self._create_notebook_parent(parent_short_id)
blocks: list[StoredBlock] = [VisualizationRefBlock(artifact_id=viz_short_id, title="Chart")]
async_to_sync(save_notebook_to_db)(
@@ -58,6 +65,7 @@ class TestSaveNotebookToDb(BaseTest):
artifact=parent,
blocks=blocks,
title="Test Notebook",
+ state_messages=state_messages or [],
)
return Notebook.objects.get(team=self.team, short_id=parent.short_id)
@@ -83,14 +91,6 @@ class TestSaveNotebookToDb(BaseTest):
"DataVisualizationNode",
"HogQLQuery",
),
- (
- "assistant_hogql_query_wrapped_in_dvn",
- "vahq",
- "nahq",
- {"kind": "AssistantHogQLQuery", "query": "SELECT 1"},
- "DataVisualizationNode",
- "AssistantHogQLQuery",
- ),
(
"insight_query_wrapped_in_insight_viz_node",
"vtrd",
@@ -119,3 +119,35 @@ class TestSaveNotebookToDb(BaseTest):
stored_query = ph_queries[0]["attrs"]["query"]
self.assertEqual(stored_query["kind"], expected_kind)
self.assertEqual(stored_query["source"]["kind"], expected_source_kind)
+
+ def test_save_notebook_resolves_state_only_visualization(self):
+ # Reproduces the "[Visualization not found: <id>]" bug: viz exists only in
+ # conversation state (as a VisualizationMessage), not in AgentArtifact.
+ viz_short_id = "vstt"
+ viz_message = VisualizationMessage(
+ id=viz_short_id,
+ answer=TrendsQuery(series=[]),
+ )
+
+ notebook = self._save_and_get_notebook(
+ viz_short_id,
+ "nstt",
+ state_messages=[viz_message],
+ )
+
+ ph_queries = _find_ph_query_nodes(notebook.content)
+ self.assertEqual(len(ph_queries), 1, "state-only viz should resolve to a ph-query node")
+ stored_query = ph_queries[0]["attrs"]["query"]
+ self.assertEqual(stored_query["kind"], "InsightVizNode")
+ self.assertEqual(stored_query["source"]["kind"], "TrendsQuery")
+
+ def test_save_notebook_emits_placeholder_when_artifact_missing(self):
+ # Sanity: when the ref can't be resolved from any source, we still get the
+ # "[Visualization not found]" placeholder paragraph instead of a ph-query.
+ notebook = self._save_and_get_notebook(
+ viz_short_id="vmis",
+ parent_short_id="nmis",
+ )
+
+ ph_queries = _find_ph_query_nodes(notebook.content)
+ self.assertEqual(len(ph_queries), 0)
diff --git a/ee/hogai/tools/create_notebook/tool.py b/ee/hogai/tools/create_notebook/tool.py
index 116b5ba43980..267e6c21f36b 100644
--- a/ee/hogai/tools/create_notebook/tool.py
+++ b/ee/hogai/tools/create_notebook/tool.py
@@ -139,6 +139,7 @@ class CreateNotebookTool(MaxTool):
artifact=artifact,
blocks=blocks,
title=title,
+ state_messages=self._state.messages,
)
# Build response message