Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(notebooks): close markdown notebook functional gaps for launch (#68562)

Marius Andrae4b6b20ce4cb
diff --git a/ee/hogai/tools/create_notebook/helpers.py b/ee/hogai/tools/create_notebook/helpers.py
index d63e5765fee4..d3f183632bd6 100644
--- a/ee/hogai/tools/create_notebook/helpers.py
+++ b/ee/hogai/tools/create_notebook/helpers.py
@@ -4,11 +4,16 @@ from typing import Any
from posthog.models import Team, User
from posthog.rbac.user_access_control import UserAccessControl
+from posthog.sync import database_sync_to_async
from products.notebooks.backend.facade import (
api as notebooks,
collab,
)
+from products.notebooks.backend.facade.content import (
+ build_markdown_notebook_content,
+ convert_notebook_content_to_markdown,
+)
from products.notebooks.backend.facade.contracts import NotebookData
from products.posthog_ai.backend.models.assistant import AgentArtifact
@@ -17,6 +22,7 @@ from ee.hogai.artifacts.manager import ArtifactManager
from ee.hogai.artifacts.types import StoredBlock, StoredNotebookArtifactContent, VisualizationRefBlock
from ee.hogai.tools.create_notebook.parsing import parse_notebook_content_for_storage
from ee.hogai.tools.create_notebook.tiptap import blocks_to_tiptap_doc
+from ee.hogai.utils.feature_flags import has_markdown_notebooks_feature_flag
from ee.hogai.utils.types.base import AssistantMessageUnion
@@ -178,13 +184,23 @@ 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.
+ content: dict[str, Any] = tiptap_doc
+ text_content: str | None = None
+ if existing_notebook is None and await database_sync_to_async(has_markdown_notebooks_feature_flag)(team, user):
+ markdown = convert_notebook_content_to_markdown(tiptap_doc)
+ content = build_markdown_notebook_content(markdown)
+ text_content = markdown
+
notebook, created = await notebooks.aupsert_notebook(
team.id,
artifact.short_id,
created_by_id=user.id,
last_modified_by_id=user.id,
title=title,
- content=tiptap_doc,
+ content=content,
+ text_content=text_content,
)
if not created:
await collab.apublish_notebook_update(team.id, str(notebook.short_id), notebook.version)
diff --git a/ee/hogai/tools/create_notebook/test/test_helpers.py b/ee/hogai/tools/create_notebook/test/test_helpers.py
index 7944f77c5eac..e80a09413204 100644
--- a/ee/hogai/tools/create_notebook/test/test_helpers.py
+++ b/ee/hogai/tools/create_notebook/test/test_helpers.py
@@ -154,6 +154,60 @@ class TestSaveNotebookToDb(BaseTest):
ph_queries = _find_ph_query_nodes(notebook.content)
self.assertEqual(len(ph_queries), 0)
+ def test_save_notebook_creates_markdown_notebook_when_flag_enabled(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=[],
+ )
+
+ notebook = Notebook.objects.get(team=self.team, short_id=parent.short_id)
+ nodes = notebook.content["content"]
+ self.assertEqual(len(nodes), 1)
+ self.assertEqual(nodes[0]["type"], "ph-markdown-notebook")
+ markdown = nodes[0]["attrs"]["markdown"]
+ self.assertIn("Test Notebook", markdown)
+ self.assertIn("<Query", markdown)
+ self.assertIn("InsightVizNode", markdown)
+ self.assertEqual(notebook.text_content, markdown)
+
+ def test_save_notebook_keeps_tiptap_format_for_existing_notebook_when_flag_enabled(self):
+ parent = self._create_notebook_parent("ntfm")
+ notebook = Notebook.objects.create(
+ team=self.team,
+ short_id=parent.short_id,
+ title="Original title",
+ created_by=self.user,
+ last_modified_by=self.user,
+ 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"),
+ ):
+ async_to_sync(save_notebook_to_db)(
+ team=self.team,
+ user=self.user,
+ artifact=parent,
+ blocks=[],
+ title="Updated title",
+ state_messages=[],
+ markdown_content="# Updated",
+ )
+
+ notebook.refresh_from_db()
+ self.assertEqual(notebook.title, "Updated title")
+ self.assertNotEqual(notebook.content["content"][0]["type"], "ph-markdown-notebook")
+
def test_save_notebook_preserves_existing_markdown_v2_wrapper(self):
parent = self._create_notebook_parent("nv2m")
notebook = Notebook.objects.create(
diff --git a/ee/hogai/utils/feature_flags.py b/ee/hogai/utils/feature_flags.py
index 3087069460f3..3497d0923bd0 100644
--- a/ee/hogai/utils/feature_flags.py
+++ b/ee/hogai/utils/feature_flags.py
@@ -114,6 +114,16 @@ 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/src/lib/components/MarkdownNotebook/TODO.md b/frontend/src/lib/components/MarkdownNotebook/TODO.md
index 12b2930f2686..541b79352e17 100644
--- a/frontend/src/lib/components/MarkdownNotebook/TODO.md
+++ b/frontend/src/lib/components/MarkdownNotebook/TODO.md
@@ -4,8 +4,7 @@ The markdown notebook rewrite (markdown storage, custom component tags, conflict
## Rollout and migration
-- New notebooks still default to the legacy TipTap editor. Markdown notebooks only exist through the upgrade dialog (`notebookUpgradeDialog.tsx`), gated behind the `MARKDOWN_NOTEBOOKS` feature flag.
-- Decide and implement the default-on path: create new notebooks as markdown notebooks once the flag ramps.
+- 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.
- 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.
@@ -14,6 +13,7 @@ The markdown notebook rewrite (markdown storage, custom component tags, conflict
- Accessibility: the formatting toolbar, insert menu, and component insertion flow need keyboard navigation and screen-reader coverage (focus management, roving tabindex, ARIA roles beyond the current labels).
- Inline comments: selections inside code blocks can't be commented (code carries no inline marks).
+- Drag and drop: dropping a resource directly onto the editor canvas is not handled (the legacy editor's `DropAndPasteHandlerExtension` equivalent). The notebook panel dropzone and "add to notebook" flows work — they append to the end of the document via `notebookLogic` instead of inserting at the drop position.
## Open questions
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts
index 7a8a2a46b146..90bf2e9aabf2 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts
@@ -1,14 +1,20 @@
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'
import { AccessControlLevel } from '~/types'
import { NotebookNodeType, NotebookType } from '../types'
-import { buildMarkdownNotebookContent } from './markdownNotebookV2'
-import { notebookLogic } from './notebookLogic'
+import {
+ buildMarkdownNotebookContent,
+ getMarkdownNotebookMarkdown,
+ isMarkdownNotebookContent,
+} from './markdownNotebookV2'
+import { NotebookLogicMode, notebookLogic } from './notebookLogic'
import { NOTEBOOK_AI_PRESENCE_CLIENT_ID, NOTEBOOK_AI_PRESENCE_NAME } from './notebookPresence'
jest.mock('./migrations/migrate', () => {
@@ -47,7 +53,7 @@ describe('notebookLogic markdown editor state', () => {
useMocks({
get: {
[`/api/projects/@current/notebooks/${SHORT_ID}/`]: () => [200, cachedNotebook],
- [`/api/projects/:project_id/notebooks/${SHORT_ID}/kernel/status/`]: () => [200, { backend: null }],
+ [`/api/projects/:project_id/notebooks/:short_id/kernel/status/`]: () => [200, { backend: null }],
},
})
// localContent is a persisted reducer — clear it so tests don't leak into each other
@@ -248,6 +254,79 @@ Thinking...`)
expect(logic.values.notebook?.content).toEqual(latestNotebook.content)
})
+ it.each([
+ // NotebookSelectButton and the scene menus pass an array of resources
+ ['an array of resources', [{ type: NotebookNodeType.Recording, attrs: { id: 'rec-1' } }]],
+ // The notebook panel dropzone passes a single dropped resource
+ ['a single dropped resource', { type: NotebookNodeType.Recording, attrs: { id: 'rec-1' } }],
+ ])('insertAfterLastNode appends %s to the markdown source', async (_name, content) => {
+ await expectLogic(logic, () => {
+ logic.actions.insertAfterLastNode(content)
+ }).toDispatchActions(['setLocalContent'])
+
+ const markdown = getMarkdownNotebookMarkdown(logic.values.localContent)
+ expect(markdown.startsWith(BASE_MARKDOWN)).toBe(true)
+ expect(markdown).toContain('<Recording')
+ expect(markdown).toContain('id="rec-1"')
+ })
+
+ it('pasteAfterLastNode appends dropped text to the markdown source', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.pasteAfterLastNode('Dropped text')
+ }).toDispatchActions(['setLocalContent'])
+
+ expect(getMarkdownNotebookMarkdown(logic.values.localContent)).toEqual(`${BASE_MARKDOWN}\n\nDropped text`)
+ })
+
+ 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) => {
+ 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 () => {
+ logic.unmount()
+ const templateNotebook = {
+ ...cachedNotebook,
+ short_id: 'template-test',
+ is_template: true,
+ content: {
+ type: 'doc',
+ content: [
+ { type: 'heading', attrs: { level: 1 }, content: [{ type: 'text', text: 'Template title' }] },
+ ],
+ },
+ } as unknown as NotebookType
+ logic = 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'])
+
+ const createSpy = jest
+ .spyOn(api.notebooks, 'create')
+ .mockResolvedValue({ ...templateNotebook, short_id: 'duplicated' } as any)
+
+ logic.actions.duplicateNotebook()
+ await expectLogic(logic).toDispatchActions(['duplicateNotebookSuccess'])
+
+ expect(createSpy).toHaveBeenCalledTimes(1)
+ const createdContent = createSpy.mock.calls[0][0]?.content
+ expect(isMarkdownNotebookContent(createdContent)).toBe(true)
+ expect(getMarkdownNotebookMarkdown(createdContent)).toEqual('# Template title')
+ })
+
it('only surfaces the left column for markdown notebooks when history is open', () => {
logic.unmount()
logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook' })
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
index b83208a08230..39c766eafee3 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
@@ -146,13 +146,40 @@ function convertNotebookContentForRender(
content: JSONContent | null | undefined,
markdownNotebooksEnabled: boolean
): JSONContent | null | undefined {
- if (!markdownNotebooksEnabled || !content || isMarkdownNotebookContent(content)) {
+ if (!markdownNotebooksEnabled || 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.
+ if (!content) {
+ return buildMarkdownNotebookContent('')
+ }
+
return buildMarkdownNotebookContent(convertNotebookContentToMarkdown(content))
}
+/**
+ * Markdown notebooks never mount the TipTap editor, so the generic insertion actions append
+ * serialized markdown blocks to the markdown source instead. Returns null when the notebook
+ * isn't a markdown notebook, so callers fall through to the TipTap editor path.
+ */
+function appendContentToMarkdownNotebook(
+ notebookContent: JSONContent,
+ insertedContent: JSONContent | JSONContent[] | string
+): JSONContent | null {
+ if (!isMarkdownNotebookContent(notebookContent)) {
+ return null
+ }
+ // The converter serializes the children of a doc, so a single leaf node (e.g. a dropped
+ // resource) must be wrapped in an array to be serialized itself.
+ const normalizedContent =
+ typeof insertedContent === 'string' || Array.isArray(insertedContent) || insertedContent.type === 'doc'
+ ? insertedContent
+ : [insertedContent]
+ return appendMarkdownNotebookBlock(notebookContent, convertNotebookContentToMarkdown(normalizedContent))
+}
+
export type NotebookLogicMode = 'notebook' | 'canvas'
/** A markdown notebook update from the collab SSE stream or a 409 conflict body. */
@@ -1574,8 +1601,16 @@ export const notebookLogic = kea<notebookLogicType>([
},
insertAfterLastNode: async ({ content }) => {
await runWhenEditorIsReady(
- () => !!values.editor && (values.isLocalOnly || !!values.notebook),
+ () =>
+ (values.isLocalOnly || !!values.notebook) &&
+ (!!values.editor || isMarkdownNotebookContent(values.content)),
() => {
+ const markdownContent = appendContentToMarkdownNotebook(values.content, content)
+ if (markdownContent) {
+ actions.setLocalContent(markdownContent)
+ return
+ }
+
let insertionPosition = 0
let nextNode = values.editor?.nextNode(insertionPosition)
while (nextNode) {
@@ -1589,8 +1624,16 @@ export const notebookLogic = kea<notebookLogicType>([
},
pasteAfterLastNode: async ({ content }) => {
await runWhenEditorIsReady(
- () => !!values.editor && (values.isLocalOnly || !!values.notebook),
+ () =>
+ (values.isLocalOnly || !!values.notebook) &&
+ (!!values.editor || isMarkdownNotebookContent(values.content)),
() => {
+ const markdownContent = appendContentToMarkdownNotebook(values.content, content)
+ if (markdownContent) {
+ actions.setLocalContent(markdownContent)
+ return
+ }
+
const endPosition = values.editor?.getEndPosition() || 0
values.editor?.pasteContent(endPosition, content)
}
@@ -1598,8 +1641,17 @@ export const notebookLogic = kea<notebookLogicType>([
},
insertAfterLastNodeOfType: async ({ content, nodeType, knownStartingPosition }) => {
await runWhenEditorIsReady(
- () => !!values.editor && (values.isLocalOnly || !!values.notebook),
+ () =>
+ (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)) {
@@ -1940,7 +1992,7 @@ export const notebookLogic = kea<notebookLogicType>([
exportJSON: () => {
const file = new File(
- [JSON.stringify(values.editor?.getJSON(), null, 2)],
+ [JSON.stringify(values.editor?.getJSON() ?? values.content, null, 2)],
`${slugify(values.title ?? 'untitled')}.ph-notebook.json`,
{ type: 'application/json' }
)
diff --git a/products/notebooks/backend/facade/api.py b/products/notebooks/backend/facade/api.py
index 742cec39d5e0..2a75355a6623 100644
--- a/products/notebooks/backend/facade/api.py
+++ b/products/notebooks/backend/facade/api.py
@@ -128,6 +128,7 @@ async def aupsert_notebook(
last_modified_by_id: int | None,
title: str,
content: dict[str, Any],
+ text_content: str | None = None,
) -> tuple[contracts.NotebookData, bool]:
notebook, created = await logic.aupsert_notebook(
team_id,
@@ -136,6 +137,7 @@ async def aupsert_notebook(
last_modified_by_id=last_modified_by_id,
title=title,
content=content,
+ text_content=text_content,
)
return _to_notebook_data(notebook), created
diff --git a/products/notebooks/backend/facade/content.py b/products/notebooks/backend/facade/content.py
index c68b9b2afe2b..07bfd36a910f 100644
--- a/products/notebooks/backend/facade/content.py
+++ b/products/notebooks/backend/facade/content.py
@@ -6,6 +6,11 @@ so cross-product callers that build or sanitize notebook content import them fro
here rather than reaching into ``backend.util``.
"""
+from ..markdown_conversion import (
+ build_markdown_notebook_content as build_markdown_notebook_content,
+ convert_notebook_content_to_markdown as convert_notebook_content_to_markdown,
+ is_markdown_notebook_content as is_markdown_notebook_content,
+)
from ..util import (
QUERY_NODE_TYPE as QUERY_NODE_TYPE,
SAVED_INSIGHT_NODE_KIND as SAVED_INSIGHT_NODE_KIND,
diff --git a/products/notebooks/backend/logic.py b/products/notebooks/backend/logic.py
index cdaa16a2050c..a44db0e86773 100644
--- a/products/notebooks/backend/logic.py
+++ b/products/notebooks/backend/logic.py
@@ -87,6 +87,7 @@ async def aupsert_notebook(
last_modified_by_id: int | None,
title: str,
content: dict[str, Any],
+ text_content: str | None = None,
) -> tuple[Notebook, bool]:
notebook, created = await Notebook.objects.aget_or_create(
team_id=team_id,
@@ -96,6 +97,7 @@ async def aupsert_notebook(
"last_modified_by_id": last_modified_by_id,
"title": title,
"content": content,
+ "text_content": text_content,
},
)
if not created:
@@ -103,7 +105,11 @@ async def aupsert_notebook(
notebook.title = title
notebook.version += 1
notebook.last_modified_by_id = last_modified_by_id
- await notebook.asave(update_fields=["content", "title", "version", "last_modified_by", "last_modified_at"])
+ update_fields = ["content", "title", "version", "last_modified_by", "last_modified_at"]
+ if text_content is not None:
+ notebook.text_content = text_content
+ update_fields.append("text_content")
+ await notebook.asave(update_fields=update_fields)
return notebook, created