: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(customer-analytics): store account notes as markdown notebooks (#98350)
Sinan Kucukkoseler61d6abd5ce76
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 018758d33ca0..a6d86de7f463 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -1084,9 +1084,8 @@ class CreateAccountNotebookInput:"""Validated body for creating an account notebook.``content`` is the ProseMirror document the caller supplied (or ``None``);- ``synthesized_content`` is the markdown-derived document the view built when the- caller passed only ``text_content`` — the view owns that normalization so the- ``ee.hogai`` tiptap helper stays off the facade import path.+ ``synthesized_content`` is the markdown notebook document the view built when the+ caller passed only ``text_content``."""title: str | Nonediff --git a/products/customer_analytics/backend/max_tools.py b/products/customer_analytics/backend/max_tools.pyindex 873a66cc9d9a..ea4883c6ca25 100644--- a/products/customer_analytics/backend/max_tools.py+++ b/products/customer_analytics/backend/max_tools.py@@ -21,6 +21,7 @@ from products.customer_analytics.backend.facade.api import ()from products.customer_analytics.backend.logic import relationships as relationships_logicfrom products.customer_analytics.backend.models import Account, AccountRelationshipDefinition+from products.notebooks.backend.facade.content import build_markdown_notebook_content, is_markdown_notebook_contentfrom products.notebooks.backend.models import Notebook, ResourceNotebookfrom ee.hogai.tool import MaxTool@@ -369,6 +370,20 @@ def _tiptap_doc(markdown: str) -> dict[str, Any]:return {"type": "doc", "content": markdown_to_tiptap_nodes(markdown) or [{"type": "paragraph"}]}+def _updated_note_content(stored_content: Any, markdown: str) -> dict[str, Any]:+ """A note written before the markdown editor keeps its rich-text document. The editor picks+ its mode from the stored document, so a format change moves an open session to the other+ editor and discards the unsaved work in it. An empty ``doc`` opens the rich-text editor too,+ so it counts as one; a null or shapeless document has no format to keep."""+ is_rich_text_document = (+ isinstance(stored_content, dict)+ and stored_content.get("type") == "doc"+ and isinstance(stored_content.get("content"), list)+ and not is_markdown_notebook_content(stored_content)+ )+ return _tiptap_doc(markdown) if is_rich_text_document else build_markdown_notebook_content(markdown)++class CreateAccountNotebookAction(BaseModel):action: Literal["create"] = "create"account_id: str = Field(description="UUID of the account to attach the note to.")@@ -485,7 +500,7 @@ class UpsertAccountNotebookTool(MaxTool):visibility=Notebook.Visibility.INTERNAL,title=action.title[:256],text_content=action.content,- content=_tiptap_doc(action.content),+ content=build_markdown_notebook_content(action.content),)ResourceNotebook.objects.create(notebook=notebook, account=account)return notebook@@ -501,7 +516,7 @@ class UpsertAccountNotebookTool(MaxTool):locked.title = action.title[:256]update_fields.append("title")if action.content is not None:- locked.content = _tiptap_doc(action.content)+ locked.content = _updated_note_content(locked.content, action.content)locked.text_content = action.contentlocked.version = locked.version + 1update_fields += ["content", "text_content", "version"]diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex c676c5741bd3..fd40b1176963 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -116,8 +116,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (UserCustomerAnalyticsConfigSerializer,UserCustomerAnalyticsConfigUpdateSerializer,)--from ee.hogai.tools.create_notebook.tiptap import markdown_to_tiptap_nodes+from products.notebooks.backend.facade.content import build_markdown_notebook_content# Object-level access levels for the resource ViewSets, matching what# ``AccessControlPermission._get_required_access_level`` derives for these scope objects:@@ -2151,18 +2150,18 @@ class AccountNotebookViewSet(def _synthesize_notebook_content(text_content, existing_content):"""When the caller passed Markdown ``text_content`` but no usable ProseMirror ``content``- tree, build one from the Markdown. Agents calling the MCP notebook-create tool typically- send ``text_content`` only (hand-writing ProseMirror is awkward), and NotebookScene only- renders ``content`` — so without this the result is a blank page. The tiptap helper lives- in ``ee.hogai`` and stays in the view so it never reaches the facade import path. Returns- ``None`` when the caller already supplied usable content (or no markdown)."""+ tree, build a markdown notebook document from the Markdown. Agents calling the MCP+ notebook-create tool typically send ``text_content`` only, because hand-writing ProseMirror+ is awkward, and NotebookScene renders ``content`` only, so without this the result is a+ blank page. Returns ``None`` when the caller already supplied usable content (or no+ markdown)."""has_usable_content = (isinstance(existing_content, dict)and existing_content.get("type") == "doc"and isinstance(existing_content.get("content"), list))if text_content and not has_usable_content:- return {"type": "doc", "content": markdown_to_tiptap_nodes(text_content) or [{"type": "paragraph"}]}+ return build_markdown_notebook_content(text_content)return Nonediff --git a/products/customer_analytics/backend/test/test_upsert_account_notebook.py b/products/customer_analytics/backend/test/test_upsert_account_notebook.pyindex 2d25faa969db..08285479b7d8 100644--- a/products/customer_analytics/backend/test/test_upsert_account_notebook.py+++ b/products/customer_analytics/backend/test/test_upsert_account_notebook.py@@ -5,6 +5,7 @@ from posthog.test.base import BaseTestfrom asgiref.sync import sync_to_asyncfrom langchain_core.runnables import RunnableConfig+from parameterized import parameterizedfrom posthog.models import Team@@ -14,6 +15,7 @@ from products.customer_analytics.backend.max_tools import (UpsertAccountNotebookTool,)from products.customer_analytics.backend.models import Account+from products.notebooks.backend.facade.content import build_markdown_notebook_content, is_markdown_notebook_contentfrom products.notebooks.backend.models import Notebook, ResourceNotebook@@ -52,8 +54,7 @@ class TestUpsertAccountNotebookTool(BaseTest):assert notebook.visibility == Notebook.Visibility.INTERNALassert notebook.created_by_id == self.user.idassert notebook.title == "Q3 call recap"- assert notebook.content["type"] == "doc"- assert notebook.content["content"]+ assert notebook.content == build_markdown_notebook_content("# Summary\n\nThey want SSO by Q3.")assert notebook.text_content == "# Summary\n\nThey want SSO by Q3."assert notebook.version == 0@@ -62,7 +63,7 @@ class TestUpsertAccountNotebookTool(BaseTest):@pytest.mark.django_db@pytest.mark.asyncio- async def test_create_blank_markdown_falls_back_to_empty_paragraph(self):+ async def test_create_blank_markdown_stores_an_empty_markdown_notebook(self):account = await sync_to_async(Account.objects.unscoped().create)(team=self.team, name="Beta Inc")_, artifact = await self._tool()._arun_impl(@@ -70,7 +71,7 @@ class TestUpsertAccountNotebookTool(BaseTest):)notebook = await sync_to_async(Notebook.objects.get)(short_id=artifact["notebook_short_id"])- assert notebook.content == {"type": "doc", "content": [{"type": "paragraph"}]}+ assert notebook.content == build_markdown_notebook_content("")@pytest.mark.django_db@pytest.mark.asyncio@@ -113,9 +114,43 @@ class TestUpsertAccountNotebookTool(BaseTest):notebook = await sync_to_async(Notebook.objects.get)(short_id=short_id)assert notebook.title == "Q3 recap (updated)"+ assert notebook.content == build_markdown_notebook_content(+ "# Summary\n\nSSO by Q3.\n\n## Pricing\n\nAsked about SSO pricing."+ )assert notebook.text_content is not None and "Pricing" in notebook.text_contentassert notebook.version == 1+ @parameterized.expand(+ [+ ("holding a node", [{"type": "paragraph"}]),+ ("empty", []),+ ]+ )+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_update_keeps_a_rich_text_note_in_rich_text(self, _name: str, stored_nodes: list) -> None:+ def _make_rich_text_note() -> str:+ account = Account.objects.unscoped().create(team=self.team, name="Legacy Corp")+ notebook = Notebook.objects.create(+ team=self.team,+ title="Legacy note",+ content={"type": "doc", "content": stored_nodes},+ visibility=Notebook.Visibility.INTERNAL,+ )+ ResourceNotebook.objects.create(notebook=notebook, account=account)+ return notebook.short_id++ short_id = await sync_to_async(_make_rich_text_note)()++ _, artifact = await self._tool()._arun_impl(+ action=UpdateAccountNotebookAction(notebook_short_id=short_id, content="# Later\n\nStill rich text.")+ )++ assert artifact["notebook_short_id"] == short_id+ notebook = await sync_to_async(Notebook.objects.get)(short_id=short_id)+ assert not is_markdown_notebook_content(notebook.content)+ assert notebook.content["content"][0]["type"] == "heading"+@pytest.mark.django_db@pytest.mark.asyncioasync def test_update_with_no_fields_returns_error(self):diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex 86df445dbdfa..b110c2903b58 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -51,6 +51,7 @@ from products.customer_analytics.backend.models import (TargetType,)from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition+from products.notebooks.backend.facade.content import build_markdown_notebook_contentfrom products.notebooks.backend.models import Notebook, ResourceNotebookfrom products.product_analytics.backend.facade.models import Insightfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema@@ -1296,12 +1297,7 @@ class TestAccountNotebookViewSet(APIBaseTest):# nosemgrep: idor-lookup-without-team (test assertion)notebook = Notebook.objects.get(short_id=response.json()["short_id"])self.assertEqual(notebook.text_content, "# Heading\n\nSome **bold** text.")- self.assertIsInstance(notebook.content, dict)- self.assertEqual(notebook.content["type"], "doc")- first_node = notebook.content["content"][0]- self.assertEqual(first_node["type"], "heading")- self.assertEqual(first_node["attrs"]["level"], 1)- self.assertEqual(first_node["content"][0]["text"], "Heading")+ self.assertEqual(notebook.content, build_markdown_notebook_content("# Heading\n\nSome **bold** text."))def test_create_preserves_caller_supplied_content(self):explicit_content = {@@ -1349,10 +1345,7 @@ class TestAccountNotebookViewSet(APIBaseTest):self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())# nosemgrep: idor-lookup-without-team (test assertion)notebook = Notebook.objects.get(short_id=response.json()["short_id"])- self.assertEqual(notebook.content["type"], "doc")- first_node = notebook.content["content"][0]- self.assertEqual(first_node["type"], "paragraph")- self.assertEqual(first_node["content"][0]["text"], "Just a sentence.")+ self.assertEqual(notebook.content, build_markdown_notebook_content("Just a sentence."))def test_create_with_empty_valid_prosemirror_doc_respects_caller(self):empty_doc = {"type": "doc", "content": []}