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): render legacy notebooks as markdown (#67414)

Marius Andraa9d5056704c8
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookHistory.test.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookHistory.test.tsx
index 4940f867ed03..3e4b3fc27013 100644
--- a/frontend/src/scenes/notebooks/Notebook/NotebookHistory.test.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookHistory.test.tsx
@@ -14,7 +14,7 @@ import { AccessControlLevel, ActivityScope } from '~/types'
import { NotebookEditor, NotebookType } from '../types'
import { buildMarkdownNotebookContent } from './markdownNotebookV2'
import { notebookCollabLogic } from './notebookCollabLogic'
-import { SYNC_DELAY, notebookLogic } from './notebookLogic'
+import { MARKDOWN_SYNC_DELAY, SYNC_DELAY, notebookLogic } from './notebookLogic'
// Skip the API-driven query upgrade step inside migrate so the loader doesn't try
// to upgrade insight nodes. Our fixture content has no insight nodes anyway, but
@@ -94,6 +94,7 @@ describe('Notebook history revert flow', () => {
}) as unknown as NotebookEditor
beforeEach(() => {
+ localStorage.clear()
historyLogic = null
editorContent = null
useMocks({
@@ -149,6 +150,27 @@ describe('Notebook history revert flow', () => {
expect(apiUpdateSpy).not.toHaveBeenCalled()
})
+ it('does not persist editor updates emitted 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()
+
+ 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()
+ )
+ })
+
it('saves through the pending content debounce after autosave resumes', async () => {
logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook', cachedNotebook })
logic.mount()
@@ -245,6 +267,100 @@ converted`)
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,
+ }
+ )
+
+ logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook' })
+ logic.mount()
+ logic.actions.loadNotebook()
+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()
+
+ expect(logic.values.notebook?.content).toEqual(SAMPLE_DOC)
+ 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 () => {
+ const historicalMarkdownContent = buildMarkdownNotebookContent('historical')
+ apiMarkdownSaveSpy.mockResolvedValueOnce({
+ ...cachedNotebook,
+ version: 2,
+ 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()
+
+ const contentToRestore = logic.values.content
+ logic.actions.clearPreviewContent()
+ logic.actions.setLocalContent(contentToRestore, true)
+ logic.actions.setShowHistory(false)
+
+ await expectLogic(logic)
+ .delay(MARKDOWN_SYNC_DELAY + 100)
+ .toFinishAllListeners()
+
+ expect(editorSetContent).toHaveBeenCalledWith(historicalMarkdownContent)
+ expect(apiMarkdownSaveSpy).toHaveBeenCalledWith(
+ SHORT_ID,
+ expect.objectContaining({
+ content: historicalMarkdownContent,
+ text_content: 'historical',
+ version: 1,
+ })
+ )
+ expect(apiUpdateSpy).not.toHaveBeenCalled()
+ })
+
+ it('clears stale legacy local content when loading a markdown v2 notebook', async () => {
+ const markdownNotebook = {
+ ...cachedNotebook,
+ content: buildMarkdownNotebookContent('# Markdown v2'),
+ text_content: '# Markdown v2',
+ }
+ jest.spyOn(api.notebooks, 'get').mockResolvedValueOnce(markdownNotebook as NotebookType)
+
+ logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook' })
+ logic.mount()
+ logic.actions.setLocalContent(HISTORICAL_DOC)
+ expect(logic.values.localContent).toEqual(HISTORICAL_DOC)
+
+ logic.actions.loadNotebook()
+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess', 'clearLocalContent']).toFinishAllListeners()
+
+ expect(logic.values.notebook?.content).toEqual(markdownNotebook.content)
+ expect(logic.values.localContent).toBeNull()
+
+ await expectLogic(logic)
+ .delay(SYNC_DELAY + 100)
+ .toFinishAllListeners()
+
+ expect(apiUpdateSpy).not.toHaveBeenCalled()
+ })
+
it('refreshes markdown v2 notebooks from the update stream', async () => {
const baseContent = buildMarkdownNotebookContent('# Markdown v2')
const updatedContent = buildMarkdownNotebookContent('# Markdown v2\n\nStreamed update')
@@ -446,6 +562,8 @@ Base paragraph with local edit`
if (collab) {
notebookCollabLogic({ shortId: SHORT_ID }).actions.bindEditor({
state: { selection: { head: 0 } },
+ on: jest.fn(),
+ off: jest.fn(),
} as any)
}
logic.actions.loadNotebook()
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookHistory.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookHistory.tsx
index d891a03fb0ac..aa8f1da053ad 100644
--- a/frontend/src/scenes/notebooks/Notebook/NotebookHistory.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookHistory.tsx
@@ -147,7 +147,7 @@ export function NotebookHistory(): JSX.Element {
}
export function NotebookHistoryWarning(): JSX.Element | null {
- const { previewContent } = useValues(notebookLogic)
+ const { previewContent, content } = useValues(notebookLogic)
const { setLocalContent, clearPreviewContent, duplicateNotebook, setShowHistory } = useActions(notebookLogic)
if (!previewContent) {
@@ -161,7 +161,6 @@ export function NotebookHistoryWarning(): JSX.Element | null {
// 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.
- const content = previewContent
clearPreviewContent()
setLocalContent(content, true)
setShowHistory(false)
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
index 170fabc05e23..b83208a08230 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
@@ -95,6 +95,7 @@ import { NotebookArtifactApplyMode } from './markdownNotebookRuntime'
import {
appendMarkdownNotebookBlock,
buildMarkdownNotebookContent,
+ convertNotebookContentToMarkdown,
getMarkdownNotebookMarkdown,
getMarkdownNotebookNodeId,
getMarkdownNotebookTextContent,
@@ -141,6 +142,17 @@ function keepNewestNotebookResponse(current: NotebookType | null, incoming: Note
return incoming.version < current.version ? current : incoming
}
+function convertNotebookContentForRender(
+ content: JSONContent | null | undefined,
+ markdownNotebooksEnabled: boolean
+): JSONContent | null | undefined {
+ if (!markdownNotebooksEnabled || !content || isMarkdownNotebookContent(content)) {
+ return content
+ }
+
+ return buildMarkdownNotebookContent(convertNotebookContentToMarkdown(content))
+}
+
export type NotebookLogicMode = 'notebook' | 'canvas'
/** A markdown notebook update from the collab SSE stream or a 409 conflict body. */
@@ -977,30 +989,28 @@ export const notebookLogic = kea<notebookLogicType>([
},
],
collabEnabled: [
- (s) => [s.featureFlags, s.isLocalOnly, s.localContent, s.notebook],
- (
- featureFlags: Record<string, string | boolean>,
- isLocalOnly: boolean,
- localContent: JSONContent | null,
- notebook: NotebookType | null
- ): boolean =>
+ (s) => [s.featureFlags, s.isLocalOnly, s.content],
+ (featureFlags: Record<string, string | boolean>, isLocalOnly: boolean, content: JSONContent): boolean =>
!!featureFlags[FEATURE_FLAGS.NOTEBOOKS_COLLABORATION] &&
!isLocalOnly &&
- !isMarkdownNotebookContent(localContent || notebook?.content),
+ !isMarkdownNotebookContent(content),
],
markdownRealtimeEnabled: [
- (s) => [(_, props) => props, s.mode, s.isLocalOnly, s.notebook],
+ (s) => [(_, props) => props, s.mode, s.isLocalOnly, s.notebook, s.content, s.featureFlags],
(
props: NotebookLogicProps,
mode: NotebookLogicMode,
isLocalOnly: boolean,
- notebook: NotebookType | null
+ notebook: NotebookType | null,
+ content: JSONContent,
+ featureFlags: Record<string, string | boolean>
): boolean =>
mode === 'notebook' &&
!props.cachedNotebook &&
!isLocalOnly &&
!!notebook &&
- isMarkdownNotebookContent(notebook.content),
+ (isMarkdownNotebookContent(notebook.content) ||
+ (!!featureFlags[FEATURE_FLAGS.MARKDOWN_NOTEBOOKS] && isMarkdownNotebookContent(content))),
],
notebookMissing: [
(s) => [s.notebook, s.notebookLoading, s.mode],
@@ -1059,10 +1069,15 @@ export const notebookLogic = kea<notebookLogicType>([
},
],
content: [
- (s) => [s.notebook, s.localContent, s.previewContent],
- (notebook, localContent, previewContent): JSONContent => {
- // We use the local content is set otherwise the notebook content
- return previewContent || localContent || notebook?.content || []
+ (s) => [s.notebook, s.localContent, s.previewContent, s.featureFlags],
+ (
+ notebook: NotebookType | null,
+ localContent: JSONContent | null,
+ previewContent: JSONContent | null,
+ featureFlags: Record<string, string | boolean>
+ ): JSONContent => {
+ const content = previewContent || localContent || notebook?.content
+ return convertNotebookContentForRender(content, !!featureFlags[FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]) || []
},
],
markdownEditorMarkdown: [(s) => [s.content], (content): string => getMarkdownNotebookMarkdown(content)],
@@ -1849,6 +1864,9 @@ export const notebookLogic = kea<notebookLogicType>([
if (!values.editor) {
return
}
+ if (values.previewContent) {
+ return
+ }
const jsonContent = values.editor.getJSON()
actions.setLocalContent(jsonContent)
@@ -1903,7 +1921,15 @@ export const notebookLogic = kea<notebookLogicType>([
saveNotebookFailure: () => {
actions.processPendingMarkdownStreamEvents()
},
- loadNotebookSuccess: () => {
+ loadNotebookSuccess: ({ notebook }) => {
+ if (
+ notebook &&
+ isMarkdownNotebookContent(notebook.content) &&
+ values.localContent &&
+ !isMarkdownNotebookContent(values.localContent)
+ ) {
+ actions.clearLocalContent()
+ }
actions.scheduleNotebookRefresh()
actions.maybeLoadComments()
actions.processPendingMarkdownStreamEvents()
diff --git a/frontend/src/scenes/notebooks/NotebookMenu.test.tsx b/frontend/src/scenes/notebooks/NotebookMenu.test.tsx
new file mode 100644
index 000000000000..00116bcfcffc
--- /dev/null
+++ b/frontend/src/scenes/notebooks/NotebookMenu.test.tsx
@@ -0,0 +1,83 @@
+import '@testing-library/jest-dom'
+
+import { render, screen } from '@testing-library/react'
+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'
+
+import { notebookLogic } from './Notebook/notebookLogic'
+import { NotebookMenu } from './NotebookMenu'
+import { type NotebookType } from './types'
+
+jest.mock('./Notebook/migrations/migrate', () => {
+ const actual = jest.requireActual('./Notebook/migrations/migrate')
+ return {
+ ...actual,
+ migrate: jest.fn(async (notebook) => notebook),
+ }
+})
+
+jest.mock('lib/ui/DropdownMenu/DropdownMenu', () => ({
+ DropdownMenu: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DropdownMenuContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DropdownMenuGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DropdownMenuItem: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DropdownMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
+}))
+
+const SHORT_ID = 'test-notebook-menu'
+
+const legacyNotebook: NotebookType = {
+ id: 'notebook-id',
+ short_id: SHORT_ID,
+ title: 'Legacy notebook',
+ content: {
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'legacy notebook' }] }],
+ },
+ text_content: 'legacy notebook',
+ version: 1,
+ deleted: false,
+ is_template: false,
+ user_access_level: AccessControlLevel.Editor,
+ created_at: '2025-01-01T00:00:00Z',
+ created_by: null,
+ last_modified_at: '2025-01-01T00:00:00Z',
+ last_modified_by: null,
+} as unknown as NotebookType
+
+describe('NotebookMenu', () => {
+ let logic: ReturnType<typeof notebookLogic.build>
+
+ beforeEach(async () => {
+ 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()
+ logic.actions.loadNotebook()
+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ jest.restoreAllMocks()
+ })
+
+ it('shows the markdown download action for legacy notebooks rendered as markdown', () => {
+ render(<NotebookMenu shortId={SHORT_ID} />)
+
+ expect(screen.getByText('Download .md')).toBeInTheDocument()
+ expect(screen.queryByText('Export JSON')).not.toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/scenes/notebooks/NotebookMenu.tsx b/frontend/src/scenes/notebooks/NotebookMenu.tsx
index 0cce67f40738..6f5fbffa29bb 100644
--- a/frontend/src/scenes/notebooks/NotebookMenu.tsx
+++ b/frontend/src/scenes/notebooks/NotebookMenu.tsx
@@ -43,7 +43,7 @@ export function NotebookMenu({ shortId }: NotebookLogicProps): JSX.Element {
{isMarkdownNotebook ? (
<ButtonPrimitive onClick={() => downloadMarkdown()} menuItem>
<IconDownload />
- Download
+ Download .md
</ButtonPrimitive>
) : (
<ButtonPrimitive onClick={() => exportJSON()} menuItem>
diff --git a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx
index 0578ea733ac8..7403befbf4cc 100644
--- a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx
+++ b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx
@@ -30,9 +30,11 @@ import { notebookPanelLogic } from './notebookPanelLogic'
export function NotebookPanel(): JSX.Element | null {
const { selectedNotebook, initialAutofocus, droppedResource, dropProperties } = useValues(notebookPanelLogic)
const { selectNotebook, closeSidePanel } = useActions(notebookPanelLogic)
- const { notebook } = useValues(notebookLogic({ shortId: selectedNotebook, target: NotebookTarget.Popover }))
+ const { notebook, content } = useValues(
+ notebookLogic({ shortId: selectedNotebook, target: NotebookTarget.Popover })
+ )
const editable = !notebook?.is_template
- const isMarkdownNotebook = isMarkdownNotebookContent(notebook?.content)
+ const isMarkdownNotebook = isMarkdownNotebookContent(content)
const { ref, size } = useResizeBreakpoints({
0: 'small',
832: 'medium',
diff --git a/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx b/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx
index c7fac42f3f16..4fe835944031 100644
--- a/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx
+++ b/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx
@@ -59,7 +59,7 @@ function NotebookSceneMenuBarInner({ shortId }: { shortId: string }): JSX.Elemen
data-attr={`${RESOURCE_TYPE}-menubar-download-markdown`}
>
<IconDownload />
- Download markdown
+ Download .md
</SceneMenuBarItem>
<SceneMenuBarItem
onClick={() => copyMarkdown()}
diff --git a/posthog/api/test/notebooks/test_notebook.py b/posthog/api/test/notebooks/test_notebook.py
index 3f0ac26d1aa7..5199ae612c8a 100644
--- a/posthog/api/test/notebooks/test_notebook.py
+++ b/posthog/api/test/notebooks/test_notebook.py
@@ -79,6 +79,19 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):
{"some": "kind", "of": "tip", "tap": "content"},
"some kind of tip tap content",
),
+ (
+ "with_markdown_content",
+ {
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-markdown-notebook",
+ "attrs": {"nodeId": "markdown-notebook-v2", "markdown": "# Test\n\nBody"},
+ }
+ ],
+ },
+ "# Test\n\nBody",
+ ),
]
)
def test_create_a_notebook(self, _, content: dict | None, text_content: str | None) -> None:
@@ -87,28 +100,56 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):
data={"content": content, "text_content": text_content},
)
assert response.status_code == status.HTTP_201_CREATED
- assert response.json() == {
- "id": response.json()["id"],
- "short_id": response.json()["short_id"],
+ response_json = response.json()
+ assert response_json == {
+ "id": response_json["id"],
+ "short_id": response_json["short_id"],
"content": content,
"text_content": text_content,
"title": None,
"version": 0,
- "created_at": mock.ANY,
- "created_by": response.json()["created_by"],
+ "created_at": response_json["created_at"],
+ "created_by": response_json["created_by"],
"deleted": False,
- "last_modified_at": mock.ANY,
- "last_modified_by": response.json()["last_modified_by"],
+ "last_modified_at": response_json["last_modified_at"],
+ "last_modified_by": response_json["last_modified_by"],
"user_access_level": "manager",
"parent_resource": None,
}
self.assert_notebook_activity(
[
- self.created_activity(item_id=response.json()["short_id"], short_id=response.json()["short_id"]),
+ self.created_activity(item_id=response_json["short_id"], short_id=response_json["short_id"]),
],
)
+ @parameterized.expand(
+ [
+ ("legacy_rich_text", {"some": "kind", "of": "tip", "tap": "content"}, None),
+ (
+ "markdown_notebook",
+ {
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-markdown-notebook",
+ "attrs": {"nodeId": "markdown-notebook-v2", "markdown": "# Test\n\nBody"},
+ }
+ ],
+ },
+ "# Test\n\nBody",
+ ),
+ ]
+ )
+ def test_gets_notebook_markdown_by_shortid(self, _, content: dict, expected_markdown: str | None) -> None:
+ create_response = self.client.post(f"/api/projects/{self.team.id}/notebooks", data={"content": content})
+ short_id = create_response.json()["short_id"]
+
+ response = self.client.get(f"/api/projects/{self.team.id}/notebooks/{short_id}/markdown")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"markdown": expected_markdown}
+
def test_gets_individual_notebook_by_shortid(self) -> None:
create_response = self.client.post(f"/api/projects/{self.team.id}/notebooks", data={})
response = self.client.get(f"/api/projects/{self.team.id}/notebooks/{create_response.json()['short_id']}")
diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.py
index 73d54df4f315..fc556a20e760 100644
--- a/posthog/hogql/database/schema/system.py
+++ b/posthog/hogql/database/schema/system.py
@@ -1222,6 +1222,46 @@ hog_functions: PostgresTable = PostgresTable(
},
)
+
+def _notebook_content_or_empty_object_expr() -> ast.Expr:
+ return ast.Call(name="ifNull", args=[ast.Field(chain=["content"]), ast.Constant(value="{}")])
+
+
+def _first_notebook_content_node_expr() -> ast.Expr:
+ return ast.ArrayAccess(
+ array=ast.Call(
+ name="JSONExtractArrayRaw",
+ args=[_notebook_content_or_empty_object_expr(), ast.Constant(value="content")],
+ ),
+ property=ast.Constant(value=1),
+ )
+
+
+def _notebook_markdown_expr() -> ast.Expr:
+ return ast.Call(
+ name="if",
+ args=[
+ ast.CompareOperation(
+ left=ast.Call(
+ name="JSONExtractString",
+ args=[_first_notebook_content_node_expr(), ast.Constant(value="type")],
+ ),
+ right=ast.Constant(value="ph-markdown-notebook"),
+ op=ast.CompareOperationOp.Eq,
+ ),
+ ast.Call(
+ name="JSONExtractString",
+ args=[
+ _first_notebook_content_node_expr(),
+ ast.Constant(value="attrs"),
+ ast.Constant(value="markdown"),
+ ],
+ ),
+ ast.Constant(value=None),
+ ],
+ )
+
+
notebooks: PostgresTable = PostgresTable(
name="notebooks",
postgres_table_name="posthog_notebook",
@@ -1235,6 +1275,12 @@ notebooks: PostgresTable = PostgresTable(
"content": StringJSONDatabaseField(
name="content", description="JSON rich-text document (ProseMirror) content."
),
+ "markdown": ExpressionField(
+ name="markdown",
+ nullable=True,
+ expr=_notebook_markdown_expr(),
+ description="Markdown source for markdown notebooks; NULL for legacy rich-text notebooks.",
+ ),
"text_content": StringDatabaseField(
name="text_content", description="Plain-text rendering of the notebook, for search."
),
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 32260d4dc789..0b42439a1a8a 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -827,6 +827,48 @@ class TestSystemTablesTaskInternalExclusionIsolation(NonAtomicBaseTest):
assert str(internal_task.pk) not in ids
+class TestSystemTablesNotebookMarkdown(NonAtomicBaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def test_markdown_column_extracts_only_markdown_notebook_source(self):
+ markdown_source = "# Title\n\nSome notebook markdown."
+ Notebook.objects.create(
+ team=self.team,
+ short_id="mdnote",
+ content={
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-markdown-notebook",
+ "attrs": {"nodeId": "markdown-notebook-v2", "markdown": markdown_source},
+ }
+ ],
+ },
+ text_content=markdown_source,
+ )
+ Notebook.objects.create(
+ team=self.team,
+ short_id="legacy",
+ content={
+ "type": "doc",
+ "content": [
+ {"type": "paragraph", "content": [{"type": "text", "text": "Legacy content"}]},
+ ],
+ },
+ text_content="Legacy content",
+ )
+ Notebook.objects.create(team=self.team, short_id="empty", content=None, text_content=None)
+
+ response = execute_hogql_query(
+ "SELECT short_id, markdown FROM system.notebooks WHERE short_id IN ('mdnote', 'legacy', 'empty')",
+ team=self.team,
+ user=self.user,
+ )
+ rows = {row[0]: row[1] for row in response.results}
+
+ assert rows == {"mdnote": markdown_source, "legacy": None, "empty": None}
+
+
class TestSystemAccountsLazyJoins(NonAtomicBaseTest):
"""Verify the `accounts.tags.names` and `accounts.notebooks.count` lazy joins."""
diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambr
index 7e3010d847c5..d5b29534d2a9 100644
--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr
+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr
@@ -7270,6 +7270,16 @@
"table": null,
"type": "json"
},
+ "markdown": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "markdown",
+ "id": null,
+ "name": "markdown",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
"text_content": {
"chain": null,
"fields": null,
@@ -15866,6 +15876,16 @@
"table": null,
"type": "json"
},
+ "markdown": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "markdown",
+ "id": null,
+ "name": "markdown",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
"text_content": {
"chain": null,
"fields": null,
diff --git a/posthog/temporal/common/clickhouse.py b/posthog/temporal/common/clickhouse.py
index 631f1f95f02e..5f731d7cf773 100644
--- a/posthog/temporal/common/clickhouse.py
+++ b/posthog/temporal/common/clickhouse.py
@@ -694,7 +694,7 @@ class ClickHouseClient:
results = await self.read_query_as_jsonl(
query,
query_parameters={"query_id": query_id, "cluster_name": settings.CLICKHOUSE_CLUSTER},
- query_id=f"{query_id}-CHECK-QUERY-LOG",
+ query_id=f"{query_id}-CHECK-QUERY-LOG-{uuid.uuid4()}",
)
except ClickHouseError as e:
error_message = f"Error checking for query '{query_id}' in query log: {str(e)}"
diff --git a/posthog/temporal/tests/test_clickhouse.py b/posthog/temporal/tests/test_clickhouse.py
index 38b5060c23ac..dcb2c23f9579 100644
--- a/posthog/temporal/tests/test_clickhouse.py
+++ b/posthog/temporal/tests/test_clickhouse.py
@@ -346,6 +346,26 @@ async def test_acheck_query_in_query_log_error(clickhouse_client, django_db_setu
await clickhouse_client.acheck_query_in_query_log(query_id)
+async def test_acheck_query_in_query_log_uses_unique_check_query_ids(clickhouse_client: ClickHouseClient) -> None:
+ query_id = f"test-check-query-id-{uuid.uuid4()}"
+ check_query_ids: list[str] = []
+
+ async def mock_read_query_as_jsonl(
+ _query: str, query_parameters: dict[str, object] | None = None, query_id: str | None = None
+ ) -> list[dict[str, str]]:
+ assert query_id is not None
+ check_query_ids.append(query_id)
+ return [{"type": "QueryFinish", "exception": ""}]
+
+ with patch.object(clickhouse_client, "read_query_as_jsonl", side_effect=mock_read_query_as_jsonl):
+ await clickhouse_client.acheck_query_in_query_log(query_id)
+ await clickhouse_client.acheck_query_in_query_log(query_id)
+
+ assert len(check_query_ids) == 2
+ assert check_query_ids[0] != check_query_ids[1]
+ assert all(value.startswith(f"{query_id}-CHECK-QUERY-LOG-") for value in check_query_ids)
+
+
async def test_acheck_query_found(clickhouse_client, django_db_setup):
query_id = f"test-acheck-query-{uuid.uuid4()}"
await clickhouse_client.execute_query("SELECT 1", query_id=query_id)
diff --git a/products/notebooks/backend/markdown_migration.py b/products/notebooks/backend/markdown_migration.py
index 7a6151016c8e..31c95dca8ae7 100644
--- a/products/notebooks/backend/markdown_migration.py
+++ b/products/notebooks/backend/markdown_migration.py
@@ -3,7 +3,7 @@ from datetime import timedelta
from typing import Any, cast
from django.db import transaction
-from django.db.models import QuerySet
+from django.db.models import Q, QuerySet
from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import changes_between
@@ -131,7 +131,10 @@ def _notebook_scope(team_id: int | None) -> QuerySet[Notebook]:
def _pending_notebook_scope(team_id: int | None) -> QuerySet[Notebook]:
- return _notebook_scope(team_id).exclude(content__content__0__type=markdown_collab.MARKDOWN_NOTEBOOK_NODE_TYPE)
+ return _notebook_scope(team_id).filter(
+ Q(content__content__0__type__isnull=True)
+ | ~Q(content__content__0__type=markdown_collab.MARKDOWN_NOTEBOOK_NODE_TYPE)
+ )
def _convert_notebook(notebook: Notebook, *, user: User, content: dict[str, Any], text_content: str) -> bool:
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index a0725cd872d1..6a8774089795 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -274,6 +274,15 @@ class NotebookSerializer(NotebookMinimalSerializer):
raise serializers.ValidationError(str(err))
+class NotebookMarkdownSerializer(serializers.Serializer):
+ markdown = serializers.CharField(
+ allow_blank=True,
+ allow_null=True,
+ read_only=True,
+ help_text="Markdown source for markdown notebooks, or `null` for legacy rich-text notebooks.",
+ )
+
+
class NotebookKernelExecuteSerializer(serializers.Serializer):
code = serializers.CharField(allow_blank=True)
return_variables = serializers.BooleanField(default=True)
@@ -513,6 +522,15 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
def _current_user(self) -> User | None:
return self.request.user if isinstance(self.request.user, User) else None
+ @extend_schema(exclude=True)
+ @action(methods=["GET"], url_path="markdown", detail=True, required_scopes=["notebook:read"])
+ def markdown(self, request: Request, **kwargs) -> Response:
+ notebook = self.get_object()
+ serializer = NotebookMarkdownSerializer(
+ {"markdown": markdown_collab.get_markdown_notebook_markdown(notebook.content)}
+ )
+ return Response(serializer.data)
+
def safely_get_queryset(self, queryset) -> QuerySet:
if not self.action.endswith("update"):
# Soft-deleted notebooks can be brought back with a PATCH request
diff --git a/products/notebooks/backend/test/test_markdown_migration.py b/products/notebooks/backend/test/test_markdown_migration.py
index a96c7770f986..adeae439e79d 100644
--- a/products/notebooks/backend/test/test_markdown_migration.py
+++ b/products/notebooks/backend/test/test_markdown_migration.py
@@ -252,6 +252,41 @@ class TestNotebookMarkdownMigration(BaseTest):
}
assert not ActivityLog.objects.filter(scope="Notebook", item_id=notebook.short_id).exists()
+ @patch("products.notebooks.backend.markdown_collab.publish_notebook_update")
+ def test_batches_include_pending_notebooks_without_first_content_node_type(self, mock_publish) -> None:
+ no_content_array = Notebook.objects.create(team=self.team, content={"type": "doc"}, version=1)
+ null_content = Notebook.objects.create(team=self.team, content=None, version=2)
+ Notebook.objects.create(team=self.team, content=build_markdown_notebook_content("done"))
+
+ dry_run_result = migrate_notebooks_to_markdown(
+ user=self.user,
+ team_id=self.team.id,
+ dry_run=True,
+ batch_size=10,
+ )
+
+ assert dry_run_result.pending_before == 2
+ assert dry_run_result.converted == 2
+ assert dry_run_result.pending_after == 2
+
+ with self.captureOnCommitCallbacks(execute=True):
+ apply_result = migrate_notebooks_to_markdown(
+ user=self.user,
+ team_id=self.team.id,
+ dry_run=False,
+ batch_size=10,
+ )
+
+ no_content_array.refresh_from_db()
+ null_content.refresh_from_db()
+
+ assert apply_result.converted == 2
+ assert apply_result.pending_before == 2
+ assert apply_result.pending_after == 0
+ assert no_content_array.content == build_markdown_notebook_content("")
+ assert null_content.content == build_markdown_notebook_content("")
+ assert mock_publish.call_count == 2
+
@patch("products.notebooks.backend.markdown_collab.publish_notebook_update")
def test_batches_dry_run_and_apply_without_processing_every_pending_notebook(self, mock_publish) -> None:
notebooks = [
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-notebooks.md b/products/posthog_ai/skills/querying-posthog-data/references/models-notebooks.md
index 971d5a851a32..aa5a2f86485c 100644
--- a/products/posthog_ai/skills/querying-posthog-data/references/models-notebooks.md
+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-notebooks.md
@@ -11,6 +11,7 @@ Column | Type | Nullable | Description
`short_id` | varchar(12) | NOT NULL | Unique short identifier for URLs
`title` | varchar(256) | NULL | Notebook title
`content` | jsonb | NULL | Notebook content blocks
+`markdown` | text | NULL | Markdown source when the notebook is stored as a markdown notebook; NULL for legacy rich-text notebooks
`text_content` | text | NULL | Plain text extraction for search
`deleted` | boolean | NOT NULL | Soft delete flag
`visibility` | varchar(20) | NOT NULL | `private`, `shared`, or `public`
@@ -56,6 +57,9 @@ Notebooks use a block-based content format:
}
```
+Markdown notebooks store a single `ph-markdown-notebook` block in `content`.
+Use the `markdown` column when reading or editing markdown notebooks instead of selecting and parsing the raw `content` JSON.
+
### Block Types
Type | Description
@@ -101,3 +105,12 @@ FROM system.notebooks
WHERE NOT deleted
AND text_content ILIKE '%retention%'
```
+
+**Read markdown source for a notebook:**
+
+```sql
+SELECT short_id, title, markdown
+FROM system.notebooks
+WHERE short_id = 'abc123'
+ AND markdown IS NOT NULL
+```
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index e6ba157a3169..3c3cfe269249 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6121,7 +6121,7 @@
"system_prompt_hint": "Discover which server/infrastructure metrics exist before querying them"
},
"notebook-edit": {
- "description": "Edit part of a notebook's content. Use this for any change inside a notebook — text, headings, attributes, whole paragraphs. Call `notebooks-retrieve` first to see what to target.\n\nMatching is by content. The tool finds `old_value` anywhere in the notebook and swaps it for `new_value` in place.\n\nOn success, returns the updated notebook with the new content and bumped version. On a 409 or 410 error, the notebook has changed since you loaded it — call `notebooks-retrieve` and re-apply your edit against the latest content.",
+ "description": "Edit part of a notebook's content by short_id.\n\nFor markdown notebooks, use `execute-sql` to read the current markdown from `system.notebooks.markdown`, then edit with `old_markdown` / `new_markdown`. These are plain markdown strings; do not copy or construct the nested `ph-markdown-notebook` JSON wrapper.\n\nFor legacy rich-text notebooks, inspect the JSON content from `system.notebooks.content`, then edit with `old_value` / `new_value` JSON subtree replacement. Matching is by content: the tool finds `old_value` anywhere in the notebook and swaps it for `new_value` in place.\n\nOn success, returns the updated notebook with the new content and bumped version. On a 409 or 410 error, the notebook has changed since you loaded it; reload the latest markdown or JSON content and re-apply your edit.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Edit part of a notebook's content.",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index b0d0863b3cda..7b6b183e9734 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -324,7 +324,7 @@
}
},
"notebook-edit": {
- "description": "Edit part of a notebook's content. Use this for any change inside a notebook — text, headings, attributes, whole paragraphs. Call `notebooks-retrieve` first to see what to target.\n\nMatching is by content. The tool finds `old_value` anywhere in the notebook and swaps it for `new_value` in place.\n\nOn success, returns the updated notebook with the new content and bumped version. On a 409 or 410 error, the notebook has changed since you loaded it — call `notebooks-retrieve` and re-apply your edit against the latest content.",
+ "description": "Edit part of a notebook's content by short_id.\n\nFor markdown notebooks, use `execute-sql` to read the current markdown from `system.notebooks.markdown`, then edit with `old_markdown` / `new_markdown`. These are plain markdown strings; do not copy or construct the nested `ph-markdown-notebook` JSON wrapper.\n\nFor legacy rich-text notebooks, inspect the JSON content from `system.notebooks.content`, then edit with `old_value` / `new_value` JSON subtree replacement. Matching is by content: the tool finds `old_value` anywhere in the notebook and swaps it for `new_value` in place.\n\nOn success, returns the updated notebook with the new content and bumped version. On a 409 or 410 error, the notebook has changed since you loaded it; reload the latest markdown or JSON content and re-apply your edit.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Edit part of a notebook's content.",
diff --git a/services/mcp/src/tools/notebooks/edit.ts b/services/mcp/src/tools/notebooks/edit.ts
index 49e4c2bc293b..7574d561d250 100644
--- a/services/mcp/src/tools/notebooks/edit.ts
+++ b/services/mcp/src/tools/notebooks/edit.ts
@@ -1,15 +1,15 @@
/**
* `notebook-edit` tool.
*
- * Subtree replacement against the notebook's content tree. The caller supplies
- * `{ short_id, old_value, new_value, replace_all? }` where `old_value` and
- * `new_value` are JSON values describing the subtree to find and the subtree
- * to put in its place. Match is by deep equality of the parsed values, so
- * whitespace, key order, and indentation do not matter — the agent never has
- * to imagine the tool's serialization format.
+ * Content replacement for notebooks. Markdown notebooks use native markdown
+ * string replacement: `{ short_id, old_markdown, new_markdown, replace_all? }`.
+ * Legacy rich-text notebooks use JSON subtree replacement:
+ * `{ short_id, old_value, new_value, replace_all? }`.
*
- * The diff is expressed as a single ProseMirror ReplaceStep and POSTed to
- * `/collab/save` so the edit streams live to other connected clients over SSE.
+ * Markdown edits POST the full markdown notebook document to
+ * `/collab/markdown_save` so other connected clients receive markdown diffs.
+ * Legacy JSON edits are expressed as a single ProseMirror ReplaceStep and
+ * POSTed to `/collab/save`.
*
* Server errors (409 concurrent edit, 410 stale buffer, etc.) flow through
* `context.api.request` → PostHogApiError → `handleToolError`, which surfaces
@@ -27,42 +27,209 @@ import type { Schemas } from '@/api/generated'
import { buildSchemaForDoc, packDocAttrs, type ProseMirrorNodeJSON, unpackDocAttrs } from '@/lib/prosemirror/schema'
import type { Context, ToolBase } from '@/tools/types'
+const MARKDOWN_NOTEBOOK_NODE_TYPE = 'ph-markdown-notebook'
+const ERROR_PREVIEW_LENGTH = 160
+
const Subtree = z.union([z.record(z.string(), z.unknown()), z.array(z.unknown())])
-export const NotebookEditSchema = z
- .object({
- short_id: z.string().describe('The notebook short_id (the public id in the URL, e.g. `aBcD1234`).'),
- old_value: Subtree.describe(
- 'The piece of content to find. Copy it straight out of the response from ' +
- '`notebooks-retrieve` — typically a single node like a text node or a whole ' +
- 'paragraph. Must be a JSON object or array, not a primitive. Must match exactly ' +
- 'one place in the notebook unless `replace_all` is true; if it appears in more ' +
- 'than one place, include more surrounding structure (e.g. pass the parent ' +
- 'paragraph instead of just the text node) to make it unique. To append to the ' +
- 'end of a notebook, pass the last paragraph with content — trailing empty ' +
- 'paragraphs are often identical and will cause an ambiguity error.'
+const BaseEditSchema = z.object({
+ short_id: z.string().describe('The notebook short_id (the public id in the URL, e.g. `aBcD1234`).'),
+ replace_all: z
+ .boolean()
+ .optional()
+ .describe(
+ 'Replace every matching occurrence. Default false — the tool errors out if the target is not unique.'
+ ),
+})
+
+const MarkdownEditSchema = BaseEditSchema.extend({
+ old_markdown: z
+ .string()
+ .min(1)
+ .describe(
+ 'Markdown text to find inside a markdown notebook. Get the current markdown with `execute-sql` from `system.notebooks.markdown`; pass the full markdown body to replace the whole notebook, or a unique markdown span to make a local edit.'
),
- new_value: Subtree.describe(
- 'What to put in place of `old_value`. Pass a JSON value of the same shape — the whole ' +
- 'matched piece is replaced, so include every key you want preserved. Must be a JSON ' +
- 'object or array, not a primitive. Must differ from `old_value`.'
+ new_markdown: z
+ .string()
+ .describe(
+ 'Markdown text to put in place of `old_markdown`. This is plain notebook markdown; do not wrap it in ProseMirror JSON.'
),
- replace_all: z
- .boolean()
- .optional()
- .describe(
- 'Replace every place `old_value` matches. Default false — the tool errors out if ' +
- '`old_value` is not unique, so you can either narrow `old_value` to a single match ' +
- 'or set `replace_all` to true.'
- ),
+})
+ .strict()
+ .refine((v) => v.old_markdown !== v.new_markdown, {
+ message: 'old_markdown and new_markdown must differ',
+ path: ['new_markdown'],
})
+
+const JsonEditSchema = BaseEditSchema.extend({
+ old_value: Subtree.describe(
+ 'Legacy rich-text notebook mode only. The JSON subtree to find. For markdown notebooks, use `old_markdown` instead of copying nested `ph-markdown-notebook` JSON.'
+ ),
+ new_value: Subtree.describe(
+ 'Legacy rich-text notebook mode only. The JSON subtree to put in place of `old_value`. For markdown notebooks, use `new_markdown`.'
+ ),
+})
+ .strict()
.refine((v) => !isDeepStrictEqual(v.old_value, v.new_value), {
message: 'old_value and new_value must differ',
path: ['new_value'],
})
+export const NotebookEditSchema = z.union([MarkdownEditSchema, JsonEditSchema])
+
+type MarkdownParams = z.infer<typeof MarkdownEditSchema>
+type JsonParams = z.infer<typeof JsonEditSchema>
type Params = z.infer<typeof NotebookEditSchema>
+function isMarkdownParams(params: Params): params is MarkdownParams {
+ return 'old_markdown' in params
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+function getMarkdownNotebookNode(content: unknown): Record<string, unknown> | null {
+ if (!isRecord(content)) {
+ return null
+ }
+ const nodes = content.content
+ if (!Array.isArray(nodes) || nodes.length !== 1) {
+ return null
+ }
+ const node = nodes[0]
+ if (!isRecord(node) || node.type !== MARKDOWN_NOTEBOOK_NODE_TYPE) {
+ return null
+ }
+ const attrs = node.attrs
+ if (!isRecord(attrs) || typeof attrs.markdown !== 'string') {
+ return null
+ }
+ return node
+}
+
+function buildMarkdownNotebookContent(content: unknown, markdown: string): ProseMirrorNodeJSON {
+ const clonedContent = structuredClone(content) as ProseMirrorNodeJSON
+ const node = getMarkdownNotebookNode(clonedContent)
+ if (node === null || !isRecord(node.attrs)) {
+ throw new Error('Notebook content is no longer a markdown notebook document.')
+ }
+ node.attrs = { ...node.attrs, markdown }
+ return clonedContent
+}
+
+function truncateForError(value: string): string {
+ const normalized = value.replace(/\s+/g, ' ').trim()
+ if (normalized.length <= ERROR_PREVIEW_LENGTH) {
+ return normalized
+ }
+ return `${normalized.slice(0, ERROR_PREVIEW_LENGTH)}...`
+}
+
+function safeJsonStringify(value: unknown): string {
+ try {
+ return JSON.stringify(value)
+ } catch {
+ return '[unserializable JSON value]'
+ }
+}
+
+function topLevelNodeCount(content: unknown): number | null {
+ if (!isRecord(content) || !Array.isArray(content.content)) {
+ return null
+ }
+ return content.content.length
+}
+
+function countStringMatches(value: string, target: string): number {
+ let count = 0
+ let start = 0
+ while (start <= value.length) {
+ const index = value.indexOf(target, start)
+ if (index === -1) {
+ return count
+ }
+ count++
+ start = index + target.length
+ }
+ return count
+}
+
+function replaceMarkdown(currentMarkdown: string, params: MarkdownParams): string {
+ const matches = countStringMatches(currentMarkdown, params.old_markdown)
+ if (matches === 0) {
+ throw new Error(
+ 'old_markdown was not found in the notebook markdown. The match is exact, including whitespace. ' +
+ `Current markdown length: ${currentMarkdown.length} characters. ` +
+ `old_markdown length: ${params.old_markdown.length} characters. ` +
+ `old_markdown preview: ${truncateForError(params.old_markdown)}. ` +
+ 'Use `execute-sql` to refresh `system.notebooks.markdown` for this short_id.'
+ )
+ }
+
+ if (matches > 1 && params.replace_all !== true) {
+ throw new Error(
+ `old_markdown matches ${matches} places in the notebook markdown. ` +
+ 'Pass a longer unique markdown span, or set `replace_all: true` to replace every match.'
+ )
+ }
+
+ if (params.replace_all === true) {
+ return currentMarkdown.split(params.old_markdown).join(params.new_markdown)
+ }
+
+ const index = currentMarkdown.indexOf(params.old_markdown)
+ return (
+ currentMarkdown.slice(0, index) +
+ params.new_markdown +
+ currentMarkdown.slice(index + params.old_markdown.length)
+ )
+}
+
+async function fetchNotebookMarkdown(context: Context, notebookPath: string): Promise<string | null> {
+ const result = await context.api.request<{ markdown: string | null }>({
+ method: 'GET',
+ path: `${notebookPath}markdown/`,
+ })
+ return result.markdown
+}
+
+async function editMarkdownNotebook(
+ context: Context,
+ notebookPath: string,
+ notebook: Schemas.Notebook,
+ params: MarkdownParams
+): Promise<Schemas.Notebook> {
+ const currentMarkdown = await fetchNotebookMarkdown(context, notebookPath)
+ if (currentMarkdown === null) {
+ throw new Error(
+ `Notebook ${params.short_id} is not a markdown notebook. ` +
+ 'Use `old_value`/`new_value` JSON subtree replacement for legacy rich-text notebooks.'
+ )
+ }
+
+ if (getMarkdownNotebookNode(notebook.content) === null) {
+ throw new Error(
+ `Notebook ${params.short_id} content is not a markdown notebook document. ` +
+ 'Use `old_value`/`new_value` JSON subtree replacement for legacy rich-text notebooks.'
+ )
+ }
+
+ const nextMarkdown = replaceMarkdown(currentMarkdown, params)
+ const nextContent = buildMarkdownNotebookContent(notebook.content, nextMarkdown)
+
+ return await context.api.request<Schemas.Notebook>({
+ method: 'POST',
+ path: `${notebookPath}collab/markdown_save/`,
+ body: {
+ client_id: uuidv4(),
+ version: notebook.version,
+ content: nextContent as unknown as Record<string, unknown>,
+ text_content: nextMarkdown,
+ },
+ })
+}
+
/** Counts subtrees deep-equal to `target`; lets the handler reject bad inputs before mutating. */
function countMatches(tree: unknown, target: unknown): number {
let count = 0
@@ -176,38 +343,28 @@ function buildTextContent(doc: Node): string {
return parts.join('\n')
}
-export const editHandler: ToolBase<typeof NotebookEditSchema, Schemas.Notebook>['handler'] = async (
+async function editJsonNotebook(
context: Context,
- params: Params
-) => {
- const projectId = await context.stateManager.getProjectId()
- const notebookPath = `/api/projects/${encodeURIComponent(projectId)}/notebooks/${encodeURIComponent(params.short_id)}/`
-
- // Load current notebook.
- const notebook = await context.api.request<Schemas.Notebook>({ method: 'GET', path: notebookPath })
-
- if (notebook.content === null || typeof notebook.content !== 'object' || Array.isArray(notebook.content)) {
- throw new Error(
- `Notebook ${params.short_id} has no editable content. ` +
- 'Create one with `notebooks-create` or initialise its content first.'
- )
- }
-
- if (typeof notebook.version !== 'number') {
- throw new Error(`Notebook ${params.short_id} has no numeric version — required for optimistic concurrency.`)
- }
-
+ notebookPath: string,
+ notebook: Schemas.Notebook,
+ params: JsonParams
+): Promise<Schemas.Notebook> {
// Find target subtree(s) and apply the replacement.
const matches = countMatches(notebook.content, params.old_value)
if (matches === 0) {
+ const currentContentJson = safeJsonStringify(notebook.content)
+ const oldValueJson = safeJsonStringify(params.old_value)
+ const nodeCount = topLevelNodeCount(notebook.content)
throw new Error(
'old_value was not found in the notebook content. ' +
'Matching compares every key, value, and array index — extra or missing fields will ' +
'prevent a match. Common causes: an explicit `attrs: null` vs. omitted attrs; content ' +
'has changed since you last read it (call `notebooks-retrieve` to refresh); or you ' +
- 'passed only part of the value where the full one is stored.\n\nCurrent notebook ' +
- 'content:\n' +
- JSON.stringify(notebook.content, null, 2)
+ 'passed only part of the value where the full one is stored. ' +
+ `Current notebook JSON length: ${currentContentJson.length} characters. ` +
+ `Top-level node count: ${nodeCount ?? 'unknown'}. ` +
+ `old_value JSON length: ${oldValueJson.length} characters. ` +
+ `old_value preview: ${truncateForError(oldValueJson)}.`
)
}
@@ -263,6 +420,34 @@ export const editHandler: ToolBase<typeof NotebookEditSchema, Schemas.Notebook>[
})
}
+export const editHandler: ToolBase<typeof NotebookEditSchema, Schemas.Notebook>['handler'] = async (
+ context: Context,
+ params: Params
+) => {
+ const projectId = await context.stateManager.getProjectId()
+ const notebookPath = `/api/projects/${encodeURIComponent(projectId)}/notebooks/${encodeURIComponent(params.short_id)}/`
+
+ // Load current notebook.
+ const notebook = await context.api.request<Schemas.Notebook>({ method: 'GET', path: notebookPath })
+
+ if (notebook.content === null || typeof notebook.content !== 'object' || Array.isArray(notebook.content)) {
+ throw new Error(
+ `Notebook ${params.short_id} has no editable content. ` +
+ 'Create one with `notebooks-create` or initialise its content first.'
+ )
+ }
+
+ if (typeof notebook.version !== 'number') {
+ throw new Error(`Notebook ${params.short_id} has no numeric version — required for optimistic concurrency.`)
+ }
+
+ if (isMarkdownParams(params)) {
+ return await editMarkdownNotebook(context, notebookPath, notebook, params)
+ }
+
+ return await editJsonNotebook(context, notebookPath, notebook, params)
+}
+
const tool = (): ToolBase<typeof NotebookEditSchema, Schemas.Notebook> => ({
name: 'notebook-edit',
schema: NotebookEditSchema,
diff --git a/services/mcp/tests/unit/notebook-edit.test.ts b/services/mcp/tests/unit/notebook-edit.test.ts
index 1495c5e5435d..fe2db35586d3 100644
--- a/services/mcp/tests/unit/notebook-edit.test.ts
+++ b/services/mcp/tests/unit/notebook-edit.test.ts
@@ -14,6 +14,21 @@ const sampleDoc = {
],
}
+const sampleMarkdown =
+ '# Sample Notebook\n\nOriginal paragraph.\n\n<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />'
+const sampleMarkdownDoc = {
+ type: 'doc',
+ content: [
+ {
+ type: 'ph-markdown-notebook',
+ attrs: {
+ nodeId: 'markdown-notebook-v2',
+ markdown: sampleMarkdown,
+ },
+ },
+ ],
+}
+
// ---------- Input schema -----------------------------------------------------
describe('NotebookEditSchema', () => {
@@ -27,7 +42,16 @@ describe('NotebookEditSchema', () => {
expect(result.success).toBe(false)
})
- it('accepts a minimal valid payload', () => {
+ it('rejects identical old_markdown and new_markdown', () => {
+ const result = NotebookEditSchema.safeParse({
+ short_id: 'abc',
+ old_markdown: 'same',
+ new_markdown: 'same',
+ })
+ expect(result.success).toBe(false)
+ })
+
+ it('accepts a minimal valid JSON payload', () => {
const result = NotebookEditSchema.safeParse({
short_id: 'abc',
old_value: { type: 'text', text: 'a' },
@@ -36,6 +60,26 @@ describe('NotebookEditSchema', () => {
expect(result.success).toBe(true)
})
+ it('accepts a minimal valid markdown payload', () => {
+ const result = NotebookEditSchema.safeParse({
+ short_id: 'abc',
+ old_markdown: '# Old',
+ new_markdown: '# New',
+ })
+ expect(result.success).toBe(true)
+ })
+
+ it('rejects payloads that mix markdown and JSON edit modes', () => {
+ const result = NotebookEditSchema.safeParse({
+ short_id: 'abc',
+ old_markdown: '# Old',
+ new_markdown: '# New',
+ old_value: { type: 'text', text: 'a' },
+ new_value: { type: 'text', text: 'b' },
+ })
+ expect(result.success).toBe(false)
+ })
+
it('accepts replace_all', () => {
const result = NotebookEditSchema.safeParse({
short_id: 'abc',
@@ -50,10 +94,12 @@ describe('NotebookEditSchema', () => {
// ---------- editHandler — handler-level smoke test --------------------------
interface MockState {
- notebookContent: typeof sampleDoc | Record<string, unknown> | null
+ notebookContent: typeof sampleDoc | typeof sampleMarkdownDoc | Record<string, unknown> | null
+ markdownResponse?: string | null
version: number
- saveCalls: Array<{ body: any }>
+ saveCalls: Array<{ path?: string; body: any }>
getCalls: number
+ markdownGetCalls?: number
/**
* Queued POST responses. Each entry is either a successful body (returned
* as-is) or an error to throw (e.g. PostHogApiError for 409/410).
@@ -61,9 +107,24 @@ interface MockState {
saveResponses: Array<{ ok: true; body: unknown } | { ok: false; error: Error }>
}
+function getMockMarkdown(content: MockState['notebookContent']): string | null {
+ const node = content?.content
+ if (!Array.isArray(node) || node.length !== 1) {
+ return null
+ }
+ const attrs = node[0]?.attrs
+ return typeof attrs?.markdown === 'string' ? attrs.markdown : null
+}
+
function createMockContext(state: MockState): Context {
- const requestMock = vi.fn(async (opts: { method: string; body?: any }) => {
+ const requestMock = vi.fn(async (opts: { method: string; path?: string; body?: any }) => {
if (opts.method === 'GET') {
+ if (opts.path?.endsWith('/markdown/')) {
+ state.markdownGetCalls = (state.markdownGetCalls ?? 0) + 1
+ return {
+ markdown: state.markdownResponse ?? getMockMarkdown(state.notebookContent),
+ }
+ }
state.getCalls++
return {
short_id: 'aBcD1234',
@@ -72,8 +133,8 @@ function createMockContext(state: MockState): Context {
title: 'Original',
}
}
- // POST → collab/save
- state.saveCalls.push({ body: opts.body })
+ // POST → collab/save or collab/markdown_save
+ state.saveCalls.push({ path: opts.path, body: opts.body })
const response = state.saveResponses.shift()
if (!response) {
throw new Error('No queued response for save call')
@@ -95,6 +156,113 @@ function createMockContext(state: MockState): Context {
}
describe('editHandler', () => {
+ it('happy path: replaces markdown text by value and returns the updated notebook', async () => {
+ const nextMarkdown = sampleMarkdown.replace('Original paragraph.', 'Edited markdown paragraph.')
+ const updatedNotebook = {
+ short_id: 'aBcD1234',
+ content: sampleMarkdownDoc,
+ version: 8,
+ title: 'Original',
+ }
+ const state: MockState = {
+ notebookContent: sampleMarkdownDoc,
+ version: 7,
+ saveCalls: [],
+ getCalls: 0,
+ saveResponses: [{ ok: true, body: updatedNotebook }],
+ }
+ const context = createMockContext(state)
+
+ const result = await editHandler(context, {
+ short_id: 'aBcD1234',
+ old_markdown: 'Original paragraph.',
+ new_markdown: 'Edited markdown paragraph.',
+ })
+
+ expect(result).toEqual(updatedNotebook)
+ expect(state.markdownGetCalls).toBe(1)
+ expect(state.saveCalls).toHaveLength(1)
+ expect(state.saveCalls[0]!.path).toContain('/collab/markdown_save/')
+ expect(state.saveCalls[0]!.body.version).toBe(7)
+ expect(state.saveCalls[0]!.body.steps).toBeUndefined()
+ expect(state.saveCalls[0]!.body.text_content).toBe(nextMarkdown)
+ expect(state.saveCalls[0]!.body.content.content[0].attrs.markdown).toBe(nextMarkdown)
+ })
+
+ it('throws when markdown edit mode is used on a legacy rich-text notebook', async () => {
+ const state: MockState = {
+ notebookContent: sampleDoc,
+ version: 7,
+ saveCalls: [],
+ getCalls: 0,
+ saveResponses: [],
+ }
+ const context = createMockContext(state)
+
+ await expect(
+ editHandler(context, {
+ short_id: 'aBcD1234',
+ old_markdown: 'First paragraph.',
+ new_markdown: 'First paragraph EDITED.',
+ })
+ ).rejects.toThrow(/not a markdown notebook/)
+ expect(state.markdownGetCalls).toBe(1)
+ expect(state.saveCalls).toHaveLength(0)
+ })
+
+ it('fails closed when markdown endpoint returns text but notebook content is not a markdown document', async () => {
+ const state: MockState = {
+ notebookContent: sampleDoc,
+ markdownResponse: sampleMarkdown,
+ version: 7,
+ saveCalls: [],
+ getCalls: 0,
+ saveResponses: [],
+ }
+ const context = createMockContext(state)
+
+ await expect(
+ editHandler(context, {
+ short_id: 'aBcD1234',
+ old_markdown: 'Original paragraph.',
+ new_markdown: 'Edited markdown paragraph.',
+ })
+ ).rejects.toThrow(/content is not a markdown notebook document/)
+ expect(state.markdownGetCalls).toBe(1)
+ expect(state.saveCalls).toHaveLength(0)
+ })
+
+ it('throws not-found markdown error without including the current markdown body', async () => {
+ const state: MockState = {
+ notebookContent: sampleMarkdownDoc,
+ version: 7,
+ saveCalls: [],
+ getCalls: 0,
+ saveResponses: [],
+ }
+ const context = createMockContext(state)
+
+ let error: unknown
+ try {
+ await editHandler(context, {
+ short_id: 'aBcD1234',
+ old_markdown: 'Missing markdown span',
+ new_markdown: 'Replacement',
+ })
+ } catch (err) {
+ error = err
+ }
+
+ expect(error).toBeInstanceOf(Error)
+ const message = (error as Error).message
+ expect(message).toContain('old_markdown was not found')
+ expect(message).toContain('Current markdown length:')
+ expect(message).toContain('old_markdown preview: Missing markdown span')
+ expect(message).not.toContain(sampleMarkdown)
+ expect(message).not.toContain('Original paragraph.')
+ expect(state.saveCalls).toHaveLength(0)
+ })
+
it('happy path: replaces a text node by value and returns the updated notebook', async () => {
const updatedNotebook = {
short_id: 'aBcD1234',
@@ -209,13 +377,26 @@ describe('editHandler', () => {
saveResponses: [],
}
const context = createMockContext(state)
- await expect(
- editHandler(context, {
+ let error: unknown
+ try {
+ await editHandler(context, {
short_id: 'aBcD1234',
old_value: { type: 'text', text: 'This text does not exist anywhere' },
new_value: { type: 'text', text: 'replacement' },
})
- ).rejects.toThrow(/old_value was not found/)
+ } catch (err) {
+ error = err
+ }
+
+ expect(error).toBeInstanceOf(Error)
+ const message = (error as Error).message
+ expect(message).toContain('old_value was not found')
+ expect(message).toContain('Current notebook JSON length:')
+ expect(message).toContain('Top-level node count: 4')
+ expect(message).toContain('old_value preview:')
+ expect(message).not.toContain('Sample Notebook')
+ expect(message).not.toContain('Second paragraph.')
+ expect(message).not.toContain('sess-123')
expect(state.saveCalls).toHaveLength(0)
})